@ritualai/cli 0.5.0 → 0.7.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 (73) hide show
  1. package/README.md +45 -16
  2. package/dist/commands/init.js +188 -20
  3. package/dist/commands/init.js.map +1 -1
  4. package/dist/index.js +0 -0
  5. package/dist/lib/oidc.js +60 -3
  6. package/dist/lib/oidc.js.map +1 -1
  7. package/package.json +73 -64
  8. package/skills/claude-code/ritual/DESIGN.md +35 -0
  9. package/skills/claude-code/ritual/SKILL.md +43 -370
  10. package/skills/claude-code/ritual/agents/openai.yaml +5 -0
  11. package/skills/claude-code/ritual/references/async-polling.md +26 -0
  12. package/skills/claude-code/ritual/references/build-flow.md +1449 -0
  13. package/skills/claude-code/ritual/references/cli-output-contract.md +135 -0
  14. package/skills/claude-code/ritual/references/context-pulse-flow.md +356 -0
  15. package/skills/claude-code/ritual/references/discovery-classification.md +175 -0
  16. package/skills/claude-code/ritual/references/lineage-flow.md +152 -0
  17. package/skills/claude-code/ritual/references/resume-flow.md +156 -0
  18. package/skills/claude-code/ritual/references/scoring-fallback.md +125 -0
  19. package/skills/codex/ritual/DESIGN.md +35 -0
  20. package/skills/codex/ritual/SKILL.md +43 -370
  21. package/skills/codex/ritual/agents/openai.yaml +5 -0
  22. package/skills/codex/ritual/references/async-polling.md +26 -0
  23. package/skills/codex/ritual/references/build-flow.md +1449 -0
  24. package/skills/codex/ritual/references/cli-output-contract.md +135 -0
  25. package/skills/codex/ritual/references/context-pulse-flow.md +356 -0
  26. package/skills/codex/ritual/references/discovery-classification.md +175 -0
  27. package/skills/codex/ritual/references/lineage-flow.md +152 -0
  28. package/skills/codex/ritual/references/resume-flow.md +156 -0
  29. package/skills/codex/ritual/references/scoring-fallback.md +125 -0
  30. package/skills/cursor/ritual/DESIGN.md +35 -0
  31. package/skills/cursor/ritual/SKILL.md +43 -370
  32. package/skills/cursor/ritual/agents/openai.yaml +5 -0
  33. package/skills/cursor/ritual/references/async-polling.md +26 -0
  34. package/skills/cursor/ritual/references/build-flow.md +1449 -0
  35. package/skills/cursor/ritual/references/cli-output-contract.md +135 -0
  36. package/skills/cursor/ritual/references/context-pulse-flow.md +356 -0
  37. package/skills/cursor/ritual/references/discovery-classification.md +175 -0
  38. package/skills/cursor/ritual/references/lineage-flow.md +152 -0
  39. package/skills/cursor/ritual/references/resume-flow.md +156 -0
  40. package/skills/cursor/ritual/references/scoring-fallback.md +125 -0
  41. package/skills/gemini/ritual/DESIGN.md +35 -0
  42. package/skills/gemini/ritual/SKILL.md +43 -370
  43. package/skills/gemini/ritual/agents/openai.yaml +5 -0
  44. package/skills/gemini/ritual/references/async-polling.md +26 -0
  45. package/skills/gemini/ritual/references/build-flow.md +1449 -0
  46. package/skills/gemini/ritual/references/cli-output-contract.md +135 -0
  47. package/skills/gemini/ritual/references/context-pulse-flow.md +356 -0
  48. package/skills/gemini/ritual/references/discovery-classification.md +175 -0
  49. package/skills/gemini/ritual/references/lineage-flow.md +152 -0
  50. package/skills/gemini/ritual/references/resume-flow.md +156 -0
  51. package/skills/gemini/ritual/references/scoring-fallback.md +125 -0
  52. package/skills/kiro/ritual/DESIGN.md +35 -0
  53. package/skills/kiro/ritual/SKILL.md +43 -370
  54. package/skills/kiro/ritual/agents/openai.yaml +5 -0
  55. package/skills/kiro/ritual/references/async-polling.md +26 -0
  56. package/skills/kiro/ritual/references/build-flow.md +1449 -0
  57. package/skills/kiro/ritual/references/cli-output-contract.md +135 -0
  58. package/skills/kiro/ritual/references/context-pulse-flow.md +356 -0
  59. package/skills/kiro/ritual/references/discovery-classification.md +175 -0
  60. package/skills/kiro/ritual/references/lineage-flow.md +152 -0
  61. package/skills/kiro/ritual/references/resume-flow.md +156 -0
  62. package/skills/kiro/ritual/references/scoring-fallback.md +125 -0
  63. package/skills/vscode/ritual/DESIGN.md +35 -0
  64. package/skills/vscode/ritual/SKILL.md +43 -370
  65. package/skills/vscode/ritual/agents/openai.yaml +5 -0
  66. package/skills/vscode/ritual/references/async-polling.md +26 -0
  67. package/skills/vscode/ritual/references/build-flow.md +1449 -0
  68. package/skills/vscode/ritual/references/cli-output-contract.md +135 -0
  69. package/skills/vscode/ritual/references/context-pulse-flow.md +356 -0
  70. package/skills/vscode/ritual/references/discovery-classification.md +175 -0
  71. package/skills/vscode/ritual/references/lineage-flow.md +152 -0
  72. package/skills/vscode/ritual/references/resume-flow.md +156 -0
  73. package/skills/vscode/ritual/references/scoring-fallback.md +125 -0
@@ -0,0 +1,1449 @@
1
+ ## /ritual build
2
+
3
+ Walks the engineer from a free-form problem statement to vetted, accepted Ritual recommendations using the vNext MCP tool surface.
4
+
5
+ Output: a fully-closed loop — **exploration in COMPLETE state, recommendations accepted (or explicitly handed off to an admin), build brief generated, code implemented, and `sync_implementation` called to register the result in the knowledge graph**. The engineer stays in the driver's seat through concise status updates and explicit pauses only at real decision gates.
6
+
7
+ ### Vocabulary mapping (engineer-tone)
8
+
9
+ The Ritual data model uses product-research terminology. This skill translates to engineer-natural terms when speaking to the user. The underlying API still uses original names — keep this table mental when you read tool inputs / outputs:
10
+
11
+ | User-facing term (the skill says) | Tool field name (the API uses) |
12
+ |---|---|
13
+ | **scope** | `problemStatement` |
14
+ | **sub-problem** | `consideration` |
15
+ | **matter** | `matter` (no rename — already the right word) |
16
+ | **discovery question** | `question` |
17
+ | **recommendation** | `recommendation` |
18
+
19
+ When the user says "tighten the scope," call `generate_problem_statement(...)` with their refinement. When you tell the user "I picked these sub-problems," you mean the items you put in `considerations[]`. The tools don't change; only the language to the user does.
20
+
21
+
22
+ ### Runtime contracts
23
+
24
+ Before running this flow, apply `references/cli-output-contract.md` and `references/async-polling.md`. Keep raw recon internal, pass the `codebase_context_packet` downstream, and show the user only the compact `recon_digest`.
25
+
26
+ ### When to use
27
+
28
+ - The user describes a new feature, refactor, migration, or implementation-heavy change that needs planning before coding
29
+ - The user wants the coding agent to gather codebase context, prior decisions, sub-problems, discovery questions, recommendations, and a build brief before implementation
30
+ - The user describes a problem they want explored ("we need to figure out X", "let's scope Y", "I want recommendations on Z")
31
+ - The user wants the full pipeline — sub-problems → scope → discovery → recommendations → build brief — not just one step
32
+ - The user runs `/ritual build` from inside a repo that already has explorations in the workspace — the resume path (Step 1.5) decides whether to continue an existing exploration or start a new one based on the per-exploration state badge
33
+
34
+ When **not** to use:
35
+ - The user already has a specific exploration id and just wants a quick status check — call `get_exploration` directly
36
+ - The user wants to *implement* a feature from a build brief that's already been generated and accepted — that's a separate downstream coding-agent task (the build brief itself is the input)
37
+
38
+ ### Workflow — 13 steps (Steps 10-13 cover the build-brief → implement → sync close-the-loop phase; unpicked considerations are preserved as later candidates by default)
39
+
40
+ Use explicit **[USER PAUSE]** only at decision gates. Pause when the user must choose among options, approve creation or acceptance, resolve ambiguity, authorize implementation, accept cost/time, or provide missing non-code context. Do **not** pause for status-only steps, safe defaults, internal recon, or silent checks.
41
+
42
+ ---
43
+
44
+ ### CLI and async guardrails
45
+
46
+ Follow `references/cli-output-contract.md` for terminal output, dense-list formatting, user-facing vocabulary, and the no-internal-step-label rule. Follow `references/async-polling.md` for every long-running server operation.
47
+
48
+ #### Step 1
49
+ #### Step 1 — Pick a workspace
50
+
51
+ Resolution order:
52
+
53
+ 1. **Project-bound workspace (preferred).** Check for a `.ritual/config.json` at the project root (you can use the Read tool — the file is a small JSON with `workspaceId` + `workspaceName`). If it exists, that's the workspace this repo is bound to. Use it without pausing.
54
+
55
+ User-visible:
56
+
57
+ > Using workspace: **{workspaceName}** from `.ritual/config.json`.
58
+ > Override with `workspace: list`.
59
+
60
+ Pause only if the file is missing/malformed, the workspace cannot be accessed, or the user explicitly asks to switch.
61
+ 2. **List existing project workspaces.** If no `.ritual/config.json`, call `mcp__ritual__list_workspaces` — this returns project-type workspaces (the General workspace is excluded by default; agents never use it). Present as a numbered list (id, name). **[USER PAUSE]** for selection.
62
+ 3. **Create a new one if none exist or user wants a fresh one.** Call `mcp__ritual__create_workspace` with a name — convention is to name it after the repo (basename of cwd, or origin remote). Confirm the name with the user first. **[USER PAUSE]**
63
+
64
+ Store `workspace_id` for the rest of the flow.
65
+
66
+ If you created a new workspace, persist the binding to `.ritual/config.json` so future runs in this repo skip the workspace-selection prompt. Write it yourself if you have filesystem write access; otherwise show the user the JSON and have them save it.
67
+
68
+ **`.ritual/config.json` is committed to the repo — it is shared, not per-user.** Same model as `.eslintrc.json` or `tsconfig.json`: it binds this codebase to a Ritual workspace + pins team-level defaults (workspaceId, defaultTemplateId). Everyone working on this repo wants the same values. Per-user state (PATs, auth tokens) lives in `~/.config/ritual/` and never in this file.
69
+
70
+ When you write the config, also write `.ritual/.gitignore` if it doesn't already exist so any future per-user state files in this directory get ignored while `config.json` itself stays tracked:
71
+
72
+ ```
73
+ # .ritual/.gitignore — auto-generated by the SKILL.
74
+ # config.json is repo-shared and meant to be committed (workspace
75
+ # binding + team defaults). Per-user state files go below.
76
+ *
77
+ !.gitignore
78
+ !config.json
79
+ ```
80
+
81
+ When you later see `.ritual/config.json` in `git status` output (modified or untracked), it's correct to commit it — don't ask the user whether it's per-user state; this comment is the answer.
82
+
83
+ #### Step 1.1 — No-arg `/ritual build` entry
84
+
85
+ If the user invokes `/ritual build` with no problem statement, set `raw_input = null` and **do not ask for a problem statement before checking the workspace**. A no-arg build is often a continuation or next-work discovery intent, so `resume` and `suggest high-leverage work` must remain available.
86
+
87
+ After workspace selection, proceed into the existing-exploration check below. User-facing copy should avoid internal step labels and should offer these paths when applicable:
88
+
89
+ ```text
90
+ I can help you continue existing work or find the next high-leverage thing.
91
+
92
+ {existing exploration summary, if any}
93
+
94
+ Reply with:
95
+ - a number/name to resume
96
+ - `suggest` to have me look for high-leverage candidates from repo + workspace history
97
+ - a feature/problem description to start fresh
98
+ - `none` to exit
99
+ ```
100
+
101
+ If there are **zero existing explorations** and `raw_input = null`, do not say "starting fresh" and do not advance to template selection yet. Ask for the feature/problem first:
102
+
103
+ ```text
104
+ No existing explorations in this workspace yet.
105
+
106
+ What would you like to build or explore? Describe the feature/problem, or run
107
+ `/ritual context-pulse <ask>` first if you want a readiness check before planning.
108
+ ```
109
+
110
+ If the user replies `suggest` but the workspace has no prior explorations, explain that suggestions need prior workspace signal and ask for a feature/problem instead.
111
+
112
+ #### Step 1.5 — Resume vs start (cognitive-debt check)
113
+
114
+ **Skip this step ONLY if you just created the workspace in Step 1 (no explorations possible yet).** Otherwise: before generating new sub-problems, check whether the user's intent might already be covered — partially or fully — by an existing exploration in this workspace.
115
+
116
+ The cost of skipping this step is high: an engineer mid-loop on a feature ends up with two parallel explorations on the same problem, the build brief grounds on the wrong one, and the knowledge graph gets diluted with near-duplicate decisions.
117
+
118
+ Steps:
119
+
120
+ 1. **Fetch the workspace's exploration list.** Call `mcp__ritual__list_explorations(workspace_id)`. Default returns each exploration with an `implementationStatus` block — the state badge tells you where each one stands without needing per-exploration follow-ups.
121
+
122
+ 2. **Filter to recent + relevant.** Sort by most recently updated. Drop archived. Cap at 5 in the user-facing summary (the rest stay available if asked).
123
+
124
+ 3. **Group by state badge** and surface to the user with a single message. Do not mention `Step 1.5` in the CLI.
125
+
126
+ If `raw_input` is present, frame this as an overlap/continuation check before starting fresh:
127
+
128
+ > I see {N} exploration{s} already in this workspace:
129
+ >
130
+ > **{state_glyph} {state_label}**
131
+ > - **{name}** — {short scope summary, first 80 chars of problemStatement}
132
+ > - {recommendationCount} rec{s} ({accepted}/{total} approved), {decisionsCount} decision{s} logged, {openDeferralsCount} open deferral{s}
133
+ > - {state-specific call-to-action — see table below}
134
+ >
135
+ > Recommended: resume one if it matches this work.
136
+ > Reply with a number/name to resume, `suggest` to find high-leverage candidates from repo + workspace history, or `proceed` to start fresh.
137
+
138
+ If `raw_input = null`, frame this as the user's no-arg start screen:
139
+
140
+ > I can help you continue existing work or find the next high-leverage thing.
141
+ >
142
+ > **{state_glyph} {state_label}**
143
+ > - **{name}** — {short scope summary, first 80 chars of problemStatement}
144
+ > - {recommendationCount} rec{s} ({accepted}/{total} approved), {decisionsCount} decision{s} logged, {openDeferralsCount} open deferral{s}
145
+ > - {state-specific call-to-action — see table below}
146
+ >
147
+ > Reply with:
148
+ > - a number/name to resume
149
+ > - `suggest` to have me look for high-leverage candidates from repo + workspace history
150
+ > - a feature/problem description to start fresh
151
+ > - `none` to exit
152
+
153
+ State badge → user-facing label + call-to-action:
154
+
155
+ | Glyph | State | User-facing label | Suggested next action |
156
+ |---|---|---|---|
157
+ | 📍 | `in_progress` | "still in discovery" | "Continue discovery" |
158
+ | 💬 | `awaiting_admin` | "waiting on admin to accept recommendations" | "Show recommendations for admin review" |
159
+ | ✅ | `ready` | "ready to implement" | "Generate the build brief and start coding" |
160
+ | 🛠 | `in_flight` | "implementation in progress" | "Resume — generate or refresh the build brief on remaining work" |
161
+ | ✓ | `done` | "fully shipped" | "Nothing to do here — start a new exploration if this is new scope" |
162
+ | ⚠ | `implemented_ahead` | "code shipped before admin acceptance" | "Surface to user — ask admin to review the implementation against the un-accepted recs, or update the recs to match what shipped" |
163
+
164
+ The `implemented_ahead` callout is load-bearing: it means a collaborator implemented a recommendation while it was still in `draft` or `pending_review`, and the snapshot column froze that timeline. The user (typically an admin) should know about this BEFORE you do anything else.
165
+
166
+ 4. **[USER PAUSE]** — wait for the user to pick resume / suggest / fresh / abort, or to provide a new feature/problem description.
167
+
168
+ 5. **If the user picks "resume":**
169
+ - Set `exploration_id` to the picked exploration.
170
+ - Use the state badge to decide which step to jump to (see "Suggested next action" column above).
171
+ - Skip ahead in this skill — don't re-run Steps 2-9 for an exploration that already has them done.
172
+ - For `ready` or `in_flight` states, jump directly to Step 10 (build brief generation).
173
+ - For `awaiting_admin`, jump to Step 9 (review + accept). Only an admin can move it forward; collaborators see the recs and proceed only if they're explicitly authorized to implement ahead.
174
+ - For `implemented_ahead`, surface the situation to the user and ask what to do — typically the admin reconciles by either approving the recs post-hoc (no code change needed) or updating the recs to match shipped reality.
175
+ - **For `done` or `in_flight` — branch-existence sanity check FIRST.** *(CLI Tenet #9 — sanity-check the world before trusting the database.)* The state badge is computed from `ImplementationRecord` rows in the KG. If the KG was seeded from synthetic/bootstrap data (a common state in early pilot deployments), the record can assert a PR/branch that doesn't exist in this repo. Before treating the exploration as ✓ shipped, verify:
176
+
177
+ ```bash
178
+ # If implementationRecord.branch is set:
179
+ git rev-parse --verify "origin/${implementationRecord.branch}" 2>/dev/null \
180
+ || git rev-parse --verify "${implementationRecord.branch}" 2>/dev/null
181
+
182
+ # If implementationRecord.prNumber is set (and `gh` is available):
183
+ gh pr view "${implementationRecord.prNumber}" --json state 2>/dev/null
184
+ ```
185
+
186
+ If neither resolves, surface this to the user as a single-action proposal (CLI Tenet #2):
187
+
188
+ > Note: per the KG this is shipped on `{branch}` (PR #{num}), but I don't see that branch in this repo or remote. The implementation record may be bootstrap/synthetic data.
189
+ >
190
+ > Treat as ready-to-implement-for-real? **(y/N, or tell me what's actually shipped)**
191
+
192
+ Don't paint 3-4 options ("treat as done / treat as fresh / inspect the KG row / something else") — one decisive proposal with a yes/no/correct-me escape hatch. If yes: jump to Step 10 (build brief). If no/correct-me: take the user's input as ground truth and update the next move accordingly.
193
+
194
+ - **For `ready` or `in_flight` — implementation footprint check FIRST.** *(Same shape as `/ritual resume` Step R3.5.)* The KG can't distinguish "brief generated, no code yet" from "mid-implementation, unsynced" from "implementation was started and then dropped" — all three look like `ready` because no `ImplementationRecord` exists until `sync_implementation` is called. Run the footprint probes using the `Ritual-Exploration: <id>` commit trailer mandated by Tenet #14:
195
+
196
+ ```bash
197
+ git log --all --grep="Ritual-Exploration: ${exploration_id}" --oneline 2>/dev/null
198
+ git rev-parse --verify "feat/${exploration_slug}" 2>/dev/null
199
+ gh pr list --search "Ritual-Exploration: ${exploration_id}" --state all --json number,state,headRefName 2>/dev/null
200
+ ```
201
+
202
+ The **dropped-work case** is the load-bearing one: `git log --all` finds attributed commits, but the branch is gone AND no PR exists. Without this check, the agent silently regenerates the brief and the user loses a day of work that was still recoverable from the reflog. Surface as:
203
+
204
+ > ⚠ I see {N} commits attributed to this exploration in your git history from {N} days ago, but the branch is gone and no PR was opened. Looks like the implementation was started and dropped. Want me to: **(a)** show you the orphan commits so you can recover them (`git cherry-pick`), OR **(b)** start fresh implementation from the brief?
205
+
206
+ Full decision table for all footprint shapes (mid-implementation, open PR, merged-but-unsynced, orphan-only, etc.) is in `/ritual resume` Step R3.5. Apply that table here verbatim when resuming via this path.
207
+
208
+ 6. **If the user picks "start fresh":** continue to Step 2 normally. The new exploration will sit alongside the existing ones; they're independent rows in the workspace.
209
+
210
+ 6b. **If the user picks `suggest` / "help me find the highest-leverage thing":**
211
+
212
+ This path is for the "I have context but no concrete problem yet" case. The agent does a light workspace scan FIRST so suggestions land on real codebase and prior-deferral signals, not generic advice. This is **not** focused feature recon because no problem has been selected yet; focused recon still happens after the user picks a candidate.
213
+
214
+ Steps:
215
+
216
+ a. **Run a light workspace scan** (15-30 seconds of work, faster than Step 3's focused recon):
217
+ - Glob top-level structure (README, package.json/setup.py, top dirs)
218
+ - Skim 3-5 most-load-bearing files
219
+ - Build a 5-10 line workspace scan summary: architecture shape, active modules, obvious seams, open deferral hotspots, and files tied to recent Ritual implementations
220
+ - Collect a sources[] array — the file paths you actually read, 5-10 entries
221
+
222
+ b. **Tell the user** what you found and that you're sourcing suggestions:
223
+
224
+ > Reading the codebase: {recon summary, ≤ 8 lines}
225
+ >
226
+ > Now asking the workspace for high-leverage problem candidates…
227
+
228
+ c. **Call `mcp__ritual__suggest_high_leverage_problems`:**
229
+
230
+ ```
231
+ {
232
+ workspace_id,
233
+ codebase_recon_summary: <the workspace scan summary from step a>,
234
+ sources: <the file paths from step a>
235
+ }
236
+ ```
237
+
238
+ One LLM call (~3-5 seconds). Returns up to 4 candidates with title, summary, rationale citing a specific signal (deferral, prior decision, etc.), and referencesPriorWork.
239
+
240
+ d. **Surface the candidates** as a numbered list, with the rationale prominent — that's what makes the suggestion auditable. Use the readability-first dense-list shape from the Developer-facing output contract, not compact wrapped paragraphs. Each candidate should have a blank line before the next candidate and labeled blocks for `Why high-leverage:` and `Touches:`:
241
+
242
+ ```text
243
+ Based on this workspace's state, here are {N} candidates ranked by leverage:
244
+
245
+ 1. {candidate.title}
246
+
247
+ {candidate.summary}
248
+
249
+ Why high-leverage:
250
+ {candidate.rationale — cite the specific RB, deferral, prior decision, shipped PR, or file-level signal.}
251
+
252
+ Touches:
253
+ {referencesPriorWork — list exploration names/ids, PRs, RB ids, or deferrals. Wrap if long.}
254
+
255
+
256
+ 2. {candidate.title}
257
+
258
+ {candidate.summary}
259
+
260
+ Why high-leverage:
261
+ {candidate.rationale}
262
+
263
+ Touches:
264
+ {referencesPriorWork}
265
+
266
+
267
+ Pick 1, 2, 3, or 4. Or say none and describe what you want directly.
268
+ ```
269
+
270
+ If one candidate would resume an existing in-flight exploration rather than create a duplicate, add a short note after the picker:
271
+
272
+ ```text
273
+ Note on #{N}:
274
+ There's already an in-flight exploration for {RB/problem}. If you pick it, route into
275
+ `/ritual resume` on that exploration rather than creating a duplicate.
276
+ ```
277
+
278
+ e. **[USER PAUSE]** — wait for the pick.
279
+
280
+ f. **If the user picks one (1-N):**
281
+ - Set the chosen candidate's `summary` as the `raw_input` for the rest of the flow.
282
+ - **Skip Step 1.5 step 8 (overlap check)** — the user just picked from system suggestions explicitly grounded in workspace state; a fresh overlap pass would be redundant noise.
283
+ - Continue to Step 2 (template selection).
284
+
285
+ g. **If the user says "none" / "let me describe":** continue to Step 2 normally; treat as if they had originally picked "start fresh" with no raw_input yet (they'll provide one at Step 3-4 time).
286
+
287
+ h. **If `suggestions` came back empty** (LLM produced nothing or workspace was too sparse): tell the user "I couldn't find anything to suggest — let's start with something you describe" and continue to Step 2.
288
+
289
+ 7. **If there are zero existing explorations** in the workspace:
290
+
291
+ - If `raw_input` is present: skip the user pause entirely. Say one line ("No existing explorations in this workspace — starting fresh.") and move to Step 2.
292
+ - If `raw_input = null`: pause and ask what they want to build/explore before moving to Step 2. Use the no-arg copy from Step 1.1.
293
+
294
+ Don't run the suggester from an empty workspace — there's no priors signal yet, and the user opening Ritual for the first time has stronger user-driven intent than the suggester could offer.
295
+
296
+ 8. **Before the user commits to "start fresh"** — if they DID say "start fresh" (or there were no existing explorations to resume) — run a **semantic overlap check** against the workspace. This catches the case where what the user is describing is a near-duplicate of something that already exists, BEFORE they burn LLM cost on Steps 4-5:
297
+
298
+ Call `mcp__ritual__check_exploration_overlap(workspace_id, raw_input)`. Pass the user's full natural-language description of what they want to explore as `raw_input` — the SAME text you'd later pass to `generate_considerations`.
299
+
300
+ The response:
301
+
302
+ ```
303
+ {
304
+ candidates: [{
305
+ explorationId, name, problemStatement,
306
+ jaccardScore, llmConfidence, llmRationale
307
+ }],
308
+ totalCandidatesScanned: number
309
+ }
310
+ ```
311
+
312
+ - **If `candidates.length === 0`**: silently proceed to Step 2. Don't mention the overlap check happened. The whole point of the two-tier filter is silence in the common case.
313
+
314
+ - **If `candidates.length > 0`**: surface a callout BEFORE moving to Step 2:
315
+
316
+ > ⚠ **What you're describing may overlap with existing explorations in this workspace:**
317
+ >
318
+ > {for each candidate (in order, strongest first):}
319
+ > **{candidate.name}** *(LLM confidence: {Math.round(candidate.llmConfidence * 100)}%)*
320
+ > - *"{candidate.problemStatement first 120 chars, no ellipsis padding}..."*
321
+ > - Why I think it overlaps: {candidate.llmRationale}
322
+ > - URL: `https://dev.ritualapp.cloud/e/{candidate.explorationId}`
323
+ > {endfor}
324
+ >
325
+ > **Choose:**
326
+ > 1. **Resume one of these instead** — give me the number, I'll jump to the right step based on its state.
327
+ > 2. **Proceed anyway** — I'll create a new exploration. The relationship to these {N} won't be lost — when `related_exploration_ids` is supported it'll be captured automatically.
328
+ > 3. **Show me one in detail first** — give me the number, I'll fetch its full state before you decide.
329
+
330
+ - If the user picks (1): treat the chosen one as the resumed exploration (same as Step 1.5 step 5 above — jump to the right downstream step based on the state badge).
331
+ - If the user picks (2): continue to Step 2. Future PR will populate `related_exploration_ids` on the new exploration so the linkage is preserved.
332
+ - If the user picks (3): show the full exploration via `mcp__ritual__get_exploration` + `get_recommendations` if any exist, then loop back to the choose prompt.
333
+
334
+ **Calibration:** the threshold for surfacing is conservative — the agent is biased toward "miss not false-flag" (you'd rather silently skip a real overlap than noisily prompt the user when there isn't one). If you DO see this prompt, take it seriously — it's likely there's real overlap.
335
+
336
+ #### Step 2 — Template selection
337
+
338
+ Templates shape the structure of considerations, the problem statement, and the final deliverable artifact (PRD, spec, brief, etc.). A `/ritual build` flow from inside a coding agent usually wants an engineering-flavored template, but the user must retain an easy override path.
339
+
340
+ Resolution order:
341
+
342
+ 1. **Project-pinned default (preferred).** Check `.ritual/config.json` for a `defaultTemplateId` field. If present, the project has a pinned team template — use it without pausing.
343
+
344
+ User-visible:
345
+
346
+ > Template
347
+ > Using **{templateName}** from `.ritual/config.json`.
348
+ > Override anytime with `template: list` or `template: {name}`.
349
+
350
+ 2. **Pick a recommended default + offer alternatives.** If no `.ritual/config.json` pin exists, call `mcp__ritual__list_templates`. From the response, pick the first template matching this fallback chain:
351
+ - Name matches `/Feature Specification.*Agentic Coding/i` — canonical default for code-aware builds
352
+ - Name matches `/Technical Detail PRD/i`
353
+ - Name matches `/Engineering Spec|Technical (Detail|Spec)/i`
354
+ - First SYSTEM-type template in the list (last resort)
355
+
356
+ User-visible as a **[USER PAUSE]**:
357
+
358
+ > Template
359
+ > Recommended: **{templateName}** — {short description}
360
+ >
361
+ > Reply `go`, `list`, or `template: {name}`.
362
+
363
+ 3. **If the user types `list`:** present a numbered menu of all SYSTEM-type templates. Skip CUSTOM templates by default to avoid menu sprawl unless the user gives a specific custom id/name. Each line: `{N}. {name} — {short description}`. Wait for a number selection.
364
+
365
+ 4. **If the user types `template: {name}` or picks one by name:** find the case-insensitive partial match in the template list. If ambiguous, show only the matching options and ask which one. If no match, show the SYSTEM template menu.
366
+
367
+ 5. **Remember `template_id`.** It passes through every subsequent phase — `generate_considerations`, `refine_considerations`, `generate_problem_statement`, `refine_problem_statement`, and ultimately `create_exploration`. The API uses it to load template-specific anti-patterns + focus keywords into the LLM prompt, so it materially shapes output quality.
368
+
369
+ 6. **Track role silently; surface only the operational default.** Infer `role` from the selected template and carry it forward for:
370
+ - recommendation tone
371
+ - sibling exploration cap
372
+ - Step 8 run-mode default
373
+
374
+ Do **not** explain the inference or ask for role confirmation by default.
375
+
376
+ User-visible after the template is selected:
377
+
378
+ > Defaulting to **{role}** flow. Override with `role: product`, `role: design`, etc.
379
+
380
+ Recognized roles (use the role keyword the API returns, not a paraphrase):
381
+ - `engineering` — code-aware, technical depth
382
+ - `product` — PRDs, product briefs, market positioning
383
+ - `design` — UX research, design briefs
384
+ - `marketing` — campaigns, launch plans, GTM
385
+ - `delivery` — sprint plans, release plans
386
+ - `operations` — SOWs, ops planning
387
+
388
+ Pause only if:
389
+ - the template name is ambiguous,
390
+ - the user explicitly questions the role,
391
+ - the chosen role changes a costly or irreversible path,
392
+ - or no pinned/recommended default exists.
393
+
394
+ If the user corrects the role (e.g. "actually I'm building a PRD"), update internal role tracking. Do **not** re-pick the template unless the user explicitly asks to change it.
395
+
396
+ 7. **Suggest persistence only when useful.** If you picked a default from the template list and the user accepted with `go` rather than choosing a different one, suggest:
397
+
398
+ > Want me to pin this template for future `/ritual build` runs in this repo? I can add `"defaultTemplateId": "{id}"` to `.ritual/config.json`.
399
+
400
+ If the user says yes, write the field while preserving existing keys. This is a TEAM pin — `.ritual/config.json` is committed to the repo per Step 1, so the whole team picks up the same default.
401
+
402
+ Proceed to Step 3 once a template is selected. No extra confirmation is required after a pinned template or an accepted default.
403
+
404
+ #### Step 3 — Code reconnaissance
405
+
406
+ **Skip only if the user explicitly asks ("just generate, don't read the code") OR if you're operating outside a codebase context.**
407
+
408
+ Before generating considerations, gather codebase context so the sub-problems land specific to *this* code, not generic. The goal is not to show the user every fact you found; the goal is to ground downstream MCP calls and expose only decision-relevant findings in the CLI.
409
+
410
+ ##### 3.0 — Check for a pre-build context seed
411
+
412
+ Before doing fresh recon, check whether the user already seeded one via `/ritual context-pulse`. Glob for `CONTEXT-*.md` at the repo root.
413
+
414
+ If a `CONTEXT-<slug>.md` is found AND its `## The ask` section close-matches the current `raw_input`:
415
+
416
+ - **Use it to seed `codebase_context_packet`.** Parse the file's `## Candidate files` list — those become the seed for `sources[]`. Parse `## Prior KG context` as evidence inside the packet, not as final prioritization.
417
+ - **Skip fresh recon** unless the seed is stale or obviously incomplete. If you skip fresh recon, still normalize the seed into the packet structure below before calling MCP tools.
418
+ - **Surface a compact note**:
419
+ > Code recon
420
+ > Found `CONTEXT-<slug>.md` from `/ritual context-pulse`.
421
+ > Using {N} candidate files + {M} prior KG decisions as the recon base. Override with `recon: refresh`.
422
+ - Proceed directly to 3.2.
423
+
424
+ If no seed file is found, OR the seed's `## The ask` doesn't match the current `raw_input`, do fresh recon. For mismatch, mention the ignored seed in one line and do not delete it.
425
+
426
+ ##### 3.1 — Fresh recon
427
+
428
+ 1. **Read the README + top-level project structure.** Use `ls` / Glob to see top-level files. Identify the language, framework, key directories, and likely entry points.
429
+
430
+ 2. **Glob for relevance.** Derive patterns from the user's problem. Examples:
431
+ - User says "auth flow" → `**/auth/**`, `**/login*`, `**/user*`, `**/session*`
432
+ - User says "checkout" → `**/checkout/**`, `**/cart/**`, `**/order/**`, `**/payment*`
433
+ - User says "notifications" → `**/notif*`, `**/email/**`, `**/sms/**`, `**/push/**`
434
+ Cap at ~15 hits per pattern.
435
+
436
+ 3. **Skim 3–5 most-relevant files.** For each, read the first ~100 lines + scan for class/function names. Triangulate whether the behavior lives there or calls into another area.
437
+
438
+ 4. **Build three recon artifacts.**
439
+
440
+ A. `raw_recon_notes` — internal evidence only
441
+ - files read and why they were selected
442
+ - symbols/classes/functions inspected
443
+ - relevant comments, schema details, tests, migrations, and config
444
+ - KG hits, prior deferrals, and prior implementation references
445
+ - uncertain observations, false leads, and things not found
446
+ - do **not** show this by default and do **not** pass it as the main MCP planning input
447
+
448
+ B. `codebase_context_packet` — downstream planning input
449
+ - this is the synthesized artifact passed into `raw_input`, context pulses, and any MCP field named `recon_context`
450
+ - it helps MCP understand what the coding agent observed locally without deciding the final considerations itself
451
+ - separate factual observations from agent hypotheses
452
+ - include confidence levels for hypotheses
453
+ - use neutral labels like `agent_observed_scope_pressure` or `candidate_scope_pressure`, not `priority_considerations`
454
+ - never present the packet as authoritative; MCP/tooling decides final sub-problems, recommendations, and scope
455
+
456
+ C. `recon_digest` — user-visible, compact
457
+ - 3–6 bullets max
458
+ - key surfaces, hard constraints, scope corrections, and next action
459
+ - avoid quoting code comments unless they are load-bearing
460
+ - avoid listing every file read
461
+
462
+ `codebase_context_packet` structure:
463
+
464
+ ```markdown
465
+ --- Codebase context packet ---
466
+
467
+ ## User intent
468
+ {verbatim or lightly normalized ask}
469
+
470
+ ## Observed relevant surfaces
471
+ - `path` — observed role in this feature or constraint
472
+ - `path` — observed extension point, lifecycle, model, or integration seam
473
+
474
+ ## Evidence
475
+ - `path:symbol` — factual observation from code
476
+ - Prior Ritual signal: {exploration / PR / RB / deferral}, if available
477
+ - Missing or not-found evidence when it corrects the user's framing
478
+
479
+ ## Agent hypotheses
480
+ - This may make {candidate area} important because {evidence-backed reason}
481
+ Confidence: low / medium / high
482
+
483
+ ## Agent-observed scope pressure
484
+ - Privacy / lifecycle / migration / compatibility / async / ownership / testing risk
485
+ - Only include pressure that intersects with the feature intent and code evidence
486
+
487
+ ## Scope corrections
488
+ - The ask says X, but the code suggests Y
489
+ - Missing fields, renamed concepts, or assumptions the code contradicts
490
+
491
+ ## Open questions for discovery
492
+ - Questions the code cannot answer and the user/Ritual exploration should resolve
493
+ ```
494
+
495
+ Example `codebase_context_packet` excerpt:
496
+
497
+ ```markdown
498
+ ## Observed relevant surfaces
499
+ - `apps/conversions/abstract_models.py` — append-only conversion event model; lifecycle changes are modeled as follow-up rows.
500
+ - `apps/conversions/outbox.py` — async publish/retry surface; payload shape may affect erasure semantics.
501
+ - `apps/order/models.py` — raw guest email appears to live on the order side, not in conversion events.
502
+
503
+ ## Agent hypotheses
504
+ - Erasure semantics may need to cover both mutable raw PII and append-only pseudonymous digests.
505
+ Confidence: high; supported by model fields and schema comments.
506
+ - Outbox purge/replay behavior may be a scope pressure because retries can outlive the original conversion write.
507
+ Confidence: medium; verify worker idempotency before scoping implementation.
508
+
509
+ ## Scope corrections
510
+ - No `guest_session_id` column was found in the inspected conversion models; scope may need to use the actual guest attribution identifiers.
511
+ ```
512
+
513
+ Example `recon_digest`:
514
+
515
+ ```text
516
+ Code recon complete
517
+
518
+ Key surfaces:
519
+ - `apps/conversions/abstract_models.py` — append-only conversion events.
520
+ - `apps/conversions/outbox.py` — async publish/retry lifecycle.
521
+ - `apps/order/models.py` — raw guest email surface.
522
+
523
+ Constraint:
524
+ - Erasure likely needs to handle mutable raw PII separately from pseudonymous conversion digests.
525
+
526
+ Scope correction:
527
+ - I did not find `guest_session_id` in the inspected models.
528
+
529
+ Next: attach PRDs/tickets if they should shape scope, or proceed.
530
+ ```
531
+
532
+ ##### 3.2 — Surface the digest and continue
533
+
534
+ Surface only `recon_digest` by default. Do **not** dump `raw_recon_notes` or the full `codebase_context_packet` to the CLI unless the user asks for detail.
535
+
536
+ Pause only if:
537
+ - recon contradicts the user's stated scope,
538
+ - there are multiple plausible implementation areas and choosing wrong would waste work,
539
+ - a legal/product/business constraint is required before generation,
540
+ - the user explicitly asked to review recon before continuing.
541
+
542
+ If no pause is needed, proceed to Step 3.5. The user still has a cheap escape hatch: `recon: detail`, `recon: refresh`, or a correction in plain English.
543
+
544
+ **Pulse (Step 3 done):** Emit a pulse line — repo grounding just moved meaningfully (sources collected, agent inspected files, possibly KG hits). Compute per `/ritual context-pulse` § Step CP3 and render compact unless this is the FIRST pulse of the build flow, in which case use full.
545
+
546
+ ##### 3.3 — Compose augmented `raw_input`
547
+
548
+ Compose the augmented `raw_input` for Step 4 from:
549
+ - the user's original problem (verbatim, top)
550
+ - the full `codebase_context_packet`, under `--- Codebase context packet ---`
551
+ - any user correction or added constraint from code recon
552
+
553
+ Do not pass unsynthesized `raw_recon_notes` as the primary planning input. Step 3 is the difference between generic considerations and considerations grounded in actual code, patterns, risks, and open questions. Keep `raw_recon_notes` internally for auditability; pass the packet downstream for planning.
554
+
555
+ ##### 3.4 — Collect the `sources` array
556
+
557
+ Collect the file paths you actually read and consider load-bearing for this problem — exactly as they appear in the repo (e.g. `"apps/checkout/views.py"`, not `"./apps/checkout/views.py"` or absolute paths). This list is passed alongside `raw_input` to `generate_considerations`, `generate_problem_statement`, `query_knowledge_graph`, context pulses, and `generate_build_brief` so the API can anchor priorContext consistently.
558
+
559
+ Keep the list focused. 5–10 is the sweet spot; >20 dilutes the KG signal.
560
+
561
+ #### Step 3.5 — Stage knowledge sources (PRDs / tickets / transcripts / etc.)
562
+
563
+ The codebase recon you just did handles the *code* grounding. Most real features ALSO have non-code context — PRDs, Jira/Linear tickets, design specs, meeting transcripts, Slack threads, customer-research notes — that get paraphrased into the problem statement and lose detail. Step 3.5 ingests those as first-class **knowledge sources** attached to the exploration BEFORE generating sub-problems, so the priorContext you'll see in Step 4 (`generate_considerations`) and downstream is grounded in what the user actually brought, not the paraphrase.
564
+
565
+ ##### 3.5.1 — Prompt the user only when useful
566
+
567
+ Knowledge sources are a feature multiplier, not a mandatory gate. Ask for PRDs/tickets/designs/transcripts only when at least one of these is true:
568
+
569
+ - the ask is ambiguous or cross-functional,
570
+ - context-pulse / Reference Grounding is low,
571
+ - the user mentioned a PRD, ticket, design, chat, customer request, or meeting,
572
+ - the feature has legal, privacy, billing, permissions, enterprise, analytics, migration, or compliance constraints,
573
+ - code recon found implementation surfaces but not product intent.
574
+
575
+ When triggered, surface a single ask (CLI Tenet #2 — one recommended action with a cheap escape):
576
+
577
+ > Any PRDs, tickets, designs, transcripts, or chat excerpts that should shape this? Paste paths / URLs now, or say `skip`.
578
+
579
+ Wait for the user to either provide refs or skip.
580
+
581
+ If none of the triggers apply, do **not** block. Print a non-blocking line and proceed:
582
+
583
+ > Proceeding with codebase context only. Paste a PRD/ticket anytime before discovery if it should shape the scope.
584
+
585
+ ##### 3.5.2 — Read the content
586
+
587
+ For each item the user provided, use the agent's local tools to obtain the text content. Different routes by what the user supplied:
588
+
589
+ | What the user provided | What to do |
590
+ |---|---|
591
+ | Local file path (PDF, markdown, txt, png, pptx, docx) | `Read` the file. For binary files (PDF/image/pptx) the agent's Read tool returns extracted text or visual description; for text files just read the bytes. |
592
+ | URL (Confluence / Notion / Jira / Linear / public web) | `WebFetch` the URL to get the text content. |
593
+ | Pasted text | Use the pasted text directly. |
594
+ | Local directory | `Glob` for likely docs (`*.md`, `*.pdf`, `*.docx`), then Read each. Cap at 5 files unless user says otherwise. |
595
+
596
+ Detect each item's **`source_content_type`** from format + content cues:
597
+
598
+ - Filename + content shape: `prd.md` with "Problem statement" → `PRD`; `*.pdf` with "Slide 1" markers → could be `PRD` or `SPEC` depending on body; user research notes with multiple speakers + timestamps → `TRANSCRIPT`.
599
+ - URL host: `*.atlassian.net` / `linear.app` / GitHub issue URL → `TICKET`; generic blog/docs URL → `URL`; Slack/Discord export → `CHAT`.
600
+ - Content signal: presence of `endpoints` / `paths:` / `openapi:` → `SPEC`; image binary → `IMAGE`; multi-speaker + timestamps → `TRANSCRIPT`.
601
+ - If ambiguous: prefer the broader category (`DOC` over `OTHER`; ask user when in doubt for high-leverage items).
602
+
603
+ ##### 3.5.3 — Stage each source for registration after exploration creation
604
+
605
+ For each item, create a staged source record in working memory. Do **not** call `mcp__ritual__add_knowledge_source` yet because no `exploration_id` exists until exploration creation.
606
+
607
+ Staged record shape:
608
+
609
+ ```json
610
+ {
611
+ "source_content_type": "PRD | TICKET | URL | CHAT | TRANSCRIPT | SPEC | DOC | IMAGE | OTHER",
612
+ "content": "<full text content the agent obtained>",
613
+ "title": "<explicit title | first H1 | filename | TYPE from date>",
614
+ "source_url": "<original URL if applicable>",
615
+ "source_path": "<original local path if applicable>",
616
+ "origin_feature": "DISCOVERY"
617
+ }
618
+ ```
619
+
620
+ Surface only a staging summary:
621
+
622
+ > Staged **{title}** ({source_content_type}) for this exploration. I'll register it after the exploration is created; the content is already in my context for planning.
623
+
624
+ ##### 3.5.4 — Update the augmented `raw_input` + score impact
625
+
626
+ The content the agent collected in Step 3.5.2 also gets folded into the augmented `raw_input` for Step 4's `generate_considerations` so the LLM sees the references inline:
627
+
628
+ ```
629
+ {original user problem}
630
+
631
+ --- Codebase context ---
632
+ {codebase_context_packet from Step 3}
633
+
634
+ --- Reference context (provided by user) ---
635
+ [PRD — billing-export.md]
636
+ {first ~2000 chars of content, marked with type + title}
637
+
638
+ [TRANSCRIPT — billing planning sync 2026-05-09]
639
+ {...}
640
+
641
+ [TICKET — LINEAR-1234]
642
+ {...}
643
+ ```
644
+
645
+ Cap the inline reference context at ~10000 chars total (priority: PRD/SPEC > TRANSCRIPT/TICKET > CHAT/DOC > URL > IMAGE). Longer refs stay accessible via `get_knowledge_source` after extraction completes, but for THIS build the inline summary keeps the LLM call bounded.
646
+
647
+ ##### 3.5.5 — Pulse impact
648
+
649
+ Each registered knowledge source contributes to **Repo Grounding** (which, despite the name, covers BOTH code grounding from Step 3 AND reference grounding from Step 3.5 — the dimension will be split in MVP-2). For MVP-1 scoring (per `/ritual context-pulse` § CP3):
650
+
651
+ - Repo Grounding gets +5 points per registered knowledge source, capped at +15 total (so 3+ refs is the cap).
652
+ - Combined with code-recon signals already in the dimension, Repo Grounding stays in the 0-100 range.
653
+ - After Step 3.5 completes, fire the standard Step 3 pulse — the user will see Repo Grounding jump if they attached refs.
654
+
655
+ ##### 3.5.6 — Skip path
656
+
657
+ If the user says "skip" / "none" / "later", proceed silently to Step 4. Do NOT pressure for more — refs are a feature multiplier, not a requirement.
658
+
659
+ The user can always come back later with `/ritual context-pulse <exploration>` to see the current Reference Grounding score, OR drag refs in mid-flow (e.g. at Step 8 if the agentic run surfaces a question that a PRD would have answered).
660
+
661
+ #### Step 4 — Generate sub-problems
662
+
663
+ ##### 4.1 First draft
664
+
665
+ Call `mcp__ritual__generate_considerations` with:
666
+ - `workspace_id`
667
+ - `raw_input` (the user's problem + the Step 3 `codebase_context_packet` + any reference context, concatenated as described above)
668
+ - `template_id` (the one picked in Step 2 — should always be set by this point)
669
+ - `sources` (the file path list from Step 3 step 7 — file-path strings only, e.g. `["apps/checkout/views.py", ...]`)
670
+
671
+ LLM call, ~5–10s. Returns 5–6 sub-problems — different framing axes the system should investigate. Track each one as `{ text, version: 1 }` in your working memory.
672
+
673
+ The coding agent's packet is context, not authority. Do not pre-rank or collapse the generated sub-problems based only on the agent hypotheses. Let MCP/template/KG output determine the candidate considerations; use the packet to make them specific, evidenced, and grounded.
674
+
675
+ **If the response includes `kg_context_used` with `implementationCount > 0`:** surface this to the user BEFORE presenting the considerations. It's the visible signal that prior team decisions shaped this draft.
676
+
677
+ > Reading the codebase I overlapped with 3 prior Ritual explorations on these files:
678
+ > - **"Anonymous checkout opt-in"** (shipped 2026-04-12) — 2 decisions, 1 deferral
679
+ > - **"Payment-method routing"** (shipped 2026-03-22) — 4 decisions
680
+ > - **"Session-data persistence"** (shipped 2026-02-08) — 1 decision
681
+ >
682
+ > I factored those into the sub-problems below.
683
+
684
+ If `implementationCount === 0`: don't mention the KG check (silent — would just be noise on a cold KG).
685
+
686
+ **[USER PAUSE]** Present as a numbered list and ask which to include:
687
+
688
+ > Sub-problems the system identified (v1):
689
+ >
690
+ > 1. {sub-problem 1}
691
+ > 2. {sub-problem 2}
692
+ > ...
693
+ >
694
+ > Which should we factor into the scope? Pick any subset, "all", or ask for a different framing (e.g. "make them more technical", "drop the measurement angle", "focus on enterprise").
695
+
696
+ ##### 4.2 Iteration loop
697
+
698
+ If the user asks for a refinement (anything that isn't "all" / specific picks / "these are good"):
699
+
700
+ Call `mcp__ritual__refine_considerations` with:
701
+ - `workspace_id`, `raw_input`, `template_id`, `sources` — unchanged from the generate call. Critical: pass the SAME `sources` array each iteration so the KG-injected priorContext stays consistent.
702
+ - `change_prompt`: the user's request verbatim
703
+ - `selected`: items from prior versions the user kept (track `{ text, from_version }`, send just `text`)
704
+ - `dismissed`: items the user explicitly rejected
705
+ - `session_id`: omitted on the first refinement; pass the `session_id` from the previous refine response on subsequent ones to chain context
706
+
707
+ Track the new items as `{ text, version: N+1 }`. Present **alongside** the prior versions, not replacing them — the user can mix selections across versions.
708
+
709
+ Loop until the user says "these are good" or picks a subset.
710
+
711
+ **Critical**: never re-call `generate_considerations` for a refinement. That endpoint is stateless and re-rolls a fresh seed; you'll lose what the user just told you. The whole point of `refine_*` is the LLM sees the iteration context.
712
+
713
+ Store the final picked sub-problems for Step 5 — they go into `considerations[]`.
714
+
715
+ #### Step 5 — Generate scope
716
+
717
+ ##### 5.1 First draft
718
+
719
+ Call `mcp__ritual__generate_problem_statement` with:
720
+ - `workspace_id`
721
+ - `raw_input` (same augmented version from Step 4)
722
+ - `considerations` (the picks from Step 4)
723
+ - `template_id` (same as Step 4 — the one picked in Step 2)
724
+ - `sources` (the same file-path list passed to generate_considerations — keeps the KG anchor consistent)
725
+
726
+ Returns a polished "How might we ..." style scope (typically <800 chars) plus optional follow-up questions and quality scores. Treat this as **v1** of the problem statement.
727
+
728
+ If the response includes `kg_context_used` with `implementationCount > 0`, prepend a note to the scope presentation:
729
+
730
+ > *(Grounded in {N} prior implementation{s}: {top match name}, …)*
731
+
732
+ **[USER PAUSE]** Present and ask:
733
+
734
+ > Here's the scope (v1):
735
+ >
736
+ > > **{generated scope}**
737
+ >
738
+ > Looks good? Want to tighten / broaden / change the audience / focus on a specific tier? Or "ship it" to lock it in.
739
+
740
+ ##### 5.2 Iteration loop
741
+
742
+ If the user asks for a refinement:
743
+
744
+ Call `mcp__ritual__refine_problem_statement` with:
745
+ - `workspace_id`, `raw_input`, `considerations`, `template_id`, `sources` — unchanged. (Same `sources` as the original generate call — keeps the KG anchor stable.)
746
+ - `previous_problem_statement`: the FULL TEXT of the current best draft (the v1 you just showed)
747
+ - `change_prompt`: the user's request verbatim ("tighten and drop the audience clause")
748
+ - `version`: optional label like `"v2"` — purely for telemetry
749
+ - `session_id`: omitted on the first refinement; chain on subsequent ones
750
+
751
+ The returned text becomes `v2`. Show it. The user can iterate v2 → v3 → ... by calling refine again with `previous_problem_statement` set to the latest draft.
752
+
753
+ **Critical**: each refinement's `previous_problem_statement` is the LATEST draft, not the original v1. Otherwise the LLM keeps refining the same starting point and the user can't compose multiple refinements ("tighter, AND drop the audience clause, AND make it past-tense").
754
+
755
+ When the user accepts ("ship it" / "looks good"), store the final text as `problem_statement` for Step 6.
756
+
757
+ **Pulse (Step 5 done):** Emit a pulse — feature clarity just jumped (problem statement accepted; actor / behavior / acceptance signals are now scorable). Compute per `/ritual context-pulse` § Step CP3. Render full if this crosses Raw ask → Under-specified, else compact.
758
+
759
+ #### Step 6 — Create the exploration
760
+
761
+ Generate a short name (≤60 chars) from the scope — typically the noun phrase, not the full HMW. E.g. "Reduce T2 customer churn in Q3" → name `T2 churn reduction (Q3)`.
762
+
763
+ **[USER PAUSE]** "I'll create the exploration as **T2 churn reduction (Q3)**. Proceed?"
764
+
765
+ Call `mcp__ritual__create_exploration` with:
766
+ - `workspace_id`
767
+ - `name`
768
+ - `problem_statement` (the scope from Step 5)
769
+ - `agentic: false` — **do NOT** pass `agentic: true`. We want explicit per-step control so the user gets to pick discovery questions in Step 7. Auto-agentic skips that.
770
+
771
+ Store `exploration_id`. Show the URL:
772
+
773
+ > Exploration created. Track progress at https://dev.ritualapp.cloud/e/{exploration_id}
774
+
775
+ ##### 6.1 — Promote the pre-build seed (if one was consumed in Step 3.0)
776
+
777
+ If Step 3.0 consumed a `CONTEXT-<slug>.md` seed file, promote it into the exploration's artifact trail now that an exploration id exists. Move + rename the file from `CONTEXT-<slug>.md` to `.ritual/exploration-notes/<exploration-id>.md` using the Bash tool:
778
+
779
+ ```bash
780
+ mkdir -p .ritual/exploration-notes
781
+ git mv CONTEXT-<slug>.md .ritual/exploration-notes/<exploration-id>.md 2>/dev/null \
782
+ || mv CONTEXT-<slug>.md .ritual/exploration-notes/<exploration-id>.md
783
+ ```
784
+
785
+ Surface to the user as a one-line note:
786
+
787
+ > Promoted `CONTEXT-<slug>.md` → `.ritual/exploration-notes/<exploration-id>.md` so it stays tied to this exploration.
788
+
789
+ This keeps the repo root clean (CLI Tenet #1 — files for reference, not clutter) and preserves the seed's content for future `/ritual lineage` or audit lookups. The file remains git-tracked at the new path.
790
+
791
+ If `git mv` fails (file wasn't tracked yet): use plain `mv` instead — same outcome, the user just commits the move whenever they next commit.
792
+
793
+ #### Step 6.5 — Preserve unpicked considerations without cluttering the workspace
794
+
795
+ Unpicked or dismissed considerations are useful signal, but automatically creating sibling explorations can clutter the workspace. Do **not** fork sibling explorations by default.
796
+
797
+ Default behavior:
798
+
799
+ 1. If `dismissed[]` or unpicked considerations are empty, skip silently.
800
+ 2. If there are unpicked considerations, preserve them in working memory as `phase_later_candidates[]` for the current build.
801
+ 3. Append the concise set to the build brief's `recon_context` payload under a heading like `Explicit phase/later candidates from discovery` so they can appear in **Phase Candidates / Deferrable Items** if relevant. Keep the base of `recon_context` as the `codebase_context_packet`, not raw notes.
802
+ 4. Surface at most one compact line:
803
+
804
+ > Saved {N} unpicked sub-problem{s} as later candidates for the brief.
805
+
806
+ Only call `mcp__ritual__fork_sibling_explorations` when the user explicitly asks to save separate tracks, or when an unpicked item maps cleanly to a known open deferral / existing exploration and the user confirms.
807
+
808
+ If sibling creation is confirmed, call:
809
+
810
+ ```
811
+ {
812
+ primary_exploration_id: <id from Step 6>,
813
+ unpicked_considerations: dismissed.map(d => d.text)
814
+ }
815
+ ```
816
+
817
+ Then summarize the created siblings in the dense-list format. Do not pause after creation; return to the primary build flow.
818
+
819
+ #### Step 7 — Discovery questions
820
+
821
+ Longest phase because generation is async + the user picks per-matter.
822
+
823
+ ##### 7.1 — Kick off
824
+
825
+ Call `mcp__ritual__suggest_discovery_questions(exploration_id)`. Returns immediately with `task_id`. Tell the user:
826
+
827
+ > Generating discovery questions for each matter… 30-120 seconds.
828
+
829
+ ##### 7.2 — Poll until ready
830
+
831
+ Loop:
832
+ - Call `mcp__ritual__get_discovery_state(exploration_id)`
833
+ - If `ready: false`, wait 5 seconds, poll again
834
+ - If `ready: true`, exit loop
835
+
836
+ Don't poll faster than every 5 seconds. Follow the global polling rule above: single `Bash sleep 5` per iteration and a one-line update every ~3 polls (~15s).
837
+
838
+ ##### 7.3 — Present matters and collect picks
839
+
840
+ The state contains `matters[]`, each with `id`, `name`, and `questions[]`. Walk through them **one matter at a time**:
841
+
842
+ > **{matter.name}** — {matter.questions.length} discovery questions:
843
+ >
844
+ > 1. {question 1}
845
+ > 2. {question 2}
846
+ > ...
847
+ >
848
+ > Which should the agent investigate? Pick any subset, "all", or "skip" to skip this matter.
849
+
850
+ **[USER PAUSE]** Wait per matter.
851
+
852
+ ##### 7.4 — Commit picks per-matter
853
+
854
+ For each matter where the user picked at least one question, call `mcp__ritual__accept_discovery_questions` with:
855
+ - `state_id` (from the discovery state)
856
+ - `matter_id`
857
+ - `question_ids[]` (the picks for THIS matter)
858
+
859
+ This MUST be one call per matter — the API enforces per-matter atomicity. Don't bundle across matters.
860
+
861
+ ##### 7.4.5 — Classify unpicked areas when the signal warrants it
862
+
863
+ After question picking, check for scope mismatch only when one of these triggers fires:
864
+
865
+ - Pick-rate < 40%
866
+ - Matter coverage <= 50%
867
+ - Pick-rate = 100%
868
+ - Picks concentrate heavily in one matter while the scope spans several concerns
869
+
870
+ If no trigger fires, proceed silently to anti-goals.
871
+
872
+ If a trigger fires, summarize the pattern in plain language and ask the user to classify unpicked areas:
873
+
874
+ ```text
875
+ How should I treat the unpicked areas?
876
+
877
+ 1. Out of scope — tighten the current scope around what you picked.
878
+ 2. Later phase — keep the broad scope, but mark unpicked areas as phase-later candidates.
879
+ 3. Open questions — keep the broad scope and treat unpicked areas as context debt.
880
+ 4. Pick more — return to question picking before continuing.
881
+ ```
882
+
883
+ Use `references/discovery-classification.md` for the branch handlers, pulse templates, and no-discrimination case. Do not preview score deltas in the question-picking menu; let the pulse explain the consequence after the user chooses.
884
+
885
+ For Branch 2, append an exact block to `recon_context` before build brief generation:
886
+
887
+ ```markdown
888
+ ## Explicit phase-later candidates
889
+
890
+ These were intentionally deferred by the user during discovery. They are not context debt. Include them in the Build Brief under "Phase Candidates / Deferrable Items."
891
+
892
+ - {matter/question}
893
+ Reason: {user choice or inferred dependency}
894
+ Related RB/source: {optional}
895
+ ```
896
+
897
+
898
+ ##### 7.5 — Optional: capture out-of-scope items
899
+
900
+ If the user mentioned things they DON'T want investigated ("don't touch enterprise SSO", "skip pricing"), capture them as anti-goals.
901
+
902
+ Call `mcp__ritual__set_anti_goals(exploration_id, [{ text, reason? }, ...])`.
903
+
904
+ Skip silently if no anti-goals were mentioned.
905
+
906
+ **Pulse (Step 7.4 done — and again after 7.5 if anti-goals were set):** Emit a pulse — decision resolution and (if 7.5 ran) assumption safety just moved. Compact format unless this crosses Under-specified → Exploration-safe.
907
+
908
+ #### Step 8 — Run the agentic pipeline (role-aware pause point)
909
+
910
+ The agentic pipeline runs sourcing → answers → recommendations. Two run modes are supported (2026-05-12, PR 4):
911
+
912
+ **Mode A — Full agentic to recommendations (DEFAULT for engineering / delivery / operations / marketing roles, and the **skip** path):**
913
+
914
+ Call `mcp__ritual__start_agentic_run` with:
915
+ - `scope_type: 'exploration'`
916
+ - `exploration_id`
917
+
918
+ Runs through sourcing → answers → recommendations end-to-end. Typical runtime: 3-8 minutes. Poll, show progress, proceed to Step 9 when COMPLETED.
919
+
920
+ **Mode B — Stop after answers (RECOMMENDED DEFAULT for product / PRD / design roles):**
921
+
922
+ For PRD-style flows the user often wants to iterate on the v1 answers before recommendations are synthesized — the answers ARE the substance of the PRD; refining them lifts rec quality dramatically.
923
+
924
+ Call `mcp__ritual__start_agentic_run` with:
925
+ - `scope_type: 'exploration'`
926
+ - `exploration_id`
927
+ - `stop_after: 'answers'`
928
+
929
+ The pipeline halts after Phase 3 (answering). Run lands in `PAUSED_FOR_REVIEW`. Continue with Step 8.5 instead of Step 9.
930
+
931
+ **Which mode to offer:**
932
+
933
+ Use the **role** inferred at Step 2 step 6b:
934
+ - `engineering`, `delivery`, `operations` → default Mode A; offer Mode B as opt-in
935
+ - `product`, `design`, `marketing` → default Mode B; offer Mode A as opt-in
936
+ - Otherwise → ask the user
937
+
938
+ Phrase the offer plainly. For product roles:
939
+
940
+ > I'll start the agentic pipeline. Two options:
941
+ >
942
+ > 1. **Stop after answers** *(recommended for PRD)* — I'll generate v1 answers for each matter (~3-5 min). You review and refine each one before I run recommendations. Highest-quality PRD output but takes longer overall.
943
+ > 2. **Skip the pause — run all the way to recommendations** — fastest end-to-end (~3-8 min). You can still edit answers later in the web UI, but recs will already exist.
944
+ >
945
+ > Pick 1 or 2.
946
+
947
+ For engineering roles, flip the order — Mode A first.
948
+
949
+ **Common behavior for both modes:**
950
+
951
+ Poll `mcp__ritual__get_agentic_run(run_id)` using the standard async polling rule: one `Bash sleep 5` per iteration, then a fresh status call. Print progress only when `progress_pct` or `current_step` changes, or every ~15 seconds if the status is unchanged:
952
+
953
+ > Agentic run: {progress_pct}% — {current_step}
954
+
955
+ When `status` is `COMPLETED`: continue to Step 9.
956
+ When `status` is `COMPLETED_WITH_ERRORS`: tell the user, but proceed — partial recommendations may still be useful.
957
+ When `status` is `FAILED`: surface the error message, ask if they want to retry (`start_agentic_run` again with same exploration_id) or stop.
958
+ When `status` is `PAUSED_FOR_REVIEW` (Mode B only): continue to Step 8.5.
959
+
960
+ If user wants to abort mid-flight: `mcp__ritual__cancel_agentic_run(run_id)`.
961
+
962
+ #### Step 8.5 — Agent-driven per-answer iteration (Mode B only)
963
+
964
+ When the pipeline pauses at `PAUSED_FOR_REVIEW`, the exploration is at step `REVIEWING_ANSWERS`. Every matter's questions have v1 answers + at least one clarifying question per consideration, but nothing has been committed for recommendation generation yet.
965
+
966
+ **The agent walks the user through each question one at a time.** For each question:
967
+
968
+ 1. **Fetch the state.** Call `mcp__ritual__get_answer_state({ question_id })`. Returns:
969
+ - The question text
970
+ - The current draft answer (v1)
971
+ - The considerations (sub-aspects) with their chat sessions
972
+ - The latest assistant message per consideration — this is the **first clarifying question** the answer engine already generated during Phase 3
973
+
974
+ 2. **Present to the user.** Two choices, that's it (no "skip"):
975
+
976
+ > **Question {N} of {total}** — *{matter.name}*
977
+ >
978
+ > **Q:** {question.text}
979
+ >
980
+ > **v1 answer:**
981
+ > {currentDraft, first 400 chars …}
982
+ >
983
+ > **My follow-up:** {first consideration's latest assistant message}
984
+ >
985
+ > Two options:
986
+ > 1. **submit** — you're happy with v1; lock it in and move to the next question
987
+ > 2. **iterate** — answer my follow-up OR tell me what's wrong with v1 (free-text). I'll regenerate.
988
+
989
+ 3. **Branch on user's choice:**
990
+
991
+ - **If "submit":** call `mcp__ritual__submit_answer({ question_id })`. The question advances to COMPLETED. Move to the next question's Step 8.5 loop iteration.
992
+
993
+ - **If "iterate" (any free-text reply):** call `mcp__ritual__iterate_answer({ consideration_id, message: user_text })`. The answer engine:
994
+ - Persists the user message in the consideration's chat
995
+ - Generates a new AI response (which is either the next clarifying question OR a recognition that the answer is now complete)
996
+ - The new response is **automatically KG-aware** as of PR 5: the answer engine reads the exploration's persisted `sources` and pulls in relevant prior decisions + open deferrals when forming the next question
997
+
998
+ **Loop back to step 2 with the updated state.** Fetch fresh state via `get_answer_state` (the considerations array now reflects the new chat message + AI response), show v_N+1, prompt again. Cap at ~5 iterations per consideration before suggesting "let's submit and move on" — keeps cost bounded.
999
+
1000
+ 4. **When ALL questions are submitted:** call `mcp__ritual__resume_agentic_run({ run_id })`. Pipeline runs Phase 4 (submit all answers — the per-question submits above already advanced individual questions, but submit_all_answers is the canonical batch checkpoint) + Phase 5 (recommendations). Poll as in Step 8. When `status` becomes `COMPLETED`, continue to Step 9.
1001
+
1002
+ **Skip-the-iteration escape hatch:** the user can say "just resume" at any point. Call `resume_agentic_run` immediately. Recs generate from whatever state the answers are in (whether v1 or partially iterated). Equivalent to having picked Mode A from the start, just with the option to iterate later via the web UI.
1003
+
1004
+ **Abandon:** `cancel_agentic_run(run_id)`. The exploration stays at `REVIEWING_ANSWERS` — the user can come back later and either resume or start fresh.
1005
+
1006
+ **Performance note:** each iteration is 1 LLM call (~3-5s). For 20 questions × 2 iterations average × 1 call = 40 LLM calls (~$0.04). The skip path is ~$0. Bounded by user choice per-question.
1007
+
1008
+ **Pulse (Step 8 done):** Emit a pulse — decision resolution moved significantly (answers complete, draft recommendations now exist). Render full if this crosses Under-specified → Exploration-safe, else compact.
1009
+
1010
+ #### Step 9 — Review and accept recommendations (role-aware)
1011
+
1012
+ Call `mcp__ritual__get_recommendations(exploration_id)`. Response is an array of recommendations with id, title, status, content, reasoning.
1013
+
1014
+ **Role model — load-bearing**: only **admins** can accept recommendations (call `accept_recommendations`). **Collaborators** can read, comment, and proceed to implement, but they cannot move recs from `draft`/`pending_review` to `approved`. Respect this so a collaborator running `/ritual build` doesn't hit a 403 mid-flow and lose context.
1015
+
1016
+ If you don't already know the user's role on this workspace, prefer the workspace member endpoint or cached role from `/ritual init`. When unavailable, ask plainly: *"Are you the workspace admin or a collaborator?"* Do not attempt acceptance blindly unless the user explicitly says to accept.
1017
+
1018
+ Present recommendations in a compact, scannable form and give one recommended action:
1019
+
1020
+ ```text
1021
+ Recommendations ready: {N}
1022
+
1023
+ 1. {title}
1024
+
1025
+ {one-line summary}
1026
+
1027
+ 2. {title}
1028
+
1029
+ {one-line summary}
1030
+
1031
+ Recommended: accept all and generate the build brief.
1032
+ Reply `accept`, `detail 2`, or `hold`.
1033
+ ```
1034
+
1035
+ If the user asks for detail, show the requested recommendation's `content` and `reasoning_chain` if present, then return to the same `accept / detail / hold` prompt. Do not ask a second confirmation after the user says `accept` unless statuses are mixed, rejected, or the user is not an admin.
1036
+
1037
+ **Branch A — user IS an admin and says `accept`:**
1038
+
1039
+ Call `mcp__ritual__accept_recommendations(exploration_id)`. Response includes counts (`promoted`, `alreadyApproved`, `skipped`, `transitionedToComplete`). Show:
1040
+
1041
+ > Accepted {N} recommendations. Exploration is COMPLETE.
1042
+ > View: https://dev.ritualapp.cloud/e/{exploration_id}
1043
+
1044
+ **Pulse (recommendations accepted):** Emit a pulse — this is almost always a state-tier crossing into **Recommendation-ready**. Render full.
1045
+
1046
+ Continue to Step 9.5.
1047
+
1048
+ **Branch B — user is a collaborator (no admin acceptance available):**
1049
+
1050
+ Tell the user explicitly:
1051
+
1052
+ > These recommendations are still in **{status — draft / pending_review}**. Only an admin can formally accept them.
1053
+ >
1054
+ > Recommended: keep going and generate the build brief. When we sync implementation later, Ritual will record that it shipped ahead of admin acceptance. An admin can reconcile later.
1055
+ >
1056
+ > Reply `continue`, `hold for admin`, or `detail {N}`.
1057
+
1058
+ If the user picks `continue`, proceed to Step 9.5. The `sync_implementation` call in Step 12 will automatically snapshot the rec status via the A1.5 column.
1059
+
1060
+ #### Step 9.5 — Wait for requirements (auto-triggered by Step 9)
1061
+
1062
+ `accept_recommendations` fires requirement generation **fire-and-forget** the moment it succeeds. By the time you reach this step, generation is already in flight (or done, for fast LLM calls). The brief in Step 10 needs requirements ready, so wait here.
1063
+
1064
+ Steps:
1065
+
1066
+ 1. **Tell the user once** that requirements are being generated:
1067
+
1068
+ > Generating requirements for the build brief… usually 20-60s.
1069
+
1070
+ 2. **Poll `mcp__ritual__get_requirement_set_status(exploration_id)` every ~5s.** The response shape:
1071
+
1072
+ ```
1073
+ {
1074
+ exists: boolean,
1075
+ status: 'GENERATING' | 'READY' | 'FAILED' | null,
1076
+ icp, startedAt, completedAt, errorMessage
1077
+ }
1078
+ ```
1079
+
1080
+ Polling rules in this harness:
1081
+ - Use a **single `Bash sleep 5`** call per poll iteration — don't chain sleeps or use `sleep ≥30`. The harness blocks chained sleeps; one short sleep per turn dodges that AND keeps the user-facing progress feel live.
1082
+ - **Update the user every ~3 polls (~15s)** with a "still generating…" line so they know you haven't stalled.
1083
+
1084
+ 3. **Exit conditions:**
1085
+
1086
+ | Response | Action |
1087
+ |---|---|
1088
+ | `status === 'READY'` | Proceed to Step 10 |
1089
+ | `exists === false` (still null) for 3+ polls (~15s) | The fire-and-forget hasn't reached the DB yet, OR Branch B was just hit (no LLM call yet). After ~15s either keep polling OR proceed to Step 10 — the API auto-triggers generation inline if the set is still missing when the brief is requested (adds ~30s to the brief call but never hard-fails). |
1090
+ | `status === 'GENERATING'` | Keep polling |
1091
+ | `status === 'FAILED'` | Surface `errorMessage` to the user; offer to retry by calling `generate_build_brief` directly (which will auto-trigger a fresh generation), OR by hitting `POST /requirements?force=true` via the web UI |
1092
+
1093
+ 4. **Special case — Branch B from Step 9 (collaborator did NOT call accept_recommendations):** there's no fire-and-forget auto-trigger because accept never ran. Skip the polling entirely and let Step 10's auto-trigger handle requirement generation inline. The brief call will take ~30s longer than it otherwise would.
1094
+
1095
+ 5. When `status === 'READY'`, tell the user one line ("Requirements ready, generating the build brief…") and continue to Step 10.
1096
+
1097
+ #### Step 10 — Generate the build brief
1098
+
1099
+ The Build Brief is the markdown document the engineer reads RIGHT BEFORE writing code. It bridges accepted recommendations + synthesized requirements with the implementation. Sections:
1100
+
1101
+ - **READ THIS FIRST — These Will Block Review If Missing** (RB-numbered table of must-haves)
1102
+ - **Goal** (1-2 sentences, restated for code-time clarity)
1103
+ - **Required Outcomes** (specific, testable)
1104
+ - **Suggested Implementation** (high-level approach + the trade-offs the agent considered)
1105
+ - **Codebase Anchors** (file paths + existing patterns to extend, grounded in Step 3's recon)
1106
+ - **Previously Deferred — Worth Addressing?** (only present when `sources` overlap prior implementations with open deferrals)
1107
+ - **Phase Candidates / Deferrable Items** (what to intentionally punt for v2)
1108
+
1109
+ ##### 10a — Call `generate_build_brief`
1110
+
1111
+ Call `mcp__ritual__generate_build_brief` with:
1112
+
1113
+ - `exploration_id`
1114
+ - `icp` (optional — defaults to the exploration template's primary ICP, then PM; pass `TECH_PM` for engineering-flavored explorations)
1115
+ - `recon_context` — the Step 3 `codebase_context_packet` plus any explicit phase/later candidates from discovery. Do not pass raw recon notes. This grounds "Codebase Anchors" in real file paths while keeping agent hypotheses auditable and non-authoritative.
1116
+ - `sources` — the **same** file-path array passed to `generate_considerations` and `generate_problem_statement` in Steps 4–5. Critical for KG consistency: the brief's "Previously Deferred" section only populates when overlapping prior implementations exist on these files.
1117
+
1118
+ Returns the brief markdown + an `id` + `kgContextUsed` block. The brief is **idempotent on (exploration, icp)** — same recommendation+requirement hashes return the cached READY row. Pass `force: true` only when a prompt-version update requires re-generation.
1119
+
1120
+ ##### 10b — Timeout-recovery polling (CLI Tenet #8)
1121
+
1122
+ `generate_build_brief` can take **30–90s** in the cold-start case: the API auto-triggers RequirementSet generation inline (~30s) if one doesn't exist, then synthesizes the brief on top (~20-60s). MCP clients enforce a hard **30s timeout** on the request — you will sometimes see a local-timeout error while the server-side work is still running.
1123
+
1124
+ **Don't give up and don't blindly regenerate.** Instead, fall back to status polling:
1125
+
1126
+ 1. On timeout/error from `generate_build_brief`, call `mcp__ritual__get_build_brief_status(exploration_id, icp)` immediately.
1127
+ 2. Poll every **~5s** for up to **2min** total. Polling rule (CLI Tenet #7): a single `Bash sleep 5` call per turn — the harness blocks chained sleeps and `sleep ≥ 30`. Update the user with a "still generating…" line every ~3 polls (~15s).
1128
+ 3. Exit conditions:
1129
+
1130
+ | Response | Action |
1131
+ |---|---|
1132
+ | `exists === false` for 3+ polls (~15s) | The fire-and-forget never landed — try calling `generate_build_brief` once more (it will likely succeed now that requirements are ready). |
1133
+ | `status === 'GENERATING'` | Keep polling. |
1134
+ | `status === 'READY'` | Read `content` field — proceed to Step 10c as if generate had completed. |
1135
+ | `status === 'FAILED'` | Surface `errorMessage` to the user. Propose a single action (CLI Tenet #2): *"The brief failed: {errorMessage}. Retry with a fresh generation? (y/N)"*. On yes: call `generate_build_brief` again with `force: true`. |
1136
+
1137
+ You can ALSO call `get_build_brief_status` **proactively** before `generate_build_brief` — if `exists === true && status === 'READY'` and the hashes haven't changed, you've saved a write-tool roundtrip. Tradeoff: tiny read cost for skipping a maybe-slow write.
1138
+
1139
+ ##### 10c — Write to `BUILD-BRIEF.md` + CLI summary (CLI Tenet #1, #5)
1140
+
1141
+ When the brief content is in hand (from generate OR polling), **don't dump 300 lines of markdown into the terminal**. The brief belongs in a file the user can open, search, share, and revisit; the CLI surface is for the decision.
1142
+
1143
+ 1. **Write the markdown to `BUILD-BRIEF.md`** in the repo root (or `.ritual/BUILD-BRIEF.md` if the repo prefers tooling artifacts out of the top level — check `.gitignore` first). Prepend a Ritual attribution header before writing:
1144
+
1145
+ ```markdown
1146
+ <!--
1147
+ Generated by Ritual
1148
+ Exploration: https://dev.ritualapp.cloud/e/{exploration_id}
1149
+ Build brief id: {brief_id}
1150
+ Do not remove this header; it preserves implementation lineage.
1151
+ -->
1152
+ ```
1153
+
1154
+ If a `BUILD-BRIEF.md` already exists:
1155
+ - **Same exploration** (recommendationsHash matches the cached row): silent overwrite + one-line note in the summary that you refreshed it.
1156
+ - **Different exploration**: surface a confirm: *"A `BUILD-BRIEF.md` already exists from exploration `{previous_exploration_name}`. Overwrite with brief for `{this_exploration_name}`? (y/N, or save-to-`BUILD-BRIEF-{slug}.md`)"*. (CLI Tenet #11 — confirm before destructive.)
1157
+
1158
+ 2. **Print a compact CLI summary** — the top-of-mind information plus a single line pointing at the file:
1159
+
1160
+ ```
1161
+ ✓ Build brief ready — {exploration_name} ({N} recs accepted, {M} requirements)
1162
+ BUILD-BRIEF.md ({line_count} lines, {file_kb_size} KB)
1163
+
1164
+ Goal: {first line of Goal section, ≤ 100 chars}
1165
+
1166
+ Top review-blockers (must address):
1167
+ RB-001 — {RB-001 title} → {one-line "what's required"}
1168
+ RB-002 — {RB-002 title} → {one-line "what's required"}
1169
+ RB-003 — {RB-003 title} → {one-line "what's required"}
1170
+
1171
+ Top codebase anchors:
1172
+ {path1} — {pattern to extend, ≤ 60 chars}
1173
+ {path2} — {pattern to extend, ≤ 60 chars}
1174
+ {path3} — {pattern to extend, ≤ 60 chars}
1175
+
1176
+ {ONLY IF Previously Deferred section is non-empty:}
1177
+ ⚠ {N} previously-deferred item{s} overlap this scope — see "Previously Deferred" section in BUILD-BRIEF.md
1178
+ ```
1179
+
1180
+ Rules for the summary (CLI Tenets #3, #6):
1181
+ - **Cap RBs and anchors at top 3 each.** Engineers don't read 12-row tables in terminals.
1182
+ - **Omit any section that's empty.** No "Previously Deferred: none" lines — just don't render that line.
1183
+ - If `kgContextUsed.implementationCount > 0`, append one line above the goal: *"Grounded in {N} prior implementation{s}: {top match name}, …"* (CLI Tenet #4 — cite the specific signal).
1184
+
1185
+ 3. **Offer to open the file** (CLI Tenet #10 — OS-aware affordances, available not mandatory):
1186
+
1187
+ ```bash
1188
+ # Detect, in order: VS Code on PATH, JetBrains `idea` on PATH, $EDITOR set, macOS `open` available.
1189
+ command -v code >/dev/null && code BUILD-BRIEF.md
1190
+ command -v idea >/dev/null && idea BUILD-BRIEF.md
1191
+ [ -n "$EDITOR" ] && "$EDITOR" BUILD-BRIEF.md
1192
+ command -v open >/dev/null && open BUILD-BRIEF.md # macOS
1193
+ ```
1194
+
1195
+ If any of these are detectable, offer: *"Open `BUILD-BRIEF.md` in your editor? (y/N)"* — single yes/no, never a 4-way picker. If none are detectable, omit the offer entirely; the path is still clickable in most terminals.
1196
+
1197
+ ##### 10d — Confirm and proceed (CLI Tenet #2, #12)
1198
+
1199
+ End Step 10 with a single recommended action plus a cheap escape hatch — never a 3-way option bloom.
1200
+
1201
+ > Open `BUILD-BRIEF.md` and skim the RBs + anchors. **Ready to implement?** (y / refine the brief / drill into one item)
1202
+
1203
+ Branch by user response:
1204
+
1205
+ - **y / proceed / yes**: continue to Step 11.
1206
+ - **refine**: ask what's off, then call `generate_build_brief` with `force: true` after applying their feedback to the exploration (typically a recommendation re-accept or a requirement adjustment via the web UI).
1207
+ - **drill into X**: open the specific section in the markdown, discuss inline, then loop back to "Ready to implement?".
1208
+
1209
+ **Pulse (Step 10 done):** Emit a pulse — this often crosses into **Implementation-ready** (90%+). Render full when that crossing happens — *"safe to code"* is the celebration line. If still below 90% (e.g. brief flagged residual debt), surface that in the pulse line itself and propose addressing it before coding.
1210
+
1211
+ #### Step 11 — Implement
1212
+
1213
+ This step happens **inside** the same `/ritual build` chat if the agent is also the coding agent (Claude Code / Cursor / etc.), or hand-off if the user is implementing themselves.
1214
+
1215
+ ##### 11.0 — Branch strategy (CLI Tenet #13)
1216
+
1217
+ **Never commit to `main` / `master` from an agent workflow.** Before writing a single line of code:
1218
+
1219
+ 1. Check for uncommitted user work:
1220
+ ```bash
1221
+ git status --porcelain
1222
+ ```
1223
+ If there are unrelated user changes, pause before editing and ask whether to keep working on this branch, stash, or abort. Do not overwrite or mix with user work silently.
1224
+
1225
+ 2. Check the current branch:
1226
+ ```bash
1227
+ git branch --show-current
1228
+ ```
1229
+
1230
+ 3. If on `main` / `master` / `trunk` / `develop` (or any branch named in the repo's default-branch protections): **create a feature branch FIRST.** Do not ask whether to commit to trunk. Branch creation is free and reversible. Naming heuristic:
1231
+ - `feat/<exploration-slug>` when the slug is short (≤ 4 words)
1232
+ - `ritual/<exploration-short-id>` as a fallback (e.g. `ritual/exp-7a2b9c`)
1233
+ - If the user already named one in chat ("call it `feat/conversions-tracking`"), use that.
1234
+
1235
+ User-visible:
1236
+
1237
+ > Created branch `{branch}` for this Ritual implementation.
1238
+ > Override with `branch: <name>` before implementation begins.
1239
+
1240
+ 4. If already on a feature branch and the working tree is clean or only contains this flow's changes: stay there. Don't switch.
1241
+
1242
+ **Never offer "commit to `main` directly" as an option in any user prompt.**
1243
+
1244
+ ##### 11.1 — Implement
1245
+
1246
+ 1. Take the build brief as input.
1247
+ 2. Use the standard coding-loop tools (Edit/Write/Bash/etc.) to make the code change.
1248
+ 3. Run tests, lint, build per the repo's conventions.
1249
+ 4. Track each architectural decision as you go — the input to Step 12's `sync_implementation` call. Per decision, write down: `area`, `choice`, `alternatives_considered`, `rationale`, `source_recommendation_id` (the RB-N or recommendation id the decision implements). This is what makes lineage queryable later — don't skip it.
1250
+
1251
+ ##### 11.2 — Commit (CLI Tenet #14 — Ritual attribution)
1252
+
1253
+ Commit on the feature branch from 11.0. One-or-many commits is fine; conventional-commit prefixes preferred (`feat:`, `fix:`, `test:`, etc.). Include a Ritual footer on the FINAL commit of the implementation so the trace from code → exploration is visible in `git log`:
1254
+
1255
+ ```
1256
+ feat(<area>): <one-line headline>
1257
+
1258
+ <short body — what changed, why, key trade-off>
1259
+
1260
+ Ritual-Exploration: <exploration_id>
1261
+ Ritual-Exploration-Url: https://dev.ritualapp.cloud/e/<exploration_id>
1262
+ Ritual-RBs-Satisfied: RB-1, RB-2, RB-7
1263
+ ```
1264
+
1265
+ Intermediate commits can skip the footer. The final commit IS the linkage anchor.
1266
+
1267
+ ##### 11.3 — Post-implementation summary (CLI Tenet #1 — files for detail, CLI for decisions)
1268
+
1269
+ **Don't dump a per-file changelog into the chat.** The full diff lives in `git diff <branch>..HEAD` and the eventual PR body. The CLI summary should be **≤ 8 lines** and surface only what's load-bearing for the user's next decision:
1270
+
1271
+ ```
1272
+ ✓ Implementation done — {exploration name}
1273
+ Branch: {branch}, {N} commits, {M} files changed
1274
+ Tests: {tests_added} added, all passing
1275
+ RBs satisfied: {comma-joined list of RB-N from the brief, ALL or a count}
1276
+ Open deferrals logged for Step 12: {count}
1277
+
1278
+ Next: push + open PR? (y / show me what changed / abort)
1279
+ ```
1280
+
1281
+ If the user picks "show me what changed", THEN run `git diff --stat HEAD~N..HEAD` or open per-file diffs interactively — on request, not by default.
1282
+
1283
+ ##### 11.4 — Push + PR (single recommended action)
1284
+
1285
+ If the user says "y" / "push" / "open PR":
1286
+
1287
+ 1. `git push -u origin <branch>` (single command, no `--force` ever in this flow).
1288
+ 2. Build the PR body from the template below (CLI Tenet #14).
1289
+ 3. `gh pr create --base <default-branch> --title <…> --body <…>`.
1290
+ 4. Surface the PR URL to the user.
1291
+
1292
+ **PR body template:**
1293
+
1294
+ ```markdown
1295
+ ## Summary
1296
+
1297
+ <2-3 lines max, derived from the build brief's Goal section>
1298
+
1299
+ ## RBs satisfied
1300
+
1301
+ | RB | Title | Where |
1302
+ |---|---|---|
1303
+ | RB-1 | <title from brief> | <key file/module> |
1304
+ | RB-2 | <title from brief> | <…> |
1305
+ | … | | |
1306
+
1307
+ ## Test plan
1308
+
1309
+ - <one bullet per test file / suite added>
1310
+ - <coverage notes if non-trivial>
1311
+
1312
+ ## Exploration
1313
+
1314
+ - Exploration: [<exploration name>](https://dev.ritualapp.cloud/e/<exploration_id>)
1315
+ - Build brief: see `BUILD-BRIEF.md` (committed in this PR for reviewer reference)
1316
+ - Deferrals intentionally punted: <count, with one-line each>
1317
+
1318
+ ---
1319
+
1320
+ 🪷 Generated via [Ritual](https://ritual.work) — closing the loop with `sync_implementation` after merge.
1321
+ ```
1322
+
1323
+ If the user is implementing manually: hand off the brief + the branch-strategy note ("create a feature branch off `main` — don't commit to trunk"), tell them you'll be ready to run `sync_implementation` when they're done.
1324
+
1325
+ #### Step 12 — Close the loop with `sync_implementation`
1326
+
1327
+ ##### 12.0 — What this step does (in product terms)
1328
+
1329
+ Before asking for permission, frame the call in language the user can act on. `sync_implementation` is not just an API call — it's the moment the workspace's knowledge graph absorbs what you just shipped. From the user's POV:
1330
+
1331
+ > I'm about to log this implementation into the workspace's knowledge graph. After this:
1332
+ > - The exploration's state flips to ✓ done (or ⚠ implemented-ahead if any recs weren't approved when shipped).
1333
+ > - The {N} architectural decisions you made get linked back to the recommendations that motivated them — so future `/ritual build` calls touching `{first 2 files}` will see your decisions as priorContext.
1334
+ > - The {M} open deferrals you intentionally punted get logged with their reasons — peers can see them in `/ritual lineage` on these files later.
1335
+ >
1336
+ > **OK to log? (y / hold off / let me adjust the decision list first)**
1337
+
1338
+ This framing replaces "I need to call sync_implementation, OK?" — which is jargon. The user should know what they're approving in product terms (CLI Tenet #4 — cite the specific signal).
1339
+
1340
+ ##### 12.1 — Make the call
1341
+
1342
+ Call `mcp__ritual__sync_implementation` with:
1343
+ - `workspace_id`, `exploration_id`
1344
+ - `repo`, `branch`, `pr_url`, `pr_number`, `pr_status`
1345
+ - `commits[]` — each with `sha`, `message`, `timestamp`, `files_changed`
1346
+ - `decisions[]` — each with `area`, `choice`, `alternatives_considered[]`, `rationale`, optionally `source_recommendation_id` (anchor each decision to the rec it implements when possible — this is what enables future "shipped X to satisfy rec Y" queries)
1347
+ - `deferrals[]` — for things you intentionally punted (`rb_id`, `description`, `reason`, `severity`, `related_files[]`, `related_modules[]`)
1348
+ - `gate_verdict`, `adherence_rate` — your own self-reported quality signals
1349
+
1350
+ The A1.5 snapshot column auto-captures each linked recommendation's status at the moment of sync — so if you implemented while the rec was still `draft` (Branch B in Step 9), the timeline is preserved automatically.
1351
+
1352
+ When sync_implementation succeeds, the response includes:
1353
+
1354
+ - `decisions: [{ decisionId, area, choice, recommendationStatusAtImplementation }, ...]` — IDs of every architectural decision logged + the rec-status snapshot (A1.5)
1355
+ - `deferrals: [{ deferralId, rbId, severity }, ...]` — IDs of every deferral
1356
+ - `decisionsCount`, `deferralsCount` — totals for the summary line
1357
+ - `webUrl` — clickable link to the exploration's implementation record in the web UI
1358
+
1359
+ **Surface ALL of this to the user**, not just "ok logged." This is the visible signal that the loop closed. Format:
1360
+
1361
+ > ✓ Logged implementation for **{exploration name}**
1362
+ > - {decisionsCount} decision{s} registered: {first 2 decisions, e.g. "auth: OAuth not SAML; data-model: tenant-scoped indexes"}
1363
+ > - {deferralsCount} deferral{s} registered: {first 1, e.g. "[major] Rate-limit per-tenant — out of scope for v1"}
1364
+ > - View: {webUrl}
1365
+ >
1366
+ > Future `/ritual build` calls touching `{first 2 of filesChanged}` will now see this implementation in their priorContext block.
1367
+
1368
+ If any decision's `recommendationStatusAtImplementation` is NOT `approved` (i.e. the Branch B path), add a callout:
1369
+
1370
+ > ⚠ {M} decision{s} implemented while their source recommendation was still in **{status}** — the exploration now shows `implemented_ahead`. An admin should review + accept the recs to close the gap.
1371
+
1372
+ The closing sentence is the most important one: it tells the user **what just happened in the system** in product-level terms. Without it, sync_implementation feels like a write-only black hole. With it, the user understands they just contributed to the workspace's memory.
1373
+
1374
+ **If `sync_implementation` fails:** do not drop the structured implementation data. Write the intended payload to `.ritual/pending-sync/<exploration-id>.json` and tell the user exactly what was not logged.
1375
+
1376
+ User-visible:
1377
+
1378
+ > `sync_implementation` failed: {error summary}
1379
+ > Saved the intended sync payload to `.ritual/pending-sync/<exploration-id>.json`.
1380
+ > Retry later with the same payload; no implementation decisions were lost.
1381
+
1382
+ Create `.ritual/pending-sync/` if needed. Keep the pending-sync file git-tracked unless the repo has a different convention for generated workflow state.
1383
+
1384
+ #### Step 13 — Optional follow-up
1385
+
1386
+ If they want to check the state at any time, point them at:
1387
+
1388
+ > `ritual graph status` (in their CLI) — shows the workspace's current KG counts + recent implementations.
1389
+
1390
+ Or: re-run `/ritual build` in this workspace later — the existing-work check will surface this exploration with its new `done` state badge, and any future build whose `sources` overlap will pull in the decisions + deferrals you just logged as priorContext.
1391
+
1392
+ ### Failure modes & recovery
1393
+
1394
+ **Discovery generation hangs (>5 min polling without `ready: true`)**: ask the user — wait longer? retry (`suggest_discovery_questions` again, new task)? or skip discovery entirely (proceed to Step 8 without picked questions)?
1395
+
1396
+ **Agentic run fails or stalls**: surface the error, offer retry or stop.
1397
+
1398
+ **Discovery state ready=true with zero matters**: rare but possible if the LLM produced a malformed state. Retry by calling `suggest_discovery_questions` again.
1399
+
1400
+ **LLM-cost / quota errors (HTTP 429)**: tell the user explicitly. Do NOT auto-retry — quota issues need a human decision (different model tier, wait, top up).
1401
+
1402
+ ### Tools used
1403
+
1404
+ This subcommand exclusively uses vNext MCP tools, in the order they appear:
1405
+
1406
+ 1. `mcp__ritual__list_workspaces` (Step 1)
1407
+ 2. `mcp__ritual__create_workspace` (Step 1, only if no workspace exists)
1408
+ 3. `mcp__ritual__list_explorations` (Step 1.5 — resume vs start, with state badges)
1409
+ 4. `mcp__ritual__suggest_high_leverage_problems` (Step 1.5 step 6b — option 3, "help me find the highest-leverage thing")
1410
+ 5. `mcp__ritual__check_exploration_overlap` (Step 1.5 step 8 — pre-creation overlap detection before "start fresh")
1411
+ 6. `mcp__ritual__list_templates` (Step 2)
1412
+ 7. `mcp__ritual__generate_considerations` (Step 4)
1413
+ 8. `mcp__ritual__refine_considerations` (Step 4.2, iteration only)
1414
+ 9. `mcp__ritual__generate_problem_statement` (Step 5)
1415
+ 10. `mcp__ritual__refine_problem_statement` (Step 5.2, iteration only)
1416
+ 11. `mcp__ritual__create_exploration` (Step 6)
1417
+ 12. `mcp__ritual__fork_sibling_explorations` (Step 6.5 — optional only when the user explicitly asks to save separate sibling tracks)
1418
+ 13. `mcp__ritual__suggest_discovery_questions` (Step 7.1)
1419
+ 14. `mcp__ritual__get_discovery_state` (Step 7.2)
1420
+ 15. `mcp__ritual__accept_discovery_questions` (Step 7.4)
1421
+ 16. `mcp__ritual__set_anti_goals` (Step 7.5, optional)
1422
+ 17. `mcp__ritual__start_agentic_run` (Step 8 — accepts `stop_after='answers'` for PRD/product flows)
1423
+ 18. `mcp__ritual__get_agentic_run` (Step 8 / Step 8.5 polling)
1424
+ 19. `mcp__ritual__cancel_agentic_run` (Step 8, only on user abort)
1425
+ 20. `mcp__ritual__resume_agentic_run` (Step 8.5, only when stop_after='answers' was used)
1426
+ 20a. `mcp__ritual__get_answer_state` (Step 8.5 per-question read)
1427
+ 20b. `mcp__ritual__iterate_answer` (Step 8.5 — user picked "iterate")
1428
+ 20c. `mcp__ritual__submit_answer` (Step 8.5 — user picked "submit")
1429
+ 21. `mcp__ritual__get_recommendations` (Step 9)
1430
+ 22. `mcp__ritual__accept_recommendations` (Step 9, admin branch only — fires requirement gen fire-and-forget)
1431
+ 23. `mcp__ritual__get_requirement_set_status` (Step 9.5 polling)
1432
+ 24. `mcp__ritual__generate_build_brief` (Step 10a)
1433
+ 24a. `mcp__ritual__get_build_brief_status` (Step 10b — timeout-recovery polling, OR proactive cache-hit check before 10a)
1434
+ 24b. `mcp__ritual__add_knowledge_source` (Step 3.5 — register PRDs / tickets / transcripts / etc. provided by the user)
1435
+ 24c. `mcp__ritual__list_knowledge_sources` (used inline by Step 3.5 to show already-attached refs on resume; also called by `/ritual context-pulse` CP2 for Reference Grounding count)
1436
+ 25. `mcp__ritual__sync_implementation` (Step 12)
1437
+
1438
+ 31 of the 40 vNext tools. The other 9 (`ping`, `get_exploration`, `list_agentic_runs`, `add_collaborator`, `check_anti_goals`, `query_knowledge_graph`, `get_workspace_overview`, `get_knowledge_source`, `remove_knowledge_source`) are situational, not part of the linear build flow.
1439
+
1440
+ ### After this subcommand
1441
+
1442
+ When `/ritual build` completes, the exploration is in COMPLETE state with accepted recommendations AND a build brief has been generated AND (if the agent implemented in-chat) `sync_implementation` has been called. The full close-the-loop cycle now lives inside this skill — there's no separate downstream `/ritual-builder-spec` step required.
1443
+
1444
+ Variants:
1445
+ - Admin runs the whole flow: Steps 1 → 13, no handoff.
1446
+ - Collaborator runs the build flow: Steps 1 → 13 with Step 9 Branch B (no admin acceptance available); the resulting exploration shows `⚠ implemented_ahead` until an admin reconciles.
1447
+ - Resume mid-flow: the existing-work check surfaces explorations with state badges and jumps directly to the right phase. (Or, for the "I just want to pick up" intent, see `/ritual resume` below.)
1448
+
1449
+ ---