bareloop 0.52.0 → 0.54.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.
package/src/planrun.js CHANGED
@@ -27,7 +27,7 @@ import { join, resolve, relative } from 'node:path';
27
27
  import { Gate } from 'bareguard';
28
28
  import { LiteCtx } from 'litectx';
29
29
  import { runClose, runStages, ralph, CLOSE_FAULTS, boundGap } from './ralph.js';
30
- import { validatePlan, legalScopes, closeStagesOf } from './plan.js';
30
+ import { validatePlan, pairEditGrant, legalScopes, closeStagesOf } from './plan.js';
31
31
  import { WRITE_VERBS, EXIT_TYPES, MAX_EXITS_PER_STEP, MAX_PLAN_STEPS, MAX_SCOPE_MENU, RETRIEVAL_PAIR, EXIT_EXAMPLE } from './plan.js';
32
32
  import { snapshotScope, evalExits, CHECK_GAP_MAX } from './exits.js';
33
33
  import { createRoot } from './root.js';
@@ -35,11 +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, gatedShellOptions, PERSONA_TOOLS, strategyFor } from './tools.js';
38
+ import { TOOL_BY_VERB, CTX_TOOLS, createCtxTools, toolAction, gatedShellOptions, trackedAtSeedGuard, 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';
42
41
  import { createCarryStore } from './carrystore.js';
42
+ import { buildSeedNote } from './seednote.js';
43
43
  import { globToPrefix, redactSecrets, SECRET_PATTERNS } from './validate.js';
44
44
  import { startAttemptDiff } from './attemptdiff.js';
45
45
  import { validateBridge, loadGate, newestEligibleVersion, reuseEligibility, quarantinesCredit, QUARANTINED_CODE } from './bridges.js';
@@ -49,7 +49,7 @@ import { workerThinkingMode, thinkingCallOptions } from './thinking.js';
49
49
  export { rateSourceFields };
50
50
  import { createClock, isWallTimeout } from './clock.js';
51
51
  import { isDeclaredClose, runDeclaredStages, validateCloseDecl, closeGrade, HUMAN_PAUSE, HITL_PAUSE, HITL_DECISION_RED } from './declaredclose.js';
52
- import { inputLabelsOf, outputJudgedRecords } from './rubricstep.js';
52
+ import { inputLabelsOf, outputJudgedRecords, STEP_DIR } from './rubricstep.js';
53
53
  import {
54
54
  seedAtHead, seedListing, changedSet, GAP_TRIM_MARKER, GATE_AUDIT_FILE, ARBITER_BOOK_STORES,
55
55
  HUMAN_KIND, HUMAN_DECISIONS, normalizeHumanRuling, resolveHumanRuling,
@@ -307,7 +307,7 @@ const MONEY_MIN = 0.001;
307
307
  */
308
308
  const VARIANCE_THRESHOLD = 0.5;
309
309
 
310
- /** @typedef {Error & {category?: string, lib?: string}} CategorizedError */
310
+ /** @typedef {Error & {category?: string, lib?: string, badCall?: {kind: string, tool: string|null, param?: string, expected?: string, got?: string}}} CategorizedError */
311
311
 
312
312
  /**
313
313
  * The materials block: what the run has to spend, as a BALANCE and nothing else.
@@ -352,6 +352,12 @@ function hintsBlock(text) {
352
352
  return `\n${text}\n`;
353
353
  }
354
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
+
355
361
  /**
356
362
  * MODULE 8 — the signer's words, when this leg is a RERUN taken at a previous run's
357
363
  * review door (PRD v1.71 §3.4: *"redo/rerun comes with new authoring"*).
@@ -553,6 +559,10 @@ export const FORBIDDEN_WRITE_SEGMENT_PATTERN = /"path":"(?:(?:[^"\\]|\\.)*\/)?(?
553
559
  * shipped path routinely rides through.
554
560
  */
555
561
  export const BOUND_REASON_MAX = 200;
562
+ /** the one message a text-only worker ending is continued with (once per ask, no toolChoice) */
563
+ export const TEXT_ONLY_NUDGE = 'You ended without writing any file. Make the change now with your write or edit tool; do not reply in text.';
564
+ /** the stored text-only ending is capped here (report-only record, masked first) */
565
+ export const TEXT_ONLY_MAX = 2000;
556
566
 
557
567
  /** the recorded reason for a step attempt whose round was cut at the output cap (F122 2A b) */
558
568
  export const TRUNCATED_REASON = 'output cut at the token limit (max_tokens)';
@@ -561,6 +571,55 @@ const REPLAN_CUT_RED = 'Your previous answer was cut off at its length limit bef
561
571
  /** the plain sentence for a replan answer cut off at its length limit (hamr 2026-10-16, run mv9gm796) */
562
572
  export const REPLAN_CUT_WORDS = 'The replan answer was cut off at its length limit, so no new plan came back.';
563
573
 
574
+ /**
575
+ * @typedef {{ kind: string, tool: string|null, param?: string, expected?: string, got?: string, argBytes?: number, parsed?: boolean, hasAppend: boolean, round: number|null }} BadCallFact
576
+ * @typedef {{ calls: BadCallFact[], cutOff: {outputTokens: number|null, reasoningTokens: number|null, maxTokensRequested: number|null}|null }} BadCallFacts
577
+ * bare-agent's STRUCTURED `badCalls`/`cutOff` for one attempt (BA-29); the only input of the two note sentences below
578
+ */
579
+
580
+ /** a cut call at least this many bytes long is the reason the round hit the cap: the note teaches `append` (a bareloop choice, not bare-agent's) */
581
+ export const CUT_LARGE_ARG_BYTES = 8000;
582
+ /** a cut round whose reasoning tokens are more than this share of its output tokens was spent thinking, not writing */
583
+ export const CUT_REASONING_SHARE = 0.5;
584
+
585
+ /**
586
+ * F266 — what to add after the frozen cut-off sentence, from `cutOff`/`badCalls` fields only (never from
587
+ * the `detail` prose, BA-26). A large cut write that has an `append` option: write in parts. Reasoning
588
+ * dominating the cut round: decide sooner. Anything else known-or-unknown adds nothing.
589
+ * @param {BadCallFacts|undefined|null} bad
590
+ * @returns {string} '' or a sentence starting with a space
591
+ */
592
+ function cutSentence(bad) {
593
+ if (!bad) return '';
594
+ const cut = bad.calls.find((c) => c.kind === 'cut-off');
595
+ if (cut && cut.hasAppend && typeof cut.argBytes === 'number' && cut.argBytes >= CUT_LARGE_ARG_BYTES) {
596
+ return ` The call that was cut was ${cut.tool ?? 'a write'}, about ${cut.argBytes} bytes. Write that file in parts: send the first part, then add each next part with append:true.`;
597
+ }
598
+ const co = bad.cutOff;
599
+ if (co && typeof co.reasoningTokens === 'number' && typeof co.outputTokens === 'number' && co.outputTokens > 0
600
+ && co.reasoningTokens / co.outputTokens > CUT_REASONING_SHARE) {
601
+ return ` Most of that output (${co.reasoningTokens} of ${co.outputTokens} tokens) was reasoning, before the call was finished. Decide sooner: make the change with a shorter call.`;
602
+ }
603
+ return '';
604
+ }
605
+
606
+ /**
607
+ * F265 — a refused tool argument (`checkArgs`): say what was wrong, from the structured `kind/param/expected/got`.
608
+ * An object or array sent where a string was declared is the JSON-as-object case: send JSON as text.
609
+ * @param {BadCallFacts|undefined|null} bad
610
+ * @returns {string} '' or a sentence starting with a space
611
+ */
612
+ function badCallSentence(bad) {
613
+ const c = bad?.calls.find((x) => x.kind === 'arg-type' || x.kind === 'arg-missing');
614
+ if (!c || !c.param) return '';
615
+ const where = `${c.tool ?? 'a tool'} ${c.param}`;
616
+ if (c.kind === 'arg-missing') return ` A tool call was refused: ${where} was missing.`;
617
+ if (c.expected === 'string' && (c.got === 'object' || c.got === 'array')) {
618
+ return ` A tool call was refused: ${where} arrived as a JSON ${c.got}, not text. Send JSON as text: encode it as one string.`;
619
+ }
620
+ return ` A tool call was refused: ${where} must be ${c.expected ?? 'the declared type'}, got ${c.got ?? 'something else'}.`;
621
+ }
622
+
564
623
  /**
565
624
  * What the NEXT attempt is told about the bound that cut the previous one.
566
625
  *
@@ -587,19 +646,20 @@ export const REPLAN_CUT_WORDS = 'The replan answer was cut off at its length lim
587
646
  * and announces the trim with the repo's ONE marker rather than a second spelling
588
647
  * of "this text was cut" (F90.2).
589
648
  *
590
- * @param {{iteration?: number|string|undefined, cause: string, reason: string|null}|null|undefined} bounded
649
+ * @param {{iteration?: number|string|undefined, cause: string, reason: string|null, bad?: BadCallFacts|null}|null|undefined} bounded
591
650
  * the previous attempt's bound state, or nullish when it was not bounded
592
651
  * @param {number} rounds the step's round bound, as quoted by the frozen sentence
593
652
  * @returns {string|null} the note, or null when there is nothing to say
594
653
  */
595
654
  export function boundedNote(bounded, rounds) {
596
655
  if (!bounded) return null;
656
+ const bad = badCallSentence(bounded.bad);
597
657
  if (bounded.cause === 'truncated') {
598
- return `Your previous attempt was CUT OFF: ${TRUNCATED_REASON}. That response was discarded.`;
658
+ return `Your previous attempt was CUT OFF: ${TRUNCATED_REASON}. That response was discarded.${cutSentence(bounded.bad)}${bad}`;
599
659
  }
600
660
  if (bounded.cause !== 'denied') {
601
661
  return `Your previous attempt was CUT OFF after ${rounds} tool rounds. `
602
- + 'Reading is bounded; writing is not. Form a hypothesis EARLY and make the change.';
662
+ + `Reading is bounded; writing is not. Form a hypothesis EARLY and make the change.${bad}`;
603
663
  }
604
664
  const raw = String(bounded.reason ?? '');
605
665
  const shown = raw.length > BOUND_REASON_MAX
@@ -607,7 +667,7 @@ export function boundedNote(bounded, rounds) {
607
667
  : raw;
608
668
  return 'Your previous attempt was CUT OFF by the gate: it denied consecutive tool calls '
609
669
  + `until the streak guard ended the attempt. The gate recorded: ${shown}. `
610
- + 'The round budget was not what stopped you — repeating a denied call ends this attempt the same way.';
670
+ + `The round budget was not what stopped you — repeating a denied call ends this attempt the same way.${bad}`;
611
671
  }
612
672
 
613
673
  /**
@@ -648,8 +708,9 @@ export function boundedNote(bounded, rounds) {
648
708
  * byte-identically to the pre-shim prompt.
649
709
  * @param {string|null} [hints] the cross-run learnings block (src/learn.js `renderHints`), verbatim; null/empty
650
710
  * renders byte-identically to the prompt without it. Only ever passed for the draft and the first replan.
711
+ * @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.
651
712
  */
652
- export function planPrompt(job, scoutBlob, reds, maxStepRounds, failure, scopes, materials, startingDraft = null, checkFacts = {}, doorNote = null, readShim = false, hints = null) {
713
+ export function planPrompt(job, scoutBlob, reds, maxStepRounds, failure, scopes, materials, startingDraft = null, checkFacts = {}, doorNote = null, readShim = false, hints = null, seedNote = null) {
653
714
  const scopeMenu = Array.isArray(scopes) && scopes.length ? scopes : legalScopes(job.writeScope ?? []);
654
715
  const ceiling = Array.isArray(job.tools) ? job.tools : [...TOOL_MENU];
655
716
  // The shape-lottery laws, stated where the check menu is offered (the mailbox
@@ -740,7 +801,7 @@ ${scopeMenu.map((s) => ` ${JSON.stringify(s)}`).join('\n')}
740
801
 
741
802
  Goal:
742
803
  ${job.goal}
743
- ${doorNoteBlock(doorNote)}${materialsBlock(materials)}${hintsBlock(hints)}
804
+ ${doorNoteBlock(doorNote)}${materialsBlock(materials)}${hintsBlock(hints)}${seedNoteBlock(seedNote)}
744
805
  Repository survey (from a read-only scout):
745
806
  ${scoutBlob || '(no scout notes)'}`;
746
807
  let p = doc;
@@ -1003,15 +1064,12 @@ ${scoutBlob || '(no scout notes)'}`;
1003
1064
  * run start from the ledger as it stood). Handed to the PLANNER only: the first draft and the FIRST replan. No worker ever
1004
1065
  * receives it, and a later replan gets nothing. Each injection is recorded on the spine as a `learnings` record (the exact
1005
1066
  * 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.
1009
1067
  * @returns {Promise<string>} 'green' | 'already-green' | 'escalated' | 'plan-red' |
1010
1068
  * 'check-red' | 'close-red' | 'close-unsupported' | 'recipe-stale' | 'pricing-red' |
1011
1069
  * 'branch-red' | 'cap-halt' | 'wall-halt' | 'stopped' | 'provider-red' | 'interpreter-red' |
1012
1070
  * 'step-stalled' | 'hitl-pause' | 'hitl-decision-red' | `step-red:<id>`
1013
1071
  */
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 }) {
1072
+ 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 }) {
1015
1073
  // MEMORY-CACHE: what the read shim (src/readshim.js) saved THIS run, summed across
1016
1074
  // every mkWorker's own shim instance (scout, drafter, each step's worker, the fix
1017
1075
  // worker) — one accumulator closed over by all of them, because the shim's ledger
@@ -1028,13 +1086,17 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
1028
1086
  // would be wrong and would look fine). Only the guard runs here; the flag itself
1029
1087
  // is still threaded onward as written.
1030
1088
  readShimArm(readShim);
1031
- // THE HANDOFF NOTE (src/handoff.js): the paths earlier asks of THIS run read. In memory only, so a resumed leg starts empty.
1032
- // The switch is the signed spec's `handoffNote` (absent = on, only `false` turns it off).
1033
- const handoffOn = job.handoffNote !== false;
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;
1089
+ // THE SEED NOTE (src/seednote.js): the signed spec's `seedNote`; absent = ON, only `false` turns it off (like the legacy `handoffNote`).
1090
+ const seedNoteOn = job.seedNote !== false;
1091
+ // 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.
1092
+ const readMapOn = job.readMap === true;
1093
+ if (readMapOn && !readShimArm(readShim).on) emit('read-map-skip', { reason: 'shim-off' });
1094
+ /** @type {{ text: string, body: string, stages: string[] }|null} built once, after the preflight loop */
1095
+ let seedNote = null;
1096
+ // THE CARRY NOTE (src/carrynote.js, src/carrystore.js): facts the earlier asks of THIS run produced, files read with their function
1097
+ // line ranges included (the old separate handoff note is folded in). ALWAYS ON, no switch (hamr 2026-11-01); a legacy spec's
1098
+ // `handoffNote` and the retired `carryNote` config key have no effect. One `carry-note` spine record (counts only) per note handed.
1099
+ const carry = createCarryStore({ workdir, emit, strikeLimit, resume: resumeBranch !== null && resumeBranch !== undefined });
1038
1100
  // The scout switch's guard, same class and same door: a mis-typed value
1039
1101
  // coerced by truthiness would run the scout under an "off" label (or skip it
1040
1102
  // under an "on" one) and no reading of the results afterwards could recover
@@ -2163,6 +2225,10 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2163
2225
  * is still the goal the plan exists to flip).
2164
2226
  * @type {string[]} */
2165
2227
  const seedRed = [];
2228
+ // THE SEED NOTE (experimental, default off): the red-at-seed verdicts, with their stage's declared kind, for src/seednote.js.
2229
+ // The kind is read off the signed close's own stage (a command close has none), never matched on a stage name.
2230
+ /** @type {{stage: string|null|undefined, kind: string|null|undefined, gap: string|null|undefined}[]} */
2231
+ const seedReds = [];
2166
2232
  emit('check-menu', {
2167
2233
  offered: menu.map((m) => m.name),
2168
2234
  ...(menu.length < stagedClose.length
@@ -2173,6 +2239,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2173
2239
  const v = await runCloseStages(m.run);
2174
2240
  if (v.verdict === 'needs_revision') {
2175
2241
  seedRed.push(m.name);
2242
+ if (seedNoteOn) seedReds.push({ stage: v.stage, kind: stagedClose.find((/** @type {any} */ s2) => s2?.name === v.stage)?.kind, gap: v.gap });
2176
2243
  // …and the preflight grade is a READING, for the same reason the precheck one
2177
2244
  // above is: it is the seed the run's work is measured against. The precheck
2178
2245
  // only ever reds at the close's FIRST failing stage (first-red-wins), so on
@@ -2198,6 +2265,10 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2198
2265
  }
2199
2266
  }
2200
2267
 
2268
+ if (seedNoteOn) seedNote = buildSeedNote(seedReds, scrub);
2269
+ // every step/fix worker gets it through the carry memo (earlier failures, `at start`); the planner has its own block
2270
+ if (seedNote) carry?.setStartFailure(seedNote.body);
2271
+
2201
2272
  // ── 0c, COLD. The seam and both halves of its placement ruling are stated
2202
2273
  // above, where a RESUME reaches it; this is where a run that is NOT resuming
2203
2274
  // does — after the $0 precheck and preflight, so an already-green tree has
@@ -2207,6 +2278,24 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2207
2278
  if (stop !== null) return stop;
2208
2279
  }
2209
2280
 
2281
+ // ── BA-30's `guardPath` (F272/F276): "tracked at seed" is HEAD at THIS LEG's start, read from
2282
+ // the WORKER tree (`workdir`, never the source repo) once the work branch is prepared — a
2283
+ // resumed leg therefore counts what earlier legs committed as tracked. It is read for EVERY job,
2284
+ // declared or not (a command or rubric close has no `declaredCtx`). A fault is a stop, never an
2285
+ // unguarded run: a write guard that silently fails open is the failure it exists to prevent.
2286
+ const guardSeed = await seedAtHead(workdir);
2287
+ const guardListing = guardSeed.stop === null ? await seedListing(workdir, guardSeed.seedRef) : null;
2288
+ if (guardSeed.stop !== null || guardListing === null || guardListing.stop !== null) {
2289
+ emit('escalation', {
2290
+ category: 'interpreter-red', decisionReady: true,
2291
+ decision: 'The write guard needs the files tracked at the start of this leg, and they could not be read. Nothing was spent.',
2292
+ options: ['check the repository is a git checkout with at least one commit', 'retry the run', 'abandon the run'],
2293
+ detail: scrub(String(guardSeed.stop ?? guardListing?.stop ?? '')),
2294
+ });
2295
+ return 'interpreter-red';
2296
+ }
2297
+ const shrinkGuardPath = await trackedAtSeedGuard(workdir, guardListing.files);
2298
+
2210
2299
  const lc = new LiteCtx({ root: workdir });
2211
2300
  const ceiling = Array.isArray(job.tools) ? job.tools : [...TOOL_MENU];
2212
2301
  const fencePrefixes = job.writeScope.map((/** @type {string} */ g) => resolve(workdir, globToPrefix(g)));
@@ -2482,7 +2571,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2482
2571
  * `iteration` mirrors `roundIteration` exactly, undefined included: the bound
2483
2572
  * cannot know a label the run never set, and inventing one here would be the
2484
2573
  * only place in this file that claims to.
2485
- * @type {{iteration: number|string|undefined, cause: 'rounds'|'wall'|'denied'|'truncated', reason: string|null}|undefined}
2574
+ * @type {{iteration: number|string|undefined, cause: 'rounds'|'wall'|'denied'|'truncated', reason: string|null, bad?: BadCallFacts|null}|undefined}
2486
2575
  */
2487
2576
  let attemptBounded;
2488
2577
  /**
@@ -2503,7 +2592,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2503
2592
  }
2504
2593
  };
2505
2594
  const grantedNames = new Set(granted.map((v) => /** @type {Record<string, string>} */ (TOOL_BY_VERB)[v]));
2506
- const shell = createShellTools(gatedShellOptions(gate, workdir)).tools.filter((/** @type {{name: string}} */ t) => grantedNames.has(t.name));
2595
+ const shell = createShellTools(gatedShellOptions(gate, workdir, shrinkGuardPath)).tools.filter((/** @type {{name: string}} */ t) => grantedNames.has(t.name));
2507
2596
  // THE READ SHIM (arm-gated, default OFF): a per-worker delivery ledger over the
2508
2597
  // read tool — cap at READ_SHIM_CAP, pointer only once the CURRENT content has been
2509
2598
  // delivered whole, next-unseen-slice otherwise, diff on a changed re-read. WHICH of
@@ -2537,6 +2626,8 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2537
2626
  else memoryCacheCounts.capped++;
2538
2627
  memoryCacheCounts.bytesWithheld += bytes;
2539
2628
  },
2629
+ // The first-read map (experimental, off unless the spec says `readMap: true`): this worker's index, and whether it holds ctx_get.
2630
+ 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,
2540
2631
  });
2541
2632
  const rdTool = shell.find((/** @type {{name: string}} */ t) => t.name === TOOL_BY_VERB.read);
2542
2633
  // F48: on native, bound shell_read below the CLI's tool-result display cap and hand back a
@@ -2579,34 +2670,17 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2579
2670
  // sampler all live here) for its full duration: measured 4.4s at 4.5% liveness on a
2580
2671
  // 155-file force pass. With yield:true the worst single block measured 189–252ms (n=4),
2581
2672
  // below anything a second/minute-scale timer can perceive. Store output is byte-identical.
2582
- if (ctx.length) await lc.index({ yield: true });
2673
+ // …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.
2674
+ if (ctx.length || readMapOn) await lc.index({ yield: true });
2583
2675
  const toolDefs = [...shell, ...ctx];
2584
- // The handoff note: record what each ask READS (the allowed read-class calls), hand the next step/fix ask the map.
2585
- // Scout and drafter asks feed the store but are never given a note.
2586
- /** @type {Set<string>} */
2587
- let askReads = new Set();
2588
- if (handoffOn) trackReads(toolDefs, [TOOL_BY_VERB.read, TOOL_BY_VERB.get], (a) => askReads.add(a), workdir);
2589
- /** @param {(prompt: string, defs?: any) => Promise<any>} inner */
2590
- const withHandoff = (inner) => (!handoffOn ? inner : async (/** @type {string} */ prompt, /** @type {any} */ defs) => {
2591
- askReads = new Set();
2592
- let p = prompt;
2593
- if (phase === 'fix' || phase.startsWith('step:')) {
2594
- // The index is incremental: refreshing it here is what keeps the symbol ranges true to the files as they now are.
2595
- try { if (ctx.length) await lc.index({ yield: true }); } catch { /* the map falls back to line counts */ }
2596
- const note = handoff.render({ getNode: (rel) => lc.getNode(rel) });
2597
- if (note.text) {
2598
- p = `${prompt}\n\n${note.text}`;
2599
- emit('handoff-note', { phase, iteration: roundIteration, chars: note.text.length, paths: note.paths });
2600
- }
2601
- }
2602
- try { return await inner(p, defs); } finally { handoff.absorb(askReads); }
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.
2676
+ // The carry note: records what each ask's read-class tools returned (a summary, never content) and hands the next
2677
+ // step/fix ask the facts. Scout and drafter asks feed the store but are never given a note.
2606
2678
  if (carry) carry.wrapTools(toolDefs);
2607
2679
  /** @param {(prompt: string, defs?: any) => Promise<any>} inner */
2608
2680
  const withCarry = (inner) => (!carry ? inner : async (/** @type {string} */ prompt, /** @type {any} */ defs) => {
2609
- const text = await carry.beginAsk({ phase, iteration: roundIteration, prompt });
2681
+ // The index is incremental: refreshing it here keeps the function ranges true to the files as they now are.
2682
+ if (phase === 'fix' || phase.startsWith('step:')) { try { if (ctx.length) await lc.index({ yield: true }); } catch { /* ranges are left out */ } }
2683
+ const text = await carry.beginAsk({ phase, iteration: roundIteration, prompt, getNode: (rel) => lc.getNode(rel) });
2610
2684
  try { return await inner(text ? `${prompt}\n\n${text}` : prompt, defs); } finally { carry.endAsk({ bounded: attemptBounded, iteration: roundIteration, rounds: attemptRounds }); }
2611
2685
  });
2612
2686
  // F19 per VERB (P, corrected 2026-07-31): a strategy SENTENCE rides only with
@@ -2706,7 +2780,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2706
2780
  }
2707
2781
  return r;
2708
2782
  };
2709
- return { ask: withHandoff(withCarry(ask)), askFrom, workerWrites, writeCount, setIteration, wasBounded: () => attemptBounded };
2783
+ return { ask: withCarry(ask), askFrom, workerWrites, writeCount, setIteration, wasBounded: () => attemptBounded };
2710
2784
  }
2711
2785
 
2712
2786
  // ── LOOP path: the injected provider (anthropic-api and every other
@@ -2848,7 +2922,8 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2848
2922
  }
2849
2923
  return onLlmResult(arg);
2850
2924
  };
2851
- self = new Loop({ provider: loopProvider, system, policy, onLlmResult: metered, onToolResult: onToolOutcome, ...(rates ? { rates } : {}) });
2925
+ // BA-29: checkArgs refuses a wrong-typed or missing top-level tool argument BEFORE the tool runs (F265: an object where a string was declared)
2926
+ self = new Loop({ provider: loopProvider, system, policy, checkArgs: true, onLlmResult: metered, onToolResult: onToolOutcome, ...(rates ? { rates } : {}) });
2852
2927
  return self;
2853
2928
  };
2854
2929
  /**
@@ -2903,20 +2978,56 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2903
2978
  throw categorize(e).err;
2904
2979
  }
2905
2980
  };
2906
- const ask = async (prompt, defs = toolDefs) => {
2907
- let r;
2908
- // A fresh Loop = a fresh transcript: the read shim's delivered-ledger resets with it, or a
2909
- // later attempt's re-read is answered with a pointer to bytes its model never saw (F252).
2910
- // askFrom (a continuation of a prior transcript) deliberately does NOT reset.
2911
- shim.reset();
2912
- const thinkOpts = thinkingForCall();
2913
- try {
2914
- r = await stallWatch.watch((gen) => newLoop(gen).run([{ role: 'user', content: prompt }], defs, { cacheMessages: true, maxTokens: 32000, ...callBounds(), ...thinkOpts }));
2915
- throwIfStopped();
2916
- noteThinkingStatus(r);
2917
- } catch (e) {
2918
- throw categorize(e).err;
2981
+ /**
2982
+ * BA-29 (F265/F266) — record what the model got wrong in ONE call, from bare-agent's STRUCTURED fields only
2983
+ * (`r.badCalls`, `r.cutOff`, `r.malformedToolCall`; the `detail` prose is never read, the BA-26 anti-pattern).
2984
+ * Two spine records: `worker-malformed-tool-call` (F184, now also on a cut round) and `worker-bad-calls`
2985
+ * (kind, tool, param, expected, got, size, hasAppend, round; raw arguments never exist upstream). Returns the
2986
+ * facts the next-attempt note is built from (`boundedNote`), or null when the round had none.
2987
+ * @param {any} r a Loop.run() result
2988
+ * @returns {BadCallFacts|null}
2989
+ */
2990
+ const noteBadCalls = (r) => {
2991
+ if (r.malformedToolCall) {
2992
+ const rawErr = String(r.malformedToolCall.error ?? '');
2993
+ const scrubbedErr = scrub(rawErr);
2994
+ const shownErr = scrubbedErr.length > BOUND_REASON_MAX
2995
+ ? `${scrubbedErr.slice(0, BOUND_REASON_MAX)} [${GAP_TRIM_MARKER} ${scrubbedErr.length - BOUND_REASON_MAX} of ${scrubbedErr.length} characters withheld — the cap is ${BOUND_REASON_MAX}]`
2996
+ : scrubbedErr;
2997
+ emit('worker-malformed-tool-call', {
2998
+ phase, iteration: roundIteration, name: scrub(String(r.malformedToolCall.name ?? '')), error: shownErr,
2999
+ });
2919
3000
  }
3001
+ const calls = Array.isArray(r.badCalls) ? r.badCalls : [];
3002
+ if (calls.length === 0) return null;
3003
+ /** @type {BadCallFacts} */
3004
+ const facts = {
3005
+ calls: calls.map((/** @type {any} */ c) => ({
3006
+ kind: String(c.kind),
3007
+ tool: typeof c.tool === 'string' ? scrub(c.tool) : null,
3008
+ ...(typeof c.param === 'string' ? { param: scrub(c.param) } : {}),
3009
+ ...(typeof c.expected === 'string' ? { expected: c.expected } : {}),
3010
+ ...(typeof c.got === 'string' ? { got: c.got } : {}),
3011
+ ...(typeof c.argBytes === 'number' ? { argBytes: c.argBytes } : {}),
3012
+ ...(typeof c.parsed === 'boolean' ? { parsed: c.parsed } : {}),
3013
+ hasAppend: c.hasAppend === true,
3014
+ round: typeof c.round === 'number' ? c.round : null,
3015
+ })),
3016
+ cutOff: r.cutOff && typeof r.cutOff === 'object'
3017
+ ? { outputTokens: r.cutOff.outputTokens ?? null, reasoningTokens: r.cutOff.reasoningTokens ?? null, maxTokensRequested: r.cutOff.maxTokensRequested ?? null }
3018
+ : null,
3019
+ };
3020
+ emit('worker-bad-calls', { phase, iteration: roundIteration, calls: facts.calls, ...(facts.cutOff ? { cutOff: facts.cutOff } : {}) });
3021
+ return facts;
3022
+ };
3023
+ /** the post-round taxonomy of one worker Loop result (bad calls, bounds, error map); returns r or throws — shared by an ask's first round and its nudge round @param {any} r */
3024
+ const settle = (r) => {
3025
+ // BA-29 (F265/F266): what the model got wrong is read off bare-agent's structured `badCalls`/`cutOff`
3026
+ // (never off prose) and recorded BEFORE any branch below returns or throws — a cut round used to
3027
+ // return first and lose both this and the malformed marker.
3028
+ const badFacts = noteBadCalls(r);
3029
+ // a round/wall bound was set inside the Loop callbacks, before the facts existed: attach them to THIS attempt's bound
3030
+ if (badFacts && attemptBounded && attemptBounded.iteration === roundIteration && !attemptBounded.bad) attemptBounded = { ...attemptBounded, bad: badFacts };
2920
3031
  // BA-11's deny streak is a BOUNDED ATTEMPT, not a terminal. It is the same
2921
3032
  // shape `loop.stop()` has at the round bound thirty lines up: the attempt
2922
3033
  // ran, produced real work, and was cut short by a governance bound doing
@@ -2927,7 +3038,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2927
3038
  // takes the identical lane above — one doctrine, both surfaces.
2928
3039
  if (r.error && r.error.startsWith('denied:')) {
2929
3040
  const reason = scrub(r.error);
2930
- attemptBounded = { iteration: roundIteration, cause: 'denied', reason };
3041
+ attemptBounded = { iteration: roundIteration, cause: 'denied', reason, bad: badFacts };
2931
3042
  emit('attempt-bounded', { phase, iteration: roundIteration, rounds: roundsThisAttempt, cap: attemptRounds, reason });
2932
3043
  return r;
2933
3044
  }
@@ -2940,7 +3051,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2940
3051
  // replan drafter opts in with `truncatedBounded`. Scout and the first draft keep the
2941
3052
  // transport route below (provider-red).
2942
3053
  if (r.error && r.error.startsWith('truncated:') && (phase.startsWith('step:') || phase === 'fix' || truncatedBounded)) {
2943
- attemptBounded = { iteration: roundIteration, cause: 'truncated', reason: TRUNCATED_REASON };
3054
+ attemptBounded = { iteration: roundIteration, cause: 'truncated', reason: TRUNCATED_REASON, bad: badFacts };
2944
3055
  emit('attempt-bounded', { phase, iteration: roundIteration, rounds: roundsThisAttempt, cap: attemptRounds, reason: TRUNCATED_REASON, stopReason: r.stopReason ?? null });
2945
3056
  return r;
2946
3057
  }
@@ -2952,6 +3063,11 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2952
3063
  : r.error.startsWith('truncated:') ? 'provider-red'
2953
3064
  : 'interpreter-red';
2954
3065
  err.lib = 'bare-agent';
3066
+ // F265: a stuck loop of refused arguments says WHICH fault in structured words (the panel renders them); bare-agent's own fields, never prose
3067
+ const refused = badFacts?.calls.find((c) => c.kind === 'arg-type' || c.kind === 'arg-missing');
3068
+ if (refused && r.error.startsWith('stuck:')) {
3069
+ err.badCall = { kind: refused.kind, tool: refused.tool, param: refused.param, ...(refused.expected ? { expected: refused.expected } : {}), ...(refused.got ? { got: refused.got } : {}) };
3070
+ }
2955
3071
  throw err;
2956
3072
  }
2957
3073
  // F184 — bare-agent 0.43.0 (BA-27) returns a malformed final-turn tool
@@ -2968,19 +3084,58 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2968
3084
  // marker before `ask()` returns it unexamined, so a distinct spine
2969
3085
  // record names the transport class here — the same honesty bar
2970
3086
  // F179/F180 set for the authoring path, applied to the worker path.
2971
- if (r.malformedToolCall) {
2972
- const rawErr = String(r.malformedToolCall.error ?? '');
2973
- const scrubbedErr = scrub(rawErr);
2974
- const shownErr = scrubbedErr.length > BOUND_REASON_MAX
2975
- ? `${scrubbedErr.slice(0, BOUND_REASON_MAX)} [${GAP_TRIM_MARKER} ${scrubbedErr.length - BOUND_REASON_MAX} of ${scrubbedErr.length} characters withheld — the cap is ${BOUND_REASON_MAX}]`
2976
- : scrubbedErr;
2977
- emit('worker-malformed-tool-call', {
2978
- phase, iteration: roundIteration, name: scrub(String(r.malformedToolCall.name ?? '')), error: shownErr,
2979
- });
3087
+ return r;
3088
+ };
3089
+ const ask = async (prompt, defs = toolDefs) => {
3090
+ let r;
3091
+ // A fresh Loop = a fresh transcript: the read shim's delivered-ledger resets with it, or a
3092
+ // later attempt's re-read is answered with a pointer to bytes its model never saw (F252).
3093
+ // askFrom (a continuation of a prior transcript) deliberately does NOT reset.
3094
+ shim.reset();
3095
+ const thinkOpts = thinkingForCall();
3096
+ const writesBefore = writeCount();
3097
+ try {
3098
+ r = await stallWatch.watch((gen) => newLoop(gen).run([{ role: 'user', content: prompt }], defs, { cacheMessages: true, maxTokens: 32000, ...callBounds(), ...thinkOpts }));
3099
+ throwIfStopped();
3100
+ noteThinkingStatus(r);
3101
+ } catch (e) {
3102
+ throw categorize(e).err;
3103
+ }
3104
+ r = settle(r);
3105
+ // The text-only ending: a writeable step's (or the fix loop's) ask finished (end_turn) with text and the REAL gate audit holds no allowed
3106
+ // write/edit for it. Continue the SAME conversation (`r.msgs`) ONCE with one code-written message; the round is inside this try, metered by
3107
+ // the same seam, and honours the cap, wall, Stop and the round limit. Read-only steps are never nudged.
3108
+ const writeable = (phase.startsWith('step:') || phase === 'fix') && WRITE_VERBS.some((v) => granted.includes(v));
3109
+ const textOnly = writeable && r.stopReason === 'end_turn' && !r.error && typeof r.text === 'string' && r.text !== '' && writeCount() === writesBefore;
3110
+ if (!textOnly) return r;
3111
+ let lastText = r.text;
3112
+ let nudged = false;
3113
+ let nudgeWrote = false;
3114
+ if (!attemptBounded && !stopHit && !clock.expired() && roundsThisAttempt < attemptRounds && Array.isArray(r.msgs)) {
3115
+ nudged = true;
3116
+ emit('worker-nudge', { phase, iteration: roundIteration, round: roundsThisAttempt });
3117
+ let r2;
3118
+ try {
3119
+ const rest = r.msgs[0]?.role === 'system' ? r.msgs.slice(1) : r.msgs; // same strip as askFrom: the new Loop prepends `system` again
3120
+ r2 = await stallWatch.watch((gen) => newLoop(gen).run([...rest, { role: 'user', content: TEXT_ONLY_NUDGE }], defs, { cacheMessages: true, maxTokens: 32000, ...callBounds(), ...thinkOpts }));
3121
+ throwIfStopped();
3122
+ noteThinkingStatus(r2);
3123
+ } catch (e) {
3124
+ throw categorize(e).err;
3125
+ }
3126
+ r2 = settle(r2);
3127
+ nudgeWrote = writeCount() > writesBefore;
3128
+ if (typeof r2.text === 'string' && r2.text !== '' && !nudgeWrote) lastText = r2.text;
3129
+ r = r2;
2980
3130
  }
3131
+ const shown = scrub(String(lastText));
3132
+ emit('worker-text-only', {
3133
+ phase, iteration: roundIteration, nudged, nudgeWrote,
3134
+ text: shown.length > TEXT_ONLY_MAX ? shown.slice(0, TEXT_ONLY_MAX) : shown, truncated: shown.length > TEXT_ONLY_MAX,
3135
+ });
2981
3136
  return r;
2982
3137
  };
2983
- return { ask: withHandoff(withCarry(ask)), askFrom, workerWrites, writeCount, setIteration, wasBounded: () => attemptBounded };
3138
+ return { ask: withCarry(ask), askFrom, workerWrites, writeCount, setIteration, wasBounded: () => attemptBounded };
2984
3139
  }
2985
3140
 
2986
3141
  /** relay a throw from OUTSIDE ralph (scout/plan drafting/fix) as its honest
@@ -3137,6 +3292,9 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
3137
3292
  // handed (a record, never a verdict), so the Audit can show it and the byte check can compare it with a fresh render.
3138
3293
  const hints = learnHints && learnHints.text && (phase === 'draft' || (phase === 'replan' && replans === 1)) ? learnHints : null;
3139
3294
  if (hints) emit('learnings', { phase, text: hints.text, ids: hints.ids, chars: hints.text.length });
3295
+ // The seed note: the planner's FIRST draft only (and its redrafts). A record of counts and names, never the text.
3296
+ const seedNoteForPlanner = seedNote && phase === 'draft' ? seedNote : null;
3297
+ if (seedNoteForPlanner) emit('seed-note', { to: 'planner', chars: seedNoteForPlanner.text.length, stages: seedNoteForPlanner.stages });
3140
3298
  // D5 — the bridge rides into the FIRST draft phase ONLY. A replan drafts from the
3141
3299
  // RUN'S OWN STATE (what failed, what is left): re-handing the recipe there would
3142
3300
  // answer the replan's question with the material the run just demonstrated does not
@@ -3161,7 +3319,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
3161
3319
  const draftPlan = async (/** @type {any[]|null} */ reds) => {
3162
3320
  drafter.setIteration(reds ? 'redraft' : 'draft');
3163
3321
  replanCut = false;
3164
- const r = await drafter.ask(planPrompt(job, scoutBlob, reds, maxStepRounds, failure, scopeMenu, materials, starting, checkFacts, doorWords?.text ?? null, readShim, hints?.text ?? null), []);
3322
+ 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), []);
3165
3323
  if (phase === 'replan' && typeof r.error === 'string' && r.error.startsWith('truncated:')) {
3166
3324
  replanCut = true;
3167
3325
  return '';
@@ -3240,7 +3398,8 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
3240
3398
  });
3241
3399
  return 'plan-red';
3242
3400
  }
3243
- plan = /** @type {any} */ (pv.plan);
3401
+ // F271 (B2): a write grant is paired with edit when the SIGNED ceiling offers it; the reloaded plan is executed — and recorded — paired
3402
+ plan = /** @type {any} */ (pairEditGrant(pv.plan, job, STEP_DIR));
3244
3403
  // The skip set is a PREFIX match on the plan's own step ids, never a count: a count
3245
3404
  // would skip whatever happens to sit at that index. Steps run strictly sequentially
3246
3405
  // and idx only advances on a satisfied exit, so the dead run's completions ARE a
@@ -3270,7 +3429,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
3270
3429
  for (const r of pv.reds) emit('plan-red', r);
3271
3430
  return 'plan-red';
3272
3431
  }
3273
- plan = /** @type {any} */ (pv.plan);
3432
+ plan = /** @type {any} */ (pairEditGrant(pv.plan, job, STEP_DIR)); // F271 (B2)
3274
3433
  emit('plan-accepted', { plan });
3275
3434
  } catch (e) {
3276
3435
  return relay(e, 'plan');
@@ -3536,6 +3695,8 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
3536
3695
  // results makes the leak inexpressible; scrubbing each consumer makes it
3537
3696
  // something the next consumer has to remember.
3538
3697
  const results = raw.map((r) => (typeof r.detail === 'string' ? { ...r, detail: scrub(r.detail) } : r));
3698
+ // 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)
3699
+ carry?.settleAsk(results.some((r) => r.fault) ? 'unknown' : pass ? 'green' : 'red', results.filter((r) => !r.pass).map((r) => r.detail).join('\n'));
3539
3700
  // 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
3540
3701
  // overwrites the file. The worker is idle between its turn and this judge, so these are the bytes the check read.
3541
3702
  for (const o of await outputJudgedRecords(job.closeDecl, workdir, step.exit)) emit('output-judged', { step: step.id, iteration: iterationNow, ...o });
@@ -3821,7 +3982,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
3821
3982
  planExecuted();
3822
3983
  return 'plan-red';
3823
3984
  }
3824
- plan = /** @type {any} */ (pv.plan);
3985
+ plan = /** @type {any} */ (pairEditGrant(pv.plan, job, STEP_DIR)); // F271 (B2)
3825
3986
  emit('plan-accepted', { plan, phase: 'replan' });
3826
3987
  // the new plan's steps are NOT the old plan's steps — its abandoned greens
3827
3988
  // must not ride forward as this plan's "prior steps' results" (stale, and
@@ -4271,7 +4432,11 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
4271
4432
  // two exhaustion rules are alternatives and never both at once, so the count
4272
4433
  // is not passed — it survives only inside the governor, as the bound for the
4273
4434
  // case the trend instrument is blind.
4274
- middle, judge: async () => judgeClose(), ladder: fixGovernor, emit: emitL, redact: scrub,
4435
+ middle, judge: async () => {
4436
+ const v = await judgeClose();
4437
+ 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
4438
+ return v;
4439
+ }, ladder: fixGovernor, emit: emitL, redact: scrub,
4275
4440
  closeTimeoutMs, cwd: workdir, workerWrites: w.workerWrites, closeDir, phase: 'fix',
4276
4441
  });
4277
4442
  } catch (e) {
package/src/ralph.js CHANGED
@@ -694,6 +694,8 @@ export async function ralph({ middle, close, judge, capRuns, ladder, emit, redac
694
694
  // loop → bare-agent): the ledger prefers the typed field over sniffing
695
695
  // this detail string for library names
696
696
  ...(e && typeof e.lib === 'string' ? { lib: e.lib } : {}),
697
+ // a stuck loop of refused tool arguments names the fault in structured fields (F265) so a reader renders it, never parses `detail`
698
+ ...(e && e.badCall && typeof e.badCall === 'object' ? { badCall: e.badCall } : {}),
697
699
  decision, options, detail: String(e.message || e),
698
700
  });
699
701
  emit('run-end', { outcome: 'escalated', iterations: iteration });