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.
- package/README.md +2 -2
- package/bareagent.context.md +29 -60
- package/index.d.ts +2 -5
- package/index.js +2 -5
- package/package.json +5 -1
- package/primitives.json +21 -12
- package/src/{recurse-retrieval.d.ts → recurse-adapters.d.ts} +71 -89
- package/src/{recurse-retrieval.js → recurse-adapters.js} +10 -60
- package/src/recurse-brakes.d.ts +111 -0
- package/src/recurse-brakes.js +154 -0
- package/src/recurse-env.d.ts +43 -0
- package/src/recurse-env.js +233 -0
- package/src/recurse-finish.d.ts +46 -0
- package/src/recurse-finish.js +123 -0
- package/src/recurse-prompts.d.ts +38 -0
- package/src/recurse-prompts.js +69 -1
- package/src/recurse.d.ts +114 -503
- package/src/recurse.js +176 -1513
- package/src/refine-worker.d.ts +155 -0
- package/src/refine-worker.js +598 -0
- package/src/recurse-synthesize.d.ts +0 -53
- package/src/recurse-synthesize.js +0 -106
package/src/recurse.js
CHANGED
|
@@ -1,22 +1,10 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
// Shape (§0, §4.2): "B-shell with an A-tool." A deterministic shell owns control flow; the model is OFFERED
|
|
9
|
-
// a `spawn_child` tool it MAY use to delegate a sub-task to a fresh context window. Default control is
|
|
10
|
-
// Family A (the model decides whether/how to decompose, bounded by depth + bareguard). assessComplexity is a
|
|
11
|
-
// HINT, not a gate: it only routes `simple → single-shot` and flags `critical → force adversarial verify`.
|
|
12
|
-
//
|
|
13
|
-
// The recursion mechanism is the spike-2 default (§4.5, POC-resolved): an IN-PROCESS self-call — `spawn_child`
|
|
14
|
-
// runs `recurse(subtask, {...ctx, depth: depth+1})` with a fresh Loop / fresh message array (true fresh
|
|
15
|
-
// window) — ~0 ms/node vs ≥90 ms/node for a process fork. Termination is bareguard's (the gate), reached via
|
|
16
|
-
// `ctx.depth` threaded into the `policy` check; `opts.maxDepth` is only the topology knob that stops OFFERING
|
|
17
|
-
// the spawn tool (NB-4 tool-shaping), never the safety halt (§6). Forced fan-out (Family B / NB-2) and the
|
|
18
|
-
// code-reduce default (NB-3) are later build steps; the seams (`opts.count`/`mode`, `opts.synthesize`) are
|
|
19
|
-
// present here so they slot in without a rewrite.
|
|
3
|
+
// recurse() v2 (docs/product/rlm-prd.md §0.1) — a real RLM over the Loop: the input lives in an env var map the
|
|
4
|
+
// model inspects through FIXED tools (no model-written code), sub-calls run over pieces from code, results live in
|
|
5
|
+
// vars, and the answer is a var of the caller-declared kind ("AI points, code decides"). Brakes are structural
|
|
6
|
+
// (src/recurse-brakes.js: one shared call counter in a closure the model cannot reach, formula cap) and every path
|
|
7
|
+
// ends in ONE tail (src/recurse-finish.js). Composes AROUND a Loop; `loop.js` never imports it.
|
|
20
8
|
|
|
21
9
|
/** @typedef {import('../types').Provider} Provider */
|
|
22
10
|
/** @typedef {import('../types').ToolDef} ToolDef */
|
|
@@ -24,1541 +12,216 @@
|
|
|
24
12
|
/** @typedef {{id: string, text: string}} Slice */
|
|
25
13
|
|
|
26
14
|
const { Loop } = require('./loop');
|
|
27
|
-
const { Evaluator } = require('./evaluator');
|
|
28
|
-
const { Planner } = require('./planner');
|
|
29
|
-
const { runPlan } = require('./run-plan');
|
|
30
15
|
const { assessComplexity, isCritical } = require('./complexity');
|
|
31
|
-
const {
|
|
32
|
-
const {
|
|
33
|
-
const {
|
|
34
|
-
const {
|
|
35
|
-
const {
|
|
36
|
-
|
|
37
|
-
impliesCompleteness,
|
|
38
|
-
normalizeCorpus,
|
|
39
|
-
buildSearchTool,
|
|
40
|
-
buildExactTool,
|
|
41
|
-
buildScanTool,
|
|
42
|
-
} = require('./recurse-retrieval');
|
|
43
|
-
|
|
44
|
-
// NB-2 forced-fan-out tier→count map (Family B). CALIBRATED live (poc/rlm-nb2-calibrate.mjs, gpt-4o-mini):
|
|
45
|
-
// the measured coverage knees {2,4,6} == predicted ⌈corpus/worker-budget⌉ for medium/complex/critical. These
|
|
46
|
-
// are OVERRIDABLE DEFAULTS, not discovered constants — the right count is task-specific (which is why
|
|
47
|
-
// `opts.count` overrides this and Family A is the adaptive default). `simple` → 1 (a single forced worker).
|
|
48
|
-
const TIER_COUNT = { simple: 1, medium: 2, complex: 4, critical: 6 };
|
|
49
|
-
// Cap on workers run at once within a fan-out wave (in-process; bareguard caps the family rate too). Overridable.
|
|
50
|
-
const DEFAULT_FANOUT_CONCURRENCY = 4;
|
|
51
|
-
// Data-driven width (NB-2 / §11): default items-per-worker for the PARTITION path. width = ⌈size/budget⌉ — how
|
|
52
|
-
// many parallel scan-workers a measured corpus needs. A calibratable knob (the §9.1 algorithm; corpus-specific),
|
|
53
|
-
// not a discovered constant — overridable via `opts.workerBudget`. 100 items ≈ a worker doing ~25 scan windows.
|
|
54
|
-
const DEFAULT_WORKER_BUDGET = 100;
|
|
55
|
-
// BA-8 leaf-refine: temperature ESCALATES per retry. The live POC (poc/ba8-leaf-refine.mjs) found that at a flat
|
|
56
|
-
// low temperature a weak model regenerates byte-identical wrong code and IGNORES even crisp deterministic
|
|
57
|
-
// feedback (0/5 recovery); recovery only appears once retries are given room to vary (0/5 → 2-3/5). So escalation
|
|
58
|
-
// is a DESIGN REQUIREMENT of the seam, not a tuning nicety. Overridable via `opts.refineLeaf.temperatures`.
|
|
59
|
-
// SCOPE (BA-10): this holds for models that ACCEPT `temperature`. On a temperature-fixed model (e.g.
|
|
60
|
-
// claude-sonnet-5 — the provider drops the param, `receipts.refineLeaf.temperatures` records `null`), the
|
|
61
|
-
// escalation lever is inert and the fed-back gap `critique` carries recovery alone (an empirical question the
|
|
62
|
-
// live run answers). The critique is the primary correction lever; temperature is a secondary diversity lever.
|
|
63
|
-
const DEFAULT_REFINE_TEMPS = [0.2, 0.7, 1.0];
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* Split an array into EXACTLY `n` contiguous, near-equal chunks (the data-partition for the §11 width path).
|
|
67
|
-
* Deterministic; every chunk non-empty when `n <= arr.length` (the caller caps `n` at the size).
|
|
68
|
-
* @template T @param {T[]} arr @param {number} n @returns {T[][]}
|
|
69
|
-
*/
|
|
70
|
-
function partitionInto(arr, n) {
|
|
71
|
-
/** @type {T[][]} */
|
|
72
|
-
const chunks = [];
|
|
73
|
-
let start = 0;
|
|
74
|
-
for (let i = 0; i < n; i++) {
|
|
75
|
-
const take = Math.ceil((arr.length - start) / (n - i)); // even spread of the remainder
|
|
76
|
-
chunks.push(arr.slice(start, start + take));
|
|
77
|
-
start += take;
|
|
78
|
-
}
|
|
79
|
-
return chunks;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* The persona prefix for a worker system prompt (Gap 3 / 0.21.0). A caller-supplied `opts.persona` AUGMENTS the
|
|
84
|
-
* decomposition policy + scrub (never replaces them — that text drives the spawn mechanics). Returns '' when
|
|
85
|
-
* absent/blank, so the default worker prompt is byte-identical to pre-0.21 (backward-compatible). Validated live
|
|
86
|
-
* by `poc/rlm-persona-seam.mjs` (the worker still decomposes, adopts the persona, and carries it to children).
|
|
87
|
-
* @param {unknown} persona
|
|
88
|
-
* @returns {string}
|
|
89
|
-
*/
|
|
90
|
-
function workerPersonaPrefix(persona) {
|
|
91
|
-
const p = typeof persona === 'string' ? persona.trim() : '';
|
|
92
|
-
return p ? p + '\n\n' : '';
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/**
|
|
96
|
-
* BA-9 (relayfact F19): prepend the caller's read-only working-context blob to a worker's task message, so a
|
|
97
|
-
* sliced child can LOCATE its artifact (absolute paths / cwd) — the concrete context the Planner otherwise
|
|
98
|
-
* strips when it paraphrases the parent goal into child subtasks. Distinct from `persona`: persona is a STANCE
|
|
99
|
-
* on the SYSTEM prompt (a privileged seam); context is neutral run-state FACTS on the USER message (the form
|
|
100
|
-
* the live POC `poc/ba9-context-thread.mjs` validated: no-context 0/3 → context 3/3 on a weak model). Absent/
|
|
101
|
-
* blank ⇒ the task message is byte-identical to pre-BA-9 (backward-compatible). Carries down the tree via
|
|
102
|
-
* `forChild` (a child of a worker rooted at `/proj` is still rooted at `/proj`), like `persona`.
|
|
103
|
-
* @param {string} task
|
|
104
|
-
* @param {unknown} context
|
|
105
|
-
* @returns {string}
|
|
106
|
-
*/
|
|
107
|
-
function withContext(task, context) {
|
|
108
|
-
const c = typeof context === 'string' ? context.trim() : '';
|
|
109
|
-
return c ? `Working context (read-only):\n${c}\n\n${task}` : task;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/**
|
|
113
|
-
* The opts a delegated child inherits. Strips the parent's TOP-LEVEL SETPOINT — `contract`/`evaluate` grade
|
|
114
|
-
* the WHOLE task's final answer; a child grading its own slice against the whole definition-of-done is wasted
|
|
115
|
-
* (the verdict is never read by the parent) AND misapplied (a slice isn't expected to satisfy the whole DoD).
|
|
116
|
-
* Also strips the forced-fan-out knobs (`count`/`mode`) so a child runs Family A, not another forced wave, and
|
|
117
|
-
* the TOP-LEVEL retrieval knobs (`retrieval`/`corpus`/`window`/`passes`) — those describe how the WHOLE task is
|
|
118
|
-
* answered over the parent's corpus; a child has its own subtask and must not re-scan the parent's full corpus
|
|
119
|
-
* (that would fan a whole-corpus count out under every child). The `critical → force-verify` SAFETY FLOOR is
|
|
120
|
-
* unaffected — it keys on the task text via `isCritical`, not the contract, so a critical child still
|
|
121
|
-
* self-verifies. Handle tools (`opts.tools`), `synthesize`, `maxDepth`, **`persona`**, and **`context`** (BA-9)
|
|
122
|
-
* carry down — the persona is a DURABLE worker stance (a child of a "senior security engineer" is still one)
|
|
123
|
-
* and the context is durable run-state (a child rooted at `/proj` is still rooted at `/proj`), unlike the
|
|
124
|
-
* top-only `contract`/`evaluate` setpoint. They ride through the `...opts` spread (not in the strip list).
|
|
125
|
-
* @param {RecurseOptions} opts
|
|
126
|
-
* @returns {RecurseOptions}
|
|
127
|
-
*/
|
|
128
|
-
function forChild(opts) {
|
|
129
|
-
return {
|
|
130
|
-
...opts,
|
|
131
|
-
count: undefined,
|
|
132
|
-
mode: undefined,
|
|
133
|
-
contract: undefined,
|
|
134
|
-
evaluate: undefined,
|
|
135
|
-
retrieval: undefined,
|
|
136
|
-
corpus: undefined,
|
|
137
|
-
window: undefined,
|
|
138
|
-
passes: undefined,
|
|
139
|
-
};
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
* The ctx handed to a worker `Loop.run({ ctx })` or to a direct `ctx.policy(...)` checkpoint — i.e. the ctx
|
|
144
|
-
* that a wired gate records VERBATIM into the audit as `action._ctx` (see `defaultActionTranslator` in
|
|
145
|
-
* src/bareguard-adapter.js). It STRIPS the live `provider` instance, because that object carries the API key
|
|
146
|
-
* (`provider.apiKey`) and bareguard serializes `_ctx` to disk — so an un-stripped ctx writes the raw
|
|
147
|
-
* `sk-…` key into the plaintext audit log (F16/BA-1, confirmed by relayfact probe-03).
|
|
148
|
-
*
|
|
149
|
-
* Only the AUDITED copy is cleaned: the provider still rides in the recurse-internal ctx that is threaded into
|
|
150
|
-
* each child `recurse()` self-call (children need `ctx.provider` to run), and the worker Loop already receives
|
|
151
|
-
* the provider as a constructor option — `Loop.run` never reads `ctx.provider`. The provider's IDENTITY is not
|
|
152
|
-
* lost from the audit either: the meter records the provider NAME on the `{type:'llm'}` action's args.
|
|
153
|
-
*
|
|
154
|
-
* NB: this strips the provider only — the leak that was grounded. A caller that threads its OWN secret-bearing
|
|
155
|
-
* fields onto ctx is backstopped by bareguard-side redaction (BG-1), the defense-in-depth pair to this fix.
|
|
156
|
-
* @param {RecurseCtx} ctx
|
|
157
|
-
* @param {object} [overrides] - extra fields to set on the audited copy (e.g. `{ depth }`).
|
|
158
|
-
* @returns {object}
|
|
159
|
-
*/
|
|
160
|
-
function auditSafeCtx(ctx, overrides = {}) {
|
|
161
|
-
const safe = { ...(ctx || {}) };
|
|
162
|
-
delete (/** @type {any} */ (safe)).provider;
|
|
163
|
-
return { ...safe, ...overrides };
|
|
164
|
-
}
|
|
16
|
+
const { HaltError, ValidationError } = require('./errors');
|
|
17
|
+
const { envSystem, SCAN_WINDOW, SCAN_PASSES } = require('./recurse-prompts');
|
|
18
|
+
const { resolveLimits, makeCounter, countingProvider } = require('./recurse-brakes');
|
|
19
|
+
const { finish } = require('./recurse-finish');
|
|
20
|
+
const { makeEnv, normalizeInput, describeInput, KINDS, hasWork } = require('./recurse-env');
|
|
21
|
+
const { refineWorker, newNode, withContext, auditSafeCtx } = require('./refine-worker');
|
|
165
22
|
|
|
166
23
|
/**
|
|
167
24
|
* @typedef {object} RecurseCtx
|
|
168
|
-
* The per-run
|
|
169
|
-
*
|
|
170
|
-
* @property {
|
|
171
|
-
* @property {Function} [
|
|
172
|
-
*
|
|
173
|
-
* @property {
|
|
174
|
-
* and worker tokens are all real spend (BA1: never invisible).
|
|
175
|
-
* @property {number} [depth] - The current recursion depth (0 at the top). Incremented on each self-call;
|
|
176
|
-
* threaded into `policy`. Callers normally omit it (defaults to 0).
|
|
177
|
-
* @property {object} [stream] - Optional event stream forwarded to each worker Loop (receipts substrate). This
|
|
178
|
-
* is the observability channel for worker activity (relayfact F15/BA-5): recurse intentionally does NOT take
|
|
179
|
-
* `onToolCall`/`onText` Loop callbacks — instead every worker Loop emits `loop:tool_call` / `loop:tool_result`
|
|
180
|
-
* (and `loop:text`/`loop:done`) to THIS stream (loop.js), so a consumer observes worker tool calls by reading
|
|
181
|
-
* the stream, not via per-call callbacks. The full audit trail is stream + the RC-10 receipts tree + (if a
|
|
182
|
-
* gate is wired) the bareguard audit.
|
|
183
|
-
* @property {{recall: Function}} [litectx] - Optional litectx handle (RC-5, §10 step 7). Backs the `search`
|
|
184
|
-
* retrieval mode (`recall`). NOT used by `scan` — litectx has no exhaustive enumerate verb today; scan reads
|
|
185
|
-
* the generic array slice-source `opts.corpus` instead (the litectx-resident scan case waits on the litectx
|
|
186
|
-
* `enumerate` verb and drops in behind the same socket).
|
|
25
|
+
* The per-run wiring, threaded down the recursion tree and forwarded to every Loop's governance.
|
|
26
|
+
* @property {Provider} [provider] - The model. Required (here or on `opts.provider`).
|
|
27
|
+
* @property {Function} [policy] - bareguard `policy(tool, args, ctx)`; sees `ctx.depth`. Money stays the gate's.
|
|
28
|
+
* @property {Function} [onLlmResult] - Metering hook forwarded to every Loop AND the verifier (never invisible spend).
|
|
29
|
+
* @property {number} [depth] - Current recursion depth (0 at the top; callers normally omit it).
|
|
30
|
+
* @property {object} [stream] - Optional event stream forwarded to the root worker Loop; also gets `recurse:limits`.
|
|
187
31
|
*/
|
|
188
32
|
|
|
189
33
|
/**
|
|
190
34
|
* @typedef {object} RecurseOptions
|
|
191
35
|
* @property {Provider} [provider] - Fallback provider if `ctx.provider` is absent.
|
|
192
|
-
* @property {
|
|
193
|
-
*
|
|
194
|
-
*
|
|
195
|
-
* @property {
|
|
196
|
-
*
|
|
197
|
-
*
|
|
198
|
-
*
|
|
199
|
-
*
|
|
200
|
-
*
|
|
201
|
-
*
|
|
202
|
-
*
|
|
203
|
-
*
|
|
204
|
-
* @property {
|
|
205
|
-
*
|
|
206
|
-
*
|
|
207
|
-
*
|
|
208
|
-
*
|
|
209
|
-
*
|
|
210
|
-
*
|
|
211
|
-
*
|
|
212
|
-
* Absent/blank ⇒ byte-identical to pre-BA-9 (backward-compatible). Validated live (`poc/ba9-context-thread.mjs`:
|
|
213
|
-
* a weak model went 0/3 → 3/3 at locating an unguessable file once the root was threaded).
|
|
214
|
-
* **SECURITY:** this becomes part of every worker's prompt (and the verifier's) — lower-privilege than
|
|
215
|
-
* `persona` (the USER message, not the SYSTEM prompt) but still a prompt-injection surface. Intended for
|
|
216
|
-
* TRUSTED run-state (paths/cwd); do NOT pass untrusted / end-user-controlled text here.
|
|
217
|
-
* @property {ToolDef[]} [tools] - Handle tools offered to EVERY worker (RC-5 pull-default: litectx
|
|
218
|
-
* `recall`/`get`, wired at build step 7). Workers query on demand; never the whole corpus.
|
|
36
|
+
* @property {string | Slice[] | (() => Promise<Slice[]>)} [input] - The data the task is about. Lives in the env var
|
|
37
|
+
* `input`; the root prompt shows ONLY metadata (type, size, short prefix). A function is awaited once. Malformed or
|
|
38
|
+
* duplicate `Slice`s are dropped and counted in `receipts.input.dropped`.
|
|
39
|
+
* @property {'count'|'ids'|'text'|'composite'} [kind='text'] - The answer kind the CALLER expects. `count`/`ids`: the
|
|
40
|
+
* model must cite a classify var with `final(var)` and CODE derives `{count, ids}`; `composite`: `final_parts`
|
|
41
|
+
* gives `{needle, count:{count, ids}}`; `text`: `final_text`/`final(var)`, or a plain reply. A wrong-kind final gets
|
|
42
|
+
* ONE nudge, then `{incomplete, blocker:'wrong-final'}`; no final at all is `blocker:'no-final'`.
|
|
43
|
+
* @property {{maxDepth?: number, maxCalls?: number, maxWidth?: number, maxRounds?: number} | 'none'} [limits] - Structural
|
|
44
|
+
* brakes (default ON, even with a gate). `maxCalls` is TIGHTEN-ONLY against a formula cap computed from the input size;
|
|
45
|
+
* `'none'` disables them and every return carries `unbraked:true`. Money/tokens/wall-clock stay with bareguard.
|
|
46
|
+
* @property {number} [maxDepth] - Shorthand for `limits.maxDepth`.
|
|
47
|
+
* @property {{in: number, out: number, cacheReadMult?: number, cacheWriteMult?: number}} [rates] - Caller USD-per-1K token rates (same semantics as `Loop({rates})`): when given, `metrics.costUsd` is priced from them (authoritative); otherwise it is a flagged tier guess, or null if any round carries no usage.
|
|
48
|
+
* @property {number} [concurrency=8] - Max sub-calls in flight per fan-out.
|
|
49
|
+
* @property {string} [persona] - Caller stance PREPENDED to every env worker's system prompt (carries down; never the
|
|
50
|
+
* verifier or the classify judge). PRIVILEGED seam: trusted text only.
|
|
51
|
+
* @property {string} [context] - Read-only working-context (paths/cwd) put on the USER message of every worker and shown
|
|
52
|
+
* to the verifier. Carries down. Trusted run-state only.
|
|
53
|
+
* @property {ToolDef[]} [tools] - Caller tools appended to the fixed env tools (carry down).
|
|
54
|
+
* @property {string} [contract] - Definition of done; the isolated verifier grades against it (top node only).
|
|
55
|
+
* @property {(result: any, ctx: {contract: string|null, task: string}) => (Verdict|Promise<Verdict>)} [evaluate] - Override the verifier.
|
|
219
56
|
* @property {{sensor: (result: any, ctx: {task: string, context: string|undefined, contract: string|null}) => (Verdict|Promise<Verdict>), maxIterations?: number, temperatures?: number[], rejectedBuffer?: boolean}} [refineLeaf]
|
|
220
|
-
*
|
|
221
|
-
* tier or at `maxDepth`) into a bounded generate→sense→regenerate loop instead of a single pass, so a failed
|
|
222
|
-
* slice can self-correct. `sensor` is a DETERMINISTIC close (test/compile/lint — NOT a model judge, R-S8) that
|
|
223
|
-
* returns a `Verdict`; on a non-pass its `critique` (the GAP, not the transcript) is fed FRESH into the next
|
|
224
|
-
* attempt (D6/A1 anti-anchoring) and, on models that ACCEPT `temperature`, the **retry temperature ESCALATES**
|
|
225
|
-
* (`temperatures`, default `[0.2,0.7,1.0]`) — the live-validated lever that lets a weak model escape a
|
|
226
|
-
* repeat-the-same-mistake rut (`poc/ba8-leaf-refine.mjs`: 0/5 → 2-3/5; flat temp recovers 0/5). On a
|
|
227
|
-
* temperature-fixed model (BA-10) the provider drops the param, `receipts.refineLeaf.temperatures` records
|
|
228
|
-
* `null`, and the fed-back gap critique carries recovery alone — UNLESS the rejected-attempt buffer engages
|
|
229
|
-
* (below). `maxIterations` defaults to
|
|
230
|
-
* `temperatures.length`; the REAL bound is bareguard (each attempt is gate-checked + metered). CARRIES DOWN the
|
|
231
|
-
* tree (preserved by `forChild`), so it engages at the leaves of a Family-A decomposition. Recovery is PARTIAL
|
|
232
|
-
* (a stubborn blind spot may persist) — `receipts.refineLeaf.passed` reports honestly. Does NOT apply to a node
|
|
233
|
-
* that delegates (its children + the tree verify own quality), nor to the scan/fanout/partition dispatch paths.
|
|
234
|
-
* Absent ⇒ a leaf is a single pass (byte-identical to pre-BA-8). An error-keyed `recall` is the CALLER's tool
|
|
235
|
-
* (`opts.tools`) keyed off the fed-back critique — bareagent stays litectx-agnostic.
|
|
236
|
-
* **Sensor integrity (RSI-learnings #1/#5, "audit the close"):** the `sensor` MUST judge the RETURNED result
|
|
237
|
-
* (tamper-proof — e.g. build/run the returned string in an isolated context, as `poc/ba8-leaf-refine.mjs` does),
|
|
238
|
-
* NEVER a worker side-effect a worker with edit tools could GAME (writing a passing file then returning junk, or
|
|
239
|
-
* editing the failing test itself). A gameable close is the reward-hacking surface every RSI system in the field
|
|
240
|
-
* got bitten by; the loop optimizes against WHATEVER the sensor reads, so keep it outside what the worker can write.
|
|
241
|
-
* **Broken sensor ≠ failing model (BA-15):** a sensor that THROWS (non-Halt) or returns a MALFORMED verdict
|
|
242
|
-
* (anything but `{pass: boolean}` or a valid tri-state `status`) is a faulty ARBITER — the loop stops at the
|
|
243
|
-
* FIRST broken close (never retries against it) and returns a labeled `{incomplete, blocker:'broken-sensor'}`
|
|
244
|
-
* (+ `receipts.blockerDetail`), with `best` preserving the model's last attempt. A `HaltError` thrown by the
|
|
245
|
-
* sensor stays a clean governance halt. The sensor's EXECUTION environment is the caller's: run untrusted /
|
|
246
|
-
* model-generated checks in an isolated child process WITH A TIMEOUT — a sensor that hangs forever hangs the
|
|
247
|
-
* leaf (no bareguard checkpoint fires between sensor start and return; confirmed by `poc/rlmplans-hung-sensor.mjs`).
|
|
248
|
-
* **`rejectedBuffer` (BA-14):** a SkillOpt-shaped rejected-attempt buffer — instead of only the LATEST critique,
|
|
249
|
-
* surface the model's OWN prior failed attempts verbatim ("you wrote these, they failed X — write something
|
|
250
|
-
* STRUCTURALLY DIFFERENT"). This is DIRECTED diversity (attack the specific repeated mistake), where escalation
|
|
251
|
-
* is RANDOM diversity; the two are ANTAGONISTIC (`poc/ba14b-temp-with-buffer.mjs`: temperature monotonically
|
|
252
|
-
* degrades the buffer, 100%→70%→50% across 0.2/0.7/1.0), so when the buffer engages the retry temperature is
|
|
253
|
-
* HELD at `temperatures[0]` (flat-low), never escalated. `true` = force on (also on temperature-accepting
|
|
254
|
-
* models); `false` = force off (pure BA-8 escalation); UNSET = ADAPTIVE — engage only once a prior attempt's
|
|
255
|
-
* temperature was dropped (a temperature-fixed model, BA-10, where escalation is inert and the buffer is the
|
|
256
|
-
* sole lever — `poc/ba14-rejected-buffer.mjs`: flat-temp 50%→100%). `receipts.refineLeaf.rejectedBuffer`
|
|
257
|
-
* reports whether any iteration injected it. Bounded by `maxIterations` (the buffer never outgrows it).
|
|
258
|
-
* @property {string} [contract] - Definition of done (A3). When present, the verifier grades against THIS,
|
|
259
|
-
* not the loose task, and verification always runs.
|
|
260
|
-
* @property {(result: any, ctx: {contract: string|null, task: string}) => (Verdict|Promise<Verdict>)} [evaluate]
|
|
261
|
-
* Override the verifier (fills `recurse()`'s verify slot, §7.1). Default = an `Evaluator` rubric pass.
|
|
262
|
-
* @property {((args: {task: string, text: string|null, results: any[], children: object[], ctx: RecurseCtx}) => any) | 'concat' | 'merge'} [synthesize]
|
|
263
|
-
* Override synthesis/reduce (NB-3). A FUNCTION is a deterministic code-reduce over the child `results` — the
|
|
264
|
-
* §9.1 aggregation path (LLM arithmetic over partials carried ~10–15% error). A STRATEGY string runs the
|
|
265
|
-
* built-in reducer: `'concat'` (lossless no-LLM join) or `'merge'` (an isolated Loop-driven subjective
|
|
266
|
-
* merge); a string is ignored when no child ran. Default (unset) = the worker's own final text (Family A:
|
|
267
|
-
* the parent model already combined the children's results in its closing turn).
|
|
268
|
-
* @property {number} [count] - (Opt-in, NB-2 / Family B) FORCED fan-out: decompose into exactly this many
|
|
269
|
-
* independent parallel workers via `Planner`→`runPlan`, then reduce. A positive integer here is the count;
|
|
270
|
-
* it OVERRIDES the tier→count map. Setting it (or `mode:'fanout'`) takes the deterministic-parallelism path
|
|
271
|
-
* instead of the model-driven Family-A default. For known-parallel tasks where the caller wants guaranteed
|
|
272
|
-
* fan-out, not the model's adaptive choice.
|
|
273
|
-
* @property {'fanout'|'partition'} [mode] - (Opt-in, NB-2 / Family B) `'fanout'` = forced semantic fan-out
|
|
274
|
-
* WITHOUT a fixed count — derived from `assessComplexity`'s tier via the calibrated map (medium/complex/
|
|
275
|
-
* critical → 2/4/6; simple → 1); `opts.count` takes precedence. `'partition'` = the DATA-DRIVEN WIDTH path
|
|
276
|
-
* (§11): measure `opts.corpus` and partition it into `max(opts.count floor, ⌈size/workerBudget⌉)` parallel
|
|
277
|
-
* scan-workers (capped by the guards), CODE-reducing the per-chunk counts. Distinct from `'fanout'`: a data
|
|
278
|
-
* partition, not a `Planner` semantic split.
|
|
279
|
-
* @property {number} [workerBudget] - (`mode:'partition'`) items per worker; width = `⌈corpus.length /
|
|
280
|
-
* workerBudget⌉` (default 100). A calibratable knob (the §9.1 algorithm), not a discovered constant.
|
|
281
|
-
* @property {number} [concurrency] - (Family B) max workers run at once per wave (default 4). The wave
|
|
282
|
-
* structure is `runPlan`'s; bareguard still bounds the family rate independently.
|
|
283
|
-
* @property {'scan'|'search'|'exact'|'tools'} [retrieval] - (§10 step 7) the retrieval shape for a task OVER A
|
|
284
|
-
* CORPUS, routed by question shape (§9.2.1). `'scan'` (the default WHEN `opts.corpus` is present) = process
|
|
285
|
-
* every slice + LLM-judge + CODE-count — the only COMPLETE path (for "how many / all"). `'search'` = litectx
|
|
286
|
-
* `recall` handle tool offered to the worker (needle; CANNOT count; requires `ctx.litectx`). `'exact'` = a
|
|
287
|
-
* deterministic code-side AND-term filter tool over `opts.corpus`. `'tools'` = the PER-QUERY Family-A face:
|
|
288
|
-
* offer the worker `scan_count` (over `opts.corpus`) + `search_memory` (when `ctx.litectx`) + `exact_match`
|
|
289
|
-
* (array corpus) ALL AT ONCE, and let it pick the shape PER SUB-QUERY — the routing lives in the tool
|
|
290
|
-
* descriptions (scan says "use for how many / all / count"; search says "never count"), so a mixed task gets
|
|
291
|
-
* needle-search AND complete-count without per-sub-query adopter declaration. The completeness guard upgrades a
|
|
292
|
-
* `'search'` on a "how many / all" ask to `'scan'` (UPGRADE-only, never a silent downgrade); it does NOT fire
|
|
293
|
-
* for `'tools'` (the complete `scan_count` is always offered there, so a mixed task keeps its search tool).
|
|
294
|
-
* Absent `corpus` AND `retrieval`, behaviour is unchanged (Family A / single-shot) — fully backward-compatible.
|
|
295
|
-
* @property {Slice[] | (() => Promise<Slice[]>)} [corpus] - (§10 step 7) the generic slice-source scan/partition
|
|
296
|
-
* reads: an in-hand `{id, text}[]` array, OR an async `() => Promise<Slice[]>` (e.g. `litectxCorpus(litectx,
|
|
297
|
-
* {kind})` materializing a litectx-resident corpus via `enumerate`). recurse depends on this SHAPE, never on
|
|
298
|
-
* litectx. Malformed entries are dropped, never miscounted.
|
|
299
|
-
* @property {number} [window] - (scan) items per judge window. Default 8 (§9.2.1 recall knee — the one
|
|
300
|
-
* calibrated number; per-model).
|
|
301
|
-
* @property {number} [passes] - (scan) shuffled-boundary passes unioned for recall. Default 2 (~0.91 recall).
|
|
57
|
+
* Compat shim ONLY, with `maxDepth:0`: forwards to `refineWorker()` and warns once per process. Use `refineWorker`.
|
|
302
58
|
*/
|
|
303
59
|
|
|
304
60
|
/**
|
|
305
61
|
* @typedef {object} RecurseNode
|
|
306
|
-
* One
|
|
307
|
-
*
|
|
62
|
+
* One receipts node (RC-10). Besides lineage (`spawned`), it carries the run's own facts, set before the first call:
|
|
63
|
+
* `limits`, `cap`; and updated as it runs: `rounds`, `rootPeakInput` (max per-round input tokens), `vars`, `memoHits`,
|
|
64
|
+
* `nudges`, `toolCalls` (counts by tool), `calls` (root only: whole-tree LLM calls), `input` `{type, items, dropped}`.
|
|
308
65
|
* @property {string} task
|
|
309
66
|
* @property {number} depth
|
|
310
67
|
* @property {{level: string, score: number}} complexity
|
|
311
68
|
* @property {boolean} critical
|
|
312
|
-
* @property {RecurseNode[]} spawned
|
|
69
|
+
* @property {RecurseNode[]} spawned
|
|
313
70
|
* @property {Verdict|null} verdict
|
|
314
71
|
* @property {boolean} incomplete
|
|
315
72
|
* @property {boolean} halted
|
|
316
|
-
* @property {string} [blocker] -
|
|
317
|
-
*
|
|
318
|
-
*
|
|
319
|
-
*
|
|
320
|
-
* @property {string} [
|
|
321
|
-
*
|
|
322
|
-
* @property {{blocker: string, blockerDetail?: string, blockerTask?: string}} [blockerFrom] - (BA-15) a
|
|
323
|
-
* DESCENDANT's blocker, surfaced here so an aggregating node still reports the fault upward. Deliberately
|
|
324
|
-
* SEPARATE from this node's own `blocker` (which means "THIS node's arbiter/Loop broke"): stamping a
|
|
325
|
-
* descendant's label onto every ancestor made the receipts tree accuse nodes whose sensor never ran, and
|
|
326
|
-
* re-labelled a parent `governance-deny` when only one child was denied. `blockerTask` names the culprit.
|
|
327
|
-
* @property {object|null} tokens - The worker Loop's `metrics.tokens`.
|
|
328
|
-
* @property {{iterations: number, passed: boolean, temperatures: (number|null)[], rejectedBuffer: boolean}} [refineLeaf] - (BA-8) when
|
|
329
|
-
* this leaf ran as a bounded refine loop: how many attempts it took and whether the deterministic sensor finally
|
|
330
|
-
* passed (false = honest non-recovery, not a faked success). `temperatures` are the EFFECTIVE per-attempt temps
|
|
331
|
-
* (BA-10): a `null` marks an attempt the model ran at its DEFAULT because it rejected the requested temperature.
|
|
332
|
-
* `rejectedBuffer` (BA-14): whether any iteration injected the rejected-attempt buffer (prior failed attempts
|
|
333
|
-
* surfaced verbatim); when it engages the REQUESTED retry temperature is held flat at `temperatures[0]`, never
|
|
334
|
-
* escalated (ba14b antagonism) — but a temperature-fixed model still drops it, so the EFFECTIVE temp recorded
|
|
335
|
-
* above is `null`, not `temperatures[0]`.
|
|
73
|
+
* @property {string} [blocker] - This node stopped for a specific reason (`brake`, `halt`, `wrong-final`, `no-final`, `governance-deny`, `verify-failed`, `broken-verifier`, `broken-sensor`, `error`, `input`).
|
|
74
|
+
* @property {string} [blockerDetail]
|
|
75
|
+
* @property {{blocker: string, blockerDetail?: string, blockerTask?: string}} [blockerFrom] - A DESCENDANT's blocker (never stamped as this node's own).
|
|
76
|
+
* @property {any} [best]
|
|
77
|
+
* @property {string[]} [missingSlices]
|
|
78
|
+
* @property {object|null} tokens
|
|
336
79
|
* @property {string|null} model
|
|
337
|
-
* @property {string|null} [retrieval] -
|
|
338
|
-
*
|
|
339
|
-
* @property {
|
|
340
|
-
*
|
|
341
|
-
* @property {
|
|
342
|
-
*
|
|
343
|
-
* @property {
|
|
344
|
-
*
|
|
345
|
-
*
|
|
80
|
+
* @property {string|null} [retrieval] - unused in v2 (kept for the refineWorker node shape).
|
|
81
|
+
* @property {any} [refineLeaf]
|
|
82
|
+
* @property {any} [limits]
|
|
83
|
+
* @property {number} [cap]
|
|
84
|
+
* @property {number} [calls]
|
|
85
|
+
* @property {number} [rounds]
|
|
86
|
+
* @property {number} [rootPeakInput]
|
|
87
|
+
* @property {number} [vars]
|
|
88
|
+
* @property {number} [memoHits]
|
|
89
|
+
* @property {number} [nudges]
|
|
90
|
+
* @property {Record<string, number>} [toolCalls]
|
|
91
|
+
* @property {{type: string, items: number, dropped: number}} [input]
|
|
346
92
|
*/
|
|
347
93
|
|
|
348
94
|
/**
|
|
349
95
|
* @typedef {object} RecurseResult
|
|
350
|
-
* @property {any} [result] -
|
|
351
|
-
* @property {Verdict|null} [verdict]
|
|
352
|
-
* @property {boolean} [incomplete] -
|
|
353
|
-
*
|
|
354
|
-
* @property {
|
|
355
|
-
* @property {string
|
|
356
|
-
*
|
|
357
|
-
* @property {string} [
|
|
358
|
-
*
|
|
359
|
-
*
|
|
360
|
-
*
|
|
361
|
-
*
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
*
|
|
381
|
-
*
|
|
382
|
-
* each recursing to `opts.maxDepth` (default 3) — so node count, and therefore TOKEN + $ SPEND, compounds
|
|
383
|
-
* multiplicatively and is **not capped by recurse itself**. (The forced paths — `mode:'fanout'`/`'partition'` —
|
|
384
|
-
* ARE bounded: a deterministic `count` + a `concurrency` cap. The uncapped path is the model-driven default.)
|
|
385
|
-
* This is real, not theoretical: a live POC (`poc/rlm-defer2-history-overflow.mjs`) showed a weak model
|
|
386
|
-
* over-decomposing into 40–117 calls on a single run. **So: running WITHOUT bareguard — or without ANY
|
|
387
|
-
* token/cost cap — CAN BURN TOKENS / $ unboundedly (up to ~100×depth nodes).** **WIRE bareguard**
|
|
388
|
-
* (`ctx.policy` via `wireGate`) for any non-trivial or untrusted run — it enforces depth/budget/call caps and
|
|
389
|
-
* the pre-wave fan-out checkpoint, turning a runaway into a clean `{incomplete}`. With no gate available, the
|
|
390
|
-
* only local brakes are `opts.maxDepth: 1` (flat — no nesting) and the provider/key's own usage limits.
|
|
391
|
-
*
|
|
96
|
+
* @property {any} [result] - On success: `{count, ids}` (count/ids), `{needle, count}` (composite) or a string (text).
|
|
97
|
+
* @property {Verdict|null} [verdict]
|
|
98
|
+
* @property {boolean} [incomplete] - The ONE "not done" signal: brake, gate halt, dead slot, failed verify, wrong/no final. Never a faked pass.
|
|
99
|
+
* @property {any} [best] - Last non-empty work when `incomplete` (BA-5).
|
|
100
|
+
* @property {string[]} [missingSlices] - Pieces that never produced an answer (never survivor-summed).
|
|
101
|
+
* @property {string} [blocker]
|
|
102
|
+
* @property {string} [brake] - With `blocker:'brake'`: `maxCalls`/`maxWidth`/`maxRounds`.
|
|
103
|
+
* @property {string} [blockerDetail]
|
|
104
|
+
* @property {string} [blockerTask]
|
|
105
|
+
* @property {boolean} [unbraked] - Present (true) under `limits:'none'`.
|
|
106
|
+
* @property {{calls: number, tokens: object, costUsd: number|null}} [metrics] - Root only: whole-tree calls/tokens/cost (null if any node is unpriced).
|
|
107
|
+
* @property {RecurseNode} receipts
|
|
108
|
+
*/
|
|
109
|
+
|
|
110
|
+
/** Internal opts key: a child `recurse` receives its parent's counter VIEW here (tighten-only, shared total). Not public. */
|
|
111
|
+
const SHARED = Symbol('recurse.shared');
|
|
112
|
+
|
|
113
|
+
// Options removed in v2 → fail LOUD (a silently dead knob would change what the call means).
|
|
114
|
+
const REMOVED = {
|
|
115
|
+
corpus: 'use opts.input (and kind:"count" with classify)', retrieval: 'use opts.input', window: 'fixed at 8', passes: 'fixed at 2',
|
|
116
|
+
mode: 'use limits.maxWidth / concurrency', count: 'use limits.maxWidth / concurrency', workerBudget: 'use limits.maxWidth / concurrency',
|
|
117
|
+
synthesize: 'reductions are code tools (join/count)',
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
let shimWarned = false;
|
|
121
|
+
|
|
122
|
+
/** The opts a delegated child inherits: persona/context/tools/concurrency carry down; the top-level setpoint, input and brakes do not. */
|
|
123
|
+
const forChild = (/** @type {any} */ opts) => ({ ...opts, input: undefined, kind: 'text', limits: undefined, maxDepth: undefined, contract: undefined, evaluate: undefined });
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Answer a task over an input held in an environment, with fixed tools, structural brakes and one honest tail.
|
|
127
|
+
* Input is never pasted into the prompt; the answer is a var of the declared `kind` (count derived by CODE).
|
|
392
128
|
* @param {string} task - The goal.
|
|
393
|
-
* @param {RecurseCtx} [ctx] -
|
|
394
|
-
* @param {RecurseOptions} [opts] - The
|
|
395
|
-
* @returns {Promise<RecurseResult>} `{
|
|
396
|
-
*
|
|
397
|
-
* @
|
|
398
|
-
* @
|
|
399
|
-
* @fails returns `{incomplete, best}` on guard exhaustion or a dead worker (never a faked pass); a gate HaltError exits clean. Cost is open by design — run under a budget gate.
|
|
129
|
+
* @param {RecurseCtx} [ctx] - Runtime wiring (provider, policy, onLlmResult, stream, depth).
|
|
130
|
+
* @param {RecurseOptions} [opts] - The knobs (`input`, `kind`, `limits`, ...).
|
|
131
|
+
* @returns {Promise<RecurseResult>} `{result, verdict, receipts, metrics}` or `{incomplete, best, blocker, receipts, metrics}`.
|
|
132
|
+
* @throws {Error} no task/provider; a removed v1 option; a bad `kind`/`limits`.
|
|
133
|
+
* @when a task is about data too big for one prompt (counts, needles, per-chunk questions) and you want it answered from an environment with hard call limits
|
|
134
|
+
* @fails returns `{incomplete, best, blocker}` on a brake, gate halt, dead slot, failed verify, wrong or missing final (never a faked pass); a v1 option throws.
|
|
400
135
|
* @example
|
|
401
|
-
* const
|
|
402
|
-
*
|
|
403
|
-
* if (incomplete) retryOrEscalate(result);
|
|
136
|
+
* const { result, incomplete } = await recurse('how many are about sports?', { provider }, { input: items, kind: 'count' });
|
|
137
|
+
* if (!incomplete) console.log(result.count);
|
|
404
138
|
*/
|
|
405
139
|
async function recurse(task, ctx = {}, opts = {}) {
|
|
406
|
-
if (typeof task !== 'string' || task.length === 0)
|
|
407
|
-
throw new Error('[recurse] task must be a non-empty string');
|
|
408
|
-
}
|
|
140
|
+
if (typeof task !== 'string' || task.length === 0) throw new Error('[recurse] task must be a non-empty string');
|
|
409
141
|
const provider = ctx.provider || opts.provider;
|
|
410
|
-
if (!provider)
|
|
411
|
-
|
|
142
|
+
if (!provider) throw new Error('[recurse] requires a provider on ctx.provider (or opts.provider)');
|
|
143
|
+
|
|
144
|
+
if (opts.refineLeaf) { // decision 3: one-release compat shim for relayfact's recurse(…, {maxDepth:0, refineLeaf})
|
|
145
|
+
if (opts.maxDepth === 0 && typeof opts.refineLeaf.sensor === 'function') {
|
|
146
|
+
if (!shimWarned) { shimWarned = true; console.warn('[bare-agent] recurse(…, {maxDepth:0, refineLeaf}) is deprecated: call refineWorker(task, ctx, opts) instead (shim removed next release).'); }
|
|
147
|
+
const { maxDepth: _dropped, ...workerOpts } = opts; // refineWorker rejects maxDepth (dead knob there)
|
|
148
|
+
return refineWorker(task, ctx, workerOpts);
|
|
149
|
+
}
|
|
150
|
+
throw new ValidationError('recurse: opts.refineLeaf is only supported through the maxDepth:0 compat shim — use refineWorker()');
|
|
412
151
|
}
|
|
152
|
+
for (const k of Object.keys(REMOVED)) if (/** @type {any} */ (opts)[k] !== undefined) throw new ValidationError(`recurse: option "${k}" was removed in v2 — ${/** @type {any} */ (REMOVED)[k]}`);
|
|
153
|
+
const kind = opts.kind === undefined ? 'text' : opts.kind;
|
|
154
|
+
if (!KINDS.includes(kind)) throw new ValidationError('recurse: kind must be one of count|ids|text|composite');
|
|
413
155
|
|
|
156
|
+
const shared = /** @type {any} */ (opts)[SHARED];
|
|
414
157
|
const depth = Number.isInteger(ctx.depth) ? /** @type {number} */ (ctx.depth) : 0;
|
|
415
|
-
const maxDepth = Number.isInteger(opts.maxDepth) ? /** @type {number} */ (opts.maxDepth) : 3;
|
|
416
|
-
|
|
417
|
-
// The classifier ALWAYS runs — as a hint, not a gate (§4.2). It decides only the two low-regret rails:
|
|
418
|
-
// `simple → single-shot` (no spawn tool offered; the depth-0 baseline that already beats most, §10F) and
|
|
419
|
-
// `critical → force adversarial verify` (the non-overridable safety floor, isCritical). It NEVER gates the
|
|
420
|
-
// high-regret decomposition structure — that stays the model's (Family A).
|
|
421
|
-
const assessment = assessComplexity(task);
|
|
422
158
|
const critical = isCritical(task);
|
|
159
|
+
const node = /** @type {RecurseNode} */ (newNode(task, depth, assessComplexity(task), critical));
|
|
160
|
+
Object.assign(node, { rounds: 0, rootPeakInput: 0, vars: 0, memoHits: 0, nudges: 0, toolCalls: {} });
|
|
423
161
|
|
|
424
|
-
/** @type {
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
//
|
|
438
|
-
|
|
439
|
-
|
|
162
|
+
/** @type {any} */ let input = null; let inputErr = null; let counter = shared; let err = null;
|
|
163
|
+
try {
|
|
164
|
+
const raw = typeof opts.input === 'function' ? await opts.input() : opts.input;
|
|
165
|
+
const norm = normalizeInput(raw); input = norm.input;
|
|
166
|
+
node.input = { type: input == null ? 'none' : Array.isArray(input) ? 'items' : 'string', items: Array.isArray(input) ? input.length : 0, dropped: norm.dropped };
|
|
167
|
+
} catch (e) {
|
|
168
|
+
if (e instanceof HaltError) err = e; else inputErr = e; // a source fault is an honest incomplete, never an empty scan
|
|
169
|
+
}
|
|
170
|
+
if (input == null && kind !== 'text' && !inputErr && !err) throw new ValidationError(`recurse: kind "${kind}" needs opts.input`);
|
|
171
|
+
|
|
172
|
+
if (!counter) {
|
|
173
|
+
const verifyCalls = critical || typeof opts.contract === 'string' || typeof opts.evaluate === 'function' ? 1 : 0;
|
|
174
|
+
const maxWidthHint = typeof opts.limits === 'object' && opts.limits && opts.limits.maxWidth != null ? opts.limits.maxWidth : 16;
|
|
175
|
+
// string/absent input has no classify scan; reserve one full-width map (maxWidth sub-calls) via the same formula
|
|
176
|
+
const items = Array.isArray(input) ? input.length : maxWidthHint * Math.ceil(SCAN_WINDOW / SCAN_PASSES);
|
|
177
|
+
const limits = opts.limits === 'none' ? 'none' : opts.maxDepth != null ? { ...(opts.limits || {}), maxDepth: opts.maxDepth } : opts.limits;
|
|
178
|
+
counter = makeCounter(resolveLimits(limits, { items, window: SCAN_WINDOW, passes: SCAN_PASSES, verifyCalls }), { rates: opts.rates });
|
|
179
|
+
}
|
|
180
|
+
node.limits = counter.limits; node.cap = counter.limits.maxCalls; // exposed BEFORE the first call (tighten-only)
|
|
181
|
+
try { if (ctx.stream && typeof ctx.stream.emit === 'function') ctx.stream.emit({ type: 'recurse:limits', data: { depth, cap: node.cap, limits: { ...counter.limits } } }); } catch { /* observability only */ }
|
|
182
|
+
|
|
183
|
+
const canSub = counter.canSpawn(depth);
|
|
184
|
+
const child = (/** @type {string} */ prompt, /** @type {any} */ piece) => recurse(prompt, { ...ctx, depth: depth + 1 },
|
|
185
|
+
{ ...forChild(opts), input: Array.isArray(piece) || typeof piece === 'string' ? piece : isPlain(piece) ? [piece] : JSON.stringify(piece), [SHARED]: counter.child() });
|
|
186
|
+
const env = makeEnv({ input, kind, node, counter, depth, ctx, opts, provider, child });
|
|
187
|
+
|
|
188
|
+
const base = countingProvider(provider, counter);
|
|
189
|
+
const metered = Object.create(base); // per-round input peak of THIS node's own worker (the bounded-window claim)
|
|
190
|
+
metered.generate = async (/** @type {any[]} */ ...a) => {
|
|
191
|
+
const r = await /** @type {any} */ (base).generate(...a); node.rounds = (node.rounds || 0) + 1;
|
|
192
|
+
const u = r && r.usage; if (u) node.rootPeakInput = Math.max(node.rootPeakInput || 0, (u.inputTokens || 0) + (u.cacheReadTokens || 0) + (u.cacheCreationTokens || 0));
|
|
193
|
+
return r;
|
|
440
194
|
};
|
|
441
|
-
|
|
442
|
-
// Family B (NB-2) — FORCED fan-out, opt-in. The caller asked for guaranteed deterministic parallelism, so
|
|
443
|
-
// this path does NOT offer the model the spawn tool; a deterministic count → Planner → runPlan waves →
|
|
444
|
-
// NB-3 reduce → verify. assessComplexity is still only a hint here (it sets the count when no explicit
|
|
445
|
-
// `opts.count`); `critical` still forces verify. Branches before the Family-A spawn-tool setup below.
|
|
446
|
-
// Data-driven width PARTITION (NB-2 / §11) — opt-in, checked BEFORE the fanout branch so `opts.count` acts as
|
|
447
|
-
// the width FLOOR here (not a fanout trigger). Distinct from Family B's semantic decomposition: it PARTITIONS
|
|
448
|
-
// a measured corpus into ⌈size/workerBudget⌉ parallel scan-workers (capped by guards), never a Planner split.
|
|
449
|
-
if (opts.mode === 'partition') {
|
|
450
|
-
return recursePartition(task, ctx, opts, { provider, depth, critical, node });
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
// PRECEDENCE: an explicit forced fan-out (`mode:'fanout'`/`count`) is the stronger, deterministic intent and
|
|
454
|
-
// wins over `retrieval:'tools'` — this branch returns BEFORE the retrieval routing below, so a worker-level
|
|
455
|
-
// per-query tool face is NOT attached on a forced fan-out (each fan-out slice is its own fresh-window recurse
|
|
456
|
-
// and may route retrieval for ITS subtask). Pair forced fan-out with a per-slice `corpus`, not `retrieval:'tools'`.
|
|
457
|
-
if (opts.mode === 'fanout' || opts.count != null) {
|
|
458
|
-
return recurseFanout(task, ctx, opts, { provider, depth, maxDepth, assessment, critical, node });
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
// Retrieval routing (§10 step 7, §9.2.1 task-shape model). A task OVER A CORPUS gets context as a HANDLE
|
|
462
|
-
// chosen by the question's shape. `scan` is the default WHEN a corpus is present (the only complete path);
|
|
463
|
-
// `search`/`exact` are opt-in handle TOOLS for a Family-A worker. Absent both, behaviour is unchanged.
|
|
464
|
-
// A corpus may be an in-hand array OR an async slice-source `() => Promise<Slice[]>` (e.g. `litectxCorpus`
|
|
465
|
-
// over a litectx-resident corpus). Either form defaults retrieval to scan.
|
|
466
|
-
const hasCorpus = Array.isArray(opts.corpus) || typeof opts.corpus === 'function';
|
|
467
|
-
let retrieval = opts.retrieval || (hasCorpus ? 'scan' : null);
|
|
468
|
-
// Completeness-contract GUARD (RC-9 applied to retrieval): a "how many / all" ask must not be answered by a
|
|
469
|
-
// capped `search` (which cannot count). UPGRADE-only — never silently downgrade a scan to a search.
|
|
470
|
-
if (retrieval === 'search' && (impliesCompleteness(task) || impliesCompleteness(opts.contract))) {
|
|
471
|
-
retrieval = 'scan';
|
|
472
|
-
node.retrievalUpgraded = 'search→scan (completeness)';
|
|
473
|
-
}
|
|
474
|
-
node.retrieval = retrieval;
|
|
475
|
-
|
|
476
|
-
// `scan` is a deterministic ORCHESTRATION (code-driven judge-per-window + code-count), not a worker model
|
|
477
|
-
// call — it branches to its own path. `search`/`exact` fall through to the Family-A worker below with their
|
|
478
|
-
// handle tool injected (the worker decides per sub-query — the §10 step-7 "offered as tools" shape).
|
|
479
|
-
if (retrieval === 'scan') {
|
|
480
|
-
return recurseScan(task, ctx, opts, { provider, depth, critical, node });
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
// Offer the spawn A-tool only below the cap AND only when decomposition is plausibly useful (`simple`
|
|
484
|
-
// routes to single-shot). At `depth >= maxDepth` the tool is withheld — the NB-4 tool half of the scrub,
|
|
485
|
-
// and what makes `maxDepth=1` flat (RC-11): top spawns, children cannot (no nesting).
|
|
486
|
-
const canSpawn = depth < maxDepth && assessment.level !== 'simple';
|
|
487
|
-
|
|
488
|
-
// Capability-scrub (NB-4 / RC-12): the worker system prompt is the OPTIONAL caller persona (`opts.persona`) +
|
|
489
|
-
// the decomposition policy (NB-5) + a depth-conservative suffix that nudges deeper workers toward direct
|
|
490
|
-
// action. The persona AUGMENTS, never replaces — the decomposition + scrub text is load-bearing for the spawn
|
|
491
|
-
// mechanics, so a persona that replaced it would break decomposition (POC `rlm-persona-seam.mjs` validated the
|
|
492
|
-
// prepend: the worker still decomposes AND adopts the persona). Persona CARRIES DOWN the tree (it is preserved
|
|
493
|
-
// by `forChild`, unlike contract/evaluate) — a durable worker stance, not a top-only setpoint. It is deliberately
|
|
494
|
-
// NOT applied to the isolated verifier (that would defeat the anti-sycophancy isolation) nor the scan judge.
|
|
495
|
-
// Tool set is monotone: a child's tools ⊆ its parent's (same handle tools, spawn dropped at the cap).
|
|
496
|
-
const system = workerPersonaPrefix(opts.persona) + DECOMPOSITION_POLICY + capabilityScrub(depth, maxDepth);
|
|
497
|
-
|
|
498
|
-
// Handle tools (RC-5 pull-default) = caller-supplied `opts.tools` + the retrieval handle for `search`/`exact`/
|
|
499
|
-
// `tools` (offered so the Family-A worker pulls context per sub-query, never the whole corpus). `search` needs
|
|
500
|
-
// `ctx.litectx`; `exact` is a code-side filter over the corpus. A mode whose backend is absent contributes
|
|
501
|
-
// no tool (the worker just answers directly) rather than erroring.
|
|
502
|
-
const retrievalTools = [];
|
|
503
|
-
if (retrieval === 'search' && ctx.litectx) retrievalTools.push(buildSearchTool(ctx.litectx, {}));
|
|
504
|
-
if (retrieval === 'exact') retrievalTools.push(buildExactTool(normalizeCorpus(opts.corpus)));
|
|
505
|
-
// `tools` (§10 step-7 follow-on, per-query face) — offer ALL applicable handles at once; the worker routes by
|
|
506
|
-
// their descriptions per sub-query. `scan_count` is the COMPLETE path (so the completeness guard need not fire
|
|
507
|
-
// for `tools`); `search_memory`/`exact_match` are the cheap needle/rule paths. Each is offered only when its
|
|
508
|
-
// backend is present (a corpus for scan/exact, `ctx.litectx` for search), else simply absent.
|
|
509
|
-
if (retrieval === 'tools') {
|
|
510
|
-
if (hasCorpus) {
|
|
511
|
-
retrievalTools.push(buildScanTool(/** @type {Slice[] | (() => Promise<Slice[]>)} */ (opts.corpus), {
|
|
512
|
-
provider,
|
|
513
|
-
window: opts.window,
|
|
514
|
-
passes: opts.passes,
|
|
515
|
-
ctx: auditSafeCtx(ctx, { depth }), // scan's Loop run ctx reaches the gate — strip provider (F16/BA-1)
|
|
516
|
-
onLlmResult: ctx.onLlmResult,
|
|
517
|
-
policy: ctx.policy,
|
|
518
|
-
}));
|
|
519
|
-
}
|
|
520
|
-
if (ctx.litectx) retrievalTools.push(buildSearchTool(ctx.litectx, {}));
|
|
521
|
-
if (Array.isArray(opts.corpus)) retrievalTools.push(buildExactTool(normalizeCorpus(opts.corpus)));
|
|
522
|
-
}
|
|
523
|
-
const handleTools = [...(Array.isArray(opts.tools) ? opts.tools : []), ...retrievalTools];
|
|
524
|
-
|
|
525
|
-
// BA-8 (opt-in): a DEFINITE leaf (no spawn offered — `simple` tier or at `maxDepth`) with a caller sensor runs
|
|
526
|
-
// as a bounded refine-with-escalation loop instead of a single pass, so a failed slice self-corrects. Gating on
|
|
527
|
-
// `!canSpawn` keeps it predictable (a node that may delegate is an orchestrator, not a leaf) and means the seam
|
|
528
|
-
// engages exactly at the leaves of a Family-A tree (it carries down via forChild). A no-op when unset.
|
|
529
|
-
if (!canSpawn && opts.refineLeaf && typeof opts.refineLeaf.sensor === 'function') {
|
|
530
|
-
return recurseRefineLeaf(task, ctx, opts, { provider, system, handleTools, depth, critical, node, sensor: opts.refineLeaf.sensor });
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
// NB-3: collect each child's declared RESULT value (copy-on-return: the value, never its transcript) so the
|
|
534
|
-
// reducer can aggregate them. Step-3's seam handed the receipts only, so a code-reduce could not see what to
|
|
535
|
-
// combine — this closes that gap and is what Family B (step 5) will reduce over `runPlan` results[].
|
|
536
|
-
const childResults = [];
|
|
537
|
-
const tools = canSpawn
|
|
538
|
-
? [...handleTools, buildSpawnTool(ctx, opts, depth, maxDepth, node, childResults)]
|
|
539
|
-
: handleTools;
|
|
540
|
-
|
|
541
195
|
const loop = new Loop({
|
|
542
|
-
provider,
|
|
543
|
-
system,
|
|
544
|
-
policy: ctx.policy || undefined,
|
|
545
|
-
onLlmResult: ctx.onLlmResult || undefined,
|
|
546
|
-
stream: ctx.stream || undefined,
|
|
196
|
+
provider: metered,
|
|
197
|
+
system: envSystem({ persona: opts.persona, meta: describeInput(input), kind, canSub, depth, maxDepth: counter.limits.maxDepth }),
|
|
198
|
+
policy: ctx.policy || undefined, onLlmResult: ctx.onLlmResult || undefined, stream: ctx.stream || undefined,
|
|
547
199
|
throwOnError: false, // a worker fault surfaces as out.error → honest incomplete, never a thrown run
|
|
548
200
|
});
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
//
|
|
554
|
-
[{ role: 'user', content: withContext(task, opts.context) }],
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
// probe-16: 16 calls, sensor never reached → incomplete). Surface it as a clean, LABELED incomplete so a
|
|
575
|
-
// caller can tell a governance block apart from a model failure and act (widen scope, re-gate, escalate).
|
|
576
|
-
if (typeof out.error === 'string' && out.error.startsWith('denied:')) {
|
|
577
|
-
node.incomplete = true;
|
|
578
|
-
node.blocker = 'governance-deny';
|
|
579
|
-
return { incomplete: true, best: out.text || null, blocker: 'governance-deny', receipts: node };
|
|
580
|
-
}
|
|
581
|
-
if (out.error) {
|
|
582
|
-
node.incomplete = true;
|
|
583
|
-
return { incomplete: true, best: out.text || null, receipts: node };
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
// Synthesis / reduce (NB-3, build step 4) + verify (RC-7), under one HaltError guard: a governance cap that
|
|
587
|
-
// trips mid-synthesis or mid-verify is a clean exit returning the partial `best` (RC-6), never a thrown run.
|
|
588
|
-
let result = out.text;
|
|
589
|
-
try {
|
|
590
|
-
// Default (Family A) = the worker's own final text — the parent model already combined the children's
|
|
591
|
-
// returned results in its closing turn. `opts.synthesize` OVERRIDES that (§9.1): a FUNCTION is a
|
|
592
|
-
// deterministic code-reduce over the child `results` (the aggregation path — LLM arithmetic is the weak
|
|
593
|
-
// link); a STRATEGY string ('concat'|'merge') runs the built-in reducer. Either form is a REDUCE over
|
|
594
|
-
// children, so it only fires when this node actually spawned some — a leaf (incl. a single-shot worker, or
|
|
595
|
-
// a deep child with no grandchildren) has nothing to reduce, so its own direct answer stands. This is also
|
|
596
|
-
// why threading `synthesize` down the tree is correct: each level reduces ITS children, leaves don't.
|
|
597
|
-
if (childResults.length > 0 && opts.synthesize != null) {
|
|
598
|
-
if (typeof opts.synthesize === 'function') {
|
|
599
|
-
result = await opts.synthesize({ task, text: out.text, results: childResults, children: node.spawned, ctx });
|
|
600
|
-
} else if (typeof opts.synthesize === 'string') {
|
|
601
|
-
result = await synthesize(task, childResults, {
|
|
602
|
-
strategy: /** @type {any} */ (opts.synthesize),
|
|
603
|
-
provider,
|
|
604
|
-
contract: typeof opts.contract === 'string' ? opts.contract : null,
|
|
605
|
-
onLlmResult: ctx.onLlmResult,
|
|
606
|
-
policy: ctx.policy,
|
|
607
|
-
text: out.text,
|
|
608
|
-
children: node.spawned,
|
|
609
|
-
ctx,
|
|
610
|
-
});
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
// Honest completeness (RC-9 / §9 negative scenario 1): if ANY child came back incomplete, THIS node is
|
|
615
|
-
// incomplete — never a silent survivor-sum over partial data (the §9.1 undercount: 99 vs 151, no signal).
|
|
616
|
-
// Mirrors spike-2's `incomplete: parts.some(p => p.incomplete)`, which the shipped glue had dropped. The
|
|
617
|
-
// reduce still runs first, so `best` carries the partial answer; we just refuse to call it a clean success.
|
|
618
|
-
// Propagates up the tree: a dead grandchild → incomplete child → incomplete parent. (A dead *worker at this
|
|
619
|
-
// level* is already handled above via `out.error`; this covers a dead *child* surfacing through the reduce.)
|
|
620
|
-
const missingSlices = node.spawned.filter(c => c.incomplete).map(c => c.task);
|
|
621
|
-
if (missingSlices.length > 0) {
|
|
622
|
-
node.incomplete = true;
|
|
623
|
-
// BA-15: carry a child's blocker up, so a nested broken sensor still names itself at the top.
|
|
624
|
-
return incompleteWithBlocker(node, result, { missingSlices });
|
|
625
|
-
}
|
|
626
|
-
|
|
627
|
-
// Verify: a SEPARATE-context judge, never the generator grading itself. Runs when a contract is given, the
|
|
628
|
-
// caller supplied a verifier, OR the task is critical (the forced-verify safety rail).
|
|
629
|
-
const wantVerify = critical || typeof opts.contract === 'string' || typeof opts.evaluate === 'function';
|
|
630
|
-
if (wantVerify) {
|
|
631
|
-
// `return await` (not a bare `return`) is load-bearing here — see verifyOrBlock's JSDoc.
|
|
632
|
-
return await verifyOrBlock(task, result, ctx, opts, node);
|
|
633
|
-
}
|
|
634
|
-
|
|
635
|
-
return { result, verdict: null, receipts: node };
|
|
636
|
-
} catch (err) {
|
|
637
|
-
if (err instanceof HaltError) {
|
|
638
|
-
node.halted = true;
|
|
639
|
-
node.incomplete = true;
|
|
640
|
-
// BA-15: a halt AFTER the children ran (e.g. mid-synthesize) must still name a child's broken sensor —
|
|
641
|
-
// otherwise the caller reads a governance problem where their own arbiter crashed.
|
|
642
|
-
return incompleteWithBlocker(node, result);
|
|
643
|
-
}
|
|
644
|
-
throw err;
|
|
645
|
-
}
|
|
646
|
-
}
|
|
647
|
-
|
|
648
|
-
/** Valid tri-state `Verdict.status` values a caller arbiter (sensor/verifier) may return in lieu of a boolean `pass`. */
|
|
649
|
-
const SENSOR_STATUS = new Set(['satisfied', 'needs_revision', 'failed']);
|
|
650
|
-
|
|
651
|
-
/**
|
|
652
|
-
* BA-15 — a TYPED signal that a caller arbiter (the `refineLeaf.sensor` or the `opts.evaluate` verifier)
|
|
653
|
-
* broke (threw non-Halt, or returned a malformed verdict). Classified by `instanceof` + `.tag`, NOT by
|
|
654
|
-
* re-parsing an `Error.message` prefix — so an intermediate layer that rewords the message (the exact class
|
|
655
|
-
* of the prior loop.js HaltError-wrapping bug) or a Loop/provider error whose text happens to begin
|
|
656
|
-
* `broken-sensor: ` can never be mis-labeled. Module-local: it is always thrown AND caught inside recurse.js
|
|
657
|
-
* (never propagates to a caller), so it needs no `errors.js` entry or public export.
|
|
658
|
-
*/
|
|
659
|
-
class BrokenArbiterError extends Error {
|
|
660
|
-
/**
|
|
661
|
-
* @param {'broken-sensor'|'broken-verifier'} tag - which seam broke.
|
|
662
|
-
* @param {string} detail - what the arbiter did (surfaced as `receipts.blockerDetail`).
|
|
663
|
-
* @param {{cause?: any}} [options] - `cause` preserves the original error (stack/type) for debugging.
|
|
664
|
-
*/
|
|
665
|
-
constructor(tag, detail, options = {}) {
|
|
666
|
-
super(`${tag}: ${detail}`, options.cause !== undefined ? { cause: options.cause } : undefined);
|
|
667
|
-
this.name = 'BrokenArbiterError';
|
|
668
|
-
this.tag = tag;
|
|
669
|
-
this.detail = detail;
|
|
670
|
-
}
|
|
671
|
-
}
|
|
672
|
-
|
|
673
|
-
/**
|
|
674
|
-
* BA-15 — validate a caller arbiter's return at a close seam (the `refineLeaf.sensor` AND the caller
|
|
675
|
-
* `opts.evaluate` verifier). A verdict is well-formed iff it is an object carrying a boolean `pass` OR a
|
|
676
|
-
* valid tri-state `status` (the two shapes `refine`/callers branch on). Returns `null` when well-formed,
|
|
677
|
-
* else a short description of the malformation ("named, never coerced" — a garbage verdict otherwise reads
|
|
678
|
-
* as pass:false with critique:null at the sensor seam, or rides a converged-shaped return at the verify slot).
|
|
679
|
-
* @param {any} v
|
|
680
|
-
* @returns {string|null}
|
|
681
|
-
*/
|
|
682
|
-
function verdictShapeFault(v) {
|
|
683
|
-
if (v === null || typeof v !== 'object' || Array.isArray(v)) {
|
|
684
|
-
return `returned ${v === null ? 'null' : Array.isArray(v) ? 'an array' : `a ${typeof v}`}`;
|
|
685
|
-
}
|
|
686
|
-
// A PRESENT `pass` counts whatever its type (`1`/`0`/`'yes'` are a long-standing yes-no convention, and
|
|
687
|
-
// `refine` has always branched on its TRUTHINESS). BA-15 exists to catch a verdict carrying NO usable
|
|
688
|
-
// signal — not to reject one that answers clearly in a different dialect: demanding a strict boolean
|
|
689
|
-
// silently flipped previously-CONVERGING adopter sensors to a permanent first-attempt block.
|
|
690
|
-
if (v.pass != null || SENSOR_STATUS.has(v.status)) return null;
|
|
691
|
-
const keys = Object.keys(v).slice(0, 5).join(', ');
|
|
692
|
-
return `returned an object with neither a usable \`pass\` nor a valid \`status\` (keys: ${keys || 'none'})`;
|
|
693
|
-
}
|
|
694
|
-
|
|
695
|
-
/** Upper bound on a `blockerDetail` fragment — it rides into receipts and, via a wired gate, onto disk. */
|
|
696
|
-
const DETAIL_MAX = 200;
|
|
697
|
-
|
|
698
|
-
/**
|
|
699
|
-
* BA-15 — a readable one-liner for ANYTHING thrown by a caller arbiter. `String(err)` on a non-Error throw
|
|
700
|
-
* (a test harness rejecting with a raw `{code:'ENOENT', path}` result is the common case) yields the useless
|
|
701
|
-
* `[object Object]`, defeating `blockerDetail`'s entire purpose: naming what broke so the operator can fix it.
|
|
702
|
-
* @param {any} err
|
|
703
|
-
* @returns {string}
|
|
704
|
-
*/
|
|
705
|
-
function describeThrown(err) {
|
|
706
|
-
const clamp = (s) => (s.length > DETAIL_MAX ? `${s.slice(0, DETAIL_MAX)}… (truncated)` : s);
|
|
707
|
-
if (err instanceof Error && typeof err.message === 'string' && err.message) return clamp(err.message);
|
|
708
|
-
if (err === null || typeof err !== 'object') return clamp(String(err));
|
|
709
|
-
// Deliberately NOT a whole-object dump. A thrown non-Error is typically a spawn/exec RESULT, which routinely
|
|
710
|
-
// carries a full stdout buffer and an env snapshot — and `blockerDetail` rides into `receipts`, which a wired
|
|
711
|
-
// gate serializes VERBATIM into a plaintext audit log (the F16/BA-1 lesson: never let caller data of unknown
|
|
712
|
-
// shape reach the audit unfiltered). Take only the conventional diagnostic fields, clamped.
|
|
713
|
-
try {
|
|
714
|
-
const picked = ['name', 'code', 'errno', 'syscall', 'path', 'status', 'signal', 'message']
|
|
715
|
-
.filter(k => typeof err[k] === 'string' || typeof err[k] === 'number')
|
|
716
|
-
.map(k => `${k}=${String(err[k])}`)
|
|
717
|
-
.join(' ');
|
|
718
|
-
if (picked) return clamp(picked);
|
|
719
|
-
} catch { /* a throwing accessor / Proxy trap — fall through to the type tag */ }
|
|
720
|
-
return Object.prototype.toString.call(err);
|
|
721
|
-
}
|
|
722
|
-
|
|
723
|
-
/**
|
|
724
|
-
* BA-15 — run a caller arbiter (the `refineLeaf.sensor` or the `opts.evaluate` verifier) and NAME a broken one
|
|
725
|
-
* rather than let it launder. A non-`HaltError` throw or a malformed return (per {@link verdictShapeFault}) is
|
|
726
|
-
* re-thrown as a typed {@link BrokenArbiterError} the call sites classify by `instanceof` + `.tag` (NEVER by
|
|
727
|
-
* re-parsing the message text); a `HaltError` passes straight through (clean
|
|
728
|
-
* governance exit, BA-2). One helper so the sensor and verifier seams stay byte-identical (same guidance
|
|
729
|
-
* string, same fault taxonomy) — a divergence between them was the copy-paste risk this replaces.
|
|
730
|
-
* A verdict that carries a valid `status` but no boolean `pass` is NORMALIZED to add `pass = status ===
|
|
731
|
-
* 'satisfied'` (the same derivation as `evaluator.js`): the advertised `{status}` contract must actually
|
|
732
|
-
* WORK — `refine.js` stops the leaf on `verdict.pass`, so a bare `{status:'satisfied'}` would otherwise never
|
|
733
|
-
* satisfy, burn every iteration, and report `passed:false` (a satisfied close mislabeled as non-recovery).
|
|
734
|
-
* @template {{pass?: boolean, status?: string}} T
|
|
735
|
-
* @param {'broken-sensor'|'broken-verifier'} tag - the fault channel, carried on the thrown error's `.tag`.
|
|
736
|
-
* @param {() => (T | Promise<T>)} call - invokes the arbiter (already bound to its result/ctx args).
|
|
737
|
-
* @returns {Promise<T>} the arbiter's well-formed verdict (with `pass` derived from `status` when absent).
|
|
738
|
-
*/
|
|
739
|
-
async function runArbiter(tag, call) {
|
|
740
|
-
const who = tag === 'broken-sensor' ? 'sensor' : 'evaluate';
|
|
741
|
-
const shape = `a ${who === 'sensor' ? 'sensor' : 'verifier'} must return {pass} or {status: 'satisfied'|'needs_revision'|'failed'}`;
|
|
742
|
-
/** A throw from the arbiter's own body (sync or async rejection) — "the sensor threw". */
|
|
743
|
-
const threw = (err) => {
|
|
744
|
-
if (err instanceof HaltError || err instanceof BrokenArbiterError) return err;
|
|
745
|
-
// `cause` keeps the original error (stack + type) reachable for debugging; `detail` stays the short label.
|
|
746
|
-
return new BrokenArbiterError(tag, `${who} threw: ${describeThrown(err)}`, { cause: err });
|
|
747
|
-
};
|
|
748
|
-
/** A throw from READING the value the arbiter returned — "the verdict is unreadable", a different fault. */
|
|
749
|
-
const unreadable = (err) => {
|
|
750
|
-
if (err instanceof HaltError || err instanceof BrokenArbiterError) return err;
|
|
751
|
-
return new BrokenArbiterError(tag, `${who} returned a verdict whose properties could not be read: ${describeThrown(err)} — ${shape}`, { cause: err });
|
|
752
|
-
};
|
|
753
|
-
|
|
754
|
-
// Typed `any` deliberately: this block probes an UNTRUSTED caller return (it may be a promise, a plain
|
|
755
|
-
// verdict, or a hostile Proxy), so the generic `T | Promise<T>` narrowing does not apply until it is settled.
|
|
756
|
-
/** @type {any} */
|
|
757
|
-
let raw;
|
|
758
|
-
try {
|
|
759
|
-
raw = call();
|
|
760
|
-
} catch (err) { throw threw(err); }
|
|
761
|
-
|
|
762
|
-
// `await`ing directly would conflate two different faults: the await PROBES `.then` on the returned value,
|
|
763
|
-
// so an accessor-backed/Proxy verdict throws during the await and gets reported as "the sensor threw" —
|
|
764
|
-
// sending the operator hunting a `throw` in a sensor that returned perfectly normally. Probe the thenable
|
|
765
|
-
// separately (a throw HERE is the returned value being unreadable) and only then await (a rejection THERE
|
|
766
|
-
// is genuinely the arbiter's body failing).
|
|
767
|
-
let thenable;
|
|
768
|
-
try {
|
|
769
|
-
thenable = raw !== null && (typeof raw === 'object' || typeof raw === 'function') && typeof raw.then === 'function';
|
|
770
|
-
} catch (err) { throw unreadable(err); }
|
|
771
|
-
|
|
772
|
-
/** @type {any} */
|
|
773
|
-
let v = raw;
|
|
774
|
-
if (thenable) {
|
|
775
|
-
try {
|
|
776
|
-
v = await raw;
|
|
777
|
-
} catch (err) { throw threw(err); }
|
|
778
|
-
}
|
|
779
|
-
// The SHAPE INSPECTION is guarded SEPARATELY: reading `.status`/`.pass`/`Object.keys` on a returned Proxy or
|
|
780
|
-
// accessor-backed object can itself throw. Unguarded that escapes untyped (the very uncaught crash this seam
|
|
781
|
-
// prevents, one step later) — but folding it into the call's own catch is also wrong: it reports "the sensor
|
|
782
|
-
// threw" for a sensor that RETURNED NORMALLY, sending the operator hunting a `throw` that does not exist.
|
|
783
|
-
// The fault is in the returned VALUE, so it is named as such.
|
|
784
|
-
try {
|
|
785
|
-
const fault = verdictShapeFault(v);
|
|
786
|
-
if (fault) throw new BrokenArbiterError(tag, `${who} ${fault} — ${shape}`);
|
|
787
|
-
// Derive `pass` from a status-only verdict so the advertised `{status}` shape actually gates `refine`, which
|
|
788
|
-
// branches on `verdict.pass`. NEVER mutate the caller's object — and never flatten it either: an object
|
|
789
|
-
// spread copies OWN enumerable properties only, so a class-instance verdict whose `status`/`critique` are
|
|
790
|
-
// PROTOTYPE getters passes the shape check above and then comes out the other side with those fields
|
|
791
|
-
// ERASED (critique lost ⇒ every retry re-sends the plain task with zero feedback — the exact burn BA-15
|
|
792
|
-
// exists to prevent). Copy descriptors onto the SAME prototype so accessor-backed fields survive.
|
|
793
|
-
if (v.pass == null && typeof v.status === 'string') {
|
|
794
|
-
const copy = Object.create(Object.getPrototypeOf(v), Object.getOwnPropertyDescriptors(v));
|
|
795
|
-
Object.defineProperty(copy, 'pass', {
|
|
796
|
-
value: v.status === 'satisfied', writable: true, enumerable: true, configurable: true,
|
|
797
|
-
});
|
|
798
|
-
return /** @type {T} */ (copy);
|
|
799
|
-
}
|
|
800
|
-
return v;
|
|
801
|
-
} catch (err) { throw unreadable(err); }
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
/**
|
|
805
|
-
* BA-15 — surface a CHILD's blocker at the PARENT. A nested tree aggregates a dead child into
|
|
806
|
-
* `{incomplete, missingSlices}`; without this the child's `broken-sensor` (or `governance-deny`) label is
|
|
807
|
-
* dropped at the first parent, so a top-level caller branching on `result.blocker` sees nothing and debugs
|
|
808
|
-
* the model instead of its own sensor — the exact laundering BA-15 exists to close, reintroduced one level up.
|
|
809
|
-
* `broken-sensor` wins over `governance-deny`: it names a fault in the CALLER's own code, which is both more
|
|
810
|
-
* actionable and cheaper to fix than a gate decision.
|
|
811
|
-
*
|
|
812
|
-
* `blockerTask` names WHICH descendant broke. Without it a nested run reports "a sensor broke" with no way to
|
|
813
|
-
* find which one — half a fix. (It is also why the label is NOT stamped onto the parent's own `blocker`; see
|
|
814
|
-
* {@link incompleteWithBlocker}.)
|
|
815
|
-
*
|
|
816
|
-
* `'broken-verifier'` is deliberately NOT matched here: `forChild` strips `evaluate`, so a child never runs a
|
|
817
|
-
* caller verifier and no child node can carry that label. Matching it would be unreachable code asserting a
|
|
818
|
-
* capability that does not exist.
|
|
819
|
-
* @param {RecurseNode[]} spawned - this node's child receipts.
|
|
820
|
-
* @returns {{blocker: string, blockerDetail?: string, blockerTask?: string}|null}
|
|
821
|
-
*/
|
|
822
|
-
function inheritedBlocker(spawned) {
|
|
823
|
-
const pick = spawned.find(c => c.incomplete && c.blocker === 'broken-sensor')
|
|
824
|
-
|| spawned.find(c => c.incomplete && c.blocker);
|
|
825
|
-
if (!pick || !pick.blocker) return null;
|
|
826
|
-
return {
|
|
827
|
-
blocker: pick.blocker,
|
|
828
|
-
...(pick.blockerDetail && { blockerDetail: pick.blockerDetail }),
|
|
829
|
-
...(pick.task && { blockerTask: pick.task }),
|
|
830
|
-
};
|
|
831
|
-
}
|
|
832
|
-
|
|
833
|
-
/**
|
|
834
|
-
* BA-15 — the ONE shared "this node is incomplete because a descendant was" return. Used by every aggregating
|
|
835
|
-
* path (worker / partition / fanout) on BOTH its `missingSlices` branch AND its `HaltError` catch: the halt
|
|
836
|
-
* branches originally skipped the inherit entirely, so a gate tripping AFTER a broken-sensor child (e.g. mid-
|
|
837
|
-
* synthesize) dropped the label and the caller read a governance problem where their own sensor had crashed.
|
|
838
|
-
*
|
|
839
|
-
* The inherited label rides the RETURNED result (the caller-facing API — that surfacing is the whole point)
|
|
840
|
-
* but is recorded on the node as `blockerFrom`, NOT by overwriting `node.blocker`. `node.blocker` means "THIS
|
|
841
|
-
* node's own arbiter/Loop broke"; stamping a descendant's label onto every ancestor made the receipts tree
|
|
842
|
-
* accuse nodes whose sensor never ran, and re-labelled a parent `governance-deny` when only one child was
|
|
843
|
-
* denied — pointing the operator at the wrong node to re-gate.
|
|
844
|
-
* @param {RecurseNode} node
|
|
845
|
-
* @param {any} best
|
|
846
|
-
* @param {{missingSlices?: string[]}} [extra] - extra fields for the non-halt aggregation branch.
|
|
847
|
-
* @returns {RecurseResult}
|
|
848
|
-
*/
|
|
849
|
-
function incompleteWithBlocker(node, best, extra = {}) {
|
|
850
|
-
const inherited = inheritedBlocker(node.spawned);
|
|
851
|
-
if (inherited) node.blockerFrom = inherited;
|
|
852
|
-
return /** @type {RecurseResult} */ ({ incomplete: true, best, ...extra, ...(inherited || {}), receipts: node });
|
|
853
|
-
}
|
|
854
|
-
|
|
855
|
-
/**
|
|
856
|
-
* BA-8 leaf-refine — run a DEFINITE leaf as a bounded generate→sense→regenerate loop (relayfact F17). Reuses the
|
|
857
|
-
* existing `refine.js` primitive (the Outcomes iterate→grade→revise port): each attempt is a FRESH leaf Loop
|
|
858
|
-
* (fresh window = fresh-feedback, D6/A1) seeded with the working-context'd task + (on a retry) the prior GAP, run
|
|
859
|
-
* at an ESCALATING temperature — the live-validated requirement that lets a weak model escape a repeat-the-same-
|
|
860
|
-
* mistake rut (a flat temperature recovered 0/5 in `poc/ba8-leaf-refine.mjs`). The `sensor` is the caller's
|
|
861
|
-
* DETERMINISTIC close (test/compile/lint, not a model judge). Governance is bareguard's: every attempt is gate-
|
|
862
|
-
* checked (`ctx.policy`) and metered (`onLlmResult`); a HaltError mid-loop is a clean `{incomplete}`. Honest
|
|
863
|
-
* non-recovery is reported (`receipts.refineLeaf.passed=false`), never a faked pass. An optional rubric `verify`
|
|
864
|
-
* still runs on top when a `contract`/`evaluate`/critical applies (the sensor gates retries; the rubric grades).
|
|
865
|
-
* @param {string} task
|
|
866
|
-
* @param {RecurseCtx} ctx
|
|
867
|
-
* @param {RecurseOptions} opts
|
|
868
|
-
* @param {{provider: Provider, system: string, handleTools: ToolDef[], depth: number, critical: boolean, node: RecurseNode, sensor: Function}} state
|
|
869
|
-
* @returns {Promise<RecurseResult>}
|
|
870
|
-
*/
|
|
871
|
-
async function recurseRefineLeaf(task, ctx, opts, state) {
|
|
872
|
-
const { provider, system, handleTools, depth, critical, node, sensor } = state;
|
|
873
|
-
node.model = provider.model || null;
|
|
874
|
-
const cfg = /** @type {{maxIterations?: number, temperatures?: number[], rejectedBuffer?: boolean}} */ (opts.refineLeaf || {});
|
|
875
|
-
const temps = Array.isArray(cfg.temperatures) && cfg.temperatures.length ? cfg.temperatures : DEFAULT_REFINE_TEMPS;
|
|
876
|
-
const maxIterations = Number.isInteger(cfg.maxIterations) && /** @type {number} */ (cfg.maxIterations) > 0
|
|
877
|
-
? /** @type {number} */ (cfg.maxIterations) : temps.length;
|
|
878
|
-
// BA-14 rejected-attempt buffer: surface the model's OWN prior failed attempts verbatim ("you wrote these,
|
|
879
|
-
// they failed X — write something DIFFERENT") — a SkillOpt-shaped directed-diversity lever. `rejectedBuffer`:
|
|
880
|
-
// `true` = force on (also on temperature-accepting models); `false` = force off; unset = ADAPTIVE (engage only
|
|
881
|
-
// once a prior attempt's temperature was DROPPED, i.e. a temperature-fixed model where BA-8 escalation is inert
|
|
882
|
-
// and the buffer is the only lever — ba14 D>C). Escalation and the buffer are ANTAGONISTIC (ba14b: temp
|
|
883
|
-
// monotonically degrades the buffer 100→70→50% across 0.2/0.7/1.0), so when the buffer engages we HOLD temps[0].
|
|
884
|
-
const bufferForced = cfg.rejectedBuffer === true;
|
|
885
|
-
const bufferDisabled = cfg.rejectedBuffer === false;
|
|
886
|
-
let bufferUsed = false; // receipt: did any iteration actually inject the ledger?
|
|
887
|
-
const LEDGER_ENTRY_CAP = 600, LEDGER_WHY_CAP = 400;
|
|
888
|
-
const formatLedger = (/** @type {Array<{result: any, verdict: any}>} */ history) => history.map((h, i) => {
|
|
889
|
-
const code = String(h.result == null ? '' : h.result).replace(/```[a-zA-Z]*\n?/g, '').trim().slice(0, LEDGER_ENTRY_CAP);
|
|
890
|
-
const why = h.verdict && typeof h.verdict.critique === 'string' ? h.verdict.critique.slice(0, LEDGER_WHY_CAP) : '';
|
|
891
|
-
return `--- Rejected attempt ${i + 1} (already failed — do NOT reproduce) ---\n${code}${why ? `\nFailed: ${why}` : ''}`;
|
|
892
|
-
}).join('\n\n');
|
|
893
|
-
|
|
894
|
-
// A refine leaf runs N Loops, so its receipts.tokens SUMS every attempt's spend (not just the last) — the
|
|
895
|
-
// honest cost of the node. The 4-tier tokens object (`{input,output,cacheCreation,cacheRead}`, loop.js) is flat
|
|
896
|
-
// numeric, so we accrue field-wise (robust to extra/renamed numeric fields). The gate already sees each attempt
|
|
897
|
-
// via onLlmResult independently; this is the receipts mirror. Stays null until an attempt produces metrics.
|
|
898
|
-
/** @type {Record<string, number>|null} */
|
|
899
|
-
let tokensSum = null;
|
|
900
|
-
const accrueTokens = (/** @type {any} */ t) => {
|
|
901
|
-
if (!t || typeof t !== 'object') return;
|
|
902
|
-
tokensSum = tokensSum || {};
|
|
903
|
-
for (const [k, v] of Object.entries(t)) if (typeof v === 'number') tokensSum[k] = (tokensSum[k] || 0) + v;
|
|
904
|
-
};
|
|
905
|
-
// BA-10 honest receipt: the EFFECTIVE temperature per attempt. A model that rejects a non-default
|
|
906
|
-
// `temperature` (400, unsupported/deprecated) runs at its DEFAULT — the provider drops it and the Loop
|
|
907
|
-
// surfaces `temperatureDropped`. Recording the requested temp would claim a value the model ignored, so
|
|
908
|
-
// a dropped attempt is stored as `null` ("provider default"). Indexed by iteration (refine calls once each).
|
|
909
|
-
/** @type {(number|null)[]} */
|
|
910
|
-
const effectiveTemps = [];
|
|
911
|
-
// BA-15/BA-5: the last attempt's text, kept OUTSIDE refine so a broken-sensor stop can still preserve the
|
|
912
|
-
// model's work — when the ARBITER breaks, the work was never judged; destroying it would punish the model
|
|
913
|
-
// for the caller's fault (refine's own history is lost on the throw).
|
|
914
|
-
/** @type {string|null} */
|
|
915
|
-
let lastAttemptText = null;
|
|
916
|
-
// One attempt = a fresh leaf Loop (no spawn tool: a retry is a direct correction, not a re-decomposition) at the
|
|
917
|
-
// iteration's temperature, with the GAP fed forward as fresh feedback. A governance halt → throw so refine stops.
|
|
918
|
-
const attempt = async ({ iteration, critique, history }) => {
|
|
919
|
-
const hist = Array.isArray(history) ? history : [];
|
|
920
|
-
// ADAPTIVE trigger: a prior attempt whose temperature the model rejected (BA-10) records `null` in
|
|
921
|
-
// effectiveTemps → escalation is inert on this (temperature-fixed) model, so engage the buffer. Forced-on
|
|
922
|
-
// engages regardless (incl. temperature-accepting models). Needs ≥1 prior attempt to have something to buffer.
|
|
923
|
-
const tempDropped = effectiveTemps.some((t) => t === null);
|
|
924
|
-
const useBuffer = hist.length > 0 && !bufferDisabled && (bufferForced || tempDropped);
|
|
925
|
-
// ba14b: temperature is antagonistic to the buffer's directed diversity — HOLD temps[0] when it engages;
|
|
926
|
-
// otherwise escalate (BA-8, the no-memory lever). On a temperature-fixed model both collapse to the default.
|
|
927
|
-
const temperature = useBuffer ? temps[0] : temps[Math.min(iteration, temps.length - 1)];
|
|
928
|
-
const loop = new Loop({
|
|
929
|
-
provider, system,
|
|
930
|
-
policy: ctx.policy || undefined,
|
|
931
|
-
onLlmResult: ctx.onLlmResult || undefined,
|
|
932
|
-
stream: ctx.stream || undefined,
|
|
933
|
-
throwOnError: false,
|
|
934
|
-
});
|
|
935
|
-
const base = withContext(task, opts.context);
|
|
936
|
-
let userText;
|
|
937
|
-
if (useBuffer) {
|
|
938
|
-
bufferUsed = true;
|
|
939
|
-
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)}`;
|
|
940
|
-
} else if (critique) {
|
|
941
|
-
userText = `${base}\n\nYour previous attempt FAILED these checks:\n${critique}\n\nReturn a corrected result that passes ALL of them.`;
|
|
942
|
-
} else {
|
|
943
|
-
userText = base;
|
|
944
|
-
}
|
|
945
|
-
const out = await loop.run([{ role: 'user', content: userText }], handleTools, { ctx: auditSafeCtx(ctx, { depth }), temperature });
|
|
946
|
-
// `temperatureDropped` is set on the Loop result only when the model rejected the requested temperature
|
|
947
|
-
// (BA-10); it's absent on the error/halt return shapes, so read it through a narrow cast.
|
|
948
|
-
const dropped = /** @type {{temperatureDropped?: boolean}} */ (out).temperatureDropped;
|
|
949
|
-
effectiveTemps[iteration] = dropped ? null : temperature;
|
|
950
|
-
accrueTokens(out.metrics ? out.metrics.tokens : null);
|
|
951
|
-
// BA-5: capture BEFORE the throws. The Loop returns its last non-empty text on EVERY terminating path
|
|
952
|
-
// (halt/deny/truncation/refusal), so a throw placed above this line would discard the text of the very
|
|
953
|
-
// attempt that terminated — leaving `best:null` on a FIRST-attempt halt, the exact loss the catch-branch
|
|
954
|
-
// preservation exists to prevent. (Caught by review: the earlier tests only halted on attempt 2, where a
|
|
955
|
-
// prior clean attempt had already populated this.)
|
|
956
|
-
lastAttemptText = out.text || lastAttemptText;
|
|
957
|
-
if (typeof out.error === 'string' && out.error.startsWith('halt:')) throw new HaltError('refine-leaf attempt halted', { rule: out.error.slice('halt:'.length) });
|
|
958
|
-
if (out.error) throw new Error(out.error); // a non-halt worker fault → honest incomplete
|
|
959
|
-
return out.text;
|
|
960
|
-
};
|
|
961
|
-
|
|
962
|
-
// BA-15: the sensor call is WRAPPED (via runArbiter) so a broken arbiter is NAMED, never coerced. A non-Halt
|
|
963
|
-
// throw (the caller's test runner crashed — ENOENT, syntax error in the harness) and a malformed return are
|
|
964
|
-
// the same fault class: "didn't judge", which must never collapse into "judged-and-failed" (the model's
|
|
965
|
-
// fault) or a bare {incomplete} (indistinguishable from a provider death). The throw stops refine at the
|
|
966
|
-
// FIRST broken close — retrying against a broken arbiter burns every remaining attempt for nothing (each
|
|
967
|
-
// retry would carry critique:null, i.e. the plain task again). HaltError passes through (governance, BA-2).
|
|
968
|
-
const evaluate = (result, c) => runArbiter('broken-sensor', () => sensor(result, { task, context: opts.context, contract: c.contract }));
|
|
969
|
-
|
|
970
|
-
try {
|
|
971
|
-
const outcome = await refine({
|
|
972
|
-
attempt,
|
|
973
|
-
evaluate,
|
|
974
|
-
contract: typeof opts.contract === 'string' ? opts.contract : undefined,
|
|
975
|
-
maxIterations,
|
|
976
|
-
});
|
|
977
|
-
node.tokens = tokensSum;
|
|
978
|
-
// `temperatures` = the EFFECTIVE temps (BA-10): a `null` marks an attempt whose requested temperature the
|
|
979
|
-
// model rejected and ran at its default — so the receipt never claims a value the model ignored. On a
|
|
980
|
-
// temperature-accepting model this equals the requested `temps.slice(0, iterations)` (byte-identical receipt).
|
|
981
|
-
node.refineLeaf = { iterations: outcome.iterations, passed: !!(outcome.verdict && outcome.verdict.pass), temperatures: effectiveTemps.slice(0, outcome.iterations), rejectedBuffer: bufferUsed };
|
|
982
|
-
const result = outcome.result;
|
|
983
|
-
|
|
984
|
-
// Optional rubric layer on top of the deterministic sensor (RC-7): forced for critical, or a contract/override.
|
|
985
|
-
const wantVerify = critical || typeof opts.contract === 'string' || typeof opts.evaluate === 'function';
|
|
986
|
-
if (wantVerify) {
|
|
987
|
-
// `return await` (not a bare `return`) is load-bearing here — see verifyOrBlock's JSDoc.
|
|
988
|
-
return await verifyOrBlock(task, result, ctx, opts, node);
|
|
989
|
-
}
|
|
990
|
-
// No rubric layer ⇒ the sensor's final verdict IS the node verdict (a non-pass is surfaced, not hidden).
|
|
991
|
-
node.verdict = outcome.verdict || null;
|
|
992
|
-
return { result, verdict: outcome.verdict || null, receipts: node };
|
|
993
|
-
} catch (err) {
|
|
994
|
-
node.tokens = tokensSum; // record whatever attempts DID spend, on both the halt and fault paths
|
|
995
|
-
// The refineLeaf receipt must ride EVERY terminating path, not just the clean one (same invariant as BA-10's
|
|
996
|
-
// `temperatureDropped`): a leaf that ran attempts then halted/faulted still spent tokens and may have engaged
|
|
997
|
-
// the buffer. `effectiveTemps[iteration]` is set BEFORE each attempt's throw, so it reflects every attempt made.
|
|
998
|
-
// NOT unconditional: the refine loop may have COMPLETED (receipt already written, possibly `passed:true`) and
|
|
999
|
-
// the throw come from the verify layer below it — clobbering that to `passed:false` would report a sensor that
|
|
1000
|
-
// never closed when it did, misattributing a verify-slot halt to a non-converging leaf.
|
|
1001
|
-
if (!node.refineLeaf) {
|
|
1002
|
-
node.refineLeaf = { iterations: effectiveTemps.length, passed: false, temperatures: effectiveTemps.slice(), rejectedBuffer: bufferUsed };
|
|
1003
|
-
}
|
|
1004
|
-
// BA-5: EVERY terminating branch preserves the model's last non-empty attempt (`lastAttemptText`), never
|
|
1005
|
-
// `null` — matching the plain-worker path (`best: out.text || null`) and the "bounds PRESERVE work"
|
|
1006
|
-
// invariant. A refine leaf is the sole cross-attempt text channel in a ralph-style retry; dropping it on a
|
|
1007
|
-
// halt/deny/fault (as this path did pre-BA-15) loses attempt N's only bridge to attempt N+1.
|
|
1008
|
-
if (err instanceof HaltError) {
|
|
1009
|
-
node.halted = true;
|
|
1010
|
-
node.incomplete = true;
|
|
1011
|
-
return { incomplete: true, best: lastAttemptText, receipts: node };
|
|
1012
|
-
}
|
|
1013
|
-
// BA-11: a deny-spin inside a refine attempt (the Loop short-circuited after N consecutive governance
|
|
1014
|
-
// denials, rethrown at recurse.js as `denied:<tool>`) is a LABELED governance block, not a model fault.
|
|
1015
|
-
if (typeof err?.message === 'string' && err.message.startsWith('denied:')) {
|
|
1016
|
-
node.incomplete = true;
|
|
1017
|
-
node.blocker = 'governance-deny';
|
|
1018
|
-
return { incomplete: true, best: lastAttemptText, blocker: 'governance-deny', receipts: node };
|
|
1019
|
-
}
|
|
1020
|
-
// BA-15: the caller's SENSOR broke — a faulty arbiter, not a model failure. Named (like BA-11's
|
|
1021
|
-
// governance-deny) so the caller fixes the sensor instead of debugging the model; `best` preserves the
|
|
1022
|
-
// model's last non-empty attempt (BA-5) — the arbiter, not the model, is at fault.
|
|
1023
|
-
if (err instanceof BrokenArbiterError && err.tag === 'broken-sensor') {
|
|
1024
|
-
node.incomplete = true;
|
|
1025
|
-
node.blocker = 'broken-sensor';
|
|
1026
|
-
node.blockerDetail = err.detail;
|
|
1027
|
-
// `blockerDetail` rides the RESULT too, not just receipts: it is the actionable half of the label (WHAT
|
|
1028
|
-
// the sensor did), and a parent reading a child's return — or a caller branching on the documented
|
|
1029
|
-
// `{blocker}` shape — should not have to walk the receipts tree to get it.
|
|
1030
|
-
return { incomplete: true, best: lastAttemptText, blocker: 'broken-sensor', blockerDetail: err.detail, receipts: node };
|
|
1031
|
-
}
|
|
1032
|
-
node.incomplete = true;
|
|
1033
|
-
return { incomplete: true, best: lastAttemptText, receipts: node };
|
|
1034
|
-
}
|
|
1035
|
-
}
|
|
1036
|
-
|
|
1037
|
-
/**
|
|
1038
|
-
* SCAN (§10 step 7 / §9.2.1) — the default retrieval mode for a "how many / all" task over a corpus. A
|
|
1039
|
-
* deterministic ORCHESTRATION, not a worker model call: every slice is processed, an isolated Loop LLM-judges
|
|
1040
|
-
* each window, and the matching ids are unioned + CODE-counted (the aggregation is CODE, never a model
|
|
1041
|
-
* Finish/count — RC-5 / §9.1 flaw #2, the path that does not silently undercount). The result is structured
|
|
1042
|
-
* (`{count, matchedIds}`), never a model-stated number. RC-9: a dead window → `{incomplete, missingSlices}`,
|
|
1043
|
-
* never folded into the count as a zero; a governance HaltError mid-scan → clean incomplete.
|
|
1044
|
-
*
|
|
1045
|
-
* The corpus is the generic array slice-source `opts.corpus`. Absent it, scan has nothing to read — litectx's
|
|
1046
|
-
* resident-corpus enumerate path is deferred (docs/archive/prd.md) — so we return an
|
|
1047
|
-
* honest incomplete, never a fabricated zero.
|
|
1048
|
-
* @param {string} task
|
|
1049
|
-
* @param {RecurseCtx} ctx
|
|
1050
|
-
* @param {RecurseOptions} opts
|
|
1051
|
-
* @param {{provider: Provider, depth: number, critical: boolean, node: RecurseNode}} state
|
|
1052
|
-
* @returns {Promise<RecurseResult>}
|
|
1053
|
-
*/
|
|
1054
|
-
async function recurseScan(task, ctx, opts, state) {
|
|
1055
|
-
const { provider, critical, node } = state;
|
|
1056
|
-
node.model = provider.model || null;
|
|
1057
|
-
|
|
1058
|
-
// Resolve the slice-source: an in-hand array, or an async `() => Promise<Slice[]>` (e.g. `litectxCorpus`
|
|
1059
|
-
// materializing a litectx-resident corpus via enumerate). A source fault is an honest incomplete, not a
|
|
1060
|
-
// fabricated empty scan; a governance HaltError during materialization is a clean halt.
|
|
1061
|
-
let corpus;
|
|
1062
|
-
try {
|
|
1063
|
-
const raw = typeof opts.corpus === 'function' ? await opts.corpus() : opts.corpus;
|
|
1064
|
-
corpus = normalizeCorpus(raw);
|
|
1065
|
-
} catch (err) {
|
|
1066
|
-
if (err instanceof HaltError) {
|
|
1067
|
-
node.halted = true;
|
|
1068
|
-
node.incomplete = true;
|
|
1069
|
-
return { incomplete: true, best: null, receipts: node };
|
|
1070
|
-
}
|
|
1071
|
-
node.incomplete = true;
|
|
1072
|
-
return { incomplete: true, best: null, missingSlices: [`scan corpus source failed: ${err.message}`], receipts: node };
|
|
1073
|
-
}
|
|
1074
|
-
if (corpus.length === 0) {
|
|
1075
|
-
node.incomplete = true;
|
|
1076
|
-
return {
|
|
1077
|
-
incomplete: true,
|
|
1078
|
-
best: null,
|
|
1079
|
-
missingSlices: ['scan requires a non-empty corpus (array or an async slice-source like litectxCorpus)'],
|
|
1080
|
-
receipts: node,
|
|
1081
|
-
};
|
|
1082
|
-
}
|
|
1083
|
-
|
|
1084
|
-
// BA-5: hoisted so a halt thrown BELOW the scan (e.g. from the verify slot) still returns the finished,
|
|
1085
|
-
// code-counted result as `best` instead of destroying it — re-running a scan re-pays every window judge call.
|
|
1086
|
-
/** @type {{count: number, matchedIds: string[]}|null} */
|
|
1087
|
-
let scanResult = null;
|
|
1088
|
-
try {
|
|
1089
|
-
const scan = await scanCount(task, corpus, {
|
|
1090
|
-
provider,
|
|
1091
|
-
window: opts.window,
|
|
1092
|
-
passes: opts.passes,
|
|
1093
|
-
ctx: auditSafeCtx(ctx, { depth: state.depth }), // scan's Loop run ctx reaches the gate — strip provider (F16/BA-1)
|
|
1094
|
-
onLlmResult: ctx.onLlmResult,
|
|
1095
|
-
policy: ctx.policy,
|
|
1096
|
-
});
|
|
1097
|
-
node.scan = { window: scan.window, passes: scan.passes, scanned: scan.scanned, matched: scan.count };
|
|
1098
|
-
// Structured, CODE-counted result — the count is authoritative; matchedIds carry the evidence (RC-10).
|
|
1099
|
-
const result = { count: scan.count, matchedIds: scan.matchedIds };
|
|
1100
|
-
scanResult = result;
|
|
1101
|
-
|
|
1102
|
-
// RC-9: a dead window means we did NOT see every slice → the count is a floor, not the answer. Report it
|
|
1103
|
-
// incomplete with the partial as `best`, never a clean pass over a hole.
|
|
1104
|
-
if (scan.missingSlices.length > 0) {
|
|
1105
|
-
node.incomplete = true;
|
|
1106
|
-
return { incomplete: true, best: result, missingSlices: scan.missingSlices, receipts: node };
|
|
1107
|
-
}
|
|
1108
|
-
|
|
1109
|
-
// Verify (RC-7): forced for critical, or when a contract/override is supplied. The judge grades the
|
|
1110
|
-
// structured count against the goal/contract (an isolated grader, never the scanner itself).
|
|
1111
|
-
const wantVerify = critical || typeof opts.contract === 'string' || typeof opts.evaluate === 'function';
|
|
1112
|
-
if (wantVerify) {
|
|
1113
|
-
// `return await` (not a bare `return`) is load-bearing here — see verifyOrBlock's JSDoc.
|
|
1114
|
-
return await verifyOrBlock(task, result, ctx, opts, node);
|
|
1115
|
-
}
|
|
1116
|
-
return { result, verdict: null, receipts: node };
|
|
1117
|
-
} catch (err) {
|
|
1118
|
-
if (err instanceof HaltError) {
|
|
1119
|
-
node.halted = true;
|
|
1120
|
-
node.incomplete = true;
|
|
1121
|
-
// BA-5, PARTIAL by construction: a halt from the VERIFY slot lands here with the scan already finished,
|
|
1122
|
-
// so the counted result is returned instead of null (it previously survived only in receipts, forcing a
|
|
1123
|
-
// full re-scan). A halt DURING `scanCount` — the likelier case, since a token cap trips after many window
|
|
1124
|
-
// judge calls — still yields `null`: `scanCount` throws without surfacing the windows it did judge, so
|
|
1125
|
-
// there is nothing here to preserve. Fixing that needs `scanCount` to return its partial union on halt
|
|
1126
|
-
// (a retrieval-side change, not this seam's); tracked as a known limit rather than papered over here.
|
|
1127
|
-
return { incomplete: true, best: scanResult, receipts: node };
|
|
1128
|
-
}
|
|
1129
|
-
throw err;
|
|
1130
|
-
}
|
|
1131
|
-
}
|
|
1132
|
-
|
|
1133
|
-
/**
|
|
1134
|
-
* DATA-DRIVEN WIDTH PARTITION (NB-2 / §11) — the *width* dial that stacks above the fixed/semantic count floor.
|
|
1135
|
-
* Distinct from Family B's `recurseFanout` (a `Planner` SEMANTIC decomposition): this MEASURES a real corpus and
|
|
1136
|
-
* PARTITIONS it into `width = max(floor, ⌈size / workerBudget⌉)` contiguous chunks (capped by the guards and by
|
|
1137
|
-
* the size), each scanned by a fresh-window `recurse({retrieval:'scan'})` worker, then CODE-reduced (union the
|
|
1138
|
-
* matched ids → count; the §9.1 aggregation, never a model count). `opts.count` is the width FLOOR (never
|
|
1139
|
-
* lowered); the data may RAISE it. Like `recurseFanout`: a pre-wave `ctx.policy('recurse_partition', …)`
|
|
1140
|
-
* checkpoint runs once `width` is known (a budget HaltError → clean incomplete before any worker spends); RC-9
|
|
1141
|
-
* holds (a dead/incomplete chunk → `{incomplete, missingSlices}`, never a survivor-sum).
|
|
1142
|
-
*
|
|
1143
|
-
* The corpus is the generic slice-source (`opts.corpus` array or async fn, e.g. `litectxCorpus`) — materialized
|
|
1144
|
-
* once in the parent (cheap: data in an array), then each worker's LLM context sees only its chunk's windows.
|
|
1145
|
-
* @param {string} task
|
|
1146
|
-
* @param {RecurseCtx} ctx
|
|
1147
|
-
* @param {RecurseOptions} opts
|
|
1148
|
-
* @param {{provider: Provider, depth: number, critical: boolean, node: RecurseNode}} state
|
|
1149
|
-
* @returns {Promise<RecurseResult>}
|
|
1150
|
-
*/
|
|
1151
|
-
async function recursePartition(task, ctx, opts, state) {
|
|
1152
|
-
const { provider, depth, critical, node } = state;
|
|
1153
|
-
node.model = provider.model || null;
|
|
1154
|
-
|
|
1155
|
-
// 1) Materialize the slice-source (array or async fn). A fault is an honest incomplete; a Halt is clean.
|
|
1156
|
-
let corpus;
|
|
1157
|
-
try {
|
|
1158
|
-
const raw = typeof opts.corpus === 'function' ? await opts.corpus() : opts.corpus;
|
|
1159
|
-
corpus = normalizeCorpus(raw);
|
|
1160
|
-
} catch (err) {
|
|
1161
|
-
if (err instanceof HaltError) { node.halted = true; node.incomplete = true; return { incomplete: true, best: null, receipts: node }; }
|
|
1162
|
-
node.incomplete = true;
|
|
1163
|
-
return { incomplete: true, best: null, missingSlices: [`partition corpus source failed: ${err.message}`], receipts: node };
|
|
1164
|
-
}
|
|
1165
|
-
if (corpus.length === 0) {
|
|
1166
|
-
node.incomplete = true;
|
|
1167
|
-
return { incomplete: true, best: null, missingSlices: ['partition requires a non-empty corpus (array or async slice-source)'], receipts: node };
|
|
1168
|
-
}
|
|
1169
|
-
|
|
1170
|
-
// 2) Width = max(floor, ⌈size / workerBudget⌉), never below the floor, capped at the corpus size (no empty
|
|
1171
|
-
// workers). `opts.count` is the floor; the data raises it. The guards (the checkpoint below) are the ceiling.
|
|
1172
|
-
const size = corpus.length;
|
|
1173
|
-
const floor = Number.isInteger(opts.count) && /** @type {number} */ (opts.count) > 0 ? /** @type {number} */ (opts.count) : 1;
|
|
1174
|
-
const workerBudget = Number.isInteger(opts.workerBudget) && /** @type {number} */ (opts.workerBudget) > 0 ? /** @type {number} */ (opts.workerBudget) : DEFAULT_WORKER_BUDGET;
|
|
1175
|
-
const dataWidth = Math.ceil(size / workerBudget);
|
|
1176
|
-
const width = Math.min(Math.max(floor, dataWidth), size);
|
|
1177
|
-
const concurrency = Number.isInteger(opts.concurrency) && /** @type {number} */ (opts.concurrency) > 0 ? /** @type {number} */ (opts.concurrency) : DEFAULT_FANOUT_CONCURRENCY;
|
|
1178
|
-
node.partition = { size, workerBudget, floor, dataWidth, width };
|
|
1179
|
-
// NB: `node.retrieval` stays null here (its default) — the partition orchestrator is its OWN dispatch path, not
|
|
1180
|
-
// the Family-A scan dispatch; its audit record is `node.partition`. The per-chunk WORKERS run scan and record it
|
|
1181
|
-
// on THEIR nodes (`receipts.spawned`). The node-literal null default is what makes this consistently defined
|
|
1182
|
-
// (never `undefined`) across every dispatch path.
|
|
1183
|
-
|
|
1184
|
-
const childResults = [];
|
|
1185
|
-
/** @type {{count: number, matchedIds: string[]}|null} */
|
|
1186
|
-
let partitionResult = null;
|
|
1187
|
-
try {
|
|
1188
|
-
// 2b) Pre-wave checkpoint — width (the cost) is now known. A governance HaltError halts BEFORE any worker
|
|
1189
|
-
// spends (bounds the burst to zero); a plain deny is advisory (allowlist-safe), same contract as fanout.
|
|
1190
|
-
if (typeof ctx.policy === 'function') {
|
|
1191
|
-
try {
|
|
1192
|
-
await ctx.policy('recurse_partition', { width, size, depth }, auditSafeCtx(ctx, { depth }));
|
|
1193
|
-
} catch (err) {
|
|
1194
|
-
if (err instanceof HaltError) throw err;
|
|
1195
|
-
}
|
|
1196
|
-
}
|
|
1197
|
-
|
|
1198
|
-
// 3) Partition into `width` chunks; each chunk → a fresh-window scan worker. The chunk rides on the step so
|
|
1199
|
-
// `runPlan` (waves + concurrency cap) can route it (executeFn gets only the step); results align by index.
|
|
1200
|
-
const chunks = partitionInto(corpus, width);
|
|
1201
|
-
const childOpts = { ...forChild(opts), retrieval: /** @type {'scan'} */ ('scan'), window: opts.window, passes: opts.passes };
|
|
1202
|
-
const steps = chunks.map((chunk, i) => ({ id: `p${i}`, action: `partition ${i} (${chunk.length} items)`, dependsOn: [], chunk }));
|
|
1203
|
-
const results = await runPlan(
|
|
1204
|
-
steps,
|
|
1205
|
-
(step) => recurse(task, { ...ctx, depth: depth + 1 }, { ...childOpts, corpus: /** @type {any} */ (step).chunk }),
|
|
1206
|
-
{ concurrency },
|
|
1207
|
-
);
|
|
1208
|
-
|
|
1209
|
-
// 4) CODE-reduce: union the matched ids across chunks (chunks are disjoint, so union size == Σ counts, and
|
|
1210
|
-
// union is robust to any overlap). RC-9: a dead/incomplete chunk is a MISSING slice, never survivor-summed.
|
|
1211
|
-
/** @type {Set<string>} */
|
|
1212
|
-
const matched = new Set();
|
|
1213
|
-
/** @type {string[]} */
|
|
1214
|
-
const missingSlices = [];
|
|
1215
|
-
for (let i = 0; i < results.length; i++) {
|
|
1216
|
-
const r = results[i];
|
|
1217
|
-
const label = steps[i] ? steps[i].action : `partition ${i}`;
|
|
1218
|
-
if (r.status !== 'done' || !r.result) {
|
|
1219
|
-
node.spawned.push(makeDeadNode(label, depth + 1));
|
|
1220
|
-
missingSlices.push(label);
|
|
1221
|
-
continue;
|
|
1222
|
-
}
|
|
1223
|
-
const child = /** @type {RecurseResult} */ (r.result);
|
|
1224
|
-
node.spawned.push(child.receipts);
|
|
1225
|
-
const val = child.incomplete ? child.best : child.result;
|
|
1226
|
-
if (val && Array.isArray(val.matchedIds)) for (const id of val.matchedIds) matched.add(id);
|
|
1227
|
-
childResults.push(val);
|
|
1228
|
-
if (child.incomplete) missingSlices.push(label);
|
|
1229
|
-
}
|
|
1230
|
-
const result = { count: matched.size, matchedIds: [...matched] };
|
|
1231
|
-
partitionResult = result; // BA-5: a halt below this (e.g. verify) returns the full result, not a count-only rebuild
|
|
1232
|
-
node.partition.matched = matched.size;
|
|
1233
|
-
|
|
1234
|
-
if (missingSlices.length > 0) {
|
|
1235
|
-
node.incomplete = true;
|
|
1236
|
-
// BA-15: carry a child's blocker up (see inheritedBlocker).
|
|
1237
|
-
return incompleteWithBlocker(node, result, { missingSlices });
|
|
1238
|
-
}
|
|
1239
|
-
const wantVerify = critical || typeof opts.contract === 'string' || typeof opts.evaluate === 'function';
|
|
1240
|
-
if (wantVerify) {
|
|
1241
|
-
// `return await` (not a bare `return`) is load-bearing here — see verifyOrBlock's JSDoc.
|
|
1242
|
-
return await verifyOrBlock(task, result, ctx, opts, node);
|
|
1243
|
-
}
|
|
1244
|
-
return { result, verdict: null, receipts: node };
|
|
1245
|
-
} catch (err) {
|
|
1246
|
-
if (err instanceof HaltError) {
|
|
1247
|
-
node.halted = true;
|
|
1248
|
-
node.incomplete = true;
|
|
1249
|
-
// Prefer the finished result (a halt from the verify slot lands here with it already computed); else
|
|
1250
|
-
// rebuild a best-effort count from whatever slices did return (BA-5, never a bare null).
|
|
1251
|
-
const best = partitionResult
|
|
1252
|
-
|| (childResults.length ? { count: new Set(childResults.flatMap((v) => (v && Array.isArray(v.matchedIds) ? v.matchedIds : []))).size } : null);
|
|
1253
|
-
// BA-15: a halt must not swallow a child's broken-sensor label (see incompleteWithBlocker).
|
|
1254
|
-
return incompleteWithBlocker(node, best);
|
|
1255
|
-
}
|
|
1256
|
-
throw err;
|
|
1257
|
-
}
|
|
1258
|
-
}
|
|
1259
|
-
|
|
1260
|
-
/**
|
|
1261
|
-
* Family B (NB-2) — the forced-fan-out path. Deterministic count → `Planner` (the NB-2 `count` seam forces
|
|
1262
|
-
* exactly N independent parallel steps) → `runPlan` (wave parallelism, concurrency cap) → NB-3 reduce →
|
|
1263
|
-
* verify. Each step runs as a fresh-window `recurse()` child (so copy-on-return / honest-incomplete / the
|
|
1264
|
-
* capability-scrub all come for free, and a child MAY itself decompose under Family A); forced fan-out is NOT
|
|
1265
|
-
* re-applied to children (their `count`/`mode` are stripped). Reduce default is `'concat'` (lossless) since
|
|
1266
|
-
* there is no parent closing turn to combine the slices the way Family A's does. RC-9 holds: any dead/halted/
|
|
1267
|
-
* incomplete slice → `{incomplete, missingSlices}`, never a survivor-sum. A governance HaltError (planner,
|
|
1268
|
-
* a child, the reduce, or verify) is a clean `incomplete` exit, never a thrown run.
|
|
1269
|
-
* @param {string} task
|
|
1270
|
-
* @param {RecurseCtx} ctx
|
|
1271
|
-
* @param {RecurseOptions} opts
|
|
1272
|
-
* @param {{provider: Provider, depth: number, maxDepth: number, assessment: {level: string, score: number}, critical: boolean, node: RecurseNode}} state
|
|
1273
|
-
* @returns {Promise<RecurseResult>}
|
|
1274
|
-
*/
|
|
1275
|
-
async function recurseFanout(task, ctx, opts, state) {
|
|
1276
|
-
const { provider, depth, assessment, critical, node } = state; // maxDepth rides in opts → children
|
|
1277
|
-
node.model = provider.model || null; // the orchestration is code; per-worker tokens live in node.spawned[]
|
|
1278
|
-
|
|
1279
|
-
// Count: an explicit positive-integer `opts.count` wins; otherwise the calibrated tier→count map. Floor at 1
|
|
1280
|
-
// (a 0/NaN/negative `count` is meaningless for "guaranteed parallelism" — fall back to the tier default).
|
|
1281
|
-
const explicit = Number.isInteger(opts.count) && /** @type {number} */ (opts.count) > 0 ? opts.count : null;
|
|
1282
|
-
const count = explicit != null ? /** @type {number} */ (explicit) : (TIER_COUNT[assessment.level] || 1);
|
|
1283
|
-
const concurrency = Number.isInteger(opts.concurrency) && /** @type {number} */ (opts.concurrency) > 0
|
|
1284
|
-
? opts.concurrency : DEFAULT_FANOUT_CONCURRENCY;
|
|
1285
|
-
|
|
1286
|
-
const childResults = [];
|
|
1287
|
-
const contract = typeof opts.contract === 'string' ? opts.contract : null;
|
|
1288
|
-
// BA-5: declared OUTSIDE the try so a halt from the verify slot (which lands in the catch below, with the
|
|
1289
|
-
// reduce already computed and PAID FOR) returns the finished reduce instead of a lossy re-join of the raw
|
|
1290
|
-
// child strings — a different TYPE from the documented reduce output, and an 'merge' strategy's LLM call
|
|
1291
|
-
// thrown away. Mirrors `scanResult`/`partitionResult` on the sibling paths.
|
|
1292
|
-
let result;
|
|
1293
|
-
|
|
1294
|
-
try {
|
|
1295
|
-
// 1) Decompose into exactly `count` independent parallel steps (the NB-2 Planner seam). A non-Halt planner
|
|
1296
|
-
// failure (e.g. unparseable plan) is an honest incomplete — we cannot fan out, so we do not pretend to.
|
|
1297
|
-
// The plan call forwards its usage to the gate (`onLlmResult`) so decomposition spend is metered, not
|
|
1298
|
-
// invisible — and it is the CHEAP call that RESOLVES the unknown fan-out cost into a known width.
|
|
1299
|
-
const planner = new Planner({ provider, onLlmResult: /** @type {any} */ (ctx.onLlmResult) || undefined });
|
|
1300
|
-
let steps;
|
|
1301
|
-
try {
|
|
1302
|
-
// BA-9: forward the working-context as the Planner's `info` so the slices it writes are path-aware (a
|
|
1303
|
-
// child still also receives `opts.context` directly via `forChild` — this just improves the split).
|
|
1304
|
-
const planContext = typeof opts.context === 'string' && opts.context.trim() ? { count, info: opts.context } : { count };
|
|
1305
|
-
steps = await planner.plan(task, planContext);
|
|
1306
|
-
} catch (err) {
|
|
1307
|
-
if (err instanceof HaltError) throw err;
|
|
1308
|
-
node.incomplete = true;
|
|
1309
|
-
return { incomplete: true, best: null, missingSlices: [task], receipts: node };
|
|
1310
|
-
}
|
|
1311
|
-
|
|
1312
|
-
// 1b) Pre-wave gate checkpoint (the cost-commitment point). Decomposition just turned an UNKNOWN cost into
|
|
1313
|
-
// a KNOWN width — so before committing the worker wave, give the gate a chance to act on it. A governance
|
|
1314
|
-
// HaltError (e.g. bareguard's budget cap, or a near-threshold HITL pause surfaced as a halt) propagates
|
|
1315
|
-
// to the outer catch → clean incomplete, BEFORE any worker spends — this is what bounds the concurrent
|
|
1316
|
-
// burst (N workers can't each overshoot between post-round meters if the wave never launches). A plain
|
|
1317
|
-
// deny is advisory only: it must NOT break an allowlist policy that doesn't know this internal
|
|
1318
|
-
// descriptor — the load-bearing budget signal is the HaltError, on bareguard's existing contract.
|
|
1319
|
-
if (typeof ctx.policy === 'function') {
|
|
1320
|
-
try {
|
|
1321
|
-
await ctx.policy('recurse_fanout', { count: steps.length, depth }, auditSafeCtx(ctx, { depth }));
|
|
1322
|
-
} catch (err) {
|
|
1323
|
-
if (err instanceof HaltError) throw err;
|
|
1324
|
-
// non-halt policy error/deny → advisory; proceed (per-worker policy still gates each child below)
|
|
1325
|
-
}
|
|
1326
|
-
}
|
|
1327
|
-
|
|
1328
|
-
// 2) Fan out: each step is a fresh-window recurse() child. Forced fan-out is NOT re-applied to children, and
|
|
1329
|
-
// the top-level contract/verifier is the TOP's job — `forChild` strips both (the slices run Family A, or
|
|
1330
|
-
// single-shot; `maxDepth` is preserved so a genuinely oversized slice may still self-decompose).
|
|
1331
|
-
const childOpts = forChild(opts);
|
|
1332
|
-
const results = await runPlan(
|
|
1333
|
-
steps,
|
|
1334
|
-
(step) => recurse(step.action, { ...ctx, depth: depth + 1 }, childOpts),
|
|
1335
|
-
{ concurrency },
|
|
1336
|
-
);
|
|
1337
|
-
|
|
1338
|
-
// 3) Collect copy-on-return values + lineage, in plan order. A failed step (executeFn threw) or a child
|
|
1339
|
-
// that came back incomplete/halted is a MISSING slice — recorded, never survivor-summed (RC-9).
|
|
1340
|
-
/** @type {string[]} */
|
|
1341
|
-
const missingSlices = [];
|
|
1342
|
-
for (let i = 0; i < results.length; i++) {
|
|
1343
|
-
const r = results[i];
|
|
1344
|
-
const slice = steps[i] ? steps[i].action : `slice ${i}`;
|
|
1345
|
-
if (r.status !== 'done' || !r.result) {
|
|
1346
|
-
node.spawned.push(makeDeadNode(slice, depth + 1));
|
|
1347
|
-
childResults.push('');
|
|
1348
|
-
missingSlices.push(slice);
|
|
1349
|
-
continue;
|
|
1350
|
-
}
|
|
1351
|
-
const child = /** @type {RecurseResult} */ (r.result);
|
|
1352
|
-
node.spawned.push(child.receipts);
|
|
1353
|
-
const value = child.incomplete
|
|
1354
|
-
? (child.best == null ? '' : child.best)
|
|
1355
|
-
: (child.result == null ? '' : child.result);
|
|
1356
|
-
childResults.push(value);
|
|
1357
|
-
if (child.incomplete) missingSlices.push(slice);
|
|
1358
|
-
}
|
|
1359
|
-
|
|
1360
|
-
// 4) NB-3 reduce over the slice results. Unlike Family A there is no parent closing turn, so we ALWAYS
|
|
1361
|
-
// reduce: a `synthesize` FUNCTION is the deterministic code-reduce (§9.1); a string runs the built-in
|
|
1362
|
-
// reducer; unset defaults to lossless `'concat'`. (`childResults` always has `count` entries.)
|
|
1363
|
-
if (typeof opts.synthesize === 'function') {
|
|
1364
|
-
result = await opts.synthesize({ task, text: null, results: childResults, children: node.spawned, ctx });
|
|
1365
|
-
} else {
|
|
1366
|
-
const strategy = typeof opts.synthesize === 'string' ? opts.synthesize : 'concat';
|
|
1367
|
-
result = await synthesize(task, childResults, {
|
|
1368
|
-
strategy: /** @type {any} */ (strategy),
|
|
1369
|
-
provider,
|
|
1370
|
-
contract,
|
|
1371
|
-
onLlmResult: ctx.onLlmResult,
|
|
1372
|
-
policy: ctx.policy,
|
|
1373
|
-
text: null,
|
|
1374
|
-
children: node.spawned,
|
|
1375
|
-
ctx,
|
|
1376
|
-
});
|
|
1377
|
-
}
|
|
1378
|
-
|
|
1379
|
-
// 5) Honest completeness (RC-9): any missing slice → incomplete, with the partial reduce as `best`.
|
|
1380
|
-
if (missingSlices.length > 0) {
|
|
1381
|
-
node.incomplete = true;
|
|
1382
|
-
// BA-15: carry a child's blocker up (see inheritedBlocker).
|
|
1383
|
-
return incompleteWithBlocker(node, result, { missingSlices });
|
|
1384
|
-
}
|
|
1385
|
-
|
|
1386
|
-
// 6) Verify (RC-7): forced for critical, or when a contract/override is supplied.
|
|
1387
|
-
const wantVerify = critical || contract != null || typeof opts.evaluate === 'function';
|
|
1388
|
-
if (wantVerify) {
|
|
1389
|
-
// `return await` (not a bare `return`) is load-bearing here — see verifyOrBlock's JSDoc.
|
|
1390
|
-
return await verifyOrBlock(task, result, ctx, opts, node);
|
|
1391
|
-
}
|
|
1392
|
-
return { result, verdict: null, receipts: node };
|
|
1393
|
-
} catch (err) {
|
|
1394
|
-
if (err instanceof HaltError) {
|
|
1395
|
-
node.halted = true;
|
|
1396
|
-
node.incomplete = true;
|
|
1397
|
-
// BA-5: prefer the FINISHED reduce when the halt landed after it (the verify slot); only fall back to a
|
|
1398
|
-
// lossless join of the raw slices when the halt tripped before/during the reduce itself. Never a bare null.
|
|
1399
|
-
const rejoined = childResults.length ? childResults.filter(v => v !== '').join('\n\n') : null;
|
|
1400
|
-
const best = result !== undefined ? result : (rejoined || null);
|
|
1401
|
-
// BA-15: a halt must not swallow a child's broken-sensor label (see incompleteWithBlocker).
|
|
1402
|
-
return incompleteWithBlocker(node, best);
|
|
1403
|
-
}
|
|
1404
|
-
throw err;
|
|
1405
|
-
}
|
|
1406
|
-
}
|
|
1407
|
-
|
|
1408
|
-
/**
|
|
1409
|
-
* A receipts node for a slice that never produced a result (the worker threw / runPlan marked it failed) — so
|
|
1410
|
-
* the audit tree still shows the lineage and the dead branch, rather than a silent gap.
|
|
1411
|
-
* @param {string} task
|
|
1412
|
-
* @param {number} depth
|
|
1413
|
-
* @returns {RecurseNode}
|
|
1414
|
-
*/
|
|
1415
|
-
function makeDeadNode(task, depth) {
|
|
1416
|
-
const a = assessComplexity(task);
|
|
1417
|
-
return {
|
|
1418
|
-
task, depth,
|
|
1419
|
-
complexity: { level: a.level, score: a.score },
|
|
1420
|
-
critical: isCritical(task),
|
|
1421
|
-
spawned: [], verdict: null, incomplete: true, halted: false, tokens: null, model: null,
|
|
1422
|
-
};
|
|
1423
|
-
}
|
|
1424
|
-
|
|
1425
|
-
/**
|
|
1426
|
-
* NB-4 — the `spawn_child` A-tool. The in-process self-call (§4.5 candidate (a), POC-resolved as default):
|
|
1427
|
-
* `execute` runs a full `recurse(subtask, {...ctx, depth: depth+1})`, so a delegated sub-task gets its own
|
|
1428
|
-
* fresh Loop / fresh window and may itself decompose, bounded by the same `maxDepth` + bareguard. Copy-on-
|
|
1429
|
-
* return (RC-2): only the child's declared RESULT string crosses back into the parent transcript — never the
|
|
1430
|
-
* child's scratch/transcript (the child receipts node is filed under `node.spawned` for audit, separate from
|
|
1431
|
-
* the transcript). A child `HaltError` is intentionally NOT caught here: it throws out of `execute`, the
|
|
1432
|
-
* Loop re-throws it (loop.js), and the parent's run halts cleanly — propagating the guard trip up the tree.
|
|
1433
|
-
* @param {RecurseCtx} ctx
|
|
1434
|
-
* @param {RecurseOptions} opts
|
|
1435
|
-
* @param {number} depth - The PARENT's depth; the child runs at `depth + 1`.
|
|
1436
|
-
* @param {number} maxDepth
|
|
1437
|
-
* @param {RecurseNode} node - The parent's receipts node; children append to `node.spawned`.
|
|
1438
|
-
* @param {any[]} childResults - Sink for each child's declared RESULT value (NB-3 reduce input).
|
|
1439
|
-
* @returns {ToolDef}
|
|
1440
|
-
*/
|
|
1441
|
-
function buildSpawnTool(ctx, opts, depth, maxDepth, node, childResults) {
|
|
1442
|
-
return {
|
|
1443
|
-
name: 'spawn_child',
|
|
1444
|
-
description:
|
|
1445
|
-
'Delegate a sub-task to a fresh worker with its own clean context window. Use ONLY when a sub-task is ' +
|
|
1446
|
-
'too large or too independent to handle directly in this pass. The worker returns ONLY its result — ' +
|
|
1447
|
-
'not its working notes. Do the small/glue parts yourself and combine the results into your final answer.',
|
|
1448
|
-
parameters: {
|
|
1449
|
-
type: 'object',
|
|
1450
|
-
properties: {
|
|
1451
|
-
subtask: {
|
|
1452
|
-
type: 'string',
|
|
1453
|
-
description: 'A self-contained sub-task, with all the context the fresh worker needs to do it (it cannot see this conversation).',
|
|
1454
|
-
},
|
|
1455
|
-
},
|
|
1456
|
-
required: ['subtask'],
|
|
1457
|
-
},
|
|
1458
|
-
/** @param {{subtask?: string}} args */
|
|
1459
|
-
execute: async (args) => {
|
|
1460
|
-
const subtask = typeof args?.subtask === 'string' ? args.subtask : '';
|
|
1461
|
-
if (!subtask) return '[error] spawn_child requires a non-empty subtask string';
|
|
1462
|
-
// A delegated child grades only ITS slice; the parent's contract/verifier is the top's job (see forChild).
|
|
1463
|
-
const child = await recurse(subtask, { ...ctx, depth: depth + 1 }, forChild(opts));
|
|
1464
|
-
node.spawned.push(child.receipts); // audit lineage (RC-10) — NOT the parent transcript
|
|
1465
|
-
// Only the declared result crosses the boundary (RC-2). An incomplete child is reported honestly, not
|
|
1466
|
-
// silently dropped or faked. The same declared value is collected for the NB-3 reducer.
|
|
1467
|
-
const value = child.incomplete ? (child.best == null ? '' : child.best) : (child.result == null ? '' : child.result);
|
|
1468
|
-
childResults.push(value);
|
|
1469
|
-
// BA-15: a child blocked by a BROKEN ARBITER must not read to the parent model as a generic failure.
|
|
1470
|
-
// Collapsed into a bare `[incomplete]`, the parent cannot tell "the model failed" from "the judge is
|
|
1471
|
-
// broken", so it re-spawns the identical subtask against the identical broken sensor — re-running a
|
|
1472
|
-
// full leaf attempt each time, up to the Loop's round limit. That is BA-15's own spend-burn ("retrying
|
|
1473
|
-
// against a broken arbiter carries zero feedback") reintroduced one level up, so the tool result says
|
|
1474
|
-
// so explicitly and tells the model not to retry.
|
|
1475
|
-
if (child.incomplete && child.blocker === 'broken-sensor') {
|
|
1476
|
-
const where = child.blockerTask ? ` (in sub-task: ${child.blockerTask})` : '';
|
|
1477
|
-
return `[blocked: broken-sensor] The CHECK that judges this subtask is itself broken${where} — ${child.blockerDetail || 'no detail available'}. Retrying will hit the same broken check: do NOT re-delegate this subtask; report it as blocked. Partial output: ${String(value)}`.trim();
|
|
1478
|
-
}
|
|
1479
|
-
if (child.incomplete) return `[incomplete] ${String(value)}`.trim();
|
|
1480
|
-
return String(value);
|
|
1481
|
-
},
|
|
1482
|
-
};
|
|
1483
|
-
}
|
|
1484
|
-
|
|
1485
|
-
/**
|
|
1486
|
-
* The verify slot (§7.1) — the Evaluator fills it by default. `opts.evaluate` overrides. The default path
|
|
1487
|
-
* runs an isolated adversarial rubric grader (separate context window): when a `contract` is present it
|
|
1488
|
-
* grades against THAT (A3); otherwise it grades full-and-correct against the goal — which is exactly the
|
|
1489
|
-
* `critical → force verify` rail (a critical task with no contract still gets an independent grader).
|
|
1490
|
-
* @param {string} task
|
|
1491
|
-
* @param {any} result
|
|
1492
|
-
* @param {RecurseCtx} ctx
|
|
1493
|
-
* @param {RecurseOptions} opts
|
|
1494
|
-
* @returns {Promise<Verdict>}
|
|
1495
|
-
*/
|
|
1496
|
-
function verify(task, result, ctx, opts) {
|
|
1497
|
-
const contract = typeof opts.contract === 'string' ? opts.contract : null;
|
|
1498
|
-
// BA-9: the verifier sees the working-context too — neutral facts (not a stance, so no anti-sycophancy risk),
|
|
1499
|
-
// and an agentic critic needs the path to exercise the artifact. A caller `evaluate` gets the RAW task (it owns
|
|
1500
|
-
// its own context); only the default isolated grader is contextualized.
|
|
1501
|
-
if (typeof opts.evaluate === 'function') {
|
|
1502
|
-
// BA-15 (verifier seam): the CALLER-supplied verifier is wrapped exactly like the refineLeaf sensor — a
|
|
1503
|
-
// non-Halt throw or a malformed return is a faulty ARBITER, tagged so the call sites label it (pre-fix a
|
|
1504
|
-
// throw crashed the whole run on the plain-worker path / laundered to a bare {incomplete} under refineLeaf,
|
|
1505
|
-
// and a garbage verdict rode a CONVERGED-shaped {result, verdict} out). The default Evaluator path below is
|
|
1506
|
-
// NOT wrapped: it constructs well-formed Verdicts by design, and its failures are provider-class faults.
|
|
1507
|
-
// Capture the narrowed reference in a const: `typeof opts.evaluate === 'function'` does NOT survive into the
|
|
1508
|
-
// nested async closure (TS re-widens `opts.evaluate` to possibly-undefined there → TS2722/TS18048).
|
|
1509
|
-
// BOUND to `opts`, because a bare `const evaluate = opts.evaluate` DETACHES the method: the call used to be
|
|
1510
|
-
// `opts.evaluate(...)` (receiver `opts`), and a caller passing a class method (`evaluate: grader.check`)
|
|
1511
|
-
// would suddenly get `this === undefined` and throw on its first `this.x` read — a working (if degraded)
|
|
1512
|
-
// integration flipped to a hard `broken-verifier` by an unrelated typecheck fix.
|
|
1513
|
-
const evaluate = opts.evaluate.bind(opts);
|
|
1514
|
-
return runArbiter('broken-verifier', () => evaluate(result, { contract, task }));
|
|
1515
|
-
}
|
|
1516
|
-
const provider = ctx.provider || opts.provider;
|
|
1517
|
-
const evaluator = new Evaluator({ provider });
|
|
1518
|
-
const rubric = contract
|
|
1519
|
-
? 'Judge whether the result satisfies the definition of done. Be strict and adversarial; cite the specific gap on any shortfall.'
|
|
1520
|
-
: 'Judge whether the result fully and correctly answers the goal. Be strict and adversarial; cite the specific gap on any shortfall.';
|
|
1521
|
-
return evaluator.evaluate(
|
|
1522
|
-
withContext(task, opts.context),
|
|
1523
|
-
result,
|
|
1524
|
-
{ rubric, contract: contract || undefined },
|
|
1525
|
-
{ onLlmResult: /** @type {any} */ (ctx.onLlmResult), policy: ctx.policy },
|
|
1526
|
-
);
|
|
1527
|
-
}
|
|
1528
|
-
|
|
1529
|
-
/**
|
|
1530
|
-
* BA-15 (verifier seam) — run the verify slot, converting a `BrokenArbiterError` into a LABELED
|
|
1531
|
-
* `{ incomplete, blocker:'broken-verifier' }` return with `best` preserving the result the arbiter failed to
|
|
1532
|
-
* judge (BA-5: the work exists — best-effort, not a graded pass). One helper so all five dispatch paths (worker /
|
|
1533
|
-
* refineLeaf / scan / partition / fanout) get identical semantics. Anything else (HaltError, a default-
|
|
1534
|
-
* Evaluator provider fault) rethrows to the caller's own catch, exactly as before.
|
|
1535
|
-
*
|
|
1536
|
-
* MUST be called as `return await verifyOrBlock(...)` from inside each caller's `try` — a bare
|
|
1537
|
-
* `return verifyOrBlock(...)` returns the promise and exits the `try` before it settles, so a verifier
|
|
1538
|
-
* `HaltError` would escape the caller's own catch instead of landing as a clean `{ incomplete, halted }`
|
|
1539
|
-
* (proven by `poc/ba15-broken-sensor.mjs` [E4]).
|
|
1540
|
-
* @param {string} task
|
|
1541
|
-
* @param {any} result
|
|
1542
|
-
* @param {RecurseCtx} ctx
|
|
1543
|
-
* @param {RecurseOptions} opts
|
|
1544
|
-
* @param {RecurseNode} node
|
|
1545
|
-
* @returns {Promise<RecurseResult>}
|
|
1546
|
-
*/
|
|
1547
|
-
async function verifyOrBlock(task, result, ctx, opts, node) {
|
|
1548
|
-
try {
|
|
1549
|
-
const verdict = await verify(task, result, ctx, opts);
|
|
1550
|
-
node.verdict = verdict;
|
|
1551
|
-
return { result, verdict, receipts: node };
|
|
1552
|
-
} catch (err) {
|
|
1553
|
-
// Only a typed BrokenArbiterError is a caller-verifier fault; everything else (HaltError, a default-
|
|
1554
|
-
// Evaluator provider fault) rethrows to the caller's own catch. Classified by type, never by message text.
|
|
1555
|
-
if (!(err instanceof BrokenArbiterError)) throw err;
|
|
1556
|
-
node.incomplete = true;
|
|
1557
|
-
node.blocker = 'broken-verifier';
|
|
1558
|
-
node.blockerDetail = err.detail;
|
|
1559
|
-
// `blockerDetail` rides the RESULT too (see the sensor-side sibling) — the actionable half of the label.
|
|
1560
|
-
return { incomplete: true, best: result, blocker: 'broken-verifier', blockerDetail: err.detail, receipts: node };
|
|
1561
|
-
}
|
|
1562
|
-
}
|
|
201
|
+
env.setLoop(loop);
|
|
202
|
+
|
|
203
|
+
let value; let blocker;
|
|
204
|
+
if (!err && !inputErr) {
|
|
205
|
+
// Fresh message array = a true fresh window; the input is NOT in it. auditSafeCtx: the gate records ctx verbatim as `_ctx` (F16/BA-1).
|
|
206
|
+
const out = await loop.run([{ role: 'user', content: withContext(task, opts.context) }], [...env.tools, ...(Array.isArray(opts.tools) ? opts.tools : [])], { ctx: auditSafeCtx(ctx, { depth }) });
|
|
207
|
+
node.tokens = out.metrics ? out.metrics.tokens : null;
|
|
208
|
+
node.model = out.model || provider.model || null;
|
|
209
|
+
if (!hasWork(node.best) && hasWork(out.text)) node.best = out.text; // BA-5
|
|
210
|
+
const e = typeof out.error === 'string' ? out.error : null;
|
|
211
|
+
if (e && e.startsWith('halt:')) err = new HaltError(`[${e}]`, { rule: e.slice(5) });
|
|
212
|
+
else if (env.state.wrong) blocker = { blocker: 'wrong-final', detail: env.state.wrong };
|
|
213
|
+
else if (env.state.final) value = env.state.final.value;
|
|
214
|
+
else if (e && e.startsWith('denied:')) blocker = { blocker: 'governance-deny' }; // BA-11: a deny spin is a governance block, not a model failure
|
|
215
|
+
else if (e) blocker = { blocker: 'error', error: e };
|
|
216
|
+
else if (kind === 'text' && hasWork(out.text)) value = out.text;
|
|
217
|
+
} else if (inputErr) blocker = { blocker: 'input', detail: `input source failed (${inputErr && inputErr.name ? inputErr.name : typeof inputErr})` };
|
|
218
|
+
|
|
219
|
+
// The verifier is a SEPARATE isolated context but its calls count against the SAME brake (cap funds verify).
|
|
220
|
+
const res = await finish(node, value, err, { ctx: { ...ctx, provider: countingProvider(provider, counter) }, opts, counter, blocker });
|
|
221
|
+
if (counter.isRoot) node.calls = counter.metrics().calls;
|
|
222
|
+
return res;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const isPlain = (/** @type {any} */ x) => !!x && typeof x === 'object' && typeof x.id === 'string' && typeof x.text === 'string';
|
|
1563
226
|
|
|
1564
227
|
module.exports = { recurse };
|