bareloop 0.53.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.
@@ -15,7 +15,7 @@ import { splitReadNotes } from '../pagedropwords.js';
15
15
  import { checksOfClose, signedFactNames, proseNotChecked, lineRules, confirmedGoalOf } from '../rubricstep.js';
16
16
 
17
17
  /** @typedef {{name: string, cls: 'machine check'|'judge'|null}} PlanCheck */
18
- /** @typedef {{n: number, text: string, rule: string, rules: string[], checks: PlanCheck[], refused: string[]}} PlanLine */
18
+ /** @typedef {{n: number, text: string, rule: string, rules: string[], checks: PlanCheck[], refused: string[], always?: string[]}} PlanLine */
19
19
  /** @typedef {{lines: PlanLine[], loose: PlanCheck[], notChecked: string[], readNotes: string[], alwaysOn: string[], older: boolean, goal?: string}} JobPlan */
20
20
 
21
21
  /**
@@ -95,6 +95,11 @@ export function planFromSpec(spec) {
95
95
  for (const line of served) line.checks.push({ name: s.name, cls: s.cls });
96
96
  if (served.length === 0) loose.push({ name: s.name, cls: s.cls });
97
97
  }
98
+ // an always-on guard that the drafter said covers a job line is shown under that line too ("› check · always-on: <guard>")
99
+ for (const g of Array.isArray(spec?.closeDecl?.guardLines) ? spec.closeDecl.guardLines : []) {
100
+ if (!g || typeof g.guard !== 'string' || !Array.isArray(g.lines)) continue;
101
+ for (const line of lines.filter((l) => g.lines.includes(l.n))) (line.always ??= []).push(g.guard);
102
+ }
98
103
  const refused = Array.isArray(spec?.closeDecl?.refused) ? spec.closeDecl.refused : [];
99
104
  for (const r of refused) {
100
105
  const line = lines.find((l) => l.n === r?.line);
@@ -49,7 +49,7 @@ import { chainSpend } from '../ledger.js';
49
49
  import { runBehaviour } from '../behaviour.js';
50
50
  import { SPEND_RECORD_TYPES, floorsFromRecords } from '../ledger.js';
51
51
  import { jobSpecHash, workflowKey } from '../job.js';
52
- import { parseHintBlock, hintsErrorLine } from '../learn.js';
52
+ import { attachMemos, learningsHanded, attachLearnings } from './handed.js';
53
53
  import { confirmProtections } from '../authorflow.js';
54
54
  import { createScheduleDoor } from './schedules.js';
55
55
  import { createStarter } from './schedulestart.js';
@@ -551,6 +551,22 @@ function endedBase(summary, death, o) {
551
551
  const esc = summary.lastEscalation;
552
552
  const cat = typeof esc?.category === 'string' ? esc.category : null;
553
553
 
554
+ // F265: a stuck loop of refused tool arguments (bare-agent `checkArgs`): the engine recorded the fault in structured fields
555
+ // (`badCall`), so the sentence names what the model did instead of the raw code
556
+ const refused = esc?.badCall;
557
+ if (refused && typeof refused === 'object' && typeof refused.param === 'string' && (outcome === 'interpreter-red' || outcome === 'escalated')) {
558
+ const what = `${refused.param} of ${refused.tool ?? 'a tool'}`;
559
+ const how = refused.kind === 'arg-missing'
560
+ ? `leaving out the ${what}`
561
+ : `sending the ${what} as ${refused.got === 'object' || refused.got === 'array' ? `a JSON ${refused.got}` : `a ${refused.got ?? 'wrong type'}`}${refused.expected ? ` instead of ${/^[aeiou]/.test(refused.expected) ? 'an' : 'a'} ${refused.expected}` : ''}`;
562
+ return {
563
+ reason: `The model kept ${how}, and the tool refused it every time, so the step stopped.`,
564
+ next: CHANGE,
565
+ line: 'tool call refused',
566
+ actions: [],
567
+ };
568
+ }
569
+
554
570
  // `escalated` is a TERMINAL: its sentence may name the real governor, but it is never
555
571
  // resumable. Two governors, never mixed (F198): the STRIKE ladder (the fix loop stopped
556
572
  // improving) also files category `cap-halt` — it is the MONEY cap only when the spine
@@ -1630,7 +1646,12 @@ function getRunDetailBody(runid, opts) {
1630
1646
  const draftingPartHere = draftingFor(row, summary, opts);
1631
1647
  const draftingShiftHere = draftingShift(row, summary, opts);
1632
1648
  const specForParts = resolveSpecForRow(row);
1633
- const enrichedParts = enrichPartsWithStageKind(summary.parts, stageKindMetaFromSpec(specForParts), specForParts);
1649
+ // the memory and the learnings each part was handed, placed where they were passed on (src/panel/handed.js)
1650
+ const handed = attachLearnings(
1651
+ attachMemos(enrichPartsWithStageKind(summary.parts, stageKindMetaFromSpec(specForParts), specForParts), rawSpineRecords),
1652
+ draftingPartHere, learningsHanded(rawSpineRecords),
1653
+ );
1654
+ const enrichedParts = handed.parts;
1634
1655
  const death = deriveDeath(row, rawSpineRecords, summary.outcome);
1635
1656
  const runName = runNameOf(row.job, runNumbers(readRunList(opts).rows).get(row.runid));
1636
1657
  // the export row only for a run export would take — the one rule, `checkExportable`, never a copy of it
@@ -1860,7 +1881,7 @@ function getRunDetailBody(runid, opts) {
1860
1881
  // tabs still never disagree about order/counts/blocked-call figures.
1861
1882
  // a run that DIED (no job-end, runner gone — `death`, decided once above) leaves its last part in flight: that part reads
1862
1883
  // `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) => ({ ...(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) })),
1884
+ parts: (handed.drafting && Array.isArray(enrichedParts) ? [handed.drafting, ...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
1885
  replans: summary.replans,
1865
1886
  close: summary.close,
1866
1887
  branch: summary.branch,
@@ -1886,11 +1907,7 @@ function getRunDetailBody(runid, opts) {
1886
1907
  // carries no contamination risk); `null` when the spine carries no
1887
1908
  // `memory-cache` record at all (never armed on this run).
1888
1909
  behaviour: scopedBehaviour(row, rawSpineRecords),
1889
- // Cross-run learnings, READ-ONLY (ITEM33 rev 2, RULING 8): the exact block the planner was handed, as the spine recorded it at
1890
- // injection (the draft, and the first replan); `hints` = the same text split into fields by learn.js's parseHintBlock (the one reader). Empty when the setting was off or nothing was readable.
1891
- learnings: rawSpineRecords.filter((e) => e?.type === 'learnings' && typeof e.text === 'string').map((e) => ({ phase: String(e.phase), text: e.text, chars: e.text.length, ids: Array.isArray(e.ids) ? e.ids : [], hints: parseHintBlock(e.text) })),
1892
- // a learnings file that could not be read: the plain line (null when it could)
1893
- learningsError: ((r) => (r ? hintsErrorLine(String(r.hintsError)) : null))(rawSpineRecords.find((e) => e?.type === 'learnings' && typeof e.hintsError === 'string')),
1910
+ // Cross-run learnings now ride on the part that received them (`part.learnings`, `part.learningsError`; src/panel/handed.js).
1894
1911
  // PRD v1.106 Part 5 F: the two Run summary rows, worded here (the page prints them)
1895
1912
  callsLine: callsLineOf(rawSpineRecords, scopedBehaviour(row, rawSpineRecords)),
1896
1913
  checksLine: checksLineOf(rawSpineRecords, enrichedParts),
package/src/plan.js CHANGED
@@ -39,7 +39,7 @@ export const MAX_EXITS_PER_STEP = 2;
39
39
  /** a legal-example sentence for the exit menu — shown in the planner prompt and
40
40
  * appended to the missing-required exit red, so a redraft sees a legal shape,
41
41
  * not only the rule (F254: `exit` is required on EVERY step) */
42
- export const EXIT_EXAMPLE = 'Legal exit examples: a step with no check uses [{"type":"artifact-written","path":"<its target>"},{"type":"tree-changed","scope":"<an offered scope>"}]; a step with a check uses [{"type":"tree-changed","scope":"<an offered scope>"},{"type":"check-passes","name":"<a check name>"}].';
42
+ export const EXIT_EXAMPLE = 'Legal exit examples: a read-only look-around step (tools read, grep) uses [{"type":"artifact-written","path":"<an existing file the step reads>"}]; a step that changes files and has no check uses [{"type":"artifact-written","path":"<its target>"},{"type":"tree-changed","scope":"<an offered scope>"}]; a step with a check uses [{"type":"tree-changed","scope":"<an offered scope>"},{"type":"check-passes","name":"<a check name>"}].';
43
43
  /** plan size bound — per-step rounds bound the spend, but an unbounded step
44
44
  * COUNT is still an unbounded claim on the wallet; same 8 as loop.maxIterations */
45
45
  export const MAX_PLAN_STEPS = 8;
@@ -644,3 +644,40 @@ function validateExit(s, at, red, { checkNames, fence, insideFence, writeStep, t
644
644
  red('exit-illegal', `${at}.exit`, `check-passes on a step with no write-class tool (${WRITE_VERBS.join('|')}) — the check's failure gap comes back to this step's own worker, which cannot edit; attach the check to the step that fixes (the operator's close already verifies the finished run)`);
645
645
  }
646
646
  }
647
+
648
+ /**
649
+ * F271 (B2) — pair a `write` grant with `edit`. A look-around step the drafter gave `write` but not `edit`, whose exits force a
650
+ * change to an existing big file, can pass only by a whole-file `write` (u-mvy4cd0d: src/gate.js 2433 lines to 1). Code adds the
651
+ * verb; the agent never asks for it, and it is added only when the SIGNED ceiling (`job.tools`, absent = the full menu) already
652
+ * offers `edit`, so the agent still cannot widen its own menu. `edit` is judged by the same `writeScope` fence as `write`: no
653
+ * authority a whole-file write did not have. No signed hash covers a plan, so none moves.
654
+ *
655
+ * A rubric step-file step is exempt: every path it declares (`target` plus the `artifact-written`/`json-valid` paths) lies under
656
+ * `newFileDir` (`output/steps`, the engine-owned always-new-file directory), so there is nothing to edit.
657
+ *
658
+ * Pure: never mutates `plan`; returns the SAME reference when nothing changes. `validatePlan` is untouched — the runner applies this
659
+ * to the validated plan, so `plan-accepted` records the plan as executed.
660
+ * @param {any} plan a validated plan (`validatePlan(...).plan`)
661
+ * @param {any} job the validateJob-green plan shape spec (its `tools` is the signed ceiling)
662
+ * @param {string|null} [newFileDir] the always-new-file directory whose steps are exempt, or null for none
663
+ * @returns {any} the plan with `edit` appended to each write-without-edit step, or `plan` itself
664
+ */
665
+ export function pairEditGrant(plan, job, newFileDir = null) {
666
+ if (!isObj(plan) || !Array.isArray(plan.steps)) return plan;
667
+ const ceiling = isObj(job) && Array.isArray(job.tools) ? job.tools : [...TOOL_MENU];
668
+ if (!ceiling.includes('edit')) return plan;
669
+ const dir = typeof newFileDir === 'string' && newFileDir.length > 0 ? `${newFileDir.replace(/\/+$/, '')}/` : null;
670
+ const inNewDir = (/** @type {any} */ s) => {
671
+ if (dir === null) return false;
672
+ const paths = [s.target, ...(Array.isArray(s.exit) ? s.exit : []).filter((/** @type {any} */ e) => e && (e.type === 'artifact-written' || e.type === 'json-valid')).map((/** @type {any} */ e) => e.path)]
673
+ .filter((/** @type {any} */ x) => typeof x === 'string' && x.length > 0);
674
+ return paths.length > 0 && paths.every((/** @type {string} */ x) => x.startsWith(dir));
675
+ };
676
+ let changed = false;
677
+ const steps = plan.steps.map((/** @type {any} */ s) => {
678
+ if (!isObj(s) || !Array.isArray(s.tools) || !s.tools.includes('write') || s.tools.includes('edit') || inNewDir(s)) return s;
679
+ changed = true;
680
+ return { ...s, tools: [...s.tools, 'edit'] };
681
+ });
682
+ return changed ? { ...plan, steps } : plan;
683
+ }
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,7 +35,7 @@ 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
41
  import { createCarryStore } from './carrystore.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.
@@ -559,6 +559,10 @@ export const FORBIDDEN_WRITE_SEGMENT_PATTERN = /"path":"(?:(?:[^"\\]|\\.)*\/)?(?
559
559
  * shipped path routinely rides through.
560
560
  */
561
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;
562
566
 
563
567
  /** the recorded reason for a step attempt whose round was cut at the output cap (F122 2A b) */
564
568
  export const TRUNCATED_REASON = 'output cut at the token limit (max_tokens)';
@@ -567,6 +571,55 @@ const REPLAN_CUT_RED = 'Your previous answer was cut off at its length limit bef
567
571
  /** the plain sentence for a replan answer cut off at its length limit (hamr 2026-10-16, run mv9gm796) */
568
572
  export const REPLAN_CUT_WORDS = 'The replan answer was cut off at its length limit, so no new plan came back.';
569
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
+
570
623
  /**
571
624
  * What the NEXT attempt is told about the bound that cut the previous one.
572
625
  *
@@ -593,19 +646,20 @@ export const REPLAN_CUT_WORDS = 'The replan answer was cut off at its length lim
593
646
  * and announces the trim with the repo's ONE marker rather than a second spelling
594
647
  * of "this text was cut" (F90.2).
595
648
  *
596
- * @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
597
650
  * the previous attempt's bound state, or nullish when it was not bounded
598
651
  * @param {number} rounds the step's round bound, as quoted by the frozen sentence
599
652
  * @returns {string|null} the note, or null when there is nothing to say
600
653
  */
601
654
  export function boundedNote(bounded, rounds) {
602
655
  if (!bounded) return null;
656
+ const bad = badCallSentence(bounded.bad);
603
657
  if (bounded.cause === 'truncated') {
604
- 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}`;
605
659
  }
606
660
  if (bounded.cause !== 'denied') {
607
661
  return `Your previous attempt was CUT OFF after ${rounds} tool rounds. `
608
- + '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}`;
609
663
  }
610
664
  const raw = String(bounded.reason ?? '');
611
665
  const shown = raw.length > BOUND_REASON_MAX
@@ -613,7 +667,7 @@ export function boundedNote(bounded, rounds) {
613
667
  : raw;
614
668
  return 'Your previous attempt was CUT OFF by the gate: it denied consecutive tool calls '
615
669
  + `until the streak guard ended the attempt. The gate recorded: ${shown}. `
616
- + '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}`;
617
671
  }
618
672
 
619
673
  /**
@@ -2224,6 +2278,24 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2224
2278
  if (stop !== null) return stop;
2225
2279
  }
2226
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
+
2227
2299
  const lc = new LiteCtx({ root: workdir });
2228
2300
  const ceiling = Array.isArray(job.tools) ? job.tools : [...TOOL_MENU];
2229
2301
  const fencePrefixes = job.writeScope.map((/** @type {string} */ g) => resolve(workdir, globToPrefix(g)));
@@ -2499,7 +2571,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2499
2571
  * `iteration` mirrors `roundIteration` exactly, undefined included: the bound
2500
2572
  * cannot know a label the run never set, and inventing one here would be the
2501
2573
  * only place in this file that claims to.
2502
- * @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}
2503
2575
  */
2504
2576
  let attemptBounded;
2505
2577
  /**
@@ -2520,7 +2592,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2520
2592
  }
2521
2593
  };
2522
2594
  const grantedNames = new Set(granted.map((v) => /** @type {Record<string, string>} */ (TOOL_BY_VERB)[v]));
2523
- 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));
2524
2596
  // THE READ SHIM (arm-gated, default OFF): a per-worker delivery ledger over the
2525
2597
  // read tool — cap at READ_SHIM_CAP, pointer only once the CURRENT content has been
2526
2598
  // delivered whole, next-unseen-slice otherwise, diff on a changed re-read. WHICH of
@@ -2850,7 +2922,8 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2850
2922
  }
2851
2923
  return onLlmResult(arg);
2852
2924
  };
2853
- 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 } : {}) });
2854
2927
  return self;
2855
2928
  };
2856
2929
  /**
@@ -2905,20 +2978,56 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2905
2978
  throw categorize(e).err;
2906
2979
  }
2907
2980
  };
2908
- const ask = async (prompt, defs = toolDefs) => {
2909
- let r;
2910
- // A fresh Loop = a fresh transcript: the read shim's delivered-ledger resets with it, or a
2911
- // later attempt's re-read is answered with a pointer to bytes its model never saw (F252).
2912
- // askFrom (a continuation of a prior transcript) deliberately does NOT reset.
2913
- shim.reset();
2914
- const thinkOpts = thinkingForCall();
2915
- try {
2916
- r = await stallWatch.watch((gen) => newLoop(gen).run([{ role: 'user', content: prompt }], defs, { cacheMessages: true, maxTokens: 32000, ...callBounds(), ...thinkOpts }));
2917
- throwIfStopped();
2918
- noteThinkingStatus(r);
2919
- } catch (e) {
2920
- 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
+ });
2921
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 };
2922
3031
  // BA-11's deny streak is a BOUNDED ATTEMPT, not a terminal. It is the same
2923
3032
  // shape `loop.stop()` has at the round bound thirty lines up: the attempt
2924
3033
  // ran, produced real work, and was cut short by a governance bound doing
@@ -2929,7 +3038,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2929
3038
  // takes the identical lane above — one doctrine, both surfaces.
2930
3039
  if (r.error && r.error.startsWith('denied:')) {
2931
3040
  const reason = scrub(r.error);
2932
- attemptBounded = { iteration: roundIteration, cause: 'denied', reason };
3041
+ attemptBounded = { iteration: roundIteration, cause: 'denied', reason, bad: badFacts };
2933
3042
  emit('attempt-bounded', { phase, iteration: roundIteration, rounds: roundsThisAttempt, cap: attemptRounds, reason });
2934
3043
  return r;
2935
3044
  }
@@ -2942,7 +3051,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2942
3051
  // replan drafter opts in with `truncatedBounded`. Scout and the first draft keep the
2943
3052
  // transport route below (provider-red).
2944
3053
  if (r.error && r.error.startsWith('truncated:') && (phase.startsWith('step:') || phase === 'fix' || truncatedBounded)) {
2945
- attemptBounded = { iteration: roundIteration, cause: 'truncated', reason: TRUNCATED_REASON };
3054
+ attemptBounded = { iteration: roundIteration, cause: 'truncated', reason: TRUNCATED_REASON, bad: badFacts };
2946
3055
  emit('attempt-bounded', { phase, iteration: roundIteration, rounds: roundsThisAttempt, cap: attemptRounds, reason: TRUNCATED_REASON, stopReason: r.stopReason ?? null });
2947
3056
  return r;
2948
3057
  }
@@ -2954,6 +3063,11 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2954
3063
  : r.error.startsWith('truncated:') ? 'provider-red'
2955
3064
  : 'interpreter-red';
2956
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
+ }
2957
3071
  throw err;
2958
3072
  }
2959
3073
  // F184 — bare-agent 0.43.0 (BA-27) returns a malformed final-turn tool
@@ -2970,16 +3084,55 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2970
3084
  // marker before `ask()` returns it unexamined, so a distinct spine
2971
3085
  // record names the transport class here — the same honesty bar
2972
3086
  // F179/F180 set for the authoring path, applied to the worker path.
2973
- if (r.malformedToolCall) {
2974
- const rawErr = String(r.malformedToolCall.error ?? '');
2975
- const scrubbedErr = scrub(rawErr);
2976
- const shownErr = scrubbedErr.length > BOUND_REASON_MAX
2977
- ? `${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}]`
2978
- : scrubbedErr;
2979
- emit('worker-malformed-tool-call', {
2980
- phase, iteration: roundIteration, name: scrub(String(r.malformedToolCall.name ?? '')), error: shownErr,
2981
- });
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;
2982
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;
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
+ });
2983
3136
  return r;
2984
3137
  };
2985
3138
  return { ask: withCarry(ask), askFrom, workerWrites, writeCount, setIteration, wasBounded: () => attemptBounded };
@@ -3245,7 +3398,8 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
3245
3398
  });
3246
3399
  return 'plan-red';
3247
3400
  }
3248
- 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));
3249
3403
  // The skip set is a PREFIX match on the plan's own step ids, never a count: a count
3250
3404
  // would skip whatever happens to sit at that index. Steps run strictly sequentially
3251
3405
  // and idx only advances on a satisfied exit, so the dead run's completions ARE a
@@ -3275,7 +3429,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
3275
3429
  for (const r of pv.reds) emit('plan-red', r);
3276
3430
  return 'plan-red';
3277
3431
  }
3278
- plan = /** @type {any} */ (pv.plan);
3432
+ plan = /** @type {any} */ (pairEditGrant(pv.plan, job, STEP_DIR)); // F271 (B2)
3279
3433
  emit('plan-accepted', { plan });
3280
3434
  } catch (e) {
3281
3435
  return relay(e, 'plan');
@@ -3828,7 +3982,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
3828
3982
  planExecuted();
3829
3983
  return 'plan-red';
3830
3984
  }
3831
- plan = /** @type {any} */ (pv.plan);
3985
+ plan = /** @type {any} */ (pairEditGrant(pv.plan, job, STEP_DIR)); // F271 (B2)
3832
3986
  emit('plan-accepted', { plan, phase: 'replan' });
3833
3987
  // the new plan's steps are NOT the old plan's steps — its abandoned greens
3834
3988
  // must not ride forward as this plan's "prior steps' results" (stale, and
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 });