bare-agent 0.59.0 → 0.60.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.
@@ -0,0 +1,598 @@
1
+ 'use strict';
2
+
3
+ // refineWorker — a DEFINITE leaf worker run as a bounded generate→sense→regenerate loop (BA-8/9/10/11/14/15).
4
+ // Extracted from `recurse.js` (no behaviour change): `recurse(task, ctx, {maxDepth:0, refineLeaf})` and
5
+ // `refineWorker(task, ctx, {refineLeaf, ...})` are the SAME code path and return the same shape. This file also
6
+ // owns the BA-15 arbiter machinery and the verify slot, which `recurse.js` imports back (moved, not copied).
7
+ // Composes AROUND a Loop; `loop.js` never imports it.
8
+
9
+ /** @typedef {import('../types').Provider} Provider */
10
+ /** @typedef {import('../types').ToolDef} ToolDef */
11
+ /** @typedef {import('./evaluator').Verdict} Verdict */
12
+ /** @typedef {import('./recurse').RecurseCtx} RecurseCtx */
13
+ /** @typedef {import('./recurse').RecurseOptions} RecurseOptions */
14
+ /** @typedef {import('./recurse').RecurseNode} RecurseNode */
15
+ /** @typedef {import('./recurse').RecurseResult} RecurseResult */
16
+
17
+ const { Loop } = require('./loop');
18
+ const { Evaluator } = require('./evaluator');
19
+ const { assessComplexity, isCritical } = require('./complexity');
20
+ const { refine } = require('./refine');
21
+ const { HaltError, ValidationError } = require('./errors');
22
+ const { DECOMPOSITION_POLICY, capabilityScrub } = require('./recurse-prompts');
23
+
24
+ // BA-8 leaf-refine: temperature ESCALATES per retry. The live POC (poc/ba8-leaf-refine.mjs) found that at a flat
25
+ // low temperature a weak model regenerates byte-identical wrong code and IGNORES even crisp deterministic
26
+ // feedback (0/5 recovery); recovery only appears once retries are given room to vary (0/5 → 2-3/5). So escalation
27
+ // is a DESIGN REQUIREMENT of the seam, not a tuning nicety. Overridable via `opts.refineLeaf.temperatures`.
28
+ // SCOPE (BA-10): this holds for models that ACCEPT `temperature`. On a temperature-fixed model (e.g.
29
+ // claude-sonnet-5 — the provider drops the param, `receipts.refineLeaf.temperatures` records `null`), the
30
+ // escalation lever is inert and the fed-back gap `critique` carries recovery alone (an empirical question the
31
+ // live run answers). The critique is the primary correction lever; temperature is a secondary diversity lever.
32
+ const DEFAULT_REFINE_TEMPS = [0.2, 0.7, 1.0];
33
+
34
+ /**
35
+ * The persona prefix for a worker system prompt (Gap 3 / 0.21.0). A caller-supplied `opts.persona` AUGMENTS the
36
+ * decomposition policy + scrub (never replaces them — that text drives the spawn mechanics). Returns '' when
37
+ * absent/blank, so the default worker prompt is byte-identical to pre-0.21 (backward-compatible). Validated live
38
+ * by `poc/rlm-persona-seam.mjs` (the worker still decomposes, adopts the persona, and carries it to children).
39
+ * @param {unknown} persona
40
+ * @returns {string}
41
+ */
42
+ function workerPersonaPrefix(persona) {
43
+ const p = typeof persona === 'string' ? persona.trim() : '';
44
+ return p ? p + '\n\n' : '';
45
+ }
46
+
47
+ /**
48
+ * BA-9 (relayfact F19): prepend the caller's read-only working-context blob to a worker's task message, so a
49
+ * sliced child can LOCATE its artifact (absolute paths / cwd) — the concrete context the Planner otherwise
50
+ * strips when it paraphrases the parent goal into child subtasks. Distinct from `persona`: persona is a STANCE
51
+ * on the SYSTEM prompt (a privileged seam); context is neutral run-state FACTS on the USER message (the form
52
+ * the live POC `poc/ba9-context-thread.mjs` validated: no-context 0/3 → context 3/3 on a weak model). Absent/
53
+ * blank ⇒ the task message is byte-identical to pre-BA-9 (backward-compatible). Carries down the tree via
54
+ * `forChild` (a child of a worker rooted at `/proj` is still rooted at `/proj`), like `persona`.
55
+ * @param {string} task
56
+ * @param {unknown} context
57
+ * @returns {string}
58
+ */
59
+ function withContext(task, context) {
60
+ const c = typeof context === 'string' ? context.trim() : '';
61
+ return c ? `Working context (read-only):\n${c}\n\n${task}` : task;
62
+ }
63
+
64
+ /**
65
+ * The ctx handed to a worker `Loop.run({ ctx })` or to a direct `ctx.policy(...)` checkpoint — i.e. the ctx
66
+ * that a wired gate records VERBATIM into the audit as `action._ctx` (see `defaultActionTranslator` in
67
+ * src/bareguard-adapter.js). It STRIPS the live `provider` instance, because that object carries the API key
68
+ * (`provider.apiKey`) and bareguard serializes `_ctx` to disk — so an un-stripped ctx writes the raw
69
+ * `sk-…` key into the plaintext audit log (F16/BA-1, confirmed by relayfact probe-03).
70
+ *
71
+ * Only the AUDITED copy is cleaned: the provider still rides in the recurse-internal ctx that is threaded into
72
+ * each child `recurse()` self-call (children need `ctx.provider` to run), and the worker Loop already receives
73
+ * the provider as a constructor option — `Loop.run` never reads `ctx.provider`. The provider's IDENTITY is not
74
+ * lost from the audit either: the meter records the provider NAME on the `{type:'llm'}` action's args.
75
+ *
76
+ * NB: this strips the provider only — the leak that was grounded. A caller that threads its OWN secret-bearing
77
+ * fields onto ctx is backstopped by bareguard-side redaction (BG-1), the defense-in-depth pair to this fix.
78
+ * @param {RecurseCtx} ctx
79
+ * @param {object} [overrides] - extra fields to set on the audited copy (e.g. `{ depth }`).
80
+ * @returns {object}
81
+ */
82
+ function auditSafeCtx(ctx, overrides = {}) {
83
+ const safe = { ...(ctx || {}) };
84
+ delete (/** @type {any} */ (safe)).provider;
85
+ return { ...safe, ...overrides };
86
+ }
87
+
88
+ /** Valid tri-state `Verdict.status` values a caller arbiter (sensor/verifier) may return in lieu of a boolean `pass`. */
89
+ const SENSOR_STATUS = new Set(['satisfied', 'needs_revision', 'failed']);
90
+
91
+ /**
92
+ * BA-15 — a TYPED signal that a caller arbiter (the `refineLeaf.sensor` or the `opts.evaluate` verifier)
93
+ * broke (threw non-Halt, or returned a malformed verdict). Classified by `instanceof` + `.tag`, NOT by
94
+ * re-parsing an `Error.message` prefix — so an intermediate layer that rewords the message (the exact class
95
+ * of the prior loop.js HaltError-wrapping bug) or a Loop/provider error whose text happens to begin
96
+ * `broken-sensor: ` can never be mis-labeled. Module-local: it is always thrown AND caught inside recurse.js
97
+ * (never propagates to a caller), so it needs no `errors.js` entry or public export.
98
+ */
99
+ class BrokenArbiterError extends Error {
100
+ /**
101
+ * @param {'broken-sensor'|'broken-verifier'} tag - which seam broke.
102
+ * @param {string} detail - what the arbiter did (surfaced as `receipts.blockerDetail`).
103
+ * @param {{cause?: any}} [options] - `cause` preserves the original error (stack/type) for debugging.
104
+ */
105
+ constructor(tag, detail, options = {}) {
106
+ super(`${tag}: ${detail}`, options.cause !== undefined ? { cause: options.cause } : undefined);
107
+ this.name = 'BrokenArbiterError';
108
+ this.tag = tag;
109
+ this.detail = detail;
110
+ }
111
+ }
112
+
113
+ /**
114
+ * BA-15 — validate a caller arbiter's return at a close seam (the `refineLeaf.sensor` AND the caller
115
+ * `opts.evaluate` verifier). A verdict is well-formed iff it is an object carrying a boolean `pass` OR a
116
+ * valid tri-state `status` (the two shapes `refine`/callers branch on). Returns `null` when well-formed,
117
+ * else a short description of the malformation ("named, never coerced" — a garbage verdict otherwise reads
118
+ * as pass:false with critique:null at the sensor seam, or rides a converged-shaped return at the verify slot).
119
+ * @param {any} v
120
+ * @returns {string|null}
121
+ */
122
+ function verdictShapeFault(v) {
123
+ if (v === null || typeof v !== 'object' || Array.isArray(v)) {
124
+ return `returned ${v === null ? 'null' : Array.isArray(v) ? 'an array' : `a ${typeof v}`}`;
125
+ }
126
+ // A PRESENT `pass` counts whatever its type (`1`/`0`/`'yes'` are a long-standing yes-no convention, and
127
+ // `refine` has always branched on its TRUTHINESS). BA-15 exists to catch a verdict carrying NO usable
128
+ // signal — not to reject one that answers clearly in a different dialect: demanding a strict boolean
129
+ // silently flipped previously-CONVERGING adopter sensors to a permanent first-attempt block.
130
+ if (v.pass != null || SENSOR_STATUS.has(v.status)) return null;
131
+ const keys = Object.keys(v).slice(0, 5).join(', ');
132
+ return `returned an object with neither a usable \`pass\` nor a valid \`status\` (keys: ${keys || 'none'})`;
133
+ }
134
+
135
+ /** Upper bound on a `blockerDetail` fragment — it rides into receipts and, via a wired gate, onto disk. */
136
+ const DETAIL_MAX = 200;
137
+
138
+ /**
139
+ * BA-15 — a readable one-liner for ANYTHING thrown by a caller arbiter. `String(err)` on a non-Error throw
140
+ * (a test harness rejecting with a raw `{code:'ENOENT', path}` result is the common case) yields the useless
141
+ * `[object Object]`, defeating `blockerDetail`'s entire purpose: naming what broke so the operator can fix it.
142
+ * @param {any} err
143
+ * @returns {string}
144
+ */
145
+ function describeThrown(err) {
146
+ const clamp = (s) => (s.length > DETAIL_MAX ? `${s.slice(0, DETAIL_MAX)}… (truncated)` : s);
147
+ if (err instanceof Error && typeof err.message === 'string' && err.message) return clamp(err.message);
148
+ if (err === null || typeof err !== 'object') return clamp(String(err));
149
+ // Deliberately NOT a whole-object dump. A thrown non-Error is typically a spawn/exec RESULT, which routinely
150
+ // carries a full stdout buffer and an env snapshot — and `blockerDetail` rides into `receipts`, which a wired
151
+ // gate serializes VERBATIM into a plaintext audit log (the F16/BA-1 lesson: never let caller data of unknown
152
+ // shape reach the audit unfiltered). Take only the conventional diagnostic fields, clamped.
153
+ try {
154
+ const picked = ['name', 'code', 'errno', 'syscall', 'path', 'status', 'signal', 'message']
155
+ .filter(k => typeof err[k] === 'string' || typeof err[k] === 'number')
156
+ .map(k => `${k}=${String(err[k])}`)
157
+ .join(' ');
158
+ if (picked) return clamp(picked);
159
+ } catch { /* a throwing accessor / Proxy trap — fall through to the type tag */ }
160
+ return Object.prototype.toString.call(err);
161
+ }
162
+
163
+ /**
164
+ * BA-15 — run a caller arbiter (the `refineLeaf.sensor` or the `opts.evaluate` verifier) and NAME a broken one
165
+ * rather than let it launder. A non-`HaltError` throw or a malformed return (per {@link verdictShapeFault}) is
166
+ * re-thrown as a typed {@link BrokenArbiterError} the call sites classify by `instanceof` + `.tag` (NEVER by
167
+ * re-parsing the message text); a `HaltError` passes straight through (clean
168
+ * governance exit, BA-2). One helper so the sensor and verifier seams stay byte-identical (same guidance
169
+ * string, same fault taxonomy) — a divergence between them was the copy-paste risk this replaces.
170
+ * A verdict that carries a valid `status` but no boolean `pass` is NORMALIZED to add `pass = status ===
171
+ * 'satisfied'` (the same derivation as `evaluator.js`): the advertised `{status}` contract must actually
172
+ * WORK — `refine.js` stops the leaf on `verdict.pass`, so a bare `{status:'satisfied'}` would otherwise never
173
+ * satisfy, burn every iteration, and report `passed:false` (a satisfied close mislabeled as non-recovery).
174
+ * @template {{pass?: boolean, status?: string}} T
175
+ * @param {'broken-sensor'|'broken-verifier'} tag - the fault channel, carried on the thrown error's `.tag`.
176
+ * @param {() => (T | Promise<T>)} call - invokes the arbiter (already bound to its result/ctx args).
177
+ * @returns {Promise<T>} the arbiter's well-formed verdict (with `pass` derived from `status` when absent).
178
+ */
179
+ async function runArbiter(tag, call) {
180
+ const who = tag === 'broken-sensor' ? 'sensor' : 'evaluate';
181
+ const shape = `a ${who === 'sensor' ? 'sensor' : 'verifier'} must return {pass} or {status: 'satisfied'|'needs_revision'|'failed'}`;
182
+ /** A throw from the arbiter's own body (sync or async rejection) — "the sensor threw". */
183
+ const threw = (err) => {
184
+ if (err instanceof HaltError || err instanceof BrokenArbiterError) return err;
185
+ // `cause` keeps the original error (stack + type) reachable for debugging; `detail` stays the short label.
186
+ return new BrokenArbiterError(tag, `${who} threw: ${describeThrown(err)}`, { cause: err });
187
+ };
188
+ /** A throw from READING the value the arbiter returned — "the verdict is unreadable", a different fault. */
189
+ const unreadable = (err) => {
190
+ if (err instanceof HaltError || err instanceof BrokenArbiterError) return err;
191
+ return new BrokenArbiterError(tag, `${who} returned a verdict whose properties could not be read: ${describeThrown(err)} — ${shape}`, { cause: err });
192
+ };
193
+
194
+ // Typed `any` deliberately: this block probes an UNTRUSTED caller return (it may be a promise, a plain
195
+ // verdict, or a hostile Proxy), so the generic `T | Promise<T>` narrowing does not apply until it is settled.
196
+ /** @type {any} */
197
+ let raw;
198
+ try {
199
+ raw = call();
200
+ } catch (err) { throw threw(err); }
201
+
202
+ // `await`ing directly would conflate two different faults: the await PROBES `.then` on the returned value,
203
+ // so an accessor-backed/Proxy verdict throws during the await and gets reported as "the sensor threw" —
204
+ // sending the operator hunting a `throw` in a sensor that returned perfectly normally. Probe the thenable
205
+ // separately (a throw HERE is the returned value being unreadable) and only then await (a rejection THERE
206
+ // is genuinely the arbiter's body failing).
207
+ let thenable;
208
+ try {
209
+ thenable = raw !== null && (typeof raw === 'object' || typeof raw === 'function') && typeof raw.then === 'function';
210
+ } catch (err) { throw unreadable(err); }
211
+
212
+ /** @type {any} */
213
+ let v = raw;
214
+ if (thenable) {
215
+ try {
216
+ v = await raw;
217
+ } catch (err) { throw threw(err); }
218
+ }
219
+ // The SHAPE INSPECTION is guarded SEPARATELY: reading `.status`/`.pass`/`Object.keys` on a returned Proxy or
220
+ // accessor-backed object can itself throw. Unguarded that escapes untyped (the very uncaught crash this seam
221
+ // prevents, one step later) — but folding it into the call's own catch is also wrong: it reports "the sensor
222
+ // threw" for a sensor that RETURNED NORMALLY, sending the operator hunting a `throw` that does not exist.
223
+ // The fault is in the returned VALUE, so it is named as such.
224
+ try {
225
+ const fault = verdictShapeFault(v);
226
+ if (fault) throw new BrokenArbiterError(tag, `${who} ${fault} — ${shape}`);
227
+ // Derive `pass` from a status-only verdict so the advertised `{status}` shape actually gates `refine`, which
228
+ // branches on `verdict.pass`. NEVER mutate the caller's object — and never flatten it either: an object
229
+ // spread copies OWN enumerable properties only, so a class-instance verdict whose `status`/`critique` are
230
+ // PROTOTYPE getters passes the shape check above and then comes out the other side with those fields
231
+ // ERASED (critique lost ⇒ every retry re-sends the plain task with zero feedback — the exact burn BA-15
232
+ // exists to prevent). Copy descriptors onto the SAME prototype so accessor-backed fields survive.
233
+ if (v.pass == null && typeof v.status === 'string') {
234
+ const copy = Object.create(Object.getPrototypeOf(v), Object.getOwnPropertyDescriptors(v));
235
+ Object.defineProperty(copy, 'pass', {
236
+ value: v.status === 'satisfied', writable: true, enumerable: true, configurable: true,
237
+ });
238
+ return /** @type {T} */ (copy);
239
+ }
240
+ return v;
241
+ } catch (err) { throw unreadable(err); }
242
+ }
243
+
244
+ /**
245
+ * BA-8 leaf-refine — run a DEFINITE leaf as a bounded generate→sense→regenerate loop (relayfact F17). Reuses the
246
+ * existing `refine.js` primitive (the Outcomes iterate→grade→revise port): each attempt is a FRESH leaf Loop
247
+ * (fresh window = fresh-feedback, D6/A1) seeded with the working-context'd task + (on a retry) the prior GAP, run
248
+ * at an ESCALATING temperature — the live-validated requirement that lets a weak model escape a repeat-the-same-
249
+ * mistake rut (a flat temperature recovered 0/5 in `poc/ba8-leaf-refine.mjs`). The `sensor` is the caller's
250
+ * DETERMINISTIC close (test/compile/lint, not a model judge). Governance is bareguard's: every attempt is gate-
251
+ * checked (`ctx.policy`) and metered (`onLlmResult`); a HaltError mid-loop is a clean `{incomplete}`. Honest
252
+ * non-recovery is reported (`receipts.refineLeaf.passed=false`), never a faked pass. An optional rubric `verify`
253
+ * still runs on top when a `contract`/`evaluate`/critical applies (the sensor gates retries; the rubric grades).
254
+ * @param {string} task
255
+ * @param {RecurseCtx} ctx
256
+ * @param {RecurseOptions} opts
257
+ * @param {{provider: Provider, system: string, handleTools: ToolDef[], depth: number, critical: boolean, node: RecurseNode, sensor: Function}} state
258
+ * @returns {Promise<RecurseResult>}
259
+ */
260
+ async function runRefineLeaf(task, ctx, opts, state) {
261
+ const { provider, system, handleTools, depth, critical, node, sensor } = state;
262
+ node.model = provider.model || null;
263
+ const cfg = /** @type {{maxIterations?: number, temperatures?: number[], rejectedBuffer?: boolean}} */ (opts.refineLeaf || {});
264
+ const temps = Array.isArray(cfg.temperatures) && cfg.temperatures.length ? cfg.temperatures : DEFAULT_REFINE_TEMPS;
265
+ const maxIterations = Number.isInteger(cfg.maxIterations) && /** @type {number} */ (cfg.maxIterations) > 0
266
+ ? /** @type {number} */ (cfg.maxIterations) : temps.length;
267
+ // BA-14 rejected-attempt buffer: surface the model's OWN prior failed attempts verbatim ("you wrote these,
268
+ // they failed X — write something DIFFERENT") — a SkillOpt-shaped directed-diversity lever. `rejectedBuffer`:
269
+ // `true` = force on (also on temperature-accepting models); `false` = force off; unset = ADAPTIVE (engage only
270
+ // once a prior attempt's temperature was DROPPED, i.e. a temperature-fixed model where BA-8 escalation is inert
271
+ // and the buffer is the only lever — ba14 D>C). Escalation and the buffer are ANTAGONISTIC (ba14b: temp
272
+ // monotonically degrades the buffer 100→70→50% across 0.2/0.7/1.0), so when the buffer engages we HOLD temps[0].
273
+ const bufferForced = cfg.rejectedBuffer === true;
274
+ const bufferDisabled = cfg.rejectedBuffer === false;
275
+ let bufferUsed = false; // receipt: did any iteration actually inject the ledger?
276
+ const LEDGER_ENTRY_CAP = 600, LEDGER_WHY_CAP = 400;
277
+ const formatLedger = (/** @type {Array<{result: any, verdict: any}>} */ history) => history.map((h, i) => {
278
+ const code = String(h.result == null ? '' : h.result).replace(/```[a-zA-Z]*\n?/g, '').trim().slice(0, LEDGER_ENTRY_CAP);
279
+ const why = h.verdict && typeof h.verdict.critique === 'string' ? h.verdict.critique.slice(0, LEDGER_WHY_CAP) : '';
280
+ return `--- Rejected attempt ${i + 1} (already failed — do NOT reproduce) ---\n${code}${why ? `\nFailed: ${why}` : ''}`;
281
+ }).join('\n\n');
282
+
283
+ // A refine leaf runs N Loops, so its receipts.tokens SUMS every attempt's spend (not just the last) — the
284
+ // honest cost of the node. The 4-tier tokens object (`{input,output,cacheCreation,cacheRead}`, loop.js) is flat
285
+ // numeric, so we accrue field-wise (robust to extra/renamed numeric fields). The gate already sees each attempt
286
+ // via onLlmResult independently; this is the receipts mirror. Stays null until an attempt produces metrics.
287
+ /** @type {Record<string, number>|null} */
288
+ let tokensSum = null;
289
+ const accrueTokens = (/** @type {any} */ t) => {
290
+ if (!t || typeof t !== 'object') return;
291
+ tokensSum = tokensSum || {};
292
+ for (const [k, v] of Object.entries(t)) if (typeof v === 'number') tokensSum[k] = (tokensSum[k] || 0) + v;
293
+ };
294
+ // BA-10 honest receipt: the EFFECTIVE temperature per attempt. A model that rejects a non-default
295
+ // `temperature` (400, unsupported/deprecated) runs at its DEFAULT — the provider drops it and the Loop
296
+ // surfaces `temperatureDropped`. Recording the requested temp would claim a value the model ignored, so
297
+ // a dropped attempt is stored as `null` ("provider default"). Indexed by iteration (refine calls once each).
298
+ /** @type {(number|null)[]} */
299
+ const effectiveTemps = [];
300
+ // BA-15/BA-5: the last attempt's text, kept OUTSIDE refine so a broken-sensor stop can still preserve the
301
+ // model's work — when the ARBITER breaks, the work was never judged; destroying it would punish the model
302
+ // for the caller's fault (refine's own history is lost on the throw).
303
+ /** @type {string|null} */
304
+ let lastAttemptText = null;
305
+ // One attempt = a fresh leaf Loop (no spawn tool: a retry is a direct correction, not a re-decomposition) at the
306
+ // iteration's temperature, with the GAP fed forward as fresh feedback. A governance halt → throw so refine stops.
307
+ const attempt = async ({ iteration, critique, history }) => {
308
+ const hist = Array.isArray(history) ? history : [];
309
+ // ADAPTIVE trigger: a prior attempt whose temperature the model rejected (BA-10) records `null` in
310
+ // effectiveTemps → escalation is inert on this (temperature-fixed) model, so engage the buffer. Forced-on
311
+ // engages regardless (incl. temperature-accepting models). Needs ≥1 prior attempt to have something to buffer.
312
+ const tempDropped = effectiveTemps.some((t) => t === null);
313
+ const useBuffer = hist.length > 0 && !bufferDisabled && (bufferForced || tempDropped);
314
+ // ba14b: temperature is antagonistic to the buffer's directed diversity — HOLD temps[0] when it engages;
315
+ // otherwise escalate (BA-8, the no-memory lever). On a temperature-fixed model both collapse to the default.
316
+ const temperature = useBuffer ? temps[0] : temps[Math.min(iteration, temps.length - 1)];
317
+ const loop = new Loop({
318
+ provider, system,
319
+ policy: ctx.policy || undefined,
320
+ onLlmResult: ctx.onLlmResult || undefined,
321
+ stream: /** @type {any} */ (ctx.stream) || undefined,
322
+ throwOnError: false,
323
+ });
324
+ const base = withContext(task, opts.context);
325
+ let userText;
326
+ if (useBuffer) {
327
+ bufferUsed = true;
328
+ userText = `${base}\n\nYou have already tried the following and each FAILED. Do NOT reproduce them — write a STRUCTURALLY DIFFERENT result that passes ALL checks:\n\n${formatLedger(hist)}`;
329
+ } else if (critique) {
330
+ userText = `${base}\n\nYour previous attempt FAILED these checks:\n${critique}\n\nReturn a corrected result that passes ALL of them.`;
331
+ } else {
332
+ userText = base;
333
+ }
334
+ const out = await loop.run([{ role: 'user', content: userText }], handleTools, { ctx: auditSafeCtx(ctx, { depth }), temperature });
335
+ // `temperatureDropped` is set on the Loop result only when the model rejected the requested temperature
336
+ // (BA-10); it's absent on the error/halt return shapes, so read it through a narrow cast.
337
+ const dropped = /** @type {{temperatureDropped?: boolean}} */ (out).temperatureDropped;
338
+ effectiveTemps[iteration] = dropped ? null : temperature;
339
+ accrueTokens(out.metrics ? out.metrics.tokens : null);
340
+ // BA-5: capture BEFORE the throws. The Loop returns its last non-empty text on EVERY terminating path
341
+ // (halt/deny/truncation/refusal), so a throw placed above this line would discard the text of the very
342
+ // attempt that terminated — leaving `best:null` on a FIRST-attempt halt, the exact loss the catch-branch
343
+ // preservation exists to prevent. (Caught by review: the earlier tests only halted on attempt 2, where a
344
+ // prior clean attempt had already populated this.)
345
+ lastAttemptText = out.text || lastAttemptText;
346
+ if (typeof out.error === 'string' && out.error.startsWith('halt:')) throw new HaltError('refine-leaf attempt halted', { rule: out.error.slice('halt:'.length) });
347
+ if (out.error) throw new Error(out.error); // a non-halt worker fault → honest incomplete
348
+ return out.text;
349
+ };
350
+
351
+ // BA-15: the sensor call is WRAPPED (via runArbiter) so a broken arbiter is NAMED, never coerced. A non-Halt
352
+ // throw (the caller's test runner crashed — ENOENT, syntax error in the harness) and a malformed return are
353
+ // the same fault class: "didn't judge", which must never collapse into "judged-and-failed" (the model's
354
+ // fault) or a bare {incomplete} (indistinguishable from a provider death). The throw stops refine at the
355
+ // FIRST broken close — retrying against a broken arbiter burns every remaining attempt for nothing (each
356
+ // retry would carry critique:null, i.e. the plain task again). HaltError passes through (governance, BA-2).
357
+ const evaluate = (result, c) => runArbiter('broken-sensor', () => sensor(result, { task, context: opts.context, contract: c.contract }));
358
+
359
+ try {
360
+ const outcome = await refine({
361
+ attempt,
362
+ evaluate,
363
+ contract: typeof opts.contract === 'string' ? opts.contract : undefined,
364
+ maxIterations,
365
+ });
366
+ node.tokens = tokensSum;
367
+ // `temperatures` = the EFFECTIVE temps (BA-10): a `null` marks an attempt whose requested temperature the
368
+ // model rejected and ran at its default — so the receipt never claims a value the model ignored. On a
369
+ // temperature-accepting model this equals the requested `temps.slice(0, iterations)` (byte-identical receipt).
370
+ node.refineLeaf = { iterations: outcome.iterations, passed: !!(outcome.verdict && outcome.verdict.pass), temperatures: effectiveTemps.slice(0, outcome.iterations), rejectedBuffer: bufferUsed };
371
+ const result = outcome.result;
372
+
373
+ // Optional rubric layer on top of the deterministic sensor (RC-7): forced for critical, or a contract/override.
374
+ const wantVerify = critical || typeof opts.contract === 'string' || typeof opts.evaluate === 'function';
375
+ if (wantVerify) {
376
+ // `return await` (not a bare `return`) is load-bearing here — see verifyOrBlock's JSDoc.
377
+ return await verifyOrBlock(task, result, ctx, opts, node);
378
+ }
379
+ // No rubric layer ⇒ the sensor's final verdict IS the node verdict (a non-pass is surfaced, not hidden).
380
+ node.verdict = outcome.verdict || null;
381
+ return { result, verdict: outcome.verdict || null, receipts: node };
382
+ } catch (err) {
383
+ node.tokens = tokensSum; // record whatever attempts DID spend, on both the halt and fault paths
384
+ // The refineLeaf receipt must ride EVERY terminating path, not just the clean one (same invariant as BA-10's
385
+ // `temperatureDropped`): a leaf that ran attempts then halted/faulted still spent tokens and may have engaged
386
+ // the buffer. `effectiveTemps[iteration]` is set BEFORE each attempt's throw, so it reflects every attempt made.
387
+ // NOT unconditional: the refine loop may have COMPLETED (receipt already written, possibly `passed:true`) and
388
+ // the throw come from the verify layer below it — clobbering that to `passed:false` would report a sensor that
389
+ // never closed when it did, misattributing a verify-slot halt to a non-converging leaf.
390
+ if (!node.refineLeaf) {
391
+ node.refineLeaf = { iterations: effectiveTemps.length, passed: false, temperatures: effectiveTemps.slice(), rejectedBuffer: bufferUsed };
392
+ }
393
+ // BA-5: EVERY terminating branch preserves the model's last non-empty attempt (`lastAttemptText`), never
394
+ // `null` — matching the plain-worker path (`best: out.text || null`) and the "bounds PRESERVE work"
395
+ // invariant. A refine leaf is the sole cross-attempt text channel in a ralph-style retry; dropping it on a
396
+ // halt/deny/fault (as this path did pre-BA-15) loses attempt N's only bridge to attempt N+1.
397
+ if (err instanceof HaltError) {
398
+ node.halted = true;
399
+ node.incomplete = true;
400
+ return { incomplete: true, best: lastAttemptText, receipts: node };
401
+ }
402
+ // BA-11: a deny-spin inside a refine attempt (the Loop short-circuited after N consecutive governance
403
+ // denials, rethrown at recurse.js as `denied:<tool>`) is a LABELED governance block, not a model fault.
404
+ if (typeof err?.message === 'string' && err.message.startsWith('denied:')) {
405
+ node.incomplete = true;
406
+ node.blocker = 'governance-deny';
407
+ return { incomplete: true, best: lastAttemptText, blocker: 'governance-deny', receipts: node };
408
+ }
409
+ // BA-15: the caller's SENSOR broke — a faulty arbiter, not a model failure. Named (like BA-11's
410
+ // governance-deny) so the caller fixes the sensor instead of debugging the model; `best` preserves the
411
+ // model's last non-empty attempt (BA-5) — the arbiter, not the model, is at fault.
412
+ if (err instanceof BrokenArbiterError && err.tag === 'broken-sensor') {
413
+ node.incomplete = true;
414
+ node.blocker = 'broken-sensor';
415
+ node.blockerDetail = err.detail;
416
+ // `blockerDetail` rides the RESULT too, not just receipts: it is the actionable half of the label (WHAT
417
+ // the sensor did), and a parent reading a child's return — or a caller branching on the documented
418
+ // `{blocker}` shape — should not have to walk the receipts tree to get it.
419
+ return { incomplete: true, best: lastAttemptText, blocker: 'broken-sensor', blockerDetail: err.detail, receipts: node };
420
+ }
421
+ node.incomplete = true;
422
+ return { incomplete: true, best: lastAttemptText, receipts: node };
423
+ }
424
+ }
425
+
426
+ /**
427
+ * The verify slot (§7.1) — the Evaluator fills it by default. `opts.evaluate` overrides. The default path
428
+ * runs an isolated adversarial rubric grader (separate context window): when a `contract` is present it
429
+ * grades against THAT (A3); otherwise it grades full-and-correct against the goal — which is exactly the
430
+ * `critical → force verify` rail (a critical task with no contract still gets an independent grader).
431
+ * @param {string} task
432
+ * @param {any} result
433
+ * @param {RecurseCtx} ctx
434
+ * @param {RecurseOptions} opts
435
+ * @returns {Promise<Verdict>}
436
+ */
437
+ function verify(task, result, ctx, opts) {
438
+ const contract = typeof opts.contract === 'string' ? opts.contract : null;
439
+ // BA-9: the verifier sees the working-context too — neutral facts (not a stance, so no anti-sycophancy risk),
440
+ // and an agentic critic needs the path to exercise the artifact. A caller `evaluate` gets the RAW task (it owns
441
+ // its own context); only the default isolated grader is contextualized.
442
+ if (typeof opts.evaluate === 'function') {
443
+ // BA-15 (verifier seam): the CALLER-supplied verifier is wrapped exactly like the refineLeaf sensor — a
444
+ // non-Halt throw or a malformed return is a faulty ARBITER, tagged so the call sites label it (pre-fix a
445
+ // throw crashed the whole run on the plain-worker path / laundered to a bare {incomplete} under refineLeaf,
446
+ // and a garbage verdict rode a CONVERGED-shaped {result, verdict} out). The default Evaluator path below is
447
+ // NOT wrapped: it constructs well-formed Verdicts by design, and its failures are provider-class faults.
448
+ // Capture the narrowed reference in a const: `typeof opts.evaluate === 'function'` does NOT survive into the
449
+ // nested async closure (TS re-widens `opts.evaluate` to possibly-undefined there → TS2722/TS18048).
450
+ // BOUND to `opts`, because a bare `const evaluate = opts.evaluate` DETACHES the method: the call used to be
451
+ // `opts.evaluate(...)` (receiver `opts`), and a caller passing a class method (`evaluate: grader.check`)
452
+ // would suddenly get `this === undefined` and throw on its first `this.x` read — a working (if degraded)
453
+ // integration flipped to a hard `broken-verifier` by an unrelated typecheck fix.
454
+ const evaluate = opts.evaluate.bind(opts);
455
+ return runArbiter('broken-verifier', () => evaluate(result, { contract, task }));
456
+ }
457
+ const provider = ctx.provider || opts.provider;
458
+ const evaluator = new Evaluator({ provider });
459
+ const rubric = contract
460
+ ? 'Judge whether the result satisfies the definition of done. Be strict and adversarial; cite the specific gap on any shortfall.'
461
+ : 'Judge whether the result fully and correctly answers the goal. Be strict and adversarial; cite the specific gap on any shortfall.';
462
+ return evaluator.evaluate(
463
+ withContext(task, opts.context),
464
+ result,
465
+ { rubric, contract: contract || undefined },
466
+ { onLlmResult: /** @type {any} */ (ctx.onLlmResult), policy: ctx.policy },
467
+ );
468
+ }
469
+
470
+ /**
471
+ * BA-15 (verifier seam) — run the verify slot, converting a `BrokenArbiterError` into a LABELED
472
+ * `{ incomplete, blocker:'broken-verifier' }` return with `best` preserving the result the arbiter failed to
473
+ * judge (BA-5: the work exists — best-effort, not a graded pass). One helper so all five dispatch paths (worker /
474
+ * refineLeaf / scan / partition / fanout) get identical semantics. Anything else (HaltError, a default-
475
+ * Evaluator provider fault) rethrows to the caller's own catch, exactly as before.
476
+ *
477
+ * MUST be called as `return await verifyOrBlock(...)` from inside each caller's `try` — a bare
478
+ * `return verifyOrBlock(...)` returns the promise and exits the `try` before it settles, so a verifier
479
+ * `HaltError` would escape the caller's own catch instead of landing as a clean `{ incomplete, halted }`
480
+ * (proven by `poc/ba15-broken-sensor.mjs` [E4]).
481
+ * @param {string} task
482
+ * @param {any} result
483
+ * @param {RecurseCtx} ctx
484
+ * @param {RecurseOptions} opts
485
+ * @param {RecurseNode} node
486
+ * @returns {Promise<RecurseResult>}
487
+ */
488
+ async function verifyOrBlock(task, result, ctx, opts, node) {
489
+ try {
490
+ const verdict = await verify(task, result, ctx, opts);
491
+ node.verdict = verdict;
492
+ return { result, verdict, receipts: node };
493
+ } catch (err) {
494
+ // Only a typed BrokenArbiterError is a caller-verifier fault; everything else (HaltError, a default-
495
+ // Evaluator provider fault) rethrows to the caller's own catch. Classified by type, never by message text.
496
+ if (!(err instanceof BrokenArbiterError)) throw err;
497
+ node.incomplete = true;
498
+ node.blocker = 'broken-verifier';
499
+ node.blockerDetail = err.detail;
500
+ // `blockerDetail` rides the RESULT too (see the sensor-side sibling) — the actionable half of the label.
501
+ return { incomplete: true, best: result, blocker: 'broken-verifier', blockerDetail: err.detail, receipts: node };
502
+ }
503
+ }
504
+
505
+ /** Internal opts key: `recurse` hands its already-resolved state (provider/system/tools/depth/node) to `refineWorker`. Not public. */
506
+ const PRE = Symbol('refineWorker.pre');
507
+
508
+ /**
509
+ * The audit node every recurse/refineWorker call returns as `receipts` (RC-10). One factory so the two entry
510
+ * points cannot drift. `retrieval` stays null here; `recurse` assigns it once its routing resolves.
511
+ * @param {string} task
512
+ * @param {number} depth
513
+ * @param {{level: string, score: number}} assessment
514
+ * @param {boolean} critical
515
+ * @returns {RecurseNode}
516
+ */
517
+ function newNode(task, depth, assessment, critical) {
518
+ return {
519
+ task,
520
+ depth,
521
+ complexity: { level: assessment.level, score: assessment.score },
522
+ critical,
523
+ spawned: [],
524
+ verdict: null,
525
+ incomplete: false,
526
+ halted: false,
527
+ tokens: null,
528
+ model: null,
529
+ // Always-defined so the audit trail is consistent across ALL dispatch paths.
530
+ // null = no corpus retrieval (Family A/B single-shot or semantic fan-out); a mode string when one ran.
531
+ retrieval: null,
532
+ };
533
+ }
534
+
535
+ /**
536
+ * Run ONE worker as a bounded refine loop: each attempt is a fresh Loop at an escalating temperature, a
537
+ * deterministic caller `sensor` judges it, the GAP is fed forward, and a rejected-attempt buffer engages on a
538
+ * temperature-fixed model. Does exactly what `recurse(task, ctx, {maxDepth:0, refineLeaf, ...})` does and returns
539
+ * the SAME shape (`{result, verdict, receipts}` or `{incomplete, best, blocker?, receipts}`), incl.
540
+ * `receipts.refineLeaf`. Takes the same `opts` as `recurse` (`refineLeaf`, `persona`, `context`, `tools`,
541
+ * `contract`, `evaluate`; `maxDepth` is REJECTED with a ValidationError — a worker is always a leaf). Governance is the caller's gate (`ctx.policy`/`onLlmResult`).
542
+ * `opts.evaluate` (optional `(result, {contract, task}) => Verdict`) is supported: when set (as with a `contract` or
543
+ * a critical task) it runs AFTER the sensor loop and its verdict is the TOP verdict — it overrides the sensor's
544
+ * (a failing sensor verdict is replaced by the evaluate verdict; a throwing/garbage evaluate is `blocker:'broken-verifier'`).
545
+ * @when you want a model to produce an artifact that a deterministic check (test/compile/lint) must pass, retried with fed-back gaps — one worker, no decomposition
546
+ * @fails returns `{incomplete, best}` on non-recovery, halt, deny-spin (`blocker:'governance-deny'`) or a broken sensor (`blocker:'broken-sensor'`); throws on a missing task, provider or sensor
547
+ * @param {string} task
548
+ * @param {RecurseCtx} [ctx]
549
+ * @param {RecurseOptions} [opts]
550
+ * @returns {Promise<RecurseResult>}
551
+ * @example
552
+ * const out = await refineWorker('write add(a,b)', { provider }, { tools: [editTool], refineLeaf: { sensor } });
553
+ * if (out.incomplete) console.log(out.blocker, out.best);
554
+ */
555
+ async function refineWorker(task, ctx = {}, opts = {}) {
556
+ if (/** @type {any} */ (opts).maxDepth !== undefined) {
557
+ throw new ValidationError('refineWorker: opts.maxDepth is not supported (a refineWorker is always a depth-0 leaf; there is nothing to cap) — remove it');
558
+ }
559
+ const sensor = opts.refineLeaf && opts.refineLeaf.sensor;
560
+ if (typeof sensor !== 'function') {
561
+ throw new Error('[refineWorker] opts.refineLeaf.sensor must be a function');
562
+ }
563
+ /** @type {any} */
564
+ let state = /** @type {any} */ (opts)[PRE]; // internal hand-over from `recurse` (state it already resolved)
565
+ if (!state) {
566
+ if (typeof task !== 'string' || task.length === 0) {
567
+ throw new Error('[refineWorker] task must be a non-empty string');
568
+ }
569
+ const provider = ctx.provider || opts.provider;
570
+ if (!provider) throw new Error('[refineWorker] requires a provider on ctx.provider (or opts.provider)');
571
+ const depth = Number.isInteger(ctx.depth) ? /** @type {number} */ (ctx.depth) : 0;
572
+ const maxDepth = 0; // a refineWorker is always a leaf (opts.maxDepth is rejected above)
573
+ const assessment = assessComplexity(task);
574
+ const critical = isCritical(task);
575
+ state = {
576
+ provider,
577
+ system: workerPersonaPrefix(opts.persona) + DECOMPOSITION_POLICY + capabilityScrub(depth, maxDepth),
578
+ handleTools: Array.isArray(opts.tools) ? opts.tools : [],
579
+ depth,
580
+ critical,
581
+ node: newNode(task, depth, assessment, critical),
582
+ };
583
+ }
584
+ return runRefineLeaf(task, ctx, opts, { ...state, sensor });
585
+ }
586
+
587
+ module.exports = {
588
+ refineWorker,
589
+ PRE,
590
+ newNode,
591
+ withContext,
592
+ auditSafeCtx,
593
+ workerPersonaPrefix,
594
+ runArbiter,
595
+ verifyOrBlock,
596
+ verify,
597
+ BrokenArbiterError,
598
+ };
@@ -1,53 +0,0 @@
1
- export type Provider = import("../types").Provider;
2
- /**
3
- * The reducer dispatcher used by `recurse` (and, at build step 5, Family B over `runPlan` results[]).
4
- * @param {string} task
5
- * @param {any[]} results - The worker/child result values (NOT transcripts — copy-on-return holds upstream).
6
- * @param {object} [opts]
7
- * @param {Function} [opts.reduce] - A deterministic code-reduce: `({ task, results }) => any`. The §9.1
8
- * aggregation path; takes precedence over `strategy`.
9
- * @param {'concat'|'merge'} [opts.strategy='concat'] - Built-in strategy when no `reduce` fn is given.
10
- * @param {Provider} [opts.provider] - Required for `merge`.
11
- * @param {string|null} [opts.contract]
12
- * @param {Function} [opts.onLlmResult]
13
- * @param {Function} [opts.policy]
14
- * @param {any} [opts.text] - The worker's own synthesized text (Family A), available to a `reduce` fn.
15
- * @param {any[]} [opts.children] - The receipts nodes, available to a `reduce` fn.
16
- * @param {any} [opts.ctx]
17
- * @returns {Promise<any>}
18
- */
19
- export function synthesize(task: string, results: any[], opts?: {
20
- reduce?: Function | undefined;
21
- strategy?: "concat" | "merge" | undefined;
22
- provider?: import("../types").Provider | undefined;
23
- contract?: string | null | undefined;
24
- onLlmResult?: Function | undefined;
25
- policy?: Function | undefined;
26
- text?: any;
27
- children?: any[] | undefined;
28
- ctx?: any;
29
- }): Promise<any>;
30
- /**
31
- * Deterministic lossless join — no LLM. The safe default when partials are independent and order-able.
32
- * @param {any[]} results
33
- * @returns {string}
34
- */
35
- export function concatReduce(results: any[]): string;
36
- /**
37
- * Subjective merge — an ISOLATED Loop (fresh context window, a harsh synthesis persona) combines the partials
38
- * into one answer. Use for prose / overlapping-findings synthesis; NEVER for arithmetic (§9.1 → use a
39
- * `reduce` fn). Budget visibility: forwards usage to `onLlmResult`. A governance HaltError propagates clean
40
- * (the caller decides), mirroring the Evaluator's agentic path.
41
- * @param {string} task
42
- * @param {any[]} results
43
- * @param {{provider: Provider, contract?: string|null, onLlmResult?: Function, policy?: Function}} opts
44
- * @returns {Promise<string>}
45
- * @throws {HaltError} a governance cap halted the synthesis Loop.
46
- */
47
- export function mergeReduce(task: string, results: any[], opts: {
48
- provider: Provider;
49
- contract?: string | null;
50
- onLlmResult?: Function;
51
- policy?: Function;
52
- }): Promise<string>;
53
- export const MERGE_PROMPT: string;