Skip to content

Commit 9b84634

Browse files
committed
Attach selected code lines to review feedback
1 parent be268b9 commit 9b84634

8 files changed

Lines changed: 194 additions & 9 deletions

File tree

‎docs/implementation/read-only-review.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,13 @@ Review round 5 found a symlinked-ancestor escape and raw-spelling collisions in
5050
Review round 6 reproduced destination-inside-source mutation; planting now resolves the existing destination ancestor and rejects canonical source descendants before creating files, including `.git` and symlink aliases. The Git-environment finding was declined: `gitRaw` already passes `{cwd, env, ...}` to `execFileSync`. A new end-to-end test with inherited `GIT_DIR`/`GIT_WORK_TREE` passed before any production change. The summary's snapshot-race claim supplied no concrete interleaving; the service already checks revision/snapshot/review version before publishing a view and writes use atomic store CAS, covered by concurrent-write tests.
5151

5252
Review round 7 reproduced oversized-dimension raster previews and dangling SQLite sidecar symlinks. Preview metadata is now parsed from the bounded buffer with image-size: at most 8,192 pixels per side, 4 million pixels per image and 16 million pixels across unique preview blobs. Unknown dimensions omit the preview; existing compressed/response byte limits remain. Sidecars use lstat so dangling links are rejected. Both new regressions failed before the fixes. The summary mentioned rename-scope/literal-path concerns without specific findings; no additional behavior was inferred from that shorthand.
53+
54+
## Feedback on selected code
55+
56+
Click a changed line number, Shift-click to extend a range, or highlight code within one changed block. The selection toolbar offers Ask and Request change; each attaches the full selected lines to that item's composer. Question/change-request drafts retain separate attachments. Remove snippet returns to item-level feedback.
57+
58+
The server validates the segment and range against the current review token and constructs the saved reference itself: path, old/new side, exact text, line range, base and head commits. Limits are 200 lines and 16,000 characters. References on unassigned changes require assigning them to a plan item first. Existing item-level notes remain compatible without a database migration.
59+
60+
Saved references navigate to the selected lines while the reviewed commits and assignment still match. Otherwise they are labeled Outdated and open the original captured snippet, never silently pointing at new code. This deliberately marks references outdated on any base/head change, even if the snippet is unchanged. Refresh invalidates transient selections; outdated draft attachments must be removed and reselected before submission. No agent or GitHub comment is invoked.
61+
62+
Snippet-feedback validation: 176 unit/integration tests and 15 browser tests pass (baseline 174 and 13), plus typecheck and diff checks. Coverage includes clicked lines, Shift-click ranges, DOM text highlighting, independent question/change drafts, removal, persistence, navigation, removed-side references, forged/invalid references and outdated snapshots. The actual PR #597 walkthrough was also opened in Chromium and the selected-line/composer layout visually inspected without saving test notes to its database.

‎runner/review.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { createHash } from 'node:crypto';
22
import { basename } from 'node:path';
33
import { isDeepStrictEqual } from 'node:util';
4-
import { Store, type ReviewState } from './store.ts';
4+
import { Store, type ReviewState, type SnippetReference } from './store.ts';
55
import type { PlanIdentity } from '../core/identity.ts';
66
import { readHistory } from '../git/history.ts';
77
import { linkHistory } from '../core/linking.ts';
@@ -52,7 +52,7 @@ export class ReviewService {
5252
if (states[item.id] === 'approved' && (segments.some(segment => segment.row === 'Ambiguous' && segment.owners.includes(item.id)) || item.depends_on.some(id => states[id] === 'stale'))) states[item.id] = 'stale';
5353
}
5454
const expected: ReviewState = { revision: plan.revision, snapshotId: snapshot.id, reviewVersion };
55-
const notes = this.store.getReviewNotes(identity);
55+
const notes = this.store.getReviewNotes(identity).map(note => ({ ...note, outdated: !!note.reference && (note.reference.head !== history.head || note.reference.base !== history.base || !segments.some(segment => segment.key === note.reference!.key && segment.row === note.item)) }));
5656
if (this.store.reviewVersion(identity) !== reviewVersion || this.store.getPlan(identity).revision !== plan.revision || this.store.getSnapshot(identity).id !== snapshot.id) throw new Error('Stale review state. Reload before writing.');
5757
const items = plan.items.map(item => {
5858
const owned = segments.filter(segment => segment.row === item.id);
@@ -92,7 +92,21 @@ export class ReviewService {
9292
const storedKey = choiceKeys(view.segments, identity)[view.segments.indexOf(segment)]!;
9393
this.store.saveReview(identity, view.expected, [], [{ key: storedKey, action: command.action, item }]);
9494
} else if (command.action === 'note' && typeof command.item === 'string' && typeof command.text === 'string' && (command.kind === 'question' || command.kind === 'change')) {
95-
this.store.addReviewNote(identity, view.expected, command.item, command.kind, command.text);
95+
let reference: SnippetReference | undefined;
96+
if (command.reference !== undefined) {
97+
if (!command.reference || typeof command.reference !== 'object') throw new Error('Invalid snippet reference.');
98+
const input = command.reference as Record<string, unknown>;
99+
const segment = view.segments.find(s => s.key === input.key && s.row === command.item && s.kind !== 'file');
100+
const start = input.start as number, end = input.end as number;
101+
if (!segment || !Number.isSafeInteger(start) || !Number.isSafeInteger(end)) throw new Error('Invalid snippet reference.');
102+
const first = segment.operation === '+' ? segment.newLine : segment.oldLine;
103+
const lines = segment.content.split('\n'); if (lines.at(-1) === '') lines.pop();
104+
if (first === null || start < first || end < start || end >= first + lines.length || end - start >= 200) throw new Error('Select up to 200 lines within one changed block.');
105+
const text = lines.slice(start-first, end-first+1).join('\n');
106+
if (text.length > 16000) throw new Error('Selected snippet exceeds 16000 characters.');
107+
reference = { key: segment.key, path: segment.operation === '-' ? segment.oldPath ?? segment.path : segment.path, side: segment.operation === '+' ? 'new' : 'old', start, end, text, head: view.snapshot.head, base: view.snapshot.base };
108+
}
109+
this.store.addReviewNote(identity, view.expected, command.item, command.kind, command.text, reference);
96110
} else throw new Error('Unknown review command.');
97111
return this.load();
98112
}

‎runner/store.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ export function requireSupportedNode(version = process.versions.node): void {
1212
}
1313
export interface Snapshot { id: string; base: string; head: string }
1414
export interface ReviewState { revision: number; snapshotId: string; reviewVersion?: number }
15-
export interface ReviewNote { id: string; item: string; kind: 'question' | 'change'; text: string; createdAt: string; revision: number; snapshotId: string }
15+
export interface SnippetReference { key: string; path: string; side: 'old' | 'new'; start: number; end: number; text: string; head: string; base: string }
16+
export interface ReviewNote { id: string; item: string; kind: 'question' | 'change'; text: string; reference?: SnippetReference; createdAt: string; revision: number; snapshotId: string }
1617
export interface LedgerEntry { sha: string; owner: string | null; origin: 'owned' | 'foreign'; sourceSha: string | null }
1718
export interface Checkpoint {
1819
id: string; revision: number; snapshotId: string; item: string;
@@ -246,12 +247,12 @@ export class Store {
246247
});
247248
}
248249
reviewVersion(identity: PlanIdentity): number { return this.#current(identityKey(identity)).review_version as number; }
249-
addReviewNote(identity: PlanIdentity, expected: ReviewState, item: string, kind: ReviewNote['kind'], text: string): ReviewNote {
250+
addReviewNote(identity: PlanIdentity, expected: ReviewState, item: string, kind: ReviewNote['kind'], text: string, reference?: SnippetReference): ReviewNote {
250251
const key = identityKey(identity);
251252
return this.#transaction(() => {
252253
this.#expect(key, expected);
253254
if (!this.getPlan(identity).items.some(entry => entry.id === item) || !['question', 'change'].includes(kind) || typeof text !== 'string' || !text.trim() || text.length > 4000) throw new Error('Invalid review note.');
254-
const note = { id: randomUUID(), item, kind, text: text.trim(), createdAt: new Date().toISOString(), revision: expected.revision, snapshotId: expected.snapshotId };
255+
const note = { id: randomUUID(), item, kind, text: text.trim(), ...(reference ? { reference } : {}), createdAt: new Date().toISOString(), revision: expected.revision, snapshotId: expected.snapshotId };
255256
this.#run('INSERT INTO review_notes VALUES (?,?,?)', key, note.id, encode(note));
256257
this.#run('UPDATE plans SET review_version=review_version+1 WHERE key=?', key);
257258
return note;

‎test/browser/review.spec.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,32 @@ test('routes mixed owned and ambiguous items to attribution resolution',async({p
7777
test('keeps review shortcuts active while a toolbar button has focus',async({page})=>{
7878
await page.goto(app.url);await expect(page.getByRole('heading',{name:'Bound exponential retries'})).toBeVisible();await page.getByRole('button',{name:'Refresh',exact:true}).focus();await page.keyboard.press('n');await expect(page.getByRole('heading',{name:'Document retry behavior'})).toBeVisible();
7979
});
80+
test('attaches clicked lines to a question, persists and navigates the reference, and shows archived evidence',async({page})=>{
81+
await page.goto(app.url);
82+
const line=page.locator('.added [data-line]').first();await line.click();
83+
await page.getByRole('button',{name:'Ask about selection',exact:true}).click();
84+
await expect(page.locator('#attachment')).toContainText('retry.ts');
85+
await page.getByLabel('Question about this item').fill('Why this exact line?');await page.getByRole('button',{name:'Save question',exact:true}).click();
86+
await page.reload();await page.locator('.note-reference').click();await expect(page.locator('.selected-line').first()).toBeVisible();
87+
execFileSync('git',['-c','core.hooksPath=/dev/null','commit','--allow-empty','-m','another revision'],{cwd:app.service.config.repository,stdio:'pipe'});
88+
await page.getByRole('button',{name:'Refresh',exact:true}).click();await expect(page.locator('.note-reference')).toContainText('Outdated');await page.locator('.note-reference').click();await expect(page.getByRole('heading',{name:'! Outdated code reference'})).toBeVisible();await expect(page.locator('#dialog-body pre')).toContainText('Math.min');
89+
});
90+
test('supports shift ranges, highlighted lines, and independent snippet drafts',async({page})=>{
91+
const repository=app.service.config.repository;
92+
writeFileSync(join(repository,'retry.ts'),'export const cap = 5000;\nexport const base = 100;\nexport const delay = (n: number) => Math.min(cap, base * 2 ** n);\n');
93+
execFileSync('git',['-c','core.hooksPath=/dev/null','commit','-am','rewrite retry'],{cwd:repository,stdio:'pipe'});
94+
let view=app.service.load();
95+
for(const key of view.segments.filter(s=>s.path==='retry.ts'&&['Unplanned','Ambiguous'].includes(s.row)).map(s=>s.key)) view=app.service.act({action:'assign',key,item:'P1',token:view.token});
96+
await page.goto(app.url);
97+
const block=page.locator('.added[data-segment]').filter({hasText:'export const cap'});
98+
await block.locator('[data-line]').nth(0).click();await block.locator('[data-line]').nth(2).click({modifiers:['Shift']});
99+
await expect(page.locator('#selection-label')).toContainText('L1–3');
100+
await page.getByRole('button',{name:'Request change to selection',exact:true}).click();await expect(page.locator('#attachment pre')).toContainText('export const delay');
101+
await page.getByLabel('Change to request').fill('Please explain these constants.');
102+
await page.getByRole('button',{name:'Ask',exact:true}).click();await expect(page.locator('#attachment')).toBeHidden();
103+
await block.locator('.code-lines').evaluate(element=>{const lines=element.querySelectorAll('[data-code-line]');const range=document.createRange();range.setStart(lines[0]!.firstChild!,0);range.setEnd(lines[1]!.firstChild!,6);const selection=window.getSelection()!;selection.removeAllRanges();selection.addRange(range);element.dispatchEvent(new MouseEvent('mouseup',{bubbles:true}));});
104+
await expect(page.locator('#selection-label')).toContainText('L1–2');await page.getByRole('button',{name:'Ask about selection',exact:true}).click();await expect(page.locator('#attachment pre')).not.toContainText('export const delay');
105+
await page.getByRole('button',{name:'Remove snippet',exact:true}).click();await expect(page.locator('#attachment')).toBeHidden();
106+
await page.getByRole('button',{name:'Request change',exact:true}).click();await expect(page.locator('#attachment pre')).toContainText('export const delay');
107+
await page.getByRole('button',{name:'Save change request',exact:true}).click();await expect(page.locator('.note-reference')).toContainText('L1–3');
108+
});

‎test/review.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,19 @@ it('refuses no-change confirmation while the item still owns ambiguous changes',
4242
expect(view.items[1]!.count).toBeGreaterThan(0);
4343
expect(()=>service.act({action:'approve',item:'P2',token:view.token})).toThrow(/ambiguous/i);
4444
});
45+
it('anchors notes to server-owned code and rejects invalid ranges and cross-item references',()=>{
46+
const {service,config}=fixture();let view=service.load();const segment=view.segments.find(s=>s.row==='P1'&&s.kind!=='file'&&s.operation==='+')!;
47+
const start=segment.newLine!;
48+
expect(()=>service.act({action:'note',item:'P2',kind:'question',text:'Why?',reference:{key:segment.key,start,end:start},token:view.token})).toThrow(/Invalid snippet/);
49+
expect(()=>service.act({action:'note',item:'P1',kind:'question',text:'Why?',reference:{key:segment.key,start:0,end:start},token:view.token})).toThrow(/changed block/);
50+
view=service.act({action:'note',item:'P1',kind:'question',text:'Why?',reference:{key:segment.key,start,end:start,text:'forged',path:'forged'},token:view.token});
51+
const ref=view.notes[0]!.reference!;expect(ref.text).toBe(segment.content.split('\n')[0]);expect(ref.path).toBe(segment.path);expect(ref.head).toBe(view.snapshot.head);expect(view.notes[0]!.outdated).toBe(false);
52+
const reopened=new ReviewService(config);services.push(reopened);expect(reopened.load().notes[0]!.reference).toEqual(ref);
53+
});
54+
it('preserves removed-side snippets and marks their references outdated after HEAD changes',async()=>{
55+
const {service,config}=fixture();let view=service.load();const segment=view.segments.find(s=>s.row==='P1'&&s.kind!=='file'&&s.operation==='-')!;
56+
view=service.act({action:'note',item:'P1',kind:'change',text:'Keep this?',reference:{key:segment.key,start:segment.oldLine,end:segment.oldLine},token:view.token});
57+
const ref=view.notes[0]!.reference!;expect(ref.side).toBe('old');
58+
const {execFileSync}=await import('node:child_process');execFileSync('git',['-c','core.hooksPath=/dev/null','commit','--allow-empty','-m','new revision'],{cwd:config.repository,stdio:'pipe'});
59+
view=service.load();expect(view.notes[0]!.outdated).toBe(true);expect(view.notes[0]!.reference).toEqual(ref);
60+
});

0 commit comments

Comments
 (0)