draht-codex 2026.7.7 → 2026.7.11

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 (42) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +24 -0
  3. package/agents/advisor.md +45 -0
  4. package/agents/architect.md +28 -0
  5. package/agents/debugger.md +18 -0
  6. package/agents/git-committer.md +2 -0
  7. package/agents/implementer.md +24 -0
  8. package/agents/reviewer.md +9 -2
  9. package/agents/security-auditor.md +1 -0
  10. package/agents/spec-reviewer.md +2 -1
  11. package/agents/verifier.md +12 -1
  12. package/bin/draht-tools.cjs +1808 -988
  13. package/commands/discuss-phase.md +1 -1
  14. package/commands/execute-phase.md +8 -4
  15. package/commands/fix.md +13 -1
  16. package/commands/init-project.md +1 -0
  17. package/commands/map-codebase.md +1 -1
  18. package/commands/new-project.md +1 -0
  19. package/commands/next-milestone.md +3 -0
  20. package/commands/orchestrate-loop.md +100 -0
  21. package/commands/orchestrate.md +29 -6
  22. package/commands/pause-work.md +4 -3
  23. package/commands/plan-phase.md +6 -0
  24. package/commands/quick.md +6 -2
  25. package/commands/review.md +4 -1
  26. package/commands/verify-work.md +10 -8
  27. package/hooks/hooks.json +24 -0
  28. package/package.json +2 -2
  29. package/scripts/gsd-post-phase.cjs +24 -0
  30. package/scripts/gsd-post-task.cjs +9 -3
  31. package/scripts/gsd-quality-gate.cjs +8 -3
  32. package/scripts/post-edit-check.cjs +59 -0
  33. package/scripts/session-start.cjs +46 -0
  34. package/scripts/stop-quality-gate.cjs +68 -0
  35. package/skills/atomic-reasoning/SKILL.md +8 -0
  36. package/skills/brainstorming/SKILL.md +13 -2
  37. package/skills/debugging-workflow/SKILL.md +9 -0
  38. package/skills/gsd-workflow/SKILL.md +162 -0
  39. package/skills/loop-workflow/SKILL.md +52 -0
  40. package/skills/model-tiering/SKILL.md +45 -0
  41. package/skills/orchestrate-loop/SKILL.md +14 -0
  42. package/skills/verification-gate/SKILL.md +10 -0
@@ -33,7 +33,7 @@ Before questioning, decompose this phase scope into atomic reasoning units:
33
33
  3. Identify gray areas based on what's being built
34
34
  4. Present 1-2 questions at a time about preferences
35
35
  5. If `.planning/DOMAIN.md` exists, load it and validate discovered terms against the glossary. Add any new domain terms found during discussion.
36
- 6. Record decisions with `draht-tools save-context $1`
36
+ 6. Record decisions with `draht-tools save-context $1` — label each entry **decided** (the user explicitly chose) or **assumed** (you inferred from context). Assumed entries are flagged for confirmation; a plan built on an unlabeled assumption fails silently later.
37
37
  7. Commit: `draht-tools commit-docs "capture phase $1 context"`
38
38
 
39
39
  ## Workflow
@@ -36,6 +36,7 @@ Before executing, decompose this phase execution into atomic reasoning units:
36
36
  **Synthesize execution strategy:**
37
37
  - Identify parallel execution groups (plans with no shared files/dependencies)
38
38
  - Order dependent plans (plan B depends on plan A's outputs)
39
+ - Within each group, dispatch the riskiest plan first (highest uncertainty × blast radius) — its failure invalidates the rest of the phase most cheaply, before effort has been sunk into work it would obsolete
39
40
  - Map each plan to a subagent task with clear success criteria
40
41
 
41
42
  ## Steps
@@ -60,7 +61,7 @@ Before executing, decompose this phase execution into atomic reasoning units:
60
61
 
61
62
  ### Stage 1 — Implementer
62
63
  Dispatch a Codex subagent using the `implementer` agent prompt and the prompt from the template below. Read the final `STATUS:` line in the response.
63
- - `STATUS: DONE` → go to Stage 2.
64
+ - `STATUS: DONE` → **re-derive before trusting**: a `DONE` that does not quote its verification output (test counts, command output) is treated as `DONE_WITH_CONCERNS` — run the task's `<verify>` step yourself and read the result before Stage 2. Subagent claims are inputs, not verdicts.
64
65
  - `STATUS: DONE_WITH_CONCERNS` → note the concerns; if any are correctness issues, instruct the implementer to fix and re-dispatch; otherwise go to Stage 2.
65
66
  - `STATUS: NEEDS_CONTEXT` → provide the missing context (paste the relevant file content or decision) and re-dispatch. Do not skip.
66
67
  - `STATUS: BLOCKED` → STOP. Report the blocker to the user. Do not move on.
@@ -78,7 +79,7 @@ Before executing, decompose this phase execution into atomic reasoning units:
78
79
  ```
79
80
  - `STATUS: DONE` → go to Stage 3.
80
81
  - `STATUS: DONE_WITH_CONCERNS` → note, go to Stage 3.
81
- - `STATUS: BLOCKED` → re-dispatch the implementer with the "Required Fixes" list to address the gaps. Repeat Stage 1+2 until `DONE`. **Never proceed to Stage 3 with a non-compliant diff.**
82
+ - `STATUS: BLOCKED` → re-dispatch the implementer with the "Required Fixes" list to address the gaps. Repeat Stage 1+2 until `DONE`. **Never proceed to Stage 3 with a non-compliant diff.** **Hard cap: 3 implementer re-dispatches per task (across Stage 2 and Stage 3 combined).** On the 3rd failed re-dispatch, record the task as failed via the post-task hook and STOP — report the disagreement to the user. Never negotiate past the cap.
82
83
 
83
84
  ### Stage 3 — Reviewer (code quality)
84
85
  Once spec compliance is ✅, dispatch a Codex subagent using the `reviewer` agent prompt and a prompt of the form:
@@ -90,13 +91,14 @@ Before executing, decompose this phase execution into atomic reasoning units:
90
91
  ```
91
92
  - `STATUS: DONE` → task is complete, run the post-task hook (below), then move to the next task.
92
93
  - `STATUS: DONE_WITH_CONCERNS` → log the `Should fix` items; if any are correctness-critical, re-dispatch implementer; otherwise log and move on.
93
- - `STATUS: BLOCKED` → `Must fix` issues exist; re-dispatch the implementer with the issue list. Repeat the three stages until `DONE`.
94
+ - `STATUS: BLOCKED` → `Must fix` issues exist; re-dispatch the implementer with the issue list. Repeat the three stages until `DONE` — subject to the same **hard cap of 3 implementer re-dispatches per task**; at the cap, record the task as failed and STOP.
94
95
 
95
96
  ### Post-task hook
96
- After Stage 3 passes for a task, record the result:
97
+ After Stage 3 passes for a task — or when a task hits the re-dispatch cap — record the result:
97
98
  ```bash
98
99
  node "${PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-$HOME/.draht/codex-marketplace/plugins/draht}}/scripts/gsd-post-task.cjs" <phase> <plan> <task-num> <status> <commit-hash>
99
100
  ```
101
+ If the hook exits non-zero (3+ recorded failures for the task), that is a **harness-enforced hard stop**: do not dispatch any further implementer runs for this task; report to the user or create a fix plan.
100
102
 
101
103
  5. After all plans complete, run `draht-tools verify-phase $1` yourself (not the subagent)
102
104
  6. Run the post-phase hook to generate the phase report:
@@ -129,6 +131,8 @@ Checkpoint handling:
129
131
  - type="checkpoint:human-verify" → stop and report back what was built.
130
132
  - type="checkpoint:decision" → stop and report the options.
131
133
 
134
+ Evidence rule: quote the decisive output of every test run and <verify> step in your report (pass/fail counts, exit codes, error text). Unquoted claims will be re-run by the orchestrator. If a plan instruction contradicts what you find in the code, stop and report NEEDS_CONTEXT — do not silently obey either side.
135
+
132
136
  End your response with `STATUS: DONE` / `DONE_WITH_CONCERNS` / `NEEDS_CONTEXT` / `BLOCKED` per the agent contract.
133
137
  ```
134
138
 
package/commands/fix.md CHANGED
@@ -18,6 +18,14 @@ Issue: $ARGUMENTS
18
18
 
19
19
  Symptom fixes are failure — they create new bugs in different places. If you find yourself proposing a "quick fix for now, investigate later", STOP and return to Phase 1.
20
20
 
21
+ ## The Report Is a Symptom, Not a Diagnosis
22
+
23
+ **Procedure:** Restate the failure as observable behavior — "X happens when Y; expected Z" — before touching anything. If the user names a cause ("the cache is stale"), treat it as Hypothesis #0: it enters Phase 3 like any other hypothesis and does not skip Phase 1.
24
+
25
+ **Example:** "fix the stale cache bug" — Phase 1 traces the data flow and finds the cache is fine; the query behind it silently drops a filter. The fix lands in the query.
26
+
27
+ **Prevents:** shipping a correct fix to the wrong component.
28
+
21
29
  ## Red Flags — STOP
22
30
 
23
31
  Stop immediately if you catch yourself:
@@ -29,7 +37,7 @@ Stop immediately if you catch yourself:
29
37
  - Watching each fix reveal new problems elsewhere
30
38
  - Implementing before a failing test exists for the bug
31
39
 
32
- When you've tried **3 fix attempts and still failing**, STOP. This is an architectural problem, not a hypothesis problem. Report back to the user — do not try a 4th fix.
40
+ When you've tried **3 fix attempts and still failing**, STOP. This is a **hard cap**, not advice — an architectural problem, not a hypothesis problem. Report back to the user — do not try a 4th fix. Before reporting, append one line to `.planning/STATE.md` under `## Lessons`: what was tried, why it failed, dated — so the next session doesn't repeat the same three attempts.
33
41
 
34
42
  ## Atomic Reasoning
35
43
 
@@ -58,6 +66,7 @@ Walk through these steps and report on each:
58
66
  3. Check recent changes — `git log --oneline -20` and `git diff HEAD~5` against the affected files. What changed?
59
67
  4. For multi-component flows: trace data flow. Where does the bad value originate? What called this with that value? Keep tracing UPWARD until you find the source. Fix at source, not at symptom.
60
68
  5. State the root cause as one sentence: "X happens because Y at <file:line>."
69
+ 6. Label every statement in your report: observed (you ran it and saw it), derived (follows necessarily from evidence), or assumed (unchecked — say what would check it). A root cause resting on an assumption is a hypothesis, not a diagnosis.
61
70
 
62
71
  End your response with `STATUS: DONE | DONE_WITH_CONCERNS | NEEDS_CONTEXT | BLOCKED`.
63
72
  ```
@@ -112,6 +121,8 @@ You may also say "I don't understand X" rather than pretend. That is the correct
112
121
  | "I'll write the test after I confirm the fix" | Untested fixes don't stick. The test-first proves the bug existed. |
113
122
  | "I'll just try a few things and see what works" | Can't isolate what worked. Creates new bugs. |
114
123
  | "I already manually tested it" | A reproducing test is the only durable proof. |
124
+ | "The user already told me the cause" | The reporter saw the symptom. Their diagnosis is Hypothesis #0, not a finding. |
125
+ | "The fix passed, so my diagnosis was right" | Fixes can mask. Verify the causal chain, not just the symptom's absence. |
115
126
 
116
127
  ## Rules
117
128
  - Always reproduce before fixing — a fix without a test is a guess
@@ -119,3 +130,4 @@ You may also say "I don't understand X" rather than pretend. That is the correct
119
130
  - Fix at the source, not the symptom
120
131
  - If 3 fix attempts have failed, the architecture is wrong — stop and discuss
121
132
  - If the fix is non-obvious, the commit body explains the chain
133
+ - Final report order: verdict first (fixed / not fixed, root cause in one sentence), then evidence (reproducing test red→green, suite results), then risk (what the fix could regress, what stays assumed)
@@ -62,5 +62,6 @@ After project initialization, phases are executed one at a time in fresh session
62
62
 
63
63
  ## Rules
64
64
  - Ask 1-2 questions at a time, never dump 10 at once
65
+ - When the focus names a solution ("migrate to X"), ask what problem it solves — the existing code may admit a smaller answer
65
66
  - Respect what already exists — do not propose rewriting working code
66
67
  - Stop when you have: current state, goals, MVP scope, constraints, success criteria
@@ -54,7 +54,7 @@ Before analyzing, decompose codebase understanding into atomic reasoning units:
54
54
  End with `STATUS: DONE | DONE_WITH_CONCERNS | NEEDS_CONTEXT | BLOCKED`."
55
55
 
56
56
  4. Read each subagent's `STATUS:` line. `BLOCKED` or `NEEDS_CONTEXT` from either means STOP — `map-codebase` produces foundational artifacts and partial output here causes downstream confusion. Collect subagent results and merge with the draht-tools output.
57
- 5. Create `.planning/DOMAIN.md` (if it doesn't exist) with:
57
+ 5. Create `.planning/DOMAIN.md` (if it doesn't exist). Everything in it is **inferred from code, not confirmed by the user** — mark uncertain context boundaries and ambiguous terms as `(inferred)` so later commands know to confirm rather than build on them. With:
58
58
  - `## Bounded Contexts` — one entry per discovered context with a brief description
59
59
  - `## Ubiquitous Language` — glossary of extracted domain terms
60
60
  - `## Context Map` — how bounded contexts relate (upstream/downstream, shared kernel, ACL)
@@ -69,5 +69,6 @@ Start a fresh session (`/clear`) between steps. Do NOT suggest `/next-milestone`
69
69
  - Follow threads based on answers
70
70
  - Use examples ("Like Stripe Checkout, or custom?")
71
71
  - Confirm, don't assume
72
+ - When the description names a solution ("an app with X"), ask what problem it solves — requirements record problems and outcomes; mechanisms stay candidates
72
73
  - 3-7 follow-up rounds typical
73
74
  - Stop when you have: problem, audience, MVP scope, constraints, success criteria
@@ -29,6 +29,7 @@ Before planning the next milestone, decompose progress into atomic reasoning uni
29
29
  2. If any phase is not complete, STOP and tell the user which phase needs attention
30
30
  3. Read all phase reports in `.planning/phase-N-report.md` to extract lessons learned
31
31
  4. Read the execution log `.planning/execution-log.jsonl` for failure patterns
32
+ 4b. **Write the distilled lessons back**: append each durable lesson from steps 3-4 as a dated bullet to `.planning/STATE.md` under `## Lessons` (create the section before `## Blockers` if missing). Extraction that only informs this planning session evaporates; the `## Lessons` section is what future sessions actually reread.
32
33
  5. Refresh the living map if stale: `draht-tools map-graph --quiet` (guarded — skip if the post-phase hook already refreshed), then `draht-tools graph-clusters --surprising`. Compare clusters / bounded contexts / entry points against the milestone start to surface architectural drift before planning the next milestone
33
34
  6. Review `.planning/DOMAIN.md` — is it still accurate? Any terms to add/revise (esp. drift flagged in step 5)?
34
35
  7. Review `.planning/TEST-STRATEGY.md` — any updates needed?
@@ -46,5 +47,7 @@ Before planning the next milestone, decompose progress into atomic reasoning uni
46
47
 
47
48
  ## Rules
48
49
  - Do not start planning phase details — that happens in `/discuss-phase` + `/plan-phase`
50
+ - Distinguish **verified-complete** (a UAT report shows observed passes) from **believed-complete** (someone said so) — only the former counts toward requirement satisfaction; the latter goes back on the list
49
51
  - Respect lessons learned from the previous milestone — don't repeat mistakes
50
52
  - Keep the next milestone focused — 3-6 phases is typical
53
+ - Order the new phases risk-first: the phase carrying the highest uncertainty × blast radius comes earliest, so a wrong bet invalidates the least downstream work
@@ -0,0 +1,100 @@
1
+ ---
2
+ description: Run a verification-gated loop of fresh subagent iterations until a deterministic check passes
3
+ argument-hint: "<goal with a measurable success criterion> [--max-iterations N]"
4
+ allowed-tools: Bash, Read, Write, Edit, Task
5
+ ---
6
+
7
+ # /orchestrate-loop
8
+
9
+ Run fresh-context worker iterations against a fixed goal until an independent check passes — or a hard stop fires. The loop closes on a deterministic check, never on an agent's claim of completion.
10
+
11
+ Goal: $ARGUMENTS
12
+
13
+ > **Tool note**: Spawn Codex subagents using the matching Draht agent prompts. Workers are `implementer` (or `debugger` for pure-diagnosis goals); the final gate is `spec-reviewer`. One worker per iteration — never parallel workers inside the loop.
14
+
15
+ ## When to Loop vs Orchestrate
16
+
17
+ | Situation | Command |
18
+ |---|---|
19
+ | Decomposition is known, sub-tasks dispatch once | `/orchestrate` |
20
+ | Phase plans exist in `.planning/phases/` | `/execute-phase` |
21
+ | Goal needs iteration until a measurable criterion holds | `/orchestrate-loop` |
22
+
23
+ Loops trade tokens for persistence: use one when the work is too large or too uncertain for a single pass AND success is checkable without human judgment.
24
+
25
+ ## The Loop Contract — no check, no loop
26
+
27
+ A loop is only as good as its check. Before iterating, establish all four:
28
+
29
+ 1. **GOAL** — one measurable end state, stated in one sentence.
30
+ 2. **CHECK** — a command that proves the goal, pass/fail by exit code (test suite, typecheck + lint, a script comparing against a known-good oracle). Prefer terse output: failures only.
31
+ 3. **STOP CONDITIONS** — check passes (verified independently), max iterations reached (default 10; `--max-iterations N` overrides), stall detected, or `STATUS: BLOCKED`.
32
+ 4. **CONSTRAINTS** — what no iteration may touch: existing tests and the check itself are immutable (weakening either to "make it pass" is a hard-stop violation), plus anything out of scope.
33
+
34
+ If no deterministic check can be derived from the goal, STOP and ask the user to define one (or fall back to `/orchestrate`). Never start a loop whose only stop signal is "looks done" — without a check, you become the verification loop and it never closes.
35
+
36
+ Write the contract to `.planning/loop/LOOP.md`:
37
+
38
+ ```markdown
39
+ # Loop: <slug>
40
+ Started: <date> | Max iterations: <N>
41
+
42
+ ## Goal
43
+ <one sentence>
44
+
45
+ ## Check
46
+ `<command>` — passes when <what the output proves>
47
+
48
+ ## Constraints
49
+ - <immutables and out-of-scope items>
50
+ ```
51
+
52
+ Create `.planning/loop/PROGRESS.md` alongside it (append-only iteration log).
53
+
54
+ ## Iteration Protocol
55
+
56
+ Each iteration dispatches ONE fresh worker whose prompt contains, in full (workers cannot see this conversation):
57
+
58
+ 1. The loop contract verbatim
59
+ 2. The last 3 entries of `PROGRESS.md` and the last 5 `git log --oneline` lines — the recoverable state
60
+ 3. The previous iteration's failure evidence, terse: the failing assertions or error lines, not full output
61
+ 4. Standing orders:
62
+ - **Startup ritual** — read the progress log, run the CHECK first, observe the current failure before changing anything
63
+ - **One increment** — the smallest change that moves the check toward passing; do not batch
64
+ - **Commit the increment** even if the check still fails — state must survive context death
65
+ - **Append one `PROGRESS.md` entry** — what changed / check result observed / suggested next step
66
+ - Never edit or delete tests or the check to make it pass; never claim completion without quoting check output
67
+
68
+ ## Independent Verification — the gate
69
+
70
+ After EVERY iteration, re-run the CHECK yourself and read exit code and output. Completion is decided by this re-run, never by the worker's report — worker claims are inputs, not verdicts.
71
+
72
+ - **Check passes** → dispatch `spec-reviewer` once over the full loop diff (contract vs everything changed since the loop started). Only a clean spec review ends the loop as DONE; concerns trigger one more targeted iteration.
73
+ - **Check fails** → extract the terse failure evidence and feed it into the next iteration's prompt as guidance.
74
+
75
+ ## Stall Detection
76
+
77
+ Stop early when the loop is running but not progressing:
78
+
79
+ - Two consecutive iterations with the identical failure signature, or
80
+ - An iteration that produced no commit
81
+
82
+ On stall, do not dispatch the same input again — change something: decompose the goal, add context the workers were missing, switch worker (`implementer` → `debugger`), consult `advisor` for a course correction, or surface to the user with the evidence so far.
83
+
84
+ ## Steps
85
+
86
+ 1. Parse `$ARGUMENTS` into GOAL and flags; derive the CHECK; refuse to loop without one
87
+ 2. Write `.planning/loop/LOOP.md` and `.planning/loop/PROGRESS.md`
88
+ 3. Iterate: dispatch worker → re-run CHECK yourself → branch (pass → gate, fail → next iteration, stall / max / BLOCKED → hard stop)
89
+ 4. On success: spec-review the full diff, then report — outcome first, check output quoted, iterations used
90
+ 5. On any hard stop: append a handoff entry to `PROGRESS.md` (state observed, failure evidence, recommended next step) and report with observed / derived / assumed labels
91
+ 6. Leave `.planning/loop/` in place as the loop's record
92
+
93
+ ## Rules
94
+
95
+ - One worker, one increment, at least one commit per iteration
96
+ - Loops are volume work — run workers on the executor tier and keep steering (this context, `advisor`, `spec-reviewer`) on the strongest tier
97
+ - The worker never grades its own work — your re-run of the check plus a fresh-context spec review decide completion
98
+ - Never raise max iterations mid-loop without asking the user
99
+ - Tests and the check are immutable inside the loop; tampering means revert and hard stop
100
+ - Evidence discipline applies to the loop verdict: label results observed / derived / assumed
@@ -10,15 +10,15 @@ Decompose a task and dispatch the right mix of specialist subagents.
10
10
 
11
11
  Task: $ARGUMENTS
12
12
 
13
- > **Tool note**: Spawn Codex subagents using the matching Draht `architect` agent prompt, `implementer`, `spec-reviewer`, `reviewer`, `debugger`, `verifier`, `git-committer`, `security-auditor`. Dispatch multiple tasks in the same assistant turn for parallel execution.
13
+ > **Tool note**: Spawn Codex subagents using the matching Draht `architect` agent prompt, `implementer`, `spec-reviewer`, `reviewer`, `debugger`, `verifier`, `git-committer`, `security-auditor`, `advisor`. Dispatch multiple tasks in the same assistant turn for parallel execution.
14
14
 
15
15
  ## Atomic Reasoning
16
16
 
17
17
  Before delegating, decompose the task into atomic work units:
18
18
 
19
- 1. **State the logical components** — What sub-tasks make up this work? Which are independent?
19
+ 1. **State the logical components** — What sub-tasks make up this work? Which are independent? A sub-task is well-cut only if its success can be checked without reference to the others.
20
20
  2. **Match agents to work** — Which specialist is right for each sub-task?
21
- 3. **Determine order** — What can run in parallel vs what must be sequential? For **code-touching** sub-tasks (skip for doc-only work), run `draht-tools graph-impact <files>` on each sub-task's targets: disjoint impact sets parallelize, overlapping ones sequence. The orchestrator runs it and pastes the summary into each Codex subagent's prompt.
21
+ 3. **Determine order** — What can run in parallel vs what must be sequential? For **code-touching** sub-tasks (skip for doc-only work), run `draht-tools graph-impact <files>` on each sub-task's targets: disjoint impact sets parallelize, overlapping ones sequence. The orchestrator runs it and pastes the summary into each Codex subagent's prompt. Among independent sub-tasks, dispatch the riskiest first (highest uncertainty × blast radius): its failure invalidates the rest of the graph most cheaply, before effort is sunk into work it would obsolete.
22
22
  4. **Define success** — What does "done" look like for each sub-task, and for the whole?
23
23
 
24
24
  ## Agent Selection Guide
@@ -33,9 +33,28 @@ Before delegating, decompose the task into atomic work units:
33
33
  | Audit for security issues | `security-auditor` |
34
34
  | Run lint / typecheck / tests | `verifier` |
35
35
  | Create atomic commits | `git-committer` |
36
+ | Strategic steer at a decision point — rare, high-leverage | `advisor` |
36
37
 
37
38
  `spec-reviewer` and `reviewer` are distinct on purpose. Spec-reviewer ONLY checks "did the diff implement what the spec asked, no more no less". Reviewer evaluates quality (naming, structure, type safety). For any task with a written spec, run spec-reviewer **before** reviewer — accepting "close enough" on spec is a known failure mode.
38
39
 
40
+ ## Effort Scaling
41
+
42
+ Match orchestration weight to the task — over-orchestration burns tokens without adding verification value:
43
+
44
+ | Task shape | Dispatch |
45
+ |---|---|
46
+ | Single question or trivial fix | One agent, or handle it directly — no orchestration |
47
+ | One change set to evaluate | 2–4 parallel evaluators (reviewer, security-auditor, verifier) |
48
+ | Multi-part feature with known decomposition | Fan-out / fan-in |
49
+ | Goal needing iteration until a measurable criterion holds | `/orchestrate-loop` |
50
+
51
+ ## Model Tiering
52
+
53
+ Bill volume tokens at the cheaper rate — see the `model-tiering` skill:
54
+
55
+ - **Orchestrator pattern** — run this command on the strongest tier (e.g. Claude Fable 5) and let workers execute on the executor tier (e.g. Claude Sonnet 5): planning quality where it matters, volume tokens at worker rates.
56
+ - **Advisor pattern** — when the session runs on the executor tier, dispatch `advisor` sparingly: once after orientation before committing to an approach, again when stuck or before declaring a hard task done. ~1–3 consults per task; treat its guidance with serious weight.
57
+
39
58
  ## Orchestration Modes
40
59
 
41
60
  ### Parallel
@@ -58,11 +77,14 @@ implementer → spec-reviewer → reviewer
58
77
 
59
78
  Never run quality review on a spec-non-compliant diff. This is the standard pattern inside `/execute-phase`'s per-task loop.
60
79
 
80
+ ### Loop (iterate until a check passes)
81
+ When the work cannot land in one dispatch but success is provable by a deterministic check, do not improvise retries here — hand off to `/orchestrate-loop`. It runs fresh worker iterations gated by an independent re-run of the check, with max-iteration and stall bounds. See the `loop-workflow` skill for the discipline.
82
+
61
83
  ## Reading Subagent Status
62
84
 
63
85
  Every draht agent ends its response with one of four status lines. Branch on it:
64
86
 
65
- - `STATUS: DONE` — proceed to the next step in the chain.
87
+ - `STATUS: DONE` — check the evidence before proceeding: a `DONE` that quotes no verification output (test counts, command results) is treated as `DONE_WITH_CONCERNS` — re-run the decisive check yourself. Subagent claims are inputs, not verdicts.
66
88
  - `STATUS: DONE_WITH_CONCERNS` — note the concerns. If they're correctness-related, address before moving on; otherwise log and continue.
67
89
  - `STATUS: NEEDS_CONTEXT` — provide the missing information and re-dispatch the same agent. Do NOT skip ahead with a guess.
68
90
  - `STATUS: BLOCKED` — STOP. Report the blocker to the user. Do not retry the same agent on the same input — adjust the inputs (provide more context, decompose further, pick a different agent) or surface the problem.
@@ -73,11 +95,12 @@ Every draht agent ends its response with one of four status lines. Branch on it:
73
95
  3. Decide parallel vs chain vs fan-out vs two-stage based on dependencies
74
96
  4. Dispatch Codex subagent calls accordingly
75
97
  5. Read each subagent's final `STATUS:` line and branch per the protocol above
76
- 6. Collect results, handle failures, report the final outcome to the user
98
+ 6. Collect results, handle failures, report to the user — outcome first (what happened, in one line), evidence second (what each agent verified, quoted), risk last (what remains unverified or assumed)
77
99
 
78
100
  ## Rules
79
101
  - Prefer parallel dispatch when possible — it's faster and each subagent has its own context
80
- - Pass complete context to subagents — they cannot see the main conversation
102
+ - Every dispatch is a complete brief: objective, expected output format, tool guidance, and task boundaries — subagents cannot see the main conversation
81
103
  - Do not nest delegations deeply — one level is usually enough
82
104
  - Never retry the same agent on the same input after `BLOCKED` — change something
83
105
  - For any spec-driven work, spec-reviewer runs before quality reviewer
106
+ - The agent that produced work never evaluates it — completion verdicts come from a fresh-context evaluator plus your own re-run of the decisive check
@@ -28,9 +28,10 @@ Before pausing, decompose session state into atomic reasoning units:
28
28
  - `## Decisions Made This Session` — any design decisions or context
29
29
  - `## Next Steps` — exact commands to run when resuming
30
30
  - `## Blockers` — anything waiting on external input or clarification
31
- 4. Update `.planning/STATE.md` last activity timestamp via `draht-tools update-state`
32
- 5. Commit: `draht-tools commit-docs "pause work — handoff"`
33
- 6. Tell the user: "Resume with `/resume-work` in a fresh session."
31
+ 4. **Distill lessons before the context is lost**: for anything this session tried that failed, or an approach that worked against expectations, append one dated bullet to `.planning/STATE.md` under `## Lessons` (create the section before `## Blockers` if missing). Lessons name what to do differently — "runner hits TLS issue in PowerShell, use bash", not "had problems with tests".
32
+ 5. Update `.planning/STATE.md` last activity timestamp via `draht-tools update-state`
33
+ 6. Commit: `draht-tools commit-docs "pause work — handoff"`
34
+ 7. Tell the user: "Resume with `/resume-work` in a fresh session."
34
35
 
35
36
  ## Rules
36
37
  - Be specific — "fix bug in auth" is useless; "null check in src/auth/session.ts:42, test reproducing in test/auth-null.test.ts" is useful
@@ -20,6 +20,7 @@ A plan is only as good as the tasks inside it. STOP and revise instead of saving
20
20
  - A task takes more than ~5 minutes of focused work — break it down further
21
21
  - The plan introduces new domain terms that are NOT in `.planning/DOMAIN.md` — update DOMAIN.md first
22
22
  - A plan touches more than one bounded context without explicit ACL — split per context
23
+ - The first plan is scaffolding/boilerplate while an unproven risk (new integration, unfamiliar API, untested pattern) sits in a later plan — reorder so the risk is proven first
23
24
 
24
25
  Run `draht-tools validate-plans $1` after saving. If it reports issues, fix them before commit.
25
26
 
@@ -34,14 +35,19 @@ Before creating plans, decompose this phase goal into atomic reasoning units:
34
35
  2. **Validate independence** — Which artifacts (files, endpoints, schemas) prove this truth exists? Can it be built independently?
35
36
  3. **Verify correctness** — What test scenarios would prove this observable truth? What are the specific inputs → expected outputs?
36
37
 
38
+ **Atomicity test:** a task is atomic only if its `<verify>` can fail while every other task passes. If two tasks can only be checked together, they are one task.
39
+
37
40
  **Synthesize planning strategy:**
38
41
  - Group related observable truths into cohesive plans (2-5 tasks each)
39
42
  - Identify which plans can be created in parallel vs sequentially
40
43
  - Map each plan to specific bounded contexts and domain concepts
41
44
  - Ensure each plan produces testable, verifiable outcomes
45
+ - **Order risk-first**: score each truth by uncertainty (has this codebase done it before?) × blast radius (how much becomes invalid if it's wrong?). The plan proving the highest-scoring truth executes first; boilerplate goes last. Boilerplate never invalidates a phase — the risky part regularly does.
46
+ - Write every assumption a plan rests on as an explicit `Assumes:` line (with how to confirm it) in the plan header. Unwritten assumptions become the executor's bugs.
42
47
 
43
48
  ## Steps
44
49
  1. Run `draht-tools load-phase-context $1` to gather all context
50
+ 1b. Read `.planning/STATE.md` `## Lessons` — every plan this command produces must respect the recorded lessons; a plan that repeats a documented failure is invalid. Feed relevant lessons into each architect prompt.
45
51
  2. Optional: `draht-tools research-phase $1` for domain research
46
52
  3. Goal-backward planning:
47
53
  a. State the goal (outcome, not activity)
package/commands/quick.md CHANGED
@@ -12,6 +12,10 @@ Task: $ARGUMENTS
12
12
 
13
13
  > **Tool note**: Invoke `draht-tools <subcommand>` as `node "${PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-$HOME/.draht/codex-marketplace/plugins/draht}}/bin/draht-tools.cjs" <subcommand>`. For subagents, spawn Codex subagents using the `implementer`, `spec-reviewer`, or `reviewer` agent prompts.
14
14
 
15
+ ## "Small" Is a Claim, Not a Fact
16
+
17
+ Before planning, verify the task is actually quick: grep the blast radius (callers, imports, tests touching the target). If the change reaches further than the description implies, say so and recommend `/plan-phase`-level treatment instead of forcing it through. And if the description names a solution ("add a flag"), confirm the problem it solves — a smaller fix may exist. A "quick task" that silently grows is how untracked complexity enters a codebase.
18
+
15
19
  ## Atomic Reasoning
16
20
 
17
21
  Before executing, decompose this task into atomic reasoning units:
@@ -67,7 +71,7 @@ Before executing, decompose this task into atomic reasoning units:
67
71
  ```
68
72
 
69
73
  - `DONE` → go to Stage 3.
70
- - `BLOCKED` → re-dispatch implementer with the "Required Fixes" list. Repeat Stage 1+2 until `DONE`.
74
+ - `BLOCKED` → re-dispatch implementer with the "Required Fixes" list. Repeat Stage 1+2 until `DONE`. **Hard cap: 3 implementer re-dispatches total (across Stage 2 and Stage 3).** At the cap, STOP and report the disagreement to the user.
71
75
 
72
76
  5. **Stage 3 — Reviewer (optional code-quality pass).** For non-trivial quick tasks (touches more than one file or modifies domain code), _optionally_ run `draht-tools graph-impact <changed files>` and paste its reverse-dependents + boundary warnings into the Codex subagent prompt. Then dispatch a Codex subagent using the `reviewer` agent prompt:
73
77
  ```
@@ -77,7 +81,7 @@ Before executing, decompose this task into atomic reasoning units:
77
81
  ```
78
82
 
79
83
  - `DONE` → quick task complete.
80
- - `BLOCKED` → re-dispatch implementer with the Must-fix list.
84
+ - `BLOCKED` → re-dispatch implementer with the Must-fix list — subject to the same **hard cap of 3 re-dispatches**; at the cap, STOP and report.
81
85
 
82
86
  6. Write summary: `draht-tools write-quick-summary NNN`
83
87
  7. Update state: `draht-tools update-state`
@@ -69,11 +69,14 @@ Before reviewing, decompose code changes into atomic reasoning units:
69
69
 
70
70
  5. Read each subagent's final `STATUS:` line.
71
71
  6. Collect and merge results from all dispatched subagents.
72
- 7. Produce a unified, prioritized findings report:
72
+ 7. **Refute before reporting.** For each Critical or Important finding, attempt to kill it yourself before it reaches the report: read the code path that would make it a false positive — an upstream guard clause, a type constraint, an existing test that covers the case. A finding that survives an honest refutation attempt is **confirmed** (you traced the failing path); one you couldn't confirm is downgraded and labeled **suspected**. Reporting unattacked findings trains readers to ignore the report.
73
+ 8. Produce a unified, prioritized findings report. Verdict first: one line — mergeable or not, and why. Then findings:
73
74
  - **Critical** — must fix before merge (security `BLOCKED`, spec gaps for required deliverables, correctness issues that cause data loss / crashes)
74
75
  - **Important** — should fix (bugs, type issues, spec over-builds, missing error handling)
75
76
  - **Minor** — style, naming, or optional improvements
76
77
 
78
+ Each finding carries its label (confirmed/suspected). End with residual risk: what the review did NOT cover (files skipped, paths not traced) — a review that claims total coverage it doesn't have is worse than a scoped one.
79
+
77
80
  ## Reading STATUS
78
81
 
79
82
  - Any subagent returning `STATUS: BLOCKED` → its findings escalate to Critical in the merged report
@@ -74,29 +74,31 @@ Before verifying, decompose phase acceptance into atomic reasoning units:
74
74
  node "${PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-$HOME/.draht/codex-marketplace/plugins/draht}}/scripts/gsd-quality-gate.cjs"
75
75
  ```
76
76
 
77
- 5. **Read each subagent's `STATUS:` line and the quality gate exit code.** Treat the phase as failed if **any** of these is true:
77
+ 5. **Spot-check before aggregating.** Subagent claims are inputs, not verdicts. Before accepting the verifier's `DONE`, re-run the test suite headline yourself and read the counts. Before accepting the spec-reviewer's compliance verdict, read one plan's diff yourself. A pass you only heard about is an "assumed pass" — and an assumed pass is not a pass. This costs two commands and catches the most expensive failure mode this command has: trust laundered into evidence.
78
+
79
+ 6. **Read each subagent's `STATUS:` line and the quality gate exit code.** Treat the phase as failed if **any** of these is true:
78
80
  - `verifier` returns `STATUS: BLOCKED` (tests / lint / typecheck failed)
79
81
  - `security-auditor` returns `STATUS: BLOCKED` (Critical or High findings)
80
82
  - `spec-reviewer` returns `STATUS: BLOCKED` (any plan is non-compliant)
81
83
  - `reviewer` returns `STATUS: BLOCKED` (Must-fix correctness issues)
82
84
  - Quality gate exits non-zero
83
85
 
84
- 6. Walk the user through each deliverable one at a time, incorporating findings from all four subagents.
86
+ 7. Walk the user through each deliverable one at a time, incorporating findings from all four subagents.
85
87
 
86
- 7. Record results (pass/fail/partially/skip).
88
+ 8. Record results (pass/fail/partially/skip). Label each: **observed** (you or a subagent ran it and quoted output), **derived** (follows necessarily from something observed), or **assumed** (unchecked). Verdicts inherit the weakest label they rest on.
87
89
 
88
- 8. For failures: diagnose and create fix plans via `draht-tools create-fix-plan $1 P`
90
+ 9. For failures: diagnose and create fix plans via `draht-tools create-fix-plan $1 P`
89
91
  - Fix plans MUST include a reproducing test that demonstrates the failure before any implementation
90
92
  - Spec-reviewer omissions become explicit fix-plan tasks (one task per omission)
91
93
 
92
- 9. Write UAT report: `draht-tools write-uat $1`
93
- - Report must include: test health summary (pass/fail/coverage), security audit results, **spec compliance summary per plan**, domain model status (any glossary violations), deliverable results
94
+ 10. Write UAT report: `draht-tools write-uat $1`
95
+ - Order: **verdict first** (phase pass/fail, X/Y deliverables, in the first line), **evidence second** (test health summary with pass/fail/coverage, security audit results, spec compliance summary per plan, domain model status, deliverable results with labels), **risk last** (what was NOT tested and how it could bite). Never bury a failure under passes.
94
96
 
95
- 10. If all passed: mark phase complete.
97
+ 11. If all passed: mark phase complete.
96
98
  - If more phases remain in the milestone: tell the user to start a fresh session and run `/discuss-phase N+1`.
97
99
  - If ALL phases in the milestone are complete: tell the user to start a fresh session and run `/next-milestone`.
98
100
 
99
- 11. If failures: route to `/execute-phase $1 --gaps-only`
101
+ 12. If failures: route to `/execute-phase $1 --gaps-only`
100
102
 
101
103
  ## Why a phase-level spec-reviewer
102
104
 
package/hooks/hooks.json CHANGED
@@ -21,6 +21,30 @@
21
21
  }
22
22
  ]
23
23
  }
24
+ ],
25
+ "PostToolUse": [
26
+ {
27
+ "matcher": "Edit|Write|MultiEdit",
28
+ "hooks": [
29
+ {
30
+ "type": "command",
31
+ "command": "node \"${PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT}}/scripts/post-edit-check.cjs\"",
32
+ "timeout": 30
33
+ }
34
+ ]
35
+ }
36
+ ],
37
+ "Stop": [
38
+ {
39
+ "matcher": "",
40
+ "hooks": [
41
+ {
42
+ "type": "command",
43
+ "command": "node \"${PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT}}/scripts/stop-quality-gate.cjs\"",
44
+ "timeout": 180
45
+ }
46
+ ]
47
+ }
24
48
  ]
25
49
  }
26
50
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "draht-codex",
3
- "version": "2026.7.7",
3
+ "version": "2026.7.11",
4
4
  "description": "Draht GSD, multi-agent, TDD and DDD workflows as a Codex plugin. Install with `npx draht-codex install`.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -25,7 +25,7 @@
25
25
  "prepublishOnly": "node ../../scripts/sync-draht-tools.mjs"
26
26
  },
27
27
  "dependencies": {
28
- "@draht/tools": "2026.7.7"
28
+ "@draht/tools": "2026.7.11"
29
29
  },
30
30
  "keywords": [
31
31
  "codex",
@@ -132,6 +132,30 @@ try {
132
132
  }
133
133
  } catch { /* map refresh is best-effort */ }
134
134
 
135
+ // 4.6 Seed lessons: persist phase failure patterns into STATE.md ## Lessons so
136
+ // they compound across sessions instead of living only in transient reports.
137
+ try {
138
+ const statePath = path.join(PLANNING, "STATE.md");
139
+ if (fs.existsSync(statePath) && (failed > 0 || tddViolations > 0 || warnings > 0)) {
140
+ let state = fs.readFileSync(statePath, "utf-8");
141
+ const date = new Date().toISOString().slice(0, 10);
142
+ const lessonBits = [];
143
+ if (failed > 0) lessonBits.push(`${failed} task(s) failed`);
144
+ if (tddViolations > 0) lessonBits.push(`${tddViolations} TDD violation(s) (green: without red:)`);
145
+ if (warnings > 0) lessonBits.push(`${warnings} task(s) with warnings`);
146
+ const lesson = `- ${date}: Phase ${phaseNum}: ${lessonBits.join(", ")} — see phase-${phaseNum}-report.md; distill the root cause here before the next phase.`;
147
+ if (!state.includes(lesson)) {
148
+ if (/## Lessons\n/.test(state)) {
149
+ state = state.replace(/## Lessons\n(\(none yet[^\n]*\)\n)?/, (m) => `## Lessons\n${lesson}\n`);
150
+ } else {
151
+ state = state.replace(/## Blockers/, `## Lessons\n${lesson}\n\n## Blockers`);
152
+ }
153
+ fs.writeFileSync(statePath, state);
154
+ console.log(`STATE.md: lesson recorded for phase ${phaseNum}`);
155
+ }
156
+ }
157
+ } catch { /* lessons are best-effort */ }
158
+
135
159
  // 5. Summary
136
160
  console.log(`\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);
137
161
  console.log(` Draht ► PHASE ${phaseNum} ${failed === 0 ? "COMPLETE ✅" : "NEEDS FIXES ❌"}`);
@@ -34,7 +34,9 @@ function detectToolchain(cwd) {
34
34
  }
35
35
 
36
36
  function readHookConfig(cwd) {
37
- const defaults = { coverageThreshold: 80, tddMode: "advisory", qualityGateStrict: false };
37
+ // Strict by default: failing tests/types/lint fail the gate (exit 1).
38
+ // Opt out per-project with hooks.qualityGateStrict: false in .planning/config.json.
39
+ const defaults = { coverageThreshold: 80, tddMode: "advisory", qualityGateStrict: true };
38
40
  const configPath = path.join(cwd, ".planning", "config.json");
39
41
  if (!fs.existsSync(configPath)) return defaults;
40
42
  try {
@@ -145,9 +147,13 @@ if (status === "pass") {
145
147
  .map((l) => JSON.parse(l))
146
148
  .filter((e) => e.phase === parseInt(phaseNum, 10) && e.plan === parseInt(planNum, 10) && e.task === parseInt(taskNum, 10) && e.status === "fail");
147
149
 
150
+ // Hard stop: 3 recorded failures for the same task ends the retry loop.
151
+ // The orchestrator must escalate to the user or a fix plan — never a 4th blind attempt.
148
152
  if (taskFailures.length >= 3) {
149
- console.log(`\n⚠️ Task has failed 3+ times. Consider creating a fix plan:`);
150
- console.log(` draht create-fix-plan ${phaseNum} ${planNum} "Task ${taskNum} failed repeatedly"`);
153
+ console.error(`\n❌ HARD STOP: task ${phaseNum}-${planNum}-${taskNum} has failed ${taskFailures.length} times.`);
154
+ console.error(` Do NOT re-dispatch the implementer. Escalate: report to the user or create a fix plan:`);
155
+ console.error(` draht create-fix-plan ${phaseNum} ${planNum} "Task ${taskNum} failed repeatedly"`);
156
+ process.exit(1);
151
157
  }
152
158
  } else {
153
159
  console.log(`⏭️ Task ${phaseNum}-${planNum}-${taskNum}: skipped`);
@@ -6,7 +6,9 @@
6
6
  * Runs after task completion to enforce quality standards.
7
7
  * Called by the build agent after each verify step.
8
8
  *
9
- * Usage: node gsd-quality-gate.js [--strict]
9
+ * Usage: node gsd-quality-gate.js [--strict] [--no-tests]
10
+ * --no-tests skips the test-suite run (used by the Stop hook, where the
11
+ * post-task hook and /verify-work own test execution).
10
12
  * Exit 0 = quality OK, Exit 1 = quality issues
11
13
  */
12
14
 
@@ -29,7 +31,9 @@ function detectToolchain(cwd) {
29
31
  }
30
32
 
31
33
  function readHookConfig(cwd) {
32
- const defaults = { coverageThreshold: 80, tddMode: "advisory", qualityGateStrict: false };
34
+ // Strict by default: failing tests/types/lint fail the gate (exit 1).
35
+ // Opt out per-project with hooks.qualityGateStrict: false in .planning/config.json.
36
+ const defaults = { coverageThreshold: 80, tddMode: "advisory", qualityGateStrict: true };
33
37
  const configPath = path.join(cwd, ".planning", "config.json");
34
38
  if (!fs.existsSync(configPath)) return defaults;
35
39
  try {
@@ -67,6 +71,7 @@ const cwd = process.cwd();
67
71
  const toolchain = detectToolchain(cwd);
68
72
  const hookConfig = readHookConfig(cwd);
69
73
  const strict = process.argv.includes("--strict") || hookConfig.qualityGateStrict;
74
+ const skipTests = process.argv.includes("--no-tests");
70
75
  const issues = [];
71
76
 
72
77
  // 1. TypeScript check
@@ -92,7 +97,7 @@ if (fs.existsSync(path.join(cwd, "biome.json"))) {
92
97
  }
93
98
 
94
99
  // 3. Run tests
95
- try {
100
+ if (!skipTests) try {
96
101
  const testOutput = execSync(`${toolchain.testCmd} 2>&1`, { timeout: 120000, encoding: "utf-8", cwd });
97
102
  const failMatch = testOutput.match(/(\d+) fail/);
98
103
  if (failMatch && parseInt(failMatch[1], 10) > 0) {