convergedev 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/LICENSE.md +34 -0
  2. package/THIRD_PARTY_NOTICES.md +149 -0
  3. package/dist/agent-execution.js +103 -0
  4. package/dist/agent-process.js +70 -0
  5. package/dist/agent.js +2 -0
  6. package/dist/anchors.js +101 -0
  7. package/dist/applications.js +69 -0
  8. package/dist/apply-proposal.js +236 -0
  9. package/dist/bridge-health.js +57 -0
  10. package/dist/bridge.js +203 -0
  11. package/dist/change-proposals.js +51 -0
  12. package/dist/claude.js +277 -0
  13. package/dist/cli.js +278 -0
  14. package/dist/commands.js +80 -0
  15. package/dist/comment-file.js +41 -0
  16. package/dist/comment-host.js +96 -0
  17. package/dist/config.js +43 -0
  18. package/dist/converge.js +36 -0
  19. package/dist/exec.js +52 -0
  20. package/dist/follow-branch.js +70 -0
  21. package/dist/git.js +169 -0
  22. package/dist/hunks.js +558 -0
  23. package/dist/implementation-results.js +98 -0
  24. package/dist/implementation-runner.js +262 -0
  25. package/dist/queries/ecmascript.scm +35 -0
  26. package/dist/queries/javascript.scm +6 -0
  27. package/dist/queries/python.scm +10 -0
  28. package/dist/queries/typescript.scm +16 -0
  29. package/dist/relay.js +32 -0
  30. package/dist/runner.js +104 -0
  31. package/dist/sandbox.js +53 -0
  32. package/dist/session-state.js +36 -0
  33. package/dist/setup.js +328 -0
  34. package/dist/share-review.js +34 -0
  35. package/dist/shared.js +193 -0
  36. package/dist/skill/converge/SKILL.md +25 -0
  37. package/dist/skill/converge/converge.mjs +35 -0
  38. package/dist/skill-link.js +100 -0
  39. package/dist/worktree.js +231 -0
  40. package/grammars/SOURCES.json +22 -0
  41. package/grammars/tree-sitter-javascript.wasm +0 -0
  42. package/grammars/tree-sitter-python.wasm +0 -0
  43. package/grammars/tree-sitter-tsx.wasm +0 -0
  44. package/grammars/tree-sitter-typescript.wasm +0 -0
  45. package/package.json +45 -4
  46. package/README.md +0 -3
package/dist/hunks.js ADDED
@@ -0,0 +1,558 @@
1
+ // Cuts a unified diff into hunks at function boundaries: every changed line is filed under the innermost
2
+ // top-level function, method or class around it (or under "imports" / "top level" when it is outside any),
3
+ // so a file with five changed functions gives five hunks. Rule-based only; see grammars/README.md.
4
+ //
5
+ // Hunks point at lines of the diff (indexes into diff.split('\n')) instead of copying text.
6
+ import { spawn } from 'node:child_process';
7
+ import { readFileSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { Language, Parser, Query } from 'web-tree-sitter';
11
+ export const MAX_FILE_BYTES = 400_000;
12
+ export const MAX_HUNKS = 3000; // the API accepts up to 5000
13
+ const MAX_SYMBOL = 300;
14
+ const PARSE_TIMEOUT_MS = 500;
15
+ const MAX_TOTAL_BYTES = 32 * 1024 * 1024;
16
+ /** Runs one `git cat-file --batch…` for many objects; one process per call however many files the changes touch. */
17
+ function catFile(cwd, mode, specs) {
18
+ return new Promise((resolve, reject) => {
19
+ // Hidden for the same reason as git() in git.ts: the detached bridge has no console to share.
20
+ const child = spawn('git', ['-c', 'core.quotepath=off', 'cat-file', mode], { cwd, stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });
21
+ const chunks = [];
22
+ child.stdout.on('data', (c) => chunks.push(c));
23
+ child.on('error', reject);
24
+ child.on('close', (code) => code === 0 ? resolve(Buffer.concat(chunks)) : reject(new Error(`git cat-file exited with ${code}`)));
25
+ child.stdin.on('error', reject);
26
+ child.stdin.end(`${specs.join('\n')}\n`);
27
+ });
28
+ }
29
+ const OBJECT_HEADER = /^[0-9a-f]+ (\w+) (\d+)$/;
30
+ export function gitIo(cwd) {
31
+ return {
32
+ async read(requests) {
33
+ if (!requests.length)
34
+ return [];
35
+ const specs = requests.map((r) => `${r.sha}:${r.path}`);
36
+ // Sizes first, so oversized files are never read.
37
+ const sizes = (await catFile(cwd, '--batch-check', specs)).toString('utf8').split('\n').slice(0, specs.length)
38
+ .map((line) => { const m = OBJECT_HEADER.exec(line); return m && m[1] === 'blob' ? Number(m[2]) : null; });
39
+ const wanted = [];
40
+ let total = 0;
41
+ sizes.forEach((size, i) => {
42
+ if (size === null || size > MAX_FILE_BYTES || total + size > MAX_TOTAL_BYTES)
43
+ return;
44
+ wanted.push(i);
45
+ total += size;
46
+ });
47
+ const out = requests.map(() => null);
48
+ if (!wanted.length)
49
+ return out;
50
+ const buf = await catFile(cwd, '--batch', wanted.map((i) => specs[i]));
51
+ let pos = 0;
52
+ for (const i of wanted) {
53
+ const nl = buf.indexOf(10, pos);
54
+ if (nl < 0)
55
+ break;
56
+ const m = OBJECT_HEADER.exec(buf.toString('utf8', pos, nl));
57
+ if (!m) {
58
+ pos = nl + 1;
59
+ continue;
60
+ } // "<spec> missing"
61
+ const size = Number(m[2]);
62
+ out[i] = buf.toString('utf8', nl + 1, nl + 1 + size);
63
+ pos = nl + 1 + size + 1;
64
+ }
65
+ return out;
66
+ },
67
+ };
68
+ }
69
+ const HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/;
70
+ function pathFromGitLine(rest) {
71
+ // "a/P b/P": without renames both sides are the same path, so P is half of what remains.
72
+ if (!rest.startsWith('a/') || (rest.length - 5) % 2)
73
+ return undefined;
74
+ const n = (rest.length - 5) / 2;
75
+ const a = rest.slice(2, 2 + n);
76
+ return rest.slice(2 + n, 5 + n) === ' b/' && rest.slice(5 + n) === a ? a : undefined;
77
+ }
78
+ export function parseDiff(lines) {
79
+ const files = [];
80
+ let i = 0;
81
+ while (i < lines.length) {
82
+ if (!lines[i].startsWith('diff --git ')) {
83
+ i++;
84
+ continue;
85
+ }
86
+ const rest = lines[i].slice('diff --git '.length);
87
+ const file = { path: pathFromGitLine(rest) ?? rest, start: i, end: i, status: 'modified',
88
+ quoted: rest.startsWith('"'), truncated: false, hunks: [] };
89
+ files.push(file);
90
+ i++;
91
+ for (; i < lines.length && !lines[i].startsWith('@@') && !lines[i].startsWith('diff --git '); i++) {
92
+ const l = lines[i];
93
+ if (l.startsWith('new file mode'))
94
+ file.status = 'added';
95
+ else if (l.startsWith('deleted file mode'))
96
+ file.status = 'deleted';
97
+ else if (l.startsWith('Binary files ') || l === 'GIT binary patch')
98
+ file.status = 'binary';
99
+ else if (l.startsWith('--- ') || l.startsWith('+++ ')) {
100
+ const p = l.slice(4).replace(/\t$/, '');
101
+ if (p === '/dev/null')
102
+ continue;
103
+ if (p.startsWith('"'))
104
+ file.quoted = true;
105
+ else if (l.startsWith('+++ ') || file.status === 'deleted')
106
+ file.path = p.replace(/^[ab]\//, '');
107
+ }
108
+ }
109
+ while (i < lines.length && lines[i].startsWith('@@')) {
110
+ const m = HUNK_HEADER.exec(lines[i]);
111
+ if (!m) {
112
+ file.truncated = true;
113
+ i++;
114
+ break;
115
+ }
116
+ const hunk = { header: i, end: i + 1, funcname: m[5].trim(), entries: [] };
117
+ file.hunks.push(hunk);
118
+ let b = Number(m[1]), h = Number(m[3]);
119
+ let remOld = m[2] === undefined ? 1 : Number(m[2]);
120
+ let remNew = m[4] === undefined ? 1 : Number(m[4]);
121
+ i++;
122
+ // Walk by the counts in the header, not by looking for the next "@@", so a body line such as
123
+ // "--- x" (a deleted "-- x") is never mistaken for a header.
124
+ while (remOld > 0 || remNew > 0) {
125
+ if (i >= lines.length || lines[i].startsWith('diff --git ')) {
126
+ file.truncated = true;
127
+ break;
128
+ }
129
+ const l = lines[i];
130
+ const last = hunk.entries[hunk.entries.length - 1];
131
+ if (l.startsWith('\\')) {
132
+ if (last)
133
+ last.last = i;
134
+ i++;
135
+ continue;
136
+ }
137
+ if (l.startsWith('+')) {
138
+ hunk.entries.push({ idx: i, last: i, type: '+', base: b, head: h });
139
+ h++;
140
+ remNew--;
141
+ }
142
+ else if (l.startsWith('-')) {
143
+ hunk.entries.push({ idx: i, last: i, type: '-', base: b, head: h });
144
+ b++;
145
+ remOld--;
146
+ }
147
+ else {
148
+ hunk.entries.push({ idx: i, last: i, type: ' ', base: b, head: h });
149
+ b++;
150
+ h++;
151
+ remOld--;
152
+ remNew--;
153
+ }
154
+ i++;
155
+ }
156
+ while (i < lines.length && lines[i].startsWith('\\')) {
157
+ const last = hunk.entries[hunk.entries.length - 1];
158
+ if (last)
159
+ last.last = i;
160
+ i++;
161
+ }
162
+ hunk.end = i;
163
+ }
164
+ while (i < lines.length && !lines[i].startsWith('diff --git '))
165
+ i++;
166
+ file.end = i;
167
+ }
168
+ return files;
169
+ }
170
+ const LANGUAGES = {
171
+ '.ts': 'typescript', '.mts': 'typescript', '.cts': 'typescript', '.tsx': 'tsx',
172
+ '.js': 'javascript', '.mjs': 'javascript', '.cjs': 'javascript', '.jsx': 'javascript',
173
+ '.py': 'python',
174
+ };
175
+ const QUERY_FILES = {
176
+ typescript: ['ecmascript', 'typescript'], tsx: ['ecmascript', 'typescript'],
177
+ javascript: ['ecmascript', 'javascript'], python: ['python'],
178
+ };
179
+ const CONFIG_FILE = /(^|\/)(\.env[^/]*|Dockerfile[^/]*|\.[^/]+rc|[^/]+\.(json|jsonc|ya?ml|toml|ini|cfg|conf|lock|properties)|[^/]+\.config\.[^/]+)$/i;
180
+ export function languageFor(path) {
181
+ const ext = /\.[^./]+$/.exec(path)?.[0].toLowerCase();
182
+ return ext ? LANGUAGES[ext] : undefined;
183
+ }
184
+ const grammarsDir = fileURLToPath(new URL('../grammars/', import.meta.url));
185
+ const queriesDir = fileURLToPath(new URL('./queries/', import.meta.url));
186
+ let parser;
187
+ const loaded = new Map();
188
+ /** Loads a grammar and its query once per process. A failure is remembered: it would only fail again. */
189
+ export function loadLanguage(lang) {
190
+ let entry = loaded.get(lang);
191
+ if (!entry) {
192
+ entry = (async () => {
193
+ const p = await (parser ??= Parser.init().then(() => new Parser()));
194
+ const language = await Language.load(new Uint8Array(readFileSync(join(grammarsDir, `tree-sitter-${lang}.wasm`))));
195
+ const source = QUERY_FILES[lang].map((q) => readFileSync(join(queriesDir, `${q}.scm`), 'utf8')).join('\n');
196
+ return { parser: p, language, query: new Query(language, source) };
197
+ })();
198
+ loaded.set(lang, entry);
199
+ }
200
+ return entry;
201
+ }
202
+ const nodeId = (n) => `${n.startIndex}:${n.endIndex}:${n.type}`;
203
+ const endRow = (n) => n.endPosition.column === 0 && n.endPosition.row > n.startPosition.row
204
+ ? n.endPosition.row - 1 : n.endPosition.row;
205
+ /** Rows a definition covers: widened to its decorators, `export`, `const` wrapper and the comments just above it. */
206
+ function span(node) {
207
+ let top = node;
208
+ for (let p = top.parent; p; p = top.parent) {
209
+ const wrapper = p.type === 'decorated_definition' || p.type === 'export_statement' ||
210
+ ((p.type === 'lexical_declaration' || p.type === 'variable_declaration') && p.namedChildCount === 1);
211
+ if (!wrapper)
212
+ break;
213
+ top = p;
214
+ }
215
+ let start = top.startPosition.row;
216
+ for (let s = top.previousNamedSibling; s && s.type === 'comment' && s.endPosition.row >= start - 1; s = s.previousNamedSibling) {
217
+ const before = s.previousSibling;
218
+ if (before && before.endPosition.row === s.startPosition.row)
219
+ break; // a trailing comment on another line of code
220
+ start = s.startPosition.row;
221
+ }
222
+ return { start, end: endRow(top) };
223
+ }
224
+ const unquote = (s) => /^(['"]).*\1$/s.test(s) ? s.slice(1, -1) : s;
225
+ /**
226
+ * The definitions in a file. Only top-level ones count: classes and their methods, titled calls such as tests,
227
+ * and functions not nested in another function (a callback or helper inside a function is part of that
228
+ * function's hunk). Throws on failure.
229
+ */
230
+ export async function outline(lang, text) {
231
+ const { parser: p, language, query } = await loadLanguage(lang);
232
+ p.setLanguage(language);
233
+ const deadline = Date.now() + PARSE_TIMEOUT_MS;
234
+ // Returning true from the progress callback cancels the parse (parse then returns null).
235
+ const progressCallback = (() => Date.now() > deadline);
236
+ const tree = p.parse(text, null, { progressCallback });
237
+ if (!tree)
238
+ throw new Error('parse cancelled');
239
+ try {
240
+ const raw = new Map();
241
+ const imports = [];
242
+ for (const match of query.matches(tree.rootNode)) {
243
+ const def = match.captures.find((c) => c.name === 'function' || c.name === 'method' || c.name === 'class' ||
244
+ c.name === 'call' || c.name === 'import');
245
+ if (!def)
246
+ continue;
247
+ if (def.name === 'import') {
248
+ imports.push([def.node.startPosition.row, endRow(def.node)]);
249
+ continue;
250
+ }
251
+ const nameNode = match.captures.find((c) => c.name === 'name')?.node;
252
+ if (!nameNode)
253
+ continue;
254
+ const callee = match.captures.find((c) => c.name === 'callee')?.node.text;
255
+ const name = def.name === 'call' ? `${callee}: ${unquote(nameNode.text)}` : nameNode.text;
256
+ raw.set(nodeId(def.node), { kind: def.name, name, node: def.node });
257
+ }
258
+ // Resolve each definition after its containers; null marks one nested inside a function (not its own hunk).
259
+ const resolve = (r) => {
260
+ if (r.def !== undefined)
261
+ return r.def;
262
+ let outer;
263
+ for (let a = r.node.parent; a && !outer; a = a.parent)
264
+ outer = raw.get(nodeId(a));
265
+ const parent = outer ? resolve(outer) : undefined;
266
+ // Inside a function only nothing is its own hunk; inside a titled call (a test's callback) only titled calls are.
267
+ if (parent === null || (parent && (parent.kind === 'function' || parent.kind === 'method')))
268
+ return r.def = null;
269
+ if (parent?.kind === 'call' && r.kind !== 'call')
270
+ return r.def = null;
271
+ const kind = r.kind === 'class' || r.kind === 'call' ? r.kind
272
+ : r.kind === 'method' || parent?.kind === 'class' ? 'method' : 'function';
273
+ const prefix = parent ? `${parent.symbol}${parent.kind === 'call' ? ' › ' : '.'}` : '';
274
+ const symbol = `${prefix}${r.name}${kind === 'function' || kind === 'method' ? '()' : ''}`.slice(0, MAX_SYMBOL);
275
+ return r.def = { kind, symbol, ...span(r.node), parent };
276
+ };
277
+ const defs = [...raw.values()].map(resolve).filter((d) => !!d);
278
+ return { defs, imports, symbols: new Set(defs.map((d) => d.symbol)) };
279
+ }
280
+ finally {
281
+ tree.delete();
282
+ }
283
+ }
284
+ /** The smallest definition containing a 0-based row; on a tie, the one that is not a class. */
285
+ export function innermost(defs, row) {
286
+ let best;
287
+ for (const d of defs) {
288
+ if (row < d.start || row > d.end)
289
+ continue;
290
+ const size = d.end - d.start, bestSize = best ? best.end - best.start : Infinity;
291
+ if (size < bestSize || (size === bestSize && best?.kind === 'class' && d.kind !== 'class'))
292
+ best = d;
293
+ }
294
+ return best;
295
+ }
296
+ const IMPORTS = { id: 'imports', kind: 'imports', symbol: null };
297
+ const TOP_LEVEL = { id: 'top-level', kind: 'top-level', symbol: null };
298
+ /**
299
+ * The key for a definition. A definition inside a class that only exists on this side of the change (a class
300
+ * added or removed whole) is reviewed as part of that class, not method by method.
301
+ */
302
+ function defKey(d, other) {
303
+ let top = d;
304
+ for (let p = d.parent; p; p = p.parent)
305
+ if (p.kind === 'class' && !other?.symbols.has(p.symbol))
306
+ top = p;
307
+ return { id: `def:${top.symbol}`, kind: top.kind === 'call' ? 'function' : top.kind, symbol: top.symbol };
308
+ }
309
+ function keyAt(o, row, other) {
310
+ const d = innermost(o.defs, row);
311
+ if (d)
312
+ return defKey(d, other);
313
+ return o.imports.some(([s, e]) => row >= s && row <= e) ? IMPORTS : TOP_LEVEL;
314
+ }
315
+ function lineKey(e, base, head) {
316
+ if (e.type === '+' || (e.type === ' ' && head))
317
+ return keyAt(head, e.head - 1, base);
318
+ if (e.type === ' ')
319
+ return keyAt(base, e.base - 1, head);
320
+ // A deleted line belongs to the definition it was in, unless that definition was renamed or rewritten in
321
+ // place: its name is gone from the new file and the new definition at the same spot did not exist before.
322
+ const before = innermost(base.defs, e.base - 1);
323
+ if (!before)
324
+ return keyAt(base, e.base - 1, head);
325
+ if (head && !head.symbols.has(before.symbol)) {
326
+ const after = innermost(head.defs, e.head - 1);
327
+ if (after && !base.symbols.has(after.symbol))
328
+ return defKey(after, base);
329
+ }
330
+ return defKey(before, head);
331
+ }
332
+ function emptyHunk(path, kind, symbol, fallback) {
333
+ return { path, kind, symbol, ranges: [], additions: 0, deletions: 0, fallback };
334
+ }
335
+ function addEntry(h, e) {
336
+ const last = h.ranges[h.ranges.length - 1];
337
+ if (last && last[1] === e.idx)
338
+ last[1] = e.last + 1;
339
+ else
340
+ h.ranges.push([e.idx, e.last + 1]);
341
+ if (e.type === '+')
342
+ h.additions++;
343
+ else if (e.type === '-')
344
+ h.deletions++;
345
+ }
346
+ function addGitHunk(h, g) {
347
+ if (g.end > g.header + 1)
348
+ h.ranges.push([g.header + 1, g.end]);
349
+ for (const e of g.entries) {
350
+ if (e.type === '+')
351
+ h.additions++;
352
+ else if (e.type === '-')
353
+ h.deletions++;
354
+ }
355
+ }
356
+ const FILLER = /^[\s)\]};,]*$/;
357
+ const BLANK = /^\s*$/;
358
+ /** A changed line with nothing reviewable on it, outside any function: blank, or only closing brackets. */
359
+ const isFiller = (key, line) => (key.kind === 'top-level' || key.kind === 'imports' || key.kind === 'class') && FILLER.test(line.slice(1));
360
+ export function groupFile(lines, file, base, head) {
361
+ const byKey = new Map();
362
+ const put = (key, e) => {
363
+ let h = byKey.get(key.id);
364
+ if (!h)
365
+ byKey.set(key.id, h = emptyHunk(file.path, key.kind, key.symbol, null));
366
+ addEntry(h, e);
367
+ };
368
+ for (const g of file.hunks) {
369
+ let current;
370
+ let pending = [];
371
+ const flush = (key) => { for (const p of pending)
372
+ put(key, p); pending = []; };
373
+ for (const e of g.entries) {
374
+ const key = lineKey(e, base, head);
375
+ if (e.type === ' ') {
376
+ // Context stays with the run before it when it is part of the same definition (a closing brace),
377
+ // otherwise it waits for the next changed line.
378
+ if (current && !pending.length && key.id === current.id)
379
+ put(current, e);
380
+ else
381
+ pending.push(e);
382
+ continue;
383
+ }
384
+ if (isFiller(key, lines[e.idx])) {
385
+ // A lone closing bracket joins the run before it rather than forming a hunk of its own (git often aligns
386
+ // a class's closing "}" with the end of the next one). A blank line between definitions instead waits for
387
+ // the next changed line: it reads as the start of what follows, and counting it above would mark a
388
+ // neighbour as changed. With nothing after it in the git hunk it still ends up on the run before.
389
+ if (current && !BLANK.test(lines[e.idx].slice(1))) {
390
+ flush(current);
391
+ put(current, e);
392
+ }
393
+ else
394
+ pending.push(e);
395
+ continue;
396
+ }
397
+ flush(key);
398
+ put(key, e);
399
+ current = key;
400
+ }
401
+ if (current)
402
+ flush(current);
403
+ else
404
+ for (const p of pending)
405
+ put(lineKey(p, base, head), p);
406
+ }
407
+ return [...byKey.values()].filter((h) => h.ranges.length).sort((a, b) => a.ranges[0][0] - b.ranges[0][0]);
408
+ }
409
+ /**
410
+ * Markdown has no grammar here, but its own headings name a section better than git's guess, which is the nearest
411
+ * line above the hunk that starts with a letter and is often a line inside a code block.
412
+ */
413
+ const MARKDOWN = /\.(md|markdown|mdx)$/i;
414
+ const ATX_HEADING = /^ {0,3}#{1,6}\s+(.+?)\s*#*\s*$/;
415
+ const FENCE = /^ {0,3}(```|~~~)/;
416
+ /** The last heading among the first `rows` lines of a Markdown text; "#" lines inside fenced code do not count. */
417
+ function headingAbove(text, rows) {
418
+ let heading, fence;
419
+ const all = text.split(/\r?\n/);
420
+ for (let i = 0; i < Math.min(rows, all.length); i++) {
421
+ const mark = FENCE.exec(all[i])?.[1];
422
+ if (mark) {
423
+ fence = fence === undefined ? mark : fence === mark ? undefined : fence;
424
+ continue;
425
+ }
426
+ if (fence === undefined)
427
+ heading = ATX_HEADING.exec(all[i])?.[1] ?? heading;
428
+ }
429
+ return heading;
430
+ }
431
+ /** One hunk per git hunk, named by `name` (git's own guess by default); neighbours with the same name merge. */
432
+ function byGitHunk(file, kind, fallback, name = (g) => g.funcname || undefined) {
433
+ const out = [];
434
+ for (const g of file.hunks) {
435
+ const symbol = name(g)?.slice(0, MAX_SYMBOL) ?? null;
436
+ const prev = out[out.length - 1];
437
+ const h = prev && symbol && prev.symbol === symbol ? prev : emptyHunk(file.path, kind, symbol, fallback);
438
+ if (h !== prev)
439
+ out.push(h);
440
+ addGitHunk(h, g);
441
+ }
442
+ return out.filter((h) => h.ranges.length);
443
+ }
444
+ function wholeFile(lines, file, fallback) {
445
+ const h = emptyHunk(file.path, 'file', null, fallback);
446
+ for (const g of file.hunks)
447
+ addGitHunk(h, g);
448
+ if (!h.ranges.length && file.status === 'binary') {
449
+ let end = file.end;
450
+ while (end > file.start + 1 && !lines[end - 1])
451
+ end--;
452
+ if (end > file.start + 1)
453
+ h.ranges.push([file.start + 1, end]);
454
+ }
455
+ return h.ranges.length ? [h] : [];
456
+ }
457
+ /** Never throws: a file that cannot be split becomes one whole-file hunk, marked with the reason. */
458
+ export async function collectHunks(input) {
459
+ const io = input.io ?? gitIo(input.cwd);
460
+ const budgetMs = input.budgetMs ?? 3000;
461
+ const maxHunks = input.maxHunks ?? MAX_HUNKS;
462
+ const lines = input.diff.split('\n');
463
+ const files = parseDiff(lines);
464
+ if (input.diffTruncated && files.length)
465
+ files[files.length - 1].truncated = true;
466
+ const started = Date.now();
467
+ // Read every file needed in one go: base and head of each changed file in a supported language, and of each
468
+ // Markdown file for its headings.
469
+ const toRead = files.filter((f) => f.status !== 'binary' && f.hunks.length && !f.truncated && !f.quoted &&
470
+ (languageFor(f.path) || MARKDOWN.test(f.path)));
471
+ const requests = [];
472
+ const slots = new Map();
473
+ for (const f of toRead) {
474
+ const slot = {};
475
+ if (f.status !== 'added')
476
+ slot.base = requests.push({ sha: input.baseSha, path: f.path }) - 1;
477
+ if (f.status !== 'deleted')
478
+ slot.head = requests.push({ sha: input.headSha, path: f.path }) - 1;
479
+ slots.set(f, slot);
480
+ }
481
+ const texts = await io.read(requests).catch(() => requests.map(() => null));
482
+ const perFile = [];
483
+ for (const file of files) {
484
+ perFile.push(await splitFile(file).catch(() => wholeFile(lines, file, 'whole-file')));
485
+ }
486
+ // Too many hunks for the room: show the files with the most hunks whole until the total fits.
487
+ let total = perFile.reduce((n, h) => n + h.length, 0);
488
+ while (total > maxHunks) {
489
+ let worst = -1;
490
+ perFile.forEach((h, i) => { if (h.length > 1 && (worst < 0 || h.length > perFile[worst].length))
491
+ worst = i; });
492
+ if (worst < 0)
493
+ break;
494
+ const whole = wholeFile(lines, files[worst], 'whole-file');
495
+ total += whole.length - perFile[worst].length;
496
+ perFile[worst] = whole;
497
+ }
498
+ return perFile.flat();
499
+ async function splitFile(file) {
500
+ if (file.status === 'binary')
501
+ return wholeFile(lines, file, 'binary');
502
+ if (!file.hunks.length)
503
+ return [];
504
+ if (file.truncated)
505
+ return wholeFile(lines, file, 'truncated');
506
+ if (file.quoted)
507
+ return wholeFile(lines, file, 'whole-file');
508
+ const lang = languageFor(file.path);
509
+ if (!lang) {
510
+ const kind = CONFIG_FILE.test(file.path) ? 'config' : 'top-level';
511
+ return byGitHunk(file, kind, 'no-grammar', MARKDOWN.test(file.path) ? markdownName(file) : undefined);
512
+ }
513
+ if (Date.now() - started > budgetMs)
514
+ return wholeFile(lines, file, 'whole-file');
515
+ const slot = slots.get(file);
516
+ const baseText = slot.base === undefined ? undefined : texts[slot.base];
517
+ const headText = slot.head === undefined ? undefined : texts[slot.head];
518
+ if (baseText === null || headText === null)
519
+ return wholeFile(lines, file, 'whole-file');
520
+ let base, head;
521
+ try {
522
+ base = baseText === undefined ? undefined : await outline(lang, baseText);
523
+ head = headText === undefined ? undefined : await outline(lang, headText);
524
+ }
525
+ catch {
526
+ return wholeFile(lines, file, 'parse-failed');
527
+ }
528
+ return groupFile(lines, file, base, head);
529
+ }
530
+ /** Names a git hunk after the heading above its first changed line: in the new text, or the old one if deleted. */
531
+ function markdownName(file) {
532
+ const slot = slots.get(file);
533
+ const head = slot?.head === undefined ? undefined : texts[slot.head] ?? undefined;
534
+ const base = slot?.base === undefined ? undefined : texts[slot.base] ?? undefined;
535
+ return (g) => {
536
+ const first = g.entries.find((e) => e.type !== ' ');
537
+ // An added line is itself row `head`; a deleted one was removed just before row `head`.
538
+ const heading = !first ? undefined
539
+ : head !== undefined ? headingAbove(head, first.type === '+' ? first.head : first.head - 1)
540
+ : base !== undefined ? headingAbove(base, first.base) : undefined;
541
+ return heading ?? (g.funcname || undefined);
542
+ };
543
+ }
544
+ }
545
+ /** One line for the CLI: how the diff was split. */
546
+ export function describeHunks(hunks) {
547
+ const files = (pred) => new Set(hunks.filter(pred).map((h) => h.path)).size;
548
+ const parts = [`by function in ${files((h) => h.fallback === null)} file(s)`];
549
+ const noGrammar = files((h) => h.fallback === 'no-grammar');
550
+ if (noGrammar)
551
+ parts.push(`by git hunk in ${noGrammar} file(s) without a grammar`);
552
+ const whole = ['binary', 'truncated', 'parse-failed', 'whole-file']
553
+ .map((f) => [f, files((h) => h.fallback === f)]).filter(([, n]) => n)
554
+ .map(([f, n]) => `${n} ${f.replace('-', ' ')}`);
555
+ if (whole.length)
556
+ parts.push(`shown whole: ${whole.join(', ')}`);
557
+ return `${hunks.length} hunk${hunks.length === 1 ? '' : 's'} (${parts.join('; ')})`;
558
+ }
@@ -0,0 +1,98 @@
1
+ // What an implementation request's agent changed, kept on the requester's machine once its run succeeds
2
+ // (docs/review-room.md, decision 17). The worktree is removed after every run, so before that its changes become one
3
+ // commit whose parent is the commit the request was claimed at, under `refs/converge/<room>/<request>` in the
4
+ // requester's own repository: not a branch, never checked out, and not pushed. The commit's message names the room,
5
+ // the request, the requester and the base, so the result can be found and checked without the relay.
6
+ //
7
+ // A ref exists only for a request the relay has, or may still get, as completed: the runner removes it when the
8
+ // relay refuses the completion (the member cancelled meanwhile, the agent's access was revoked), and on connect when
9
+ // the relay says the request ended otherwise (implementation-runner.ts). A save that fails part-way removes its own.
10
+ //
11
+ // `readResult` is how the room gets to see it (#44): the same snapshot a review room shows, made from the base and the
12
+ // result's ref, so a Change Proposal renders as hunks like any other change.
13
+ import { createHash } from 'node:crypto';
14
+ import { collectReview, git } from './git.js';
15
+ /** apps/api implementation_runs.py MAX_RESULT_FILES, MAX_RESULT_PATH_CHARS. */
16
+ export const RESULT_LIMITS = { files: 300, pathChars: 1000 };
17
+ const RESULT_REF_PREFIX = 'refs/converge'; // apps/api implementation_runs.py RESULT_REF_PREFIX
18
+ /** Who git records as having written the commit: the requester's agent, not a person with an address. */
19
+ const AUTHOR_EMAIL = 'agent@converge.invalid';
20
+ const TITLE_CHARS = 72;
21
+ /** SHA-256 of the diff as sent, in hex (apps/api snapshot_check.diff_digest). */
22
+ export const diffDigest = (diff) => createHash('sha256').update(diff, 'utf8').digest('hex');
23
+ /** The ids are the relay's (checked by worktree.ts before the worktree was made), so the name is a valid ref. */
24
+ export const resultRef = (roomId, requestId) => `${RESULT_REF_PREFIX}/${roomId}/${requestId}`;
25
+ function message(opts) {
26
+ const first = opts.instructions.split('\n')[0].trim();
27
+ const title = first.length > TITLE_CHARS ? `${first.slice(0, TITLE_CHARS - 1)}…` : first;
28
+ return [
29
+ title || 'Implementation request',
30
+ opts.summary,
31
+ [`Converge-Room: ${opts.roomId}`, `Converge-Request: ${opts.requestId}`,
32
+ `Converge-Requested-By: ${opts.requester.replace(/\n/g, ' ')}`, `Converge-Base: ${opts.base}`].join('\n'),
33
+ ].filter(Boolean).join('\n\n');
34
+ }
35
+ /**
36
+ * Keeps what the agent left in `worktree` as a commit on `base`, under the request's ref, and describes it. Null when
37
+ * the agent changed nothing: nothing since the commit the worktree was made at (for a revision, its proposal's
38
+ * commit, which is not `base`), or nothing against `base` at all. The ref is created, never moved: a second save for the same request fails, so one request
39
+ * has one result. No hook runs (commit-tree, update-ref) and nothing is signed, so no prompt can hold it up. If
40
+ * describing it fails after the ref was made, the ref is removed again before the error is thrown.
41
+ */
42
+ export async function saveResult(opts) {
43
+ const { worktree, roomId, requestId, base } = opts;
44
+ // Everything the agent left, as git sees the folder: new files included, ignored files (build output) not.
45
+ await git(worktree, ['add', '--all']);
46
+ const tree = (await git(worktree, ['write-tree'])).trim();
47
+ const unchanged = async (commit) => tree === (await git(worktree, ['rev-parse', `${commit}^{tree}`])).trim();
48
+ if (await unchanged('HEAD') || await unchanged(base))
49
+ return null;
50
+ const commit = (await git(worktree, ['-c', `user.name=${opts.requester.replace(/\n/g, ' ')}'s agent`, '-c', `user.email=${AUTHOR_EMAIL}`,
51
+ '-c', 'commit.gpgSign=false', 'commit-tree', tree, '-p', base, '-m', message(opts)])).trim();
52
+ const ref = resultRef(roomId, requestId);
53
+ await git(worktree, ['update-ref', '-m', 'converge: implementation result', ref, commit, '0'.repeat(commit.length)]);
54
+ try {
55
+ const { snapshot } = await collectReview(worktree, base, ref);
56
+ return describe(snapshot, ref, commit);
57
+ }
58
+ catch (err) {
59
+ await discardResult(worktree, ref, commit).catch(() => { });
60
+ throw err;
61
+ }
62
+ }
63
+ /** Removes a result's ref, only while it still names `commit`: a ref that is not that result is left alone. */
64
+ export async function discardResult(repoDir, ref, commit) {
65
+ await git(repoDir, ['update-ref', '-m', 'converge: result not kept', '-d', ref, commit]);
66
+ }
67
+ /** The requests of `roomId` that have a result kept in this repository. */
68
+ export async function keptResults(repoDir, roomId) {
69
+ const prefix = `${RESULT_REF_PREFIX}/${roomId}/`;
70
+ const lines = (await git(repoDir, ['for-each-ref', '--format=%(refname)%09%(objectname)', prefix])).split('\n').filter(Boolean);
71
+ return lines.map((line) => {
72
+ const [ref, commit] = line.split('\t');
73
+ return { requestId: ref.slice(prefix.length), ref, commit };
74
+ });
75
+ }
76
+ function describe(snapshot, ref, commit) {
77
+ const listed = snapshot.files.filter((file) => file.path.length <= RESULT_LIMITS.pathChars).slice(0, RESULT_LIMITS.files);
78
+ return {
79
+ ref, commit, base_sha: snapshot.base_sha, diff_sha256: diffDigest(snapshot.diff),
80
+ files: listed.map(({ path, status, additions, deletions }) => ({ path, status, additions, deletions })),
81
+ files_count: snapshot.files.length,
82
+ additions: snapshot.files.reduce((n, f) => n + (f.additions ?? 0), 0),
83
+ deletions: snapshot.files.reduce((n, f) => n + (f.deletions ?? 0), 0),
84
+ };
85
+ }
86
+ /**
87
+ * A kept result, for showing it to the room: its commit, the base it starts from (from the commit itself, not from
88
+ * anything the caller says), and the snapshot of base..result as review rooms render it. Null if there is none.
89
+ */
90
+ export async function readResult(repoDir, roomId, requestId) {
91
+ const ref = resultRef(roomId, requestId);
92
+ const commit = (await git(repoDir, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]).catch(() => '')).trim();
93
+ if (!commit)
94
+ return null;
95
+ const base = (await git(repoDir, ['rev-parse', `${commit}^1`])).trim();
96
+ const { snapshot } = await collectReview(repoDir, base, ref);
97
+ return { result: describe(snapshot, ref, commit), snapshot };
98
+ }