fwdloop 0.28.0 → 0.29.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 (56) hide show
  1. package/README.md +1 -1
  2. package/bin/fwdloop +27 -5
  3. package/package.json +3 -3
  4. package/src/ask.js +1 -1
  5. package/src/audit-fold.js +9 -1
  6. package/src/authoring.js +11 -4
  7. package/src/checked.js +5 -2
  8. package/src/checkpick.js +257 -0
  9. package/src/checkwords.js +24 -0
  10. package/src/closers.js +8 -1
  11. package/src/declaration.js +53 -3
  12. package/src/drafter.js +114 -33
  13. package/src/learn.js +1 -1
  14. package/src/learnstore.js +6 -6
  15. package/src/memo.js +120 -0
  16. package/src/model-step.js +89 -17
  17. package/src/pageask.js +9 -6
  18. package/src/pagedropwords.js +9 -0
  19. package/src/panel/author.js +31 -9
  20. package/src/panel/authorcard.js +51 -2
  21. package/src/panel/data.js +12 -7
  22. package/src/panel/index.html +137 -59
  23. package/src/panel/result.js +28 -7
  24. package/src/panel/server.js +2 -1
  25. package/src/pickrecord.js +146 -0
  26. package/src/plain-checks.js +1 -0
  27. package/src/provider.js +4 -1
  28. package/src/runfile.js +4 -2
  29. package/src/runner.js +82 -30
  30. package/src/send.js +71 -4
  31. package/src/setup.js +13 -1
  32. package/types/ask.d.ts +2 -1
  33. package/types/audit-fold.d.ts +13 -2
  34. package/types/authoring.d.ts +6 -2
  35. package/types/checked.d.ts +7 -2
  36. package/types/checkpick.d.ts +149 -0
  37. package/types/checkwords.d.ts +14 -0
  38. package/types/closers.d.ts +2 -1
  39. package/types/declaration.d.ts +9 -0
  40. package/types/drafter.d.ts +12 -25
  41. package/types/learn.d.ts +1 -0
  42. package/types/learnstore.d.ts +2 -3
  43. package/types/memo.d.ts +15 -0
  44. package/types/model-step.d.ts +5 -0
  45. package/types/pageask.d.ts +9 -2
  46. package/types/pagedropwords.d.ts +1 -0
  47. package/types/panel/author.d.ts +1 -1
  48. package/types/panel/authorcard.d.ts +41 -0
  49. package/types/panel/result.d.ts +9 -3
  50. package/types/pickrecord.d.ts +88 -0
  51. package/types/runfile.d.ts +7 -2
  52. package/types/runner.d.ts +16 -5
  53. package/types/send.d.ts +10 -2
  54. package/types/setup.d.ts +1 -56
  55. package/src/attemptdiff.js +0 -118
  56. package/types/attemptdiff.d.ts +0 -38
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The key of every job line: its own words, plus how many lines before it have the same words (equal lines match in their order).
3
+ * @param {{n: number, text: string}[]} lines @returns {Map<number, {lineWords: string, occurrence: number}>}
4
+ */
5
+ export function lineKeys(lines: {
6
+ n: number;
7
+ text: string;
8
+ }[]): Map<number, {
9
+ lineWords: string;
10
+ occurrence: number;
11
+ }>;
12
+ /**
13
+ * The entries for answers just given, numbered on THIS card (the answer redraft's card: its line and rule numbers are the ones the asks carried).
14
+ * @param {{n: number, text: string}[]} lines @param {Rule[]} rules
15
+ * @param {{line: number, rule: number, check?: Record<string, any>|null, added?: string|null, own?: boolean}[]} picks @param {{line: number, rule: number}[]} left
16
+ * @returns {Entry[]}
17
+ */
18
+ export function entriesFromAnswers(lines: {
19
+ n: number;
20
+ text: string;
21
+ }[], rules: Rule[], picks: {
22
+ line: number;
23
+ rule: number;
24
+ check?: Record<string, any> | null;
25
+ added?: string | null;
26
+ own?: boolean;
27
+ }[], left: {
28
+ line: number;
29
+ rule: number;
30
+ }[]): Entry[];
31
+ /**
32
+ * Decide, for the card in hand, which stored picks are kept and which guardrails must be asked.
33
+ * A pick is KEPT when the job line with its words (same order among equal lines) still has its source guardrail with the exact words and, if the pick wrote a `~` line,
34
+ * that line with its exact words too. Otherwise the pick is dropped (never partly kept) and its guardrails are asked: a pair broken on one side is ONE ask, so the
35
+ * partner left on the card is folded (neither asked nor given the old check) - except an EDITED added line (M10 am21): that one is asked (`pairRule` = its source's number) and the source is folded. Pure.
36
+ * @param {Entry[]} entries @param {{n: number, text: string}[]} lines @param {Rule[]} rules every guardrail the call settles
37
+ * @returns {{picks: {line: number, rule: number, check: Record<string, any>|null, added?: string, own?: boolean}[], left: {line: number, rule: number}[],
38
+ * kept: {line: number, rule: number, entry: Entry}[], askRules: (Rule & {pairRule?: number})[]}}
39
+ */
40
+ export function matchRecord(entries: Entry[], lines: {
41
+ n: number;
42
+ text: string;
43
+ }[], rules: Rule[]): {
44
+ picks: {
45
+ line: number;
46
+ rule: number;
47
+ check: Record<string, any> | null;
48
+ added?: string;
49
+ own?: boolean;
50
+ }[];
51
+ left: {
52
+ line: number;
53
+ rule: number;
54
+ }[];
55
+ kept: {
56
+ line: number;
57
+ rule: number;
58
+ entry: Entry;
59
+ }[];
60
+ askRules: (Rule & {
61
+ pairRule?: number;
62
+ })[];
63
+ };
64
+ /**
65
+ * Read a carried record (the folder's file). A missing or unreadable file is no record (a plan from before am17 has none).
66
+ * @param {string} file @returns {Entry[]|null}
67
+ */
68
+ export function readRecordFile(file: string): Entry[] | null;
69
+ /** the record's file, inside a drafting folder only (never a run folder) */
70
+ export const RECORD_FILE: "picks-record.json";
71
+ /** the exact words a kept pick is marked with in the draft log, the Audit and the plan card (M10 am17 (6)) */
72
+ export const KEPT_WORDS: "kept from last draft";
73
+ export function sameWords(a: unknown, b: unknown): boolean;
74
+ export function recordPath(planDir: string): string;
75
+ export type Entry = {
76
+ lineWords: string;
77
+ occurrence: number;
78
+ ruleText: string;
79
+ added: string | null;
80
+ check: Record<string, any> | null;
81
+ own: boolean;
82
+ left: boolean;
83
+ };
84
+ export type Rule = {
85
+ line: number;
86
+ rule: number;
87
+ text: string;
88
+ };
@@ -33,15 +33,20 @@ export function readRunInputs(runDir: string | null): {
33
33
  * M8b item 1: the ONE writer of `run.json`, called once when a fresh run has frozen its inputs (`runFlow`); never over an existing record. `model` is the pick
34
34
  * the run started on (M4d am33; null = the section is left out), `thinking` the job's "Thinking on" box as it was at the start (M4d am25: written for every fresh
35
35
  * run, ticked or not), `inputs` the manifest `freezeInputs` returned. A fresh run always has `thinking` and `inputs`.
36
- * @param {string} runDir @param {{ model: { slot: string, model: string }|null, thinking: boolean, inputs: any[] }} start
36
+ * @param {string} runDir @param {{ model: { slot: string, model: string }|null, thinking: boolean, inputs: any[], rerun?: {decision: 'rerun', words: string, afterStep: string|null}|null }} start
37
37
  */
38
- export function writeRunStart(runDir: string, { model, thinking, inputs }: {
38
+ export function writeRunStart(runDir: string, { model, thinking, inputs, rerun }: {
39
39
  model: {
40
40
  slot: string;
41
41
  model: string;
42
42
  } | null;
43
43
  thinking: boolean;
44
44
  inputs: any[];
45
+ rerun?: {
46
+ decision: "rerun";
47
+ words: string;
48
+ afterStep: string | null;
49
+ } | null;
45
50
  }): void;
46
51
  /** the file's name in the run's folder */
47
52
  export const RUN_FILE: "run.json";
package/types/runner.d.ts CHANGED
@@ -29,13 +29,14 @@ export function readHaltRecord(runDir: string): {
29
29
  missing?: undefined;
30
30
  red?: undefined;
31
31
  };
32
- /** @param {{goal:string, primitives?:string[], reads?:Record<string,any>, gap?:string|null, hints?:string|null}} opts `hints` (M8 am7): the earlier runs' block, text only, for a retry / redo / rerun try */
32
+ /** @param {{goal:string, primitives?:string[], reads?:Record<string,any>, gap?:string|null, hints?:string|null, memo?:string|null}} opts `hints` (M8 am7): the earlier runs' block, text only, for a retry / redo / rerun try; `memo` (M14): what happened so far in this run, text only, every try */
33
33
  export function buildExecutorContext(opts: {
34
34
  goal: string;
35
35
  primitives?: string[];
36
36
  reads?: Record<string, any>;
37
37
  gap?: string | null;
38
38
  hints?: string | null;
39
+ memo?: string | null;
39
40
  }): Readonly<{
40
41
  goal: string;
41
42
  primitives: readonly string[];
@@ -44,6 +45,7 @@ export function buildExecutorContext(opts: {
44
45
  }>;
45
46
  gap: string | null;
46
47
  hints: string | null;
48
+ memo: string | null;
47
49
  }>;
48
50
  /**
49
51
  * @param {unknown} value
@@ -278,13 +280,14 @@ export function runStepRalph({ mcpServer, ...opts }: Parameters<typeof runStepTr
278
280
  * @param {unknown} opts.catalogue - passed straight through to `readFlow`.
279
281
  * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<{ok:boolean, artifact?:unknown, costUsd:number|null, red?:string, transport?:boolean, model?:string, modelMatch?:boolean}>} opts.modelStep
280
282
  * @param {(opts:{question:string, evidence:unknown, runDir:string}) => Promise<{decision:'accept'|'redo'|'rerun'|'timeout'|'park', reason?:string, artifactSha256?:string}>} opts.askStep
281
- * @param {(target:string, filename:string, content:unknown, acceptedSha256?:string|null) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
283
+ * @param {(target:string, filename:string, content:unknown, acceptedSha256?:string|null) => Promise<{ok:boolean, red?:string, bytes?:number, sha256?:string}>} opts.sendStep
282
284
  * @param {Record<string, any>} [opts.primitives] - injected primitive implementations, keyed by catalogue verb.
283
285
  * @param {string[]} [opts.primitiveReds] - `resolvePrimitives`'s own `reds` (e.g. bareguard refusing a symlinked file scope); any entry refuses the run at $0 like an unwired verb, before the run dir exists.
284
286
  * @param {() => string} [opts.clock] - returns the current ISO timestamp; defaults to the wall clock.
285
287
  * @param {string} opts.businessDate - the run's explicit "as of today", never the wall clock.
286
288
  * @param {number} [opts.ceilingUsd] - per-attempt ceiling override; the model's hold from Settings prices (`ceilingCostUsd`); absent = no hold.
287
289
  * @param {{slot: string, model: string}} [opts.runModel] - M4d am33: the model this run started on; recorded once in the run folder (run.json) and kept by every resume/continue.
290
+ * @param {{decision: 'rerun', words: string, afterStep: string|null}} [opts.rerunOf] - M14 am1 item 1: only `resumeRun`'s rerun path passes it; kept in the new run's run.json
288
291
  * @param {string|null} [opts.initialGap] - M3 scope item 7 (rerun as a fresh
289
292
  * run): a human's rerun reason, carried as the FIRST ordinary step's
290
293
  * starting gap. Never used by a plain `runFlow` call outside `resumeRun`'s
@@ -294,7 +297,7 @@ export function runStepRalph({ mcpServer, ...opts }: Parameters<typeof runStepTr
294
297
  * epoch ms; defaults to the wall clock. Mirrors `clock` (ISO) so a test
295
298
  * can advance wall time across a park/resume boundary without a real wait.
296
299
  */
297
- export function runFlow({ root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd, initialGap, fetchPage, runModel, nowMs, }: {
300
+ export function runFlow({ root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd, initialGap, fetchPage, rerunOf, runModel, nowMs, }: {
298
301
  root: string;
299
302
  name: string;
300
303
  runId: string;
@@ -327,6 +330,7 @@ export function runFlow({ root, name, runId, sources, catalogue, modelStep, askS
327
330
  ok: boolean;
328
331
  red?: string;
329
332
  bytes?: number;
333
+ sha256?: string;
330
334
  }>;
331
335
  primitives?: Record<string, any> | undefined;
332
336
  primitiveReds?: string[] | undefined;
@@ -337,6 +341,11 @@ export function runFlow({ root, name, runId, sources, catalogue, modelStep, askS
337
341
  slot: string;
338
342
  model: string;
339
343
  } | undefined;
344
+ rerunOf?: {
345
+ decision: "rerun";
346
+ words: string;
347
+ afterStep: string | null;
348
+ } | undefined;
340
349
  initialGap?: string | null | undefined;
341
350
  fetchPage?: ((url: string) => Promise<{
342
351
  ok: true;
@@ -372,7 +381,7 @@ export function makeParkingAskStep(): (opts?: any) => Promise<{
372
381
  * @param {string} opts.runId
373
382
  * @param {unknown} opts.catalogue
374
383
  * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<any>} opts.modelStep
375
- * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
384
+ * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number, sha256?:string}>} opts.sendStep
376
385
  * @param {Record<string, any>} [opts.primitives]
377
386
  * @param {string[]} [opts.primitiveReds] - see `runFlow`'s own.
378
387
  * @param {() => string} [opts.clock]
@@ -394,6 +403,7 @@ export function resumeRun({ root, name, runId, catalogue, modelStep, sendStep, p
394
403
  ok: boolean;
395
404
  red?: string;
396
405
  bytes?: number;
406
+ sha256?: string;
397
407
  }>;
398
408
  primitives?: Record<string, any> | undefined;
399
409
  primitiveReds?: string[] | undefined;
@@ -436,7 +446,7 @@ export function auditSpend(runDir: string): {
436
446
  * @param {string} opts.runId
437
447
  * @param {unknown} opts.catalogue
438
448
  * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<any>} opts.modelStep
439
- * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
449
+ * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number, sha256?:string}>} opts.sendStep
440
450
  * @param {Record<string, any>} [opts.primitives]
441
451
  * @param {string[]} [opts.primitiveReds]
442
452
  * @param {() => string} [opts.clock]
@@ -456,6 +466,7 @@ export function continueRun({ root, name, runId, catalogue, modelStep, sendStep,
456
466
  ok: boolean;
457
467
  red?: string;
458
468
  bytes?: number;
469
+ sha256?: string;
459
470
  }>;
460
471
  primitives?: Record<string, any> | undefined;
461
472
  primitiveReds?: string[] | undefined;
package/types/send.d.ts CHANGED
@@ -1,12 +1,19 @@
1
+ /**
2
+ * M15 items 3 and am1, am2: the accepted answer as the plain-text file the send writes. `{text}` alone is the text exactly; any other flat object is one
3
+ * `Name words: value` line per field; a list of results is one `## Result k` block per result with one line per value, in the order the answer holds
4
+ * them, then `from the page: "<quote>"`. Never JSON braces, never check marks. What it throws away: a result's keys other than `quote` and `values`.
5
+ * @param {Record<string, any>} content @returns {string}
6
+ */
7
+ export function renderSentMd(content: Record<string, any>): string;
1
8
  /**
2
9
  * @param {string} target - a signed arbiter target, e.g. `file:poc/m0/out`.
3
10
  * @param {string} filename
4
- * @param {unknown} content - JSON-serialised before writing.
11
+ * @param {unknown} content - the accepted artifact; hash-checked as its JSON, written as plain text (`renderSentMd`).
5
12
  * @param {string|null} [acceptedSha256] - the sha256 the human's accept recorded
6
13
  * (`answerAsk`, M4b piece 3). Required: none recorded (an answer written by an
7
14
  * older version, or no accept in this process) refuses by name.
8
15
  * @param {{root?: string, runDir?: string}} [ctx] the flow root and this run's folder, for the destination refusals
9
- * @returns {Promise<{ok:true, path:string, bytes:number} | {ok:false, red:string}>}
16
+ * @returns {Promise<{ok:true, path:string, bytes:number, sha256:string} | {ok:false, red:string}>}
10
17
  */
11
18
  export function sendViaPrimitive(target: string, filename: string, content: unknown, acceptedSha256?: string | null, ctx?: {
12
19
  root?: string;
@@ -15,6 +22,7 @@ export function sendViaPrimitive(target: string, filename: string, content: unkn
15
22
  ok: true;
16
23
  path: string;
17
24
  bytes: number;
25
+ sha256: string;
18
26
  } | {
19
27
  ok: false;
20
28
  red: string;
package/types/setup.d.ts CHANGED
@@ -10,62 +10,7 @@ export function buildSetupRows({ sessionDir, planDir, hash, signedBy, signedAt,
10
10
  signedBy: string;
11
11
  signedAt: string;
12
12
  flowHash?: string;
13
- }): ({
14
- tries?: {
15
- label: string;
16
- passed: boolean;
17
- reds: string[];
18
- outcome: string;
19
- rawOutcome: string;
20
- again: boolean;
21
- }[] | undefined;
22
- kind: any;
23
- n: any;
24
- at: any;
25
- model: any;
26
- costUsd: any;
27
- spendComplete: boolean;
28
- calls: any;
29
- wallMs: any;
30
- structureRetries: any;
31
- verdict: string;
32
- hash: string | null;
33
- gap: string | null;
34
- } | {
35
- kind: string;
36
- n: number;
37
- at: string | null;
38
- source: string;
39
- ask: string | undefined;
40
- question: string;
41
- answer: string | null;
42
- line: number;
43
- ruleNo: number | undefined;
44
- ruleText: string | undefined;
45
- proposal: string | null;
46
- rule: string | null;
47
- } | {
48
- kind: string;
49
- n: number;
50
- at: string | null;
51
- card: any;
52
- signedBy?: undefined;
53
- hash?: undefined;
54
- flowHash?: undefined;
55
- notChecked?: undefined;
56
- } | {
57
- kind: string;
58
- n: number;
59
- at: string;
60
- signedBy: string;
61
- hash: string;
62
- flowHash: string | null;
63
- notChecked: {
64
- label: string;
65
- items: any[];
66
- };
67
- card?: undefined;
68
- })[];
13
+ }): any[];
69
14
  /**
70
15
  * Write `<flowDir>/setup.jsonl` ONCE ('wx': a second write is refused, never merged or replaced), mode 0600, every row scrubbed of the
71
16
  * given key values. Never throws.
@@ -1,118 +0,0 @@
1
- // borrowed-from: bareloop src/attemptdiff.js@v0.46.0 (8b3d815)
2
- // Adaptations: redactSecrets imported from ./redact.js (fwdloop's one secret inventory) in place of bareloop's ./validate.js; the temp index dir prefix is fwdloop-adiff-. Nothing else changed.
3
- // attempt-diff — what each worker TRY changed, as a spine record (ITEM33 addendum
4
- // 2026-10-22). The spine and the gate audit keep only file names and byte sizes of
5
- // edits; a learnings card could say WHICH files a passing try touched but never WHAT
6
- // changed. This module is the ONE owner of that capture. It is a record, never a
7
- // verdict: every failure is caught and returned as a field, nothing here throws.
8
- //
9
- // How: a git TREE snapshot at try start and at try end, each through a TEMPORARY
10
- // index (GIT_INDEX_FILE + `git add -A` + `git write-tree`), then `git diff <t0> <t1>`.
11
- // The work branch, HEAD, the real index and the stash list are never touched; the
12
- // temp index is removed. Only unreferenced loose objects are left in the object store.
13
-
14
- import { execFile } from 'node:child_process';
15
- import { promisify } from 'node:util';
16
- import { mkdtemp, rm } from 'node:fs/promises';
17
- import { tmpdir } from 'node:os';
18
- import { existsSync } from 'node:fs';
19
- import { join, relative, resolve } from 'node:path';
20
- import { redactSecrets } from './redact.js';
21
-
22
- const exec = promisify(execFile);
23
-
24
- /** per-file and per-event byte caps for the recorded diff text */
25
- export const ATTEMPT_DIFF_FILE_MAX = 4096;
26
- export const ATTEMPT_DIFF_EVENT_MAX = 16384;
27
-
28
- /**
29
- * Cut `text` to at most `max` bytes at a LINE boundary (never mid-line).
30
- * @param {string} text @param {number} max
31
- * @returns {{text: string, truncated: boolean, cutLines: number}}
32
- */
33
- export function cutAtLine(text, max) {
34
- if (Buffer.byteLength(text) <= max) return { text, truncated: false, cutLines: 0 };
35
- const lines = text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
36
- let used = 0;
37
- let kept = 0;
38
- for (const l of lines) {
39
- const b = Buffer.byteLength(l);
40
- if (used + b > max) break;
41
- used += b;
42
- kept++;
43
- }
44
- return { text: lines.slice(0, kept).join(''), truncated: true, cutLines: lines.length - kept };
45
- }
46
-
47
- /** @param {string} abs @param {string[]} prefixes */
48
- const inFence = (abs, prefixes) => prefixes.some((p) => abs === p || abs.startsWith(p.endsWith('/') ? p : `${p}/`));
49
-
50
- // the arbiter's books and installed packages never enter a snapshot, even inside a wide fence
51
- const NOT_WORK = [':(exclude,glob)**/node_modules/**', ':(exclude,glob)**/.git/**', ':(exclude).smoke', ':(exclude).litectx', ':(exclude)gate-audit.jsonl'];
52
-
53
- /**
54
- * Snapshot the FENCE of the working tree to a git tree id via a throwaway index. Only the
55
- * fence's existing prefixes are added, and with `-f`: a rubric job's `output/` must be seen
56
- * even when the source folder's own .gitignore lists it (the hidden-git seed ignores that
57
- * file's meaning; so does this).
58
- * @param {string} workdir @param {string[]} fence @returns {Promise<string>}
59
- */
60
- async function snapshotTree(workdir, fence) {
61
- const tmp = await mkdtemp(join(tmpdir(), 'fwdloop-adiff-'));
62
- try {
63
- const env = { ...process.env, GIT_INDEX_FILE: join(tmp, 'index') };
64
- const specs = fence.filter((p) => existsSync(p)).map((p) => `:(literal)${relative(workdir, p) || '.'}`);
65
- if (specs.length > 0) await exec('git', ['add', '-A', '-f', '--', ...specs, ...NOT_WORK], { cwd: workdir, env, maxBuffer: 1 << 26 });
66
- const { stdout } = await exec('git', ['write-tree'], { cwd: workdir, env });
67
- return stdout.trim();
68
- } finally {
69
- await rm(tmp, { recursive: true, force: true });
70
- }
71
- }
72
-
73
- /**
74
- * Begin recording one worker try. Call BEFORE the worker's turn; call `finish()` after
75
- * (in a `finally`). Never throws.
76
- * @param {{workdir: string, fence: string[], redact?: (s: string) => string}} o
77
- * `fence` = the ABSOLUTE write-scope prefixes the gate enforces for this try.
78
- * @returns {Promise<{finish: () => Promise<null | {files: {path: string, diff: string, truncated: boolean, cutLines: number}[], binary: string[], truncated: boolean, gitError?: string}>}>}
79
- * `finish()` resolves null when the try changed nothing in scope.
80
- */
81
- export async function startAttemptDiff({ workdir, fence, redact = redactSecrets }) {
82
- /** @type {string|null} */
83
- let t0 = null;
84
- /** @type {string|null} */
85
- let startError = null;
86
- try { t0 = await snapshotTree(workdir, fence); } catch (e) { startError = String(/** @type {any} */ (e)?.message ?? e); }
87
- return {
88
- async finish() {
89
- try {
90
- if (t0 === null) throw new Error(`start snapshot failed: ${startError}`);
91
- const t1 = await snapshotTree(workdir, fence);
92
- if (t1 === t0) return null;
93
- const g = (/** @type {string[]} */ a) => exec('git', ['-c', 'core.quotepath=false', ...a], { cwd: workdir, maxBuffer: 1 << 26 });
94
- const { stdout: names } = await g(['diff', '--name-only', '-z', '--relative', /** @type {string} */ (t0), t1]);
95
- const paths = names.split('\0').filter(Boolean).filter((p) => inFence(resolve(workdir, p), fence));
96
- /** @type {{path: string, diff: string, truncated: boolean, cutLines: number}[]} */
97
- const files = [];
98
- /** @type {string[]} */
99
- const binary = [];
100
- let left = ATTEMPT_DIFF_EVENT_MAX;
101
- let anyCut = false;
102
- for (const p of paths) {
103
- const { stdout } = await g(['diff', '-U1', '--no-color', '--no-ext-diff', '--relative', /** @type {string} */ (t0), t1, '--', `:(literal)${p}`]);
104
- const path = redact(p);
105
- if (/^Binary files .* differ$/m.test(stdout) || /^GIT binary patch$/m.test(stdout)) { binary.push(path); continue; }
106
- const cut = cutAtLine(redact(stdout), Math.min(ATTEMPT_DIFF_FILE_MAX, left));
107
- left -= Buffer.byteLength(cut.text);
108
- if (cut.truncated) anyCut = true;
109
- files.push({ path, diff: cut.text, truncated: cut.truncated, cutLines: cut.cutLines });
110
- }
111
- if (files.length === 0 && binary.length === 0) return null;
112
- return { files, binary, truncated: anyCut };
113
- } catch (e) {
114
- return { files: [], binary: [], truncated: false, gitError: redact(String(/** @type {any} */ (e)?.message ?? e)).slice(0, 500) };
115
- }
116
- },
117
- };
118
- }
@@ -1,38 +0,0 @@
1
- /**
2
- * Cut `text` to at most `max` bytes at a LINE boundary (never mid-line).
3
- * @param {string} text @param {number} max
4
- * @returns {{text: string, truncated: boolean, cutLines: number}}
5
- */
6
- export function cutAtLine(text: string, max: number): {
7
- text: string;
8
- truncated: boolean;
9
- cutLines: number;
10
- };
11
- /**
12
- * Begin recording one worker try. Call BEFORE the worker's turn; call `finish()` after
13
- * (in a `finally`). Never throws.
14
- * @param {{workdir: string, fence: string[], redact?: (s: string) => string}} o
15
- * `fence` = the ABSOLUTE write-scope prefixes the gate enforces for this try.
16
- * @returns {Promise<{finish: () => Promise<null | {files: {path: string, diff: string, truncated: boolean, cutLines: number}[], binary: string[], truncated: boolean, gitError?: string}>}>}
17
- * `finish()` resolves null when the try changed nothing in scope.
18
- */
19
- export function startAttemptDiff({ workdir, fence, redact }: {
20
- workdir: string;
21
- fence: string[];
22
- redact?: (s: string) => string;
23
- }): Promise<{
24
- finish: () => Promise<null | {
25
- files: {
26
- path: string;
27
- diff: string;
28
- truncated: boolean;
29
- cutLines: number;
30
- }[];
31
- binary: string[];
32
- truncated: boolean;
33
- gitError?: string;
34
- }>;
35
- }>;
36
- /** per-file and per-event byte caps for the recorded diff text */
37
- export const ATTEMPT_DIFF_FILE_MAX: 4096;
38
- export const ATTEMPT_DIFF_EVENT_MAX: 16384;