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.
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 |
@@ -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 |
@@ -485,7 +486,7 @@ if (result.error?.startsWith('halt:')) {
485
486
 
486
487
  **Why four pieces (`policy` + `onLlmResult` + `onToolResult` + `filterTools`).** `policy` runs `gate.check` *before* every tool call. `onLlmResult` fires after every successful `provider.generate` — without it, `budget.maxCostUsd` never sees LLM cost and is silently undercounted for token-heavy / tool-light workloads (every chatbot). It also fires for the out-of-band `ctx.summarize` call (R-C6) tagged `kind:'summarize'`; main-loop rounds carry `kind:'turn'` — so summary-window tokens count against the budget too, and a consumer can tell the two apart. `onToolResult` fires after every `tool.execute` and carries the per-run `ctx` opaque blob into `gate.record` so per-principal accounting works. `filterTools` is a `gate.allows` pre-filter — denied tools are dropped from the catalog the LLM ever sees, no `gate.check` round-trip per call.
487
488
 
488
- `onToolResult` on a tool ERROR records `{error, durationMs}` plus an allow-listed `errorContext` copied from `error.context` — `timeout`/`denied` (boolean), `server`/`tool` (string, ≤200 chars), `timeoutMs` (finite number); wrong-typed values are dropped and `stderr`/everything else is never forwarded (the gate writes the record verbatim into the audit row). The key is absent when no allowed field is present.
489
+ `onToolResult` on a tool ERROR records `{error, durationMs}` plus an allow-listed `errorContext` copied from `error.context` — `timeout`/`denied`/`shrink` (boolean), `server`/`tool` (string, ≤200 chars), `timeoutMs`/`oldBytes`/`newBytes`/`oldLines`/`newLines` (finite number; the last four are BA-30 `shrinkGuard` refusal facts); wrong-typed values are dropped and `stderr`/everything else is never forwarded (the gate writes the record verbatim into the audit row). The key is absent when no allowed field is present.
489
490
 
490
491
  Halt-severity decisions exit the loop cleanly via a typed `HaltError` — full mechanics (sealed `msgs`, `halt:<rule>` error token, `loop:done{halted:true}` event, `throwOnError:true` interaction, `halt:unknown` coalesce) are in the **Halt decisions throw `HaltError`** paragraph below. Short version: check `result.error?.startsWith('halt:')` after the run.
491
492
 
@@ -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`.
@@ -1492,6 +1461,8 @@ Mobile tools follow the observe-act pattern: action tools auto-return a fresh sn
1492
1461
  >
1493
1462
  > **`resolveToolPath(p)`** — exported alongside `createShellTools` from `bare-agent/tools`. THE canonicalizer every shell file tool applies internally before opening: expand `~`/`~/…` via `os.homedir()` (throws rather than silently degrading `~/x` to `/x` when no home directory can be determined), then `path.resolve` against `process.cwd()`. Idempotent; rejects a non-string/empty path (thrown, naming only the type/category of the bad value, never the value itself) — every file tool routes through it, so `shell_read`/`shell_grep` with `""` now error instead of silently reading/searching `process.cwd()`. Call it in your `actionTranslator` on `args.path` before returning the gated action, so the string the gate judges is the exact string the tool opens.
1494
1463
 
1464
+ > **Opt-in `shrinkGuard` (BA-30) — refuse a whole-file `shell_write` that would gut an existing file.** `createShellTools({ shrinkGuard: true })` (= `{ minOldBytes: 2048, maxShrinkRatio: 0.5 }`; an object overrides either, plus `guardPath(absPath) => boolean | Promise<boolean>` — `false` skips the guard for that file, e.g. a worker's own earlier output). `guardPath` sees the lexical path, not the realpath; realpath inside the predicate (or exempt-list rather than guard-list) if aliases matter. Bytes decide: if the existing file is `>= minOldBytes` and the new content is `< old * maxShrinkRatio`, the write is refused (a thrown `ToolError`, so `maxIdenticalToolErrors` applies) and the file is left byte-identical. The message names the old/new bytes and lines and points at `shell_edit`, `append:true`, or `content:''`; `error.context` is `{ shrink: true, oldBytes, newBytes, oldLines, newLines }` — numbers only, no path or content — and `wireGate`'s `errorContext` forwards those five fields to the audit row. Skipped for `append:true`, `content:''`, a new file, and a non-regular target. There is deliberately no override flag the model can set. Size is measured at call time (`lstat` under `noFollowSymlinks`, never through a symlink); a stat error other than ENOENT rejects. Lines are counted only on refusal, with a bounded read (`N+ lines` when capped). A throwing or non-boolean `guardPath` rejects the write (type only); `HaltError` propagates. Unset is byte-identical; `false` is off (same as unset); any other shape throws `ValidationError` at creation. `shell_edit` is unaffected.
1465
+
1495
1466
  > **⚠️ `shell_write` requires `content` — and a gate cannot cover for it (v0.27+).** `content` used to default to `''`, so a tool call that OMITTED it silently overwrote the target with **zero bytes** and returned `"wrote 0 bytes to <path>"` as success. That is the ordinary shape of a model hitting its **output-token cap** mid-generation on a long file — observed live emptying a 1789-line source file. **No policy can catch it:** a 0-byte write is a *legal* write, and bareguard's `fs` primitive judges `{type:'write', path}` without inspecting the body (the gate correctly `allow`s it). `shell_write` now **rejects** an absent, `null`, or non-string `content` and leaves the file byte-identical; the error tells the model to retry with the full content. An explicit `content: ""` still empties the file — that one is deliberate.
1496
1467
 
1497
1468
  > **`shell_edit` — the surgical write (BA-13).** Changing one line of an 800-line file with `shell_write` forces the model to re-emit **all 800 lines** as tool-call JSON: an output-token tax ∝ file size (output is the expensive token class), paid on every revision, and the maximal broken-tree surface (a truncated rewrite mangles the lines it never meant to touch — the BA-4/BA-6 class). `shell_edit({path, oldText, newText})` emits only the anchor + replacement. Semantics worth knowing: `oldText` must match **exactly once** (a 0/2+ match is a refusal *returned as the tool result*, so the loop continues and the model widens the anchor — not a throw, so a repeated-identical miss is bounded by maxTurns/budget, not the spin guard); missing/empty `oldText` or missing/non-string `newText` **throw** (BA-4 guards; `newText:""` is a legal deletion); the write is **atomic** (sibling temp + rename, mode preserved) so an fs failure never leaves a partial file; and `newText` is a **literal splice** (a `$&`/`$1` in it lands verbatim, unlike `String.replace`). Gate it exactly like `shell_write` but as `{type:'edit'}` — **bareguard gates `edit` by the same `fs.writeScope` as `write` with zero config** (its FS primitive's `FS_TYPES` already includes `edit`).
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.58.0",
3
+ "version": "0.60.0",
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",
@@ -141,8 +141,8 @@
141
141
  "category": "tools",
142
142
  "when": "you want to give an agent shell/file tools (read, grep, write, edit, run, exec) — cross-platform, pure Node, zero deps",
143
143
  "import": "import { createShellTools } from 'bare-agent/tools'",
144
- "signature": "createShellTools(options?: {noFollowSymlinks?: boolean, canRead?: CanRead}) => {tools: ToolDef[]}",
145
- "fails": "never throws at creation; gating is the caller's via Loop({ policy }) and fs.writeScope, shell_edit refuses a non-unique anchor as a tool result (file untouched), and with noFollowSymlinks:true the four file tools throw ELOOP on a symlinked final path component.",
144
+ "signature": "createShellTools(options?: {noFollowSymlinks?: boolean, canRead?: CanRead, shrinkGuard?: true|{minOldBytes?: number, maxShrinkRatio?: number, guardPath?: (absPath: string) => boolean|Promise<boolean>}}) => {tools: ToolDef[]}",
145
+ "fails": "throws ValidationError at creation for a non-function canRead or a bad shrinkGuard shape; gating is the caller's via Loop({ policy }) and fs.writeScope, shell_edit refuses a non-unique anchor as a tool result (file untouched), and with noFollowSymlinks:true the four file tools throw ELOOP on a symlinked final path component.",
146
146
  "example": "const { tools } = createShellTools();\nconst loop = new Loop({ provider, tools, policy });\nconst { tools: safeTools } = createShellTools({ noFollowSymlinks: true });"
147
147
  },
148
148
  {
@@ -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",
@@ -47,6 +47,8 @@ function safeStringify(value) {
47
47
  // its result verbatim to the audit log. Anything not listed here, or of the wrong type, is dropped.
48
48
  const ERROR_CONTEXT_KEYS = /** @type {const} */ ({
49
49
  timeout: 'boolean', denied: 'boolean', server: 'string', tool: 'string', timeoutMs: 'number',
50
+ // BA-30 shrinkGuard refusal facts (numbers/boolean only — never a path or content).
51
+ shrink: 'boolean', oldBytes: 'number', newBytes: 'number', oldLines: 'number', newLines: 'number',
50
52
  });
51
53
  const ERROR_CONTEXT_MAX_STR = 200;
52
54