@rafinery/cli 0.3.0 → 0.4.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.
Files changed (43) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +17 -7
  3. package/bin/rafa.mjs +68 -20
  4. package/blueprint/.claude/agents/atlas.md +28 -20
  5. package/blueprint/.claude/agents/bloom.md +15 -8
  6. package/blueprint/.claude/agents/compass.md +46 -0
  7. package/blueprint/.claude/agents/prism.md +42 -25
  8. package/blueprint/.claude/commands/rafa.md +151 -26
  9. package/blueprint/{.rafa → .claude/rafa}/contract.md +108 -22
  10. package/blueprint/.claude/skills/rafa-build/SKILL.md +76 -0
  11. package/blueprint/.claude/skills/rafa-distill/SKILL.md +87 -0
  12. package/blueprint/{.rafa/capabilities/improve.md → .claude/skills/rafa-improve/SKILL.md} +10 -5
  13. package/blueprint/.claude/skills/rafa-insights/SKILL.md +71 -0
  14. package/blueprint/{.rafa/capabilities/leverage.md → .claude/skills/rafa-leverage/SKILL.md} +9 -4
  15. package/blueprint/{.rafa/capabilities/plan.md → .claude/skills/rafa-plan/SKILL.md} +30 -3
  16. package/blueprint/{.rafa/capabilities/scan.md → .claude/skills/rafa-scan/SKILL.md} +14 -9
  17. package/blueprint/{.rafa/capabilities/validate.md → .claude/skills/rafa-validate/SKILL.md} +14 -5
  18. package/lib/blueprint.mjs +22 -12
  19. package/lib/brain-repo.mjs +100 -0
  20. package/lib/checkpoint.mjs +138 -0
  21. package/lib/ci-setup.mjs +109 -0
  22. package/lib/claude-config.mjs +5 -5
  23. package/lib/compile.mjs +6 -21
  24. package/lib/distill.mjs +237 -0
  25. package/lib/fold.mjs +53 -0
  26. package/lib/gate/compile.mjs +549 -0
  27. package/lib/gate/verify-citations.mjs +156 -0
  28. package/lib/hydrate.mjs +96 -0
  29. package/lib/init.mjs +15 -30
  30. package/lib/leverage/adapters/claude-code.mjs +5 -4
  31. package/lib/mcp-client.mjs +97 -0
  32. package/lib/mcp-config.mjs +1 -1
  33. package/lib/migrations/index.mjs +39 -3
  34. package/lib/pull.mjs +129 -0
  35. package/lib/push.mjs +93 -14
  36. package/lib/releases.mjs +33 -0
  37. package/lib/verify-citations.mjs +9 -0
  38. package/lib/working-set.mjs +113 -0
  39. package/package.json +2 -2
  40. package/blueprint/.rafa/bin/rafa-compile.mjs +0 -478
  41. package/blueprint/.rafa/bin/rafa-push.mjs +0 -75
  42. package/blueprint/.rafa/bin/verify-citations.mjs +0 -153
  43. package/blueprint/.rafa/capabilities/build.md +0 -39
@@ -1,10 +1,75 @@
1
1
  ---
2
- description: rafa — init · scan · improve · plan · build · push · leverage · migrate · update · help. Usage: /rafa <init|scan|improve|plan|build|push|leverage|migrate|update|help> [--brain-only]
2
+ version: 1.3.0
3
+ description: rafa — the repo's engineering SOP. Use whenever the dev wants to plan a feature or change, build/execute against the active plan, improve code health, or ground work in the repo's brain — intent counts, the dev does NOT need to type /rafa. Also explicit: /rafa <init|scan|improve|plan|build|push|leverage|migrate|update|help> [--brain-only]. Admin verbs (init/scan/push/migrate/update) run ONLY when explicitly invoked.
3
4
  ---
4
5
 
5
6
  You are the **conductor** of the rafa agent loop, running in the **main session**.
6
7
  Argument: `$ARGUMENTS`
7
8
 
9
+ ## Intent routing — implicit by default, explicit as override
10
+
11
+ Work verbs dispatch on **prompt intent**; the dev never needs to remember a command.
12
+ Admin verbs are expensive or side-effectful and run **only when explicitly typed**.
13
+
14
+ | Prompt shape | Route |
15
+ |---|---|
16
+ | "let's add / build / implement / refactor X" (no active plan) | `## plan` — weight by blast radius: lite vs full (see plan.md § plan-lite) |
17
+ | same, with an active plan covering it | `## build` |
18
+ | "why / how / where does X …" (a question) | recall-and-answer: MCP `search_knowledge` → cited answer. No choreography. |
19
+ | "list plans / what plans are there" | `list_plans` — NAMES ONLY (id · title · status · progress); never dump bodies |
20
+ | "load / open / work on plan X" | `get_plan(X)` → materialize parent + children (bodies) into `.rafa/plans/<X>/` + set `active.md` → resume per `## build` |
21
+ | "improve / clean up / what's rotting" | `## improve` |
22
+ | explicit `/rafa <admin verb>` — init · scan · push · migrate · update | that verb, and ONLY then |
23
+
24
+ **Announce-and-proceed, never ask-permission:** state the route in one line — *"this
25
+ looks plan-shaped — following the plan SOP (say 'skip' to bypass)"* — then go. "skip"
26
+ always wins, immediately and without argument. Never narrate other devs' activity
27
+ unless explicitly asked (serve knowledge, not gossip). Misroutes the dev corrects are
28
+ signal — prefer under-routing (answer plainly) over dragging a question through
29
+ choreography.
30
+
31
+ **Scope discipline (owner rule):** deliver exactly what the message asked — fix what
32
+ they're expecting, nothing else. No unsolicited extras beyond bloom's single opt-in
33
+ nudge. Fix-shaped prompts: recall the failure domain's knowledge → fix the asked
34
+ thing → verify → stop.
35
+
36
+ ## Offers — ask at the boundary, never nag
37
+
38
+ Three interaction modes by the weight of the action:
39
+ 1. **Just do** (session-local, reversible): recall · drafting · local journaling ·
40
+ status updates. Announce-and-proceed.
41
+ 2. **Ask once per session, then remember**: recurring cadences — *"keep plans
42
+ updated + pushed as I work (progress, notes, staged insights)?"* at build start.
43
+ One answer covers the session.
44
+ 3. **Offer at the boundary** (creates a durable artifact, leaves the machine, or
45
+ spends real money): a short, well-timed question at a NATURAL boundary —
46
+ - intent is getting big mid-conversation → *"want me to turn this into a plan?"*
47
+ - work/task complete → *"push the brain so the platform (and your team) see it?"*
48
+ - plan drafted but the dev drifted → *"push this plan to the platform?"*
49
+ - session start, local ahead of platform → *"brain is N commits behind — push?"*
50
+ - reconciliation pending → *"branch <x> merged with N working-set files — distill now?"*
51
+ - adjudication pending → *"1 file diverged at the <x>→<y> fold — pick a copy?"*
52
+
53
+ Offer etiquette (hard rules): boundaries only, never mid-flow · once per moment — a
54
+ "no" is remembered for the session and never re-argued · an unanswered offer never
55
+ blocks; keep working, the offer stands · admin verbs stay explicit — an ACCEPTED
56
+ offer is the explicit invocation.
57
+
58
+ **Bootstrap digest — one question, however much is pending.** Session start may
59
+ accumulate many offers (staleness push, N distills, needs-adjudication flags, a
60
+ nudge). NEVER ask them serially — batch into ONE itemized digest: *"3 things
61
+ pending: brain push · 2 merged branches to distill · 1 file needs adjudication —
62
+ want any now, or later?"*
63
+ Dismissible as a unit; offer fatigue trains reflexive yes, which corrodes every
64
+ consent rung above it.
65
+
66
+ **The frame is CONSENT (owner, 2026-07-10).** Four rungs, each action needs exactly
67
+ one: (1) **implied** — the message itself consents to what it asks, and only that ·
68
+ (2) **session** — asked once, remembered, revocable mid-session ("stop pushing") ·
69
+ (3) **boundary** — the offer; acceptance is the consent · (4) **standing** — durable
70
+ opt-ins recorded in config (insights capture per dev). And one thing consent can
71
+ never waive: nothing person-scoped leaves the user brain, ever.
72
+
8
73
  You orchestrate three context-isolated *leaf* subagents — **atlas** (scan/fix), **prism**
9
74
  (validate), **bloom** (improve) — and shuttle artifacts between them via the filesystem.
10
75
  Subagents never spawn each other (Claude Code forbids nesting), so the loop lives here, in the
@@ -20,11 +85,11 @@ codebase in *its* window — you hold only summaries + the on-disk artifacts (`.
20
85
  The default runs the whole pipeline. `--brain-only` stops after the brain is validated (skips
21
86
  improve + push — a cheap knowledge refresh).
22
87
 
23
- 1. **Scan — spawn `atlas`** context-isolated: *"Run the scan per `.rafa/capabilities/scan.md`:
88
+ 1. **Scan — spawn `atlas`** context-isolated: *"Run the scan per `.claude/skills/rafa-scan/SKILL.md`:
24
89
  comprehensive, breadth-before-depth, cited notes → `.rafa/brain/{rules,playbooks}/` +
25
- `coverage.md`. Run `node .rafa/bin/verify-citations.mjs` until it **exits 0**. Return a
90
+ `coverage.md`. Run `npx @rafinery/cli verify-citations` until it **exits 0**. Return a
26
91
  coverage summary only — not the raw reads."*
27
- 2. **Gate 1 — checker (trust-but-verify)**: re-run `node .rafa/bin/verify-citations.mjs`
92
+ 2. **Gate 1 — checker (trust-but-verify)**: re-run `npx @rafinery/cli verify-citations`
28
93
  yourself. Must **exit 0** (if not, re-spawn atlas to fix). It writes `citation-check.md`.
29
94
  3. **Gate 2 — prism**: spawn the `prism` subagent **context-isolated** — pass ONLY:
30
95
  *"Validate the scan in `.rafa/brain/` against the repo per your SOP; write
@@ -37,7 +102,7 @@ improve + push — a cheap knowledge refresh).
37
102
  6. **Improve** *(skip if `--brain-only`)* — run the **improve pass** (below): spawn `bloom` →
38
103
  `.rafa/improve/`. improve reads the *validated* brain as its index, so it only runs after PASS.
39
104
  7. **Push** — present the full summary (brain verdict/score + top improvements). **On the dev's
40
- explicit approval**, push the brain: `node .rafa/bin/rafa-push.mjs` — commits `.rafa/` and
105
+ explicit approval**, push the brain: `npx @rafinery/cli push` — commits `.rafa/` and
41
106
  pushes to the brain remote using the dev's own git auth, stamped `brain-for: <code sha>`.
42
107
  Never push without approval.
43
108
 
@@ -53,39 +118,93 @@ cite-check them (`--root=.rafa/improve --dirs=improvements`, drop unresolved), r
53
118
  high-leverage P0/P1s — don't nag; the dev triages.**
54
119
 
55
120
  ## `plan <intent>` — brain-grounded, prism-validated decomposition
56
- Per [`.rafa/capabilities/plan.md`](../../.rafa/capabilities/plan.md). The trio at plan time —
121
+ Per [the rafa-plan skill](../skills/rafa-plan/SKILL.md). The trio at plan time —
57
122
  atlas drafts, bloom pulls, prism validates the plan itself:
58
123
  1. **Staleness check** — if this repo is platform-connected, compare the MCP envelope's
59
124
  `brainForSha` to the local brain stamp; if the platform is behind, surface "run `rafa push`"
60
125
  (never proceed silently, never block).
61
126
  2. **Spawn `atlas`** context-isolated: *"Draft a plan for `<intent>` per
62
- `.rafa/capabilities/plan.md`: RECALL the brain slice for the touched domains (coverage →
127
+ `.claude/skills/rafa-plan/SKILL.md`: RECALL the brain slice for the touched domains (coverage →
63
128
  search → rules/playbooks, honor non-exemplars), name the blast radius, decompose into
64
129
  contract §7 files — one parent + child-owned tasks, globally-unique prefixed ids, each child
65
130
  body carrying a `## Done-check`. Return the draft file contents."*
66
131
  3. **Spawn `bloom`**: *"List open improvements in the blast radius `<domains>`; return the
67
132
  top-leverage few as optional child tasks."* Fold them in, marked optional.
68
133
  4. **Spawn `prism`** context-isolated: *"Validate this DRAFT plan against the brain + code per
69
- `.rafa/capabilities/plan.md`: every task grounded (not hallucinated), every child has a
134
+ `.claude/skills/rafa-plan/SKILL.md`: every task grounded (not hallucinated), every child has a
70
135
  `## Done-check`. REJECT with reasons or PASS."* Fix-and-revalidate until PASS (max 3; then
71
136
  surface and stop).
72
137
  5. **Approval gate** (ExitPlanMode / the dev). On approval: write `plans/<plan>/*.md`, set
73
- `active.md` = `# <plan-id>`, run `node .rafa/bin/rafa-compile.mjs` to exit 0, offer
74
- `rafa push` (the plan becomes resumable from any session/machine via the platform).
138
+ `active.md` = `# <plan-id>`, run `npx @rafinery/cli compile` to exit 0, then in a
139
+ connected repo **`push_plan` + `set_active_plan` immediately approval IS the push
140
+ trigger for plans** (the dedicated plans channel; plans never ride the brain manifest;
141
+ no second prompt — the dev just approved this exact content). The plan renders on the
142
+ platform and becomes resumable from any session/machine/teammate within moments:
143
+ *"list plans"* = names only · *"load plan X"* materializes it back into `.rafa/plans/`.
75
144
 
76
145
  ## `build` — execute the active plan, trio-choreographed
77
- Per [`.rafa/capabilities/build.md`](../../.rafa/capabilities/build.md). Resume from `active.md`
78
- (or the platform's `get_active_plan` when connected)never re-derive context.
146
+ Per [the rafa-build skill](../skills/rafa-build/SKILL.md). Resume from `active.md`
147
+ (or the platform's `get_active_plan` when connected — "load plan X" materializes it) —
148
+ never re-derive context.
79
149
  Per task: **atlas** recalls + implements → **prism** validates against the child's
80
150
  `## Done-check` (**`status: done` only on prism PASS**; FAIL → atlas corrects) → **bloom**
81
151
  sweeps (new opportunities → ledger files; fixed-in-passing → `status: fixed`; one opt-in
82
- nudge max) → update the child file's `status` periodically compile + push so the platform
83
- reflects live progress. If execution invalidates/creates brain knowledge, run a **full
84
- `## scan`** (v1 rule never hand-edit brain files around the gate). When all children are
85
- done: prism-style final verify, set `active.md` = `# No active plan`, compile + push.
152
+ nudge max) → update the child file's `status` + `## Log` at CHECKPOINTS (task done ·
153
+ cadence under session consent): `push_plan`/`update_plan_status` (plans channel) +
154
+ `rafa checkpoint` (working set) so the platform reflects live progress. Terminal
155
+ statuses when honest: `superseded` (replaced by a newer plan) · `abandoned` (dropped).
156
+ If execution invalidates/creates brain knowledge, route per §capture (working set on a
157
+ branch; full `## scan` on main — never hand-edit main's brain around the gate). When all
158
+ children are done: prism-style final verify, set `active.md` = `# No active plan`,
159
+ final `push_plan` + `set_active_plan` (clear).
160
+
161
+ ## capture — during ANY work (plan/build/answering), consent-gated
162
+ Two destinations, one rule — route by what the observation is ABOUT:
163
+ - **About the code** (a fact/gotcha/how-to discovered while working) → the
164
+ branch **working set**: author or edit the brain-shaped FILE under
165
+ `.rafa/brain/{rules,playbooks}/` (files are the working medium; hydrate the
166
+ existing note first via `rafa hydrate <rule|playbook> <id>` when refining
167
+ one). Candidate-grade — no gate at capture; it enters the org brain only at
168
+ merge-to-main distillation. Announce per file as it happens (*"capturing:
169
+ <path>"* — a "no" drops it). Sync at **checkpoints** (`rafa checkpoint`):
170
+ task done · plan approved · explicit ask · cadence under session consent ·
171
+ git push/pull of the code branch — **never session-end**. A checkpoint
172
+ CONFLICT (a teammate's newer copy) is decided HERE, in this session — read
173
+ the `.theirs.md` copy, merge/adopt/keep, re-checkpoint. **Third-party
174
+ rule:** a statement attributable to someone not in this session ("Carol
175
+ says…") is NEVER captured verbatim — paraphrase to an ownerless code fact,
176
+ or drop it. **No person-scoped content in the working set, ever** — a note
177
+ that names a person is rewritten person-free or routed/dropped. **No
178
+ secrets** — names are contracts, values are secrets (the platform also
179
+ screens; don't rely on it).
180
+ - **About the dev** (a repeated correction, a stated preference/constraint) →
181
+ offer first (*"want me to remember that?"*), then `put_dev_insight` — the
182
+ dev's PRIVATE user brain, cross-repo. Never logged to repo activity, never
183
+ narrated to anyone (consent floor: nothing person-scoped leaves it).
184
+
185
+ ## `insights` — bootstrap/refresh the dev's user brain (compass)
186
+ **Spawn `compass`** context-isolated per
187
+ [the rafa-insights skill](../skills/rafa-insights/SKILL.md):
188
+ bootstrap from the dev's native `/insights` report (distilled with judgment,
189
+ never parsed) and/or refine from recent observations — every candidate OFFERED,
190
+ banked only on yes (`put_dev_insight`). Legibility on request: list, correct,
191
+ delete — the dev's brain, the dev's record. Capture during normal work does NOT
192
+ require this command (rafa.md §capture routes it); this is the deliberate pass.
193
+
194
+ ## `distill [<branch>]` — reconcile a merged branch's working set into the org brain
195
+ Per [the rafa-distill skill](../skills/rafa-distill/SKILL.md). The SESSION
196
+ fallback of the rigor gradient — orgs with `rafa ci-setup` run this headlessly
197
+ in their own CI on merge; offer it only when CI hasn't (or isn't wired).
198
+ Normally OFFER-driven: at bootstrap, if `get_working_set` shows active files
199
+ for a branch whose code reached main → *"branch <x> merged with N working-set
200
+ files — distill now?"* Trio roles: conductor collects + surfaces adjudication
201
+ flags to the dev · prism validates each file against MERGED MAIN (cited) ·
202
+ atlas authors survivors into org-brain files → compile → push ·
203
+ `resolve_working_file` (distilled/refuted with the cited reason — refutations
204
+ reported to their author).
86
205
 
87
206
  ## `push` — (re-)push the brain to the brain remote
88
- `node .rafa/bin/rafa-push.mjs` — commit `.rafa/` and push to `origin` (the brain repo) with the
207
+ `npx @rafinery/cli push` — commit `.rafa/` and push to `origin` (the brain repo) with the
89
208
  dev's own git auth. Use after a scan, or to re-sync a brain that changed.
90
209
 
91
210
  ## `leverage` — tune the dev's toolbox (rafa's 3rd mission; intelligence + exact edits)
@@ -94,7 +213,7 @@ Detection is cheap and deterministic; **acting needs intelligence — that's why
94
213
  1. **Inspect** the committed toolbox: `.claude/settings.json`, `.mcp.json`, `.claude/skills/`,
95
214
  `.claude/commands/`, and the stack (`package.json` / dirs). (`rafa leverage` gives the fast
96
215
  deterministic signal; here you reason over the real files.)
97
- 2. **Reason** per [`.rafa/capabilities/leverage.md`](../../.rafa/capabilities/leverage.md): what's
216
+ 2. **Reason** per [the rafa-leverage skill](../skills/rafa-leverage/SKILL.md): what's
98
217
  missing / misconfigured / unused — permission gaps, an MCP the stack needs but isn't wired, a
99
218
  repeatable flow worth capturing as a skill, the best-fit *existing* skill for THIS repo. P1→P3.
100
219
  3. **Act — on the dev's approval, edit exactly.** Merge the precise permission entries, write the
@@ -105,11 +224,11 @@ Detection is cheap and deterministic; **acting needs intelligence — that's why
105
224
  Two channels. **Mechanical** changes (field rename, path move) run deterministically via the
106
225
  terminal `rafa migrate`. **Semantic** changes — a plan's *shape* changed and each file must be
107
226
  understood to be rewritten correctly — need intelligence, and that's this command.
108
- 1. Read the target schema in [`.rafa/contract.md`](../../.rafa/contract.md) (§6/§7 for plans) and
227
+ 1. Read the target schema in [`.claude/rafa/contract.md`](../rafa/contract.md) (§6/§7 for plans) and
109
228
  the `from` versions in `rafa.json`.
110
229
  2. For each affected file under `.rafa/plans/` (and any other structured dir), **rewrite it to
111
230
  conform** — preserve meaning, remap fields, fill new required fields sensibly.
112
- 3. Run `node .rafa/bin/rafa-compile.mjs` until it **exits 0** (validate-and-correct loop), surface
231
+ 3. Run `npx @rafinery/cli compile` until it **exits 0** (validate-and-correct loop), surface
113
232
  the diff for approval, then offer `rafa push` if this is a connected repo.
114
233
 
115
234
  ## `update` — the BRAIN-side of an upgrade (the CLI already did the blueprint side)
@@ -121,13 +240,13 @@ understood to be rewritten correctly — need intelligence, and that's this comm
121
240
  or re-run the CLI.
122
241
  1. **Find the gap.** The brain/plans conform to a *data* version; the blueprint just moved to a
123
242
  newer one. Compare `.rafa/manifest.json`'s `schemaVersion` (and `rafa.json`'s `contract`/`plans`)
124
- to the current `.rafa/contract.md`. That gap is exactly what the CLI update flagged. (If the CLI
243
+ to the current `.claude/rafa/contract.md`. That gap is exactly what the CLI update flagged. (If the CLI
125
244
  update hasn't run yet, tell the dev to run `npx @rafinery/cli@latest update` first, then return.)
126
245
  2. **Migrate the brain side:**
127
246
  - **Contract bumped → the brain is a stale cache:** re-scan (`## scan`) to regenerate it, or for
128
247
  a targeted change, intelligently rewrite the affected notes to the new schema and re-validate.
129
248
  - **Plans shape changed:** rewrite each plan per `## migrate` (preserve meaning), compile to exit 0.
130
- 3. **Record + summarize.** Run `node .rafa/bin/rafa-compile.mjs` to exit 0, then advance the data
249
+ 3. **Record + summarize.** Run `npx @rafinery/cli compile` to exit 0, then advance the data
131
250
  version in `rafa.json` (`contract`/`plans` → the versions you migrated to). Summarize what changed;
132
251
  on the dev's approval, `rafa push` if this is a connected repo.
133
252
  Never hand-edit around a migration or discard tuned files.
@@ -140,8 +259,10 @@ Print this reference verbatim and stop.
140
259
  1. **Platform** — sign in → add a GitHub token → add brain repo + code repo → connect →
141
260
  *Generate setup command* (15-min URL carrying a one-time MCP agent key).
142
261
  2. **Install** — in the code repo: `npx @rafinery/cli init '<setup-url>'` — vendors the
143
- blueprint, wires the brain remote, registers the knowledge MCP in `.mcp.json`
144
- (secret-free) + puts the key in `.claude/settings.local.json` (gitignored).
262
+ blueprint (agents · /rafa · skills · contract), records the brain remote in the
263
+ committed `rafa.json` (teammates: clone `npx rafa pull` just works), registers the
264
+ knowledge MCP in `.mcp.json` (secret-free) + puts the key in
265
+ `.claude/settings.local.json` (gitignored).
145
266
  3. **Scan** — restart Claude Code → `/rafa scan` (atlas maps → prism validates → bloom
146
267
  ledgers) → `rafa push` → webhook → the platform ingests the manifest.
147
268
  4. **See it** — platform repo pages: Overview · Brain · Improvements · Plans; *Agent
@@ -166,6 +287,8 @@ names exist on both — the CLI does the mechanical half, `/rafa` the intelligen
166
287
  | `/rafa plan <intent>` | Trio planning: atlas drafts (brain-grounded, contract §7 files, Done-checks), bloom pulls blast-radius improvements, prism validates the plan — then approval, compile, push. |
167
288
  | `/rafa build` | Execute the active plan: per task atlas implements → prism gates `done` on the Done-check → bloom sweeps the ledger; compile + push progress as you go. |
168
289
  | `/rafa push` | (Re-)push the brain to the brain remote (your git auth). |
290
+ | `/rafa distill [<branch>]` | Reconcile a merged branch's staged notes into the org brain (prism-validated vs merged main, compile-gated). Normally offer-driven at session start. |
291
+ | `/rafa insights` | compass bootstraps/refreshes your private user brain from your native usage report + recent sessions — every insight offered before it's banked. |
169
292
  | `/rafa leverage` | Tune your toolbox: reason over config and, on approval, apply fixes exactly — merge settings, wire an MCP, scaffold a skill. |
170
293
  | `/rafa migrate` | Semantic migration — rewrite plans to a new schema preserving meaning, then compile-gate. |
171
294
  | `/rafa update` | The brain-side of an upgrade: after the CLI syncs the blueprint, run the migrations that need intelligence (re-scan a stale brain / rewrite plans). |
@@ -173,10 +296,12 @@ names exist on both — the CLI does the mechanical half, `/rafa` the intelligen
173
296
  **`rafa` — in the terminal (`npx @rafinery/cli@latest <cmd>`; deterministic):**
174
297
  | Command | What it does |
175
298
  |---|---|
176
- | `init [<setup-url>]` | Vendor the blueprint into the repo (+ wire the brain remote from a platform setup URL). |
299
+ | `init [<setup-url>]` | Vendor the blueprint into the repo (agents, this command, the rafa skills, the contract) + wire the platform from a setup URL. `.rafa/` itself stays lazy. |
177
300
  | `update [--overwrite\|--keep]` | Blueprint-side of an upgrade: re-sync the blueprint (asks before overwriting files you tuned), run mechanical migrations, and report what the brain needs next. |
178
301
  | `compile` | Run the contract gate → `.rafa/manifest.json`. |
179
- | `push` | Compile, then push `.rafa/` to the brain remote. |
302
+ | `verify-citations` | Deterministic citation checker (B1 resolution · B2 completeness · policy). |
303
+ | `push` | Compile, then push `.rafa/` to the brain remote (a main-branch act; stamps the contract copy). |
304
+ | `pull [--full] [--force]` | Make this clone brain-ready — bootstraps the lazy `.rafa/` from committed `rafa.json`; `--full` mirrors the whole brain repo locally. Never re-scan for existing knowledge. |
180
305
  | `leverage` | Detect toolbox gaps (deterministic) and print prioritized tips — the detector for `/rafa leverage`. |
181
306
  | `migrate` | Run the mechanical (deterministic) migrations. |
182
307
 
@@ -6,6 +6,12 @@ prism) and the reader (the platform ingest). If a file violates this, the compil
6
6
  step **fails loudly** and the authoring agent must correct it — the platform never
7
7
  guesses, never assumes a value.
8
8
 
9
+ **Canonical home: `.claude/rafa/contract.md` in the CODE repo** (blueprint split,
10
+ 0.4.0) — the contract versions with the CLI that implements it (`rafa compile` ships
11
+ inside `@rafinery/cli`, never vendored). A **stamped copy** rides every brain push as
12
+ `contract.md` in the brain repo, so any reader of the brain repo knows which contract
13
+ version that brain conforms to.
14
+
9
15
  Pipeline:
10
16
 
11
17
  ```
@@ -39,9 +45,18 @@ doesn't validate, compile fails.
39
45
  | ledger | `improve/ledger.md` | **structured** | §5 | bloom |
40
46
  | plan | `plans/**/*.md` | **structured** | §7 | plan/build |
41
47
  | log | `brain/log.md` | **verbatim** | — (prose trail) | conductor |
42
- | citation-check | `**/citation-check.md` | **generated** | — (by `verify-citations`) | tool |
48
+ | citation-check | `**/citation-check.md` | **generated** | — (by `rafa verify-citations`) | tool |
43
49
  | active pointer | `active.md` | **generated** | — (`# <plan-id>` or "No active plan"; compile emits it as `activePlanId`, §7) | conductor |
44
- | blueprint | `capabilities/*`, `bin/*`, `contract.md` | **verbatim** | — (shipped SOPs/tools) | rafa |
50
+ | contract copy | `contract.md` | **generated** | — (stamped copy of `.claude/rafa/contract.md`, written by `rafa push`) | tool |
51
+ | agent | `.claude/agents/*.md` (code repo) | **structured** (local gate — NOT in manifest) | §10 | rafa |
52
+
53
+ The `agent` type is the one structured type outside `.rafa/`: the shipped agent cards
54
+ in the code repo. Compile validates them (§10) so a malformed card fails the gate like
55
+ any other contract violation, but they are never emitted into `manifest.json` — the
56
+ platform doesn't ingest agents (yet); the gate exists so the agents themselves are
57
+ never un-schema'd. The SOPs the cards point at are committed skills in the code repo
58
+ (`.claude/skills/rafa-*/SKILL.md`); the gate tools are `@rafinery/cli` commands —
59
+ neither lives under `.rafa/`, which holds purely knowledge + state.
45
60
 
46
61
  `structured` types are compiled into `manifest.json` (§1) — that JSON is the ONLY thing the
47
62
  platform ingests. `verbatim`/`generated` files are shown as-is in the file browser (fetched
@@ -77,9 +92,14 @@ key: { a: x, b: y } # flow map of scalars
77
92
  key: # block list …
78
93
  - item
79
94
  - item
95
+ key: >- # folded scalar: continuation lines joined with one space
96
+ first part
97
+ second part
80
98
  ```
81
99
 
82
- No nested block maps, no multiline scalars, no anchors. Deterministic to parse.
100
+ No nested block maps, no anchors, no literal (`|`) blocks. The folded scalar (`>-`/`>`)
101
+ is the ONLY multiline form, added for agent cards (§10) whose descriptions fold.
102
+ Deterministic to parse: indented non-empty lines after `>-` join with a single space.
83
103
 
84
104
  ### cites DSL
85
105
 
@@ -155,25 +175,15 @@ JSON. This is the exact shape the platform binds to.
155
175
  "cites": [{ "file": "…", "line": "25", "token": "…" }],
156
176
  "path": "improve/improvements/dead-model-options-google-crewai.md"
157
177
  }
158
- ],
159
-
160
- "activePlanId": null, // from active.md: plan id, or null
161
- "plans": [
162
- {
163
- "id": "multitenant", // == filename stem, globally unique
164
- "plan": "multitenant", // the parent plan id
165
- "parent": null, // parent plan id, or null for the root
166
- "kind": "parent", // "parent" | "child"
167
- "title": "…",
168
- "status": "in-progress", // omitted when absent (parent may omit)
169
- "branch": "feat/mt-c1", // omitted when absent
170
- "baseSha": "abc123", // omitted when absent
171
- "path": "plans/multitenant/multitenant.md" // prose body (lazy fetch)
172
- }
173
178
  ]
174
179
  }
175
180
  ```
176
181
 
182
+ **The manifest carries KNOWLEDGE only.** Plans and the active pointer left it
183
+ (0.4.0 — the plans channel, §7): they are pushed on approval via `push_plan` /
184
+ `set_active_plan` and never ride the brain repo. Legacy manifests carrying
185
+ `plans[]`/`activePlanId` are tolerated and IGNORED by ingest (never written).
186
+
177
187
  Ingest is `JSON.parse` + a shape-check against this schema. Any mismatch (missing
178
188
  key, wrong enum, wrong type, unknown `schemaVersion`) → a **surfaced ingest error**
179
189
  on the platform, never a guessed value.
@@ -278,7 +288,7 @@ domains: { design-system: mapped, components: mapped, api: thin, external-integr
278
288
 
279
289
  ---
280
290
 
281
- ## 7. Plan files — `plans/**/*.md`
291
+ ## 7. Plan files — `plans/**/*.md` (+ the plans channel)
282
292
 
283
293
  Each child owns exactly one file (so merges never conflict; parent progress is
284
294
  derived by counting).
@@ -291,7 +301,7 @@ plan: multitenant # required · the parent plan id
291
301
  parent: multitenant # required · parent plan id (child), or null (root)
292
302
  kind: parent | child # required
293
303
  title: … # required
294
- status: todo | in-progress | done | blocked # required (child); parent may omit
304
+ status: todo | in-progress | done | blocked | superseded | abandoned # required (child); parent may omit
295
305
  branch: feat/mt-c1 # optional · the branch this executes on
296
306
  baseSha: abc123 # optional · commit it was cut from
297
307
  ---
@@ -312,10 +322,29 @@ Rules (all compile-enforced unless noted):
312
322
  - **Progress is never stored.** A `progress` key in plan frontmatter is a compile
313
323
  error. Parent progress is `count(children where status == done) / count(children)`
314
324
  — derived at read time, everywhere (compile, platform, MCP).
325
+ - **Statuses.** `done` exists only on prism PASS (the execution gate). The two
326
+ TERMINAL statuses close work honestly without pretending `done`:
327
+ `superseded` (a newer plan replaces it) · `abandoned` (deliberately dropped).
328
+ `blocked` is waiting, not terminal. Statuses are set in sessions; the platform
329
+ board renders them read-only.
315
330
  - **`active.md` → `activePlanId`.** Compile reads the generated pointer: a first line
316
331
  `# <plan-id>` must resolve to a `kind: parent` plan (else compile error);
317
332
  `# No active plan` or a missing `active.md` → `activePlanId: null` (documented
318
333
  default — the pointer is generated, absence means "none", never a guess of one).
334
+ The PLATFORM pointer is set separately through `set_active_plan` (below).
335
+
336
+ **Transport — the plans channel (0.4.0; plans never ride the brain manifest):**
337
+
338
+ - **Authoring**: plans are drafted as the files above (compile-validated —
339
+ determinism holds; `.rafa/plans/` is the working copy).
340
+ - **Push on approval**: the dev's approval IS the trigger — `push_plan` sends the
341
+ whole plan (parent + children + bodies) to the platform; `set_active_plan`
342
+ points the repo's active pointer at it. Build cadence re-pushes statuses +
343
+ `## Log` journals (`push_plan` upsert / `update_plan_status`).
344
+ - **Pull-based work**: `list_plans` returns NAMES ONLY (id · title · status ·
345
+ progress); **"load plan X"** = `get_plan` (bodies included) materialized back
346
+ into `.rafa/plans/` by the session. Nothing plan-shaped is hydrated until
347
+ explicitly loaded.
319
348
 
320
349
  ---
321
350
 
@@ -366,8 +395,8 @@ match.
366
395
  | `search_knowledge` | `q`, `types?`, `domain?`, `limit?` | ranked candidates (fields per type below) |
367
396
  | `get_rule` / `get_playbook` / `get_improvement` | `repo`, `id` | full frontmatter + lazy-fetched body + cites as objects |
368
397
  | `list_improvements` | `repo`, `status?`, `priority?`, `domain?` | ledger rows |
369
- | `get_plan` | `repo`, `id` (parent or child) | parent + all children + **derived** progress; a child id resolves the whole plan with `requestedChild` set |
370
- | `get_active_plan` | `repo` | resolves manifest `activePlanId` → `get_plan`, or "no active plan" |
398
+ | `get_plan` | `repo`, `id` (parent or child) | parent + all children **with stored bodies** + **derived** progress; a child id resolves the whole plan with `requestedChild` set — this is what "load plan X" materializes into `.rafa/plans/` |
399
+ | `get_active_plan` | `repo` | resolves the channel pointer (`set_active_plan`) → `get_plan`, or "no active plan" |
371
400
 
372
401
  `repo` must match the key's scope exactly; `branch` is reserved (branch-keyed
373
402
  instances land in Slice 2 — third-party clients default to the production brain,
@@ -393,4 +422,61 @@ minted at setup generation and delivered consume-once through the setup fetch;
393
422
  `.claude/settings.local.json` `env` (gitignored) and `~/.config/rafinery/credentials.json`
394
423
  (0600). Teammates mint their own key on the platform (repo → Agent access).
395
424
 
425
+ ### §9 addendum — state-plane tools (three-store model, working-set architecture)
426
+
427
+ The knowledge plane stays strictly read-only (org-brain writes go ONLY through
428
+ files → compile → push → ingest). Seven additional tools write **collaboration
429
+ state**, marked by `envelope.plane: "state"`:
430
+
431
+ | Tool | Store | Notes |
432
+ |---|---|---|
433
+ | `list_dev_insights` / `put_dev_insight` / `remove_dev_insight` | **user brain** — account-scoped, cross-repo, PRIVATE | consent-gated by the conductor; never logged to repo activity; nothing person-scoped is ever served to another user |
434
+ | `checkpoint_sync` | **branch working set** — (repo, branch, file path) rows | pushes edited/new brain files from the lazy `.rafa/` instance at CHECKPOINTS (task done · plan approved · explicit ask · cadence · git push/pull — never session-end) under **base-version CAS**: each file carries the row `version` last seen (null = create); a stale base returns the newer copy as a per-file conflict for the HUMAN in that session to resolve |
435
+ | `get_working_set` | branch working set | hydration (a session starts with its branch's working set), the branch view, distillation collect; `needs-adjudication` rows carry the incoming copy in `pending` |
436
+ | `resolve_working_file` | branch working set | `distilled` / `refuted` (+ cited note) at merge-to-main distillation; `keep-current` for adjudication decisions; CAS on status — a racing distill fails loudly |
437
+ | `fold_working_set` | branch working set | branch→parent-branch MECHANICAL fold (no LLM, no prism — rigor only at main): absent → re-keyed · identical → merged · divergent → `needs-adjudication` on the parent row |
438
+ | `push_plan` / `list_plans` / `update_plan_status` / `set_active_plan` | **plans** — (repo) work objects | the dedicated push-on-approval channel (§7): approval pushes the whole plan (bodies stored); `list_plans` = names only; statuses push back from sessions; the active pointer is explicit, never inferred |
439
+
440
+ State tools work with or without an ingested brain (a working set can exist —
441
+ and a plan can be pushed — before the first scan) and are exempt from the
442
+ snapshot/ingestError gates. `get_plan`/`get_active_plan` share this exemption
443
+ (plans are work objects, not snapshot-derived knowledge). The retired
444
+ bucket-note tools (`stage/list/resolve_bucket_note`, pre-0.4.0) are superseded
445
+ by the working-set tools.
446
+
447
+ ## 10. Agent cards — `../.claude/agents/*.md` (local gate)
448
+
449
+ The shipped agents are contract-governed artifacts: every card is validated by
450
+ `rafa compile` (a malformed agent fails the gate) but never enters `manifest.json`.
451
+ No assumed values — applied to the agents themselves.
452
+
453
+ ```yaml
454
+ ---
455
+ name: prism # required · MUST equal filename stem
456
+ version: 0.4.0 # required · semver (MAJOR.MINOR.PATCH)
457
+ model: opus # required · non-empty (trailing # comment = the why)
458
+ groundTruth: code-vs-claim # required · code-at-sha | code-vs-claim | code-trend | sessions-over-time
459
+ description: >- # required · non-empty (folded scalar allowed, §0)
460
+
461
+ tools: Read, Grep, … # required · non-empty
462
+ color: orange # optional
463
+ duties: # required · block list, ≥ 1 · each a duty DSL string
464
+ - <duty> :: <sop-path> :: <bar>
465
+ ---
466
+ ```
467
+
468
+ **Duty DSL** (one string per duty, split on ` :: `, exactly three parts):
469
+ - `duty` — kebab-case name of the responsibility.
470
+ - `sop-path` — path relative to the CODE repo root (e.g.
471
+ `.claude/skills/rafa-validate/SKILL.md`); the file MUST exist at compile time (a
472
+ duty without a procedure is a claim, not a contract). Legacy `.rafa/`-relative
473
+ paths (pre-0.4.0 `capabilities/*.md`) still resolve during the migration window.
474
+ - `bar` — the explicit pass/fail sentence for this duty. Never empty: a duty whose
475
+ bar can't be stated can't be validated, so it doesn't ship.
476
+
477
+ Versioning: bump `version:` with any card change; record the *why* outside the card
478
+ (cards ship to end users and stay clean of build-log clutter).
479
+
480
+ ---
481
+
396
482
  This contract is the thing to test against.
@@ -0,0 +1,76 @@
1
+ ---
2
+ name: rafa-build
3
+ description: "rafa SOP — execute the active plan task by task: atlas implements from recalled knowledge, prism gates done on each Done-check, bloom sweeps the ledger; progress + journals sync at checkpoints. Loaded on /rafa build."
4
+ ---
5
+
6
+ # build — execute the plan, trio-choreographed, compounding (capability #4)
7
+
8
+ > Status: **active.** The work-time loop where recall + validation + improvement all
9
+ > fire — the mission payoff. Depends on: plan (#3), brain (#1), ledger (#2).
10
+ > Invoke via `/rafa build`.
11
+
12
+ Execute the approved plan with all three agents in the loop, knowledge served by the
13
+ platform MCP (one read path — the same surface any third-party agent uses).
14
+
15
+ ## The trio at build time
16
+
17
+ | Role | Agent | Job per task |
18
+ |---|---|---|
19
+ | **Executor** | atlas | RECALL the task's brain slice via MCP (`search_knowledge` + `get_rule`/`get_playbook`; honor non-exemplars) → implement, convention-adherent |
20
+ | **Validator** | prism | validate the execution against the child's `## Done-check` — strict, unbiased, against code + brain, never against atlas's claims. **`status: done` only on prism PASS**; FAIL → atlas corrects (validate-and-correct at work time). This gate is conductor-flow SOP — deterministic enforcement is the deferred capture-engine's job |
21
+ | **Improver** | bloom | **push**: new improvement opportunities spotted during execution → new ledger files. **close**: improvements fixed in passing → `status: fixed`. **nudge**: top-leverage open item in the task's blast radius — opt-in, never blocking |
22
+
23
+ ## Procedure
24
+
25
+ 1. **Resume** — `get_active_plan` (platform) or local `active.md`; staleness check
26
+ (envelope `brainForSha` vs local stamp → prompt `rafa push` if behind). MCP
27
+ recall is automatic throughout — SOP-driven, never dev-invoked; a repo without
28
+ the `rafinery` MCP connected falls back to local `.rafa/` file reads.
29
+ **Session consent (asked ONCE, verbs ENUMERATED):** *"keep the platform
30
+ updated as I work? That means exactly: (1) plan status + Log pushes on
31
+ cadence, (2) checkpointing this branch's working set (edited/new brain
32
+ files) — announced per file as it happens, (3) nothing else."* Revocable
33
+ anytime ("stop pushing"). On "no": journal locally only, push at the end on
34
+ approval. Dev-level insights are NEVER under this consent — each is its own
35
+ offer.
36
+ 2. **Per task:** atlas recalls → implements → prism validates vs `## Done-check` →
37
+ bloom sweeps (push new / close fixed / nudge) → update the child file's `status`
38
+ **and append a dated entry to the child's `## Log`** — what was done, what was
39
+ decided, what surprised (body prose: displayed verbatim on the platform, never
40
+ parsed; the plan files at `.rafa/plans/<plan>/` ARE the local cache) → at the
41
+ task-done CHECKPOINT (under the session consent): `push_plan` /
42
+ `update_plan_status` (the plans channel — statuses + Log journals) +
43
+ `rafa checkpoint` (the branch working set), so the platform and every MCP
44
+ consumer reflect live progress. Checkpoint moments: task done · plan
45
+ approved · explicit ask · cadence · git push/pull — never session-end. A
46
+ checkpoint CONFLICT (a teammate's newer copy of the same file) is decided
47
+ IN THIS SESSION: read the `.theirs.md` copy, merge/adopt/keep, re-checkpoint.
48
+ 3. **Brain changes mid-build — WHERE you are decides WHERE it goes.**
49
+ - **On the default branch (main):** run a full `/rafa scan` (regenerate →
50
+ prism → compile → push); the brain re-stamps at the new sha, so
51
+ `brain = f(code@sha)` stays exact.
52
+ - **On any other branch:** the org brain is NEVER written from a branch —
53
+ it describes main, and a branch-state scan would poison it for everyone.
54
+ Invalidated/learned knowledge → the branch **working set**: hydrate the
55
+ affected note (`rafa hydrate <rule|playbook> <id>`) and edit it, or author
56
+ a new note file under `.rafa/brain/**` — `rafa checkpoint` syncs it. It
57
+ enters the org brain at merge-to-main, through distillation. This is the
58
+ knowledge-propagates-like-code rule, enforced.
59
+ The working-set files ARE the sanctioned branch authoring surface — what is
60
+ never allowed is editing main's brain around the scan/compile/push gates.
61
+ 4. **Verify** (prism-style) before declaring the plan done; final `push_plan` +
62
+ `set_active_plan` (clear) + `rafa checkpoint`. A plan that stops being worth
63
+ finishing closes honestly: `superseded` or `abandoned`, never fake-`done`.
64
+
65
+ **Lite plans** (single-child, from plan-lite) run the same per-task loop — the
66
+ Done-check gate never relaxes; only the ceremony around it shrinks (no bloom nudge,
67
+ single checkpoint + plan push at the end).
68
+
69
+ ## Deferred / open
70
+ - **The capture engine** — `Stop`/`PostToolUse` hooks making the gates + capture
71
+ automatic rather than conductor-driven SOP (deterministic-enforcement lesson).
72
+ - **Incremental re-scan** — cite-graph invalidation (diff → invalidate notes citing
73
+ changed files → re-verify/regenerate only those). Needs: partial-brain cache-key
74
+ semantics + the seam-neighbor scope rule. Designed (see
75
+ .fable/sessions/2026-07-07-brain-versioning-and-incremental.md); first post-loop item.
76
+ - Show-thinking + pivot protocol from the atlas character.