bareloop 0.1.0 → 0.3.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/interpret.js CHANGED
@@ -12,25 +12,162 @@
12
12
 
13
13
  import { createRequire } from 'node:module';
14
14
  import { writeFileSync, readFileSync } from 'node:fs';
15
- import { join, resolve } from 'node:path';
16
- import { Gate } from 'bareguard';
15
+ import { join, resolve, sep } from 'node:path';
16
+ import { homedir } from 'node:os';
17
+ import { Gate, redact } from 'bareguard';
17
18
  import { LiteCtx, compress } from 'litectx';
18
- import { validateConfig, diffPaths, globToPrefix } from './validate.js';
19
+ import { validateConfig, diffPaths, globToPrefix, SECRET_PATTERNS } from './validate.js';
19
20
  import { ralph } from './ralph.js';
20
21
 
21
- /** @typedef {Error & {category?: string}} CategorizedError the failure map's carrier: ralph relays by `category` */
22
+ /** @typedef {Error & {category?: string, lib?: string}} CategorizedError the failure map's carrier: ralph relays by `category`, and by `lib` when the thrower knows which library owns the failure (the ledger prefers it over prose) */
22
23
 
23
24
  // consecutive close reds that count as a stall; one revision per run
24
25
  export const STALL_REDS = 2;
25
26
 
26
27
  const require = createRequire(import.meta.url);
27
28
  const { Loop, wireGate, HaltError } = require('bare-agent');
29
+ const { createShellTools } = require('bare-agent/tools');
28
30
 
29
- import { stripFences } from './text.js';
31
+ import { extractArtifact, priceOf } from './text.js';
30
32
 
31
33
  /** @typedef {{body?: string|null, text?: string|null}} RecallHit litectx recall hit — body present only with `{body: true}` */
32
34
 
33
35
  const PERSONA = 'You are a senior engineer. Reply with ONLY the complete contents of the requested JavaScript file — no markdown fences, no commentary. ESM.';
36
+ // The tool persona states the LOOP CONTRACT (F16): the worker is one attempt inside
37
+ // `while close-red and under-cap`, not a one-shot. Without knowing that, a model does
38
+ // the rational one-shot thing — read everything, be certain, then act — and the real
39
+ // run spent its ENTIRE budget on 12 rounds of reading without one write, never once
40
+ // reaching the close. Every round re-pays for every earlier tool result, so reads
41
+ // compound: that run's context grew 2k → 121k tokens and its last round cost $0.25.
42
+ // Telling the worker it will be re-run with the close's verdict makes an early,
43
+ // cheap, wrong attempt the rational move — which is exactly what the loop wants.
44
+ const PERSONA_TOOLS = 'You are a senior engineer working in a repository through file tools. '
45
+ + 'ALWAYS use absolute paths — relative paths resolve against the process, not the repository, and will be denied. '
46
+ + 'You are ONE attempt inside an automated loop: when you finish, a test suite runs and, if it still fails, you are called again with its output. '
47
+ + 'So do not try to be certain before acting. Read only what you need to form your best hypothesis, make the change with the write tool, and stop. '
48
+ + 'A wrong cheap attempt is corrected by the next round; exhaustive reading is not — every file you read is re-sent on every later round and the run has a hard budget it can exhaust before you ever write. '
49
+ + 'Make the required changes with the write tool, then reply with a short summary of what you changed. Never put file contents in your reply.';
50
+
51
+ // ---- tool mode (2b): the spec-side grant menu mapped to the underlying tools ----
52
+ // read/grep/write are bare-agent's shell tools; recall/get are litectx's retrieval
53
+ // verbs (F19), composed from the SAME LiteCtx the memory hooks already use.
54
+ const TOOL_BY_VERB = Object.freeze({ read: 'shell_read', grep: 'shell_grep', write: 'shell_write', edit: 'shell_edit', recall: 'ctx_recall', get: 'ctx_get' });
55
+ const CTX_TOOLS = Object.freeze(['ctx_recall', 'ctx_get']);
56
+
57
+ /**
58
+ * The retrieval pair (F19). `shell_read` cannot seek — it starts at byte zero — so a
59
+ * pointer at a symbol was inert and the worker paged whole files to reach one function.
60
+ * `ctx_recall` hands back a POINTER (no body: a search index returns pointers, and bodies
61
+ * on every hit rebuild the bloat — measured, a 5-hit recall dumps ~15k tokens unbidden);
62
+ * `ctx_get` trades that pointer for ONE chunk. A chunk starts at its doc-comment, so the
63
+ * body arrives WITH the docstring that says what it was supposed to do.
64
+ * @param {any} lc the run's LiteCtx (rooted at workdir)
65
+ * @param {string} workdir
66
+ * @param {(type: string, data: object) => void} emit the spine — a retrieval verb whose
67
+ * RESULT is invisible cannot be judged: a `ctx_get` that silently reds (stale pointer,
68
+ * bad range) looks exactly like one that worked, and the worker's fallback to a
69
+ * whole-file read looks like a free choice instead of a forced one.
70
+ */
71
+ function createCtxTools(lc, workdir, emit) {
72
+ return [
73
+ {
74
+ name: 'ctx_recall',
75
+ description: 'Search the repository index for a symbol or phrase. Returns POINTERS (path, symbol, line range) — not code. '
76
+ + 'Pass a pointer to ctx_get to read that one function. Search finds what you can NAME: it will not find a bug from a failing '
77
+ + "test's output (the symptom and the cause live in different files) — read the failing test first, then recall the function it calls.",
78
+ parameters: {
79
+ type: 'object',
80
+ properties: {
81
+ query: { type: 'string', description: 'Symbol name or phrase, e.g. "keywords" or "stopword filter".' },
82
+ n: { type: 'integer', description: 'Max pointers to return (default 5, max 20).' },
83
+ },
84
+ required: ['query'],
85
+ },
86
+ execute: async (/** @type {{query: string, n?: number}} */ { query, n }) => {
87
+ const hits = await lc.recall(String(query), { kind: 'code', n: Math.min(Math.max(Number(n) || 5, 1), 20) });
88
+ const out = hits.length
89
+ ? hits.map((/** @type {any} */ h) => (h.chunk
90
+ ? `${h.path}\t${h.chunk.symbol ?? '(anonymous)'}\t${h.chunk.nodeType}\tlines ${h.chunk.startLine}-${h.chunk.endLine}`
91
+ : `${h.path}\t(whole file — no chunk)`)).join('\n')
92
+ : 'no hits';
93
+ emit('ctx-tool', { tool: 'ctx_recall', query: String(query), hits: hits.length, paths: hits.map((/** @type {any} */ h) => h.path), bytes: Buffer.byteLength(out) });
94
+ return out;
95
+ },
96
+ },
97
+ {
98
+ name: 'ctx_get',
99
+ description: 'Read ONE function by the line range ctx_recall gave you — code plus its doc-comment, without the rest of the file. '
100
+ + 'The line range is a HANDLE you copy from ctx_recall, never one you compute: a range that is not a chunk boundary is refused, '
101
+ + 'and a file edited since it was indexed is refused (re-run ctx_recall for a fresh pointer).',
102
+ parameters: {
103
+ type: 'object',
104
+ properties: {
105
+ path: { type: 'string', description: 'Repository-relative path, exactly as ctx_recall printed it.' },
106
+ startLine: { type: 'integer', description: 'From ctx_recall.' },
107
+ endLine: { type: 'integer', description: 'From ctx_recall.' },
108
+ },
109
+ required: ['path', 'startLine', 'endLine'],
110
+ },
111
+ execute: async (/** @type {{path: string, startLine: number, endLine: number}} */ { path: p, startLine, endLine }) => {
112
+ // The path is spelled as recall printed it (repo-relative); the gate judges the
113
+ // resolved absolute path, exactly as toolAction resolves it. Boundary-aware
114
+ // prefix (workdir + sep, the line-247 pattern): bare startsWith would garble a
115
+ // sibling like `${workdir}-backup/x` into `ackup/x` — the gate independently
116
+ // denies such a path before execute() runs, so this is defense in depth only.
117
+ const rel = String(p).startsWith(workdir + sep) ? String(p).slice(workdir.length + 1) : String(p);
118
+ try {
119
+ const item = lc.get(rel, { startLine: Number(startLine), endLine: Number(endLine) });
120
+ if (!item?.text) {
121
+ emit('ctx-tool', { tool: 'ctx_get', path: rel, startLine, endLine, outcome: 'no-chunk', bytes: 0 });
122
+ return `no chunk at ${startLine}-${endLine} in "${rel}" — copy a line range from ctx_recall, do not compute one`;
123
+ }
124
+ emit('ctx-tool', { tool: 'ctx_get', path: rel, startLine, endLine, outcome: 'ok', bytes: Buffer.byteLength(item.text) });
125
+ return item.text;
126
+ } catch (e) {
127
+ // StalePointerError: the file changed after indexing, so these lines now describe
128
+ // DIFFERENT code. Its message IS the recovery instruction — hand it to the worker.
129
+ const detail = String(/** @type {Error} */ (e)?.message || e);
130
+ emit('ctx-tool', { tool: 'ctx_get', path: rel, startLine, endLine, outcome: 'stale', bytes: 0, detail });
131
+ return `stale pointer: ${detail}`;
132
+ }
133
+ },
134
+ },
135
+ ];
136
+ }
137
+
138
+ // The load-bearing containment line (2b POC, scenario B): bare-agent's built-in
139
+ // tools are deliberately ungated and their action type is their own NAME, which
140
+ // never trips bareguard's fs primitives — this translator maps them onto
141
+ // write/read actions so the SAME fence text mode enforces manually governs
142
+ // every tool call. Paths resolve exactly as the tools resolve them
143
+ // (path.resolve(expandHome(p)), POC scenario F) so the gate judges the same
144
+ // file the tool would touch; a relative spelling resolves against the process
145
+ // cwd and reds at the fence, and the deny reason teaches the retry.
146
+ /** @param {string} p */
147
+ const expandHome = (p) => (p === '~' || p.startsWith('~/')) ? join(homedir(), p.slice(1)) : p;
148
+ /** @param {string} name @param {any} args @param {string} [workdir] */
149
+ const toolAction = (name, args, workdir) => {
150
+ if (name === 'shell_write') return { type: 'write', path: resolve(expandHome(String(args?.path ?? ''))), args: { bytes: String(args?.content ?? '').length } };
151
+ // shell_edit (BA-13) is judged as bareguard's own 'edit' action type — the SAME
152
+ // fs.writeScope fence as write, decided upstream (bareguard FS_TYPES). `bytes` is
153
+ // the replacement's size so the audit can read the edit economy (a 40-byte splice
154
+ // vs an 8KB rewrite is the variable BA-13 exists to move — F18 blindness rule).
155
+ if (name === 'shell_edit') return { type: 'edit', path: resolve(expandHome(String(args?.path ?? ''))), args: { bytes: String(args?.newText ?? '').length } };
156
+ // `tool` rides the action so the AUDIT can tell the read tools apart. Without it every
157
+ // read tool collapses to {type:'read', path} and a whole-file shell_read is
158
+ // indistinguishable from a bounded ctx_get chunk — the ledger cannot see the one
159
+ // variable the retrieval arm exists to test (the F18 blindness, repeated).
160
+ if (name === 'shell_read' || name === 'shell_grep') return { type: 'read', path: resolve(expandHome(String(args?.path ?? ''))), args: { tool: name } };
161
+ // The retrieval verbs are READS and are judged as reads by the SAME fence (F14/F19):
162
+ // ctx_get names a file, so the gate judges that file — the deny list (gate audit,
163
+ // primitive smoke, the litectx store itself) applies to a chunk read exactly as it
164
+ // applies to shell_read, or the worker would read the arbiter's books through the
165
+ // other door. ctx_recall names no file: it is a read OF THE INDEX, judged against the
166
+ // run directory, so it is contained by readScope and cannot reach outside the repo.
167
+ if (name === 'ctx_get') return { type: 'read', path: resolve(String(workdir ?? ''), expandHome(String(args?.path ?? ''))), args: { tool: name } };
168
+ if (name === 'ctx_recall') return { type: 'read', path: resolve(String(workdir ?? '')), args: { tool: name } };
169
+ return { type: name, args };
170
+ };
34
171
 
35
172
  /**
36
173
  * Execute a workflow config against one task under the dumb shell.
@@ -38,13 +175,30 @@ const PERSONA = 'You are a senior engineer. Reply with ONLY the complete content
38
175
  * @param {object|string} configRaw schema v1 config (object or raw JSON text)
39
176
  * @param {object} opts
40
177
  * @param {string} opts.task implement instruction shown to the worker
41
- * @param {string} opts.target absolute path the artifact is written to
178
+ * @param {string} [opts.target] absolute path the artifact is written to —
179
+ * required in text mode; unused in tool mode (the worker writes through
180
+ * the gated tools, wherever the fence allows)
42
181
  * @param {string[]} opts.close argv whose exit code is truth (shell-owned)
182
+ * @param {number} [opts.closeExpect] the exit code the SIGNED spec calls success
183
+ * @param {{pattern: string, min: number}} [opts.closeJudged] the signed spec's
184
+ * judgment-rendered signal — proof the close actually judged something before
185
+ * its exit code is believed in EITHER direction (PRD v1.11; the drafted config
186
+ * cannot express it, and must not: it is the arbiter's own honesty check)
187
+ * @param {string} [opts.closeGapKeep] the signed spec's kept-failures pattern (F28):
188
+ * close-output lines matching it survive the gap bound, so a large suite's
189
+ * `not ok` names reach the worker instead of being elided into "N fail" — also
190
+ * arbiter territory, inexpressible in the drafted config
43
191
  * @param {string} opts.workdir run directory (litectx root, gate audit, scope base)
44
192
  * @param {number} opts.capRuns shell iteration budget; the config may tighten via loop.maxIterations, never exceed
45
193
  * @param {(type: string, data?: object) => object} opts.emit spine emitter
46
194
  * @param {object} opts.provider a bareagent provider — SHELL-owned binding (adaptlearn F8: an unsealed binding is a gate bypass)
47
- * @param {number} [opts.shellCapUsd=2] the shell's USD cap; config budgetUsd is clamped by validation
195
+ * @param {number} [opts.shellCapUsd=2] the shell's USD cap; a config budgetUsd above it REDS at validation (bounds — no silent clamping)
196
+ * @param {number} [opts.closeTimeoutMs] close wall-clock cap, threaded to the shell
197
+ * (shell/operator territory — the workflow config cannot express it)
198
+ * @param {string[]} [opts.jobWriteScope] the job spec's outer write fence (operator law,
199
+ * job-v1) — enforced HERE, the one choke point where a config becomes a Gate:
200
+ * every workflow scope must fit inside it (scope-escape config-red otherwise),
201
+ * on entry validation and on every revision candidate alike
48
202
  * @param {(o: {config: object, gaps: string[], policy: any, onLlmResult: any}) => Promise<{candidate: object|null, parseError?: string|null, costUsd?: number}>} [opts.revisor]
49
203
  * optional mid-run revision seam. Fires ONCE per run after STALL_REDS consecutive
50
204
  * close reds. The interpreter — never the revisor — owns acceptance: the candidate
@@ -52,54 +206,298 @@ const PERSONA = 'You are a senior engineer. Reply with ONLY the complete content
52
206
  * (arbiter-touch / cap-touch revision-reds otherwise; the run continues on the old
53
207
  * config). Revisor spend rides the run's own gate handlers — same budget axis as
54
208
  * the worker.
209
+ * @param {string} [opts.closeState] the close's CURRENT output on the tree as it stands
210
+ * (the shell's pre-token close check, F13) — shown to the first attempt only, and
211
+ * never framed as an attempt: the worker cannot run the close itself (`run` is a
212
+ * locked verb), so without this it is asked to fix a failure it cannot see
213
+ * @param {'text'|'tools'} [opts.mode] middle mode (2b): 'text' (default) writes the ONE
214
+ * target from the response artifact; 'tools' gives the worker Gate-governed file
215
+ * tools — SPEC-side territory (the step declares it; the config cannot express it)
216
+ * @param {string[]} [opts.tools] the spec's tool grant (subset of read|grep|write,
217
+ * job-v1 validated); defaults to the full menu in tool mode
55
218
  * @returns {Promise<'green'|'escalated'|'config-red'>}
56
219
  */
57
- export async function interpret(configRaw, { task, target, close, workdir, capRuns, emit, provider, shellCapUsd = 2, revisor }) {
58
- const v = validateConfig(configRaw, { shellCapUsd });
220
+ export async function interpret(configRaw, { task, target, close, workdir, capRuns, emit, provider, shellCapUsd = 2, jobWriteScope, revisor, closeTimeoutMs, mode = 'text', tools, closeState, closeExpect, closeJudged, closeGapKeep }) {
221
+ // Reds-before-tokens: text mode writes ONE artifact — a missing target is a
222
+ // caller bug that must be loud NOW, not a TypeError after a paid worker call
223
+ // that ralph would misfile as interpreter-red (the gate skips an absent path,
224
+ // so nothing downstream catches it before writeFileSync(undefined)).
225
+ if (mode === 'text' && (typeof target !== 'string' || !target)) {
226
+ throw new TypeError('interpret: text mode requires target (the absolute artifact path)');
227
+ }
228
+ // Normalize ONCE: a trailing slash or a relative spelling must mean the same
229
+ // directory everywhere below — the enforcement belt compares string prefixes,
230
+ // and "/run/" vs "/run" would false-red every legal scope (release review).
231
+ workdir = resolve(workdir);
232
+ const v = validateConfig(configRaw, { shellCapUsd, jobWriteScope });
59
233
  emit('config-validate', { ok: v.ok, reds: v.reds });
60
234
  if (!v.ok) {
61
235
  for (const r of v.reds) emit('config-red', r);
62
236
  emit('run-end', { outcome: 'config-red', iterations: 0 });
63
237
  return 'config-red';
64
238
  }
65
- let config = typeof configRaw === 'string' ? JSON.parse(configRaw) : configRaw;
239
+ let config = /** @type {any} */ (v.config); // single parse — validateConfig returns the parsed config on ok
66
240
 
67
241
  const lc = new LiteCtx({ root: workdir });
242
+ // Enforcement belt (law #1, un-gameable gate): resolve every scope and prove
243
+ // it stays under workdir BEFORE building the Gate. validateConfig already
244
+ // rejects escaping scopes, so this is defense in depth — a future globToPrefix
245
+ // regression (a spelling that normalizes to an absolute path) can never reach
246
+ // a live Gate fence. The interpreter and the validator must never disagree (F9).
247
+ const resolvedScopes = config.gate.writeScope.map((/** @type {string} */ g) => resolve(workdir, globToPrefix(g)));
248
+ // equality counts as escaped: no legal scope resolves to workdir itself (the
249
+ // close lives there), so a scope normalizing to ''/'.' is a regression, not a grant
250
+ const escaped = resolvedScopes.filter((/** @type {string} */ abs) => !abs.startsWith(workdir + sep));
251
+ if (escaped.length) {
252
+ for (const abs of escaped) emit('config-red', { code: 'scope-escape', path: 'gate.writeScope', detail: `resolved scope ${abs} escapes the run directory` });
253
+ emit('run-end', { outcome: 'config-red', iterations: 0 });
254
+ return 'config-red';
255
+ }
256
+ // The attempt's round bound — ONE number for the Gate's run-wide maxTurns and the
257
+ // per-attempt cutoff below (two literals here once drifted apart in kind: the
258
+ // advertised/enforced class). 24→40 on hamr's word 2026-07-16 (TESTGEN amendment
259
+ // 2026-07-16e): the curve measured that prompting cannot buy readability at 24 —
260
+ // the read-first prelude eats the window before the first write.
261
+ const TURNS_PER_ATTEMPT = mode === 'tools' ? 40 : 8;
68
262
  const gate = new Gate({
69
263
  // bareguard fs.writeScope is prefix-containment, not glob (adaptlearn F4); globToPrefix
70
264
  // is the ONE transform shared with the validator's legality rule — mid-path wildcards
71
265
  // and workdir-escaping scopes were already rejected up front (adaptlearn F9, law #1).
72
- fs: { writeScope: config.gate.writeScope.map((/** @type {string} */ g) => resolve(workdir, globToPrefix(g))) },
266
+ // Tool mode adds readScope: the worker's reads stay inside the run directory —
267
+ // the stray-read secrets channel (~/.ssh, /etc) closes with one field (2b POC D).
268
+ // Tool mode adds readScope (the stray-read secrets channel, 2b POC D) AND
269
+ // deny (F14): readScope is the whole workdir, which CONTAINS the run's own
270
+ // machinery — the gate's audit ledger, the primitive-smoke store, the litectx
271
+ // memory store. The real run's worker read its own gate audit and spine. The
272
+ // emergent middle does not author the arbiter, and it does not get to read the
273
+ // arbiter's books either: that is an invitation to fit-to-pass and it fills the
274
+ // context with the run's own bookkeeping instead of the repository's code.
275
+ fs: {
276
+ writeScope: resolvedScopes,
277
+ ...(mode === 'tools'
278
+ ? { readScope: [workdir], deny: [join(workdir, 'gate-audit.jsonl'), join(workdir, '.smoke'), join(workdir, '.litectx')] }
279
+ : {}),
280
+ },
73
281
  budget: { maxCostUsd: config.gate.budgetUsd },
74
- limits: { maxTurns: 8 * (capRuns + 1) },
282
+ // text mode is ~1-2 rounds per attempt; tool mode is N rounds (read→write→…)
283
+ limits: { maxTurns: TURNS_PER_ATTEMPT * (capRuns + 1) },
75
284
  audit: { path: join(workdir, 'gate-audit.jsonl') },
76
285
  humanChannel: async () => ({ decision: 'terminate' }), // no human mid-run: a tripped cap terminates → decision-ready escalation
77
286
  });
78
287
  await gate.init();
79
- const { policy, onLlmResult } = wireGate(gate);
80
- const loop = new Loop({ provider, system: PERSONA, policy, onLlmResult });
288
+ // The crash-attribution instrument (F32): which files has the worker written this
289
+ // run? Answered from the arbiter's OWN books — the gate audit's allow-decision
290
+ // write lines, run_id-scoped because the audit file appends across steps and runs.
291
+ // Both middles land here: tool-mode writes are policy-checked, text-mode writes go
292
+ // through gate.check. Read on demand (only ever at a crashed verdict) and
293
+ // fail-closed: an unreadable audit attributes nothing, so the crash escalates
294
+ // exactly as it did before F32 — attribution can only ADD a recovery path, never
295
+ // swallow an instrument stop.
296
+ const auditPath = join(workdir, 'gate-audit.jsonl');
297
+ const workerWrites = () => {
298
+ try {
299
+ const paths = new Set();
300
+ for (const line of readFileSync(auditPath, 'utf8').split('\n')) {
301
+ if (!line) continue;
302
+ let rec;
303
+ try { rec = JSON.parse(line); } catch { continue; }
304
+ if (rec.run_id === gate.runId && rec.phase === 'gate' && rec.decision === 'allow'
305
+ && (rec.action?.type === 'write' || rec.action?.type === 'edit')
306
+ && typeof rec.action.path === 'string') paths.add(rec.action.path);
307
+ }
308
+ return [...paths];
309
+ } catch { return []; }
310
+ };
311
+ const { policy, onLlmResult } = wireGate(gate, mode === 'tools' ? { actionTranslator: (/** @type {string} */ n, /** @type {any} */ a) => toolAction(n, a, workdir) } : {});
312
+ // Money is metered as it is SPENT — per ROUND, not per attempt (F12). A
313
+ // multi-round attempt that halts (or throws) never returns, so its rounds
314
+ // never reach `worker-result`: the real run bought $1.4375 of tokens inside a
315
+ // halted attempt and the job ledger reported $0.0048. `onLlmResult` is the one
316
+ // seam that sees every round, and it fires BEFORE the gate records the round —
317
+ // so even the round that trips the cap lands on the spine. Emitted first, then
318
+ // forwarded verbatim: the gate's own accounting is never altered. costUsd/
319
+ // pricing ride AS-IS (a null is the honest unknown, never $0 — F6).
320
+ /** @type {number|undefined} the attempt a round belongs to (display only) */
321
+ let roundIteration;
322
+ // F20 — THE ATTEMPT HAD NO BOUND, so ralph never ralphed. `limits.maxTurns` is bareguard's,
323
+ // and the Gate is constructed ONCE for the whole RUN: it is a run-wide HALT, not a
324
+ // per-attempt cap. Nothing else ended an attempt — a tool-mode attempt ran until the model
325
+ // CHOSE to stop calling tools. A worker that has never been told it is wrong does not stop:
326
+ // measured, attempt #1 ran 55 rounds, spent the entire $1.50 budget, and the close NEVER RAN
327
+ // ONCE (zero verdicts, zero gaps, zero writes). The loop's whole premise — a cheap wrong
328
+ // attempt corrected by the next round — was unreachable, and the persona's promise ("a test
329
+ // suite runs and you are called again") was a lie the shell never kept.
330
+ // `loop.stop()` breaks at the round boundary and — since bare-agent 0.27.0 (BA-3/BA-5) —
331
+ // returns the transcript with `error: null` and the produced text preserved, so the attempt
332
+ // ends cleanly, its summary stands, and the close renders the verdict that feeds the next
333
+ // attempt. (Before 0.27.0 stop() fell through to a HARD_ROUND_LIMIT return carrying a bogus
334
+ // error, which bareloop had to un-lie behind a `stoppedByBound` flag — the upgrade removed
335
+ // both the lie and the shim; see ask().) Per-attempt, because each attempt is a FRESH
336
+ // conversation (the context resets), which is what keeps four bounded attempts inside a
337
+ // budget one unbounded attempt exhausts.
338
+ /** rounds spent inside the CURRENT attempt (reset per attempt, unlike the gate's run-wide tick) */
339
+ let roundsThisAttempt = 0;
340
+ /** @type {number|undefined} the attempt that was cut short by the bound (spine + gap note) */
341
+ let attemptBounded;
342
+ /** true while the REVISOR holds the metered handler: its rounds are real money on
343
+ * the run's axis (F12) but they are not the WORKER's rounds, and charging them to
344
+ * the per-attempt bound silently handed the worker 40−R turns while the prompt
345
+ * still advertised 40 (advertised == enforced, PRD; a revisor that burned the whole
346
+ * bound stopped the worker loop before its first tool call) */
347
+ let inRevisor = false;
348
+ // `tokens` alone cannot answer the question the ledger exists to answer.
349
+ // bare-agent's `inputTokens` is the UNCACHED prompt remainder — re-sent context
350
+ // is billed as a cache READ and never appears in it. So a round that re-pays for
351
+ // half the repo and a round that reads it fresh can carry the same `tokens`, at
352
+ // very different cost. Record the four tiers the provider actually prices
353
+ // separately, and record the `kind` (a summarizer fold is an LLM call too, and
354
+ // must never hide inside the worker's own numbers).
355
+ /** @param {{costUsd?: number|null, pricing?: string|null, usage?: any, kind?: string}} arg */
356
+ const meteredOnLlmResult = async (arg) => {
357
+ const u = arg?.usage ?? {};
358
+ emit('worker-round', {
359
+ iteration: roundIteration,
360
+ kind: arg?.kind ?? 'turn',
361
+ costUsd: arg?.costUsd ?? null,
362
+ pricing: arg?.pricing ?? null,
363
+ tokens: (u.inputTokens ?? 0) + (u.outputTokens ?? 0),
364
+ usage: {
365
+ inputTokens: u.inputTokens ?? 0,
366
+ outputTokens: u.outputTokens ?? 0,
367
+ cacheReadTokens: u.cacheReadTokens ?? 0,
368
+ cacheCreationTokens: u.cacheCreationTokens ?? 0,
369
+ },
370
+ });
371
+ // The attempt's own bound (F20). A summarizer fold is an LLM call but not a worker
372
+ // ROUND — counting it would let a fold shorten the attempt that paid for it. The
373
+ // revisor is the same case wearing `kind: 'turn'`: metered above, never charged here.
374
+ if ((arg?.kind ?? 'turn') === 'turn' && mode === 'tools' && !inRevisor) {
375
+ roundsThisAttempt += 1;
376
+ if (roundsThisAttempt >= TURNS_PER_ATTEMPT) {
377
+ // Clean stop at the round boundary: since 0.27.0 (BA-3/BA-5) run() returns the
378
+ // transcript with error=null and the text preserved, so this is an attempt that
379
+ // ENDED, not one that FAILED. The close now runs and its verdict becomes the next
380
+ // attempt's gap — which is the entire point.
381
+ attemptBounded = roundIteration;
382
+ emit('attempt-bounded', { iteration: roundIteration, rounds: roundsThisAttempt, cap: TURNS_PER_ATTEMPT });
383
+ loop.stop();
384
+ }
385
+ }
386
+ return onLlmResult(arg);
387
+ };
388
+ // The offered tools ARE the grant (2b decision #2): an ungranted tool is never
389
+ // in the menu the model sees — a call to it is "unknown tool", not a deny.
390
+ const toolDefs = mode === 'tools'
391
+ ? await (async () => {
392
+ const granted = new Set((tools ?? Object.keys(TOOL_BY_VERB)).map((v) => /** @type {Record<string, string>} */ (TOOL_BY_VERB)[v]));
393
+ const shell = createShellTools().tools.filter((/** @type {{name: string}} */ t) => granted.has(t.name));
394
+ const ctx = CTX_TOOLS.some((t) => granted.has(t))
395
+ ? createCtxTools(lc, workdir, emit).filter((t) => granted.has(t.name))
396
+ : [];
397
+ // A retrieval verb with no index is a tool that always answers "no hits". Index is
398
+ // incremental (unchanged files skipped) and BM25-only: measured on the real repo, the
399
+ // semantic tier costs 26s of embedding and does NOT find a symbol the lexical tier
400
+ // misses (for code it only RE-RANKS a BM25-gated pool — it cannot nominate), and it
401
+ // demoted the exact-symbol hit from rank 1 to rank 4. Lexical is the better instrument here.
402
+ if (ctx.length) await lc.index();
403
+ return [...shell, ...ctx];
404
+ })()
405
+ : [];
406
+
407
+ // The retrieval verbs only pay if the worker reaches for them INSTEAD of paging a file.
408
+ // F18 measured the failure they exist to fix: the worker read one 117 KB file NINE times
409
+ // and dragged 1.37 MB of source through context to reach an 8-line function. The tool
410
+ // descriptions carry the mechanics; the persona has to carry the STRATEGY, or a model
411
+ // with a familiar `read` and an unfamiliar `recall` will simply keep reading.
412
+ const RETRIEVAL_STRATEGY = '\nYou also have a repository index. To read a function, do NOT read its whole file: '
413
+ + 'call ctx_recall with the function name to get a pointer, then ctx_get with that pointer to read that function alone '
414
+ + '(it comes with its doc-comment, which states what the function is SUPPOSED to do — compare it against what the code does). '
415
+ + 'Reserve shell_read for whole files that are genuinely small, and for files you cannot name a symbol in yet. '
416
+ + 'Search only finds what you can NAME: a failing test names the symptom, not the cause, so read the failing test first, '
417
+ + 'see which function it calls, and recall THAT.';
418
+ // BA-13: like retrieval, the edit verb only pays if the worker reaches for it INSTEAD
419
+ // of a whole-file rewrite. F31 measured the default: 4 of 5 big-file whole-writes
420
+ // broke the tree, and every one was a rewrite to change ~one line. The tool
421
+ // description carries the mechanics; the persona carries the strategy.
422
+ const EDIT_STRATEGY = '\nPrefer the edit tool over whole-file writes: quote the EXACT text to change (it must match exactly once) and its replacement. '
423
+ + 'Rewriting a whole file to change one line is how trees get broken and budgets get burned — reserve the write tool for genuinely new files.';
424
+ const usesCtx = toolDefs.some((/** @type {{name: string}} */ t) => CTX_TOOLS.includes(t.name));
425
+ const usesEdit = toolDefs.some((/** @type {{name: string}} */ t) => t.name === 'shell_edit');
426
+ const loop = new Loop({
427
+ provider,
428
+ system: mode === 'tools' ? PERSONA_TOOLS + (usesEdit ? EDIT_STRATEGY : '') + (usesCtx ? RETRIEVAL_STRATEGY : '') : PERSONA,
429
+ policy,
430
+ onLlmResult: meteredOnLlmResult,
431
+ });
81
432
 
82
433
  /** @param {string} slot */
83
434
  const slotOps = (slot) => config.hooks?.[slot] ?? [];
84
435
  /** @param {{kinds?: string[]}} op */
85
436
  const recallKinds = (op) => op.kinds ?? config.memory.recall?.kinds ?? ['fact'];
86
437
 
87
- /** @param {string} prompt */
88
- async function ask(prompt) {
438
+ /**
439
+ * @param {string} prompt
440
+ * @param {typeof toolDefs} [defs] the tool menu for THIS call — defaults to the
441
+ * step's grant; the plan-only call passes [] (its own prompt says "no code",
442
+ * and the menu is the grant: a tool it isn't offered cannot be called)
443
+ */
444
+ async function ask(prompt, defs = toolDefs) {
89
445
  let r;
90
446
  try {
91
- r = await loop.run([{ role: 'user', content: prompt }]);
447
+ // cacheMessages (BA-1, bare-agent 0.27.0): roll an Anthropic cache breakpoint onto the
448
+ // transcript so a tool loop stops re-buying its whole growing history at full price every
449
+ // round — F18 measured 754k full-price tokens, $1.55, and the job died at the cap without
450
+ // one write. Opt-in and provider-routed (loop.run forwards options to generate): a
451
+ // non-Anthropic binding ignores it, and it is safe because bareloop wires no trim/compaction
452
+ // fold — the one interaction (a fold that rewrites the cached prefix) that would defeat it.
453
+ // maxTokens (F30): the provider's 4096 default cannot hold a whole-file
454
+ // shell_write of a real source file — the API cuts the round, BA-6 surfaces
455
+ // `truncated:max_tokens`, and doctrine reads it provider-red: run over.
456
+ // Battery pass 1 lost 3/3 rows to exactly this. Output budget is shell
457
+ // territory (never the config's); 32k fits any single-file write the
458
+ // writeScope admits, and output tokens are only paid when generated.
459
+ r = await loop.run([{ role: 'user', content: prompt }], defs, { cacheMessages: true, maxTokens: 32000 });
92
460
  } catch (e) {
93
- if (e instanceof HaltError) /** @type {CategorizedError} */ (e).category = 'cap-halt'; // belt: bare-agent's contract could change
94
- throw e;
461
+ const err = /** @type {CategorizedError} */ (e);
462
+ // A throw OUT OF loop.run() is provider/loop territory by definition — the
463
+ // interpreter's own code is not on that stack. The real run died `read
464
+ // ENETUNREACH` mid-call and was filed interpreter-red ("fix the middle"),
465
+ // when the honest decision was "the network failed — retry" (F11). A
466
+ // governance halt keeps its own category; everything else is provider-red,
467
+ // the same class the drafting path already names.
468
+ err.category = e instanceof HaltError ? 'cap-halt' : (err.category ?? 'provider-red');
469
+ throw err;
95
470
  }
96
471
  // bare-agent NEVER throws HaltError out of run() — a governance halt comes
97
472
  // back as an error RETURN ({text: '', error: 'halt:<rule>'}; loop.js: "no
98
473
  // throw even when throwOnError: true"). Read it, or the failure map goes
99
474
  // blind and a cap story masquerades as a worker result (design law #8).
475
+ // A denial streak ('denied:<tool>', BA-11) is a governance deny, not a
476
+ // broken interpreter — gate-red, same category as text mode's fence deny.
477
+ // A TRUNCATED round ('truncated:max_tokens', BA-6, bare-agent 0.27.0) is the
478
+ // API cutting the generation off at the output cap — not a middle fault. It is
479
+ // provider-red (retry), the same class as an ENETUNREACH transport failure
480
+ // (F11): no verdict exists and the failed round's spend is only partly known.
481
+ // Before 0.27.0 this round was laundered into a clean finish with error:null
482
+ // (F25) — every prior sonnet arm ran on that bug; the fix surfaces it as its
483
+ // own error, so the middle can escalate instead of scoring an empty attempt.
484
+ // OUR OWN stop is not a fault (F20), and since 0.27.0 (BA-3/BA-5) `loop.stop()`
485
+ // returns `error: null` with the run's text preserved — so a bounded attempt
486
+ // lands on the clean-return path below with no special-casing (the 0.26.2
487
+ // `stoppedByBound` shim that un-lied the HARD_ROUND_LIMIT return is gone).
100
488
  if (r.error) {
101
489
  const err = /** @type {CategorizedError} */ (new Error(`worker loop: ${r.error}`));
102
- err.category = r.error.startsWith('halt:') ? 'cap-halt' : 'interpreter-red';
490
+ err.category = r.error.startsWith('halt:') ? 'cap-halt'
491
+ : r.error.startsWith('denied:') ? 'gate-red'
492
+ : r.error.startsWith('truncated:') ? 'provider-red'
493
+ : 'interpreter-red';
494
+ // Attribute at the THROW site, where the owner is known, instead of
495
+ // leaving the ledger to sniff the prose downstream: this error came out
496
+ // of bare-agent's loop, whatever words it happens to carry. A litectx
497
+ // hook throw (runOps) reaches the same escalation with no lib field and
498
+ // keeps its verb→lib mapping. Review 2026-07-18: prose-sniffing billed a
499
+ // transport failure to litectx whenever the text said "recall".
500
+ err.lib = 'bare-agent';
103
501
  throw err;
104
502
  }
105
503
  return r;
@@ -119,7 +517,10 @@ export async function interpret(configRaw, { task, target, close, workdir, capRu
119
517
  }
120
518
  context.text = hits.map((h) => h.body ?? h.text ?? '').filter(Boolean).join('\n');
121
519
  context.level = null;
122
- emit('hook-op', { slot, op: 'recall', hits: hits.length, iteration });
520
+ // paths ride on the event: a recall whose CONTENT is invisible blinds every
521
+ // downstream instrument to what the worker was handed (F33 — P5's green looked
522
+ // like an impossible sight-unseen edit until recall_log forensics explained it)
523
+ emit('hook-op', { slot, op: 'recall', hits: hits.length, paths: hits.map((h) => /** @type {any} */ (h).path).filter(Boolean), iteration });
123
524
  } else if (op.op === 'compress') {
124
525
  const level = op.level ?? config.memory.compressLevel ?? 'verbatim';
125
526
  if (context.text) context.text = await compress({ text: context.text, format: 'js' }, { level });
@@ -128,7 +529,11 @@ export async function interpret(configRaw, { task, target, close, workdir, capRu
128
529
  if (gap) lc.stash(`gap-${iteration}`, gap);
129
530
  emit('hook-op', { slot, op: 'stash', iteration });
130
531
  } else if (op.op === 'remember') {
131
- await lc.remember(`green-${iteration ?? 'final'}-${target.split('/').at(-1)}`, readFileSync(target, 'utf8'), { kind: op.kind ?? 'fact' });
532
+ // tool mode has no single target to read back — the green's retained
533
+ // form is the worker's own change summary (its final loop text), which
534
+ // is what a future recall can actually use
535
+ const content = mode === 'tools' ? (lastText ?? '') : readFileSync(/** @type {string} */ (target), 'utf8');
536
+ await lc.remember(`green-${iteration ?? 'final'}-${mode === 'tools' ? 'tools' : /** @type {string} */ (target).split('/').at(-1)}`, content, { kind: op.kind ?? 'fact' });
132
537
  emit('hook-op', { slot, op: 'remember' });
133
538
  }
134
539
  }
@@ -139,27 +544,38 @@ export async function interpret(configRaw, { task, target, close, workdir, capRu
139
544
  // already snapshotted, so gate/escalation (arbiter) and loop.maxIterations
140
545
  // (cap) must be byte-identical; anything else that validates is a legal
141
546
  // free-axis revision.
142
- /** @param {any} candidate */
547
+ /** @param {any} candidate
548
+ * @returns {{ red: {code: string, reds?: object[]} } | { red?: undefined, config: any }} */
143
549
  const acceptRevision = (candidate) => {
144
- if (!candidate) return { code: 'parse-error' };
145
- const cv = validateConfig(candidate, { shellCapUsd });
146
- if (!cv.ok) return { code: 'validation', reds: cv.reds };
147
- if (JSON.stringify(candidate.gate) !== JSON.stringify(config.gate)
148
- || JSON.stringify(candidate.escalation) !== JSON.stringify(config.escalation)) {
149
- return { code: 'arbiter-touch' };
550
+ if (!candidate) return { red: { code: 'parse-error' } };
551
+ const cv = validateConfig(candidate, { shellCapUsd, jobWriteScope });
552
+ if (!cv.ok) return { red: { code: 'validation', reds: cv.reds } };
553
+ // judged and installed on the PARSED form (single-parse contract) — a
554
+ // string candidate compared raw would false-red arbiter-touch (its .gate
555
+ // is undefined), and installing it raw would crash every later read
556
+ const cand = /** @type {any} */ (cv.config);
557
+ if (JSON.stringify(cand.gate) !== JSON.stringify(config.gate)
558
+ || JSON.stringify(cand.escalation) !== JSON.stringify(config.escalation)) {
559
+ return { red: { code: 'arbiter-touch' } };
150
560
  }
151
- if (candidate.loop?.maxIterations !== config.loop.maxIterations) return { code: 'cap-touch' };
152
- return null;
561
+ if (cand.loop?.maxIterations !== config.loop.maxIterations) return { red: { code: 'cap-touch' } };
562
+ return { config: cand };
153
563
  };
154
564
 
155
565
  /** @type {string[]} */
156
566
  const gaps = [];
157
567
  let revised = false;
568
+ /** @type {string|undefined} set on artifact-red, consumed by the next attempt's prompt */
569
+ let artifactNote;
570
+ /** @type {string|undefined} tool mode: the last attempt's summary text (retention source) */
571
+ let lastText;
158
572
  /**
159
573
  * @param {number} iteration
160
574
  * @param {string} [gap]
161
575
  */
162
576
  const middle = async (iteration, gap) => {
577
+ roundIteration = iteration; // stamps every round of this attempt (F12)
578
+ roundsThisAttempt = 0; // the bound is PER ATTEMPT — a fresh conversation, a fresh budget (F20)
163
579
  if (gap) gaps.push(gap);
164
580
  if (revisor && !revised && gaps.length >= STALL_REDS) {
165
581
  emit('stall-detected', { iteration, consecutiveReds: gaps.length });
@@ -169,46 +585,122 @@ export async function interpret(configRaw, { task, target, close, workdir, capRu
169
585
  // the run's own gate handlers ride along: revisor spend hits the same
170
586
  // budget axis as the worker; a budget halt mid-revision is a cap story,
171
587
  // not a revision bug
172
- rv = await revisor({ config, gaps: [...gaps], policy, onLlmResult });
588
+ // the METERED handler: revisor rounds are real money on the same axis (F12)
589
+ inRevisor = true;
590
+ rv = await revisor({ config, gaps: [...gaps], policy, onLlmResult: meteredOnLlmResult });
173
591
  } catch (e) {
174
592
  if (e instanceof HaltError) /** @type {CategorizedError} */ (e).category = 'cap-halt';
175
593
  throw e;
594
+ } finally {
595
+ // `finally`, not a trailing assignment: a revisor that throws (cap-halt is
596
+ // the expected one) must not leave the worker's rounds uncounted for the
597
+ // rest of the run — that would turn this fix into an unbounded attempt.
598
+ inRevisor = false;
176
599
  }
177
- const red = acceptRevision(rv.candidate);
178
- if (red) {
179
- emit('revision-red', { iteration, ...red, detail: rv.parseError ?? undefined, costUsd: rv.costUsd ?? 0 });
600
+ const rr = acceptRevision(rv.candidate);
601
+ if (rr.red) {
602
+ // `?? null`, never `?? 0`: an unpriced revisor's spend is UNKNOWN, and
603
+ // the spine is the permanent record (F6 — the cap is governed honestly
604
+ // by the metered worker-round path, but $0 on the record is a lie).
605
+ emit('revision-red', { iteration, ...rr.red, detail: rv.parseError ?? undefined, costUsd: rv.costUsd ?? null });
180
606
  } else {
181
- emit('revision-accepted', { iteration, changedPaths: diffPaths(config, rv.candidate), costUsd: rv.costUsd ?? 0 });
182
- config = rv.candidate;
607
+ emit('revision-accepted', { iteration, changedPaths: diffPaths(config, rr.config), costUsd: rv.costUsd ?? null });
608
+ config = rr.config;
183
609
  }
184
610
  }
185
611
  if (gap) await runOps('after-red', { iteration, gap, context: {} });
186
612
  const context = {};
187
613
  await runOps('before-attempt', { iteration, context });
188
- const parts = [task, context.text && `Possibly relevant notes:\n${context.text}`, gap && `Previous attempt failed the test suite:\n${gap}`];
614
+ // F10 (first real-model run): a tool-mode worker must be TOLD where the
615
+ // repository is. The persona demands absolute paths, but bare-agent's shell
616
+ // tools resolve relative paths against the PROCESS cwd — not the workdir —
617
+ // so a worker with no root is working blind: the real run groped for the repo
618
+ // (/home/hamr, the runner's own directory, then /) and the fence denied every
619
+ // guess until the denial streak stopped it. Containment held; the task was
620
+ // impossible. Text mode is told nothing: it has no tools to point anywhere,
621
+ // and the shell alone chooses its one target.
622
+ // (parts[0] stays the task: the plan shape re-orders around it)
623
+ const parts = [
624
+ task,
625
+ mode === 'tools' && `Repository root (absolute): ${workdir}\nEvery path you pass to a tool MUST be absolute and inside this root — a relative path resolves against a different directory and will be denied by the gate.`,
626
+ // F13: what the close says about the tree RIGHT NOW — the state a human
627
+ // maintainer reads first. Given only until an attempt of our own exists
628
+ // (then `gap` is the truer, attributable evidence). The real run withheld
629
+ // this on the grounds that "no attempt has happened", and the worker — which
630
+ // cannot run the suite itself, the `run` verb being locked — groped through
631
+ // the repository and burned the entire cap without one write. Attributing an
632
+ // attempt and describing the tree are different claims; this is the second.
633
+ !gap && closeState && `The close is currently failing. This is its output on the tree as it stands (not an attempt of yours):\n${closeState}`,
634
+ context.text && `Possibly relevant notes:\n${context.text}`, gap && `Previous attempt failed the test suite:\n${gap}`,
635
+ artifactNote && `Previous attempt never reached the close:\n${artifactNote}`,
636
+ // F20: a bounded attempt must SAY it was bounded. Otherwise the worker reads its own
637
+ // truncated transcript as a finished one, learns nothing from being cut off, and spends
638
+ // the next attempt investigating exactly as far and stopping exactly as short.
639
+ attemptBounded !== undefined && attemptBounded === iteration - 1
640
+ && `Your previous attempt was CUT OFF after ${TURNS_PER_ATTEMPT} tool rounds without making a change. Reading is bounded; writing is not. `
641
+ + `Form a hypothesis EARLY and make the edit — a wrong cheap edit is corrected by the next round, but an attempt that never writes teaches this loop nothing.`];
189
642
 
190
643
  if (config.loop.shape === 'plan') {
191
644
  // plan-then-execute: one call to decompose, one to implement following the plan
192
- const p = await ask([`Produce a SHORT numbered implementation plan (2-4 steps) for this task. Plan only, no code.`, ...parts.slice(1), parts[0]].filter(Boolean).join('\n\n'));
193
- emit('worker-plan', { iteration, costUsd: p.metrics?.costUsd ?? p.cost ?? null }); // metrics.costUsd carries the honest null when unpriced; cost sums priced rounds only
645
+ // Plan only, no code — so no tools either: the menu IS the grant (2b), and a
646
+ // plan call offered shell_write can mutate the tree before the implement
647
+ // round exists (release review 2026-07-19; unexercised combination until then)
648
+ const p = await ask([`Produce a SHORT numbered implementation plan (2-4 steps) for this task. Plan only, no code.`, ...parts.slice(1), parts[0]].filter(Boolean).join('\n\n'), []);
649
+ emit('worker-plan', { iteration, ...priceOf(p) }); // priceOf: the ONE honest-null cost read (F6)
194
650
  parts.push(`Follow this plan:\n${p.text}`);
195
651
  }
196
652
  const r = await ask(parts.filter(Boolean).join('\n\n'));
197
- emit('worker-result', { iteration, costUsd: r.metrics?.costUsd ?? r.cost ?? null, tokens: r.usage?.outputTokens ?? null });
653
+ emit('worker-result', { iteration, ...priceOf(r), toolCalls: r.metrics?.toolCalls ?? 0, tokens: r.usage?.outputTokens ?? null });
198
654
 
199
- const decision = await gate.check({ type: 'write', path: target, args: { bytes: r.text.length } });
655
+ // Tool mode: the worker already wrote through the gated tools (every call
656
+ // policy-checked against the fence); its final text is a change summary,
657
+ // not an artifact — there is nothing to extract and artifact-red genuinely
658
+ // does not exist here (2b decision #3). The close judges the tree as-is.
659
+ if (mode === 'tools') {
660
+ lastText = r.text ?? '';
661
+ return;
662
+ }
663
+
664
+ // Fence-robust extraction BEFORE the gate: what gets written is the
665
+ // artifact, not the response (F2 #2). A response with no artifact reds on
666
+ // its OWN axis — artifact-red — and writes nothing: the close will red
667
+ // against the stale/missing target, but the spine names the true cause,
668
+ // so the contrast evidence stays clean (F21's instrument caveat).
669
+ const ex = extractArtifact(r.text);
670
+ if (ex.red) {
671
+ emit('artifact-red', { iteration, category: 'artifact-red', reason: ex.red });
672
+ artifactNote = `your response was rejected as a non-artifact (${ex.red}) — emit ONLY the code artifact`;
673
+ return; // retryable: the next attempt carries the note; ralph's cap still governs
674
+ }
675
+ artifactNote = undefined;
676
+ const code = /** @type {string} */ (ex.code); // non-null: ex.red was checked above
677
+ const t = /** @type {string} */ (target); // text mode contract: target is required
678
+ const decision = await gate.check({ type: 'write', path: t, args: { bytes: code.length } });
200
679
  if (decision.outcome !== 'allow') {
201
- const err = /** @type {CategorizedError} */ (new Error(`gate ${decision.outcome} write to ${target} (${decision.rule ?? 'no rule'})`));
680
+ const err = /** @type {CategorizedError} */ (new Error(`gate ${decision.outcome} write to ${t} (${decision.rule ?? 'no rule'})`));
202
681
  err.category = decision.severity === 'halt' ? 'cap-halt' : 'gate-red';
203
682
  throw err;
204
683
  }
205
- writeFileSync(target, stripFences(r.text));
206
- emit('artifact-written', { iteration, path: target });
684
+ writeFileSync(t, code);
685
+ emit('artifact-written', { iteration, path: t });
207
686
  };
208
687
 
209
688
  // the config may tighten the shell's iteration budget, never exceed it (mirrors budgetUsd)
210
689
  const effectiveCap = Math.min(capRuns, config.loop.maxIterations ?? capRuns);
211
- const outcome = await ralph({ middle, close, capRuns: effectiveCap, emit });
690
+ // Secrets never enter the spine (hard line): the shell scrubs close output at
691
+ // the source with bareguard's redactor — BG-1 defaults (Bearer/sk-…) PLUS the
692
+ // validator's whole shape inventory (SECRET_PATTERNS), so redaction can never
693
+ // pass a shape detection reds (a git close echoing a ghp_ token was the gap).
694
+ // Injected here (the layer that owns bareguard) so ralph stays stdlib-only and
695
+ // the scrub is a fixed shell primitive, not an emergent component (V4 holds).
696
+ // cwd: workdir — the close judges the tree the work happened in (F8). A close
697
+ // is a repository command (`npm test`); run from anywhere else it silently
698
+ // judges another repo and exit-code-is-truth stops being true.
699
+ // expect/judged/gapKeep are the SIGNED spec's, threaded verbatim — the drafted
700
+ // config cannot express any of them (they are arbiter territory, PRD v1.11; F28
701
+ // for gapKeep, which keeps a large suite's failure NAMES in the gap the worker
702
+ // sees instead of letting the bound elide them into a bare "N fail").
703
+ const outcome = await ralph({ middle, close, capRuns: effectiveCap, emit, closeTimeoutMs, cwd: workdir, expect: closeExpect, judged: closeJudged, gapKeep: closeGapKeep, workerWrites, redact: (/** @type {string} */ s) => redact(s, { patterns: SECRET_PATTERNS }) });
212
704
  if (outcome === 'green') {
213
705
  // The close already passed — a retention hiccup must not un-green a real
214
706
  // green (it would corrupt the learning curve). It degrades loudly: