bare-agent 0.58.0 → 0.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,233 @@
1
+ 'use strict';
2
+
3
+ // recurse() v2 — the ENVIRONMENT (docs/product/rlm-prd.md §0.1, decision 4: fixed tools, no model-written code).
4
+ // The input lives in a var map the model never sees whole; every tool returns a TRUNCATED preview and stores the
5
+ // full value under a new var name. Counting/derivation is CODE. Ported from the validated POC
6
+ // (poc/rlm-v2-env.mjs): typed final, memo, classify (shipped scan wording, window 8, 2 deterministic passes).
7
+
8
+ /** @typedef {import('../types').ToolDef} ToolDef */
9
+
10
+ const { Loop } = require('./loop');
11
+ const { HaltError } = require('./errors');
12
+ const { countingProvider } = require('./recurse-brakes');
13
+ const { auditSafeCtx, withContext } = require('./refine-worker');
14
+ const { SUB_SYSTEM, classifySystem, SCAN_WINDOW, SCAN_PASSES } = require('./recurse-prompts');
15
+
16
+ const PREVIEW_CAP = 1500;
17
+ const DEFAULT_CONCURRENCY = 8;
18
+ const KINDS = ['count', 'ids', 'text', 'composite'];
19
+
20
+ const render = (/** @type {any} */ x) => (x && typeof x === 'object' && 'id' in x && 'text' in x ? `${x.id} => ${x.text}` : typeof x === 'string' ? x : JSON.stringify(x));
21
+ const asText = (/** @type {any} */ v) => (Array.isArray(v) ? v.map(render).join('\n') : render(v));
22
+ const flatItems = (/** @type {any} */ v) => (Array.isArray(v) ? v.flatMap((e) => (Array.isArray(e) ? e : [e])) : []);
23
+ const typeOf = (/** @type {any} */ v) => (Array.isArray(v) ? `list[${v.length}]` : v && typeof v === 'object' ? 'object' : typeof v);
24
+ const isItem = (/** @type {any} */ r) => !!r && typeof r.id === 'string' && r.text !== undefined;
25
+ const hasWork = (/** @type {any} */ v) => (typeof v === 'string' ? v.trim().length > 0 : v != null);
26
+ const preview = (/** @type {any} */ v, /** @type {string} */ name) => {
27
+ const s = asText(v);
28
+ return s.length > PREVIEW_CAP ? `${s.slice(0, PREVIEW_CAP)}\n…[truncated; ${s.length} chars total, full value stored as var ${name}]` : s;
29
+ };
30
+
31
+ /** Run `jobs` with at most `n` in flight; result order = job order. */
32
+ async function pool(/** @type {number} */ n, /** @type {Array<() => Promise<any>>} */ jobs) {
33
+ const out = new Array(jobs.length); let next = 0;
34
+ await Promise.all(Array.from({ length: Math.min(n, jobs.length) }, async () => { for (;;) { const i = next++; if (i >= jobs.length) return; out[i] = await jobs[i](); } }));
35
+ return out;
36
+ }
37
+
38
+ /** Literal, case-insensitive, ALL-terms (AND) match over item text; no regex. */
39
+ const findIds = (/** @type {any[]} */ items, /** @type {any[]} */ terms) => {
40
+ const t = terms.map((x) => String(x).toLowerCase()).filter(Boolean);
41
+ return t.length ? items.filter((r) => isItem(r) && t.every((x) => String(r.text).toLowerCase().includes(x))).map((r) => r.id) : [];
42
+ };
43
+
44
+ /**
45
+ * Normalize the caller's `input`: strings pass through; `Slice[]` keeps well-formed `{id,text}` with a unique id that
46
+ * contains no whitespace/comma (the judge echoes ids back — such an id cannot be matched and would silently undercount).
47
+ * Everything else is DROPPED and COUNTED (`dropped`), never silently miscounted.
48
+ * @param {any} raw
49
+ * @returns {{input: string|Array<{id: string, text: string}>|null, dropped: number}}
50
+ */
51
+ function normalizeInput(raw) {
52
+ if (raw == null) return { input: null, dropped: 0 };
53
+ if (typeof raw === 'string') return { input: raw, dropped: 0 };
54
+ if (!Array.isArray(raw)) throw new TypeError('input must be a string, a Slice[] or an async () => Slice[]');
55
+ const seen = new Set(); const out = [];
56
+ for (const r of raw) {
57
+ if (r && typeof r.id === 'string' && typeof r.text === 'string' && r.id && !/[\s,]/.test(r.id) && !seen.has(r.id)) { seen.add(r.id); out.push({ id: r.id, text: r.text }); }
58
+ }
59
+ return { input: out, dropped: raw.length - out.length };
60
+ }
61
+
62
+ /** Metadata line the root prompt shows INSTEAD of the input (type, size, 200-char prefix). */
63
+ function describeInput(/** @type {string|any[]|null} */ input) {
64
+ if (input == null) return null;
65
+ const s = asText(input);
66
+ const prefix = JSON.stringify(s.slice(0, 200));
67
+ return Array.isArray(input)
68
+ ? `input: kind=items, type=list of {id,text} items, items=${input.length}, total_chars=${s.length}, prefix=${prefix}\nItems are numbered 0..N-1 in order; each has its own id.`
69
+ : `input: kind=text, type=string, chars=${s.length}, prefix=${prefix}`;
70
+ }
71
+
72
+ /**
73
+ * Build the env for ONE node. `ctx`/`opts` are the caller's; `child(prompt, piece)` runs a full recurse one level
74
+ * down (shared counter) and is only called while `counter.canSpawn(depth + 1)`.
75
+ * @param {{input: any, kind: string, node: any, counter: import('./recurse-brakes').Counter, depth: number, ctx: any, opts: any, provider: any, child: (prompt: string, piece: any) => Promise<any>}} r
76
+ * @returns {{tools: ToolDef[], state: {final: any, wrong: string|null}, setLoop: (l: any) => void}}
77
+ */
78
+ function makeEnv({ input, kind, node, counter, depth, ctx, opts, provider, child }) {
79
+ const vars = new Map(); const kinds = new Map(); const memo = new Map(); const missingOf = new Map();
80
+ const conc = Number.isInteger(opts.concurrency) && opts.concurrency > 0 ? opts.concurrency : DEFAULT_CONCURRENCY;
81
+ const known = new Set(Array.isArray(input) ? input.map((r) => r.id) : []);
82
+ const canSub = counter.canSpawn(depth);
83
+ const state = { final: /** @type {any} */ (null), wrong: /** @type {string|null} */ (null) };
84
+ let n = 0; let last = ''; let loop = /** @type {any} */ (null); let nudged = false;
85
+ if (input != null) { vars.set('input', input); kinds.set('input', Array.isArray(input) ? 'items' : 'text'); }
86
+
87
+ const store = (/** @type {any} */ value, /** @type {string} */ k, /** @type {{best?: boolean, missing?: string[]}} */ x = {}) => {
88
+ const name = `v${++n}`; vars.set(name, value); kinds.set(name, k); last = name; node.vars = n;
89
+ if (x.missing && x.missing.length) missingOf.set(name, x.missing);
90
+ if ((x.best ?? (k === 'ids' || k === 'answers')) && hasWork(value)) node.best = value; // BA-5: last real work
91
+ return name;
92
+ };
93
+ const get = (/** @type {string} */ name) => { if (!vars.has(name)) throw new Error(`unknown var "${name}" (vars: ${[...vars.keys()].join(', ')})`); return vars.get(name); };
94
+ const reply = (/** @type {any} */ value, /** @type {string} */ k, /** @type {{best?: boolean, missing?: string[]}} */ x = {}) => { const name = store(value, k, x); return `var=${name} kind=${k} type=${typeOf(value)}${x.missing && x.missing.length ? ` MISSING ${JSON.stringify(x.missing)} (incomplete)` : ''}\n${preview(value, name)}`; };
95
+ // Memoize by tool + exact args (vars are write-once, so a var name pins its value); a repeat costs ZERO LLM calls.
96
+ // A result with missing slices is NOT memoized: re-running the same call must retry the dead window.
97
+ const memoized = async (/** @type {string} */ tool, /** @type {any} */ args, /** @type {() => Promise<string>} */ fn) => {
98
+ const key = `${tool}|${JSON.stringify(args)}`;
99
+ if (memo.has(key)) { const v = memo.get(key); node.memoHits++; return `already computed → var ${v} (memo hit, 0 LLM calls)\n${preview(vars.get(v), v)}`; }
100
+ const out = await fn(); if (!missingOf.has(last)) memo.set(key, last); return out;
101
+ };
102
+
103
+ /** One fresh-window leaf Loop; a gate/brake halt is re-thrown as a HaltError, a worker fault returns null (dead). */
104
+ const leaf = async (/** @type {string} */ system, /** @type {string} */ user) => {
105
+ const out = await new Loop({ provider: countingProvider(provider, counter), system, policy: ctx.policy || undefined, onLlmResult: ctx.onLlmResult || undefined, throwOnError: false })
106
+ .run([{ role: 'user', content: user }], [], { ctx: auditSafeCtx(ctx, { depth: depth + 1 }) });
107
+ if (typeof out.error === 'string' && out.error.startsWith('halt:')) throw new HaltError(`[${out.error}]`, { rule: out.error.slice(5) });
108
+ return out.error ? null : out.text || '';
109
+ };
110
+ /** One sub-call on a piece: a full recurse below the cap, a plain leaf Loop at it. Only the result string crosses back; null = dead. */
111
+ const sub = async (/** @type {string} */ prompt, /** @type {any} */ piece) => {
112
+ if (counter.canSpawn(depth + 1)) {
113
+ const c = await child(prompt, piece);
114
+ node.spawned.push(c.receipts);
115
+ if (c.incomplete) { // a child's brake/gate halt halts the whole run; anything else is a dead slot
116
+ if (c.blocker === 'brake') throw new HaltError(`[brake:${c.brake}]`, { rule: `brake:${c.brake}` });
117
+ if (c.blocker === 'halt') throw new HaltError(`[halt:${c.halt}]`, { rule: c.halt });
118
+ return null;
119
+ }
120
+ return typeof c.result === 'string' ? c.result : JSON.stringify(c.result);
121
+ }
122
+ return leaf(SUB_SYSTEM, `${withContext(prompt, opts.context)}\n\nPIECE:\n${asText(piece)}`);
123
+ };
124
+
125
+ // ── typed final: the model points at a var, CODE decides what the answer is ──
126
+ const idsVars = () => [...kinds].filter(([, k]) => k === 'ids').map(([v]) => `${v} (${vars.get(v).ids.length})`);
127
+ const expected = () => {
128
+ const have = idsVars().join(', ') || 'none yet — run classify first';
129
+ if (kind === 'count') return `answer is a count; vars of kind count: ${have}. Cite one with final("<var>"); code derives the number, never type it.`;
130
+ if (kind === 'ids') return `answer is a list of ids; vars of kind ids: ${have}. Cite one with final("<var>").`;
131
+ if (kind === 'composite') return `answer is {needle text, count}; call final_parts(needle="<exact text>", count="<var of kind count>"); vars of kind count: ${have}.`;
132
+ return 'answer is text; call final_text("<text>") or final("<var of kind text>").';
133
+ };
134
+ const reject = (/** @type {string} */ what) => {
135
+ if (!nudged) { nudged = true; node.nudges++; return `REJECTED (${what}): ${expected()}`; } // ONE nudge
136
+ state.wrong = what; loop.stop(); return 'rejected again — run ends';
137
+ };
138
+ const accept = (/** @type {any} */ value, /** @type {string[]} */ missing = []) => {
139
+ state.final = { value }; if (missing.length) node.missingSlices = missing; loop.stop(); return 'final recorded';
140
+ };
141
+ const idsPayload = (/** @type {string} */ v) => { const x = vars.get(v); return { count: x.ids.length, ids: [...x.ids] }; }; // count DERIVED from ids
142
+
143
+ const obj = (/** @type {any} */ properties, /** @type {string[]} */ required) => ({ type: 'object', properties, required });
144
+ const S = { type: 'string' }; const I = { type: 'integer' };
145
+ /** @type {ToolDef[]} */
146
+ const tools = [];
147
+ if (input != null) {
148
+ tools.push(
149
+ { name: 'info', description: 'Metadata of a var: type, item count, total chars, 200-char prefix.', parameters: obj({ var: S }, ['var']),
150
+ execute: ({ var: v }) => { const x = get(v); const s = asText(x); return reply(`kind=${kinds.get(v)} type=${typeOf(x)} items=${Array.isArray(x) ? x.length : 1} chars=${s.length} prefix=${JSON.stringify(s.slice(0, 200))}`, 'meta'); } },
151
+ { name: 'peek', description: 'Read items [start, start+len) of a list var (0-based), or a character range of a string var. Preview is truncated.', parameters: obj({ var: S, start: I, len: I }, ['var', 'start', 'len']),
152
+ execute: ({ var: v, start, len }) => { const x = get(v); return Array.isArray(x) ? reply(x.slice(start, start + len), 'items') : reply(String(x).slice(start, start + len), 'text'); } },
153
+ { name: 'find', description: 'Find items by CONTENT: literal, case-insensitive, ALL terms must appear (AND); no regex. Returns the matching items as a list var (ids + truncated preview). Use for locating a specific item by words it contains.', parameters: obj({ var: S, terms: { type: 'array', items: S } }, ['var', 'terms']),
154
+ execute: async ({ var: v, terms }) => {
155
+ if (!Array.isArray(terms) || !terms.length) throw new Error('find needs a non-empty terms array');
156
+ const x = get(v); const items = flatItems(x);
157
+ return memoized('find', { var: v, terms }, async () => {
158
+ const ids = typeof x === 'string' ? [] : findIds(items, terms); const m = new Set(ids);
159
+ const hit = typeof x === 'string' ? x.split('\n').filter((l) => terms.every((t) => l.toLowerCase().includes(String(t).toLowerCase()))) : items.filter((r) => m.has(r.id));
160
+ const name = store(hit, typeof x === 'string' ? 'text' : 'items');
161
+ return `var=${name} kind=${typeof x === 'string' ? 'text' : 'items'} matches=${hit.length} ids=${JSON.stringify(ids.slice(0, 50))}\n${preview(hit, name)}`;
162
+ }); } },
163
+ { name: 'chunk', description: 'Split a list var into a list of chunks of `size` items (or a string var into chunks of `size` chars). Returns a list var.', parameters: obj({ var: S, size: I }, ['var', 'size']),
164
+ execute: ({ var: v, size }) => {
165
+ const x = get(v); if (!(size >= 1) || (!Array.isArray(x) && typeof x !== 'string')) throw new Error('chunk needs a list/string var and size>=1');
166
+ const out = []; for (let i = 0; i < x.length; i += size) out.push(x.slice(i, i + size)); return reply(out, 'chunks'); } },
167
+ );
168
+ if (canSub) {
169
+ tools.push(
170
+ { name: 'ask', description: 'Ask `prompt` as ONE independent sub-call about the piece in var (fresh window; only the answer string comes back). For a subjective question about one piece; for counting use classify.', parameters: obj({ prompt: S, var: S }, ['prompt', 'var']),
171
+ execute: async ({ prompt, var: v }) => {
172
+ const answer = await sub(prompt, get(v));
173
+ return answer === null ? reply('', 'text', { best: false, missing: [`ask(${v})`] }) : reply(answer, 'text', { best: true }); } },
174
+ { name: 'map', description: 'Run `prompt` as an independent sub-call over EACH element of a list var (e.g. the chunks). Returns a list var of the answers (one per element). For subjective per-piece questions; for counting use classify.', parameters: obj({ prompt: S, listVar: S }, ['prompt', 'listVar']),
175
+ execute: async ({ prompt, listVar }) => {
176
+ const x = get(listVar); if (!Array.isArray(x)) throw new Error('map needs a list var');
177
+ counter.checkWidth(x.length); // brake:maxWidth — refused past the cap, the model cannot raise it
178
+ return memoized('map', { prompt, listVar }, async () => {
179
+ const answers = await pool(conc, x.map((piece) => () => sub(prompt, piece)));
180
+ const missing = answers.map((a, i) => (a === null ? `map slot ${i}` : null)).filter((m) => m !== null);
181
+ return reply(answers, 'answers', { missing: /** @type {string[]} */ (missing) }); }); } },
182
+ { name: 'classify', description: 'COUNT/FIND all items matching a predicate over a list var (the input, or chunks). Scans EVERY item with an LLM judge and counts in CODE; returns a var of kind count/ids {count, ids}. Use for "how many"/"all" questions; never count yourself.', parameters: obj({ predicate: S, var: S }, ['predicate', 'var']),
183
+ execute: async ({ predicate, var: v }) => {
184
+ const list = flatItems(get(v)).filter(isItem); if (!list.length) throw new Error('classify needs a list var of items');
185
+ return memoized('classify', { predicate, var: v }, async () => {
186
+ const wins = [];
187
+ for (let p = 0; p < SCAN_PASSES; p++) { const off = p ? Math.floor(SCAN_WINDOW / 2) : 0; // deterministic rotation, no RNG
188
+ for (let i = -off; i < list.length; i += SCAN_WINDOW) { const w = list.slice(Math.max(0, i), i + SCAN_WINDOW); if (w.length) wins.push(w); } }
189
+ const ids = new Set(); const dead = /** @type {string[]} */ ([]);
190
+ try {
191
+ await pool(conc, wins.map((w, wi) => async () => {
192
+ const shown = new Set(w.map((r) => r.id));
193
+ const text = await leaf(classifySystem(predicate), `[run ${wi}] Find the items matching the predicate.\n\nITEMS:\n${w.map((r) => `${r.id} => ${r.text}`).join('\n')}\n\nReply with ONLY the comma-separated matching ids (or "none").`);
194
+ if (text === null) dead.push(`classify window ${wi}`); else for (const t of text.split(/[\s,]+/)) if (shown.has(t)) ids.add(t); // RC-2: only ids SHOWN this window
195
+ }));
196
+ } catch (e) { if (e instanceof HaltError) store({ count: ids.size, ids: [...ids], partial: true }, 'partial', { best: true }); throw e; } // keep the work judged so far (never citable)
197
+ return reply({ count: ids.size, ids: [...ids] }, 'ids', { missing: dead }); }); } }, // a dead window is a FLOOR, flagged — never a zero
198
+ );
199
+ }
200
+ tools.push(
201
+ { name: 'join', description: 'Join a list var of answers/texts into ONE text var (code, newline-separated).', parameters: obj({ listVar: S }, ['listVar']),
202
+ execute: ({ listVar }) => { const x = get(listVar); if (!Array.isArray(x)) throw new Error('join needs a list var'); return reply(x.map(asText).join('\n'), 'text', { best: true, missing: missingOf.get(listVar) }); } },
203
+ { name: 'count', description: 'Code count of a var: {count,ids} -> ids.length, list -> length. (Informational: a bare number cannot be the final answer.)', parameters: obj({ var: S }, ['var']),
204
+ execute: ({ var: v }) => { const x = get(v); return reply(x && x.ids ? x.ids.length : Array.isArray(x) ? x.length : 1, 'number'); } },
205
+ );
206
+ }
207
+ if (kind === 'composite') {
208
+ tools.push({ name: 'final_parts', description: 'Final answer for a needle+count question: needle = the exact text of the item; count = the NAME of a var of kind count (classify result). Code derives the number from that var. Ends the run.', parameters: obj({ needle: S, count: S }, ['needle', 'count']),
209
+ execute: ({ needle, count }) => {
210
+ if (typeof needle !== 'string' || !needle.trim()) return reject('needle text is empty');
211
+ if (!vars.has(count) || kinds.get(count) !== 'ids') return reject(`count var "${count}" is not a count/ids var`);
212
+ return accept({ needle, count: idsPayload(count) }, missingOf.get(count)); } });
213
+ } else {
214
+ tools.push(
215
+ { name: 'final', description: 'Final answer: cite a var of the matching kind (for a count question: the classify var — code derives the number). Ends the run.', parameters: obj({ var: S }, ['var']),
216
+ execute: ({ var: v }) => {
217
+ if (!vars.has(v)) return reject(`unknown var "${v}"`);
218
+ const k = kinds.get(v);
219
+ if ((kind === 'count' || kind === 'ids') && k === 'ids') return accept(idsPayload(v), missingOf.get(v));
220
+ if (kind === 'text' && k === 'text') return hasWork(String(vars.get(v))) || missingOf.get(v)?.length ? accept(String(vars.get(v)), missingOf.get(v)) : reject(`var ${v} is blank — a blank answer is not a final`); // same blank rule as final_text; a DEAD slot (missing) keeps its honest incomplete path
221
+ return reject(`var ${v} is kind ${k}`); } },
222
+ { name: 'final_text', description: 'Final answer as literal text (ONLY for a text question; refused for count/ids questions). Ends the run.', parameters: obj({ text: S }, ['text']),
223
+ execute: ({ text }) => (kind === 'text' && hasWork(text) ? accept(String(text)) : reject('final_text is not allowed for this answer kind')) },
224
+ );
225
+ }
226
+ for (const t of tools) { // per-tool call counts for the receipts (names only, never content)
227
+ const ex = t.execute;
228
+ t.execute = (/** @type {any} */ a) => { node.toolCalls[t.name] = (node.toolCalls[t.name] || 0) + 1; return ex(a); };
229
+ }
230
+ return { tools, state, setLoop: (l) => { loop = l; } };
231
+ }
232
+
233
+ module.exports = { makeEnv, normalizeInput, describeInput, KINDS, hasWork };
@@ -0,0 +1,46 @@
1
+ export type FinishRun = {
2
+ /**
3
+ * - per-run ctx (provider/onLlmResult/policy) handed to the verifier.
4
+ */
5
+ ctx?: any;
6
+ /**
7
+ * - recurse options (`evaluate`, `contract`, `context`) read by the verify slot.
8
+ */
9
+ opts?: any;
10
+ /**
11
+ * - root counter => `metrics`; `unbraked` flag source.
12
+ */
13
+ counter?: import("./recurse-brakes").Counter | undefined;
14
+ /**
15
+ * - a path-detected non-halt stop (`wrong-final`,
16
+ * `governance-deny`, `error`, ...): returned as an incomplete carrying these fields; `best` keeps the last work.
17
+ */
18
+ blocker?: {
19
+ [k: string]: any;
20
+ blocker: string;
21
+ } | undefined;
22
+ };
23
+ /**
24
+ * Finish a node. `node` is the receipts node (`{task, spawned, best?, missingSlices?, ...}`); `best` is the last
25
+ * non-empty work the caller saw (BA-5). `value` is the produced answer, `err` anything the path caught.
26
+ * A HaltError is mapped (never thrown): `brake:*` => `blocker:'brake'`, a gate halt => `blocker:'halt'`; any other
27
+ * `err` is re-thrown (not this tail's to swallow). Returns `{result, verdict, receipts}` on a satisfied verdict,
28
+ * else `{incomplete, best, blocker?, ..., receipts}`. Root returns (counter without a parent) carry `metrics`.
29
+ * @param {any} node
30
+ * @param {any} value
31
+ * @param {any} [err]
32
+ * @param {FinishRun} [run]
33
+ * @returns {Promise<any>}
34
+ */
35
+ export function finish(node: any, value: any, err?: any, run?: FinishRun): Promise<any>;
36
+ /**
37
+ * A descendant's label, surfaced at the ancestor as `blockerFrom` — NEVER as the ancestor's own `blocker`
38
+ * (which means THIS node broke). `broken-sensor` (caller's own code) outranks any other label.
39
+ * @param {any[]} spawned
40
+ * @returns {{blocker: string, blockerDetail?: string, blockerTask?: string}|null}
41
+ */
42
+ export function inheritedBlocker(spawned: any[]): {
43
+ blocker: string;
44
+ blockerDetail?: string;
45
+ blockerTask?: string;
46
+ } | null;
@@ -0,0 +1,123 @@
1
+ 'use strict';
2
+
3
+ // recurse() v2 — the ONE tail every path ends in (docs/product/rlm-prd.md §0.1). Replaces the five copies of the
4
+ // `wantVerify` check and six HaltError catches in recurse.js: verify → halt/brake mapping → `best` → blockers.
5
+
6
+ const { HaltError } = require('./errors');
7
+ const { isCritical } = require('./complexity');
8
+ const { verify, BrokenArbiterError } = require('./refine-worker');
9
+
10
+ /**
11
+ * @typedef {object} FinishRun
12
+ * @property {any} [ctx] - per-run ctx (provider/onLlmResult/policy) handed to the verifier.
13
+ * @property {any} [opts] - recurse options (`evaluate`, `contract`, `context`) read by the verify slot.
14
+ * @property {import('./recurse-brakes').Counter} [counter] - root counter => `metrics`; `unbraked` flag source.
15
+ * @property {{blocker: string, [k: string]: any}} [blocker] - a path-detected non-halt stop (`wrong-final`,
16
+ * `governance-deny`, `error`, ...): returned as an incomplete carrying these fields; `best` keeps the last work.
17
+ */
18
+
19
+ /** Non-empty work: a non-blank string, or any non-null non-string. */
20
+ const hasWork = (v) => (typeof v === 'string' ? v.trim().length > 0 : v != null);
21
+
22
+ /**
23
+ * A descendant's label, surfaced at the ancestor as `blockerFrom` — NEVER as the ancestor's own `blocker`
24
+ * (which means THIS node broke). `broken-sensor` (caller's own code) outranks any other label.
25
+ * @param {any[]} spawned
26
+ * @returns {{blocker: string, blockerDetail?: string, blockerTask?: string}|null}
27
+ */
28
+ function inheritedBlocker(spawned) {
29
+ const list = Array.isArray(spawned) ? spawned : [];
30
+ const pick = list.find(c => c && c.incomplete && c.blocker === 'broken-sensor') || list.find(c => c && c.incomplete && c.blocker);
31
+ if (!pick) return null;
32
+ return {
33
+ blocker: pick.blocker,
34
+ ...(pick.blockerDetail && { blockerDetail: pick.blockerDetail }),
35
+ ...(pick.task && { blockerTask: pick.task }),
36
+ };
37
+ }
38
+
39
+ /**
40
+ * Finish a node. `node` is the receipts node (`{task, spawned, best?, missingSlices?, ...}`); `best` is the last
41
+ * non-empty work the caller saw (BA-5). `value` is the produced answer, `err` anything the path caught.
42
+ * A HaltError is mapped (never thrown): `brake:*` => `blocker:'brake'`, a gate halt => `blocker:'halt'`; any other
43
+ * `err` is re-thrown (not this tail's to swallow). Returns `{result, verdict, receipts}` on a satisfied verdict,
44
+ * else `{incomplete, best, blocker?, ..., receipts}`. Root returns (counter without a parent) carry `metrics`.
45
+ * @param {any} node
46
+ * @param {any} value
47
+ * @param {any} [err]
48
+ * @param {FinishRun} [run]
49
+ * @returns {Promise<any>}
50
+ */
51
+ async function finish(node, value, err, run = {}) {
52
+ const { ctx = {}, opts = {}, counter, blocker } = run;
53
+ const best = hasWork(value) ? value : hasWork(node.best) ? node.best : null;
54
+ const inherited = inheritedBlocker(node.spawned);
55
+ if (inherited) node.blockerFrom = inherited;
56
+
57
+ const rootMetrics = () => (counter && counter.isRoot ? { metrics: counter.metrics() } : {});
58
+ /** Assemble every incomplete return identically (one place for flags + metrics). */
59
+ const incomplete = (fields) => {
60
+ node.incomplete = true;
61
+ return {
62
+ incomplete: true, best,
63
+ // v1 contract: an inherited descendant label rides the RESULT as blocker/blockerTask/blockerDetail (so a caller
64
+ // checking only `result.blocker` sees it) — but only when this node has no OWN blocker; the node/receipts
65
+ // carry it as `blockerFrom` and never as their own `blocker`.
66
+ ...(inherited && !fields.blocker && inherited), ...fields, receipts: node,
67
+ ...(counter && counter.unbraked && { unbraked: true }), ...(rootMetrics()),
68
+ };
69
+ };
70
+ const haltFields = (h) => {
71
+ node.halted = true;
72
+ const rule = typeof h.rule === 'string' ? h.rule : '';
73
+ if (rule.startsWith('brake:')) { node.blocker = 'brake'; node.brake = rule.slice(6); return { blocker: 'brake', brake: node.brake }; }
74
+ node.blocker = 'halt'; node.halt = rule || 'unknown';
75
+ return { blocker: 'halt', halt: node.halt };
76
+ };
77
+
78
+ if (err !== undefined && err !== null) {
79
+ if (err instanceof HaltError) return incomplete(haltFields(err));
80
+ throw err;
81
+ }
82
+ if (blocker && typeof blocker.blocker === 'string') {
83
+ node.blocker = blocker.blocker;
84
+ return incomplete({ ...blocker });
85
+ }
86
+ if (Array.isArray(node.missingSlices) && node.missingSlices.length) {
87
+ return incomplete({ missingSlices: node.missingSlices }); // RC-9: never survivor-sum a dead piece
88
+ }
89
+ if (value === undefined || value === null) { node.blocker = 'no-final'; return incomplete({ blocker: 'no-final' }); }
90
+
91
+ // The isCritical floor guards the TOP task only: a child's task is a model-written ask/map prompt, never the caller's.
92
+ const wantVerify = ((!counter || counter.isRoot) && isCritical(node.task)) || typeof opts.contract === 'string' || typeof opts.evaluate === 'function';
93
+ if (!wantVerify) return success(node, value, null, counter);
94
+
95
+ try {
96
+ // The verdict MUST be awaited INSIDE this try (a bare `return verify(...)` would let a verifier HaltError escape the catch).
97
+ const verdict = await verify(node.task, value, ctx, opts);
98
+ node.verdict = verdict;
99
+ if (!verdict.pass) {
100
+ node.blocker = 'verify-failed';
101
+ return incomplete({ blocker: 'verify-failed', verdict, best: value });
102
+ }
103
+ return success(node, value, verdict, counter);
104
+ } catch (e) {
105
+ if (e instanceof HaltError) return incomplete({ ...haltFields(e), best: value });
106
+ if (e instanceof BrokenArbiterError) {
107
+ node.blocker = 'broken-verifier';
108
+ node.blockerDetail = e.detail;
109
+ return incomplete({ blocker: 'broken-verifier', blockerDetail: e.detail, best: value });
110
+ }
111
+ throw e; // a default-Evaluator provider fault is not an arbiter fault — propagate
112
+ }
113
+ }
114
+
115
+ function success(node, value, verdict, counter) {
116
+ return {
117
+ result: value, verdict, receipts: node,
118
+ ...(counter && counter.unbraked && { unbraked: true }),
119
+ ...(counter && counter.isRoot ? { metrics: counter.metrics() } : {}),
120
+ };
121
+ }
122
+
123
+ module.exports = { finish, inheritedBlocker };
@@ -20,3 +20,41 @@ export const DECOMPOSITION_POLICY: string;
20
20
  * @returns {string} A suffix to append to the worker system prompt ('' at depth 0).
21
21
  */
22
22
  export function capabilityScrub(depth: number, maxDepth: number): string;
23
+ /** System prompt of a leaf sub-call (`ask`/`map` at the depth cap): one question, one piece, no tools. */
24
+ export const SUB_SYSTEM: "You answer one question about one piece of data. Be brief and literal.";
25
+ export namespace TYPED_FINAL {
26
+ let count: string;
27
+ let ids: string;
28
+ let composite: string;
29
+ let text: string;
30
+ }
31
+ /**
32
+ * Depth-aware scope text for the env worker (NB-4/RC-12 for v2): at/after the cap the sub-call tools are withheld
33
+ * and the prompt says so (honest "incomplete" beats a fabricated answer); below the cap but nested, prefer direct action.
34
+ * @param {number} depth @param {number} maxDepth @returns {string}
35
+ */
36
+ export function envScope(depth: number, maxDepth: number): string;
37
+ /**
38
+ * The env worker's system prompt. The input is NEVER here — only `meta` (type, size, short prefix).
39
+ * @param {{persona?: string, meta: string|null, kind: string, canSub: boolean, depth: number, maxDepth: number}} p
40
+ * @returns {string}
41
+ */
42
+ export function envSystem({ persona, meta, kind, canSub, depth, maxDepth }: {
43
+ persona?: string;
44
+ meta: string | null;
45
+ kind: string;
46
+ canSub: boolean;
47
+ depth: number;
48
+ maxDepth: number;
49
+ }): string;
50
+ /**
51
+ * The §9.2-validated classify system prompt, GENERALIZED from the POC's hardcoded "SPORTS news" predicate to
52
+ * an arbitrary one. The load-bearing wording is verbatim ("Examine EACH item individually", "Output ONLY the
53
+ * IDs", "Comma-separated. If none, output 'none'. No count, no prose.") — the predicate is the only variable.
54
+ * It MUST return ids, not a count: counting is CODE's job (RC-5 / §9.1), so the judge never does arithmetic.
55
+ * @param {string} predicate - The task/goal the items are judged against.
56
+ * @returns {string}
57
+ */
58
+ export function classifySystem(predicate: string): string;
59
+ export const SCAN_WINDOW: 8;
60
+ export const SCAN_PASSES: 2;
@@ -68,4 +68,72 @@ function capabilityScrub(depth, maxDepth) {
68
68
  ].join('\n');
69
69
  }
70
70
 
71
- module.exports = { DECOMPOSITION_POLICY, capabilityScrub };
71
+
72
+ // ── v2 env prompts (docs/product/rlm-prd.md §0.1; wording ported from poc/rlm-v2-env.mjs, validated live) ──────
73
+
74
+ /** System prompt of a leaf sub-call (`ask`/`map` at the depth cap): one question, one piece, no tools. */
75
+ const SUB_SYSTEM = 'You answer one question about one piece of data. Be brief and literal.';
76
+
77
+ /** The typed-final rule + ONE legal example per answer kind ("AI points, code decides"). */
78
+ const TYPED_FINAL = {
79
+ count: 'ANSWER KIND: count. End with final("<var>") citing the var returned by classify (e.g. classify(...) returned var=v2, so call final("v2")). CODE derives the number from that var\'s ids — NEVER type a number; final_text is refused.',
80
+ ids: 'ANSWER KIND: ids. End with final("<var>") citing the var returned by classify (e.g. final("v2")).',
81
+ composite: 'ANSWER KIND: needle text + count. End with final_parts(needle="<exact text of the item>", count="<var of kind count>"), e.g. final_parts(needle="Some exact headline", count="v3"). CODE derives the number from the count var — NEVER type a number.',
82
+ text: 'ANSWER KIND: text. End with final_text("<your answer>"), or cite a text var with final("<var>").',
83
+ };
84
+
85
+ /**
86
+ * Depth-aware scope text for the env worker (NB-4/RC-12 for v2): at/after the cap the sub-call tools are withheld
87
+ * and the prompt says so (honest "incomplete" beats a fabricated answer); below the cap but nested, prefer direct action.
88
+ * @param {number} depth @param {number} maxDepth @returns {string}
89
+ */
90
+ function envScope(depth, maxDepth) {
91
+ if (depth >= maxDepth) {
92
+ return `\nDEPTH ${depth} of ${maxDepth} — this is the deepest level. You CANNOT delegate: ask, map and classify are not available. Work directly with info/peek/find/chunk/join/count; if the task cannot be answered faithfully, say so rather than guessing.`;
93
+ }
94
+ if (depth > 0) return `\nDEPTH ${depth} of ${maxDepth} — you are inside a delegated sub-task. PREFER DIRECT ACTION; only delegate further when a part is genuinely too large for one pass.`;
95
+ return '';
96
+ }
97
+
98
+ /**
99
+ * The env worker's system prompt. The input is NEVER here — only `meta` (type, size, short prefix).
100
+ * @param {{persona?: string, meta: string|null, kind: string, canSub: boolean, depth: number, maxDepth: number}} p
101
+ * @returns {string}
102
+ */
103
+ function envSystem({ persona, meta, kind, canSub, depth, maxDepth }) {
104
+ const lines = meta ? [
105
+ 'You answer questions about data you cannot see. It lives OUTSIDE your prompt as env var `input`.',
106
+ meta,
107
+ 'Every tool returns a truncated preview and stores the full value under a var name you can pass to the next tool.',
108
+ 'Rules: never guess the data. ' + (canSub
109
+ ? 'For "how many"/"all" questions call classify(predicate, "input") — it counts in CODE; do not count by hand. For a subjective question about one piece use ask(prompt, var); to run one question over every chunk use chunk then map. '
110
+ : '') + 'To locate an item by words it contains use find(var, terms); to read by position use peek.',
111
+ ] : ['Answer the task. Use the provided tools if any.'];
112
+ lines.push(TYPED_FINAL[/** @type {keyof typeof TYPED_FINAL} */ (kind)]);
113
+ const p = typeof persona === 'string' ? persona.trim() : '';
114
+ return (p ? p + '\n\n' : '') + lines.join('\n') + envScope(depth, maxDepth);
115
+ }
116
+
117
+ // §9.2.1 LOCKED defaults: WINDOW is the one calibrated number (recall knee ≈ 8, per-model); PASSES=2 (offset-window union → recall ~0.9+).
118
+ const SCAN_WINDOW = 8;
119
+ const SCAN_PASSES = 2;
120
+
121
+ /**
122
+ * The §9.2-validated classify system prompt, GENERALIZED from the POC's hardcoded "SPORTS news" predicate to
123
+ * an arbitrary one. The load-bearing wording is verbatim ("Examine EACH item individually", "Output ONLY the
124
+ * IDs", "Comma-separated. If none, output 'none'. No count, no prose.") — the predicate is the only variable.
125
+ * It MUST return ids, not a count: counting is CODE's job (RC-5 / §9.1), so the judge never does arithmetic.
126
+ * @param {string} predicate - The task/goal the items are judged against.
127
+ * @returns {string}
128
+ */
129
+ function classifySystem(predicate) {
130
+ return (
131
+ 'You are a precise classifier. Examine EACH item individually. Each item is shown on its own line as ' +
132
+ '`<id> => <text>`. Output ONLY the IDs of the items that match the predicate below — copy each matching ' +
133
+ 'item\'s <id> VERBATIM (the exact characters before " => "; an id may itself contain ":" — keep all of ' +
134
+ 'it). Comma-separated. If none, output "none". No count, no prose.\n\nPREDICATE: ' +
135
+ predicate
136
+ );
137
+ }
138
+
139
+ module.exports = { DECOMPOSITION_POLICY, capabilityScrub, SUB_SYSTEM, TYPED_FINAL, envScope, envSystem, classifySystem, SCAN_WINDOW, SCAN_PASSES };