claude-dev-env 1.17.1 → 1.17.5

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.
@@ -5,8 +5,8 @@ description: >-
5
5
  instructions, agent harnesses, tool-use patterns, evaluation rubrics, NotebookLM audio
6
6
  customization, and MCP or browser automation steering. Gathers scope through discovery
7
7
  and AskUserQuestion, runs the default refinement pipeline in a drafting subagent, runs a
8
- mandatory Outcome preview AskUserQuestion gate, then delivers a one-line audit, one fenced
9
- XML block, and a skimmable Outcome digest after the fence. Trigger when the user asks to
8
+ mandatory Outcome preview AskUserQuestion gate, then delivers one fenced XML block and a
9
+ skimmable Outcome digest after the fence. Trigger when the user asks to
10
10
  write, refine, or improve steering text for Claude. Execution of the described work belongs
11
11
  in /agent-prompt only after the user explicitly confirms they want it run.
12
12
  ---
@@ -26,25 +26,25 @@ description: >-
26
26
 
27
27
  **Templates:** Under `packages/claude-dev-env/skills/prompt-generator/templates/`, `skill-from-ground-up.md` is the collaborative prompt for **net-new** checkpointed Agent Skill packages; `skill-refinement-package.md` is the sibling prompt for **existing-skill** multi-file refinements and package-aware polish. Skill-builder and skill-writer in this repo require implementers to use the matching template before checkpointed package work.
28
28
 
29
- **Terminology:** **Prompt artifact** — the full XML inside the single user-facing `xml` fence (the paste-ready output). **Outcome digest** — skimmable `## Outcome digest` markdown **after** that fence on the final turn: what executing the prompt produces, inputs or tools, done criteria, short sample (see `TARGET_OUTPUT.md`). **Outcome preview gate** — mandatory `AskUserQuestion` **after** internal drafting returns candidate XML and **before** the final `Audit` line ships; uses `### Outcome preview` bullets plus confirmation options (**Ship** first, two contextual alternates, **Refine with free text**). **Preview summary** — structured fields the drafting subagent returns to the orchestrator: `final_prompt_xml`, `what_executor_produces`, `primary_inputs_or_tools`, `done_when`, `sample_excerpt_markdown` (about twenty lines; follow the sample formatting rules in SKILL.md section 7). **Scope block** — the five-key contract in §3A that grounds instructions. **Default refinement pipeline** — §10: base draft → section refine → merge → 15-row compliance audit → capped fixes (subagent-internal unless draft-only). **Light self-check** — §8: fast pre-return pass on output shape, tools, scope, and patterns; *not* the compliance audit. **Compliance audit (15-row)** — §11: hook-keyed rows that set the `Audit: pass|fail` numerator. **Execution handoff** — `/agent-prompt` after explicit user intent to run work. **Hook validation block** — structured fields appended after the Outcome digest for hook validation. Fields: `overall_status`, `checklist_results` rows, five scope-anchor tokens, `base_minimal_instruction_layer: true` (signals to the `prompt-workflow-guard` hook that the response includes the required minimal instruction scaffolding: scope anchors, checklist rows, and runtime signals), and `on_demand_skill_loading: true` (signals to the same hook that heavy skills were loaded only when the task explicitly required them, per section 17 context-footprint controls). All other files reference this single definition.
29
+ **Terminology:** **Prompt artifact** — the full XML inside the single user-facing `xml` fence (the paste-ready output). **Outcome digest** — skimmable `## Outcome digest` markdown **after** that fence on the final turn: what executing the prompt produces, inputs or tools, done criteria, short sample (see `TARGET_OUTPUT.md`). **Outcome preview gate** — mandatory `AskUserQuestion` **after** internal drafting returns candidate XML and **before** the final fenced artifact ships; uses `### Outcome preview` bullets plus confirmation options (**Ship** first, two contextual alternates, **Refine with free text**). **Preview summary** — structured fields the drafting subagent returns to the orchestrator: `final_prompt_xml`, `what_executor_produces`, `primary_inputs_or_tools`, `done_when`, `sample_excerpt_markdown` (about twenty lines; follow the sample formatting rules in SKILL.md section 7). **Scope block** — the five-key contract in §3A that grounds instructions. **Default refinement pipeline** — §10: base draft → section refine → merge → 15-row compliance audit → capped fixes (subagent-internal unless draft-only). **Light self-check** — §8: fast pre-return pass on output shape, tools, scope, and patterns; *not* the compliance audit. **Compliance audit (15-row)** — §11: hook-keyed rows the subagent evaluates internally; ships only after the file-based validation loop exits 0. **Execution handoff** — `/agent-prompt` after explicit user intent to run work. **Hook validation block** — structured fields for validation. Fields: `overall_status`, `checklist_results` rows, five scope-anchor tokens, `base_minimal_instruction_layer: true` (signals that the response includes the required minimal instruction scaffolding: scope anchors, checklist rows, and runtime signals), and `on_demand_skill_loading: true` (signals that heavy skills were loaded only when the task explicitly required them, per section 17 context-footprint controls). Stripped before user output. All other files reference this single definition.
30
30
 
31
- **Hook-survival invariant (read first):** The fenced XML artifact is the primary deliverable and MUST survive Stop-hook retries. If a Stop hook rejects the response, only the surrounding audit line, **Outcome digest**, hook validation block, and runtime signal scaffolding may change between retries—the XML inside the fence MUST be re-emitted in full on every retry. **Recovery order (user-visible):** match the standard output order: **Audit line** complete ` ```xml ` block **## Outcome digest** optional hook validation block. Re-send that full sequence on each retry attempt; keep the fenced XML payload byte-identical until the gate passes; adjust only the audit prefix or non-fence scaffolding when required. Trimming, summarizing, or deferring the prompt artifact to satisfy a hook gate is forbidden.
31
+ **File-based validation loop (read first):** The fenced XML artifact is the primary deliverable. The drafting subagent writes the complete output (fenced XML + Outcome digest + hook validation block) to `data/prompts/.draft-prompt.xml`, runs `python packages/claude-dev-env/hooks/blocking/prompt_workflow_validate.py data/prompts/.draft-prompt.xml`, reads stderr for any `[reason_code] message` violations when exit code is 2, edits the file to fix violations, and re-runs until exit code 0. Only then does the orchestrator strip the hook validation block, output fenced XML + Outcome digest to the user, and delete the temp file. Trimming or summarizing the prompt artifact to pass validation is forbidden.
32
32
 
33
- **Turn shape:** Each orchestrator turn is one of: **AskUserQuestion** only (then wait); **Outcome preview** turn (`### Outcome preview` markdown bullets + **AskUserQuestion** only); or the **final handoff** (`Audit:` + one `xml` fence + `## Outcome digest` + optional hook validation block)—per `TARGET_OUTPUT.md`. Do not substitute free-form question paragraphs for scope clarifications; preview bullets are statements, not standalone interrogative paragraphs.
33
+ **Turn shape:** Each orchestrator turn is one of: **AskUserQuestion** only (then wait); **Outcome preview** turn (`### Outcome preview` markdown bullets + **AskUserQuestion** only); or the **final handoff** (one `xml` fence + `## Outcome digest`)—per `TARGET_OUTPUT.md`. Do not substitute free-form question paragraphs for scope clarifications; preview bullets are statements, not standalone interrogative paragraphs.
34
34
 
35
- **Happy path:** (1) Choose scenario **1–4** from the router table. (2) Run discovery when that scenario calls for repo tools. (3) **AskUserQuestion** (one form per round, **2–4** options per field, recommended first). (4) Subagent produces XML plus **preview summary**, runs **light self-check**, then **15-row compliance audit** + refinement loop. (5) Orchestrator emits **Outcome preview** turn from the preview summary; user confirms or refines (up to **three** preview rounds unless the user raises the cap in chat). (6) Orchestrator prints **`Audit: pass 15/15`** or **`Audit: fail N/15 — [reason]`**, the **complete fenced XML**, then **`## Outcome digest`**, then any hook validation block hooks expect. (7) If the user names a debug phrase, append the full table / JSON **after** digest and hook validation block per `TARGET_OUTPUT.md`.
35
+ **Happy path:** (1) Choose scenario **1–4** from the router table. (2) Run discovery when that scenario calls for repo tools. (3) **AskUserQuestion** (one form per round, **2–4** options per field, recommended first). (4) Subagent produces XML plus **preview summary**, runs **light self-check**, then **15-row compliance audit** + refinement loop (all internal). (5) Orchestrator emits **Outcome preview** turn from the preview summary; user confirms or refines (up to **three** preview rounds unless the user raises the cap in chat). (6) Orchestrator prints the **complete fenced XML**, then **`## Outcome digest`**. (7) If the user names a debug phrase, append the full table / JSON **after** digest per `TARGET_OUTPUT.md`.
36
36
 
37
- **Clarity bar:** Ship concrete, outcome-first copy everywhere (AskUserQuestion fields, audit line, XML body): name *what* to do, *where* it applies, and *how* to verify done—per [Be clear and direct](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#be-clear-and-direct) and [Control the format of responses](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#control-the-format-of-responses). This skill **authors** prompts; downstream execution stays out of the default path until `/agent-prompt`.
37
+ **Clarity bar:** Ship concrete, outcome-first copy everywhere (AskUserQuestion fields, XML body, Outcome digest): name *what* to do, *where* it applies, and *how* to verify done—per [Be clear and direct](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#be-clear-and-direct) and [Control the format of responses](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#control-the-format-of-responses). This skill **authors** prompts; downstream execution stays out of the default path until `/agent-prompt`.
38
38
 
39
39
  ## Primary mission: paste-ready XML prompts (overrides other delivery instructions)
40
40
 
41
- **Delivery contract:** Each completed request yields a **repo-grounded XML prompt** a human or agent can paste into a new session, preceded by confirmation at the **Outcome preview gate** and followed by an **Outcome digest** for skimming. Turns go to discovery, **AskUserQuestion**, subagent drafting, preview gate, optional refinement loops, then the final handoff. **Author vs execution:** this skill ends at the artifact plus digest; when the user wants edits, tests, or PRs run for real, they confirm and move to **`/agent-prompt`**.
41
+ **Delivery contract:** Each completed request yields a **repo-grounded XML prompt** a human or agent can paste into a new session, preceded by confirmation at the **Outcome preview gate** and followed by an **Outcome digest** for skimming. **Author vs execution:** this skill ends at the artifact plus digest; when the user wants edits, tests, or PRs run for real, they confirm and move to **`/agent-prompt`**.
42
42
 
43
- **Hook-survival invariant:** Treat the fenced XML as the immutable payload for paste operations. On every Stop-hook retry, print the **same full** XML between the opening and closing fences; adjust only the one-line audit prefix (or other non-fence scaffolding) if a hook requires a format tweak. Re-emit the **entire** XML body before tweaking surrounding text—never shorten the artifact to pass a gate. Re-emit the **Outcome digest** after the fence on the same schedule as the successful audit line.
43
+ **Validation loop invariant:** The fenced XML is the immutable payload for paste operations. During the validation loop, keep the XML byte-identical between iterations; adjust only surrounding scaffolding. When a violation is inside the artifact (e.g. negative keywords), edit only the specific flagged lines.
44
44
 
45
- **Orchestrator vs subagent:** The **orchestrator** runs ordered discovery, issues **AskUserQuestion**, runs the **Outcome preview gate**, and owns the **final** handoff: audit + fence + digest (+ hook validation block when used). The **subagent** owns base draft, per-section refinement, merge, the **15-row compliance audit**, and returns **final XML string + pass/fail counts + preview summary** to the orchestrator (no user-facing compliance table)—unless the user asked for **draft-only** / **no refinement**, in which case you may draft inline with the same preview + handoff shape. Keep hook retries internal; expose at most one short line such as `Retrying: scope anchor missing` before the successful handoff.
45
+ **Orchestrator vs subagent:** The **orchestrator** owns discovery, **AskUserQuestion**, the **Outcome preview gate**, and the **final** handoff: read the validated file, strip the hook validation block, output fence + digest, copy to clipboard (respecting `PROMPT_WORKFLOW_SKIP_CLIPBOARD`), and delete `data/prompts/.draft-prompt.xml`. The **subagent** owns base draft, per-section refinement, merge, the **15-row compliance audit**, writing to `data/prompts/.draft-prompt.xml`, and the file-based validation loop until exit 0; returns **pass/fail counts + preview summary** to the orchestrator (no user-facing compliance table). For **draft-only** requests, draft inline with the same preview + handoff shape.
46
46
 
47
- **Interaction shape:** Route scope clarifications through **AskUserQuestion** only. Close each successful run with **audit line + one fenced XML block + Outcome digest**; keep implementation plans **inside** the fenced XML for the downstream consumer, not as a chat to-do list.
47
+ **Interaction shape:** Route scope clarifications through **AskUserQuestion** only. Close each successful run with **one fenced XML block + Outcome digest**; keep implementation plans **inside** the fenced XML for the downstream consumer, not as a chat to-do list.
48
48
 
49
49
  ## User-visible output contract (mandatory)
50
50
 
@@ -53,8 +53,8 @@ Match `TARGET_OUTPUT.md`. Summary:
53
53
  1. **Questions:** Use **AskUserQuestion** for every scope clarification (one multi-field form per round); keep normal assistant text free of standalone question paragraphs outside preview bullets.
54
54
  2. **Options:** Supply **2–4** options per question, **recommended option first**; label discovery-sourced choices **`[discovered]`**.
55
55
  3. **Outcome preview turn:** `### Outcome preview` bullet block (preview summary) plus **AskUserQuestion** with **Ship this outcome profile** first, two contextual alternates, **Refine with free text**; cap at three preview rounds unless the user raises the cap in chat.
56
- 4. **Final message:** Line 1 = `Audit: pass 15/15` or `Audit: fail N/15 — [short reason]`; then **one** ` ```xml ` fence with the **complete** prompt; then **`## Outcome digest`**; then optional hook validation block (checklist rows, scope anchors, runtime signals) for hooks—**paste-ready section** remains the single `xml` fence for downstream paste.
57
- 5. **Full audit table / JSON debug object:** Append only after the user uses an explicit debug phrase such as `show debug`, `full audit table`, or `raw internal object`, and only **after** digest and hook validation block.
56
+ 4. **Final message:** **One** ` ```xml ` fence with the **complete** prompt; then **`## Outcome digest`**—**paste-ready section** remains the single `xml` fence for downstream paste.
57
+ 5. **Full audit table / JSON debug object:** Append only after the user uses an explicit debug phrase such as `show debug`, `full audit table`, or `raw internal object`, and only **after** digest.
58
58
  6. **Commit-and-execute:** Pick a drafting approach, carry it through preview confirmation, ship the handoff; change plans only when **new** facts from the user or tools contradict the earlier scope.
59
59
 
60
60
  **Required XML sections** inside the fence: `<role>`, `<background>`, `<instructions>`, `<constraints>`, `<output_format>`. Optional: `<illustrations>`, `<open_question>` (use for unresolved discovery — see structural invariant D in `TARGET_OUTPUT.md`).
@@ -68,7 +68,7 @@ Match `TARGET_OUTPUT.md`. Summary:
68
68
  | **3 — Long unstructured input** | Many requirements / paths in one message | Verify repo references (packages, shared utils, configs) with targeted tools **before** questions | First question **confirms extracted intent**; ambiguities as **specific** options; **every** user-stated requirement captured in the generated XML by name — track all requirements from the unstructured input and confirm coverage before shipping |
69
69
  | **4 — Noisy context** | Long unrelated thread before `/prompt-generator` | Build the subagent brief from: the user’s literal `/prompt-generator` text, a **≤120-word** summary of on-topic facts, and discovery notes—**exclude** raw stack traces and unrelated tangents | As needed (often Scenario 1-shaped) |
70
70
 
71
- **Final handoff (all scenarios):** After drafting, every run uses the **Outcome preview** turn, then the final message **Audit** → ` ```xml ` → `## Outcome digest` → optional hook validation block (`TARGET_OUTPUT.md`).
71
+ **Final handoff (all scenarios):** After drafting, every run uses the **Outcome preview** turn, then the final message ` ```xml ` → `## Outcome digest` (`TARGET_OUTPUT.md`).
72
72
 
73
73
  **Handoff (Scenario 2):** `<background>` must be **self-contained** — state, **decisions**, files touched, next steps, constraints — so a new session needs no prior chat. Preserve prior decisions verbatim in the handoff; quote the exact decision text where precision matters rather than paraphrasing it away.
74
74
 
@@ -76,9 +76,9 @@ Match `TARGET_OUTPUT.md`. Summary:
76
76
 
77
77
  For the **final** user-visible turn that ships the artifact:
78
78
 
79
- - Compose the message as **audit line → opening fence → XML → closing fence → `## Outcome digest` → optional hook validation block → end**; keep the byte stream free of `tool_use` blocks **between** the opening and closing fences.
79
+ - Compose the message as **opening fence → XML → closing fence → `## Outcome digest` → end**; keep the byte stream free of `tool_use` blocks **between** the opening and closing fences.
80
80
  - **Completeness:** End every numbered step inside `<instructions>` with a complete sentence and a fully written list item. Balance every XML tag explicitly (open and close each `<role>`, `<background>`, `<instructions>`, `<constraints>`, `<output_format>`). The artifact must be copy-pasteable into a new file with zero manual repair.
81
- - Global pipeline: **discovery tools** (when applicable) → **AskUserQuestion** → **subagent** (draft + refinement + internal audit + **preview summary**) → **Outcome preview** turn → optional refinement loops → **one** orchestrator reply with audit line + fence + digest (+ hook validation block).
81
+ - Global pipeline: **discovery tools** (when applicable) → **AskUserQuestion** → **subagent** (draft + refinement + internal audit + **preview summary**) → **Outcome preview** turn → optional refinement loops → **one** orchestrator reply with fence + digest.
82
82
 
83
83
  ## Interactive discovery mode (default)
84
84
 
@@ -100,9 +100,9 @@ Issue **one** AskUserQuestion with all fields populated from discovery and the u
100
100
  Spawn a **subagent** (Agent tool) with:
101
101
 
102
102
  - Scenario id (1–4), user goal, discovery summary, AskUserQuestion answers (and any **Refine with free text** deltas from prior preview rounds)
103
- - Instruction: produce **one** well-formed XML prompt (required sections) + run the internal refinement loop and **15-row compliance audit**; return **final XML string**, **pass/fail + fail count** for that audit, and **preview summary** fields (`what_executor_produces`, `primary_inputs_or_tools`, `done_when`, `sample_excerpt_markdown` following the sample formatting rules in SKILL.md section 7, about twenty lines max)
103
+ - Instruction: produce **one** well-formed XML prompt (required sections) + run the internal refinement loop and **15-row compliance audit**; write the complete output (fenced XML + Outcome digest + hook validation block) to `data/prompts/.draft-prompt.xml`; run `python packages/claude-dev-env/hooks/blocking/prompt_workflow_validate.py data/prompts/.draft-prompt.xml`; if exit code 2, read stderr violations, edit the draft file, and re-run until exit code 0; return **pass/fail + fail count** for the audit and **preview summary** fields (`what_executor_produces`, `primary_inputs_or_tools`, `done_when`, `sample_excerpt_markdown` following the sample formatting rules in SKILL.md section 7, about twenty lines max)
104
104
 
105
- Keep subagent reasoning in the Agent transcript; the user-facing **Outcome preview** turn surfaces the preview summary; the **final** turn contains audit + fence + digest (+ hook validation block).
105
+ Keep subagent reasoning in the Agent transcript; the user-facing **Outcome preview** turn surfaces the preview summary; the **final** turn contains fence + digest.
106
106
 
107
107
  ### Phase 4 — Outcome preview gate
108
108
 
@@ -112,9 +112,9 @@ Keep subagent reasoning in the Agent transcript; the user-facing **Outcome previ
112
112
 
113
113
  ### Phase 5 — Final handoff
114
114
 
115
- Print **`Audit: pass 15/15`** or **`Audit: fail N/15 — [reason]`**, the **complete fenced XML**, then **`## Outcome digest`** (tightened copy from the accepted preview summary), then any hook validation block the prompt-workflow hooks expect.
115
+ Print the **complete fenced XML**, then **`## Outcome digest`** (tightened copy from the accepted preview summary).
116
116
 
117
- **Draft-only:** If the user explicitly requests no refinement (“quick draft”, “no refinement loop”), the subagent may skip Steps 10–12 below but must still return valid XML, honest audit line, and a **preview summary**; Phases 4–5 still run so the user confirms shape before paste.
117
+ **Draft-only:** If the user explicitly requests no refinement (“quick draft”, “no refinement loop”), the subagent may skip Steps 10–12 below but must still return valid XML and a **preview summary**; Phases 4–5 still run so the user confirms shape before paste.
118
118
 
119
119
  ## Workflow (run in order — primarily inside the drafting subagent)
120
120
 
@@ -152,17 +152,17 @@ Apply principles from Anthropic’s prompting guide (see REFERENCE.md): XML sect
152
152
 
153
153
  **Structural invariant D:** Write `<instructions>` / `<constraints>` as direct imperatives (“Open `path/to/file.ts` and …”). Park unresolved items in `<open_question>` tags—one distinct question per tag with the exact decision you need. Inside the fenced XML artifact, use only confident, definitive language: replace hedging phrases (“let me also check”, “actually”, “one more consideration”) and tentative qualifiers (“might be”, “possibly”, “I think”, “could be”) with direct assertions or move genuine uncertainty into `<open_question>` tags.
154
154
 
155
- **Set a role** in the system prompt. Anthropic: "Setting a role in the system prompt focuses Claude's behavior and tone for your use case. Even a single sentence makes a difference."
155
+ **Set a role** in the system prompt even a single sentence focuses behavior and tone.
156
156
 
157
- **Add motivation behind constraints** in `<background>`. Anthropic: "Providing context or motivation behind your instructions... can help Claude better understand your goals and deliver more targeted responses." Claude generalizes from the explanation.
157
+ **Add motivation behind constraints** in `<background>`. Claude generalizes from the explanation, delivering more targeted responses.
158
158
 
159
- **Frame positively (zero-negative-keyword rule).** Anthropic: state the desired outcome directly. "Your response should be composed of smoothly flowing prose paragraphs" provides clearer guidance than a prohibition-only instruction. Apply this rule absolutely inside the fenced XML artifact across all sections (`<role>`, `<background>`, `<instructions>`, `<constraints>`, `<output_format>`): every instruction states what to do, what to produce, what to enforce. Use affirmative directives exclusively: "only X", "always X", "ensure X", "require X." Banned keywords inside generated XML: "no", "not", "don't", "do not", "never", "avoid", "without", "refrain", "stop", "prevent", "exclude", "prohibit", "forbid", "reject", "cannot", "unless." Also banned: indirect negative patterns such as "instead of X", "rather than X", "as opposed to." Example pass: "Ensure all functions have explicit return types." Example fail: "Do not leave return types implicit." When a boundary is needed, phrase it as what is permitted: "only run commands within the scoped paths" rather than a prohibition.
159
+ **Frame positively (zero-negative-keyword rule).** Anthropic: state the desired outcome directly. "Your response should be composed of smoothly flowing prose paragraphs" provides clearer guidance than a prohibition-only instruction. Apply this rule across all XML sections: every instruction states what to do, what to produce, what to enforce. Use affirmative directives exclusively: "only X", "always X", "ensure X", "require X." Banned keywords inside generated XML: "no", "not", "don't", "do not", "never", "avoid", "without", "refrain", "stop", "prevent", "exclude", "prohibit", "forbid", "reject", "cannot", "unless." Also banned: indirect negatives ("instead of X", "rather than X", "as opposed to"). Example pass: "Ensure all functions have explicit return types." Example fail: "Do not leave return types implicit." When a boundary is needed, phrase it as what is permitted: "only run commands within the scoped paths" rather than a prohibition.
160
160
 
161
- **Emotion-informed framing.** Anthropic's emotion concepts research (2026) shows that internal activation patterns causally influence output quality. Apply: explicit success criteria with "say so if you're unsure" as an accepted answer; collaborative language ("help figure out", "work on this together"); framing tasks as interesting problems rather than chores; constructive, forward-looking tone. Cross-model caveat: studied on Sonnet 4.5; the patterns align with Anthropic's prompting best practices independently. Full pattern catalog and citations: `packages/claude-dev-env/docs/emotion-informed-prompt-design.md`.
161
+ **Emotion-informed framing.** Apply: explicit success criteria with "say so if you're unsure" as an accepted answer; collaborative language ("help figure out", "work on this together"); framing tasks as interesting problems; constructive, forward-looking tone. Full catalog: `packages/claude-dev-env/docs/emotion-informed-prompt-design.md`.
162
162
 
163
163
  **Golden rule check.** Anthropic: "Show your prompt to a colleague with minimal context on the task and ask them to follow it. If they'd be confused, Claude will be too."
164
164
 
165
- **Commit-and-execute pattern.** Anthropic: "When you're deciding how to approach a problem, choose an approach and commit to it. Avoid revisiting decisions unless you encounter new information that directly contradicts your reasoning." For prompts that guide agents through multi-step work, include this pattern so the agent doesn't spin revisiting decisions.
165
+ **Commit-and-execute pattern.** For multi-step agent prompts, include: "Choose an approach and commit to it. Revisit only when new information directly contradicts your reasoning."
166
166
 
167
167
  **Tool-return policy (agent-harness / tool-use prompts):** Require explicit justification before the harness tokenizes full tool outputs; when the next hop needs only a slice or a tool-to-tool handoff, steer authors toward code execution (bash/REPL) so only execution output reaches model-visible context—not every intermediate payload (Hook 2; [Harnessing Claude's intelligence](https://claude.com/blog/harnessing-claudes-intelligence)).
168
168
 
@@ -193,9 +193,10 @@ Use the optional `<illustrations>` section when concrete samples make format, to
193
193
 
194
194
  These steps are instructions for the orchestrator and drafting subagent to follow when filling `<illustrations>`. The person invoking `/prompt-generator` receives the finished fenced XML.
195
195
 
196
+
196
197
  ### 8. Light self-check (subagent, pre-return)
197
198
 
198
- **Two-tier validation — tier 1:** Before the subagent returns XML, run a quick pass on output shape, tool phrasing, scope anchors, and safety / research / agentic patterns as applicable (see REFERENCE.md and patterns below). This **light self-check** is not interchangeable with the **15-row compliance audit** in §11; tier 2 supplies the hook-keyed pass/fail counts for the `Audit:` line.
199
+ Before the subagent returns XML, run a quick pass on output shape, tool phrasing, scope anchors, and applicable patterns (see REFERENCE.md). This **light self-check** (tier 1) is separate from the **15-row compliance audit** (tier 2, §11).
199
200
 
200
201
  Expand the light self-check with this internal checklist when useful:
201
202
 
@@ -215,22 +216,14 @@ Expand the light self-check with this internal checklist when useful:
215
216
 
216
217
  ### 9. Deliver (orchestrator)
217
218
 
218
- The orchestrator’s **final** delivery to the user is, in order:
219
-
220
- ```text
221
- Audit: pass 15/15
222
- ```
223
-
224
- (or `fail N/15 — …`), immediately followed by **one** fenced `xml` block (paste-ready prompt artifact), immediately followed by **`## Outcome digest`** containing:
225
-
226
- - **What the downstream executor produces** (from `what_executor_produces`)
227
- - **Primary inputs or tools** (from `primary_inputs_or_tools`)
228
- - **Done when** (from `done_when`)
229
- - **Sample excerpt** (from `sample_excerpt_markdown`; follow the sample formatting rules in SKILL.md section 7 because `extract_fenced_xml_content` concatenates every `xml` fence)
219
+ The orchestrator’s **final** delivery to the user is, in order: **one** fenced `xml` block (paste-ready prompt artifact), immediately followed by **`## Outcome digest`** containing:
230
220
 
231
- Then append the **hook validation block** (see Terminology above) **after** the digest when the workflow emits it for hooks.
221
+ - **What it does** plain-language summary of what running this prompt produces
222
+ - **Key inputs** — what the prompt needs to work (files, tools, context)
223
+ - **Done when** — how to tell the prompt succeeded
224
+ - **Quick sample** — short example of what the output looks like (follow the sample formatting rules in SKILL.md section 7 because `extract_fenced_xml_content` concatenates every `xml` fence)
232
225
 
233
- **Paste-ready section:** Only the ` ```xml ` … ` ``` ` span is intended for clipboard paste into a downstream session; the digest and hook validation block are for reading and hook validation.
226
+ **Paste-ready section:** Only the ` ```xml ` … ` ``` ` span is intended for clipboard paste into a downstream session; the digest is for reading.
234
227
 
235
228
  **Render-survival:** When the fenced XML uses tag names that **collide with HTML5 elements** (`section`, `summary`, `details`, `header`, `footer`, `main`, `aside`, `article`, `nav`, `figure`), or when the artifact is **very large**, **write the artifact to a file** and give the user the path together with the usual one-line audit. Add a brief **section inventory** (confirming the five required sections) so the user can trust the file even if the inline fence would render poorly. Still emit **Outcome digest** (and file path if used) after the inline fence closes. Required grounding uses `<background>` (the old `context` name matched HTML). Details: **TARGET_OUTPUT.md — Structural invariant E**.
236
229
 
@@ -248,9 +241,9 @@ Required section list is immutable for this pipeline: `role`, `background`, `ins
248
241
 
249
242
  ### 11. Compliance audit — 15-row checklist (internal, audit numerator)
250
243
 
251
- **Two-tier validation — tier 2:** The `15` in `Audit: pass 15/15` counts these **compliance** rows (stable ids for hooks). Tier 1 is the **light self-check** in §8—keep the steps separate so models do not merge them.
244
+ The 15-row compliance audit counts these **compliance** rows (stable ids for hooks). Keep separate from the **light self-check** (§8, tier 1).
252
245
 
253
- **Runtime Stop hook:** In addition to the 15-row internal audit, the `prompt-workflow-stop-guard` Stop hook enforces **section presence** on prompt-workflow responses: any fenced Markdown XML block must include opening and closing tags for `role`, `background`, `instructions`, `constraints`, and `output_format`. Missing tags trigger a retry before the user sees a passing turn. Pair this with **Structural invariant E** in `TARGET_OUTPUT.md` so users still receive intact XML when chat renderers strip HTML-named tags. `prompt_workflow_gate_core.extract_fenced_xml_content` scans each inner Markdown fence (` ```lang ` through its closing `` ``` `` line) as a unit so hooks and clipboard copy see the **full** XML body, including everything after inner fences inside `<illustrations>`.
246
+ **File-based validation:** The `prompt_workflow_validate.py` CLI enforces **section presence**, **scope anchors**, **checklist rows**, **context-control signals**, **ambiguous scope detection**, and **negative keyword detection** on the draft file. The subagent fixes violations until exit code 0. Pair with **Structural invariant E** in `TARGET_OUTPUT.md` for render-survival. `extract_fenced_xml_content` scans inner Markdown fences as units so validation and clipboard see the **full** XML body.
254
247
 
255
248
  | # | Row name |
256
249
  |---|----------|
@@ -274,13 +267,13 @@ For each row, maintain `status`, `evidence_quote`, `source_ref`, and `fix_if_fai
274
267
 
275
268
  ### 12. Debug-only bundle (explicit user request only)
276
269
 
277
- When the user explicitly asks for debug / full audit, emit the markdown table, `scope_block` recap, and the debug JSON **in addition to** the audit line + XML fence + **Outcome digest** + any hook validation block.
270
+ When the user explicitly asks for debug / full audit, emit the markdown table, `scope_block` recap, and the debug JSON **in addition to** the XML fence + **Outcome digest**.
278
271
 
279
- **Default user-facing path (keeps Stop hooks green):** On non-debug turns, after the `xml` fence, emit **Outcome digest** and hook validation block, then **stop**—do **not** add a second outer fenced block for debug payloads, do **not** start the assistant message with `{`, and keep internal pipeline keys (`pipeline_mode`, `scope_block_validation`, `evidence_quotes`, `source_refs`, `corrective_edits`, `retry_count`, `audit_output_contract`, `section_output_contract`, `base_prompt_xml`, `required_sections`) inside the debug JSON only.
272
+ **Default user-facing path:** On non-debug turns, after the `xml` fence, emit **Outcome digest**, then **stop**—do **not** add a second outer fenced block for debug payloads, do **not** start the assistant message with `{`, and keep internal pipeline keys (`pipeline_mode`, `scope_block_validation`, `evidence_quotes`, `source_refs`, `corrective_edits`, `retry_count`, `audit_output_contract`, `section_output_contract`, `base_prompt_xml`, `required_sections`) inside the debug JSON only.
280
273
 
281
274
  **Debug JSON shape:** Full schema and field definitions: **REFERENCE.md** → **Debug JSON schema (prompt-generator pipeline)**. Use that object only on debug requests.
282
275
 
283
- **Hook-recovery (default path):** Print the full handoff again in standard output order: **Audit line**, complete ` ```xml ` fence, **## Outcome digest**, then hook validation block when used. Keep every XML section inside the fence intact while you adjust audit prefix or scaffolding outside the fence to satisfy the hook.
276
+ **Validation recovery (default path):** Fix the specific issue in `data/prompts/.draft-prompt.xml` and re-run the validator. Keep every XML section inside the fence intact; adjust only scaffolding outside the fence.
284
277
 
285
278
  ### 13. Scope quality rule for generated prompts
286
279
 
@@ -307,9 +300,9 @@ Use `/agent-prompt` only after the user explicitly asks to execute. Refinement s
307
300
 
308
301
  ### 17. Context-footprint controls
309
302
 
310
- Keep orchestrator turns structured: discovery → **AskUserQuestion** → subagent → **Outcome preview** turn → one final message (audit + fence + digest + hook validation block). Push heavy drafting to the subagent with a **curated** brief (especially Scenario 4).
303
+ Keep orchestrator turns structured: discovery → **AskUserQuestion** → subagent → **Outcome preview** turn → one final message (fence + digest). Push heavy drafting to the subagent with a **curated** brief (especially Scenario 4).
311
304
 
312
- **Low-context defaults:** Keep the base instruction layer in generated prompts lean—scope anchors, checklist-backed behaviors, and inert-content safety where hooks apply. Store stable enforcement text in hooks/rules instead of pasting full policy into every XML artifact. Load heavy skills only when the user’s task explicitly needs them. Prefer pointers to **REFERENCE.md** over repeating long excerpts; default user-visible output stays audit line + single `xml` fence + **Outcome digest** (+ hook validation block when used) unless the user requests debug extras.
305
+ **Low-context defaults:** Keep the base instruction layer in generated prompts lean—scope anchors, checklist-backed behaviors, and inert-content safety where hooks apply. Store stable enforcement text in hooks/rules instead of pasting full policy into every XML artifact. Load heavy skills only when the user’s task explicitly needs them. Prefer pointers to **REFERENCE.md** over repeating long excerpts; default user-visible output stays single `xml` fence + **Outcome digest** unless the user requests debug extras.
313
306
 
314
307
  ## Claude 4.6 considerations
315
308
 
@@ -340,7 +333,7 @@ For commands that delete data, rewrite shared history, or notify other people, o
340
333
  When tests fail or tooling blocks progress, prefer iterative fixes inside the allowed scope. Keep safety hooks (`--verify`, linters) enabled; surface unfamiliar files as questions.
341
334
  ```
342
335
 
343
- **Positive rewrite guidance:** When embedding this pattern into a generated XML artifact, rephrase each line using affirmative directives only (per the zero-negative-keyword rule in §4). Example rewrite for generated output: "Prioritize local, reversible actions: read files, run targeted tests, apply patches within scoped paths. Obtain explicit user approval before running commands that delete data, rewrite shared history, or send external notifications. Keep safety hooks enabled (`--verify`, linters). Surface unfamiliar files as questions for the user."
336
+ **Positive rewrite guidance:** When embedding this pattern into generated XML, apply the zero-negative-keyword rule (§4). Example: "Prioritize local, reversible actions: read files, run targeted tests, apply patches within scoped paths. Obtain explicit user approval before commands that delete data, rewrite shared history, or send external notifications. Keep safety hooks enabled. Surface unfamiliar files as questions for the user."
344
337
 
345
338
  ## Research prompt pattern
346
339
 
@@ -8,24 +8,22 @@ This file is the **target output spec** for eval-driven iteration of the `prompt
8
8
 
9
9
  ## Terminology
10
10
 
11
- - **Outcome preview gate** — Mandatory `AskUserQuestion` turn **after** the drafting subagent returns candidate XML internally and **before** the orchestrator emits the final `Audit` line and fenced artifact. Confirms the user recognizes what executing the generated prompt will produce.
11
+ - **Outcome preview gate** — Mandatory `AskUserQuestion` turn **after** the drafting subagent returns candidate XML internally and **before** the orchestrator emits the fenced artifact. Confirms the user recognizes what executing the generated prompt will produce.
12
12
  - **Outcome digest** — Skimmable markdown block **after** the closing ` ``` ` of the single `xml` fence on the final handoff: bullets for downstream deliverables, primary inputs or tools, done criteria, and a short sample excerpt (see `SKILL.md` §9).
13
13
 
14
14
  ## User-visible output contract
15
15
 
16
- - **Clarity bar:** Every deliverable (`AskUserQuestion` fields, audit line, XML body, outcome digest) states concrete outcomes, explicit formats, and checkable done-when signals—aligned with Anthropic [Be clear and direct](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#be-clear-and-direct) and [Control the format of responses](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#control-the-format-of-responses). Prefer what to do and how to verify it over empty prohibitions or vague quality adjectives.
16
+ - **Clarity bar:** Every deliverable (`AskUserQuestion` fields, XML body, outcome digest) states concrete outcomes, explicit formats, and checkable done-when signals—aligned with Anthropic [Be clear and direct](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#be-clear-and-direct) and [Control the format of responses](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#control-the-format-of-responses). Prefer what to do and how to verify it over empty prohibitions or vague quality adjectives.
17
17
  - **Questions:** Deliver every clarifying question through **AskUserQuestion** (one form per round), with **2–4** options per question and the **recommended** option listed **first**. Tag discovery-sourced options **`[discovered]`** when they came from repo search.
18
18
  - **Outcome preview turn (mandatory):** Immediately before the final handoff, emit exactly one assistant turn that contains:
19
- 1. A markdown block titled `### Outcome preview` with bullets only: **What the downstream executor produces**, **Primary inputs or tools**, **Done when**, **Sample excerpt** (about twenty lines max; follow the sample formatting rules in SKILL.md section 7).
19
+ 1. A markdown block titled `### Outcome preview` with bullets only: **What it does**, **Key inputs**, **Done when**, **Quick sample** (about twenty lines max; follow the sample formatting rules in SKILL.md section 7).
20
20
  2. **AskUserQuestion** with **2–4** options: **Ship this outcome profile** (recommended first), two **contextual alternates** grounded in discovery, and **Refine with free text** (starts another drafting loop). Observe the preview round cap per SKILL.md Phase 4.
21
21
  - **Final assistant message (complete handoff in one send):**
22
- 1. **Audit line:** `Audit: pass 15/15` or `Audit: fail N/15 [reason]`
23
- 2. **Artifact:** the full XML prompt inside **one** Markdown code fence whose language tag is `xml`
24
- 3. **Outcome digest:** after the closing fence, a `## Outcome digest` section repeating (or lightly tightening) the skimmable bullets and sample so the user can verify the paste-ready prompt matches intent **without** opening the whole XML
25
- 4. **Hook validation block (when used, defined in SKILL.md Terminology):** When the workflow emits the hook validation block, place it **after** the Outcome digest so `extract_fenced_xml_content` still returns only the XML body for clipboard copy
26
- 5. **Paste-ready section:** The paste-ready prompt artifact remains the single ` ```xml ` block; the digest and hook validation block are for reading and hook validation, not for pasting into the downstream session
27
- - **Full audit table / JSON debug bundle:** Stay internal until the user names debug with a phrase such as `show debug`, `full audit table`, or `raw internal object`; then append the table/JSON **after** the Outcome digest and any hook validation block.
28
- - **Hook retries:** Keep retry loops inside the subagent or internal pipeline; the user sees at most one short status line such as `Retrying: scope anchor missing` before the successful audit line + fence + digest.
22
+ 1. **Artifact:** the full XML prompt inside **one** Markdown code fence whose language tag is `xml`
23
+ 2. **Outcome digest:** after the closing fence, a `## Outcome digest` section with tightened bullets so the user can verify intent at a glance
24
+ 3. **Paste-ready section:** The paste-ready prompt artifact remains the single ` ```xml ` block; the digest is for reading, not for pasting into the downstream session
25
+ - **Full audit table / JSON debug bundle:** Stay internal until the user names debug with a phrase such as `show debug`, `full audit table`, or `raw internal object`; then append the table/JSON **after** the Outcome digest.
26
+ - **File-based validation loop:** The subagent writes output to `data/prompts/.draft-prompt.xml`, runs the validator CLI, and fixes violations until exit 0. The orchestrator then outputs the validated result to the user.
29
27
  - **Decision stability:** Pick one drafting approach, carry it through preview confirmation, then ship; change approach only when **new** facts from the user or tools contradict the earlier plan; if the draft fails checks, fix forward inside the same structure instead of restarting from scratch.
30
28
 
31
29
  ## Scenario 1: Fresh chat with brief goal
@@ -36,7 +34,7 @@ This file is the **target output spec** for eval-driven iteration of the `prompt
36
34
 
37
35
  **Q&A:** One AskUserQuestion with **2–4** questions covering: scope (which subtree), audience (human vs agent consumer), desired downstream output shape, and hard constraints (tests, CODE_RULES, deadlines). Populate options from discovery paths and package names.
38
36
 
39
- **Output:** After drafting, run the **Outcome preview** turn; then send audit line, `xml` fence, **Outcome digest**, and any hook validation block—the handoff message is complete.
37
+ **Output:** After drafting, run the **Outcome preview** turn; then send `xml` fence and **Outcome digest**—the handoff message is complete.
40
38
 
41
39
  ## Scenario 2: Session handoff
42
40
 
@@ -46,7 +44,7 @@ This file is the **target output spec** for eval-driven iteration of the `prompt
46
44
 
47
45
  **Q&A:** One AskUserQuestion with **1–2** questions, e.g. “Rank these next actions for the new session” or “Exclude these areas from scope,” each with **2–4** concrete options drawn from the thread.
48
46
 
49
- **Output:** After drafting, run the **Outcome preview** turn; then send audit line, `xml` fence, **Outcome digest**, and any hook validation block.
47
+ **Output:** After drafting, run the **Outcome preview** turn; then send `xml` fence and **Outcome digest**.
50
48
 
51
49
  **Handoff prompt quality:** `<background>` must include the bullet lists above so a new session can continue with **zero** access to this chat. Quote decision text verbatim where precision matters.
52
50
 
@@ -60,13 +58,13 @@ This file is the **target output spec** for eval-driven iteration of the `prompt
60
58
 
61
59
  **Requirements checklist:** The generated XML must mention every user-stated requirement by name (timeouts, selectors, config extraction, TDD, CODE_RULES, test safety, etc.); if one is out of scope, put the reason in `<open_question>`.
62
60
 
63
- **Output:** After drafting, run the **Outcome preview** turn; then send audit line, `xml` fence, **Outcome digest**, and any hook validation block.
61
+ **Output:** After drafting, run the **Outcome preview** turn; then send `xml` fence and **Outcome digest**.
64
62
 
65
63
  ## Scenario 4: Noisy context, stable output
66
64
 
67
65
  **Trigger:** `/prompt-generator ...` after a long thread with unrelated topics, tool errors, or tangents.
68
66
 
69
- **Output shape:** Same as Scenario 1 for the final message: audit line, one `xml` fence, **Outcome digest**, then any hook validation block.
67
+ **Output shape:** Same as Scenario 1 for the final message: one `xml` fence, then **Outcome digest**.
70
68
 
71
69
  **Content focus:** Keep the generated XML aligned with the latest `/prompt-generator` request (e.g. “security-focused code review agent”). Populate the subagent brief from: the user’s literal request string, a **one-paragraph** summary of on-topic facts, and path-grounded discovery notes—leave stack traces, failed commands, and off-topic thread history out of that brief so they never reach the XML body.
72
70
 
@@ -77,7 +75,7 @@ This file is the **target output spec** for eval-driven iteration of the `prompt
77
75
  ## Structural invariant A — Tool-free artifact output
78
76
 
79
77
  - **Order:** discovery tool calls (when used) → **AskUserQuestion** → subagent (draft + internal audit) → **Outcome preview** turn (`### Outcome preview` + **AskUserQuestion**) → optional refinement loops → **one** final assistant message.
80
- - **Final message composition:** That message is plain text only, in order: audit line → opening ` ```xml ` fence → XML body → closing fence → `## Outcome digest` → optional hook validation block → end-of-message. Run every `tool_use` in earlier turns; between the opening and closing `xml` fence, emit only the characters of the XML payload.
78
+ - **Final message composition:** That message is plain text only, in order: opening ` ```xml ` fence → XML body → closing fence → `## Outcome digest` → end-of-message. Run every `tool_use` in earlier turns; between the opening and closing `xml` fence, emit only the characters of the XML payload.
81
79
 
82
80
  ## Structural invariant B — Fenced block closes cleanly
83
81
 
@@ -102,12 +100,12 @@ This file is the **target output spec** for eval-driven iteration of the `prompt
102
100
  ## Structural invariant E — Render-survival for XML sections
103
101
 
104
102
  - **Problem (HTML):** Tag names used for prompt XML sections can overlap **HTML5 element names**. Chat renderers may treat those tokens as HTML and hide or alter the content between tags. High-risk examples include: `section`, `summary`, `details`, `header`, `footer`, `main`, `aside`, `article`, `nav`, `figure`. The former required name `context` matched an HTML element; **required** sections now use `<background>` for situational grounding so the name stays off that list. The raw assistant text may be complete while the **rendered** message looks like sections are missing.
105
- - **Problem (nested Markdown fences):** A ` ```bash ` (or other inner) line inside the outer ` ```xml ` block is still a line of text in the transcript, but many Markdown renderers treat it as **opening a nested code fence**, which **closes the outer fence early**. Everything after that point (including `</illustrations>` and other closing tags) can appear outside the code block or look “swallowed.” Hooks historically used a regex that stopped at the **first** triple-backtick line; `extract_fenced_xml_content` now walks inner fences (` ```lang ` … closing `` ``` ``) before accepting the outer `` ``` `` that ends the `xml` block.
103
+ - **Problem (nested Markdown fences):** A ` ```bash ` (or other inner) line inside the outer ` ```xml ` block is still a line of text in the transcript, but many Markdown renderers treat it as **opening a nested code fence**, which **closes the outer fence early**. Everything after that point (including `</illustrations>` and other closing tags) can appear outside the code block or look “swallowed.” `extract_fenced_xml_content` now walks inner fences (` ```lang ` … closing `` ``` ``) before accepting the outer `` ``` `` that ends the `xml` block.
106
104
  - **Outcome digest:** Follow the sample formatting rules in SKILL.md section 7 inside `## Outcome digest` so a second outer ` ```xml ` block never appears—multiple `xml` fences concatenate in `extract_fenced_xml_content` and would corrupt clipboard copy.
107
105
  - **Primary mitigation:** When the fenced XML artifact **contains any tag whose local name is on the HTML-collision list**, or when the artifact is **large enough that render truncation is likely**, the orchestrator **must write the full artifact to a file** (default: under `data/prompts/` or a path the user supplied earlier) and **paste the absolute file path** in the chat message. Pair the path with a **short section inventory** confirming all five required sections (`role`, `background`, `instructions`, `constraints`, `output_format`) are present in the file.
108
106
  - **Authoring rules for code inside `<illustrations>`:** Follow the sample formatting rules in SKILL.md section 7. Hooks and clipboard treat complete triple-backtick pairs as one unit inside the outer `` ```xml `` fence.
109
107
  - **Fallback when file write is unavailable:** Escape the **opening angle bracket** of colliding tags (for example `&lt;section>` — user restores `<` when pasting) or use another distinctive wrapper **documented in the same message**, so the user can recover literal XML. State explicitly that the user should restore brackets when copying into another system.
110
- - **Structural safety net:** Regardless of renderer behavior, the **Stop hook section-presence gate** blocks any prompt-workflow response whose fenced XML is missing any required opening/closing section tag pair. Methodology: [Anthropic Agent Skills: evaluation and iteration](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices#evaluation-and-iteration).
108
+ - **Structural safety net:** The **file-based validation loop** corrects missing section tag pairs before user output. The validator CLI enforces section presence, scope anchors, checklist rows, context-control signals, and positive phrasing.
111
109
 
112
110
  ## XML artifact (minimum sections)
113
111
 
@@ -121,6 +119,15 @@ Include at least:
121
119
 
122
120
  Add `<illustrations>` when format or tone is easy to misunderstand; nest sections when the task has natural hierarchy. **Long code samples belong in `<illustrations>`** — follow the sample formatting rules in SKILL.md section 7.
123
121
 
122
+
123
+ ## File-based validation loop (primary enforcement)
124
+
125
+ The subagent writes the complete artifact (fenced XML + Outcome digest + hook validation block) to `data/prompts/.draft-prompt.xml`, runs the validator, and fixes violations (exit 2) until exit 0. The orchestrator then strips the hook validation block and outputs fence + digest.
126
+
127
+ python packages/claude-dev-env/hooks/blocking/prompt_workflow_validate.py data/prompts/.draft-prompt.xml
128
+
129
+ The same checks are available as a Python function via `from prompt_workflow_validate import validate_prompt_workflow` for integration in tests and tooling.
130
+
124
131
  ## Internal 15-row compliance checklist (audit numerator)
125
132
 
126
- The `15` in `Audit: pass 15/15` maps to the named rows in `SKILL.md` (§11 **Compliance audit — 15-row checklist**), including `reversible_action_and_safety_check_guidance` and `scope_terms_explicit_and_anchored`. **Default user path:** keep the table internal; print the expanded table + JSON only after an explicit debug request. On failure, set the audit line to `Audit: fail N/15 — [primary theme]` where the theme names one concrete gap (e.g. `scope_block missing completion_boundary`, `output_format lacks acceptance checks`).
133
+ The 15-row compliance audit maps to the named rows in `SKILL.md` §11. **Default user path:** keep the table internal; print the expanded table + JSON only after an explicit debug request.
@@ -89,8 +89,8 @@ For EACH hook entry in settings.json (both layers):
89
89
  - hook_script_path (extract from the command string after the last quote)
90
90
  - Read the actual script file
91
91
  - purpose (what rule does this hook enforce?)
92
- - enforcement_type: "blocking" (exit 2 / permissionDecision deny) | "advisory" (stdout message) | "validation" (post-check)
93
- - method: "exit_code_2" (deprecated) | "permissionDecision" (current) | "stdout" | "other"
92
+ - enforcement_type: "blocking" (exit 2 stderr, or PreToolUse exit 0 + JSON deny) | "advisory" (stdout message) | "validation" (post-check)
93
+ - method: "exit_code_2_stderr" | "pretooluse_json_stdout" (hookSpecificOutput.permissionDecision; see https://code.claude.com/docs/en/hooks) | "stdout" | "other"
94
94
  - which_rule_file (which .Codex/rules/*.md or AGENTS.md rule does this correspond to?)
95
95
  - orphaned (hook exists on disk but NOT in settings.json?)
96
96
  ```
@@ -1,217 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Stop hook gate for prompt-workflow leakage and deterministic audit coverage.
3
-
4
- When every workflow gate passes, the fenced ``xml`` artifact body is copied to the
5
- system clipboard via :mod:`prompt_workflow_clipboard` (tkinter, then pyperclip).
6
- Set ``PROMPT_WORKFLOW_SKIP_CLIPBOARD=1`` to disable (tests, CI, headless).
7
- """
8
-
9
- from __future__ import annotations
10
-
11
- import datetime
12
- import json
13
- import sys
14
- from collections.abc import Callable
15
- from pathlib import Path
16
-
17
- from prompt_workflow_clipboard import copy_text_to_system_clipboard
18
- from prompt_workflow_gate_core import (
19
- extract_fenced_xml_content,
20
- find_ambiguous_scope_terms,
21
- find_negative_keywords_in_fenced_xml,
22
- has_debug_intent,
23
- has_checklist_container,
24
- has_internal_object_leak,
25
- is_prompt_workflow_response,
26
- missing_context_control_signals,
27
- missing_checklist_rows,
28
- missing_required_xml_sections,
29
- missing_scope_anchors,
30
- )
31
-
32
- PROMPT_GATE_LOG_PATH: Path = Path.home() / ".claude" / "logs" / "prompt-gate.log"
33
- USER_FACING_PREFIX: str = "[prompt-gate]"
34
-
35
- def _extract_user_context(hook_input: dict) -> str:
36
- candidates = (
37
- "last_user_message",
38
- "user_message",
39
- "user_prompt",
40
- "prompt",
41
- "input",
42
- )
43
- for key in candidates:
44
- value = hook_input.get(key)
45
- if isinstance(value, str) and value.strip():
46
- return value
47
- return ""
48
-
49
- def _append_diagnostic_to_log(brief_label: str, full_reason: str) -> None:
50
- try:
51
- PROMPT_GATE_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
52
- timestamp_iso = datetime.datetime.now().isoformat()
53
- log_entry = f"{timestamp_iso}\t{brief_label}\t{full_reason}\n"
54
- with PROMPT_GATE_LOG_PATH.open("a", encoding="utf-8") as log_handle:
55
- log_handle.write(log_entry)
56
- except OSError:
57
- pass
58
-
59
- def _build_block(brief_label: str, full_reason: str) -> dict:
60
- _append_diagnostic_to_log(brief_label, full_reason)
61
- return {
62
- "decision": "block",
63
- "reason": full_reason,
64
- "systemMessage": f"{USER_FACING_PREFIX} {brief_label}",
65
- "suppressOutput": True,
66
- }
67
-
68
- def _check_internal_object_leak(
69
- assistant_message: str,
70
- debug_requested: bool,
71
- ) -> dict | None:
72
- if not has_internal_object_leak(assistant_message) or debug_requested:
73
- return None
74
- return _build_block(
75
- brief_label="retrying: sanitize audit format",
76
- full_reason=(
77
- "PROMPT-WORKFLOW GATE: Raw internal refinement object leakage detected. "
78
- "Return sanitized user-facing output unless explicit debug intent is present."
79
- ),
80
- )
81
-
82
- def _check_checklist_container(assistant_message: str) -> dict | None:
83
- if has_checklist_container(assistant_message):
84
- return None
85
- return _build_block(
86
- brief_label="retrying: add checklist",
87
- full_reason=(
88
- "PROMPT-WORKFLOW GATE: Deterministic checklist container missing. "
89
- "Include `checklist_results` with all required rows."
90
- ),
91
- )
92
-
93
- def _check_missing_checklist_rows(assistant_message: str) -> dict | None:
94
- if not has_checklist_container(assistant_message):
95
- return None
96
- missing_rows = missing_checklist_rows(assistant_message)
97
- if not missing_rows:
98
- return None
99
- return _build_block(
100
- brief_label="retrying: complete checklist",
101
- full_reason=(
102
- "PROMPT-WORKFLOW GATE: Deterministic checklist rows missing: "
103
- + ", ".join(missing_rows)
104
- ),
105
- )
106
-
107
- def _check_missing_scope_anchors(assistant_message: str) -> dict | None:
108
- missing_anchors = missing_scope_anchors(assistant_message)
109
- if not missing_anchors:
110
- return None
111
- return _build_block(
112
- brief_label="retrying: add scope anchors",
113
- full_reason=(
114
- "PROMPT-WORKFLOW GATE: Required scope anchors missing: "
115
- + ", ".join(missing_anchors)
116
- ),
117
- )
118
-
119
- def _check_missing_context_signals(assistant_message: str) -> dict | None:
120
- missing_signals = missing_context_control_signals(assistant_message)
121
- if not missing_signals:
122
- return None
123
- return _build_block(
124
- brief_label="retrying: add runtime signals",
125
- full_reason=(
126
- "PROMPT-WORKFLOW GATE: Runtime context-control preamble missing. "
127
- "Include the two required lines from prompt-workflow-context-controls "
128
- "(minimal instruction layer and on-demand skill loading)."
129
- ),
130
- )
131
-
132
- def _check_ambiguous_scope(assistant_message: str) -> dict | None:
133
- ambiguous_terms = find_ambiguous_scope_terms(assistant_message)
134
- if not ambiguous_terms:
135
- return None
136
- return _build_block(
137
- brief_label="retrying: rephrase scope refs",
138
- full_reason=(
139
- "PROMPT-WORKFLOW GATE: Ambiguous scope phrasing detected: "
140
- + ", ".join(ambiguous_terms)
141
- ),
142
- )
143
-
144
- def _check_negative_keywords_in_artifact(assistant_message: str) -> dict | None:
145
- violations = find_negative_keywords_in_fenced_xml(assistant_message)
146
- if not violations:
147
- return None
148
- violation_descriptions = [
149
- f" line {each_violation['line_number']}: \"{each_violation['keyword']}\" in: {each_violation['line_text']}"
150
- for each_violation in violations
151
- ]
152
- return _build_block(
153
- brief_label="retrying: rephrase negative keywords in artifact",
154
- full_reason=(
155
- "PROMPT-WORKFLOW GATE: Banned negative keywords found inside fenced XML artifact. "
156
- "Rephrase as positive directives (what TO do, not what to avoid):\n"
157
- + "\n".join(violation_descriptions)
158
- ),
159
- )
160
-
161
- def _check_required_xml_sections(assistant_message: str) -> dict | None:
162
- missing_sections = missing_required_xml_sections(assistant_message)
163
- if not missing_sections:
164
- return None
165
- return _build_block(
166
- brief_label="retrying: include all required XML sections",
167
- full_reason=(
168
- "PROMPT-WORKFLOW GATE: Fenced XML artifact missing required sections: "
169
- + ", ".join(missing_sections)
170
- ),
171
- )
172
-
173
- def _evaluate_workflow_gates(assistant_message: str) -> dict | None:
174
- if not is_prompt_workflow_response(assistant_message):
175
- return None
176
- workflow_gate_checks: tuple[Callable[[str], dict | None], ...] = (
177
- _check_required_xml_sections,
178
- _check_missing_checklist_rows,
179
- _check_missing_scope_anchors,
180
- _check_missing_context_signals,
181
- _check_ambiguous_scope,
182
- _check_negative_keywords_in_artifact,
183
- )
184
- for check in workflow_gate_checks:
185
- block = check(assistant_message)
186
- if block is not None:
187
- return block
188
- return None
189
-
190
- def main() -> None:
191
- try:
192
- hook_input = json.load(sys.stdin)
193
- except json.JSONDecodeError:
194
- sys.exit(0)
195
-
196
- assistant_message = str(hook_input.get("last_assistant_message", ""))
197
- if not assistant_message.strip():
198
- sys.exit(0)
199
-
200
- user_context = _extract_user_context(hook_input)
201
- debug_requested = has_debug_intent(user_context)
202
-
203
- block = _check_internal_object_leak(assistant_message, debug_requested)
204
- if block is None:
205
- block = _evaluate_workflow_gates(assistant_message)
206
-
207
- if block is not None:
208
- sys.stdout.write(json.dumps(block) + "\n")
209
- elif is_prompt_workflow_response(assistant_message):
210
- artifact_text = extract_fenced_xml_content(assistant_message).strip()
211
- if artifact_text:
212
- copy_text_to_system_clipboard(artifact_text)
213
-
214
- sys.exit(0)
215
-
216
- if __name__ == "__main__":
217
- main()