bareloop 0.51.0 → 0.53.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.
@@ -1860,7 +1860,7 @@ function getRunDetailBody(runid, opts) {
1860
1860
  // tabs still never disagree about order/counts/blocked-call figures.
1861
1861
  // a run that DIED (no job-end, runner gone — `death`, decided once above) leaves its last part in flight: that part reads
1862
1862
  // `died`, never the "happened, so passed" default. Replay alone cannot tell died from still running, so the verdict lives here.
1863
- parts: (draftingPartHere && Array.isArray(enrichedParts) ? [draftingPartHere, ...enrichedParts] : enrichedParts)?.map((p, i, all) => ({ ...p, status: partStatusFor(death.died && i === all.length - 1 && p.kind !== 'drafting' && p.outcome == null && !p.stopReason ? { ...p, stopReason: 'died' } : p) })),
1863
+ parts: (draftingPartHere && Array.isArray(enrichedParts) ? [draftingPartHere, ...enrichedParts] : enrichedParts)?.map((p, i, all) => ({ ...(death.died && i === all.length - 1 ? diedFixTry(p) : p), status: partStatusFor(death.died && i === all.length - 1 && p.kind !== 'drafting' && p.outcome == null && !p.stopReason ? { ...p, stopReason: 'died' } : p) })),
1864
1864
  replans: summary.replans,
1865
1865
  close: summary.close,
1866
1866
  branch: summary.branch,
@@ -2364,7 +2364,10 @@ export function getRunRounds(runid, query = {}, opts = {}) {
2364
2364
  if (query.all === true && part.kind === 'step' && Array.isArray(part.attempts) && part.attempts.some((x) => Array.isArray(x.checks))) {
2365
2365
  return stepRoundsPage(runid, row, part, { partIndex, offset, limit: Number.isInteger(query.limit) && /** @type {number} */ (query.limit) > 0 ? Math.min(/** @type {number} */ (query.limit), ROUNDS_PAGE_MAX) : STEP_ROWS_PAGE }, opts);
2366
2366
  }
2367
- const a = Array.isArray(part.attempts) ? part.attempts[attempt - 1] : null;
2367
+ // a step's cut-off try ran no check, so it is no attempt: its window is the one after the last graded try (the Audit grid folds its rounds too)
2368
+ const graded = Array.isArray(part.attempts) ? part.attempts[attempt - 1] : null;
2369
+ const a = graded
2370
+ ?? (part.kind === 'step' && part.cutOffTry && part.cutOffTry.n === attempt ? { ...part.cutOffTry, outcome: null, verdict: null, stages: null, detail: null } : null);
2368
2371
  if (!a) return null;
2369
2372
  /** @type {{startSeq: number, endSeq: number, outcome: string|null, detail: string|null}} */
2370
2373
  const window = {
@@ -2420,7 +2423,7 @@ export function getRunRounds(runid, query = {}, opts = {}) {
2420
2423
  totalRounds,
2421
2424
  offset,
2422
2425
  limit,
2423
- check: { outcome: window.outcome, detail: window.detail },
2426
+ check: graded ? { outcome: window.outcome, detail: window.detail } : null,
2424
2427
  toolLogSaved,
2425
2428
  };
2426
2429
  }
@@ -2717,6 +2720,7 @@ function enrichPartsWithStageKind(parts, kindMeta, spec = null) {
2717
2720
  const checks = Array.isArray(a.checks) ? tryChecksOf(a.checks, kindMeta, spec) : null;
2718
2721
  return {
2719
2722
  ...a,
2723
+ ...(part.kind === 'fix' ? fixTryWords(a) : {}),
2720
2724
  ...(checks ? { checks, judged: (Array.isArray(a.outputJudged) ? a.outputJudged : []).map(judgedFileLine), stages: checks.map(stageOfCheck) } : { stages: (kindMeta && Array.isArray(a.stages)) ? a.stages.map((s) => attachStageKind(s, kindMeta)) : a.stages }),
2721
2725
  ...(declaredStagesTotal ? { declaredStagesTotal } : {}),
2722
2726
  ...(declaredStages ? { declaredStages } : {}),
@@ -2734,6 +2738,46 @@ function enrichPartsWithStageKind(parts, kindMeta, spec = null) {
2734
2738
  /** the words for a try the wall (or a cap, or a stop) ended before any of its checks ran (D2) */
2735
2739
  const CUT_OFF_WORDS = 'cut off before its checks ran';
2736
2740
 
2741
+ /** the words for a try no check ran in and that the person stopped, or that died (the Audit grid's "?" row) */
2742
+ const STOPPED_WORDS = 'you stopped it, no check ran';
2743
+ const DIED_WORDS = 'died, no check ran';
2744
+
2745
+ /**
2746
+ * The Audit grid's "?" row words for a fix try that ended with no verdict (`attempt.stop`, src/replay.js): ONE table, code-owned.
2747
+ * A provider drop names its own cause; a stop by the person says so; anything else a try can end on without a close (a cap, the wall) reads
2748
+ * the same words a cut-off step try does.
2749
+ * @param {{by: string, what: string|null, detail: string|null}} stop
2750
+ * @returns {string}
2751
+ */
2752
+ function noVerdictWords(stop) {
2753
+ if (stop.what === 'provider-red') return stop.detail ? `provider dropped (${stop.detail}), no check ran` : 'provider dropped, no check ran';
2754
+ if (stop.by === 'run-end' && stop.what === 'stopped') return STOPPED_WORDS;
2755
+ return CUT_OFF_WORDS;
2756
+ }
2757
+
2758
+ /** a died run's fix part: its last try never got a verdict (the Audit grid's "?" row says it died) @param {any} part */
2759
+ function diedFixTry(part) {
2760
+ if (part.kind !== 'fix' || !Array.isArray(part.attempts) || part.attempts.length === 0) return part;
2761
+ const last = part.attempts[part.attempts.length - 1];
2762
+ if (last.outcome != null) return part;
2763
+ return { ...part, attempts: [...part.attempts.slice(0, -1), { ...last, noVerdict: DIED_WORDS }] };
2764
+ }
2765
+
2766
+ /**
2767
+ * A fix try's failing-check lines and its no-verdict words, worded for the page. The spine's gap lines each open with `close: `, the first also with
2768
+ * the failing stage's own name (`close: <stage>: `): those are cut and nothing else, so a file path stays (a step's {@link reasonsOf} cuts more, and
2769
+ * is untouched).
2770
+ * @param {any} a a fix attempt (src/replay.js)
2771
+ * @returns {{reasons: string[], noVerdict?: string}}
2772
+ */
2773
+ function fixTryWords(a) {
2774
+ const lines = Array.isArray(a.reasons) ? a.reasons : [];
2775
+ const failing = Array.isArray(a.stages) ? a.stages.find((/** @type {any} */ st) => st && st.verdict !== 'satisfied') : null;
2776
+ const stageHead = failing && typeof failing.name === 'string' ? `close: ${failing.name}: ` : null;
2777
+ const reasons = lines.map((/** @type {string} */ l) => (stageHead && l.startsWith(stageHead) ? l.slice(stageHead.length) : l.replace(/^close:\s*/, '')));
2778
+ return { reasons, ...(a.stop ? { noVerdict: noVerdictWords(a.stop) } : {}) };
2779
+ }
2780
+
2737
2781
  /**
2738
2782
  * "71 model · 91 tool · 0 denied" — the Run summary's `calls:` row (PRD v1.106 Part 5 F). Model calls are the run's own spend records
2739
2783
  * (`worker-round`, `judge-round`; the attempt-level `worker-result` echoes are not rounds and drafting is not the run's), tool and denied come
package/src/planrun.js CHANGED
@@ -35,10 +35,11 @@ import { createStallWatch, STALL_MS, MAX_STALLS } from './stall.js';
35
35
  import { createLadder, STRIKE_LIMIT } from './ladder.js';
36
36
  import { createTrend, FIX_STRIKE_LIMIT } from './trend.js';
37
37
  import { TOOL_MENU, STORE_VERBS, checkMenu } from './job.js';
38
- import { TOOL_BY_VERB, CTX_TOOLS, createCtxTools, toolAction, PERSONA_TOOLS, strategyFor } from './tools.js';
38
+ import { TOOL_BY_VERB, CTX_TOOLS, createCtxTools, toolAction, gatedShellOptions, PERSONA_TOOLS, strategyFor } from './tools.js';
39
39
  import { anySuppressionWarning } from './authoring.js';
40
40
  import { createReadShim, readShimArm, readShimStrategy } from './readshim.js';
41
- import { createHandoffStore, trackReads } from './handoff.js';
41
+ import { createCarryStore } from './carrystore.js';
42
+ import { buildSeedNote } from './seednote.js';
42
43
  import { globToPrefix, redactSecrets, SECRET_PATTERNS } from './validate.js';
43
44
  import { startAttemptDiff } from './attemptdiff.js';
44
45
  import { validateBridge, loadGate, newestEligibleVersion, reuseEligibility, quarantinesCredit, QUARANTINED_CODE } from './bridges.js';
@@ -351,6 +352,12 @@ function hintsBlock(text) {
351
352
  return `\n${text}\n`;
352
353
  }
353
354
 
355
+ /** The seed note (src/seednote.js), verbatim, in the planner's first-draft prompt; absent or empty renders '' (byte-identical to the prompt without it). */
356
+ function seedNoteBlock(text) {
357
+ if (typeof text !== 'string' || !text.trim()) return '';
358
+ return `\n${text}\n`;
359
+ }
360
+
354
361
  /**
355
362
  * MODULE 8 — the signer's words, when this leg is a RERUN taken at a previous run's
356
363
  * review door (PRD v1.71 §3.4: *"redo/rerun comes with new authoring"*).
@@ -647,8 +654,9 @@ export function boundedNote(bounded, rounds) {
647
654
  * byte-identically to the pre-shim prompt.
648
655
  * @param {string|null} [hints] the cross-run learnings block (src/learn.js `renderHints`), verbatim; null/empty
649
656
  * renders byte-identically to the prompt without it. Only ever passed for the draft and the first replan.
657
+ * @param {string|null} [seedNote] the seed note (src/seednote.js), verbatim, after the hints; null/empty renders byte-identically to the prompt without it. First draft only.
650
658
  */
651
- export function planPrompt(job, scoutBlob, reds, maxStepRounds, failure, scopes, materials, startingDraft = null, checkFacts = {}, doorNote = null, readShim = false, hints = null) {
659
+ export function planPrompt(job, scoutBlob, reds, maxStepRounds, failure, scopes, materials, startingDraft = null, checkFacts = {}, doorNote = null, readShim = false, hints = null, seedNote = null) {
652
660
  const scopeMenu = Array.isArray(scopes) && scopes.length ? scopes : legalScopes(job.writeScope ?? []);
653
661
  const ceiling = Array.isArray(job.tools) ? job.tools : [...TOOL_MENU];
654
662
  // The shape-lottery laws, stated where the check menu is offered (the mailbox
@@ -739,7 +747,7 @@ ${scopeMenu.map((s) => ` ${JSON.stringify(s)}`).join('\n')}
739
747
 
740
748
  Goal:
741
749
  ${job.goal}
742
- ${doorNoteBlock(doorNote)}${materialsBlock(materials)}${hintsBlock(hints)}
750
+ ${doorNoteBlock(doorNote)}${materialsBlock(materials)}${hintsBlock(hints)}${seedNoteBlock(seedNote)}
743
751
  Repository survey (from a read-only scout):
744
752
  ${scoutBlob || '(no scout notes)'}`;
745
753
  let p = doc;
@@ -1024,10 +1032,17 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
1024
1032
  // would be wrong and would look fine). Only the guard runs here; the flag itself
1025
1033
  // is still threaded onward as written.
1026
1034
  readShimArm(readShim);
1027
- // THE HANDOFF NOTE (src/handoff.js): the paths earlier asks of THIS run read. In memory only, so a resumed leg starts empty.
1028
- // The switch is the signed spec's `handoffNote` (absent = on, only `false` turns it off).
1029
- const handoffOn = job.handoffNote !== false;
1030
- const handoff = createHandoffStore({ workdir });
1035
+ // THE SEED NOTE (src/seednote.js): the signed spec's `seedNote`; absent = ON, only `false` turns it off (like the legacy `handoffNote`).
1036
+ const seedNoteOn = job.seedNote !== false;
1037
+ // THE FIRST-READ MAP (src/readshim.js, EXPERIMENTAL): the signed spec's `readMap`; absent = OFF, only `true` turns it on. Needs the read shim on and `ctx_get` in the worker's grant.
1038
+ const readMapOn = job.readMap === true;
1039
+ if (readMapOn && !readShimArm(readShim).on) emit('read-map-skip', { reason: 'shim-off' });
1040
+ /** @type {{ text: string, body: string, stages: string[] }|null} built once, after the preflight loop */
1041
+ let seedNote = null;
1042
+ // THE CARRY NOTE (src/carrynote.js, src/carrystore.js): facts the earlier asks of THIS run produced, files read with their function
1043
+ // line ranges included (the old separate handoff note is folded in). ALWAYS ON, no switch (hamr 2026-11-01); a legacy spec's
1044
+ // `handoffNote` and the retired `carryNote` config key have no effect. One `carry-note` spine record (counts only) per note handed.
1045
+ const carry = createCarryStore({ workdir, emit, strikeLimit, resume: resumeBranch !== null && resumeBranch !== undefined });
1031
1046
  // The scout switch's guard, same class and same door: a mis-typed value
1032
1047
  // coerced by truthiness would run the scout under an "off" label (or skip it
1033
1048
  // under an "on" one) and no reading of the results afterwards could recover
@@ -2044,6 +2059,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2044
2059
  ? 'returned to the branch this run was killed on — its work is on this branch, and a fresh one would strand it'
2045
2060
  : 'the HARD RULE (PRD v1.57 §3): the run works here, never on the branch it was handed and never on main',
2046
2061
  });
2062
+ carry?.setBase(wb.base);
2047
2063
  return null;
2048
2064
  };
2049
2065
  if (resuming) {
@@ -2155,6 +2171,10 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2155
2171
  * is still the goal the plan exists to flip).
2156
2172
  * @type {string[]} */
2157
2173
  const seedRed = [];
2174
+ // THE SEED NOTE (experimental, default off): the red-at-seed verdicts, with their stage's declared kind, for src/seednote.js.
2175
+ // The kind is read off the signed close's own stage (a command close has none), never matched on a stage name.
2176
+ /** @type {{stage: string|null|undefined, kind: string|null|undefined, gap: string|null|undefined}[]} */
2177
+ const seedReds = [];
2158
2178
  emit('check-menu', {
2159
2179
  offered: menu.map((m) => m.name),
2160
2180
  ...(menu.length < stagedClose.length
@@ -2165,6 +2185,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2165
2185
  const v = await runCloseStages(m.run);
2166
2186
  if (v.verdict === 'needs_revision') {
2167
2187
  seedRed.push(m.name);
2188
+ if (seedNoteOn) seedReds.push({ stage: v.stage, kind: stagedClose.find((/** @type {any} */ s2) => s2?.name === v.stage)?.kind, gap: v.gap });
2168
2189
  // …and the preflight grade is a READING, for the same reason the precheck one
2169
2190
  // above is: it is the seed the run's work is measured against. The precheck
2170
2191
  // only ever reds at the close's FIRST failing stage (first-red-wins), so on
@@ -2190,6 +2211,10 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2190
2211
  }
2191
2212
  }
2192
2213
 
2214
+ if (seedNoteOn) seedNote = buildSeedNote(seedReds, scrub);
2215
+ // every step/fix worker gets it through the carry memo (earlier failures, `at start`); the planner has its own block
2216
+ if (seedNote) carry?.setStartFailure(seedNote.body);
2217
+
2193
2218
  // ── 0c, COLD. The seam and both halves of its placement ruling are stated
2194
2219
  // above, where a RESUME reaches it; this is where a run that is NOT resuming
2195
2220
  // does — after the $0 precheck and preflight, so an already-green tree has
@@ -2495,7 +2520,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2495
2520
  }
2496
2521
  };
2497
2522
  const grantedNames = new Set(granted.map((v) => /** @type {Record<string, string>} */ (TOOL_BY_VERB)[v]));
2498
- const shell = createShellTools().tools.filter((/** @type {{name: string}} */ t) => grantedNames.has(t.name));
2523
+ const shell = createShellTools(gatedShellOptions(gate, workdir)).tools.filter((/** @type {{name: string}} */ t) => grantedNames.has(t.name));
2499
2524
  // THE READ SHIM (arm-gated, default OFF): a per-worker delivery ledger over the
2500
2525
  // read tool — cap at READ_SHIM_CAP, pointer only once the CURRENT content has been
2501
2526
  // delivered whole, next-unseen-slice otherwise, diff on a changed re-read. WHICH of
@@ -2529,6 +2554,8 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2529
2554
  else memoryCacheCounts.capped++;
2530
2555
  memoryCacheCounts.bytesWithheld += bytes;
2531
2556
  },
2557
+ // The first-read map (experimental, off unless the spec says `readMap: true`): this worker's index, and whether it holds ctx_get.
2558
+ readMap: readMapOn ? { root: workdir, hasGet: grantedNames.has(TOOL_BY_VERB.get), getNode: (/** @type {string} */ rel) => lc.getNode(rel), refresh: () => lc.index({ yield: true }), emit: emitCtx } : null,
2532
2559
  });
2533
2560
  const rdTool = shell.find((/** @type {{name: string}} */ t) => t.name === TOOL_BY_VERB.read);
2534
2561
  // F48: on native, bound shell_read below the CLI's tool-result display cap and hand back a
@@ -2571,27 +2598,18 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2571
2598
  // sampler all live here) for its full duration: measured 4.4s at 4.5% liveness on a
2572
2599
  // 155-file force pass. With yield:true the worst single block measured 189–252ms (n=4),
2573
2600
  // below anything a second/minute-scale timer can perceive. Store output is byte-identical.
2574
- if (ctx.length) await lc.index({ yield: true });
2601
+ // …and with the first-read map on the index is built at run start too, so the map never waits on a ctx tool being granted.
2602
+ if (ctx.length || readMapOn) await lc.index({ yield: true });
2575
2603
  const toolDefs = [...shell, ...ctx];
2576
- // The handoff note: record what each ask READS (the allowed read-class calls), hand the next step/fix ask the map.
2577
- // Scout and drafter asks feed the store but are never given a note.
2578
- /** @type {Set<string>} */
2579
- let askReads = new Set();
2580
- if (handoffOn) trackReads(toolDefs, [TOOL_BY_VERB.read, TOOL_BY_VERB.get], (a) => askReads.add(a), workdir);
2604
+ // The carry note: records what each ask's read-class tools returned (a summary, never content) and hands the next
2605
+ // step/fix ask the facts. Scout and drafter asks feed the store but are never given a note.
2606
+ if (carry) carry.wrapTools(toolDefs);
2581
2607
  /** @param {(prompt: string, defs?: any) => Promise<any>} inner */
2582
- const withHandoff = (inner) => (!handoffOn ? inner : async (/** @type {string} */ prompt, /** @type {any} */ defs) => {
2583
- askReads = new Set();
2584
- let p = prompt;
2585
- if (phase === 'fix' || phase.startsWith('step:')) {
2586
- // The index is incremental: refreshing it here is what keeps the symbol ranges true to the files as they now are.
2587
- try { if (ctx.length) await lc.index({ yield: true }); } catch { /* the map falls back to line counts */ }
2588
- const note = handoff.render({ getNode: (rel) => lc.getNode(rel) });
2589
- if (note.text) {
2590
- p = `${prompt}\n\n${note.text}`;
2591
- emit('handoff-note', { phase, iteration: roundIteration, chars: note.text.length, paths: note.paths });
2592
- }
2593
- }
2594
- try { return await inner(p, defs); } finally { handoff.absorb(askReads); }
2608
+ const withCarry = (inner) => (!carry ? inner : async (/** @type {string} */ prompt, /** @type {any} */ defs) => {
2609
+ // The index is incremental: refreshing it here keeps the function ranges true to the files as they now are.
2610
+ if (phase === 'fix' || phase.startsWith('step:')) { try { if (ctx.length) await lc.index({ yield: true }); } catch { /* ranges are left out */ } }
2611
+ const text = await carry.beginAsk({ phase, iteration: roundIteration, prompt, getNode: (rel) => lc.getNode(rel) });
2612
+ try { return await inner(text ? `${prompt}\n\n${text}` : prompt, defs); } finally { carry.endAsk({ bounded: attemptBounded, iteration: roundIteration, rounds: attemptRounds }); }
2595
2613
  });
2596
2614
  // F19 per VERB (P, corrected 2026-07-31): a strategy SENTENCE rides only with
2597
2615
  // the verb it names. Gating per COMPONENT was close but over-reached — a
@@ -2690,7 +2708,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2690
2708
  }
2691
2709
  return r;
2692
2710
  };
2693
- return { ask: withHandoff(ask), askFrom, workerWrites, writeCount, setIteration, wasBounded: () => attemptBounded };
2711
+ return { ask: withCarry(ask), askFrom, workerWrites, writeCount, setIteration, wasBounded: () => attemptBounded };
2694
2712
  }
2695
2713
 
2696
2714
  // ── LOOP path: the injected provider (anthropic-api and every other
@@ -2964,7 +2982,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2964
2982
  }
2965
2983
  return r;
2966
2984
  };
2967
- return { ask: withHandoff(ask), askFrom, workerWrites, writeCount, setIteration, wasBounded: () => attemptBounded };
2985
+ return { ask: withCarry(ask), askFrom, workerWrites, writeCount, setIteration, wasBounded: () => attemptBounded };
2968
2986
  }
2969
2987
 
2970
2988
  /** relay a throw from OUTSIDE ralph (scout/plan drafting/fix) as its honest
@@ -3121,6 +3139,9 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
3121
3139
  // handed (a record, never a verdict), so the Audit can show it and the byte check can compare it with a fresh render.
3122
3140
  const hints = learnHints && learnHints.text && (phase === 'draft' || (phase === 'replan' && replans === 1)) ? learnHints : null;
3123
3141
  if (hints) emit('learnings', { phase, text: hints.text, ids: hints.ids, chars: hints.text.length });
3142
+ // The seed note: the planner's FIRST draft only (and its redrafts). A record of counts and names, never the text.
3143
+ const seedNoteForPlanner = seedNote && phase === 'draft' ? seedNote : null;
3144
+ if (seedNoteForPlanner) emit('seed-note', { to: 'planner', chars: seedNoteForPlanner.text.length, stages: seedNoteForPlanner.stages });
3124
3145
  // D5 — the bridge rides into the FIRST draft phase ONLY. A replan drafts from the
3125
3146
  // RUN'S OWN STATE (what failed, what is left): re-handing the recipe there would
3126
3147
  // answer the replan's question with the material the run just demonstrated does not
@@ -3145,7 +3166,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
3145
3166
  const draftPlan = async (/** @type {any[]|null} */ reds) => {
3146
3167
  drafter.setIteration(reds ? 'redraft' : 'draft');
3147
3168
  replanCut = false;
3148
- const r = await drafter.ask(planPrompt(job, scoutBlob, reds, maxStepRounds, failure, scopeMenu, materials, starting, checkFacts, doorWords?.text ?? null, readShim, hints?.text ?? null), []);
3169
+ const r = await drafter.ask(planPrompt(job, scoutBlob, reds, maxStepRounds, failure, scopeMenu, materials, starting, checkFacts, doorWords?.text ?? null, readShim, hints?.text ?? null, seedNoteForPlanner?.text ?? null), []);
3149
3170
  if (phase === 'replan' && typeof r.error === 'string' && r.error.startsWith('truncated:')) {
3150
3171
  replanCut = true;
3151
3172
  return '';
@@ -3520,6 +3541,8 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
3520
3541
  // results makes the leak inexpressible; scrubbing each consumer makes it
3521
3542
  // something the next consumer has to remember.
3522
3543
  const results = raw.map((r) => (typeof r.detail === 'string' ? { ...r, detail: scrub(r.detail) } : r));
3544
+ // the carry note's outcome for this try, from the check itself; a red also hands over the whole failing text, the SAME text the next prompt's gap carries (lastGap below)
3545
+ carry?.settleAsk(results.some((r) => r.fault) ? 'unknown' : pass ? 'green' : 'red', results.filter((r) => !r.pass).map((r) => r.detail).join('\n'));
3523
3546
  // PRD v1.106 Part 5: what the check just read (path, size, sha256 — never the content), recorded BEFORE the exit-eval because the next try
3524
3547
  // overwrites the file. The worker is idle between its turn and this judge, so these are the bytes the check read.
3525
3548
  for (const o of await outputJudgedRecords(job.closeDecl, workdir, step.exit)) emit('output-judged', { step: step.id, iteration: iterationNow, ...o });
@@ -4255,7 +4278,11 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
4255
4278
  // two exhaustion rules are alternatives and never both at once, so the count
4256
4279
  // is not passed — it survives only inside the governor, as the bound for the
4257
4280
  // case the trend instrument is blind.
4258
- middle, judge: async () => judgeClose(), ladder: fixGovernor, emit: emitL, redact: scrub,
4281
+ middle, judge: async () => {
4282
+ const v = await judgeClose();
4283
+ carry?.settleAsk(v.verdict === 'satisfied' ? 'green' : v.verdict === 'needs_revision' ? 'red' : 'unknown', v.verdict === 'needs_revision' ? v.gap : undefined); // the fix try's outcome and its whole failing text (the gap the next prompt carries), from the close itself
4284
+ return v;
4285
+ }, ladder: fixGovernor, emit: emitL, redact: scrub,
4259
4286
  closeTimeoutMs, cwd: workdir, workerWrites: w.workerWrites, closeDir, phase: 'fix',
4260
4287
  });
4261
4288
  } catch (e) {
package/src/readshim.js CHANGED
@@ -40,6 +40,7 @@
40
40
 
41
41
  import { createHash } from 'node:crypto';
42
42
  import { readFileSync } from 'node:fs';
43
+ import { relative, resolve, sep } from 'node:path';
43
44
 
44
45
  /** The delivery cap, in bytes. Equal to `NATIVE_READ_CAP` by construction — the
45
46
  * native path's CLI display bound and this cap bound the SAME seam, so one
@@ -324,6 +325,58 @@ const stalePastEofNotice = (path, startLine, endLine, lines, detail) =>
324
325
  /** @typedef {{file: string, path: string, startLine: number, endLine: number, detail: string}} StaleReq */
325
326
  /** @typedef {{text: string, outcome: 'stale-served'|'stale-absent'|'stale-past-eof'}} StaleServe */
326
327
 
328
+ // ── THE FIRST-READ MAP (EXPERIMENTAL, default off; docs/logs/MAP-PREREG.md) ─────────────────────────────────────────
329
+ // With the signed spec field `readMap: true`, the FIRST shell_read of a big non-test file in an ask returns a map (one line
330
+ // per named part: symbol and line range) instead of the file's bytes, so the worker can copy exact `ctx_get` handles instead
331
+ // of computing a range ($0 archive read: 41% of ctx_get calls on a big-file job came back no-chunk). It delivers nothing, so
332
+ // it never touches the delivery ledger: the SECOND read of the same path in the same ask is today's read, whole.
333
+
334
+ /** a file this long (in lines) or longer gets a map on its first read in an ask */
335
+ export const READ_MAP_MIN_LINES = 200;
336
+ /** the map's size bound, in characters (header, parts, `+N more` line and footer together) */
337
+ export const READ_MAP_CAP = 4000;
338
+
339
+ /** a test file: a `test/`, `tests/` or `__tests__/` path segment, or a name `*.test.*` / `*.spec.*` */
340
+ const isTestPath = (/** @type {string} */ rel) => rel.split('/').some((seg, i, a) => (i < a.length - 1 && (seg === 'test' || seg === 'tests' || seg === '__tests__')) || (i === a.length - 1 && /\.(test|spec)\./.test(seg)));
341
+
342
+ /**
343
+ * The map text for one file, from the index's chunks. Pure. A chunk that CONTAINS another named chunk is left out (a class
344
+ * chunk would hand the whole class to `ctx_get`); the rest are listed by start line as `symbol start-end` in the index's own
345
+ * 0-based inclusive line space, the one `ctx_get` takes. Cut to READ_MAP_CAP characters with a `+N more` line.
346
+ * @param {{rel: string, lines: number, chunks: {symbol?: string|null, startLine: number, endLine: number}[]}} o
347
+ * @returns {{text: string, symbols: number}|null} null when the file has no named part
348
+ */
349
+ export function buildReadMap({ rel, lines, chunks }) {
350
+ const named = chunks.filter((c) => typeof c.symbol === 'string' && c.symbol !== '' && Number.isInteger(c.startLine) && Number.isInteger(c.endLine));
351
+ const kept = named
352
+ .filter((c) => !named.some((d) => d !== c && c.startLine <= d.startLine && d.endLine <= c.endLine && (c.startLine !== d.startLine || c.endLine !== d.endLine)))
353
+ .sort((a, b) => a.startLine - b.startLine || a.endLine - b.endLine);
354
+ if (kept.length === 0) return null;
355
+ const head = `${rel} (${lines} lines) — map, not the file:`;
356
+ const foot = `Line numbers are 0-based, as ctx_recall prints them; copy them as printed. Open one part with ctx_get(path="${rel}", startLine=<start>, endLine=<end>) using a range from this list, or read the file again to get the whole file.`;
357
+ const rows = kept.map((c) => `${c.symbol} ${c.startLine}-${c.endLine}`);
358
+ const moreLine = (/** @type {number} */ n) => `+${n} more`;
359
+ let used = head.length + 1 + foot.length;
360
+ const shown = [];
361
+ for (let i = 0; i < rows.length; i++) {
362
+ // room for the `+N more` line is reserved while parts remain after this one
363
+ const reserve = i < rows.length - 1 ? moreLine(rows.length).length + 1 : 0;
364
+ if (used + rows[i].length + 1 + reserve > READ_MAP_CAP) break;
365
+ shown.push(rows[i]);
366
+ used += rows[i].length + 1;
367
+ }
368
+ const cut = rows.length - shown.length;
369
+ const text = [head, ...shown, ...(cut > 0 ? [moreLine(cut)] : []), foot].join('\n');
370
+ return { text, symbols: shown.length };
371
+ }
372
+
373
+ /**
374
+ * @typedef {{root: string, hasGet: boolean, getNode: (rel: string) => any, refresh?: (() => Promise<unknown>)|null, emit: (type: string, data: object) => void}} ReadMapOpts
375
+ * `root`: the job root (paths are made relative to it); `hasGet`: this worker holds `ctx_get` (a map hands out handles only that tool opens);
376
+ * `getNode`: the LiteCtx index's node for a path (its `chunks`); `refresh`: re-index first so the ranges are true to the file as it now is;
377
+ * `emit`: the spine channel, for the report-only `read-map` / `read-map-skip` records (counts and a reason, never text).
378
+ */
379
+
327
380
  /**
328
381
  * Create the shim: one delivery ledger, and the two seams that speak for it.
329
382
  *
@@ -332,7 +385,7 @@ const stalePastEofNotice = (path, startLine, endLine, lines, detail) =>
332
385
  * reference to the ledger — see its own note. Both live in one object because
333
386
  * they are one worker's shim: the read seam and the retrieval seam the cap
334
387
  * steers a capped worker towards.
335
- * @param {{cap?: number, arm?: ReadShimArm, onCount?: ((kind: 'pointered'|'capped', bytesWithheld: number) => void)|null}} [opts]
388
+ * @param {{cap?: number, arm?: ReadShimArm, onCount?: ((kind: 'pointered'|'capped', bytesWithheld: number) => void)|null, readMap?: ReadMapOpts|null}} [opts]
336
389
  * `cap`: delivery bound in bytes (the shipped value is `READ_SHIM_CAP`; the option
337
390
  * exists so the native path can pin the two bounds to one number rather than two
338
391
  * constants drifting apart). `arm`: which levers are live (`readShimArm`). Defaults to
@@ -343,7 +396,10 @@ const stalePastEofNotice = (path, startLine, endLine, lines, detail) =>
343
396
  * for a diff response (L2 is its own lever, uncounted here) or a first read under the
344
397
  * cap (nothing was withheld).
345
398
  */
346
- export function createReadShim({ cap = READ_SHIM_CAP, arm = ARM_ALL, onCount = null } = {}) {
399
+ export function createReadShim({ cap = READ_SHIM_CAP, arm = ARM_ALL, onCount = null, readMap = null } = {}) {
400
+ /** the paths (absolute) this ask has had its map decision for: the second read of one is today's read
401
+ * @type {Set<string>} */
402
+ const mapTried = new Set();
347
403
  /** path → what the worker has been handed of the CURRENT content. `full` is
348
404
  * the delivered text itself, kept ONLY while the worker holds the whole file
349
405
  * (null otherwise) because that is the only state a diff is legal from.
@@ -456,6 +512,38 @@ export function createReadShim({ cap = READ_SHIM_CAP, arm = ARM_ALL, onCount = n
456
512
  * @param {{name: string, execute: (args: any) => Promise<any>}} tool the read tool
457
513
  * @returns {{name: string, execute: (args: any) => Promise<any>}} the same tool
458
514
  */
515
+ /** @param {string} path the path as the worker spelled it @returns {Promise<string|null>} the map text, or null for today's read */
516
+ const firstReadMap = async (path) => {
517
+ const o = /** @type {ReadMapOpts} */ (readMap);
518
+ const abs = resolve(o.root, path);
519
+ if (mapTried.has(abs)) return null;
520
+ mapTried.add(abs);
521
+ const rel = relative(resolve(o.root), abs).split(sep).join('/');
522
+ if (rel === '' || rel.startsWith('..') || isTestPath(rel)) return null;
523
+ let lines;
524
+ try {
525
+ const text = readFileSync(abs, 'utf8');
526
+ lines = text.split('\n').length - (text.endsWith('\n') ? 1 : 0);
527
+ } catch { return null; }
528
+ if (lines < READ_MAP_MIN_LINES) return null;
529
+ /** @param {string} reason */
530
+ const skip = (reason) => { o.emit('read-map-skip', { path: rel, reason }); return null; };
531
+ if (!o.hasGet) return skip('no-ctx_get');
532
+ let chunks;
533
+ try {
534
+ if (o.refresh) await o.refresh();
535
+ chunks = o.getNode(rel)?.chunks;
536
+ } catch { return skip('no-index'); }
537
+ if (!Array.isArray(chunks)) return skip('no-index');
538
+ if (!chunks.some((/** @type {any} */ c) => c?.symbol)) return skip('no-named-chunks');
539
+ // an index older than the file: a named chunk ending past the file's last line
540
+ if (chunks.some((/** @type {any} */ c) => c?.symbol && c.endLine >= lines)) return skip('stale-index');
541
+ const built = buildReadMap({ rel, lines, chunks });
542
+ if (!built) return skip('no-named-chunks');
543
+ o.emit('read-map', { path: rel, lines, symbols: built.symbols, chars: built.text.length });
544
+ return built.text;
545
+ };
546
+
459
547
  const wrapRead = (tool) => {
460
548
  // An OFF arm wraps nothing at all — not a wrapper that passes through, which
461
549
  // would still be a `tool.execute` this module owns. A0 has to be the seam
@@ -471,6 +559,13 @@ export function createReadShim({ cap = READ_SHIM_CAP, arm = ARM_ALL, onCount = n
471
559
  // path nobody ever received bytes for.
472
560
  if (path === null || typeof r !== 'string') return r;
473
561
 
562
+ // THE FIRST-READ MAP (experimental): the first read of a big non-test file in this ask returns the map, delivers nothing, and
563
+ // leaves the ledger untouched; every other read falls through to the code below unchanged.
564
+ if (readMap) {
565
+ const m = await firstReadMap(path);
566
+ if (m !== null) return m;
567
+ }
568
+
474
569
  const buf = Buffer.from(r, 'utf8');
475
570
  const total = buf.length;
476
571
  const hash = createHash('sha256').update(buf).digest('hex');
@@ -569,7 +664,7 @@ export function createReadShim({ cap = READ_SHIM_CAP, arm = ARM_ALL, onCount = n
569
664
  * Not called for a continuation (`askFrom` re-runs the SAME transcript — the model still
570
665
  * holds everything, so its ledger stays true).
571
666
  */
572
- const reset = () => { ledger.clear(); };
667
+ const reset = () => { ledger.clear(); mapTried.clear(); };
573
668
 
574
669
  return { arm, cap, wrapRead, serveStale, summary, reset };
575
670
  }
package/src/replay.js CHANGED
@@ -376,6 +376,19 @@ function floorReasons(spine, jobStart, spendComplete) {
376
376
  return reasons;
377
377
  }
378
378
 
379
+ /**
380
+ * The failing stage's own output lines from a close record's `gap`: the lines after the `stageGap` header (`close stage "X" failed:`), each
381
+ * as the spine holds it (the panel words them). A gap that does not open with that header keeps every line. `[]` for no gap.
382
+ * @param {unknown} gap
383
+ * @returns {string[]}
384
+ */
385
+ function gapLines(gap) {
386
+ if (typeof gap !== 'string' || gap === '') return [];
387
+ const lines = gap.split('\n');
388
+ if (/^close stage ".*" failed:$/.test(lines[0])) lines.shift();
389
+ return lines.filter((l) => l.trim() !== '');
390
+ }
391
+
379
392
  /**
380
393
  * Which `close-verdict`/`outer-close` record is "the close" — the
381
394
  * OPERATOR's real, signed close, never a plan step's own exit-eval judge
@@ -588,6 +601,8 @@ export function replayRun(spineEvents, auditEvents = [], { runId = null, auditAv
588
601
  // = `['worker-round', 'judge-round', 'worker-turn']`), imported rather than
589
602
  // re-spelled so the two can never drift apart.
590
603
  const spendRecords = spine.filter((e) => SPEND_RECORD_TYPES.includes(e.type));
604
+ // the model calls inside one try's window, counted the way the Audit rounds endpoint pages them (`seq` in (lo, hi])
605
+ const countRoundsIn = (/** @type {number} */ lo, /** @type {number} */ hi) => spendRecords.filter((r) => typeof r.seq === 'number' && r.seq > lo && r.seq <= hi).length;
591
606
  const exitEvals = spine.filter((e) => e.type === 'exit-eval');
592
607
  // PRD v1.106 Part 5 (D1): which check each `check-passes` result was — the `check-run` record just before its exit-eval
593
608
  const checkRuns = spine.filter((e) => e.type === 'check-run');
@@ -879,12 +894,14 @@ export function replayRun(spineEvents, auditEvents = [], { runId = null, auditAv
879
894
  const lastIter = iterationStarts
880
895
  .filter((it) => typeof it.seq === 'number' && it.seq > prevBoundSeq && it.seq < endSeq)
881
896
  .sort((a, b) => b.seq - a.seq)[0] ?? null;
897
+ const cutOffEndSeq = end && typeof end.seq === 'number' ? end.seq : (Number.isFinite(endSeq) ? endSeq : prevBoundSeq);
882
898
  const cutOffTry = endedHere && lastIter
883
899
  ? {
884
900
  n: attemptWindows.length + 1,
885
901
  iteration: typeof lastIter.iteration === 'number' ? lastIter.iteration : null,
886
902
  startSeq: prevBoundSeq,
887
- endSeq: end && typeof end.seq === 'number' ? end.seq : (Number.isFinite(endSeq) ? endSeq : prevBoundSeq),
903
+ endSeq: cutOffEndSeq,
904
+ rounds: countRoundsIn(prevBoundSeq, cutOffEndSeq),
888
905
  startTs: prevBoundTs,
889
906
  endTs,
890
907
  }
@@ -1029,6 +1046,8 @@ export function replayRun(spineEvents, auditEvents = [], { runId = null, auditAv
1029
1046
  iteration: null,
1030
1047
  verdict,
1031
1048
  stages: Array.isArray(oc.stages) ? oc.stages : null,
1049
+ reasons: gapLines(oc.gap),
1050
+ stop: null,
1032
1051
  outcome: /** @type {'green'|'red'} */ (verdict === 'satisfied' || verdict === 'green' || verdict === 'already-green' ? 'green' : 'red'),
1033
1052
  ...buildOccurrenceMetrics(prevSeq, prevTs, seq, ts, roundsInWindow),
1034
1053
  windowStartSeq: prevSeq,
@@ -1064,6 +1083,12 @@ export function replayRun(spineEvents, auditEvents = [], { runId = null, auditAv
1064
1083
  iteration: typeof is.iteration === 'number' ? is.iteration : null,
1065
1084
  verdict,
1066
1085
  stages: end && end.type === 'close-verdict' && Array.isArray(end.stages) ? end.stages : null,
1086
+ // the failing stage's output lines (a close-verdict's `gap`); a window a close did not end (an escalation, a run-end) says what
1087
+ // ended it instead: no verdict exists for that try
1088
+ reasons: end && end.type === 'close-verdict' ? gapLines(end.gap) : [],
1089
+ stop: end && end.type !== 'close-verdict'
1090
+ ? { by: end.type, what: (end.type === 'escalation' ? end.category : end.outcome) ?? null, detail: typeof end.detail === 'string' ? end.detail : null }
1091
+ : null,
1067
1092
  // `end === null` means this iteration's own window hasn't closed
1068
1093
  // yet (no close-verdict/run-end/escalation boundary has landed on
1069
1094
  // the spine after its iteration-start) — a LIVE run reading this
@@ -1369,7 +1394,7 @@ export function replayRun(spineEvents, auditEvents = [], { runId = null, auditAv
1369
1394
  // same as a scout/plan/replan/judge/run part already does.
1370
1395
  const stepAttempts = step.attemptWindows.length > 0
1371
1396
  ? step.attemptWindows.map((aw) => ({
1372
- n: aw.n, outcome: aw.outcome, verdict: null, stages: null, detail: aw.exitEvalDetail, startSeq: aw.startSeq, endSeq: aw.endSeq, startTs: aw.startTs, endTs: aw.endTs, iteration: aw.iteration, checks: aw.checks, outputJudged: aw.outputJudged,
1397
+ n: aw.n, outcome: aw.outcome, verdict: null, stages: null, rounds: countRoundsIn(aw.startSeq, aw.endSeq), detail: aw.exitEvalDetail, startSeq: aw.startSeq, endSeq: aw.endSeq, startTs: aw.startTs, endTs: aw.endTs, iteration: aw.iteration, checks: aw.checks, outputJudged: aw.outputJudged,
1373
1398
  }))
1374
1399
  : wholePartAttempt(step.stepStartSeq, step.stepStartTs, step.stepEndSeq, step.stepEndTs);
1375
1400
  parts.push({
@@ -1413,7 +1438,7 @@ export function replayRun(spineEvents, auditEvents = [], { runId = null, auditAv
1413
1438
  unpricedRounds: fixLoop.unpricedRounds,
1414
1439
  outcome: fixLoop.attempts.length ? fixLoop.attempts[fixLoop.attempts.length - 1].outcome : null,
1415
1440
  attempts: fixLoop.attempts.map((a) => ({
1416
- n: a.n, outcome: a.outcome, verdict: a.verdict, stages: a.stages, detail: null, startSeq: a.windowStartSeq, endSeq: a.windowEndSeq, startTs: a.windowStartTs, endTs: a.windowEndTs,
1441
+ n: a.n, outcome: a.outcome, verdict: a.verdict, stages: a.stages, source: a.source, reasons: a.reasons, stop: a.stop, rounds: a.rounds, detail: null, startSeq: a.windowStartSeq, endSeq: a.windowEndSeq, startTs: a.windowStartTs, endTs: a.windowEndTs,
1417
1442
  })),
1418
1443
  });
1419
1444
  }
@@ -0,0 +1,28 @@
1
+ // THE SEED NOTE (default ON; docs/logs/SEEDGAP-PREREG.md): what the job's own check said on the untouched tree.
2
+ // Built by code from the preflight's own stage results — no extra close run, no model call, no verdict change. Read-only text for the
3
+ // planner's first draft; every step/fix worker gets it through the carry memo's "Earlier failures (folded):" section, labelled `at start`
4
+ // (src/carrystore.js `setStartFailure`). The switch is the signed spec's `seedNote` (absent = on, only `false` turns it off).
5
+ // Only a count-not-worse stage red at seed qualifies: a command-exit gap is capped noise that cannot carry the failure, and
6
+ // changed-from-seed is the "nothing changed yet" fact every run starts with. The stage text is passed as the stage rendered it, masked.
7
+
8
+ export const SEED_NOTE_HEADING = "At start, the job's own check said:";
9
+ /** the one stage kind whose text qualifies */
10
+ export const SEED_NOTE_KIND = 'count-not-worse';
11
+
12
+ /**
13
+ * @param {{stage: string|null|undefined, kind: string|null|undefined, gap: string|null|undefined}[]} reds one entry per preflight verdict
14
+ * that was RED at seed (stage = the stage that rendered it, kind = that stage's declared kind, gap = the verdict's gap text)
15
+ * @param {(s: string) => string} scrub the run's secret mask
16
+ * @returns {{ text: string, body: string, stages: string[] }|null} null when no qualifying stage was red (nothing to say)
17
+ */
18
+ export function buildSeedNote(reds, scrub) {
19
+ /** @type {Map<string, string>} */
20
+ const kept = new Map();
21
+ for (const r of reds) {
22
+ if (r.kind !== SEED_NOTE_KIND || typeof r.stage !== 'string' || typeof r.gap !== 'string' || !r.gap.trim()) continue;
23
+ if (!kept.has(r.stage)) kept.set(r.stage, scrub(r.gap));
24
+ }
25
+ if (kept.size === 0) return null;
26
+ const body = [...kept.values()].join('\n');
27
+ return { text: `${SEED_NOTE_HEADING}\n${body}`, body, stages: [...kept.keys()] };
28
+ }
package/src/tools.js CHANGED
@@ -652,3 +652,20 @@ export const toolAction = (name, args, workdir) => {
652
652
  if (name === 'ctx_forget') return { type: name, args: { id: String(args?.id ?? '') } };
653
653
  return { type: name, args };
654
654
  };
655
+
656
+ /**
657
+ * The `createShellTools()` options that keep a walking `shell_grep` inside the gate (F259).
658
+ * The loop policy judges a directory grep ONCE, on the root path it names, so `fs.deny`
659
+ * never saw the files the walk opened (the arbiter's books under the repo root). bare-agent
660
+ * 0.55.0's `canRead` asks this for every directory (false prunes it) and every file (false
661
+ * skips it); the answer is the gate's own pure `allows()` on the SAME read action
662
+ * `toolAction` builds, so the walk obeys the identical `fs.deny`/`readScope` the direct
663
+ * `shell_read` of that file does. `allows()` writes no audit line and books nothing.
664
+ * `noFollowSymlinks` closes the swap-after-vetting window bare-agent documents.
665
+ * @param {{allows: (action: any) => Promise<boolean>}} gate
666
+ * @param {string} workdir
667
+ */
668
+ export const gatedShellOptions = (gate, workdir) => ({
669
+ noFollowSymlinks: true,
670
+ canRead: (/** @type {string} */ p, /** @type {{tool: string}} */ { tool }) => gate.allows(toolAction(tool, { path: p }, workdir)),
671
+ });