bare-agent 0.59.0 → 0.60.1

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 CHANGED
@@ -37,7 +37,7 @@ An LLM call is slow, deliberate thinking (System 2). Jev, from TypeSafe, is the
37
37
 
38
38
  ## Break big tasks down — RLM
39
39
 
40
- `recurse` brings Recursive Language Models (RLM) to your code in one call: split a hard task into smaller ones, run each in a fresh context window, check the result, and stitch it back together. The model decides when to split (or you force a fixed count), and over a large set of documents it picks the path by question shape — scan everything for "how many", search for a needle. Totals are counted by code, and a dead worker comes back `incomplete`, never a faked pass. Cost is open by design: run it under a budget cap (bareguard) or set `maxDepth: 1`.
40
+ `recurse` brings Recursive Language Models (RLM) to your code in one call: the data stays out of the prompt, in a variable the model inspects through a small fixed set of tools, so a task over far more data than fits in context still runs with a small, bounded window. Counts and totals are derived by code from what the model points at (never a number it typed), and a dead worker, a tripped limit or a failed check comes back `incomplete`, never a faked pass. Hard limits on the number of calls are on by default, sized by code from the input. On the full 7,600-item AG News set, past the model's context, it counted with 0.99 recall while the same task inlined in one prompt answered confidently and missed 88%. Money caps stay with the budget gate (bareguard).
41
41
 
42
42
  ## What's inside
43
43
 
@@ -48,7 +48,7 @@ Every piece works alone — take what you need, ignore the rest. No required dep
48
48
  | Act | Loop | think → act → observe until done, any provider, opt-in policy/assemble/trim seams |
49
49
  | Act | Planner + runPlan | break a goal into a step DAG, run steps in parallel waves |
50
50
  | Act | assessComplexity | rate a goal from its text alone, no LLM — gates whether to plan |
51
- | Act | recurse | RLM in one call — decompose → fan-out → verify → synthesize (see above) |
51
+ | Act | recurse | RLM in one call — input in an environment, fixed tools, typed answer, hard call limits (see above) |
52
52
  | Act | Memory | persist and recall across sessions — JSON, SQLite, or litectx in a one-line swap |
53
53
  | Act | StateMachine | task lifecycle: pending → running → done / failed / waiting / cancelled |
54
54
  | Act | Scheduler | cron or relative triggers, survives restarts |
@@ -74,32 +74,13 @@ Every piece works alone — take what you need, ignore the rest. No required dep
74
74
  - A dead worker or broken check returns `incomplete`, never a faked pass — and counts are done by code, not by the model.
75
75
  - Stuck loops stop: repeated denials or the same failing call end the run cleanly instead of burning the budget.
76
76
 
77
- ## The bare ecosystem
77
+ ## bare suite
78
78
 
79
- Local-first, composable agent infrastructure. Same API patterns throughout —
80
- mix and match, each module works standalone.
79
+ - **Hands** · [barebrowse](https://github.com/hamr0/barebrowse) · [baremobile](https://github.com/hamr0/baremobile) · [beeperbox](https://github.com/hamr0/beeperbox)
80
+ - **Rails** · **bareagent** · [bareguard](https://github.com/hamr0/bareguard) · [barebox](https://github.com/hamr0/barebox) · [litectx](https://github.com/hamr0/litectx)
81
+ - **Apps** · [fwdloop](https://github.com/hamr0/fwdloop) · [bareloop](https://github.com/hamr0/bareloop)
81
82
 
82
- **Core** — the brain, the gate, the memory.
83
-
84
- - **[bareagent](https://npmjs.com/package/bare-agent)** — the think→act→observe loop. *Goal in → coordinated actions out.* Replaces LangChain, CrewAI, AutoGen.
85
- - **[bareguard](https://npmjs.com/package/bareguard)** — the single gate every action passes through. *Action in → allow / deny / ask-a-human out.* Replaces hand-rolled allowlists and scattered policy code.
86
- - **[litectx](https://npmjs.com/package/litectx)** — tree-sitter code + memory graph with activation decay, plus lightweight context engineering (write · select · compress · isolate). *Query in → ranked context out.*
87
-
88
- **Optional reach** — give the agent hands.
89
-
90
- - **[barebrowse](https://npmjs.com/package/barebrowse)** — a real browser for agents. *URL in → pruned snapshot out.* Replaces Playwright, Selenium, Puppeteer.
91
- - **[baremobile](https://npmjs.com/package/baremobile)** — Android + iOS device control. *Screen in → pruned snapshot out.* Replaces Appium, Espresso, XCUITest.
92
- - **[beeperbox](https://github.com/hamr0/beeperbox)** — 50+ messaging networks via one MCP server (headless Beeper Desktop in Docker). *Chat in → unified message stream out.* Replaces Twilio, per-platform bot APIs.
93
-
94
- **What you can build:**
95
-
96
- - **Headless automation** — scrape sites, fill forms, extract data, monitor pages on a schedule
97
- - **QA & testing** — automated test suites for web and Android apps without heavyweight frameworks
98
- - **Personal AI assistants** — chatbots that browse the web or control your phone on your behalf
99
- - **Remote device control** — manage Android devices over WiFi, including on-device via Termux
100
- - **Agentic workflows** — multi-step tasks where an AI plans, browses, and acts across web and mobile
101
-
102
- **Why this exists:** Most automation stacks ship 200MB of opinions before you write a line of code. These don't. Install, import, go.
83
+ Pairs well with [bareguard](https://github.com/hamr0/bareguard) (gate its actions) and [litectx](https://github.com/hamr0/litectx) (memory). → [The whole suite](https://github.com/hamr0)
103
84
 
104
85
  ## Docs
105
86
 
@@ -13,7 +13,7 @@ bareagent is a lightweight agent orchestration library (small core, zero require
13
13
  npm install bare-agent
14
14
  ```
15
15
 
16
- Eight entry points:
16
+ Nine entry points:
17
17
  - `require('bare-agent')` — Loop, Planner, **assessComplexity** (pure-code no-LLM pre-planner → `{level, score, needsPlanning, signals}`), StateMachine, Scheduler, Checkpoint, Memory, Stream, Retry, runPlan, CircuitBreaker, wireGate, defaultActionTranslator, **toUnits, fromUnits, unitAssembler** (the `assemble` context-units adapter, v0.13+), **unitTrimmer, harvestKey** (the destructive `trim` seam adapter — RT-2 harvest-before-evict, needs a consumer on litectx ≥ 0.16.0), BareAgentError, ProviderError, ToolError, TimeoutError, ValidationError, CircuitOpenError, **HaltError**
18
18
  - `require('bare-agent/errors')` — same error classes via a stable subpath (v0.10.1+) for adopters who want to import only the error surface
19
19
  - `require('bare-agent/providers')` — OpenAI, Anthropic, Ollama, CLIPipe, Fallback (the canonical short names; `*Provider` aliases — `OpenAIProvider`, `AnthropicProvider`, etc. — are also exported and match the class names, so either destructure works, v0.12.1+)
@@ -22,6 +22,7 @@ Eight entry points:
22
22
  - `require('bare-agent/tools')` — createBrowsingTools, createMobileTools, createShellTools, resolveToolPath, createSpawnTool, createDeferTool, spawnChild, readDeferQueue, liteCtxMcpBridgeConfig
23
23
  - `require('bare-agent/mcp')` — createMCPBridge (returns `tools` + `metaTools`), discoverServers, buildMetaTools, listServerTools
24
24
  - `require('bare-agent/bareguard')` — wireGate (one-line bareguard Gate integration), defaultActionTranslator
25
+ - `require('bare-agent/recurse-adapters')` — buildScanTool, buildSearchTool, buildExactTool, litectxCorpus (ordinary tools / an `input` source for `recurse`; moved off the root export in the recurse v2 rebuild)
25
26
 
26
27
  **TypeScript:** bareagent is pure JS + JSDoc but ships `.d.ts` declarations (generated from that JSDoc, v0.11+). Every entry point above resolves types automatically — `import { Loop } from 'bare-agent'` and `import { OpenAI } from 'bare-agent/providers'` give full autocomplete and type-checking, including required-option enforcement (e.g. `new Loop({})` is a type error: `provider` is required). No `@types/bare-agent` needed. Shared shapes (`Provider`, `Message`, `ToolDef`, `ToolCall`, `Usage`, `GenerateResult`, `Store`) are exported from the package's `types/`. The repo itself runs `tsc --checkJs` in CI on every push/PR so the JSDoc and the code can't drift.
27
28
 
@@ -34,11 +35,11 @@ Eight entry points:
34
35
  | Size a goal before planning (no LLM) | assessComplexity — `needsPlanning` gates a Planner pass |
35
36
  | Kill a spawned child that hangs silently | createSpawnTool / spawnChild `{ idleTimeoutMs }` |
36
37
  | Execute a step DAG with parallelism | runPlan + executeFn |
37
- | Decompose a hard task into a verified tree (RLM) | recurse — decompose → fan-out → verify → synthesize in one call (**wire a gate**, cost is open by design) |
38
- | Count / answer "how many / all" over a corpus, honestly | recurse(task, ctx, `{ corpus, retrieval: 'scan' }`) — scans every slice, CODE-counts |
39
- | Give recurse workers a persona/role (senior-dev stance) | recurse(task, ctx, `{ persona }`) — prepended to every worker, carries down the tree; not applied to the verifier |
40
- | Tell recurse workers WHERE they are (paths/cwd) so a slice can find its file | recurse(task, ctx, `{ context }`) — read-only blob on every worker's task message + the Planner + verifier; carries down (facts, not a stance) |
41
- | Let a recurse LEAF retry its own failure with a deterministic check | recurse(task, ctx, `{ refineLeaf: { sensor } }`) — leaf becomes a bounded generate→sense→regenerate loop; your sensor (test/compile/lint) judges the RETURNED result, gap fed back, escalating temperature; `rejectedBuffer` feeds prior failed attempts back on a temp-fixed model |
38
+ | Answer a question about data too big for one prompt (RLM), with hard call limits | recurse(task, ctx, `{ input, kind }`) — input lives in an env var, fixed tools, typed final, formula-capped brakes (**wire a gate for money**) |
39
+ | Count / answer "how many / all" over a corpus, honestly | recurse(task, ctx, `{ input: slices, kind: 'count' }`) — the `classify` tool scans every slice, code derives the count |
40
+ | Give recurse workers a persona/role (senior-dev stance) | recurse(task, ctx, `{ persona }`) — prepended to every env worker, carries down; not applied to the verifier |
41
+ | Tell recurse workers WHERE they are (paths/cwd) so a slice can find its file | recurse(task, ctx, `{ context }`) — read-only blob on every worker's task message + the verifier; carries down (facts, not a stance) |
42
+ | Let a worker retry its own failure against a deterministic check | refineWorker(task, ctx, `{ refineLeaf: { sensor } }`) (the `recurse(…,{maxDepth:0, refineLeaf})` shim is deprecated) |
42
43
  | Track task state (pending/running/done/failed) | StateMachine |
43
44
  | Run agent turns on a schedule (cron, timers) | Scheduler |
44
45
  | Require human approval before dangerous actions | Checkpoint |
@@ -824,75 +825,45 @@ const results = await runPlan(steps, async (step) => {
824
825
  // results: [{ id: 's1', status: 'done', result: '...' }, { id: 's2', status: 'failed', error: '...' }, ...]
825
826
  ```
826
827
 
827
- ## Wiring with recurse (RLM — decompose → fan-out → verify → synthesize)
828
+ ## Wiring with recurse (RLM — input in an environment, fixed tools, hard call limits)
828
829
 
829
- `recurse(task, ctx, opts)` is the **Recursive Language Models** primitive (v0.20.0): one import that decomposes a hard task into fresh-context workers, verifies against a setpoint, and synthesizes one result. It is **thin glue composed around `Loop`/`Planner`/`runPlan`/`Evaluator`/`spawn`** — not a new engine, never imported by `loop.js`. Returns `{ result, verdict, receipts }` on convergence, or `{ incomplete, best, missingSlices, receipts }` on guard exhaustion / a dead worker — **never a fabricated success** (RC-9).
830
-
831
- > **⚠️ Cost is open by DESIGN — wire a gate.** `recurse()` adds NO intrinsic total-work cap. On the **Family-A default** (model-driven) a node can spawn up to ~100 children per level, each recursing to `opts.maxDepth` (default 3) — so token/$ spend compounds and is bounded **only by your gate**, not by recurse. A live POC saw a weak model do 40–117 calls in one run. **Always wire bareguard** (`ctx.policy` via `wireGate`) for any non-trivial or untrusted run — it enforces depth/budget/call caps and turns a runaway into a clean `{ incomplete }` (proven: a wired `Gate` cut a 43–117-call runaway to 4–5 calls). The local brake without a gate is `opts.maxDepth: 1` (flat, no nesting). The forced modes (`mode:'fanout'`/`'partition'`) ARE bounded (deterministic count + concurrency cap).
830
+ `recurse(task, ctx, opts)` is the **Recursive Language Models** primitive, rebuilt in v2 (breaking, see CHANGELOG): the data lives in an **environment variable** the model inspects through **fixed tools** — it is never pasted into the prompt — and the answer is a var of a **kind you declare**, derived by code. Composes around `Loop`/`Evaluator`, never imported by `loop.js`. Returns `{ result, verdict, receipts, metrics }`, or `{ incomplete, best, blocker, receipts, metrics }` — **never a faked success**; `incomplete` is the ONE "not done" signal.
832
831
 
833
832
  ```javascript
834
833
  const { recurse, wireGate } = require('bare-agent');
835
- const { Gate } = require('bareguard');
836
-
837
- // ALWAYS run governed for real work — the gate is the total-work bound.
838
- const gate = new Gate({ budget: { maxCostUsd: 0.50 }, limits: { maxTurns: 30, maxDepth: 3 }, humanChannel: async () => ({ decision: 'deny' }) });
839
- await gate.init();
840
- const { policy, onLlmResult } = wireGate(gate);
841
834
 
842
- // ctx = runtime wiring threaded down the whole tree; opts = policy knobs.
843
- const ctx = { provider, policy, onLlmResult }; // policy + onLlmResult = the gate over every node + the verifier
844
- const out = await recurse('Audit this 2000-line module for security bugs and rank them', ctx, { maxDepth: 3 });
845
-
846
- if (out.incomplete) {
847
- console.warn('did not converge:', out.missingSlices, '— best partial:', out.best); // honest, never a faked pass
848
- } else {
849
- console.log(out.result, out.verdict); // the synthesized answer + the verifier's gap report
850
- }
851
- console.log(out.receipts.spawned.length); // RC-10 audit tree: parent→child lineage, per-node tokens/verdict
835
+ const ctx = { provider, policy, onLlmResult }; // gate over every call in the tree + the verifier (money stays bareguard's)
836
+ const out = await recurse('How many of these tickets are billing disputes?', ctx, {
837
+ input: tickets, // string | {id,text}[] | async () => {id,text}[] — lives in env var `input`; root prompt shows only type/size/short prefix
838
+ kind: 'count', // 'count' | 'ids' | 'text' (default) | 'composite' {needle, count}
839
+ });
840
+ if (out.incomplete) console.warn(out.blocker, out.missingSlices, out.best); // brake | halt | wrong-final | no-final | verify-failed | input | governance-deny | ...
841
+ else console.log(out.result.count, out.result.ids); // count DERIVED by code from the ids var
852
842
  ```
853
843
 
854
- > **Audit-safe by construction (since Unreleased).** You pass `provider` on `ctx`, and a wired gate records the per-run ctx VERBATIM as `action._ctx`. `recurse()` **strips the live provider** (and thus its `apiKey`) from the ctx at every governance boundary before it reaches `gate.record`/`gate.check`, so the key never lands in the audit JSONL — only the provider *name* does (identity, not secret). The provider still reaches the worker (it runs); only the audited copy is cleaned. (bareguard's own secret-redaction is opt-in and value/pattern-based, so do not rely on it to catch a key you put on `ctx` — but DO scrub any *other* secret-bearing field you thread on `ctx` yourself, or configure `gate` `secrets`.)
844
+ **Fixed tools (no model-written code):** `info`, `peek`, `find` (literal AND-terms, no regex), `chunk`, `ask` (one sub-call on a piece), `map` (code-driven fan-out over a list var, every slot required), `classify` (scan every item with an LLM judge, window 8 x 2 passes, **code-counts** the union of returned ids — the verbatim, measured wording; RC-2 drops ids the judge was not shown), `join`/`count` (code reductions), `final(var)` / `final_text(text)` / `final_parts`. Every tool returns a truncated preview and stores the full value under a var name; your `opts.tools` are appended. `classify`/`map`/`ask` are withheld at the depth cap (and the prompt says so). Repeating `classify`/`map`/`find` with the same args over the same data is a **memo hit: zero calls**.
855
845
 
856
- **Control families (how the tree is shaped):**
846
+ **Typed final — "AI points, code decides".** For `count`/`ids` the model must cite a classify var with `final("<var>")`; code derives `{count, ids}` (the model never types a number, and no number is parsed from prose). A wrong-kind final (or a `final(var)` on a blank/whitespace-only text var, same as a blank `final_text`) gets ONE nudge, then `{ incomplete, blocker:'wrong-final' }`; no final at all is `blocker:'no-final'`. (A `text` task may also end with a plain reply.) A dead window/slot is **never a zero or a survivor-sum**: it surfaces as `{ incomplete, missingSlices, best:<floor> }`.
857
847
 
858
- - **Family A — model-driven (default).** The worker is handed an in-process `spawn_child` tool and *decides* whether to split. `assessComplexity` is a **hint, not a gate** (only `simple → single-shot`, and the non-overridable `critical → force adversarial verify` safety floor). Nothing extra to set.
859
- - **Family B — forced fan-out (opt-in).** `{ count: N }` → exactly N independent parallel workers via `Planner`→`runPlan`; or `{ mode: 'fanout' }` → count derived from the complexity tier (medium/complex/critical → 2/4/6). Deterministic + concurrency-capped.
860
- - **`{ mode: 'partition', corpus, workerBudget }`** — data-driven WIDTH: measure the corpus, split into `max(count floor, ⌈size/workerBudget⌉)` parallel scan-workers, union-count. A pre-wave `recurse_partition` policy checkpoint fires before any worker spends.
848
+ **Brakes — structural, default ON (even with a gate), counting only.** `limits: { maxDepth: 1, maxCalls, maxWidth: 16, maxRounds: 20 }`. ONE call counter in a closure the model cannot read or raise meters **every** `generate` in the tree (worker rounds, sub-calls, classify windows, the verifier). `maxCalls` defaults to a **formula cap** computed by code from the input size — `ceil((ceil(items/8)*2 + maxRounds) * 1.25) + verify` (60 items: 45, 600: 213, 7,600: 2,400) — exposed in `receipts.cap`/`receipts.limits` and a `recurse:limits` stream event BEFORE the first call, and **tighten-only** (your `maxCalls` can only lower it). A tripped brake returns `{ incomplete, blocker:'brake', brake:'maxCalls'|'maxWidth'|'maxRounds', best }` with the work so far preserved (BA-5); a gate halt stays `blocker:'halt', halt:<rule>`, so "my brake" and "the gate" are distinguishable. `limits:'none'` disables them and every return carries `unbraked:true`. No dollars/tokens/wall-clock here — that is bareguard's; pass `rates` (per-1K, like `Loop({rates})`) to make `metrics.costUsd` authoritative (null if any round has no usage). Root `metrics: { calls, tokens, costUsd }` sums the whole tree.
861
849
 
862
- **Retrieval over a corpus** (`opts.corpus = {id,text}[]` or an async `() => Promise<Slice[]>`, e.g. `litectxCorpus(litectx, {kind})`). Context reaches a worker as a HANDLE routed by question shape:
850
+ **Measured (live, `poc/rlm-v2-shipped-replay.mjs`, deepseek-flash, AG News).** Shipped `recurse` at 7,600 items (the whole test set, past the model's context): recall 0.99, precision 0.96, **root peak 2,284 tokens**, 1,903 calls vs cap 2,400; the same task inlined in a plain `Loop` returns `end_turn` with no error but recall 0.12 (a silent failure). At 600 items: RLM recall 0.99 vs inline 0.91 (paired), root peak ~2.2k vs ~35k inline. The needle+count mixed task passes; `maxCalls:5` brakes cleanly; the constant-final control fails.
863
851
 
864
- | `retrieval` | For | Note |
865
- |---|---|---|
866
- | `'scan'` *(default when `corpus` present)* | "how many / all / count" | scans every slice, LLM-judges, **CODE-counts** the union — the only path that can't undercount; `window` 8, `passes` 2 |
867
- | `'search'` | find a needle | litectx `recall` tool (needs `ctx.litectx`), embeddings on — **cannot count** |
868
- | `'exact'` | rule / exact-term match | code-side AND-filter, embeddings off |
869
- | `'tools'` | mixed task (needle *and* count) | offers `scan_count` + `search_memory` + `exact_match`; worker picks per sub-query by tool description |
852
+ > **Audit-safe by construction.** `ctx.provider` (and its `apiKey`) is stripped from the ctx at every governance boundary (root loop, classify judges, sub-calls, children) before it reaches `gate.record`/`gate.check` — only the provider name lands in the audit. Scrub any *other* secret you put on `ctx` yourself.
870
853
 
871
- A completeness guard **upgrades** a `'search'` on a "how many / all" ask to `'scan'` (upgrade-only, never a silent downgrade). Aggregation is **always code**, never a model-stated number.
854
+ **Depth.** `limits.maxDepth` (shorthand `opts.maxDepth`) defaults to 1: sub-calls are plain leaf Loops (fresh window, only the result string comes back). At `maxDepth >= 2` an `ask`/`map` below the cap is a full in-process `recurse` one level down, sharing the parent's counter (children can only tighten it). Deeper nodes get a depth-aware prompt ("prefer direct action" / "deepest level, you cannot delegate").
872
855
 
873
- ```javascript
874
- // Honest count over a corpus — scans every slice, code-counts the matches.
875
- const { result } = await recurse(
876
- 'How many of these support tickets are billing disputes?',
877
- { provider, policy }, // still wire the gate
878
- { corpus: tickets /* {id,text}[] */, retrieval: 'scan' },
879
- );
880
- console.log(result.count, result.matchedIds); // a code-derived count + the ids that back it
881
- ```
856
+ **Verify / setpoint.** `opts.contract` (definition of done) or `opts.evaluate` (your verifier) or an `isCritical` task (frozen safety floor) runs an isolated adversarial verifier on the final answer; the cap funds that call. A verdict of `failed`/`needs_revision` is `{ incomplete, blocker:'verify-failed', verdict, best }` (v2: it used to return a converged-shaped result). Children never grade against the parent's contract — the top node verifies once.
882
857
 
883
- **Synthesis (`opts.synthesize`):** a **function** (deterministic code-reduce over child `results` — use for arithmetic/aggregation; LLM arithmetic over partials carried ~10–15% error), or `'concat'` (lossless no-LLM join), or `'merge'` (isolated Loop-driven subjective merge). Default = the parent model's own closing-turn synthesis. **`opts.contract`** = a definition-of-done the verifier grades against (instead of the loose task); **`opts.evaluate`** overrides the verifier. Exported helpers for the per-query face: `buildScanTool`, `buildSearchTool`, `buildExactTool`, `litectxCorpus`.
858
+ **Adapters** (`require('bare-agent/recurse-adapters')`, moved from the root export): `buildScanTool`, `buildSearchTool` (litectx recall, needle only), `buildExactTool`, `litectxCorpus(litectx, {kind})` (an async `input` source over a litectx corpus). They are ordinary tools / an `input` source now, not recurse modes.
884
859
 
885
- **Worker persona (`opts.persona`, v0.21.0):** a string PREPENDED to every Family-A worker's system prompt — give workers a stance (`persona: 'You are a senior security engineer; be specific and cite the exact file:line'`). It **augments**, never replaces, the built-in decomposition policy + depth-scrub (those drive the spawn mechanics), and **carries down the whole tree** (a child of a "senior security engineer" is still one). It is deliberately **not** applied to the isolated verifier (that isolation is what defeats self-grading sycophancy) nor the deterministic scan judge. Absent ⇒ the worker prompt is unchanged from pre-0.21. **Security:** treat `persona` like a system prompt — it is prepended ahead of the decomposition policy and can override it for every worker, so pass caller-trusted text only, never untrusted/end-user input.
860
+ **Worker persona (`opts.persona`):** a string PREPENDED to every env worker's system prompt (e.g. `'You are a senior security engineer; cite file:line'`); carries down; never applied to the isolated verifier nor the classify judge. **Security:** privileged system-prompt seam — caller-trusted text only.
886
861
 
887
- ```javascript
888
- const out = await recurse('Audit auth.js, billing.js, gateway.js for authz bugs', ctx, {
889
- persona: 'You are a blunt senior application-security engineer. Report each finding as file:line + impact + fix.',
890
- });
891
- ```
862
+ **Worker context (`opts.context`):** a read-only working-context string (paths/cwd) put on the USER message of every worker (and shown to the verifier) so a worker can locate its artifact. Carries down. Trusted run-state only; lower privilege than `persona`.
892
863
 
893
- **Worker context (`opts.context`, v0.23.0):** a read-only working-context string (paths/cwd) PREPENDED to every worker's TASK message as a `Working context:` block — so a sliced child can **locate its artifact** (the Planner paraphrases the goal into subtasks and drops absolute paths; without this, workers guess `.`/`~`/`/tmp` and get denied). Forwarded to the Planner as `info` (path-aware slices) and shown to the verifier too (neutral FACTS, not a stance — distinct from `persona`, which is a privileged SYSTEM-prompt stance). Carries down the tree. **Security:** it still becomes part of the prompt, so pass caller-trusted run-state only, never untrusted/end-user text (lower-privilege than `persona` — user message, not system — but still an injection surface). Absent ⇒ the task message is unchanged.
864
+ **Removed options fail loud** (`ValidationError` with a migration hint): `corpus`, `retrieval`, `window`, `passes`, `mode`, `count`, `workerBudget`, `synthesize`; `refineLeaf` is only honoured through the one-release compat shim `recurse(…, { maxDepth: 0, refineLeaf })` (forwards to `refineWorker`, warns once per process) — otherwise use `refineWorker`.
894
865
 
895
- **Leaf self-correction (`opts.refineLeaf`, v0.23.0, opt-in):** turn a **definite leaf** (a node offered no `spawn_child` — `simple` tier or at `maxDepth`) into a bounded generate→sense→regenerate loop instead of a single pass: `{ sensor, maxIterations?, temperatures?, rejectedBuffer? }`. `sensor(result, { task, context, contract }) → Verdict` is YOUR **deterministic** close (test/compile/lint — not a model judge); on a non-pass its `critique` (the gap, not the transcript) is fed FRESH into the next attempt and — **on models that accept `temperature`** — the **retry temperature ESCALATES** (default `[0.2, 0.7, 1.0]` — load-bearing there: a weak model at a flat temperature regenerates identical wrong code and ignores even crisp feedback). On a **temperature-fixed model** (e.g. `claude-sonnet-5`, which 400s any non-default temperature) the provider silently drops the param (see below), the escalation lever is inert, and the fed-back gap critique carries recovery alone; `receipts.refineLeaf.temperatures` then records the EFFECTIVE temps — a `null` marks an attempt that ran at the model's default (never the ignored requested value). Each attempt is gate-checked + metered; a HaltError mid-loop → clean `{ incomplete }`; honest non-recovery → `receipts.refineLeaf.passed === false` (never a faked pass); `receipts.tokens` sums all attempts. The error-keyed `recall` stays YOUR tool (`opts.tools`), keyed off the fed-back critique — bareagent stays litectx-agnostic. Carries down (engages at the leaves). Absent ⇒ a leaf is a single pass.
866
+ **Leaf self-correction (`refineWorker(task, ctx, { refineLeaf, ... })`; reached from `recurse` only through the `maxDepth:0` compat shim):** run ONE worker as a bounded generate→sense→regenerate loop: `{ sensor, maxIterations?, temperatures?, rejectedBuffer? }`. `sensor(result, { task, context, contract }) → Verdict` is YOUR **deterministic** close (test/compile/lint — not a model judge); on a non-pass its `critique` (the gap, not the transcript) is fed FRESH into the next attempt and — **on models that accept `temperature`** — the **retry temperature ESCALATES** (default `[0.2, 0.7, 1.0]` — load-bearing there: a weak model at a flat temperature regenerates identical wrong code and ignores even crisp feedback). On a **temperature-fixed model** (e.g. `claude-sonnet-5`, which 400s any non-default temperature) the provider silently drops the param (see below), the escalation lever is inert, and the fed-back gap critique carries recovery alone; `receipts.refineLeaf.temperatures` then records the EFFECTIVE temps — a `null` marks an attempt that ran at the model's default (never the ignored requested value). Each attempt is gate-checked + metered; a HaltError mid-loop → clean `{ incomplete }`; honest non-recovery → `receipts.refineLeaf.passed === false` (never a faked pass); `receipts.tokens` sums all attempts. The error-keyed `recall` stays YOUR tool (`opts.tools`), keyed off the fed-back critique — bareagent stays litectx-agnostic. One worker, no decomposition.
896
867
 
897
868
  > **Sensor integrity (`refineLeaf.sensor`):** the sensor must judge the **returned result** (tamper-proof — build/run the returned string in isolation), never a worker **side-effect** a worker with edit tools could game (writing a passing file then returning junk, or editing the failing test itself). The loop optimizes against whatever the sensor reads — keep the close outside what the worker can write. (RSI field lesson: reward-hacking appeared in every optimization loop with a gameable close. **Demonstrated in-repo** — `poc/sensor-gaming-blocked.mjs`: the moment the honest path was blocked, `claude-sonnet-5` faked a pass on an unsatisfiable on-disk check **5/5** — both by editing the test and by making the returned function non-pure — while a tamper-proof close that runs the returned artifact in isolation was not gameable.)
898
869
 
@@ -901,14 +872,12 @@ const out = await recurse('Audit auth.js, billing.js, gateway.js for authz bugs'
901
872
  > **`rejectedBuffer` (BA-14, v0.30.0):** a second lever for a **temperature-fixed** model, where escalation is inert. Instead of only the latest critique, it surfaces the model's OWN prior failed attempts VERBATIM — *"you wrote these, they failed X — write something STRUCTURALLY DIFFERENT."* This is **directed** diversity (attack the specific repeated mistake); escalation is **random** diversity, and the two are **antagonistic** — temperature monotonically degrades the buffer (`poc/ba14b`: flat-0.2 100% → 0.7 70% → 1.0 50%), so when the buffer engages the retry temperature is **held flat** at `temperatures[0]`, never escalated. Trigger: `true` = force on (also on temperature-accepting models); `false` = force off (pure BA-8 escalation); **unset = adaptive** — engage only once a prior attempt's temperature was dropped (i.e. a temp-fixed model where escalation is inert and the buffer is the sole lever). On a temperature-accepting model the default leaves behavior byte-identical. `receipts.refineLeaf.rejectedBuffer` reports whether it engaged. Efficacy is a **weak-model / fixation** phenomenon (live on `claude-sonnet-5` it engaged 6/6 but recovered no better than critique-only — cost-neutral, hence adaptive-not-always-on).
902
873
 
903
874
  ```javascript
904
- const out = await recurse('Fix the failing function in calc.js', ctx, {
875
+ const out = await refineWorker('Fix the failing function in calc.js', ctx, {
905
876
  context: `project root: ${process.cwd()}\nresolve relative paths against it`,
906
877
  refineLeaf: { sensor: (code) => runTestsAndGrade(code) }, // your deterministic test/compile close
907
878
  });
908
879
  ```
909
880
 
910
- **What a delegated child inherits (important — the setpoint is the TOP node's job):** when a worker delegates with `spawn_child`, the child runs a **fresh `recurse`** that inherits `tools`, `synthesize`, `maxDepth`, `persona`, `context`, and `refineLeaf` — but the parent's **`contract`/`evaluate` are stripped** (and the forced `count`/`mode` + the corpus `retrieval` knobs). A slice is not graded against the *whole*-task definition-of-done (that verdict is the top node's, and a slice satisfying the whole DoD is the wrong question); only the top `recurse` verifies the synthesized result. The non-overridable `critical → force-verify` safety floor still fires per node (it keys on the task text, not the contract). So: set `contract`/`evaluate` once at the top; they do not — and should not — re-run per intermediate node.
911
-
912
881
  ## Wiring with Evaluator + refine (output-side verification)
913
882
 
914
883
  `Evaluator` is the output-side judge (the mirror of `Planner`): it grades a result against a goal and returns a tri-state `Verdict`. `refine` is the bounded generate → evaluate → regenerate loop. Both compose *around* a Loop — neither lives inside `loop.js`.
package/index.d.ts CHANGED
@@ -57,10 +57,7 @@ import { Planner } from "./src/planner";
57
57
  import { Evaluator } from "./src/evaluator";
58
58
  import { refine } from "./src/refine";
59
59
  import { recurse } from "./src/recurse";
60
- import { buildSearchTool } from "./src/recurse-retrieval";
61
- import { buildExactTool } from "./src/recurse-retrieval";
62
- import { buildScanTool } from "./src/recurse-retrieval";
63
- import { litectxCorpus } from "./src/recurse-retrieval";
60
+ import { refineWorker } from "./src/refine-worker";
64
61
  import { remember } from "./src/remember";
65
62
  import { judge } from "./src/judge";
66
63
  import { calibrate } from "./src/judge-calibration";
@@ -97,4 +94,4 @@ import { TimeoutError } from "./src/errors";
97
94
  import { ValidationError } from "./src/errors";
98
95
  import { CircuitOpenError } from "./src/errors";
99
96
  import { HaltError } from "./src/errors";
100
- export { Loop, Planner, Evaluator, refine, recurse, buildSearchTool, buildExactTool, buildScanTool, litectxCorpus, remember, judge, calibrate, calibrateJev, CALIBRATION_CASES, INJECTION_BATTERY, scoreCase, gradeRun, constantHonored, assessComplexity, isCritical, SkillRegistry, createStashSkill, StateMachine, Scheduler, Checkpoint, Memory, Stream, Retry, runPlan, CircuitBreaker, wireGate, defaultActionTranslator, judgeToAnnotation, toUnits, fromUnits, unitAssembler, unitTrimmer, harvestKey, BareAgentError, ProviderError, ToolError, TimeoutError, ValidationError, CircuitOpenError, HaltError };
97
+ export { Loop, Planner, Evaluator, refine, recurse, refineWorker, remember, judge, calibrate, calibrateJev, CALIBRATION_CASES, INJECTION_BATTERY, scoreCase, gradeRun, constantHonored, assessComplexity, isCritical, SkillRegistry, createStashSkill, StateMachine, Scheduler, Checkpoint, Memory, Stream, Retry, runPlan, CircuitBreaker, wireGate, defaultActionTranslator, judgeToAnnotation, toUnits, fromUnits, unitAssembler, unitTrimmer, harvestKey, BareAgentError, ProviderError, ToolError, TimeoutError, ValidationError, CircuitOpenError, HaltError };
package/index.js CHANGED
@@ -20,7 +20,7 @@ const { Planner } = require('./src/planner');
20
20
  const { Evaluator } = require('./src/evaluator');
21
21
  const { refine } = require('./src/refine');
22
22
  const { recurse } = require('./src/recurse');
23
- const { buildSearchTool, buildExactTool, buildScanTool, litectxCorpus } = require('./src/recurse-retrieval');
23
+ const { refineWorker } = require('./src/refine-worker');
24
24
  const { remember } = require('./src/remember');
25
25
  const { judge } = require('./src/judge');
26
26
  const { calibrate, CALIBRATION_CASES, INJECTION_BATTERY, scoreCase, gradeRun, constantHonored } = require('./src/judge-calibration');
@@ -54,10 +54,7 @@ module.exports = {
54
54
  Evaluator,
55
55
  refine,
56
56
  recurse,
57
- buildSearchTool,
58
- buildExactTool,
59
- buildScanTool,
60
- litectxCorpus,
57
+ refineWorker,
61
58
  remember,
62
59
  judge,
63
60
  calibrate,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bare-agent",
3
- "version": "0.59.0",
3
+ "version": "0.60.1",
4
4
  "files": [
5
5
  "index.js",
6
6
  "index.d.ts",
@@ -56,6 +56,10 @@
56
56
  "types": "./src/mcp.d.ts",
57
57
  "default": "./src/mcp.js"
58
58
  },
59
+ "./recurse-adapters": {
60
+ "types": "./src/recurse-adapters.d.ts",
61
+ "default": "./src/recurse-adapters.js"
62
+ },
59
63
  "./bareguard": {
60
64
  "types": "./src/bareguard-adapter.d.ts",
61
65
  "default": "./src/bareguard-adapter.js"
package/primitives.json CHANGED
@@ -23,10 +23,10 @@
23
23
  "name": "buildExactTool",
24
24
  "category": "retrieval",
25
25
  "when": "you want an embeddings-free, exact AND-term filter handle over a slice-source — complete over its slices, for precise lexical matches",
26
- "import": "import { buildExactTool } from 'bare-agent'",
26
+ "import": "import { buildExactTool } from 'bare-agent/recurse-adapters'",
27
27
  "signature": "buildExactTool(corpus: Slice[]) => ToolDef",
28
28
  "fails": "only as good as a lexical rule; complete over the slices it is given (no recall cap) but matches nothing outside them.",
29
- "example": "const tool = buildExactTool(corpus);\nawait recurse(task, ctx, { retrieval: 'exact', tools: [tool] });"
29
+ "example": "const tool = buildExactTool(corpus);\nawait recurse(task, ctx, { input: corpus, tools: [tool] });"
30
30
  },
31
31
  {
32
32
  "name": "buildMetaTools",
@@ -41,7 +41,7 @@
41
41
  "name": "buildScanTool",
42
42
  "category": "retrieval",
43
43
  "when": "you need the complete count/\"all\" path — scan every slice + LLM-judge + code-count — the only retrieval mode that can honestly answer \"how many\"",
44
- "import": "import { buildScanTool } from 'bare-agent'",
44
+ "import": "import { buildScanTool } from 'bare-agent/recurse-adapters'",
45
45
  "signature": "buildScanTool(corpus: Slice[] | (() => Promise<Slice[]>), opts: {provider: Provider, window?: number, passes?: number, ctx?: object, onLlmResult?: Function, policy?: Function}) => ToolDef",
46
46
  "fails": "a dead window surfaces as `INCOMPLETE — the count is a floor`, never a clean number over a hole; a governance HaltError propagates clean.",
47
47
  "example": "const tool = buildScanTool(corpus, { provider, window: 8 });\nawait recurse('how many mention X', ctx, { tools: [tool] });"
@@ -50,10 +50,10 @@
50
50
  "name": "buildSearchTool",
51
51
  "category": "integration",
52
52
  "when": "you want to give a recurse worker a needle-search handle over litectx (embeddings recall for the relevant few) — for FINDING, never counting",
53
- "import": "import { buildSearchTool } from 'bare-agent'",
53
+ "import": "import { buildSearchTool } from 'bare-agent/recurse-adapters'",
54
54
  "signature": "buildSearchTool(litectx: {recall: Function}, opts?: {kinds?: string[], n?: number}) => ToolDef",
55
- "fails": "returns matched bodies only and CANNOT count (the completeness guard blocks a \"how many\" ask before it is offered); a dead window yields nothing, never a fabricated hit.",
56
- "example": "const tool = buildSearchTool(litectx, { n: 8 });\nawait recurse(task, ctx, { retrieval: 'search', tools: [tool] });"
55
+ "fails": "returns matched bodies only and CANNOT count (use classify for \"how many\"); a dead window yields nothing, never a fabricated hit.",
56
+ "example": "const tool = buildSearchTool(litectx, { n: 8 });\nawait recurse(task, ctx, { tools: [tool] });"
57
57
  },
58
58
  {
59
59
  "name": "calibrate",
@@ -274,11 +274,11 @@
274
274
  {
275
275
  "name": "litectxCorpus",
276
276
  "category": "integration",
277
- "when": "you want a resident slice-source that paginates a litectx corpus via enumerate — for a corpus ALREADY in litectx, feeding scan/partition",
278
- "import": "import { litectxCorpus } from 'bare-agent'",
277
+ "when": "you want a resident slice-source that paginates a litectx corpus via enumerate — for a corpus ALREADY in litectx, feeding recurse({ input })",
278
+ "import": "import { litectxCorpus } from 'bare-agent/recurse-adapters'",
279
279
  "signature": "litectxCorpus(litectx: {enumerate: Function}, opts?: {kind?: 'fact'|'episode', pageSize?: number}) => () => Promise<Slice[]>",
280
280
  "fails": "never ingests a fresh corpus (strictly worse than scanning an in-hand array); returns an async source materialized once and cached.",
281
- "example": "const corpus = litectxCorpus(litectx, { kind: 'fact' });\nawait recurse(task, ctx, { mode: 'partition', corpus });"
281
+ "example": "const corpus = litectxCorpus(litectx, { kind: 'fact' });\nawait recurse(task, ctx, { input: corpus, kind: 'count' });"
282
282
  },
283
283
  {
284
284
  "name": "liteCtxMcpBridgeConfig",
@@ -346,11 +346,11 @@
346
346
  {
347
347
  "name": "recurse",
348
348
  "category": "orchestration",
349
- "when": "a task is too big for one model pass and you want it split, fanned out, verified, and merged — with total cost capped by a gate",
349
+ "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",
350
350
  "import": "import { recurse } from 'bare-agent'",
351
351
  "signature": "recurse(task: string, ctx?: RecurseCtx, opts?: RecurseOptions) => Promise<RecurseResult>",
352
- "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.",
353
- "example": "const ctx = wireGate(gate);\nconst { result, incomplete } = await recurse('audit 400 logs', ctx, { provider, corpus });\nif (incomplete) retryOrEscalate(result);"
352
+ "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.",
353
+ "example": "const { result, incomplete } = await recurse('how many are about sports?', { provider }, { input: items, kind: 'count' });\nif (!incomplete) console.log(result.count);"
354
354
  },
355
355
  {
356
356
  "name": "refine",
@@ -361,6 +361,15 @@
361
361
  "fails": "returns the last outcome on maxIterations or a terminal `failed` verdict (never a faked pass); a HaltError from either callback propagates clean.",
362
362
  "example": "const { result, passed } = await refine({ attempt, evaluate, maxIterations: 3 });\nif (!passed) escalate(result);"
363
363
  },
364
+ {
365
+ "name": "refineWorker",
366
+ "category": "core",
367
+ "when": "you want a model to produce an artifact that a deterministic check (test/compile/lint) must pass, retried with fed-back gaps — one worker, no decomposition",
368
+ "import": "import { refineWorker } from 'bare-agent'",
369
+ "signature": "refineWorker(task: string, ctx?: RecurseCtx, opts?: RecurseOptions) => Promise<RecurseResult>",
370
+ "fails": "returns `{incomplete, best}` on non-recovery, halt, deny-spin (`blocker:'governance-deny'`) or a broken sensor (`blocker:'broken-sensor'`); throws on a missing task, provider or sensor",
371
+ "example": "const out = await refineWorker('write add(a,b)', { provider }, { tools: [editTool], refineLeaf: { sensor } });\nif (out.incomplete) console.log(out.blocker, out.best);"
372
+ },
364
373
  {
365
374
  "name": "remember",
366
375
  "category": "evaluation",
@@ -10,101 +10,20 @@ export type Slice = {
10
10
  };
11
11
  export type Provider = import("../types").Provider;
12
12
  export type ToolDef = import("../types").ToolDef;
13
- /**
14
- * SCAN — process every slice, LLM-judge each window, union matching ids across windows AND passes, CODE-count
15
- * the union. The default reliability mechanism (§9.2.1): the only path that does not silently undercount.
16
- * RC-9: a dead window is recorded in `missingSlices`, never folded into the count as a zero.
17
- * @param {string} predicate - The task the slices are judged against.
18
- * @param {Slice[]} corpus - The array slice-source (already validated/normalized by the caller).
19
- * @param {object} opts
20
- * @param {Provider} opts.provider
21
- * @param {number} [opts.window]
22
- * @param {number} [opts.passes]
23
- * @param {object} [opts.ctx]
24
- * @param {Function} [opts.onLlmResult]
25
- * @param {Function} [opts.policy]
26
- * @returns {Promise<{matchedIds: string[], count: number, missingSlices: string[], window: number, passes: number, scanned: number}>}
27
- * @throws {HaltError} a governance cap halted a window judge.
28
- */
29
- export function scanCount(predicate: string, corpus: Slice[], opts: {
30
- provider: Provider;
31
- window?: number | undefined;
32
- passes?: number | undefined;
33
- ctx?: object;
34
- onLlmResult?: Function | undefined;
35
- policy?: Function | undefined;
36
- }): Promise<{
37
- matchedIds: string[];
38
- count: number;
39
- missingSlices: string[];
40
- window: number;
41
- passes: number;
42
- scanned: number;
43
- }>;
44
- /**
45
- * @typedef {object} Slice
46
- * @property {string} id - Stable, word-like id (no whitespace/commas — it is echoed back by the judge).
47
- * @property {string} text - The item content shown to the judge.
48
- */
49
- /**
50
- * Judge ONE window: run an isolated Loop with the classify prompt over the window's items, and intersect the
51
- * returned ids with the ids actually SHOWN this window (RC-2 — a window's judge can only "match" what it was
52
- * given; a hallucinated id from another window is dropped). A governance HaltError propagates (the caller turns
53
- * it into a clean incomplete); any other Loop fault marks the window DEAD (→ RC-9 missingSlices), never a
54
- * silent zero that would undercount.
55
- * @param {string} predicate
56
- * @param {Slice[]} window
57
- * @param {{provider: Provider, ctx?: object, onLlmResult?: Function, policy?: Function, nonce: number}} opts
58
- * @returns {Promise<{ids: string[]|null, dead: boolean}>}
59
- * @throws {HaltError}
60
- */
61
- export function judgeWindow(predicate: string, window: Slice[], opts: {
62
- provider: Provider;
63
- ctx?: object;
64
- onLlmResult?: Function;
65
- policy?: Function;
66
- nonce: number;
67
- }): Promise<{
68
- ids: string[] | null;
69
- dead: boolean;
70
- }>;
71
- /**
72
- * The §9.2-validated classify system prompt, GENERALIZED from the POC's hardcoded "SPORTS news" predicate to
73
- * an arbitrary one. The load-bearing wording is verbatim ("Examine EACH item individually", "Output ONLY the
74
- * IDs", "Comma-separated. If none, output 'none'. No count, no prose.") — the predicate is the only variable.
75
- * It MUST return ids, not a count: counting is CODE's job (RC-5 / §9.1), so the judge never does arithmetic.
76
- * @param {string} predicate - The task/goal the items are judged against.
77
- * @returns {string}
78
- */
79
- export function classifySystem(predicate: string): string;
80
- /**
81
- * Does this text imply a completeness ("all / every / count / how many") ask? Used to upgrade a capped search
82
- * to a scan (the only complete path). Conservative by design — a false positive only costs a thorough scan.
83
- * @param {unknown} text
84
- * @returns {boolean}
85
- */
86
- export function impliesCompleteness(text: unknown): boolean;
87
- /**
88
- * Normalize a raw slice-source into validated `{id, text}` slices (drops malformed entries — a slice with no
89
- * string id/text cannot be judged or counted, so it is excluded rather than silently miscounted).
90
- * @param {unknown} corpus
91
- * @returns {Slice[]}
92
- */
93
- export function normalizeCorpus(corpus: unknown): Slice[];
94
13
  /**
95
14
  * The `search` handle tool (RC-5 needle path): litectx `recall` — embeddings ON, `fact`/`episode` (the
96
15
  * KNN-nominate kinds), capped at `KNN_K`. For FINDING the relevant few; the description tells the worker it
97
- * CANNOT count (the completeness guard catches a "how many" ask before this tool is ever offered). Returns the
16
+ * CANNOT count (use recurse()'s built-in `classify` for "how many"). Returns the
98
17
  * matched items' bodies as text the worker reads; never the whole corpus.
99
18
  * @param {{recall: Function}} litectx
100
19
  * @param {{kinds?: string[], n?: number}} [opts]
101
20
  * @returns {ToolDef}
102
21
  * @category integration
103
22
  * @when you want to give a recurse worker a needle-search handle over litectx (embeddings recall for the relevant few) — for FINDING, never counting
104
- * @fails returns matched bodies only and CANNOT count (the completeness guard blocks a "how many" ask before it is offered); a dead window yields nothing, never a fabricated hit.
23
+ * @fails returns matched bodies only and CANNOT count (use classify for "how many"); a dead window yields nothing, never a fabricated hit.
105
24
  * @example
106
25
  * const tool = buildSearchTool(litectx, { n: 8 });
107
- * await recurse(task, ctx, { retrieval: 'search', tools: [tool] });
26
+ * await recurse(task, ctx, { tools: [tool] });
108
27
  */
109
28
  export function buildSearchTool(litectx: {
110
29
  recall: Function;
@@ -124,7 +43,7 @@ export function buildSearchTool(litectx: {
124
43
  * @fails only as good as a lexical rule; complete over the slices it is given (no recall cap) but matches nothing outside them.
125
44
  * @example
126
45
  * const tool = buildExactTool(corpus);
127
- * await recurse(task, ctx, { retrieval: 'exact', tools: [tool] });
46
+ * await recurse(task, ctx, { input: corpus, tools: [tool] });
128
47
  */
129
48
  export function buildExactTool(corpus: Slice[]): ToolDef;
130
49
  /**
@@ -171,11 +90,11 @@ export function buildScanTool(corpus: Slice[] | (() => Promise<Slice[]>), opts:
171
90
  * @param {{kind?: 'fact'|'episode', pageSize?: number}} [opts]
172
91
  * @returns {() => Promise<Slice[]>}
173
92
  * @category integration
174
- * @when you want a resident slice-source that paginates a litectx corpus via enumerate — for a corpus ALREADY in litectx, feeding scan/partition
93
+ * @when you want a resident slice-source that paginates a litectx corpus via enumerate — for a corpus ALREADY in litectx, feeding recurse({ input })
175
94
  * @fails never ingests a fresh corpus (strictly worse than scanning an in-hand array); returns an async source materialized once and cached.
176
95
  * @example
177
96
  * const corpus = litectxCorpus(litectx, { kind: 'fact' });
178
- * await recurse(task, ctx, { mode: 'partition', corpus });
97
+ * await recurse(task, ctx, { input: corpus, kind: 'count' });
179
98
  */
180
99
  export function litectxCorpus(litectx: {
181
100
  enumerate: Function;
@@ -183,6 +102,71 @@ export function litectxCorpus(litectx: {
183
102
  kind?: "fact" | "episode";
184
103
  pageSize?: number;
185
104
  }): () => Promise<Slice[]>;
105
+ /**
106
+ * SCAN — process every slice, LLM-judge each window, union matching ids across windows AND passes, CODE-count
107
+ * the union. The default reliability mechanism (§9.2.1): the only path that does not silently undercount.
108
+ * RC-9: a dead window is recorded in `missingSlices`, never folded into the count as a zero.
109
+ * @param {string} predicate - The task the slices are judged against.
110
+ * @param {Slice[]} corpus - The array slice-source (already validated/normalized by the caller).
111
+ * @param {object} opts
112
+ * @param {Provider} opts.provider
113
+ * @param {number} [opts.window]
114
+ * @param {number} [opts.passes]
115
+ * @param {object} [opts.ctx]
116
+ * @param {Function} [opts.onLlmResult]
117
+ * @param {Function} [opts.policy]
118
+ * @returns {Promise<{matchedIds: string[], count: number, missingSlices: string[], window: number, passes: number, scanned: number}>}
119
+ * @throws {HaltError} a governance cap halted a window judge.
120
+ */
121
+ export function scanCount(predicate: string, corpus: Slice[], opts: {
122
+ provider: Provider;
123
+ window?: number | undefined;
124
+ passes?: number | undefined;
125
+ ctx?: object;
126
+ onLlmResult?: Function | undefined;
127
+ policy?: Function | undefined;
128
+ }): Promise<{
129
+ matchedIds: string[];
130
+ count: number;
131
+ missingSlices: string[];
132
+ window: number;
133
+ passes: number;
134
+ scanned: number;
135
+ }>;
136
+ /**
137
+ * @typedef {object} Slice
138
+ * @property {string} id - Stable, word-like id (no whitespace/commas — it is echoed back by the judge).
139
+ * @property {string} text - The item content shown to the judge.
140
+ */
141
+ /**
142
+ * Judge ONE window: run an isolated Loop with the classify prompt over the window's items, and intersect the
143
+ * returned ids with the ids actually SHOWN this window (RC-2 — a window's judge can only "match" what it was
144
+ * given; a hallucinated id from another window is dropped). A governance HaltError propagates (the caller turns
145
+ * it into a clean incomplete); any other Loop fault marks the window DEAD (→ RC-9 missingSlices), never a
146
+ * silent zero that would undercount.
147
+ * @param {string} predicate
148
+ * @param {Slice[]} window
149
+ * @param {{provider: Provider, ctx?: object, onLlmResult?: Function, policy?: Function, nonce: number}} opts
150
+ * @returns {Promise<{ids: string[]|null, dead: boolean}>}
151
+ * @throws {HaltError}
152
+ */
153
+ export function judgeWindow(predicate: string, window: Slice[], opts: {
154
+ provider: Provider;
155
+ ctx?: object;
156
+ onLlmResult?: Function;
157
+ policy?: Function;
158
+ nonce: number;
159
+ }): Promise<{
160
+ ids: string[] | null;
161
+ dead: boolean;
162
+ }>;
163
+ /**
164
+ * Normalize a raw slice-source into validated `{id, text}` slices (drops malformed entries — a slice with no
165
+ * string id/text cannot be judged or counted, so it is excluded rather than silently miscounted).
166
+ * @param {unknown} corpus
167
+ * @returns {Slice[]}
168
+ */
169
+ export function normalizeCorpus(corpus: unknown): Slice[];
186
170
  /**
187
171
  * Deterministic rotation by `k` — the shuffled-boundary mechanism for multi-pass union WITHOUT an RNG (keeps
188
172
  * RC-3 determinism: same corpus + same passes ⇒ identical scan). Rotating the array changes which items share a
@@ -191,6 +175,4 @@ export function litectxCorpus(litectx: {
191
175
  * @template T @param {T[]} arr @param {number} k @returns {T[]}
192
176
  */
193
177
  export function rotate<T>(arr: T[], k: number): T[];
194
- export const SCAN_WINDOW: 8;
195
- export const SCAN_PASSES: 2;
196
178
  export const KNN_K: 8;