1---
2name: prompt-enhance
3description: '[Skill Management] Use when enhancing, compressing, or expanding prompts, docs, or skills with attention anchoring [INTELLIGENT ROUTING]. Flag: --op={compress|expand|enhance} (default enhance); --op=compress strips token bloat, --op=expand reconstructs compressed text.'
4metadata:
5 source: https://skillmd.com/skills/duc01226/prompt-enhance
6---
7
8> Codex compatibility note:
9>
10> - Invoke repository skills with `$skill-name` in Codex; this mirrored copy rewrites legacy Claude `/skill-name` references.
11> - Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.
12> - User-question prompts mean to ask the user directly in Codex.
13> - Ignore Claude-specific mode-switch instructions when they appear.
14> - Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.
15> - Subagent authorization: when a skill is user-invoked or AI-detected and its protocol requires subagents, that skill activation authorizes use of the required `spawn_agent` subagent(s) for that task.
16> - Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.
17> - For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.
18> - If a required step/tool cannot run in this environment, stop and ask the user before adapting.
19
20<!-- CODEX:PROJECT-REFERENCE-LOADING:START -->
21
22## Codex Project-Reference Loading (No Hooks)
23
24Codex uses static project-reference loading instead of runtime-injected project docs.
25When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.
26
27**Always read:**
28
29- `docs/project-config.json` (project-specific paths, commands, modules, and workflow/test settings)
30- `docs/project-reference/docs-index-reference.md` (routes to the full `docs/project-reference/*` catalog)
31- `docs/project-reference/lessons.md` (always-on guardrails and anti-patterns)
32
33**Missing/stale context route:** If `docs/project-config.json`, the docs index, `lessons.md`, `CLAUDE.md`, `AGENTS.md`, or any task-required reference doc is missing or stale, auto-run `$project-init` or the narrow setup route (`$project-config`, `$docs-init`, `$scan-all`, `$scan --target=<key>`, `$claude-md-init`) before ordinary project-specific work. If Codex mirrors or `AGENTS.md` are missing/stale, ask the user to run `$sync-codex`; do not auto-run it.
34
35**Situation-based docs:**
36
37- Project structure/architecture/tech-stack/deployment/setup (any layer — backend, frontend, or infra): `project-structure-reference.md`
38- Backend/CQRS/API/domain/entity changes: `backend-patterns-reference.md`, `domain-entities-reference.md`
39- Frontend/UI/styling/design-system: `frontend-patterns-reference.md`, `scss-styling-guide.md`, `design-system/README.md`
40- Spec authoring, `docs/specs/` pathing, or TC format: `feature-spec-reference.md`, `spec-system-reference.md`, `spec-principles.md`
41- Behavior/public-contract changes or spec-test-code sync: `workflow-spec-test-code-cycle-reference.md` plus the spec docs above
42- Derived spec indexes/ERDs/reimplementation guides: `spec-system-reference.md` and source Feature Specs under `docs/specs/`
43- Integration test implementation/review: `integration-test-reference.md`
44- E2E test implementation/review: `e2e-test-reference.md`
45- Code review/audit work: `code-review-rules.md` plus domain docs above based on changed files
46
47Do not read all docs blindly. Start from `docs-index-reference.md`, then open only relevant files for the task.
48
49<!-- CODEX:PROJECT-REFERENCE-LOADING:END -->
50
51## Quick Summary
52
53**Goal:** Two-phase optimization — (1) Caveman Compression strips stop words + grammatical scaffolding while preserving semantic meaning; (2) Prompt Enhancement applies AI attention anchoring so AI reads and follows all instructions — producing a prompt/skill that states its objective and ultimate outcome (one consolidated Goal) in both top summary and bottom reminders so AI optimizes for the right result.
54
55**Summary:**
56
57- Two phases, in order: caveman-compress prose FIRST, then attention-anchor structure — NEVER skip or reorder.
58- Enhance derives BOTH a **Goal** (the outcome to optimize for) AND a **Summary** (key things + steps to notice) for the target, and places both in its Quick Summary.
59- **Anti-forget rule (task/purpose targets):** when the target performs a task or has a purpose, the Summary AND Closing Reminders MUST carry the goal + purpose + ALL important main steps/tasks (compact enumeration) — why: AI forgets steps buried in the long middle of the prompt; the top Summary and bottom Reminders are the two high-attention anchors that survive context rot.
60- Protect content: NEVER compress code/YAML/tables/SYNC tags, NEVER delete rules or `file:line` evidence; post rule-density MUST be ≥ pre.
61- Route on `--op` (default `enhance`): `compress` = token-strip only, `expand` = reconstruct compressed text.
62
63**Workflow:**
64
651. **Detect** — Classify target: skill file, sub-agent file (`.claude/agents/*.md`), protocol file, or general doc
662. **Read** — Read target file completely
673. **Goal + Summary** — Derive the target's one-sentence Goal (what it achieves + the ultimate outcome it must cause) AND its Summary (2-4 bullets of the key important things + the steps AI must notice) from the target's task, constraints, and success criteria
684. **Compress** — Apply caveman compression (Phase 1)
695. **Enhance** — Apply AI attention anchoring transforms (Phase 2)
706. **Verify** — No content loss, rule density ≥ pre-optimization, Goal anchored top and bottom
71
72**Key Rules:**
73
74- **Operation flag** (see [Operation Mode](#operation-mode---op)): `--op=enhance` (default) = compress + anchor + skill-principles; `--op=compress` = token-strip only; `--op=expand` = reconstruct compressed text into fluent form (inverse Phase 1 + structural Transform 4)
75- NEVER skip Phase 1 (compress) before Phase 2 (enhance) — compression removes noise, enhancement structures signal
76- NEVER remove meaningful rules, constraints, code examples, or `file:line` evidence
77- MUST ATTENTION derive the target's Goal and add it to both `## Quick Summary` and `## Closing Reminders`
78- MUST ATTENTION derive the target's Summary (key important things + steps AI must notice) and place it in `## Quick Summary` immediately after the Goal — a condensing digest at a different altitude than Workflow/Key Rules, NEVER a verbatim re-listing of them
79- MUST ATTENTION when the target performs a task or has a purpose, the Summary AND `## Closing Reminders` MUST enumerate the goal + purpose + ALL important main steps/tasks as a compact list — why: long task descriptions in the middle of the prompt get forgotten; the top Summary and bottom Reminders re-anchor every step so none is skipped (compact enumeration ≠ the verbose Workflow prose, so the altitude stays distinct)
80- MUST ATTENTION skill AND sub-agent (`.claude/agents/*.md`) targets require the SAME Goal + Summary + Closing-Reminders structure (see [When Target is a Sub-Agent File](#when-target-is-a-sub-agent-file)) — anchored top and bottom; NEVER alter SYNC blocks when enhancing an agent
81- Post-optimization rule density (MUST ATTENTION/NEVER/ALWAYS per 100 lines) MUST be ≥ pre-optimization
82- Caveman compression applies to prose only — NEVER compress code blocks, YAML, or structured tables
83- Prompt quality > token count, but verbose prompts degrade quality — optimize clarity-per-token
84
85---
86
87## Target File
88
89Compress and enhance this file:
90<target>$ARGUMENTS</target>
91
92No file? Ask by asking the user directly. Text passed (not file path)? Apply caveman compression directly and output result.
93
94---
95
96## Operation Mode (`--op=`)
97
98Route on `--op` (default `enhance`). Transforms 1-3 (inline summaries, top summary, closing reminders — the shared SYNC base block below) are identical across all ops; only Phase 1 and Transform 4 differ:
99
100| `--op` | Phase 1 | Transform 4 | Skill-principles + Goal | Former skill |
101| --------------------- | ----------------------------------------------- | ---------------------- | -------------------------- | ------------------ |
102| `enhance` _(default)_ | Caveman Compression | Conciseness pass | Applied (skill files) | host |
103| `compress` | Caveman Compression | Conciseness pass | Skipped (pure token strip) | `/prompt-compress` |
104| `expand` | **Language Expansion** (inverse — branch below) | **Structural Clarity** | Skipped | `/prompt-expand` |
105
106- `enhance` / `compress` → run **Phase 1: Caveman Compression** + **Transform 4: Conciseness** below. `enhance` additionally derives the Goal and (for skill files) applies the Universal Skill-Building Principles; `compress` skips both for a pure token-reduction pass.
107- `expand` → run the **Language Expansion branch** below INSTEAD of Caveman Compression, and the **Structural Clarity** Transform 4 instead of conciseness.
108- No `--op` provided → `enhance`.
109
110### `--op=expand` — Language Expansion branch
111
112Reconstruct fluent, grammatically correct English from caveman-compressed text while preserving ALL semantic content (inverse of Phase 1). Run INSTEAD of Caveman Compression.
113
114**Restore** (add back): articles (`a/an/the`); connectives matching the logical relationship (`because/however/in order to`); auxiliary verbs (`is/are/was/has`); clarifying prepositions; pronouns referencing prior nouns; subordinate clauses merging choppy sentences.
115**Preserve exactly** (never paraphrase/omit): all nouns + main verbs + adjectives, numbers/quantifiers, uncertainty qualifiers, negations (`not/no/never/without`), technical/domain terms, `file:line` paths, names/titles, time/frequency words.
116
117**Connective selection** (match relationship, never arbitrary): cause→effect `because/since/as a result`; contrast `however/although/despite`; addition `additionally/furthermore`; sequence `first/then/finally`; purpose `in order to/so that`; condition `if/when/unless`; clarification `specifically/that is`.
118
119Per sentence: identify core S-V-O (non-negotiable) → restore articles/auxiliaries/connectives/prepositions → merge related shorts → target 10-25 words. Skip code blocks, YAML, tables, SYNC tags, paths.
120
121**Transform 4 (expand) — Structural Clarity pass:** convert prose rule-lists → bullets, enumerated conditions → decision tables, before/after examples → two-column tables. Keep as prose: explanatory context (why a rule exists), workflow narratives, anti-pattern rationale.
122
123Verify (expand): no semantic loss (all facts/numbers/paths present), rule density post ≥ pre, no telegraphic 2-5 word prose sentences remain, code blocks untouched.
124
125---
126
127## Phase 0: Detect Target Type
128
129**Before any other step**, classify target:
130
131| Target type | Detection | Action |
132| ------------------ | ---------------------------------------- | ------------------------------------------------------- |
133| Skill file | Path matches `.claude/skills/**/*.md` | Apply Universal Skill-Building Principles after Phase 1 |
134| Sub-agent file | Path matches `.claude/agents/*.md` | Apply Sub-Agent Required Structure after Phase 1 |
135| Protocol file | Path matches `.claude/protocols/**/*.md` | Standard 2-phase optimization only |
136| General doc/prompt | Any other `.md` file | Standard 2-phase optimization only |
137| Raw text | No file path provided | Apply caveman compression only, output result |
138
139---
140
141## When Target is a Skill File
142
143Target `.claude/skills/**/*.md` (any `SKILL.md`)? Apply **Universal Skill-Building Principles** AFTER caveman compression, BEFORE writing enhanced output.
144
145### Skill Enhancement Checklist
146
147After caveman compression, evaluate skill against each principle, add missing structure:
148
149| Principle | Check | Action if missing |
150| ---------------------------- | ---------------------------------------- | ------------------------------------------------------ |
151| Detect Before Act | Phase 0 / classification step present? | Add artifact-type detection before Phase 1 |
152| Derive, Don't Enumerate | Thinking framework vs. fixed checklist? | Replace checklist with "understand → derive → execute" |
153| Evidence Gates | Every claim requires `file:line`? | Add evidence requirement to all review steps |
154| Fresh Eyes Protocol | Multi-round sub-agent review defined? | Add Round 2 fresh sub-agent protocol |
155| Specialize by Type | Sub-agent routing table present? | Add `security-auditor`/`performance-optimizer` options |
156| Embed Protocols Verbatim | Protocols inline in sub-agent prompts? | Move protocol bodies inline, remove file references |
157| Search-Based Discovery | Any hardcoded paths/formats/IDs? | Replace with search instructions |
158| Dimensions > Checklists | Named dimensions with `Think:` prompts? | Convert checklist to dimension framework |
159| Recursive Quality Loop | Fix → re-review → max 3 rounds defined? | Add recursive review loop |
160| Anti-Rationalization Anchors | Closing reminders include evasion table? | Add evasion → rebuttal table |
161
162### Anti-Forget Anchoring (task/purpose targets)
163
164Any target that **performs a task or has a purpose** (skill, sub-agent, task-prompt) hides its main steps in the long middle — exactly the zone AI attention drops 15-47% (Stanford "lost-in-the-middle"). The fix is to mirror those steps into the two high-attention anchors:
165
166| Anchor | Must carry |
167| ----------------------------------- | ------------------------------------------------------------------------------------------------------------ |
168| `## Quick Summary` → `**Summary:**` | Goal + purpose + **ALL important main steps/tasks** as a compact ordered enumeration (one short phrase each) |
169| `## Closing Reminders` | Goal echo + a `MUST ATTENTION` line re-listing the same main steps/tasks in order |
170
171- MUST ATTENTION enumerate EVERY important main step/task — completeness beats brevity here; a step omitted from both anchors is a step AI will skip — why: the Summary and Reminders are the only parts guaranteed to be read on a long prompt.
172- The compact enumeration is a DIFFERENT altitude than the verbose `## Workflow`/body — short phrases, not full prose — so it complements (never replaces) the detailed steps below.
173- Surface conditional routing too (modes, `--flags`, gates) so the AI doesn't forget a whole branch — why: a forgotten mode silently runs the wrong path.
174
175---
176
177## When Target is a Sub-Agent File
178
179Target `.claude/agents/*.md` (a custom sub-agent definition — the shape a creator skill like `custom-agent` emits)? Apply the **Sub-Agent Required Structure** AFTER caveman compression, BEFORE writing enhanced output. Same Goal + Summary + Closing-Reminders contract as a skill file — anchored top and bottom so the isolated, zero-history sub-agent optimizes for the right outcome — mapped onto the agent body (`## Role → ## Workflow → ## Key Rules → ## Output`).
180
181### Sub-Agent Required Structure
182
183| Block | Location | Requirement |
184| ---------------------------------- | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
185| `## Quick Summary` | first section after frontmatter | Present — holds Goal + Summary + Workflow + Key Rules |
186| `**Goal:**` | inside Quick Summary | One consolidated sentence — what the agent achieves AND the ultimate outcome it must cause |
187| `**Summary:**` | inside Quick Summary, immediately after Goal | 2-4 bullets — the read-this-if-nothing-else digest (key things + steps to notice); distinct altitude from Workflow/Key Rules, NEVER a verbatim re-listing |
188| `**Workflow:**` / `**Key Rules:**` | inside Quick Summary | Keep existing |
189| `## Closing Reminders` | end of file, after the `:reminder` SYNC blocks | Present — first line `**IMPORTANT MUST ATTENTION Goal:**` echoes the same Goal |
190
191- MUST ATTENTION add the missing `**Summary:**` and the Closing-Reminders Goal echo; lightly tighten Role/Workflow prose only — why: the structure must match a skill so creator skills emit one consistent shape.
192- NEVER alter `<!-- SYNC:... -->` blocks or their `:reminder` variants — they are canonical-sync content; edit the canonical source (`.claude/skills/shared/sync-inline-versions.md`) instead — why: a divergent SYNC copy fails the `verify-sync-divergence` oracle.
193- NEVER delete the agent body sections (`## Role`, `## Workflow`, `## Key Rules`, `## Output`) — preserve them; only restructure the summary/closing anchors.
194
195---
196
197## Phase 1: Caveman Compression
198
199> Applies to `--op=compress|enhance`. For `--op=expand`, run the Language Expansion branch (above) instead.
200
201Aggressively remove stop words + grammatical scaffolding preserving meaning. Use only content words carrying semantic weight.
202
203### What to Remove
204
205| Category | Examples |
206| ----------------------------- | ---------------------------------------------------------------------- |
207| Articles | a, an, the |
208| Auxiliary verbs | is, are, was, were, am, be, been, being, have, has, had, do, does, did |
209| Redundant prepositions | of, for, to, in, on, at (when meaning stays clear without them) |
210| Pronouns (when context clear) | it, this, that, these, those |
211| Pure intensifiers | very, quite, rather, somewhat, really, extremely |
212
213### What to Keep (Always)
214
215| Category | Reason |
216| -------------------------------- | ------------------------------------------------------ |
217| All nouns | Core semantic units |
218| All main verbs (not auxiliaries) | Actions carry meaning |
219| All meaningful adjectives | Add semantic signal |
220| Numbers and quantifiers | `at least`, `approximately`, `more than`, `15`, `many` |
221| Uncertainty qualifiers | `appears to be`, `seems`, `might`, `what sounded like` |
222| Critical prepositions | `from`, `with`, `without`, `stuck to` — change meaning |
223| Time/frequency words | `every Tuesday`, `weekly`, `always`, `never` |
224| Names and titles | `Dr.`, `Mr.`, `Senator` |
225| Technical/domain terms | Never simplify domain language |
226| Negations | `not`, `no`, `never`, `without` |
227
228### Preposition Decision Rule
229
230- Keep when defining relationship: `made from wood` (keep `from`), `stuck to wall` (keep `to`)
231- Remove when purely grammatical: `system for processing data` → `system processing data`
232- Keep `in/on/at` for location/position: `file in /src` (keep) vs `written in prose` (remove)
233
234### Compression Examples
235
236| Original | Compressed | Removed |
237| --------------------------------------------------------------------------- | --------------------------------------------------------------- | --------------------- |
238| "The system was designed to process data efficiently" | "System designed process data efficiently." | The, was, to |
239| "It removes predictable grammar while preserving the unpredictable content" | "Removes predictable grammar preserving unpredictable content." | It, the, while |
240| "There were at least 20 people" | "At least 20 people." | There, were |
241| "Made from wood and metal" | "Made from wood and metal." | nothing — `from` kept |
242| "This is a method for compressing LLM contexts" | "Method compressing LLM contexts." | This, is, a, for |
243
244### Compression Scope
245
246Apply to:
247
248- Prose paragraphs and explanatory text
249- Bullet point descriptions
250- Rule statements (keep imperative verbs)
251- Section intros and transitions
252
253Do NOT compress:
254
255- Code blocks (any language)
256- YAML frontmatter
257- Structured tables (column values may be fragmented — keep as-is)
258- `file:line` references and paths
259- `<!-- SYNC -->` tags and their content
260- Frontmatter fields
261
262---
263
264## Phase 2: Prompt Enhancement
265
266### Transform 4: Token Optimization (Conciseness Pass)
267
268> Applies to `--op=compress|enhance`. For `--op=expand`, use the Structural Clarity pass (see expand branch above).
269
270Prompt quality FIRST. Verbose prompts degrade quality — AI attention dilutes across unnecessary tokens. Optimize **clarity-per-token**: maximum signal, minimum noise.
271
272**What to cut:**
273
274- **Filler phrases** — "It is important to note that", "Please make sure to", "You should always" → just state the rule
275- **Redundant explanations** — heading says it, body doesn't re-explain. Tables > paragraphs for structured data
276- **Duplicate content** — merge sections saying same thing differently (except intentional top/bottom anchoring)
277- **Overly verbose examples** — trim to minimum lines demonstrating pattern. Replace paragraph explanations with `// comment` in code
278- **Prose paragraphs for rules** — convert to bullet lists or tables (AI parses structured formats faster)
279
280**What to KEEP:**
281
282- Code examples with actual file paths/patterns (AI copies these directly)
283- Decision tables and lookup references
284- Anti-pattern examples (before/after pairs)
285- All `file:line` evidence and concrete paths
286- Top/bottom anchoring (intentional duplication)
287
288**Evaluation metrics per doc:**
289
290- **Density score** — useful rules per 100 lines (higher = better)
291- **Savings estimate** — % tokens saveable without losing information
292- **Risk** — what breaks if cut too aggressively (e.g., AI misses a pattern)
293
294---
295
296## Process
297
298### Step 0: Detect and Classify
299
3001. Identify target type (skill file / protocol / general doc / raw text)
3012. Skill file (`.claude/skills/**/*.md`) → apply Universal Skill-Building Principles after Phase 1
302
303### Step 1: Read and Analyze
304
3051. Read target file completely
3062. Record: current line count, rule density (MUST ATTENTION/NEVER/ALWAYS count)
3073. List all READ references → classify as `.claude/` (needs inline summary) or `docs/` (skip)
3084. Derive the one-sentence **Goal** (what it achieves + ultimate outcome it must cause) from target task/outcomes/guardrails; cite source lines or mark inferred with confidence
3095. Derive the **Summary** (2-4 bullets of the key important things + the steps AI must notice) — the read-this-if-nothing-else digest at a different altitude than Workflow/Key Rules; cite source lines or mark inferred with confidence — why: the Summary condenses what matters most, it does not re-list every step/rule
310 - If the target performs a task or has a purpose, the Summary MUST also enumerate ALL important main steps/tasks (compact ordered list) + any modes/flags/gates — why: steps buried in the long middle get forgotten; the Summary anchor re-surfaces every one
3116. Identify: missing Quick Summary, missing Goal, missing Summary, missing main-step enumeration (task targets), missing Closing Reminders, prose-heavy sections
312
313### Step 2: Caveman Compression Pass
314
3151. Identify all prose paragraphs and bullet descriptions
3162. Apply Phase 1 compression rules — remove stop words, keep semantic content
3173. Skip code blocks, YAML, tables, SYNC tags, file paths
3184. Verify meaning preserved after each paragraph
319
320### Step 3: Create Inline Summaries
321
322For each `.claude/` protocol reference:
323
3241. Read the referenced file
3252. Extract 2-3 key rules
3263. Write blockquote inline summary
3274. Keep MUST ATTENTION READ instruction on next line
328
329### Step 4: Add/Fix Top Section
330
331- Missing Quick Summary → create from file content
332- Present but weak → strengthen with Goal, Workflow, Key Rules
333- Ensure `**Goal:**` states what the skill achieves AND the ultimate outcome it must cause — a single consolidated line (never split the objective and outcome into two separate lines)
334- Ensure `**Summary:**` is present in Quick Summary immediately after the Goal — create if missing, strengthen if weak; it condenses the key important things + the steps AI must notice at a different altitude than Workflow/Key Rules (NEVER a verbatim re-listing of them) — why: the Goal gives the outcome, the Summary gives the read-this-if-nothing-else digest
335- For task/purpose targets, ensure the Summary enumerates ALL important main steps/tasks (compact ordered list) + modes/flags/gates — why: completeness on steps is the anti-forget guarantee
336- Protocol summaries appear before Quick Summary
337
338### Step 5: Add/Fix Bottom Section
339
340- Missing Closing Reminders → add standard section
341- Pick rules AI most commonly skips (evidence-based, task creation, pattern search)
342- Echo the same Goal near the start of Closing Reminders: `**IMPORTANT MUST ATTENTION Goal:** ...`
343- For task/purpose targets, add a `MUST ATTENTION` line re-listing ALL important main steps/tasks in order — why: the bottom anchor re-surfaces every step after the long middle, matching the top Summary
344- Remove old "IMPORTANT Task Planning Notes" if superseded by Closing Reminders
345
346### Step 6: Verify
347
348| Check | Pass Condition |
349| ------------------- | ------------------------------------------------------------------------------------------- |
350| No YAML corruption | Frontmatter intact |
351| No content loss | All rules, code, paths present |
352| Rule density | Post ≥ pre (count MUST ATTENTION/NEVER/ALWAYS) |
353| Goal | Present in Quick Summary and Closing Reminders |
354| Summary | Present in Quick Summary (key things + steps digest) |
355| Main steps anchored | Task/purpose target → ALL main steps/tasks enumerated in BOTH Summary and Closing Reminders |
356| Line count | Reduced (compression worked) |
357| Formatting | Blank lines between sections, headers correct |
358| READ classification | `.claude/` → inline summary, `docs/` → skipped |
359
360---
361
362> **[IMPORTANT]** Use task tracking to break ALL work into small tasks BEFORE starting.
363
364<!-- SYNC:output-quality-principles -->
365
366> **Output Quality** — Token efficiency without sacrificing quality.
367>
368> 1. No inventories/counts — AI can `grep | wc -l`. Counts go stale instantly
369> 2. No directory trees — AI can `glob`/`ls`. Use 1-line path conventions
370> 3. No TOCs — AI reads linearly. TOC wastes tokens
371> 4. No examples that repeat what rules say — one example only if non-obvious
372> 5. Lead with answer, not reasoning. Skip filler words and preamble
373> 6. Sacrifice grammar for concision in reports
374> 7. Unresolved questions at end, if any
375
376<!-- /SYNC:output-quality-principles -->
377
378<!-- SYNC:universal-skill-building-principles -->
379
380> **Universal Skill-Building Principles** — 10 principles for building AI skills that work across any project type. Source: extracted from changes-review, plan-review, code-review skill rewrites.
381>
382> **Meta-principle: Teach AI to reason, not to recite.** Skill's job: structure WHEN and HOW AI applies its existing knowledge — not enumerate every possible concern.
383>
384> 1. **Detect Before Act** — Every skill starts with a classification phase. Detect artifact type (plan type, code category, change nature) before applying any logic. Detection drives: sub-agent selection, which dimensions to emphasize, mandatory vs. optional checks.
385> Anti-pattern: same checklist applied regardless of input type.
386> 2. **Derive, Don't Enumerate** — Teach AI HOW to reason about a domain, not WHAT items to tick. Replace "check X, Y, Z" with "understand role → read conventions → derive concerns from first principles → execute with evidence." Fixed checklist = ceiling. Thinking framework = floor.
387> Test: Can this skill run on a Python/Go project without modification? If not → it's enumerating, not teaching.
388> 3. **Evidence Gates** — Every claim, finding, recommendation requires `file:line` proof or traced call chain. Confidence thresholds: >80% act freely, 60-80% verify first, <60% DO NOT recommend. "Insufficient evidence" is valid output. Speculation is forbidden output.
389> 4. **Fresh Eyes Protocol** — Round 1 in main session. Round 2+ with fresh sub-agent (zero memory of Round 1). Main agent reads report but NEVER filters or overrides findings. Max 3 rounds, then escalate to user. Never declare PASS after Round 1 alone.
390> Why: main agent rationalizes its own mistakes. Zero-memory sub-agent catches what main agent dismissed.
391> 5. **Specialize by Type** — Route to specialized sub-agents based on detected artifact type:
392>
393> | Artifact type | Sub-agent |
394> | ---------------------------- | ----------------------- |
395> | Source code / diffs | `code-reviewer` |
396> | Security-sensitive changes | `security-auditor` |
397> | Performance-critical changes | `performance-optimizer` |
398> | Plans / docs / specs | `general-purpose` |
399>
400> 6. **Embed Protocols Verbatim, Never Reference** — Shared protocols MUST be copied inline into every sub-agent prompt — never referenced by file path or tag name. AI compliance drops significantly behind file-read indirection. Maintain canonical source; embed body at every call site.
401> 7. **Search-Based Discovery** — Never hardcode project-specific paths, formats, or identifiers. Teach skill to discover them:
402> - "Search for `coding-standards`, `style-guide`, `contributing`" not "read `docs/X/code-review-rules.md`"
403> - "Find the project's test format near changed files" not "look for `TC-{FEATURE}-{NNN}` in `docs/specs/`"
404> This is what makes a skill work across any project without modification.
405> 8. **Dimensions > Checklists** — Structure review/analysis as named thinking dimensions, each with a `Think:` prompt that forces first-principles reasoning: (1) state dimension's role, (2) derive what could go wrong if weak, (3) apply to artifact with evidence. Produces targeted, evidence-backed findings — not generic "add more detail" suggestions.
406> **Serial attention:** When applying a dimension-based framework, NEVER scan all dimensions simultaneously. One focused pass per dimension. AI misses violations when attention is split across concurrent concerns. Pattern: identify applicable dimensions → sequential focused passes → aggregate.
407> **Threshold invariant:** 3+ similar patterns in any dimension pass = MANDATORY extraction. 2+ violations of same kind = structural/architectural finding, not individual instance.
408> 9. **Recursive Quality Loop** — Fix → Re-review → Fix → Re-review. Each round uses a NEW fresh sub-agent. Continue until PASS or 3 rounds max, then escalate. Never declare success after Round 1 alone. Never reuse a sub-agent across rounds.
409> 10. **Anti-Rationalization Anchors** — Explicitly name and embed the evasion patterns AI uses to skip steps in the skill's closing reminders:
410>
411> | Evasion | Rebuttal |
412> | --------------------- | ---------------------------------------------------------- |
413> | "Too simple for this" | Wrong assumptions waste more time. Apply anyway. |
414> | "Already searched" | Show `file:line` evidence. No proof = no search. |
415> | "Just do it" | Still need task tracking. Skip depth, never skip tracking. |
416
417<!-- /SYNC:universal-skill-building-principles -->
418
419<!-- SYNC:context-engineering-principles -->
420
421> **Context Engineering Principles** — Research-backed principles for prompt quality. Source: Anthropic prompt engineering guide, Stanford "lost-in-the-middle" research, 2025-2026 LLM context optimization studies.
422>
423> 1. **Primacy-Recency Effect** — LLM performance drops 15-47% for middle-context information (Stanford). AI attention peaks at first/last 10% of text. **Action:** Place the 3 most critical rules in both the first 5 lines AND the last 5 lines of every prompt. Queries at end improve quality by up to 30% (Anthropic).
424> 2. **High-Signal Density** — Anthropic: _"Identify the smallest collection of high-signal tokens that maximize the probability of the desired outcome."_ **Action:** Every line should change AI behavior. If removing a line doesn't change output → cut it. Target ≥8 rules (MUST ATTENTION/NEVER/ALWAYS) per 100 lines.
425> 3. **Context Rot** — LLM performance degrades as context length grows — even when all content is relevant. Compression (5-20x) maintains or improves accuracy while saving 70-94% tokens. **Action:** Compress aggressively. Shorter, denser prompts outperform longer, diluted ones.
426> 4. **Structured > Prose** — Tables, bullets, XML/markdown parse faster than paragraphs. Constrained formats reduce error rates vs free-text. **Action:** Convert narrative to tables/bullets. Use markdown headers for semantic sections.
427> 5. **RCCF Framework** — Modern LLMs (2025+) already know how to reason. What they need: **R**ole (personality), **C**ontext (grounding), **C**onstraints (guardrails), **F**ormat (structure). Constraints and format matter more than verbose instructions.
428> 6. **Checkbox Avoidance** — `[ ]` syntax triggers mechanical compliance — AI ticks boxes without reasoning. Bullet rules force reading and evaluation. **Action:** Replace `- [ ] Check X` with `- MUST ATTENTION verify X`.
429> 7. **Example Economy** — 3-5 examples optimal for few-shot; diminishing returns after. **Action:** 1 best example per pattern. Use BAD→GOOD pairs (2-3 lines each) for anti-patterns.
430> 8. **Deferred Tool Loading** — Claude Code delays loading tool definitions when they exceed 10% of context window. **Action:** Keep injected docs well under 10% of context budget. Docs exceeding ~3,000 lines are too large for injection — split or compress.
431> 9. **Rule Density Verification** — Post-optimization rule count (MUST ATTENTION/NEVER/ALWAYS) must be ≥ pre-optimization count. Compression should preserve or increase density, never decrease it. **Action:** Count before and after every optimization pass.
432> 10. **Affirmative Directives** — Models comply with affirmative directives more reliably than prohibitions; a bare "don't X" leaves the correct action unspecified, so the model substitutes an arbitrary alternative. **Action:** State the action to take, not only the action to avoid. Keep `NEVER`/forbidden guardrails for hard invariants — but pair each with the right path ("Do X" not just "Don't do Y").
433> 11. **Rationale-Carrying Instructions** — A rule shipped with its reason generalizes to edge cases the rule never enumerated and survives compression; a bare imperative gets misapplied or silently dropped. **Action:** Append a terse `— why: …` clause to every non-obvious rule. The reason names the failure prevented or outcome wanted — never restates the rule.
434
435<!-- /SYNC:context-engineering-principles -->
436
437<!-- SYNC:prompt-enhancement-transforms-base -->
438
439> **Prompt Enhancement Transforms (Base)** — Transforms 1-3 are identical across all `$prompt-enhance` ops (`--op=compress|expand|enhance`). Transform 4 is per-op (conciseness pass for compress/enhance; structural clarity pass for expand) and stays local to each op branch.
440>
441> ### Transform 1: Inline Summaries for READ References
442>
443> **Problem:** AI sees `MUST ATTENTION READ file.md` and skips it.
444> **Solution:** Add a 2-3 line summary of key rules BEFORE the read instruction.
445>
446> **Before:**
447>
448> ```
449> MUST ATTENTION READ .claude/protocols/evidence.md
450> ```
451>
452> **After:**
453>
454> ```
455> > **Evidence-Based Reasoning** — Speculation is FORBIDDEN. Every claim requires `file:line` proof.
456> > Confidence: >95% recommend freely, 80-94% with caveats, <80% DO NOT recommend.
457>
458> MUST ATTENTION READ .claude/protocols/evidence.md for full details.
459> ```
460>
461> **Scope rules:**
462>
463> - `.claude/` protocol files → always add an inline summary (stable, belongs to framework)
464> - `docs/project-reference/` files → NO inline summary (project-specific). Add: `(Claude may inject this via hooks; Codex must open this file directly using docs-index routing)`
465>
466> ### Transform 2: Top Summary Section
467>
468> Required structure (first 20 lines after frontmatter):
469>
470> ```markdown
471> > **[IMPORTANT]** task tracking instruction...
472>
473> > **Protocol Name** — [inline summary]. MUST ATTENTION READ `path` for details.
474>
475> ## Quick Summary
476>
477> **Goal:** [One sentence — what this skill achieves AND the ultimate outcome it must cause]
478>
479> **Summary:** [2-4 bullets/sentences — the key important things + the steps AI must notice; the read-this-if-nothing-else digest, distinct altitude from the enumerated Workflow/Key Rules below]
480>
481> **Workflow:**
482>
483> 1. **[Step]** — [description]
484>
485> **Key Rules:**
486>
487> - [Most critical constraint]
488> ```
489>
490> ### Transform 3: Bottom Closing Reminders
491>
492> Add at the very end of the file:
493>
494> ```markdown
495> ---
496>
497> ## Closing Reminders
498>
499> **IMPORTANT MUST ATTENTION Goal:** [same goal as Quick Summary]
500> **IMPORTANT MUST ATTENTION** [echo rule #1 from the top section]
501> **IMPORTANT MUST ATTENTION** [echo rule #2]
502> **IMPORTANT MUST ATTENTION** [echo rule #3]
503> **IMPORTANT MUST ATTENTION** add a final review task to verify work quality
504> ```
505>
506> Pick 3-5 rules AI most commonly violates. Bottom section re-anchors attention after the long middle.
507
508<!-- /SYNC:prompt-enhancement-transforms-base -->
509
510<!-- SYNC:shared-protocol-duplication-policy -->
511
512> **Shared Protocol Duplication Policy** — Inline protocol content in skills (wrapped in `<!-- SYNC:tag -->`) is INTENTIONAL duplication. Do NOT extract, deduplicate, or replace with file references. AI compliance drops significantly when protocols are behind file-read indirection. To update: edit `.claude/skills/shared/sync-inline-versions.md` first, then grep `SYNC:protocol-name` and update all occurrences.
513
514<!-- /SYNC:shared-protocol-duplication-policy -->
515
516<!-- SYNC:ai-mistake-prevention -->
517
518> **AI Mistake Prevention** — Failure modes to avoid on every task:
519>
520> **Re-read files after context changes.** Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
521> **Verify generated content against source evidence.** AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
522> **Check downstream references before deleting or renaming.** Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
523> **Trace the full impact chain after edits.** Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
524> **Verify ALL affected outputs, not just the first.** One green check is not all green checks; validate every output surface the change can affect.
525> **Assume existing values are intentional — ask WHY before changing OR flagging one as a defect.** Before changing or reporting a constant, limit, flag, cutoff, wording, or pattern, read nearby context and history, the CALLER's ordering, and 2+ sibling call sites of the same convention. A doc stating WHAT without WHY is missing rationale, not proof of a missing guard.
526> **Surface ambiguity before acting — don't pick silently.** Multiple valid interpretations require an explicit question or stated assumption with risk.
527> **Assert the outcome your system owns, not the intermediate state your infrastructure owns.** When verifying async work, assert the final business state — never the delivery/retry bookkeeping held in shared infrastructure that any co-running process can write. Such a check passes when run alone and flakes the moment anything else shares that infrastructure.
528> **Keep shared guidance role-relevant.** Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
529
530<!-- /SYNC:ai-mistake-prevention -->
531
532<!-- SYNC:critical-thinking-mindset -->
533
534> **Critical Thinking Mindset** — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
535> **Anti-hallucination:** Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination.
536
537<!-- /SYNC:critical-thinking-mindset -->
538
539<!-- SYNC:critical-thinking-mindset:reminder -->
540
541**MUST ATTENTION** apply critical + sequential thinking — every claim needs appropriate traced evidence (`file:line` for repo/code claims; source URL or artifact section for research, product, content, and docs claims); confidence >80% to act, <60% DO NOT recommend. Anti-hallucination: never present guess as fact, admit uncertainty freely, cross-reference independently, stay skeptical of own confidence.
542
543<!-- /SYNC:critical-thinking-mindset:reminder -->
544
545<!-- SYNC:ai-mistake-prevention:reminder -->
546
547**MUST ATTENTION** apply AI mistake prevention — verify generated content against evidence, trace downstream references before deleting or renaming, verify all affected outputs, re-read files after context loss, and surface ambiguity before acting.
548
549<!-- /SYNC:ai-mistake-prevention:reminder -->
550
551<!-- SYNC:project-protocol-overlay -->
552
553> **Project Protocol Overlay** — Before executing this skill, resolve any PROJECT overlay rules layered onto it: match this skill's name against the `Target` column of the project's skill-protocol index (`docs/project-reference/skill-protocols-reference.md` by default; a `referenceDocs` entry in `docs/project-config.json` overrides the path), taking the most specific matching tier ONLY — exact name > glob > `*`. **That precedence orders overlays against EACH OTHER, never against this skill.** Read ONLY the matched bodies, resolved as `<protocols-dir>/<Name>.md`; a row's Body link is display text, never a read path. A matched body that is missing or malformed is REPORTED and skipped — never reconstructed from the index Description. No index, or no match -> proceed with no overlay, silently. Full contract: `.claude/skills/project-skill-protocol/references/registry.md`.
554>
555> Overlays are **ADDITIVE ONLY**: they ADD rules on top of this skill's own protocol and NEVER replace, override, disable, or reinterpret a rule it already states — removing every overlay must return this skill to exactly its documented behavior. An overlay is a BRIEF, not an authority escalation: it can NEVER waive a workflow gate, git discipline, a review gate, or a user-confirmation gate. A genuine overlay-vs-skill conflict, or two equally-specific overlays that directly contradict -> surface both to the user; NEVER resolve silently.
556
557<!-- /SYNC:project-protocol-overlay -->
558
559<!-- SYNC:project-protocol-overlay:reminder -->
560
561**MUST ATTENTION** resolve project protocol overlays for this skill BEFORE executing — most specific matching tier only (exact > glob > `*`, which ranks overlays against each other, NEVER against this skill), read only matched bodies at `<protocols-dir>/<Name>.md`; a missing or malformed body is reported, never reconstructed. Overlays are ADDITIVE ONLY (they never replace this skill's own rules) and are a brief, NEVER an authority escalation; an equal-specificity contradiction goes to the user.
562
563<!-- /SYNC:project-protocol-overlay:reminder -->
564
565## Closing Reminders
566
567**IMPORTANT MUST ATTENTION Goal:** Two-phase optimization (caveman compression + attention anchoring) that produces a prompt/skill stating its objective and ultimate outcome (one consolidated Goal) anchored top and bottom, so AI optimizes for the right result.
568
569**IMPORTANT MUST ATTENTION Protocols in force (concise digest of the SYNC/shared blocks this skill carries — each is a signpost to its canonical body above):**
570
571- **Output Quality:** MUST ATTENTION no inventories/trees/TOCs; lead with answer; sacrifice grammar for concision.
572- **Universal Skill-Building:** MUST ATTENTION detect-before-act, derive-don't-enumerate, evidence gates, fresh-eyes, embed protocols verbatim.
573- **Context Engineering:** MUST ATTENTION primacy-recency, high-signal density, compress aggressively, affirmative directives.
574- **Prompt Enhancement Transforms:** MUST ATTENTION inline READ summaries, top Quick-Summary, bottom Closing-Reminders (Transforms 1-3 base).
575- **Shared Protocol Duplication Policy:** NEVER extract SYNC duplication to references — edit canonical first; inline is intentional.
576- **AI Mistake Prevention:** verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
577- **Critical Thinking:** MUST ATTENTION traced `file:line` proof per claim; confidence >80% to act; NEVER guess.
578
579**IMPORTANT MUST ATTENTION** select `--op` FIRST (default `enhance`) — `compress`/`enhance` apply caveman compression FIRST (Phase 1) before structural enhancement (never skip); `expand` applies Language Expansion (inverse) instead — why: expand reconstructs, it does not strip
580**IMPORTANT MUST ATTENTION** NEVER compress code blocks, YAML frontmatter, structured tables, or SYNC tags
581**IMPORTANT MUST ATTENTION** read target file completely before any changes
582**IMPORTANT MUST ATTENTION** derive the target's one-sentence Goal (what it achieves + ultimate outcome), then place it in both `## Quick Summary` and `## Closing Reminders` — why: AI must know the ultimate outcome after enhancement
583**IMPORTANT MUST ATTENTION** enhance derives BOTH the target's Goal AND its Summary (key important things + steps AI must notice) and places both in `## Quick Summary`, the Summary at a different altitude than Workflow/Key Rules — why: the Goal tells AI the outcome to optimize for; the Summary tells AI the key things/steps to notice up front
584**IMPORTANT MUST ATTENTION** for a target that performs a task or has a purpose, the Summary AND Closing Reminders MUST enumerate the goal + purpose + ALL important main steps/tasks (compact ordered list) + modes/flags/gates — why: long task descriptions in the middle of the prompt get forgotten; the top Summary and bottom Reminders are the two anchors that survive context rot, so every step must appear in both
585**IMPORTANT MUST ATTENTION** skill AND sub-agent (`.claude/agents/*.md`) targets share ONE required structure — Goal + Summary in `## Quick Summary`, Goal echoed in `## Closing Reminders` — so creator skills (e.g. `custom-agent`) emit a consistent shape; when enhancing an agent NEVER alter `<!-- SYNC:... -->` blocks or delete `## Role`/`## Workflow`/`## Key Rules`/`## Output` — why: SYNC copies are canonical-synced and divergence fails the build
586**IMPORTANT MUST ATTENTION** read each referenced protocol file to write accurate inline summaries — NEVER guess content
587**IMPORTANT MUST ATTENTION** apply primacy-recency anchoring — 3 critical rules in first 5 AND last 5 lines of every enhanced file
588**IMPORTANT MUST ATTENTION** verify rule density: count MUST ATTENTION/NEVER/ALWAYS before and after — post ≥ pre
589**IMPORTANT MUST ATTENTION** state the action to take, not only what to avoid — pair every `NEVER` with the right path, and append a terse `— why:` to each non-obvious rule — why: affirmative directives + carried rationale are followed more reliably and survive compression (principles #10/#11)
590**IMPORTANT MUST ATTENTION** add inline summaries only for `.claude/` protocol files, not project-specific `docs/` files
591**IMPORTANT MUST ATTENTION** keep all meaningful content — only restructure/compress, NEVER delete rules or code examples
592**IMPORTANT MUST ATTENTION** verify no YAML frontmatter corruption after changes
593**IMPORTANT MUST ATTENTION** cite `file:line` evidence for every claim (confidence >80% to act). NEVER speculate without proof.
594**IMPORTANT MUST ATTENTION** READ `CLAUDE.md` before starting
595
596**Anti-Rationalization:**
597
598| Evasion | Rebuttal |
599| --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
600| "File is short, skip compression" | Apply both phases anyway — density matters at any length |
601| "Already read the file" | Show recorded line count + rule density as proof |
602| "Closing reminders already exist" | Verify they echo top-section rules AND include anti-rationalization table |
603| "Skill file, skip Universal Principles" | NEVER skip — Phase 0 detection is BLOCKING |
604| "Summary already has the goal, enough" | Task/purpose target needs ALL main steps enumerated in Summary AND Reminders — a goal alone leaves middle-buried steps forgettable |
605
606**[TASK-PLANNING]** Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using task tracking.
607
608<!-- CODEX:SYNC-PROMPT-PROTOCOLS:START -->
609
610## Hookless Prompt Protocol Mirror (Auto-Synced)
611
612Source: `.claude/.ck.json` + `.claude/skills/shared/sync-inline-versions.md` (`:full` blocks) + `.claude/scripts/lib/hookless-prompt-protocol.cjs`
613
614## [WORKFLOW-EXECUTION-PROTOCOL] [BLOCKING] Workflow Execution Protocol — MANDATORY IMPORTANT MUST CRITICAL. Do not skip for any reason.
615
616**Generic portability boundary:** Reusable skills and protocol text stay project-neutral; project-specific conventions are discovered from docs/project-config.json and docs/project-reference/. Apply shared AI-SDD from `shared/sdd-artifact-contract.md`. Read `docs/project-config.json` and `docs/project-reference/docs-index-reference.md`, then open the project reference docs named there. For spec, test-case, behavior-change, public-contract, or `docs/specs/` work, route through the local spec docs named by the docs index: `feature-spec-reference.md`, `spec-system-reference.md`, `spec-principles.md`, and `workflow-spec-test-code-cycle-reference.md` when specs/tests/code must stay synchronized. If either file or a required reference doc is missing or stale, auto-run `$project-init` (or the narrow lower-level route such as `$project-config`, `$docs-init`, `$scan-all`, or `$scan --target=<key>`) before ordinary project-specific work. Any supported AI tool may execute when this shared context and local docs are available.
617
6181. **DETECT:** If the prompt starts with an explicit slash skill/workflow command, execute it directly. Otherwise match the prompt against the workflow catalog and skill list.
6192. **ANALYZE:** Choose the best option: execute directly, invoke a skill, activate a standard workflow, or compose a custom step combination.
6203. **AUTO-SELECT:** Pick the best option yourself. Do not ask the user to choose between direct execution, skill, standard workflow, or custom workflow.
6214. **ACTIVATE:** For a selected workflow, call `$start-workflow <workflowId>`; for a selected skill, invoke that skill; for a custom workflow, sequence custom steps directly; for direct execution, proceed with the task.
6225. **CREATE TASKS:** task tracking for ALL workflow/skill/custom steps before execution when the selected path has multiple steps.
6236. **PARALLELIZE:** Before executing the task list, tag each task `PAR` (independent inputs + write set disjoint from every other `PAR` task) or `SEQ` (name the blocking dependency), group `PAR` tasks into waves, declare the wave plan, and spawn each wave's sub-agents in ONE message — all-return barrier per wave, fan-out one level deep unless a sub-agent's own definition authorizes further fan-out. Sequential-by-default is a defect when tasks are independent; do not parallelize shared write targets, output-consuming tasks, trivial single-file work, ordering a skill or workflow explicitly fixes, or user-approval gates.
6247. **EXECUTE:** Advance per the **Workflow Step Advancement & Parallel Phases** rule in your context instructions — model-driven; a sub-agent completion advances a step identically to an inline call; a parallel-phase group is an all-return barrier (advance only after ALL members return, never serialize it)
625
626## Shared AI-SDD Protocol Markers
627
628Source: `.claude/skills/shared/sync-inline-versions.md`
629
630## SYNC:ai-sdd-artifact-contract
631
632> **AI-SDD Artifact Contract** — Shared spec-driven development rules stay portable and source-owned.
633>
634> 1. Keep reusable AI-SDD principles in `.claude`; put repository-specific paths, commands, owners, products, and formats in project config/reference docs.
635> 2. Preserve cycle: `spec -> plan -> tasks -> implement -> verify -> update spec/docs`.
636> 3. Trace every requirement or invariant through decision, task, TC/test, source evidence, and docs/spec update.
637> 4. Treat code-to-spec extraction as reference-only until accepted by the canonical spec owner.
638> 5. Any supported AI tool may plan, implement, review, or verify with synced context; using multiple tools is optional.
639> 6. Update `.claude` source first, then sync generated mirrors; do not manually edit `.agents`, `.codex`, or `AGENTS.md`. — why: mirrors are generated artifacts; hand-edits are overwritten on the next sync
640> 7. If `docs/project-config.json`, root instruction files, or a required project-reference doc is missing or stale, auto-run `$project-init` or the narrow lower-level route before ordinary project-specific work.
641>
642> **Active reference:** `shared/sdd-artifact-contract.md` in the active skills root.
643
644---
645
646## SYNC:ai-sdd-artifact-contract:reminder
647
648- **MANDATORY** Apply `shared/sdd-artifact-contract.md`; keep reusable AI-SDD in `.claude` and local rules in project docs.
649- **MANDATORY** Code-to-spec extraction is reference-only until canonical acceptance; any supported AI tool may execute with synced context.
650- **MANDATORY** Update `.claude` source before syncing generated mirrors; do not manually edit `.agents`, `.codex`, or `AGENTS.md`.
651- **MANDATORY** Missing or stale project config, root instruction files, or required reference docs route project-specific work through `$project-init` or the narrow setup route automatically.
652 **[TASK-PLANNING] [MANDATORY]** BEFORE executing any workflow or skill step, create/update task tracking for all planned steps, then keep it synchronized as each step starts/completes.
653
654## [LESSON-LEARNED-REMINDER] [BLOCKING] Task Planning & Continuous Improvement — MANDATORY. Do not skip.
655
656Break work into small tasks (task tracking) before starting. Add final task: "Analyze AI mistakes & lessons learned".
657
658**Extract lessons — ROOT CAUSE ONLY, not symptom fixes:**
659
6601. Name the FAILURE MODE (reasoning/assumption failure), not symptom — "assumed API existed without reading source" not "used wrong enum value".
6612. Generality test: does this failure mode apply to ≥3 contexts/codebases? If not, abstract one level up.
6623. Write as a universal rule — strip project-specific names/paths/classes. Useful on any codebase.
6634. Consolidate: multiple mistakes sharing one failure mode → ONE lesson.
6645. **Recurrence gate:** "Would this recur in future session WITHOUT this reminder?" — No → skip `$learn`.
6656. **Auto-fix gate:** "Could `$code-review`/`$code-simplifier`/`$security-review`/`$lint` catch this?" — Yes → improve review skill instead.
6667. BOTH gates pass → ask user to run `$learn`.
667 **[CRITICAL-THINKING-MINDSET]** Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
668 **Anti-hallucination principle:** Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination.
669 **AI Attention principle (Primacy-Recency):** Put the 3 most critical rules at both top and bottom of long prompts/protocols so instruction adherence survives long context windows.
670 **Goal-driven execution:** Define success criteria first, loop until verified, and stop only when observable checks pass.
671 **Tests verify intent:** Tests must protect business rules/invariants and fail when the protected intent breaks, not only mirror current behavior.
672
673## Common AI Mistake Prevention (System Lessons)
674
675- **Re-read files after context compaction.** Edit requires prior Read in same context; compaction wipes read state. Re-read before editing.
676- **Grep for old terms after bulk replacements.** AI over-trusts find/replace completeness. Grep full repo after bulk edits for missed refs in docs/configs/catalogs.
677- **Check downstream references before deleting.** Deletions cascade doc/code staleness. Map referencing files before removal.
678- **After memory loss, check existing state before creating new.** Compaction wipes prior-work memory. Query current state to resume — never blindly duplicate.
679- **Verify AI-generated content against actual code.** AI hallucinates APIs, class names, method signatures. Grep to confirm existence before documenting/referencing.
680- **Trace full dependency chain after edits.** Changing a definition misses downstream consumers. Trace the full chain.
681- **When renaming, grep ALL consumer file types.** Some file types silently ignore missing refs (no compile error). Search code, templates, configs, generated files.
682- **Trace ALL code paths when verifying correctness.** Code existing ≠ code executing. Trace early exits, error branches, conditional skips — not just happy path.
683- **Update docs that embed canonical data when source changes.** Docs inlining derived data (workflows, schemas, configs) go stale silently. Update all embedding docs alongside source.
684- **Verify sub-agent results after context recovery.** Background agents may finish while parent compacted — grep-verify output, don't trust assumed completion.
685- **Cross-check full target list against sub-agent assignments.** Parallel sub-agents by category miss boundary items. Reconcile union of assignments against target list before proceeding.
686- **Sub-agents inherit knowledge only from their agent .md definition — use custom agent types, not built-in Explore.** Tool adoption = permission + knowledge + enforcement (numbered workflow step).
687- **Persist sub-agent findings incrementally, not as a final batch.** Long sub-agents hit cutoffs before final write — findings lost. Instruct append-per-section to report file.
688- **When debugging, ask "whose responsibility?" before fixing.** Trace caller (wrong data) vs callee (wrong handling). Fix at responsible layer — never patch symptom site.
689- **Test failure → record a provisional verdict before trace/edit, then investigate.** Use the full five-way taxonomy: SOURCE-WRONG (production violates intent), TEST-WRONG (assertion/setup is stale), TEST-NOT-OPTIMAL (valid but fragile or low-signal test), ENVIRONMENT-BLOCKED (external state prevents a verdict), or AMBIGUOUS (intent/evidence cannot choose safely). Then trace root cause and triangulate against the governing spec (`docs/specs/**` if one exists) AND source. NEVER weaken an assertion, add a skip, relax a timeout, or change source merely to force green.
690- **Grep ALL removed names after extraction/refactoring.** Primary file "done" ≠ secondary files clean. Grep entire scope for every removed symbol before declaring complete.
691- **Assume existing values are intentional — ask WHY before changing OR flagging one as a defect.** Pattern-matching as "wrong" skips context. Before changing or reporting any constant/limit/flag/cutoff: read comments, git blame, the CALLER's ordering (the guarantee that makes the value correct usually lives in code running immediately BEFORE the cited line), and 2+ sibling call sites of the same convention. A doc stating WHAT without WHY is missing rationale, not proof of a missing guard — and in a validation pass, an accurate `file:line` citation proves the transcription, never the defect.
692- **Verify ALL affected outputs, not just the first.** One build green ≠ all green. Multi-stack changes (backend/frontend/tests/docs) require verifying EVERY output.
693- **Evaluate fit before copying a nearby pattern.** Closest example ≠ matching preconditions — verify the new context shares the same constraints, base classes, scope, lifetime.
694- **Holistic-first debugging — resist nearest-attention trap.** Don't dive into first plausible cause. List EVERY precondition (config, env vars, paths, DB, endpoints, creds, versions, DI, data). Verify each against evidence (grep/query — not reasoning). Ask "what would falsify this?" — if nothing, it's not a hypothesis. Most expensive failure: going deeper in "obvious" layer while bug sits in layer never questioned.
695- **Surgical changes — apply the diff test (context-aware).** Two modes: (1) Bug fix → every line traces to the bug; no restyling; orphan cleanup only for imports YOUR changes made unused. (2) Review/enhancement → implement improvements AND announce as "Enhancement beyond main request: [what]". Never silently scope-creep. Diff test: "Would this line exist if I wasn't asked to do X?" — if no, delete or announce.
696- **Surface ambiguity before coding — don't pick silently.** Multiple valid interpretations → present each with effort: "[Request] could mean (1) [N h], (2) [N h]. Which matters?" List scope/format/volume/constraints assumptions first. If simpler path exists, say so. Never silently pick.
697- **[MANDATORY FIRST ACTION] ALWAYS activate a suitable skill or workflow BEFORE responding.** Match task against workflow catalog + skill list; invoke via skill invocation or `$start-workflow <workflowId>`. NEVER answer or write code before checking. Skip = protocol violation.
698- **Why-Review adversarial mindset — apply when reviewing any plan, decision, or design.** Default SKEPTIC not VALIDATOR: steel-man a rejected alternative, invert each stated reason ("what does it sacrifice?"), stress-test top 2-3 assumptions, run pre-mortem ("ships, fails in 3 months — what breaks?"), surface 1-2 alternatives author missed. Section presence ≠ quality; quality = causal reasoning + concrete mitigations + evidence, not "it's better" or "monitor closely".
699- **Front-load report-write in sub-agent prompts for large reviews.** Many-file sub-agents hit budget before final write — findings lost. Design prompts so: (1) report-write is first explicit deliverable, (2) append per-file/section (not batched), (3) scope bounded so reads don't exhaust budget. Truncated mid-sentence with no report file → spawn narrower scope, don't retry same prompt.
700- **After context compaction, re-verify all prior phase outcomes before continuing.** Summaries describe intent, not environment state (git index, filesystem, processes). On resume, FIRST audit: git status, re-read modified files, verify filesystem. Every "completed" claim is an untested hypothesis until evidence confirms.
701- **OOM/memory: check row count before row size.** Triage: (1) Unbounded query — no DB filter for trigger? Push filter to DB; eliminates OOM. (2) Large rows? Projection reduces proportionally. Row reduction > projection in ROI.
702- **Assert the outcome your system OWNS, never the intermediate state your INFRASTRUCTURE owns.** When testing anything asynchronous (queue/broker delivery, retries, background jobs, caches, replication), assert the final business/entity state. NEVER assert the delivery bookkeeping — consume/send status, attempt counts, last-error, row existence or counts in a broker, scheduler, or outbox/inbox table. That bookkeeping lives in shared infrastructure that ANY co-running process (a peer worker, a second replica, a leftover local container) can write, usually under a deterministic shared key, so the assertion silently tests the developer's environment instead of the system: green when run alone, flaky the instant anything else shares that broker + database. Gate question for every assertion: "would this hold no matter WHICH process did the work?" — if no, assert the converged data state instead. Corollary: process-local fault injection and in-process telemetry cannot gate work any process may perform — use them as stress amplifiers (arm → bounded window → disarm → assert convergence), never as preconditions.
703- **Keep domain concepts out of generic/shared/infrastructure layers.** Reusable layer (shared library, framework, infra module) must reference NO consumer-specific domain concept — tenant/customer/product IDs, business entities, feature rules. Leak compiles + runs → passes review silently while coupling the "reusable" layer to one consumer. Keep shared type domain-free; push domain fields/logic down into the consumer via subclass/composition. — why: a layer coupled to one consumer's domain is no longer reusable.
704
705<!-- CODEX:SYNC-PROMPT-PROTOCOLS:END -->