bareloop 0.51.0 → 0.52.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
41
  import { createHandoffStore, trackReads } from './handoff.js';
42
+ import { createCarryStore } from './carrystore.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';
@@ -1002,12 +1003,15 @@ ${scoutBlob || '(no scout notes)'}`;
1002
1003
  * run start from the ledger as it stood). Handed to the PLANNER only: the first draft and the FIRST replan. No worker ever
1003
1004
  * receives it, and a later replan gets nothing. Each injection is recorded on the spine as a `learnings` record (the exact
1004
1005
  * text) so the Audit can show it and the byte check can compare it with a fresh render. `null` = no hints (the default).
1006
+ * @param {boolean} [opts.carryNote=false] THE CARRY NOTE (src/carrynote.js): the step/fix worker is handed a facts-only note of what earlier
1007
+ * workers of this run looked at, searched and changed, after the handoff note. The caller reads the switch once; `false` builds no store
1008
+ * and leaves the worker prompt byte-identical. One `carry-note` spine record (counts only) per note handed.
1005
1009
  * @returns {Promise<string>} 'green' | 'already-green' | 'escalated' | 'plan-red' |
1006
1010
  * 'check-red' | 'close-red' | 'close-unsupported' | 'recipe-stale' | 'pricing-red' |
1007
1011
  * 'branch-red' | 'cap-halt' | 'wall-halt' | 'stopped' | 'provider-red' | 'interpreter-red' |
1008
1012
  * 'step-stalled' | 'hitl-pause' | 'hitl-decision-red' | `step-red:<id>`
1009
1013
  */
1010
- export async function runPlan(job, { workdir, provider, nativeProvider, providerFor, judgeProvider = null, judgeModel = null, rates = null, judgeRates = null, emit, remainingUsd, isUnpriced = () => false, spendComplete = () => true, capRuns = 3, strikeLimit = STRIKE_LIMIT, closeTimeoutMs, closeDir = null, maxStepRounds = 40, layerRoot = false, readShim = false, scout = true, scoutRounds = SCOUT_ROUNDS, bridge = null, now, priorWallMs = 0, resumeSeed = null, resumeGrades = [], resumeReplans = null, resumeBranch = null, humanRuling = null, heldRuling = null, priorSpentUsd = 0, reviewDoor = null, doorRerun = null, resumable = true, stopFile = null, learnHints = null }) {
1014
+ export async function runPlan(job, { workdir, provider, nativeProvider, providerFor, judgeProvider = null, judgeModel = null, rates = null, judgeRates = null, emit, remainingUsd, isUnpriced = () => false, spendComplete = () => true, capRuns = 3, strikeLimit = STRIKE_LIMIT, closeTimeoutMs, closeDir = null, maxStepRounds = 40, layerRoot = false, readShim = false, scout = true, scoutRounds = SCOUT_ROUNDS, bridge = null, now, priorWallMs = 0, resumeSeed = null, resumeGrades = [], resumeReplans = null, resumeBranch = null, humanRuling = null, heldRuling = null, priorSpentUsd = 0, reviewDoor = null, doorRerun = null, resumable = true, stopFile = null, learnHints = null, carryNote = false }) {
1011
1015
  // MEMORY-CACHE: what the read shim (src/readshim.js) saved THIS run, summed across
1012
1016
  // every mkWorker's own shim instance (scout, drafter, each step's worker, the fix
1013
1017
  // worker) — one accumulator closed over by all of them, because the shim's ledger
@@ -1028,6 +1032,9 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
1028
1032
  // The switch is the signed spec's `handoffNote` (absent = on, only `false` turns it off).
1029
1033
  const handoffOn = job.handoffNote !== false;
1030
1034
  const handoff = createHandoffStore({ workdir });
1035
+ // THE CARRY NOTE (src/carrynote.js, src/carrystore.js): facts the earlier asks of THIS run produced, handed after the handoff note.
1036
+ // The caller reads the one switch (`carryNote` in config.json) once; off builds no store, writes no state, emits nothing.
1037
+ const carry = carryNote === true ? createCarryStore({ workdir, emit, strikeLimit, resume: resumeBranch !== null && resumeBranch !== undefined }) : null;
1031
1038
  // The scout switch's guard, same class and same door: a mis-typed value
1032
1039
  // coerced by truthiness would run the scout under an "off" label (or skip it
1033
1040
  // under an "on" one) and no reading of the results afterwards could recover
@@ -2044,6 +2051,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2044
2051
  ? 'returned to the branch this run was killed on — its work is on this branch, and a fresh one would strand it'
2045
2052
  : 'the HARD RULE (PRD v1.57 §3): the run works here, never on the branch it was handed and never on main',
2046
2053
  });
2054
+ carry?.setBase(wb.base);
2047
2055
  return null;
2048
2056
  };
2049
2057
  if (resuming) {
@@ -2495,7 +2503,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2495
2503
  }
2496
2504
  };
2497
2505
  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));
2506
+ const shell = createShellTools(gatedShellOptions(gate, workdir)).tools.filter((/** @type {{name: string}} */ t) => grantedNames.has(t.name));
2499
2507
  // THE READ SHIM (arm-gated, default OFF): a per-worker delivery ledger over the
2500
2508
  // read tool — cap at READ_SHIM_CAP, pointer only once the CURRENT content has been
2501
2509
  // delivered whole, next-unseen-slice otherwise, diff on a changed re-read. WHICH of
@@ -2593,6 +2601,14 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2593
2601
  }
2594
2602
  try { return await inner(p, defs); } finally { handoff.absorb(askReads); }
2595
2603
  });
2604
+ // The carry note: the same seam, one layer in. It records what each ask's read-class tools returned (a summary, never
2605
+ // content) and hands the next step/fix ask the facts. It is the INNER wrapper, so its note lands after the handoff note.
2606
+ if (carry) carry.wrapTools(toolDefs);
2607
+ /** @param {(prompt: string, defs?: any) => Promise<any>} inner */
2608
+ const withCarry = (inner) => (!carry ? inner : async (/** @type {string} */ prompt, /** @type {any} */ defs) => {
2609
+ const text = await carry.beginAsk({ phase, iteration: roundIteration, prompt });
2610
+ try { return await inner(text ? `${prompt}\n\n${text}` : prompt, defs); } finally { carry.endAsk({ bounded: attemptBounded, iteration: roundIteration, rounds: attemptRounds }); }
2611
+ });
2596
2612
  // F19 per VERB (P, corrected 2026-07-31): a strategy SENTENCE rides only with
2597
2613
  // the verb it names. Gating per COMPONENT was close but over-reached — a
2598
2614
  // worker granted only `impact` must not be steered to tools it lacks, and the
@@ -2690,7 +2706,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2690
2706
  }
2691
2707
  return r;
2692
2708
  };
2693
- return { ask: withHandoff(ask), askFrom, workerWrites, writeCount, setIteration, wasBounded: () => attemptBounded };
2709
+ return { ask: withHandoff(withCarry(ask)), askFrom, workerWrites, writeCount, setIteration, wasBounded: () => attemptBounded };
2694
2710
  }
2695
2711
 
2696
2712
  // ── LOOP path: the injected provider (anthropic-api and every other
@@ -2964,7 +2980,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2964
2980
  }
2965
2981
  return r;
2966
2982
  };
2967
- return { ask: withHandoff(ask), askFrom, workerWrites, writeCount, setIteration, wasBounded: () => attemptBounded };
2983
+ return { ask: withHandoff(withCarry(ask)), askFrom, workerWrites, writeCount, setIteration, wasBounded: () => attemptBounded };
2968
2984
  }
2969
2985
 
2970
2986
  /** relay a throw from OUTSIDE ralph (scout/plan drafting/fix) as its honest
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
  }
package/src/run.js CHANGED
@@ -261,6 +261,9 @@ async function primitiveSmoke(workdir) {
261
261
  * round-boundary seam (where the money cap binds) and ends the leg `stopped`. `null` = no stop surface.
262
262
  * @param {{text: string, ids: string[]}|null} [opts.learnHints=null] cross-run learnings for the PLANNER only (the draft and the
263
263
  * first replan); forwarded verbatim to the plan flow, which records what it handed over as a `learnings` spine record.
264
+ * @param {boolean} [opts.carryNote=false] THE CARRY NOTE (src/carrynote.js): hand each step/fix worker a facts-only note of what earlier
265
+ * workers of this run looked at, searched and changed. The caller reads the one switch (`carryNote` in config.json, src/carrystore.js
266
+ * `carryNoteOn`) once; the library default is off, exactly like `learnHints`. Forwarded verbatim to the plan flow.
264
267
  * @returns {Promise<string>} outcome: 'green' | 'already-green' | 'escalated' |
265
268
  * 'unapproved-spec' | 'job-red' | 'smoke-red' | 'plan-red' | 'check-red' |
266
269
  * 'close-red' | 'close-unsupported' | 'recipe-stale' | 'branch-red' | 'pricing-red' | 'provider-red' |
@@ -275,7 +278,7 @@ async function primitiveSmoke(workdir) {
275
278
  * deliberately NOT in the resumable/checkpoint set (`src/reuse.js`) — an
276
279
  * unknown in-flight state is not a known-safe resume point.
277
280
  */
278
- export async function runJob(rawSpec, { approvals, workdir, provider, nativeProvider, providerFor, judgeProvider = null, judgeModel = null, rates = null, judgeRates = null, emit, capRuns = 3, strikeLimit, shellCapUsd = 2, closeTimeoutMs, closeDir = null, layerRoot = false, readShim = false, scout = true, bridge = null, draftSpentUsd = 0, draftSpendComplete = true, priorSpentUsd = 0, priorSpendComplete = true, priorWallMs = 0, resumeSeed = null, resumeGrades = [], resumeReplans = null, resumeBranch = null, humanRuling = null, heldRuling = null, reviewDoor = null, doorRerun = null, resumable = true, stopFile = null, learnHints = null }) {
281
+ export async function runJob(rawSpec, { approvals, workdir, provider, nativeProvider, providerFor, judgeProvider = null, judgeModel = null, rates = null, judgeRates = null, emit, capRuns = 3, strikeLimit, shellCapUsd = 2, closeTimeoutMs, closeDir = null, layerRoot = false, readShim = false, scout = true, bridge = null, draftSpentUsd = 0, draftSpendComplete = true, priorSpentUsd = 0, priorSpendComplete = true, priorWallMs = 0, resumeSeed = null, resumeGrades = [], resumeReplans = null, resumeBranch = null, humanRuling = null, heldRuling = null, reviewDoor = null, doorRerun = null, resumable = true, stopFile = null, learnHints = null, carryNote = false }) {
279
282
  // THE READ SHIM's ARM, resolved at the door — the FIRST thing this entry does,
280
283
  // before the ledger, before the approval gate, before a byte of the spec is read.
281
284
  // An unrecognised spelling throws here at zero cost instead of being coerced by
@@ -542,7 +545,7 @@ export async function runJob(rawSpec, { approvals, workdir, provider, nativeProv
542
545
  // accounts it natively (F12) and the job-end money contract is unchanged.
543
546
  {
544
547
  const outcome = await runPlan(job, {
545
- workdir, provider, nativeProvider, providerFor, judgeProvider, judgeModel, rates, judgeRates, emit: meter, capRuns, ...(strikeLimit !== undefined ? { strikeLimit } : {}), closeTimeoutMs, closeDir, layerRoot, readShim, scout, bridge, priorWallMs: chainWallMs, resumeSeed, resumeGrades, resumeReplans, resumeBranch, humanRuling, heldRuling, reviewDoor, doorRerun, priorSpentUsd: chainFoldUsd, resumable, stopFile, learnHints,
548
+ workdir, provider, nativeProvider, providerFor, judgeProvider, judgeModel, rates, judgeRates, emit: meter, capRuns, ...(strikeLimit !== undefined ? { strikeLimit } : {}), closeTimeoutMs, closeDir, layerRoot, readShim, scout, bridge, priorWallMs: chainWallMs, resumeSeed, resumeGrades, resumeReplans, resumeBranch, humanRuling, heldRuling, reviewDoor, doorRerun, priorSpentUsd: chainFoldUsd, resumable, stopFile, learnHints, carryNote,
546
549
  // hamr's ruling 2026-09-28 — ONE cap covers drafting + run: the run's
547
550
  // enforced ceiling is the signed `budgetUsd` (unchanged, still in the
548
551
  // spec hash) MINUS whatever drafting already spent on this job before
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
+ });
package/src/userrun.js CHANGED
@@ -83,6 +83,7 @@ import { parseJsonl } from './replayio.js';
83
83
  import { claimRun, monthlyRefusalText, legSpend, chainSpend } from './monthly.js';
84
84
  import { ConfigError } from './config.js';
85
85
  import { learnAtRunEnd, handedHints, releaseRun } from './learnstore.js';
86
+ import { carryNoteOn } from './carrystore.js';
86
87
  import { commandFor } from './invoke.js';
87
88
  import { judgeRatesFor, keyNameFor, keyValueOf, priceReadout, ratesFor, ratesOfLine, resolveWorker, judgeRowFor, rowsForHome, REFUSE_NAME_MODEL } from './providerrows.js';
88
89
  // the banner's wall arithmetic, extracted so it is reachable by a test (F83): the
@@ -1916,6 +1917,8 @@ async function execute(ctx) {
1916
1917
  outcome = await runJob(spec, {
1917
1918
  stopFile,
1918
1919
  ...(learnHints === null ? {} : { learnHints }),
1920
+ // the carry note's one switch, read once here exactly like `learningHints` above (absent = on, only `false` turns it off)
1921
+ carryNote: cfgOn && carryNoteOn(cfgHome),
1919
1922
  // PRD item 27/M3 — the SAME `emit` the pre-run close-timing reading above
1920
1923
  // used (never a second `makeSpine(spineFile)` here: two independent
1921
1924
  // emitters against one file would both start their seq counter at 0 and
@@ -0,0 +1,134 @@
1
+ /**
2
+ * One record per tool call (no content, no worker words).
3
+ * @typedef {object} Ev
4
+ * @property {number} ask
5
+ * @property {'read'|'get'|'grep'|'recall'} tool
6
+ * @property {string} [path]
7
+ * @property {number|null} [lines]
8
+ * @property {boolean} [dir]
9
+ * @property {boolean} [linesStale]
10
+ * @property {[number,number]|null} [range]
11
+ * @property {string} [pattern]
12
+ * @property {string} [scope]
13
+ * @property {number} [matches]
14
+ * @property {string[]} [firstMatches]
15
+ * @property {string} [query]
16
+ * @property {string[]} [hitPaths]
17
+ * @property {string[]} [hitRanges]
18
+ * @property {boolean} [noFix] the try that made this call ended with no change and a red check
19
+ */
20
+ /** token set, same tokenisation as src/learn.js flaggedTokens: lowercase [a-z0-9_]{2,} */
21
+ export function tokens(s: any): any[];
22
+ /**
23
+ * Files that are neither source nor test: manifests, lockfiles, docs, config. Dropped from "where looked" unless edited.
24
+ * @param {string} p repo-relative path
25
+ */
26
+ export function isNonSource(p: string): boolean;
27
+ /**
28
+ * Fold rule for two search keys (added beside Jaccard): same string prefix of >= PREFIX_MIN chars, or one
29
+ * contains the other (shorter side >= CONTAINS_MIN chars so "a" cannot swallow everything). Case-insensitive.
30
+ * @param {string|undefined} a @param {string|undefined} b
31
+ */
32
+ export function similarName(a: string | undefined, b: string | undefined): boolean;
33
+ /**
34
+ * Group items (newest first). An item joins the first group whose representative (the newest member) matches:
35
+ * Jaccard >= JACCARD_MIN on key tokens (the learnings rule), or `near(rep, item)`.
36
+ * @template T @param {T[]} items @param {(x:T)=>string} keyOf @param {(a:T,b:T)=>boolean} [near]
37
+ * @returns {{rep:T, members:T[]}[]}
38
+ */
39
+ export function fold<T>(items: T[], keyOf: (x: T) => string, near?: (a: T, b: T) => boolean): {
40
+ rep: T;
41
+ members: T[];
42
+ }[];
43
+ /** merge overlapping / adjacent [a,b] line ranges, ascending; returns 'a-b' strings */
44
+ export function mergeRanges(rs: any): string[];
45
+ /**
46
+ * Render the carry note. PURE.
47
+ * @param {{lastTry?: {step:string|null, kind:'step'|'fix', n:number|string|undefined, of?:number, ended:string, changed:string[]}|null,
48
+ * lastCheck?: string|null, events: Ev[], edits?: {path:string, lines:number, hunks:string[]}[],
49
+ * earlier?: string[], lastAsk?: number}} notes
50
+ * @param {number} [cap]
51
+ */
52
+ export function render(notes: {
53
+ lastTry?: {
54
+ step: string | null;
55
+ kind: "step" | "fix";
56
+ n: number | string | undefined;
57
+ of?: number;
58
+ ended: string;
59
+ changed: string[];
60
+ } | null;
61
+ lastCheck?: string | null;
62
+ events: Ev[];
63
+ edits?: {
64
+ path: string;
65
+ lines: number;
66
+ hunks: string[];
67
+ }[];
68
+ earlier?: string[];
69
+ lastAsk?: number;
70
+ }, cap?: number): {
71
+ text: string;
72
+ capped: boolean;
73
+ rawChars: number;
74
+ rawEntries: number;
75
+ foldedEntries: number;
76
+ named: Set<any>;
77
+ summarized: Set<string>;
78
+ sections: {
79
+ reads: number;
80
+ searches: number;
81
+ edits: number;
82
+ earlier: number;
83
+ };
84
+ };
85
+ export const CAP: 3000;
86
+ export const HUNK_LINES: 40;
87
+ export const HUNK_SHOW: 12;
88
+ export const GAP_LINES: 8;
89
+ export const GAP_CHARS: 600;
90
+ export const MATCH_SHOW: 3;
91
+ export const PREFIX_MIN: 6;
92
+ export const CONTAINS_MIN: 4;
93
+ export const HEADING: "== What earlier workers in this run did (facts from the record, written by code) ==";
94
+ export const NO_FIX_MIN_READS: 3;
95
+ export const NO_FIX: " \u00B7 looked here, no fix made";
96
+ /**
97
+ * One record per tool call (no content, no worker words).
98
+ */
99
+ export type Ev = {
100
+ ask: number;
101
+ tool: "read" | "get" | "grep" | "recall";
102
+ path?: string | undefined;
103
+ lines?: number | null | undefined;
104
+ dir?: boolean | undefined;
105
+ linesStale?: boolean | undefined;
106
+ range?: [number, number] | null | undefined;
107
+ pattern?: string | undefined;
108
+ scope?: string | undefined;
109
+ matches?: number | undefined;
110
+ firstMatches?: string[] | undefined;
111
+ query?: string | undefined;
112
+ hitPaths?: string[] | undefined;
113
+ hitRanges?: string[] | undefined;
114
+ /**
115
+ * the try that made this call ended with no change and a red check
116
+ */
117
+ noFix?: boolean | undefined;
118
+ };
119
+ export type Entry = {
120
+ text: string;
121
+ keys: string[];
122
+ /**
123
+ * 0 = last try's own fact, 1 = edited file, 2 = the rest
124
+ */
125
+ tier: 0 | 1 | 2;
126
+ /**
127
+ * times read / searched
128
+ */
129
+ count: number;
130
+ /**
131
+ * index of the newest call
132
+ */
133
+ recency: number;
134
+ };
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The ONE setting: `carryNote` in config.json, read exactly like `learningHints` (src/learnstore.js `learningHintsOn`).
3
+ * Absent = on; only an explicit `false` turns it off. An unreadable config reads as OFF (the safe side).
4
+ * @param {string} [home]
5
+ * @returns {boolean}
6
+ */
7
+ export function carryNoteOn(home?: string): boolean;
8
+ /**
9
+ * The run's edits from the working tree against the start commit: tracked (git diff) plus untracked (no diff exists).
10
+ * Arbiter books / .git / .bareloop are excluded. Never throws; [] on any git failure.
11
+ * @param {string} workdir @param {string|null} base
12
+ * @returns {Promise<{path: string, lines: number, hunks: string[]}[]>}
13
+ */
14
+ export function workingEdits(workdir: string, base: string | null): Promise<{
15
+ path: string;
16
+ lines: number;
17
+ hunks: string[];
18
+ }[]>;
19
+ /**
20
+ * Order edits oldest to newest by when they last changed: a file's recency is the latest settled ask whose `changed`
21
+ * list names it; a file in no `changed` list is oldest. Ties keep their incoming (alphabetical) order. PURE.
22
+ * @param {{path: string}[]} edits @param {{changed?: string[]}[]} settled asks settled so far, oldest first
23
+ */
24
+ export function orderEditsByRecency(edits: {
25
+ path: string;
26
+ }[], settled: {
27
+ changed?: string[];
28
+ }[]): {
29
+ path: string;
30
+ }[];
31
+ /**
32
+ * Run-level store. Asks are sequential, so "the current ask" is one counter.
33
+ * @param {{workdir: string, emit: (type: string, rec: any) => void, strikeLimit?: number, resume?: boolean}} o
34
+ */
35
+ export function createCarryStore({ workdir, emit, strikeLimit, resume }: {
36
+ workdir: string;
37
+ emit: (type: string, rec: any) => void;
38
+ strikeLimit?: number;
39
+ resume?: boolean;
40
+ }): {
41
+ wrapTools: (tools: {
42
+ name: string;
43
+ execute: Function;
44
+ }[]) => void;
45
+ beginAsk: ({ phase, iteration, prompt }: {
46
+ phase: string;
47
+ iteration: number | string | undefined;
48
+ prompt: string;
49
+ }) => Promise<string>;
50
+ endAsk: ({ bounded, iteration, rounds }: {
51
+ bounded?: {
52
+ iteration: any;
53
+ cause: string;
54
+ } | undefined;
55
+ iteration: any;
56
+ rounds: number;
57
+ }) => void;
58
+ setBase: (b: string | null | undefined) => void;
59
+ loaded: () => boolean;
60
+ _state: () => {
61
+ n: number;
62
+ events: any[];
63
+ asks: any[];
64
+ base: string | null;
65
+ };
66
+ };
67
+ export const CARRY_DIR: "carry";
68
+ /** the next prompt of a retried step / fix try carries this when the previous ask's check failed */
69
+ export const RED_MARKER: RegExp;
package/types/config.d.ts CHANGED
@@ -36,7 +36,7 @@ export function modelsProblem(list: unknown): string | null;
36
36
  * `keys` merges per key variable name, then per field; `models.<ENV>` is REPLACED WHOLE (`null`
37
37
  * clears it). Validated before anything is written; nothing is written on a refusal.
38
38
  *
39
- * Patch fields understood: `monthlyLimitUsd` (finite > 0), `learningHints` (true | false), `keys.<ENV>.{shape,baseUrl,legacyMaxTokens}`,
39
+ * Patch fields understood: `monthlyLimitUsd` (finite > 0), `learningHints` (true | false), `carryNote` (true | false), `keys.<ENV>.{shape,baseUrl,legacyMaxTokens}`,
40
40
  * `models.<ENV>` (a list judged by {@link modelsProblem}). The first write of a row's `models` list
41
41
  * removes that row's older `name` / `priceInPerM` / `priceOutPerM` in the SAME write (never two
42
42
  * sources); a retired top-level `anthropicBalanceNote` is dropped on any write. Any other field is
@@ -408,12 +408,15 @@ export function planPrompt(job: any, scoutBlob: string, reds: any[] | null, maxS
408
408
  * run start from the ledger as it stood). Handed to the PLANNER only: the first draft and the FIRST replan. No worker ever
409
409
  * receives it, and a later replan gets nothing. Each injection is recorded on the spine as a `learnings` record (the exact
410
410
  * text) so the Audit can show it and the byte check can compare it with a fresh render. `null` = no hints (the default).
411
+ * @param {boolean} [opts.carryNote=false] THE CARRY NOTE (src/carrynote.js): the step/fix worker is handed a facts-only note of what earlier
412
+ * workers of this run looked at, searched and changed, after the handoff note. The caller reads the switch once; `false` builds no store
413
+ * and leaves the worker prompt byte-identical. One `carry-note` spine record (counts only) per note handed.
411
414
  * @returns {Promise<string>} 'green' | 'already-green' | 'escalated' | 'plan-red' |
412
415
  * 'check-red' | 'close-red' | 'close-unsupported' | 'recipe-stale' | 'pricing-red' |
413
416
  * 'branch-red' | 'cap-halt' | 'wall-halt' | 'stopped' | 'provider-red' | 'interpreter-red' |
414
417
  * 'step-stalled' | 'hitl-pause' | 'hitl-decision-red' | `step-red:<id>`
415
418
  */
416
- export function runPlan(job: any, { workdir, provider, nativeProvider, providerFor, judgeProvider, judgeModel, rates, judgeRates, emit, remainingUsd, isUnpriced, spendComplete, capRuns, strikeLimit, closeTimeoutMs, closeDir, maxStepRounds, layerRoot, readShim, scout, scoutRounds, bridge, now, priorWallMs, resumeSeed, resumeGrades, resumeReplans, resumeBranch, humanRuling, heldRuling, priorSpentUsd, reviewDoor, doorRerun, resumable, stopFile, learnHints }: {
419
+ export function runPlan(job: any, { workdir, provider, nativeProvider, providerFor, judgeProvider, judgeModel, rates, judgeRates, emit, remainingUsd, isUnpriced, spendComplete, capRuns, strikeLimit, closeTimeoutMs, closeDir, maxStepRounds, layerRoot, readShim, scout, scoutRounds, bridge, now, priorWallMs, resumeSeed, resumeGrades, resumeReplans, resumeBranch, humanRuling, heldRuling, priorSpentUsd, reviewDoor, doorRerun, resumable, stopFile, learnHints, carryNote }: {
417
420
  workdir: string;
418
421
  provider: any;
419
422
  nativeProvider?: ((o: {
@@ -481,6 +484,7 @@ export function runPlan(job: any, { workdir, provider, nativeProvider, providerF
481
484
  text: string;
482
485
  ids: string[];
483
486
  } | null | undefined;
487
+ carryNote?: boolean | undefined;
484
488
  }): Promise<string>;
485
489
  export { rateSourceFields };
486
490
  /**
package/types/replay.d.ts CHANGED
@@ -197,6 +197,7 @@ export function replayRun(spineEvents: any[], auditEvents?: any[], { runId, audi
197
197
  iteration: any;
198
198
  startSeq: any;
199
199
  endSeq: any;
200
+ rounds: number;
200
201
  startTs: number | null;
201
202
  endTs: number | null;
202
203
  } | null;
package/types/run.d.ts CHANGED
@@ -200,6 +200,9 @@
200
200
  * round-boundary seam (where the money cap binds) and ends the leg `stopped`. `null` = no stop surface.
201
201
  * @param {{text: string, ids: string[]}|null} [opts.learnHints=null] cross-run learnings for the PLANNER only (the draft and the
202
202
  * first replan); forwarded verbatim to the plan flow, which records what it handed over as a `learnings` spine record.
203
+ * @param {boolean} [opts.carryNote=false] THE CARRY NOTE (src/carrynote.js): hand each step/fix worker a facts-only note of what earlier
204
+ * workers of this run looked at, searched and changed. The caller reads the one switch (`carryNote` in config.json, src/carrystore.js
205
+ * `carryNoteOn`) once; the library default is off, exactly like `learnHints`. Forwarded verbatim to the plan flow.
203
206
  * @returns {Promise<string>} outcome: 'green' | 'already-green' | 'escalated' |
204
207
  * 'unapproved-spec' | 'job-red' | 'smoke-red' | 'plan-red' | 'check-red' |
205
208
  * 'close-red' | 'close-unsupported' | 'recipe-stale' | 'branch-red' | 'pricing-red' | 'provider-red' |
@@ -214,7 +217,7 @@
214
217
  * deliberately NOT in the resumable/checkpoint set (`src/reuse.js`) — an
215
218
  * unknown in-flight state is not a known-safe resume point.
216
219
  */
217
- export function runJob(rawSpec: object | string, { approvals, workdir, provider, nativeProvider, providerFor, judgeProvider, judgeModel, rates, judgeRates, emit, capRuns, strikeLimit, shellCapUsd, closeTimeoutMs, closeDir, layerRoot, readShim, scout, bridge, draftSpentUsd, draftSpendComplete, priorSpentUsd, priorSpendComplete, priorWallMs, resumeSeed, resumeGrades, resumeReplans, resumeBranch, humanRuling, heldRuling, reviewDoor, doorRerun, resumable, stopFile, learnHints }: {
220
+ export function runJob(rawSpec: object | string, { approvals, workdir, provider, nativeProvider, providerFor, judgeProvider, judgeModel, rates, judgeRates, emit, capRuns, strikeLimit, shellCapUsd, closeTimeoutMs, closeDir, layerRoot, readShim, scout, bridge, draftSpentUsd, draftSpendComplete, priorSpentUsd, priorSpendComplete, priorWallMs, resumeSeed, resumeGrades, resumeReplans, resumeBranch, humanRuling, heldRuling, reviewDoor, doorRerun, resumable, stopFile, learnHints, carryNote }: {
218
221
  approvals: unknown;
219
222
  workdir: string;
220
223
  provider: any;
@@ -281,6 +284,7 @@ export function runJob(rawSpec: object | string, { approvals, workdir, provider,
281
284
  text: string;
282
285
  ids: string[];
283
286
  } | null | undefined;
287
+ carryNote?: boolean | undefined;
284
288
  }): Promise<string>;
285
289
  /** @typedef {{code: string, path: string, detail?: string}} Red */
286
290
  /**
package/types/tools.d.ts CHANGED
@@ -269,6 +269,14 @@ export function toolAction(name: string, args: any, workdir?: string): {
269
269
  args: any;
270
270
  path?: undefined;
271
271
  };
272
+ export function gatedShellOptions(gate: {
273
+ allows: (action: any) => Promise<boolean>;
274
+ }, workdir: string): {
275
+ noFollowSymlinks: boolean;
276
+ canRead: (p: string, { tool }: {
277
+ tool: string;
278
+ }) => Promise<boolean>;
279
+ };
272
280
  /**
273
281
  * litectx recall hit — body present only with `{body: true}`
274
282
  */