harness-only scripted model: answers every model request from fixtures

A Claude Code plugin that makes Claude plan, test, review and merge like a disciplined team, enforced in code, not prompts.
.cadre/state (not committed). No database, no extra tool to install.[RUN] cadre · p3 auth-login · strict · contained ✓ · ctx 34% · cache 87%
✓a1 ✓a4 ✓a7 │ ▶a2 ✓a3 │ ⏸a6 ◌a5 4/7 done · ▶1 ⏸1 ◌1
[1] Epic [7] Plan [8] Doctor · p3 · epic/p3-auth-login · 4/7 done
┌────────────────┐ ┏━━━━━━━━━━━━━━━━┓ ┌────────────────┐
│a1 feat [OK]✓│ ┃a2 feat [RUN]▶┃ │a6 feat [WAIT]⏸│
│Add login │━━┳━▶┃Session refresh ┃──┬─▶│Remember me │
│●●●●●● merged │ ┃ ┃●●◉○○○ implement┃ ┃ │○○○○○○ waits a2 │
└────────────────┘ ┃ ┗━━━━━━━━━━━━━━━━┛ ┃ └────────────────┘
claude plugin marketplace add it-dainb/cadre
claude plugin install cadre@cadre
Then, inside Claude Code:
/cadre setup: once per machine. Claude checks your tools and fixes what it can, in the open, and asks your default mode and limits; you confirm the settings in a dialog./cadre <goal in plain words>, e.g. /cadre fix the off-by-one in src/page.ts. In a repo cadre hasn't seen, one dialog asks to set it up first: Claude prepares the task store, your build and test commands and a changelog in the open, you confirm the safety settings (they also turn off Claude Code's built-in task tools for this project: Claude plans with cadre's own tools), and then the plan comes up with its mission for one approval. Claude picks a lane and says why:/cadre deep <goal> talks it through instead: one question per round at the weakest point, with the scores shown, until it is clear, 8 rounds pass, or you say "enough". Settings → Planning. The lane shows in the approval dialog, with an option to change it; type something instead to ask Claude for a change. Breaking, security, public contract changes and plans of 3+ tasks are always full./cadre <goal>): Claude carries the plan until it lands on dev and asks you only at the critical points: a change to the agreed spec, a question only you can answer, an integration that fails twice, a protected branch moved outside cadre, and the release./cadre yolo <goal>): after the approval nothing is asked. Claude decides spec changes and blocked questions itself and each decision is recorded (Activity, Doctor) for you to review. It stops, never releases, when the plan lands on dev. To make yolo your default, set Drive → mode to yolo in Settings (9); a repo's committed config can only force auto. Both stop by themselves when an agent moves a protected branch, the sandbox settings change, or a bound is hit (100 turns, $20, 240 minutes, or 3 turns without progress; Settings → Drive). The band shows auto · turn 12/100 · $1.20 · 0: stop; 0 stops and resumes./cadre alone opens the pane. Those forms (/cadre, /cadre <goal>, /cadre yolo <goal>, /cadre deep <goal>, setup, init, doctor, continue) are all you type; every decision is answered in a dialog. It opens once by itself; after that 1 (on the band or in the pane) opens it again, and the pane lists everything that needs you.
plan → your approval → tester (test goes red) → worker (goes green)
→ independent reviewer → merge into the epic branch
→ epic lands on dev → you release
| Who | Does |
|---|---|
| You | Approve plans, resolve flags, cut releases. Every one is a dialog answer. |
| Main Claude | Plans and manages with cadre's tools (plan, task, epic, amend, explore, ask, status). It never edits code, has no shell and starts no agent of its own to explore: it asks cadre's explorer. |
| Worker agents | Tester writes the test, worker writes the code, reviewer checks it. Each works in its own worktree. |
| cadre itself | Owns git (workers cannot commit or push), runs the checks, enforces every step; pushes only when you set landing.mode to pr. |
More: the loop in detail.
Lessons. cadre learns on its own: after a plan lands, a short side-model pass (lessons.model, lessons.passesPerDay; 0 turns it off) turns what went wrong, and what you changed, into short lessons that later task briefs carry by path (at most 1.5 KB). One that repeats or is critical moves to your user scope. The Lessons tab shows them; x prunes one for good.
| Type this | What it does |
|---|---|
/cadre setup | One-time machine setup. Details |
/cadre | One line: where things stand and what to type next; opens the pane. |
/cadre init | Re-run the repo setup on purpose (a first /cadre <goal> does it for you). A project set up by an older cadre asks for it once (a toast and a Doctor line); restart Claude Code after its confirm. |
/cadre doctor | Read-only health check. Safe any time. |
/cadre <goal> · /cadre yolo <goal> | Start work; after approval it runs to dev, asking at the critical points (auto) or not at all (yolo). |
/cadre deep <goal> | Talk the goal through first (one question per round, scores shown), then the plan comes up as usual. |
/cadre continue | Pick up a plan an earlier session left (also 0 on the band). |
/cadre open · /cadre status | Open the board pane · print the board as text. |
| Settings | Press 9 in the pane: every setting, where its value comes from, and buttons to change it. |
Every decision is a dialog (1 opens it). The typed fallbacks, config keys and the extension protocol are in docs/commands.md.
Set in .cadre/config.json (the setup writes it; edit it by hand to change it):
units: the parts of the repo that build and test on their own, each with its root, its setup command, its runner (junit or text), an optional concurrency cap and its checks (test, …). A unit has a kind (package, service, submodule, app); packages was renamed to units; a git submodule is a unit with ownGit: true, and its work lands in its own repository before the parent's pointer moves. A task belongs to the units its files fall in; a task that spans several runs every one's checks before it merges. routing.<role> picks a model and effort for that unit's agents.landing.mode: direct (default) lands a finished plan on dev locally. pr pushes it to landing.remote and opens one pull request into dev (needs gh, signed in); cadre merges it when the checks pass (and, with landing.review: true, once it is approved), and takes the usual red path when they fail. cadre never pushes in direct mode.0 on the band (0: stop); 0: resume starts it again with a fresh budget./clear or compaction: nothing to do. Running agents keep working and the run goes on.claude --continue later: the new session shows Unfinished plan … · /cadre continue to pick it up and 0: continue on the band. Nothing restarts by itself. /cadre continue (or 0) re-arms the run in its mode (auto or yolo) and respawns each task that was in flight. Each new agent starts from a checkpoint commit of the old one's worktree, with the diff and the last failing check, so nothing is redone. No waiting for old claims to expire./cadre continue elsewhere says so and takes nothing.usage limit until HH:MM UTC on the band) and goes on by itself then; nothing is charged to the task. 0: resume goes on at once.dev (or main) checked out when work lands, cadre leaves your branch, index and files alone and asks in one dialog: Land brings it into your checkout, keeping your commits and your uncommitted edits (an edit to the same file refuses, and the dialog says so). Switch to another branch and it lands by itself. A release waits until it is in.limits.silentRuns (runs without a report before a task blocks) and limits.startFails (failed starts before the run stops) are in Settings.git.cadre/state lives.bwrap (bubblewrap) and socat for sandboxed checks. macOS: setup tells you what is needed.Security note: the dependency install a task may ask for runs isolated (clean environment, your home hidden, no scripts, registry packages only) but with network access, because it must reach the package registry. On a cloud host the cloud metadata endpoint is therefore reachable from it.
/cadre doctor first. It lists every failing check and how to fix it. The full report is in the pane's Doctor tab./cadre <goal> sets it up and plans the goal.~/.cache/cadre/fix/. Read it, then run the line Claude shows you, e.g. sudo sh ~/.cache/cadre/fix/bwrap-apparmor.sh.landing.mode: pr).Read more: DESIGN · UI design · decisions (ADRs) · UI dev loop · test harness · module contracts
You need the Claude Code 2.1.295 binary (not whatever claude is on PATH).
CC=<path to claude 2.1.295>
node scripts/budget.mjs # size budget
$CC plugin validate --strict . && $CC plugin test .
$CC --plugin-dir . # try it in the repo you want to manage
node --experimental-transform-types scripts/ui-dev.mjs # the pane in your terminal, hot reload
Live runs go through Docker: harness/run.sh (see harness/README.md).
Version 0.14.0. Pre-1.0, pinned to Claude Code 2.1.295 (agent exits tested up to 2.1.299). License: not chosen yet.
hooks/register.ts 203 lines1// Harness-only scripted model (S0): answers every model request at turn.step (TM-04) from the fixtures below, never calling next, so no request
2// reaches the API (PROXY=1's effort.jsonl stays empty). Each answer is a function of the loop's own transcript ($.session.messages), never of a
3// counter: a resumed or nudged agent gets the answer its transcript calls for. Loaded with a second --plugin-dir AFTER cadre's, so it sits inner to
4// cadre in the user tier (load order): cadre's turn.step sees each scripted response come up from beneath (its cost ledger records `model: scripted`).
5// Every line it logs starts with SCRIPTED (debug log). `/s0 <end|hb|wedge>` is the forced-exit / TaskStop probe (RESULTS.md (c), (d)).
6// The script is chosen per cell by the repo's `.git/scripted.json` ({"script": …}, written by a harness/fixtures/scripted overlay), default `lite`:
7// docs: lite, a docs task (no tester, no red): the worker writes docs/usage.md; lite: main plans one lite task; full: a full-lane task (tester, worker, reviewer); loop: lite, the worker calls the same tool forever (the repeat-call breaker, then forced exit);
8// limit: lite, the first worker's first step goes to the proxy, which answers a usage limit (stub-proxy.mjs); slow: lite, the worker waits 12 s first;
9// silent: lite, the worker writes its files and stops without a report, every time (the report-less end);
10// holds: full lane, one task with S1 (new) and S2 (already true, metadata.holds): the tester's S2 test passes at red, S1's fails (holds-scenario);
11// shape: lite, the worker sends four reports with an over-long summary (a shape refusal each, never the run's tries), then the valid one (shape-refusal-budget);
12// pair: full lane, two independent tasks (concurrency-fifo, with concurrency.default 1 in the repo's config);
13// needs: lite, the worker first asks the explore helper (report outcome request), and writes its files once it is answered (needs-explore);
14// stray: lite, the worker asks for [npm install ms] twice: the second changes no file, and its reply says what the manifest holds (setup-stray-manifest);
15// setup: the worker asks for an install with its argv (a global one first: refused at once; then [npm install ms]); cadre installs it from the real registry, no helper (needs-setup-s);
16// multi: full lane, two tasks (kebabCase after titleCase), an amend on a stale revision refused then retried (plan-tools-full);
17// probe: a milestone of two epics (the second after the first); the epic's planner asks the probe helper first, and drafts its tasks once it is answered (planner-probe);
18// sub: lite, the task in the `lib` submodule unit (submodule-unit); cont: lite, the reviewer waits 14 s first (continue-after-quit-s kills before or during it).
19import type { Register } from 'claude-code'
20
21type Row = { role: 'user' | 'assistant'; text: string; toolUses?: { tool: string; input?: any }[]; toolResults?: { text?: string; isError?: boolean }[] }
22type Act = { text?: string; tool?: string; input?: unknown }
23const U = { input_tokens: 7, output_tokens: 3, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, model: 'scripted' } // tokensOf = 7 + 5*3 = 22 per step
24const L = ($: any, t: string) => $.ui.log(`SCRIPTED ${t}`)
25const id = () => `toolu_s0${crypto.randomUUID().replace(/-/g, '').slice(0, 20)}`
26const isText = (r: Row) => r.role === 'user' && !r.toolResults?.length && !!r.text
27const since = (rows: Row[]) => { let i = rows.length - 1; while (i > 0 && !isText(rows[i])) i--; return rows.slice(i) } // from the last prompt/brief/nudge on
28const done = (rows: Row[]) => rows.filter(r => r.role === 'assistant').length
29const END = 'Done. Stopping here.'
30let script = 'lite', injected = false
31const cwds: Record<string, string> = {} // agentId -> the folder cadre spawned it in (agent.spawn): the tester writes there by its full path
32
33// ---- fixtures: titleCase(s) on the `single` repo, lite lane ----
34const GOAL = /Goal from the user/
35function main(rows: Row[]): Act {
36 // custom-role: main calls the user's read-only role once (an Agent of type cadre:auditor), then ends; the answer is that Agent's result
37 if (script === 'custom-role') {
38 const m = rows.map(r => isText(r) && /S0-AUDIT/.test(r.text)).lastIndexOf(true); if (m < 0) return { text: 'OK.' }
39 return rows.slice(m + 1).some(r => r.role === 'assistant' && r.toolUses?.some(c => c.tool === 'Agent')) ? { text: END } : { tool: 'Agent', input: { description: 'audit the slug helper', subagent_type: 'cadre:auditor', prompt: 'List the risks of src/slug.mjs, one line each.' } }
40 }
41 // the tool-surface probe (probes/0.15): main asks for Agent once; under a settings deny the call comes back refused
42 const m = rows.map(r => isText(r) && /S0-PROBE main-agent/.test(r.text)).lastIndexOf(true), g = rows.map(r => isText(r) && GOAL.test(r.text)).lastIndexOf(true)
43 if (m > g) return rows.slice(m + 1).some(r => r.role === 'assistant') ? { text: END } : { tool: 'Agent', input: { description: 's0 main agent', subagent_type: 'general-purpose', prompt: 'S0-PROBE tag=end. Do the task you are given.' } }
44 if (g < 0) return { text: 'OK.' }
45 const after = rows.slice(g + 1), calls = after.flatMap(r => (r.role === 'assistant' ? r.toolUses ?? [] : []))
46 const has = (f: (c: { tool: string; input?: any }) => boolean) => calls.some(f)
47 const T = (n: string) => `mcp__cadre__${n}`, used = (n: string) => has(c => c.tool === T(n)) // main plans only through cadre's tools: plan, task, explore, ask
48 const ai = after.findIndex(r => r.role === 'assistant' && r.toolUses?.some(c => c.tool === T('explore')))
49 const answered = ai >= 0 && after.slice(ai + 1).some(r => isText(r) && /Result of ask-|its answer was already given/.test(r.text)) // the explorer's answer comes back as a message of its own
50 if (after.filter(r => r.role === 'assistant').length > (script === 'multi' ? 12 : script === 'pair' ? 12 : 8)) return { text: 'Stopping: approve the plan in the dialog.' }
51 if (ai < 0) return { tool: T('explore'), input: { question: 'What in the project does adding titleCase(s) touch: where string helpers live, how they are exported, where the tests are?' } }
52 if (!answered) return { text: 'Waiting for the explorer.' }
53 if (!used('ask')) return { tool: T('ask'), input: { clarity: { outcome: 1, scope: 1, acceptance: 1, constraints: 1 } } }
54 const mission = /There is no mission yet/.test(rows[g].text) ? { mission: 'Goal: add titleCase(s) to the library\nConstraints: none\nNon-goals: none' } : {}
55 if (script === 'probe') { // a milestone: two epics (the second after the first), the critic's review, then main waits for the roadmap's dialog
56 const n = (t: string) => calls.filter(c => c.tool === T(t)).length, ids = after.flatMap(r => (r.role === 'user' ? r.toolResults ?? [] : [])).map(r => r.text ?? ''), id = (k: number) => ids.filter(x => /"id":\s*"/.test(x))[k]?.match(/"id":\s*"([^"]+)"/)?.[1]
57 const rev = Math.max(1, ...ids.map(x => +(x.match(/"revision":\s*(\d+)/)?.[1] ?? 0)), 0)
58 if (!used('plan')) return { tool: T('plan'), input: { title: 'Add two string helpers to the library', description: 'wordCount(s) and truncate(s, n), each with node:test tests.', lane: 'milestone', reason: 'two separate features', ...mission } }
59 if (n('epic') < 2) return { tool: T('epic'), input: { ...EPICS[n('epic')], ...(n('epic') ? { after: [id(1)] } : {}) } }
60 if (n('explore') < 2) return { tool: T('explore'), input: { question: `Review this roadmap for gaps, overlaps and a wrong order: ${EPICS.map((e, i) => `${i + 1}. ${e.title}: ${e.goal} (files ${e.paths.join(', ')})`).join('; ')}` } }
61 if (after.filter(r => isText(r) && /Result of ask-|its answer was already given/.test(r.text)).length < 2) return { text: 'Waiting for the critic.' }
62 if (!used('amend')) return { tool: T('amend'), input: { id: id(0), expectedRevision: rev, critique: 'The critic found no gaps or overlaps: the order stands.' } }
63 return { text: 'The roadmap is drafted: approve it in the dialog (key 1 opens it).' }
64 }
65 if (script === 'multi') { // res: the k-th result of a tool's calls (its text, whether refused)
66 const n = (t: string) => calls.filter(c => c.tool === T(t)).length
67 const res = (t: string, k: number) => { let j = -1; for (let i = 0; i < after.length; i++) if (after[i].role === 'assistant' && after[i].toolUses?.some(c => c.tool === T(t)) && ++j === k) return after[i + 1]?.toolResults?.[0] }
68 const num = (t: string, k: number, re: RegExp) => res(t, k)?.text?.match(re)?.[1]
69 if (!used('plan')) return { tool: T('plan'), input: { title: 'Add titleCase(s) and kebabCase(s) to the library', description: 'Two public string helpers with node:test tests.', lane: 'full', reason: 'two new public functions', ...mission } }
70 if (n('task') < 2) return { tool: T('task'), input: { ...TASKS[n('task')], ...(n('task') ? { after: [num('task', 0, /"id":\s*"([^"]+)"/)] } : {}) } }
71 const b = num('task', 1, /"id":\s*"([^"]+)"/), desc = `${TASKS[1].description} Trim the input first.`
72 if (!n('amend')) return { tool: T('amend'), input: { id: b, expectedRevision: +(num('plan', 0, /"revision":\s*(\d+)/) ?? 1), description: desc } } // the revision main read at plan time: stale by now
73 if (n('amend') === 1 && /call again with expectedRevision \d+/.test(res('amend', 0)?.text ?? '')) return { tool: T('amend'), input: { id: b, expectedRevision: +(num('amend', 0, /call again with expectedRevision (\d+)/) ?? 0), description: desc } } // refused as stale: retry with the revision it names
74 return { text: 'The plan is drafted: approve it in the dialog (key 1 opens it).' }
75 }
76 if (script === 'pair') {
77 if (!used('plan')) return { tool: T('plan'), input: { title: 'Add two string helpers to the library', description: 'Two public string helpers with node:test tests.', lane: 'full', reason: 'two new public functions', ...mission } }
78 if (calls.filter(c => c.tool === T('task')).length < 2) return { tool: T('task'), input: TASKS[calls.filter(c => c.tool === T('task')).length] }
79 return { text: 'The plan is drafted: approve it in the dialog (key 1 opens it).' }
80 }
81 if (script === 'full' || script === 'holds') {
82 if (!used('plan')) return { tool: T('plan'), input: { title: 'Add titleCase(s) to the library', description: 'A new public function titleCase(s) with node:test tests.', lane: 'full', reason: 'a new public function', ...mission } }
83 if (!used('task')) return { tool: T('task'), input: script === 'holds' ? { ...TASKS[0], scenarios: [...TASKS[0].scenarios, "S2: Given ' Hello World ' When slug is called Then it returns 'hello-world'"], holds: ['S2'] } : TASKS[0] }
84 return { text: 'The plan is drafted: approve it in the dialog (key 1 opens it).' }
85 }
86 if (!used('plan') && script === 'docs') return { tool: T('plan'), input: { title: 'Document the library in docs/usage.md', description: 'Add docs/usage.md: one section that says what the library is for and how to import it.', lane: 'lite', reason: 'one small document', type: 'docs', changelog: { none: true, reason: 'documentation only' }, ...mission } }
87 if (!used('plan')) {
88 return { tool: T('plan'), input: { title: 'Add titleCase(s) with tests', description: 'Add titleCase(s) as a named export in src/titleCase.mjs, in the style of src/slug.mjs, with node:test tests in test/titleCase.test.mjs.',
89 lane: 'lite', reason: 'one small function and its test', type: 'feature', ...(script === 'sub' ? { package: 'lib' } : {}), changelog: { category: 'Added', entry: 'titleCase(s) capitalises the first letter of each word' }, ...mission } }
90 }
91 return { text: 'The plan is drafted: approve it in the dialog (key 1 opens it).' }
92}
93const EPICS = [{ title: 'wordCount(s)', goal: 'wordCount(s) in src/words.mjs returns the number of words in s', size: 1, paths: ['src/words.mjs', 'test/words.test.mjs'] },
94 { title: 'truncate(s, n)', goal: 'truncate(s, n) in src/truncate.mjs cuts s to n characters and ends it with "..."', size: 1, paths: ['src/truncate.mjs', 'test/truncate.test.mjs'] }]
95// the function a brief is about (multi: kebabCase is the second task), its test and files
96type Fn = { name: string; title: string; input: string; out: string; impl: string; what: string; lit?: string } // lit: the expected value as code, when it is no string
97const FNS: Fn[] = [ // wordCount is the probe script's task (its epic's planner drafts it); fnOf picks it by name
98 { name: 'titleCase', title: 'S1: titleCase capitalises each word', input: 'hello big world', out: 'Hello Big World', impl: String.raw`s => s.replace(/(^|\s)(\S)/g, (_, a, b) => a + b.toUpperCase())`, what: 'uppercase the first letter of each whitespace-separated word, leave the rest unchanged' },
99 { name: 'kebabCase', title: 'S1: kebabCase joins the words with dashes', input: 'Hello Big World', out: 'hello-big-world', impl: String.raw`s => s.trim().toLowerCase().split(/\s+/).join('-')`, what: 'lowercase the words and join them with dashes' },
100 { name: 'wordCount', title: 'S1: wordCount counts the words', input: 'a b c', out: '3', lit: '3', impl: String.raw`s => s.trim().split(/\s+/).length`, what: 'count the whitespace-separated words' },
101]
102const fnOf = (brief: string) => (/wordCount/.test(brief) ? FNS[2] : /kebabCase/.test(brief) ? FNS[1] : FNS[0])
103const TEST = (f: Fn) => `import { test } from 'node:test'
104import assert from 'node:assert/strict'
105import { ${f.name} } from '../src/${f.name}.mjs'
106test('${f.title}', () => assert.equal(${f.name}('${f.input}'), ${f.lit ?? `'${f.out}'`}))
107`
108// the test file only when there is none (full lane: the tester's is locked)
109const FILES = (f: Fn) => `mkdir -p src test && cat > src/${f.name}.mjs <<'EOF'
110export const ${f.name} = ${f.impl}
111EOF
112test -f test/${f.name}.test.mjs || cat > test/${f.name}.test.mjs <<'EOF'
113${TEST(f)}EOF`
114const TASKS = FNS.map(f => ({ title: `${f.name}(s) with node:test tests`, description: `Create src/${f.name}.mjs exporting ${f.name}: ${f.what}.`, type: 'feature', package: '.',
115 paths: [`src/${f.name}.mjs`, `test/${f.name}.test.mjs`], scenarios: [`S1: Given '${f.input}' When ${f.name} is called Then it returns '${f.out}'`],
116 changelog: { category: 'Added', entry: `${f.name}(s): ${f.what}` }, interface: { symbols: [{ name: f.name, kind: 'function', params: ['s: string'], returns: 'string', status: 'new' }] } }))
117const taskOf = (brief: string) => brief.match(/TASK-([a-z][\w-]*\w)/)?.[1] // ids are c-6-1, m-2: a letter first, a word char last
118const WAIT = { tool: 'Bash', input: { command: 'node -e "setTimeout(() => {}, 12000)"', description: 'Wait' } }
119const ROLES: Record<string, (k: number, brief: string, cwd: string, rows: Row[]) => Act> = {
120 worker: (k, b, _c, rows) => { if (script === 'docs') return [{ tool: 'Bash', input: { command: "mkdir -p docs && printf '# Usage\\n\\nImport the helpers from src/ and call them.\\n' > docs/usage.md", description: 'Write docs/usage.md' } }, { tool: 'mcp__cadre__report', input: { schemaVersion: 1, role: 'worker', outcome: 'done', summary: 'Added docs/usage.md.', risks: [] } }][k] ?? { text: END }
121 const f = fnOf(b), w = { tool: 'Bash', input: { command: FILES(f), description: `Write ${f.name} and its test` } }
122 const answered = rows.some(r => isText(r) && /Answer to your request/.test(r.text)) // the answer comes back as a message of its own: after it the worker goes on
123 const req = (request: unknown, summary: string) => ({ tool: 'mcp__cadre__report', input: { schemaVersion: 1, role: 'worker', outcome: 'request', summary, request } })
124 if (script === 'setup' && !answered) return [{ tool: 'Bash', input: { command: 'env | grep -E "^(npm_config_offline|npm_config_cache|npm_config_logs_dir|UV_OFFLINE|UV_CACHE_DIR|PIP_NO_INDEX|CARGO_NET_OFFLINE|GOPROXY|YARN_ENABLE_OFFLINE_MODE)=" | sort', description: 'Show the package manager settings' } }, // the settings this agent's shell starts with
125 req({ helper: 'setup', ask: 'add ms', why: `${f.name} needs the ms package`, argv: ['npm', 'install', '-g', 'ms'] }, 'I need the ms package installed.'), // refused at once (a global install): the report comes back with the allowed forms
126 req({ helper: 'setup', ask: 'add ms', why: `${f.name} needs the ms package`, argv: ['npm', 'install', 'ms'] }, 'I need the ms package installed.')][k] ?? { text: END }
127 const nAnswers = rows.filter(r => isText(r) && /Answer to your request/.test(r.text)).length
128 if (script === 'stray' && nAnswers < 2) return [req({ helper: 'setup', ask: 'add ms', why: `${f.name} needs the ms package`, argv: ['npm', 'install', 'ms'] }, 'I need the ms package installed.')][k] ?? { text: END } // asked again after the first answer: nothing left to change
129 if (script === 'needs' && !answered) return [req({ helper: 'explore', ask: 'Where do the string helpers live and how are they exported?', why: `I add ${f.name} next to them`, paths: ['src/'] }, 'I need to know where string helpers live.')][k] ?? { text: END }
130 const BAD = { tool: 'mcp__cadre__report', input: { schemaVersion: 1, role: 'worker', outcome: 'done', summary: 'x'.repeat(801) } }
131 if (script === 'shape') return [w, BAD, BAD, BAD, BAD, { tool: 'mcp__cadre__run_check', input: { name: 'test', task: taskOf(b) } }, { tool: 'mcp__cadre__report', input: { schemaVersion: 1, role: 'worker', outcome: 'done', summary: `Added ${f.name}(s) in src/${f.name}.mjs with a node:test test; npm test passes.`, risks: [] } }][k] ?? { text: END }
132 return script === 'silent' ? [w][k] ?? { text: END } : script === 'loop' ? { tool: 'mcp__cadre__run_check', input: { name: 'test', task: taskOf(b) } } : (script === 'slow' ? [WAIT] : []).concat([w, { tool: 'mcp__cadre__run_check', input: { name: 'test', task: taskOf(b) } },
133 { tool: 'mcp__cadre__report', input: { schemaVersion: 1, role: 'worker', outcome: 'done', summary: `Added ${f.name}(s) in src/${f.name}.mjs with a node:test test; npm test passes.`, risks: [] } }])[k] ?? { text: END } },
134 tester: (k, b, cwd) => { const f = fnOf(b)
135 if (script === 'holds') return [{ tool: 'Write', input: { file_path: `${cwd}/test/${f.name}.test.mjs`, content: `import { test } from 'node:test'\nimport assert from 'node:assert/strict'\nimport { slug } from '../src/slug.mjs'\ntest('S1: ${f.name} capitalises each word', async () => { const m = await import('../src/${f.name}.mjs'); assert.equal(m.${f.name}('${f.input}'), '${f.out}') })\ntest('S2: slug still trims and lowercases', () => assert.equal(slug(' Hello World '), 'hello-world'))\n` } },
136 { tool: 'mcp__cadre__report', input: { schemaVersion: 1, role: 'tester', outcome: 'done', summary: 'S1 fails now, S2 holds already.', tests: [{ path: `test/${f.name}.test.mjs`, name: `S1: ${f.name} capitalises each word`, scenario: 'S1' }, { path: `test/${f.name}.test.mjs`, name: 'S2: slug still trims and lowercases', scenario: 'S2' }], run: { command: ['node', '--test', '--test-reporter=junit', '--test-reporter-destination=$CADRE_JUNIT', `test/${f.name}.test.mjs`], junit: '$CADRE_JUNIT' } } }][k] ?? { text: END }
137 return [{ tool: 'Write', input: { file_path: `${cwd}/test/${f.name}.test.mjs`, content: TEST(f) } },
138 { tool: 'mcp__cadre__report', input: { schemaVersion: 1, role: 'tester', outcome: 'done', summary: `One test per scenario in test/${f.name}.test.mjs.`, tests: [{ path: `test/${f.name}.test.mjs`, name: f.title, scenario: 'S1' }], run: { command: ['node', '--test', `test/${f.name}.test.mjs`] } } }][k] ?? { text: END } },
139 reviewer: (k, b) => { if (script === 'docs') return [{ tool: 'mcp__cadre__report', input: { schemaVersion: 1, role: 'reviewer', verdict: 'pass', summary: 'The commit adds docs/usage.md only.', findings: [], coverage: [], contractStatus: [] } }][k] ?? { text: END }
140 const f = fnOf(b), full = ['full', 'multi', 'pair', 'probe', 'holds'].includes(script); return [{ tool: 'mcp__cadre__run_check', input: { name: 'test', task: taskOf(b) } },
141 { tool: 'mcp__cadre__report', input: { schemaVersion: 1, role: 'reviewer', verdict: 'pass', summary: `The commit adds ${f.name} and its test only; npm test passes.`, findings: [], coverage: full ? [{ scenario: 'S1', test: f.title, ok: true }, ...(script === 'holds' ? [{ scenario: 'S2', test: 'S2: slug still trims and lowercases', ok: true }] : [])] : [], contractStatus: full ? [{ name: f.name, ok: true }] : [] } }][k] ?? { text: END } },
142 planner: (k, _b, _c, rows) => rows.some(r => isText(r) && /Answer to your request/.test(r.text))
143 ? [{ tool: 'mcp__cadre__report', input: { schemaVersion: 1, role: 'planner', summary: 'One task.', tasks: [{ subject: 'wordCount(s) with node:test tests', description: 'Create src/words.mjs exporting wordCount: the number of whitespace-separated words in s.',
144 metadata: { type: 'feature', package: '.', paths: ['src/words.mjs', 'test/words.test.mjs'], scenarios: ["S1: Given 'a b c' When wordCount is called Then it returns 3"], changelog: { category: 'Added', entry: 'wordCount(s): the number of words in s' },
145 interface: { symbols: [{ name: 'wordCount', kind: 'function', params: ['s: string'], returns: 'number', status: 'new' }] } } }] } }][k] ?? { text: END } // after the probe's answer: the plan
146 : [{ tool: 'mcp__cadre__report', input: { schemaVersion: 1, role: 'planner', outcome: 'request', summary: 'I look at the project before I plan.', request: { helper: 'probe', ask: 'Where do the string helpers live and how are they tested?', why: 'I plan the tasks next to them', paths: ['src/'] } } }][k] ?? { text: END },
147 explorer: k => [{ tool: 'mcp__cadre__report', input: { schemaVersion: 1, role: 'explorer', answer: 'One string helper, slug, in src/slug.mjs as a named ESM export; tests in test/ use node:test; npm test runs node --test.', citations: [{ path: 'src/slug.mjs', line: 1 }, { path: 'package.json', line: 1 }] } }][k] ?? { text: END },
148}
149function agent(rows: Row[], cwd: string): [string, Act] {
150 const brief = rows.find(isText)?.text ?? '', probe = brief.match(/S0-PROBE tag=(\w+)/)?.[1]
151 const k = done(since(rows)) // auto mode: a role's text + end_turn is re-asked 3 times for SubagentHandback, then the run ends (RESULTS.md (c))
152 if (done(rows) > (script === 'loop' ? 40 : 15)) return ['cap', { text: END }] // loop: past the breaker (20 in a row)
153 if (probe === 'end') return [probe, { text: END }]
154 if (probe === 'hb') return [probe, /No such tool available: SubagentHandback/.test(JSON.stringify(rows.at(-1))) ? { text: END } : { text: END, tool: 'SubagentHandback', input: { message: END } }] // the tool exists in auto mode only
155 if (probe === 'wedge' || probe === 'tools') return [probe, k === 0 ? { tool: 'Bash', input: { command: 'node -e "setTimeout(() => {}, 600000)"', description: 'Wait' } } : { text: END }]
156 const role = brief.match(/\b(Worker|Reviewer|Explorer|Tester|Planner) brief/)?.[1]?.toLowerCase() ?? (/# PLAN-\w/.test(brief) ? 'planner' : 'unknown')
157 return [role, ROLES[role]?.(k, brief, cwd, rows) ?? { text: END }]
158}
159
160async function* answer(e: any, a: Act): AsyncGenerator<any, any, any> {
161 let i = 0
162 if (a.text) yield { kind: 'text', index: i++, text: a.text }
163 if (a.tool) { yield { kind: 'tool', index: i, id: id(), name: a.tool }; yield { kind: 'input', index: i, json: JSON.stringify(a.input ?? {}) } }
164 const stopReason = a.tool ? 'tool_use' : 'end_turn'
165 yield { kind: 'stop', stopReason, usage: U }
166 return { turnId: e.turnId, index: e.index, answer: a.text ?? '', toolUses: a.tool ? [{ name: a.tool, input: a.input ?? {} }] : [], stopReason, usage: U }
167}
168
169export const register: Register = (on) => {
170 on('session.start', async ($: any, e, next) => {
171 try { script = JSON.parse(await $.fs.read('/work/run/.git/scripted.json')).script ?? script } catch {}
172 await L($, `script ${script}`); await $.command.register({ name: 's0', description: 'scripted probe: /s0 end|hb|wedge|tools', immediate: true }); return next(e)
173 })
174 on('agent.spawn', async ($: any, e: any, next) => { const r = await next(e); if (r?.agentId) cwds[r.agentId] = e.cwd ?? '/work/run'; return r })
175 on('turn.step', async function* ($: any, e: any, next) {
176 const rows = ((await $.session.messages(e.agentId ? { agentId: e.agentId } : {})) ?? []) as Row[]
177 const [who, a] = e.agentId ? agent(rows, cwds[e.agentId] ?? '/work/run') : ['main', main(rows)]
178 if (script === 'limit' && who === 'worker' && !injected) { injected = true; await L($, `step agent=${e.agentId} who=worker index=${e.index} -> next (usage limit from the proxy)`); return yield* next(e) }
179 if (who === 'planner' && a.tool && JSON.stringify(a.input).includes('"tasks"')) await L($, 'planner drafts') // the cell waits for it; its tool result is the accepted plan
180 await L($, `step agent=${e.agentId ?? 'main'} who=${who} index=${e.index} msgs=${e.messageCount} effort=${e.effort ?? '-'} -> ${a.tool ? `${a.text ? 'text+' : ''}tool ${a.tool}` : 'text end_turn'}`)
181 // cont: the reviewer's first two steps wait 7 s each (a hook call over ~10 s fails: HooksError, so one long sleep won't do). The reviewer has no Bash, so the wait is a sleep here: with none, the reviewer ends within a second of the worker and the
182 // cell's SIGKILL (polled every 2 s, later under load) lands after it, leaving no reviewer to run after the restart
183 if (script === 'cont' && who === 'reviewer' && e.index < 2) await new Promise(r => setTimeout(r, 7000))
184 return yield* answer(e, a)
185 })
186 on('turn.complete', async ($: any, e: any, next) => { await L($, `turn.complete agent=${e.agentId ?? 'main'} reason=${e.reason} usage=${e.usage?.model ?? '-'}`); return next(e) })
187 // (c)/(d) probe: spawned from this command frame, so this plugin's turn.step (another registration) still sees the children's steps (G6)
188 on('command.run', { command: 's0' }, async ($: any, e: any) => {
189 const tag = String(e.args ?? '').trim() || 'end'
190 if (tag === 'tools') { // probes/0.15: the tool surface under the settings gate, and hard links where the file store will live
191 await L($, `tools ${JSON.stringify((await $.tool.list()).map((t: any) => t.name).filter((n: string) => /^(Task|Todo|Agent$|mcp__)/.test(n)))}`)
192 const ln = await $.process.run(['sh', '-c', 'cd /work/run && mkdir -p .cadre/state && cd .cadre/state && rm -f j.* && echo a > t.1 && echo b > t.2 && ln t.1 j.1 && sync j.1 && echo link=ok; ln t.2 j.1 2>/dev/null && echo cas=overwrote || echo cas=refused; stat -c nlink=%h j.1; [ j.1 -ef t.1 ] && echo ef=same; cat j.1; df -T . | tail -1'])
193 await L($, `ln exit=${ln.exitCode} ${JSON.stringify(ln.stdout + ln.stderr)}`)
194 }
195 let r: any; try { r = await $.agent.spawn({ prompt: `S0-PROBE tag=${tag}. Do the task you are given.`, description: `s0 ${tag}`, subagentType: 'general-purpose' }) } catch (x) { r = { threw: String(x) } }
196 await L($, `spawned ${tag} -> ${JSON.stringify(r)}`)
197 if ((tag === 'wedge' || tag === 'tools') && r?.agentId) $.clock.after(6_000, async () => { // a timer frame, as the backstop's: no hook is calling
198 try { await L($, `TaskStop ${r.agentId} -> ${JSON.stringify(await $.tool.call({ tool: 'TaskStop', task_id: r.agentId }))}`) } catch (x) { await L($, `TaskStop ${r.agentId} threw ${x}`) }
199 })
200 return { text: `s0 ${tag} spawned` }
201 })
202}
203