Codex compatibility note:
- Invoke repository skills with
$skill-name in Codex; this mirrored copy rewrites legacy Claude /skill-name references.
- Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.
- User-question prompts mean to ask the user directly in Codex.
- Ignore Claude-specific mode-switch instructions when they appear.
- Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.
- 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.
- Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.
- For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.
- If a required step/tool cannot run in this environment, stop and ask the user before adapting.
Codex Project-Reference Loading (No Hooks)
Codex uses static project-reference loading instead of runtime-injected project docs.
When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.
Always read:
docs/project-config.json (project-specific paths, commands, modules, and workflow/test settings)
docs/project-reference/docs-index-reference.md (routes to the full docs/project-reference/* catalog)
docs/project-reference/lessons.md (always-on guardrails and anti-patterns)
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.
Situation-based docs:
- Project structure/architecture/tech-stack/deployment/setup (any layer — backend, frontend, or infra):
project-structure-reference.md
- Backend/CQRS/API/domain/entity changes:
backend-patterns-reference.md, domain-entities-reference.md
- Frontend/UI/styling/design-system:
frontend-patterns-reference.md, scss-styling-guide.md, design-system/README.md
- Spec authoring,
docs/specs/ pathing, or TC format: feature-spec-reference.md, spec-system-reference.md, spec-principles.md
- Behavior/public-contract changes or spec-test-code sync:
workflow-spec-test-code-cycle-reference.md plus the spec docs above
- Derived spec indexes/ERDs/reimplementation guides:
spec-system-reference.md and source Feature Specs under docs/specs/
- Integration test implementation/review:
integration-test-reference.md
- E2E test implementation/review:
e2e-test-reference.md
- Code review/audit work:
code-review-rules.md plus domain docs above based on changed files
Do not read all docs blindly. Start from docs-index-reference.md, then open only relevant files for the task.
Quick Summary
Goal: Enhance code documentation, API docs, README files, and technical writing with verified accuracy.
Workflow:
- Analysis — Build knowledge model: discover APIs, components, structure, documentation gaps
- Plan — Generate detailed documentation plan with priorities and outline
- Approval Gate — Present plan for explicit user approval before writing
- Execute — Write documentation following anti-hallucination protocols
Key Rules:
- Proceed only after explicit user approval of the documentation plan — never without it
- Verify every documented feature against actual code (no assumptions)
- For business feature docs, use
spec skill instead
- Include practical examples and copy-pasteable code snippets
Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).
Skill Variant: Use this skill for interactive documentation tasks including code docs AND README files.
Disambiguation
- For business feature docs → use
spec
- This skill covers code documentation and README files
Documentation Enhancement
You are to operate as an expert technical writer and software documentation specialist to enhance documentation.
IMPORTANT: Always thinks hard, plan step by step to-do list first before execute. Always remember to-do list, never compact or summary it when memory context limit reach. Always preserve and carry your to-do list through every operation.
README Structure Template
Use this structure when creating or improving README files:
# Project Name
Brief description of the project.
## Table of Contents
- [Features](#features)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Configuration](#configuration)
- [Usage](#usage)
- [Development](#development)
- [Testing](#testing)
- [Deployment](#deployment)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
- [License](#license)
## Features
- Feature 1
- Feature 2
## Prerequisites
- Node.js >= 18
- Configured runtime SDK
## Installation
```bash
# Clone the repository
git clone [url]
# Install dependencies
npm install
dotnet restore
```
## Configuration
[Configuration details]
## Usage
[Usage examples]
## Development
[Development setup]
## Testing
[Testing instructions]
## Troubleshooting
[Common issues and solutions]
PHASE 1: EXTERNAL MEMORY-DRIVEN DOCUMENTATION ANALYSIS
Build a structured knowledge model in .ai/workspace/analysis/[task-name].analysis.md.
PHASE 1A: INITIALIZATION AND DISCOVERY
- Initialize the analysis file with standard headings
- Discovery searches for all related files
DOCUMENTATION-SPECIFIC DISCOVERY
DOCUMENTATION_COMPLETENESS_DISCOVERY: Focus on documentation-relevant patterns:
API Documentation Analysis: Find API endpoints and identify missing documentation. Document under ## API Documentation.
Component Documentation Analysis: Find public classes/methods and identify complex logic needing explanation. Document under ## Component Documentation.
Basic Structure Analysis: Find key configuration files and main application flows. Document under ## Structure Documentation.
PROJECT_OVERVIEW_DISCOVERY (README-specific): Focus on README-relevant patterns:
- Project Structure Analysis: Find entry points, map key directories, identify technologies
- Feature Discovery: Find user-facing features and map API endpoints
- Setup Requirements Analysis: Find package files, map dependencies, identify configuration needs
PHASE 1B: SYSTEMATIC FILE ANALYSIS FOR DOCUMENTATION
IMPORTANT: Must do with todo list.
For each file, document in ## Knowledge Graph:
- Standard fields plus documentation-specific:
documentationGaps: Missing or incomplete documentation
complexityLevel: How difficult to understand (1-10)
userFacingFeatures: Features needing user documentation
developerNotes: Technical details needing developer docs
exampleRequirements: Code examples or usage scenarios needed
apiDocumentationNeeds: API endpoints requiring documentation
configurationOptions: Configuration parameters needing explanation
troubleshootingAreas: Common issues requiring troubleshooting docs
README-specific fields (when analyzing for README documentation):
| Field |
Description |
readmeRelevance |
How component should be represented (1-10) |
userImpact |
How component affects end users |
setupRequirements |
Prerequisites for this component |
configurationNeeds |
Configuration required |
featureDescription |
User-facing features provided |
exampleUsage |
Usage examples for README |
projectContext |
How it fits into overall project |
PHASE 1C: OVERALL ANALYSIS
Write comprehensive summary showing:
- Complete end-to-end workflows discovered
- Documentation gaps identified
- Priority areas for documentation
- Key features and capabilities (README)
- Setup and configuration requirements (README)
PHASE 2: DOCUMENTATION PLAN GENERATION
Generate detailed documentation plan under ## Documentation Plan:
- Focus on completeness
- Ensure clarity
- Include examples
- Maintain consistency
For README plans, generate a detailed outline covering: Project Overview, Installation, Usage, Configuration, Development guidelines.
PHASE 3: APPROVAL GATE
CRITICAL: Present documentation plan for explicit approval. DO NOT proceed without it.
PHASE 4: DOCUMENTATION EXECUTION
Once approved, execute the plan using all DOCUMENTATION_SAFEGUARDS.
SUCCESS VALIDATION
Verify documentation is:
- Accurate (matches actual code)
- Complete (covers all public APIs)
- Helpful (includes examples)
README-specific checks:
Document under ## Documentation Validation.
Documentation Guidelines
- Accuracy-first approach: Verify every documented feature with actual code
- User-focused content: Organize documentation based on user needs
- Example-driven documentation: Include practical examples and usage scenarios
- Consistency maintenance: Follow established documentation patterns
- No assumptions: Always verify behavior before documenting
README Guidelines
- User-first approach: Organize content for new users; start with what the project does and why; provide clear getting-started path
- Verified instructions: Test all setup and installation instructions; include exact commands that work; document version requirements
- Practical examples: Include working examples users can follow; show common use cases; provide copy-pasteable code snippets
- No assumptions: Don't assume user knowledge; explain acronyms and domain terms; link to prerequisite documentation
⚠️ MUST ATTENTION READ: CLAUDE.md for code pattern examples (backend/frontend) when writing code documentation. See .claude/docs/ for existing documentation structure.
Anti-Hallucination Protocols
ASSUMPTION_VALIDATION_CHECKPOINT
Before every major operation:
- "What assumptions am I making about [X]?"
- "Have I verified this with actual code evidence?"
EVIDENCE_CHAIN_VALIDATION
Before claiming any relationship:
- "I believe X calls Y because..." → show actual code
- "This follows pattern Z because..." → cite specific examples
TOOL_EFFICIENCY_PROTOCOL
- Batch multiple Grep searches into single calls with OR patterns
- Use parallel Read operations for related files
CONTEXT_ANCHOR_SYSTEM
Every 10 operations:
- Re-read the original task description
- Verify the current operation aligns with original goals
Related
spec
changelog
release-notes
Task Planning Notes (MUST ATTENTION FOLLOW)
- Always plan and break work into many small todo tasks
- Always add a final review todo task to verify work quality and identify fixes/enhancements
[IMPORTANT] Use task tracking to break ALL work into small tasks BEFORE starting — including tasks for each file read. This prevents context loss from long files. For simple tasks, AI MUST ATTENTION ask user whether to skip.
AI Mistake Prevention — Failure modes to avoid on every task:
Re-read files after context changes. Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
Verify generated content against source evidence. AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
Check downstream references before deleting or renaming. Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
Trace the full impact chain after edits. Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
Verify ALL affected outputs, not just the first. One green check is not all green checks; validate every output surface the change can affect.
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.
Surface ambiguity before acting — don't pick silently. Multiple valid interpretations require an explicit question or stated assumption with risk.
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.
Keep shared guidance role-relevant. Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
Evidence-Based Reasoning — Speculation is FORBIDDEN. Every claim needs proof.
- Cite
file:line, grep results, or framework docs for EVERY claim
- Declare confidence: >80% act freely, 60-80% verify first, <60% DO NOT recommend
- Cross-service validation required for architectural changes
- "I don't have enough evidence" is valid and expected output
BLOCKED until: - [ ] Evidence file path (file:line) - [ ] Grep search performed - [ ] 3+ similar patterns found - [ ] Confidence level stated
Forbidden without proof: "obviously", "I think", "should be", "probably", "this is because"
If incomplete → output: "Insufficient evidence. Verified: [...]. Not verified: [...]."
Critical Thinking Mindset — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
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.
- MANDATORY IMPORTANT MUST ATTENTION cite
file:line evidence for every claim. Confidence >80% to act, <60% = do NOT recommend.
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.
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.
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.
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.
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.
Closing Reminders
Protocols in force (concise digest of the SYNC/shared blocks this skill carries) — MUST ATTENTION each canonical body above:
Evidence: cite file:line for every claim; confidence >80% to act, <60% NEVER recommend.
Critical Thinking: apply critical + sequential thinking; NEVER present guess as fact.
AI Mistake Prevention: verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
MANDATORY IMPORTANT MUST ATTENTION break work into small todo tasks using task tracking BEFORE starting
MANDATORY IMPORTANT MUST ATTENTION search codebase for 3+ similar patterns before creating new code
MANDATORY IMPORTANT MUST ATTENTION cite file:line evidence for every claim (confidence >80% to act)
MANDATORY IMPORTANT MUST ATTENTION add a final review todo task to verify work quality
MANDATORY IMPORTANT MUST ATTENTION READ the following files before starting:
[TASK-PLANNING] Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using task tracking.
Hookless Prompt Protocol Mirror (Auto-Synced)
Source: .claude/.ck.json + .claude/skills/shared/sync-inline-versions.md (:full blocks) + .claude/scripts/lib/hookless-prompt-protocol.cjs
[WORKFLOW-EXECUTION-PROTOCOL] [BLOCKING] Workflow Execution Protocol — MANDATORY IMPORTANT MUST CRITICAL. Do not skip for any reason.
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.
- 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.
- ANALYZE: Choose the best option: execute directly, invoke a skill, activate a standard workflow, or compose a custom step combination.
- AUTO-SELECT: Pick the best option yourself. Do not ask the user to choose between direct execution, skill, standard workflow, or custom workflow.
- 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.
- CREATE TASKS: task tracking for ALL workflow/skill/custom steps before execution when the selected path has multiple steps.
- 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.
- 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)
Shared AI-SDD Protocol Markers
Source: .claude/skills/shared/sync-inline-versions.md
SYNC:ai-sdd-artifact-contract
AI-SDD Artifact Contract — Shared spec-driven development rules stay portable and source-owned.
- Keep reusable AI-SDD principles in
.claude; put repository-specific paths, commands, owners, products, and formats in project config/reference docs.
- Preserve cycle:
spec -> plan -> tasks -> implement -> verify -> update spec/docs.
- Trace every requirement or invariant through decision, task, TC/test, source evidence, and docs/spec update.
- Treat code-to-spec extraction as reference-only until accepted by the canonical spec owner.
- Any supported AI tool may plan, implement, review, or verify with synced context; using multiple tools is optional.
- 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
- 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.
Active reference: shared/sdd-artifact-contract.md in the active skills root.
SYNC:ai-sdd-artifact-contract:reminder
- MANDATORY Apply
shared/sdd-artifact-contract.md; keep reusable AI-SDD in .claude and local rules in project docs.
- MANDATORY Code-to-spec extraction is reference-only until canonical acceptance; any supported AI tool may execute with synced context.
- MANDATORY Update
.claude source before syncing generated mirrors; do not manually edit .agents, .codex, or AGENTS.md.
- 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.
[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.
[LESSON-LEARNED-REMINDER] [BLOCKING] Task Planning & Continuous Improvement — MANDATORY. Do not skip.
Break work into small tasks (task tracking) before starting. Add final task: "Analyze AI mistakes & lessons learned".
Extract lessons — ROOT CAUSE ONLY, not symptom fixes:
- Name the FAILURE MODE (reasoning/assumption failure), not symptom — "assumed API existed without reading source" not "used wrong enum value".
- Generality test: does this failure mode apply to ≥3 contexts/codebases? If not, abstract one level up.
- Write as a universal rule — strip project-specific names/paths/classes. Useful on any codebase.
- Consolidate: multiple mistakes sharing one failure mode → ONE lesson.
- Recurrence gate: "Would this recur in future session WITHOUT this reminder?" — No → skip
$learn.
- Auto-fix gate: "Could
$code-review/$code-simplifier/$security-review/$lint catch this?" — Yes → improve review skill instead.
- BOTH gates pass → ask user to run
$learn.
[CRITICAL-THINKING-MINDSET] Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
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.
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.
Goal-driven execution: Define success criteria first, loop until verified, and stop only when observable checks pass.
Tests verify intent: Tests must protect business rules/invariants and fail when the protected intent breaks, not only mirror current behavior.
Common AI Mistake Prevention (System Lessons)
- Re-read files after context compaction. Edit requires prior Read in same context; compaction wipes read state. Re-read before editing.
- 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.
- Check downstream references before deleting. Deletions cascade doc/code staleness. Map referencing files before removal.
- After memory loss, check existing state before creating new. Compaction wipes prior-work memory. Query current state to resume — never blindly duplicate.
- Verify AI-generated content against actual code. AI hallucinates APIs, class names, method signatures. Grep to confirm existence before documenting/referencing.
- Trace full dependency chain after edits. Changing a definition misses downstream consumers. Trace the full chain.
- When renaming, grep ALL consumer file types. Some file types silently ignore missing refs (no compile error). Search code, templates, configs, generated files.
- Trace ALL code paths when verifying correctness. Code existing ≠ code executing. Trace early exits, error branches, conditional skips — not just happy path.
- 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.
- Verify sub-agent results after context recovery. Background agents may finish while parent compacted — grep-verify output, don't trust assumed completion.
- 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.
- 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).
- 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.
- When debugging, ask "whose responsibility?" before fixing. Trace caller (wrong data) vs callee (wrong handling). Fix at responsible layer — never patch symptom site.
- 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.
- Grep ALL removed names after extraction/refactoring. Primary file "done" ≠ secondary files clean. Grep entire scope for every removed symbol before declaring complete.
- 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.
- Verify ALL affected outputs, not just the first. One build green ≠ all green. Multi-stack changes (backend/frontend/tests/docs) require verifying EVERY output.
- Evaluate fit before copying a nearby pattern. Closest example ≠ matching preconditions — verify the new context shares the same constraints, base classes, scope, lifetime.
- 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.
- 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.
- 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.
- [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.
- 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".
- 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.
- 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.
- 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.
- 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.
- 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.
1---2name: documentation3description: [Code Quality] Use when the user asks to enhance documentation, add code comments, create API docs, improve technical documentation, document code, or update README files.4---5
6> Codex compatibility note:
7>
8> - Invoke repository skills with `$skill-name` in Codex; this mirrored copy rewrites legacy Claude `/skill-name` references.
9> - Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.
10> - User-question prompts mean to ask the user directly in Codex.
11> - Ignore Claude-specific mode-switch instructions when they appear.
12> - Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.
13> - 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.
14> - Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.
15> - For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.
16> - If a required step/tool cannot run in this environment, stop and ask the user before adapting.
17
18<!-- CODEX:PROJECT-REFERENCE-LOADING:START -->
19
20## Codex Project-Reference Loading (No Hooks)
21
22Codex uses static project-reference loading instead of runtime-injected project docs.
23When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.
24
25**Always read:**
26
27- `docs/project-config.json` (project-specific paths, commands, modules, and workflow/test settings)
28- `docs/project-reference/docs-index-reference.md` (routes to the full `docs/project-reference/*` catalog)
29- `docs/project-reference/lessons.md` (always-on guardrails and anti-patterns)
30
31**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.
32
33**Situation-based docs:**
34
35- Project structure/architecture/tech-stack/deployment/setup (any layer — backend, frontend, or infra): `project-structure-reference.md`
36- Backend/CQRS/API/domain/entity changes: `backend-patterns-reference.md`, `domain-entities-reference.md`
37- Frontend/UI/styling/design-system: `frontend-patterns-reference.md`, `scss-styling-guide.md`, `design-system/README.md`
38- Spec authoring, `docs/specs/` pathing, or TC format: `feature-spec-reference.md`, `spec-system-reference.md`, `spec-principles.md`
39- Behavior/public-contract changes or spec-test-code sync: `workflow-spec-test-code-cycle-reference.md` plus the spec docs above
40- Derived spec indexes/ERDs/reimplementation guides: `spec-system-reference.md` and source Feature Specs under `docs/specs/`
41- Integration test implementation/review: `integration-test-reference.md`
42- E2E test implementation/review: `e2e-test-reference.md`
43- Code review/audit work: `code-review-rules.md` plus domain docs above based on changed files
44
45Do not read all docs blindly. Start from `docs-index-reference.md`, then open only relevant files for the task.
46
47<!-- CODEX:PROJECT-REFERENCE-LOADING:END -->
48
49## Quick Summary
50
51**Goal:** Enhance code documentation, API docs, README files, and technical writing with verified accuracy.
52
53**Workflow:**
54
551. **Analysis** — Build knowledge model: discover APIs, components, structure, documentation gaps
562. **Plan** — Generate detailed documentation plan with priorities and outline
573. **Approval Gate** — Present plan for explicit user approval before writing
584. **Execute** — Write documentation following anti-hallucination protocols
59
60**Key Rules:**
61
62- Proceed only after explicit user approval of the documentation plan — never without it
63- Verify every documented feature against actual code (no assumptions)
64- For business feature docs, use `spec` skill instead
65- Include practical examples and copy-pasteable code snippets
66
67**Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).**
68
69> **Skill Variant:** Use this skill for **interactive documentation tasks** including code docs AND README files.
70
71## Disambiguation
72
73- For **business feature docs** → use `spec`
74- This skill covers **code documentation** and **README files**
75
76# Documentation Enhancement
77
78You are to operate as an expert technical writer and software documentation specialist to enhance documentation.
79
80**IMPORTANT**: Always thinks hard, plan step by step to-do list first before execute. Always remember to-do list, never compact or summary it when memory context limit reach. Always preserve and carry your to-do list through every operation.
81
82---
83
84## README Structure Template
85
86Use this structure when creating or improving README files:
87
88````markdown
89# Project Name
90
91Brief description of the project.
92
93## Table of Contents
94
95- [Features](#features)
96- [Prerequisites](#prerequisites)
97- [Installation](#installation)
98- [Configuration](#configuration)
99- [Usage](#usage)
100- [Development](#development)
101- [Testing](#testing)
102- [Deployment](#deployment)
103- [Troubleshooting](#troubleshooting)
104- [Contributing](#contributing)
105- [License](#license)
106
107## Features
108
109- Feature 1
110- Feature 2
111
112## Prerequisites
113
114- Node.js >= 18
115- Configured runtime SDK
116
117## Installation
118
119```bash
120# Clone the repository
121git clone [url]
122
123# Install dependencies
124npm install
125dotnet restore
126```
127
128## Configuration
129
130[Configuration details]
131
132## Usage
133
134[Usage examples]
135
136## Development
137
138[Development setup]
139
140## Testing
141
142[Testing instructions]
143
144## Troubleshooting
145
146[Common issues and solutions]
147````
148
149---
150
151## PHASE 1: EXTERNAL MEMORY-DRIVEN DOCUMENTATION ANALYSIS
152
153Build a structured knowledge model in `.ai/workspace/analysis/[task-name].analysis.md`.
154
155### PHASE 1A: INITIALIZATION AND DISCOVERY
156
1571. **Initialize** the analysis file with standard headings
1582. **Discovery searches** for all related files
159
160### DOCUMENTATION-SPECIFIC DISCOVERY
161
162**DOCUMENTATION_COMPLETENESS_DISCOVERY**: Focus on documentation-relevant patterns:
163
1641. **API Documentation Analysis**: Find API endpoints and identify missing documentation. Document under `## API Documentation`.
165
1662. **Component Documentation Analysis**: Find public classes/methods and identify complex logic needing explanation. Document under `## Component Documentation`.
167
1683. **Basic Structure Analysis**: Find key configuration files and main application flows. Document under `## Structure Documentation`.
169
170**PROJECT_OVERVIEW_DISCOVERY** (README-specific): Focus on README-relevant patterns:
171
1721. **Project Structure Analysis**: Find entry points, map key directories, identify technologies
1732. **Feature Discovery**: Find user-facing features and map API endpoints
1743. **Setup Requirements Analysis**: Find package files, map dependencies, identify configuration needs
175
176### PHASE 1B: SYSTEMATIC FILE ANALYSIS FOR DOCUMENTATION
177
178> **IMPORTANT:** Must do with todo list.
179
180For each file, document in `## Knowledge Graph`:
181
182- Standard fields plus documentation-specific:
183- `documentationGaps`: Missing or incomplete documentation
184- `complexityLevel`: How difficult to understand (1-10)
185- `userFacingFeatures`: Features needing user documentation
186- `developerNotes`: Technical details needing developer docs
187- `exampleRequirements`: Code examples or usage scenarios needed
188- `apiDocumentationNeeds`: API endpoints requiring documentation
189- `configurationOptions`: Configuration parameters needing explanation
190- `troubleshootingAreas`: Common issues requiring troubleshooting docs
191
192README-specific fields (when analyzing for README documentation):
193
194| Field | Description |
195| -------------------- | ------------------------------------------ |
196| `readmeRelevance` | How component should be represented (1-10) |
197| `userImpact` | How component affects end users |
198| `setupRequirements` | Prerequisites for this component |
199| `configurationNeeds` | Configuration required |
200| `featureDescription` | User-facing features provided |
201| `exampleUsage` | Usage examples for README |
202| `projectContext` | How it fits into overall project |
203
204### PHASE 1C: OVERALL ANALYSIS
205
206Write comprehensive summary showing:
207
208- Complete end-to-end workflows discovered
209- Documentation gaps identified
210- Priority areas for documentation
211- Key features and capabilities (README)
212- Setup and configuration requirements (README)
213
214---
215
216## PHASE 2: DOCUMENTATION PLAN GENERATION
217
218Generate detailed documentation plan under `## Documentation Plan`:
219
220- Focus on completeness
221- Ensure clarity
222- Include examples
223- Maintain consistency
224
225For README plans, generate a detailed outline covering: Project Overview, Installation, Usage, Configuration, Development guidelines.
226
227---
228
229## PHASE 3: APPROVAL GATE
230
231**CRITICAL**: Present documentation plan for explicit approval. **DO NOT** proceed without it.
232
233---
234
235## PHASE 4: DOCUMENTATION EXECUTION
236
237Once approved, execute the plan using all DOCUMENTATION_SAFEGUARDS.
238
239---
240
241## SUCCESS VALIDATION
242
243Verify documentation is:
244
245- Accurate (matches actual code)
246- Complete (covers all public APIs)
247- Helpful (includes examples)
248
249README-specific checks:
250
251- [ ] **Accurate**: All instructions work
252- [ ] **Comprehensive**: Covers all setup needs
253- [ ] **Helpful**: New users can get started
254- [ ] **Tested**: Commands verified to work
255
256Document under `## Documentation Validation`.
257
258---
259
260## Documentation Guidelines
261
262- **Accuracy-first approach**: Verify every documented feature with actual code
263- **User-focused content**: Organize documentation based on user needs
264- **Example-driven documentation**: Include practical examples and usage scenarios
265- **Consistency maintenance**: Follow established documentation patterns
266- **No assumptions**: Always verify behavior before documenting
267
268### README Guidelines
269
270- **User-first approach**: Organize content for new users; start with what the project does and why; provide clear getting-started path
271- **Verified instructions**: Test all setup and installation instructions; include exact commands that work; document version requirements
272- **Practical examples**: Include working examples users can follow; show common use cases; provide copy-pasteable code snippets
273- **No assumptions**: Don't assume user knowledge; explain acronyms and domain terms; link to prerequisite documentation
274
275**⚠️ MUST ATTENTION READ:** CLAUDE.md for code pattern examples (backend/frontend) when writing code documentation. See `.claude/docs/` for existing documentation structure.
276
277---
278
279## Anti-Hallucination Protocols
280
281### ASSUMPTION_VALIDATION_CHECKPOINT
282
283Before every major operation:
284
2851. "What assumptions am I making about [X]?"
2862. "Have I verified this with actual code evidence?"
287
288### EVIDENCE_CHAIN_VALIDATION
289
290Before claiming any relationship:
291
292- "I believe X calls Y because..." → show actual code
293- "This follows pattern Z because..." → cite specific examples
294
295### TOOL_EFFICIENCY_PROTOCOL
296
297- Batch multiple Grep searches into single calls with OR patterns
298- Use parallel Read operations for related files
299
300### CONTEXT_ANCHOR_SYSTEM
301
302Every 10 operations:
303
3041. Re-read the original task description
3052. Verify the current operation aligns with original goals
306
307---
308
309## Related
310
311- `spec`
312- `changelog`
313- `release-notes`
314
315---
316
317### Task Planning Notes (MUST ATTENTION FOLLOW)
318
319- Always plan and break work into many small todo tasks
320- Always add a final review todo task to verify work quality and identify fixes/enhancements
321
322---
323
324> **[IMPORTANT]** Use task tracking to break ALL work into small tasks BEFORE starting — including tasks for each file read. This prevents context loss from long files. For simple tasks, AI MUST ATTENTION ask user whether to skip.
325
326<!-- SYNC:ai-mistake-prevention -->
327
328> **AI Mistake Prevention** — Failure modes to avoid on every task:
329>
330> **Re-read files after context changes.** Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
331> **Verify generated content against source evidence.** AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
332> **Check downstream references before deleting or renaming.** Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
333> **Trace the full impact chain after edits.** Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
334> **Verify ALL affected outputs, not just the first.** One green check is not all green checks; validate every output surface the change can affect.
335> **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.
336> **Surface ambiguity before acting — don't pick silently.** Multiple valid interpretations require an explicit question or stated assumption with risk.
337> **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.
338> **Keep shared guidance role-relevant.** Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
339
340<!-- /SYNC:ai-mistake-prevention -->
341
342<!-- SYNC:evidence-based-reasoning -->
343
344> **Evidence-Based Reasoning** — Speculation is FORBIDDEN. Every claim needs proof.
345>
346> 1. Cite `file:line`, grep results, or framework docs for EVERY claim
347> 2. Declare confidence: >80% act freely, 60-80% verify first, <60% DO NOT recommend
348> 3. Cross-service validation required for architectural changes
349> 4. "I don't have enough evidence" is valid and expected output
350>
351> **BLOCKED until:** `- [ ]` Evidence file path (`file:line`) `- [ ]` Grep search performed `- [ ]` 3+ similar patterns found `- [ ]` Confidence level stated
352>
353> **Forbidden without proof:** "obviously", "I think", "should be", "probably", "this is because"
354> **If incomplete →** output: `"Insufficient evidence. Verified: [...]. Not verified: [...]."`
355
356<!-- /SYNC:evidence-based-reasoning -->
357
358<!-- SYNC:critical-thinking-mindset -->
359
360> **Critical Thinking Mindset** — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
361> **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.
362
363<!-- /SYNC:critical-thinking-mindset -->
364
365<!-- SYNC:evidence-based-reasoning:reminder -->
366
367- **MANDATORY IMPORTANT MUST ATTENTION** cite `file:line` evidence for every claim. Confidence >80% to act, <60% = do NOT recommend.
368 <!-- /SYNC:evidence-based-reasoning:reminder -->
369
370<!-- SYNC:critical-thinking-mindset:reminder -->
371
372**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.
373
374<!-- /SYNC:critical-thinking-mindset:reminder -->
375
376<!-- SYNC:ai-mistake-prevention:reminder -->
377
378**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.
379
380<!-- /SYNC:ai-mistake-prevention:reminder -->
381
382<!-- SYNC:project-protocol-overlay -->
383
384> **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`.
385>
386> 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.
387
388<!-- /SYNC:project-protocol-overlay -->
389
390<!-- SYNC:project-protocol-overlay:reminder -->
391
392**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.
393
394<!-- /SYNC:project-protocol-overlay:reminder -->
395
396## Closing Reminders
397
398**Protocols in force (concise digest of the SYNC/shared blocks this skill carries) — MUST ATTENTION each canonical body above:**
399
400- **Evidence:** cite `file:line` for every claim; confidence >80% to act, <60% NEVER recommend.
401- **Critical Thinking:** apply critical + sequential thinking; NEVER present guess as fact.
402- **AI Mistake Prevention:** verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
403
404- **MANDATORY IMPORTANT MUST ATTENTION** break work into small todo tasks using task tracking BEFORE starting
405- **MANDATORY IMPORTANT MUST ATTENTION** search codebase for 3+ similar patterns before creating new code
406- **MANDATORY IMPORTANT MUST ATTENTION** cite `file:line` evidence for every claim (confidence >80% to act)
407- **MANDATORY IMPORTANT MUST ATTENTION** add a final review todo task to verify work quality
408 **MANDATORY IMPORTANT MUST ATTENTION** READ the following files before starting:
409
410**[TASK-PLANNING]** Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using task tracking.
411
412<!-- CODEX:SYNC-PROMPT-PROTOCOLS:START -->
413
414## Hookless Prompt Protocol Mirror (Auto-Synced)
415
416Source: `.claude/.ck.json` + `.claude/skills/shared/sync-inline-versions.md` (`:full` blocks) + `.claude/scripts/lib/hookless-prompt-protocol.cjs`
417
418## [WORKFLOW-EXECUTION-PROTOCOL] [BLOCKING] Workflow Execution Protocol — MANDATORY IMPORTANT MUST CRITICAL. Do not skip for any reason.
419
420**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.
421
4221. **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.
4232. **ANALYZE:** Choose the best option: execute directly, invoke a skill, activate a standard workflow, or compose a custom step combination.
4243. **AUTO-SELECT:** Pick the best option yourself. Do not ask the user to choose between direct execution, skill, standard workflow, or custom workflow.
4254. **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.
4265. **CREATE TASKS:** task tracking for ALL workflow/skill/custom steps before execution when the selected path has multiple steps.
4276. **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.
4287. **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)
429
430## Shared AI-SDD Protocol Markers
431
432Source: `.claude/skills/shared/sync-inline-versions.md`
433
434## SYNC:ai-sdd-artifact-contract
435
436> **AI-SDD Artifact Contract** — Shared spec-driven development rules stay portable and source-owned.
437>
438> 1. Keep reusable AI-SDD principles in `.claude`; put repository-specific paths, commands, owners, products, and formats in project config/reference docs.
439> 2. Preserve cycle: `spec -> plan -> tasks -> implement -> verify -> update spec/docs`.
440> 3. Trace every requirement or invariant through decision, task, TC/test, source evidence, and docs/spec update.
441> 4. Treat code-to-spec extraction as reference-only until accepted by the canonical spec owner.
442> 5. Any supported AI tool may plan, implement, review, or verify with synced context; using multiple tools is optional.
443> 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
444> 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.
445>
446> **Active reference:** `shared/sdd-artifact-contract.md` in the active skills root.
447
448---
449
450## SYNC:ai-sdd-artifact-contract:reminder
451
452- **MANDATORY** Apply `shared/sdd-artifact-contract.md`; keep reusable AI-SDD in `.claude` and local rules in project docs.
453- **MANDATORY** Code-to-spec extraction is reference-only until canonical acceptance; any supported AI tool may execute with synced context.
454- **MANDATORY** Update `.claude` source before syncing generated mirrors; do not manually edit `.agents`, `.codex`, or `AGENTS.md`.
455- **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.
456 **[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.
457
458## [LESSON-LEARNED-REMINDER] [BLOCKING] Task Planning & Continuous Improvement — MANDATORY. Do not skip.
459
460Break work into small tasks (task tracking) before starting. Add final task: "Analyze AI mistakes & lessons learned".
461
462**Extract lessons — ROOT CAUSE ONLY, not symptom fixes:**
463
4641. Name the FAILURE MODE (reasoning/assumption failure), not symptom — "assumed API existed without reading source" not "used wrong enum value".
4652. Generality test: does this failure mode apply to ≥3 contexts/codebases? If not, abstract one level up.
4663. Write as a universal rule — strip project-specific names/paths/classes. Useful on any codebase.
4674. Consolidate: multiple mistakes sharing one failure mode → ONE lesson.
4685. **Recurrence gate:** "Would this recur in future session WITHOUT this reminder?" — No → skip `$learn`.
4696. **Auto-fix gate:** "Could `$code-review`/`$code-simplifier`/`$security-review`/`$lint` catch this?" — Yes → improve review skill instead.
4707. BOTH gates pass → ask user to run `$learn`.
471 **[CRITICAL-THINKING-MINDSET]** Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
472 **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.
473 **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.
474 **Goal-driven execution:** Define success criteria first, loop until verified, and stop only when observable checks pass.
475 **Tests verify intent:** Tests must protect business rules/invariants and fail when the protected intent breaks, not only mirror current behavior.
476
477## Common AI Mistake Prevention (System Lessons)
478
479- **Re-read files after context compaction.** Edit requires prior Read in same context; compaction wipes read state. Re-read before editing.
480- **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.
481- **Check downstream references before deleting.** Deletions cascade doc/code staleness. Map referencing files before removal.
482- **After memory loss, check existing state before creating new.** Compaction wipes prior-work memory. Query current state to resume — never blindly duplicate.
483- **Verify AI-generated content against actual code.** AI hallucinates APIs, class names, method signatures. Grep to confirm existence before documenting/referencing.
484- **Trace full dependency chain after edits.** Changing a definition misses downstream consumers. Trace the full chain.
485- **When renaming, grep ALL consumer file types.** Some file types silently ignore missing refs (no compile error). Search code, templates, configs, generated files.
486- **Trace ALL code paths when verifying correctness.** Code existing ≠ code executing. Trace early exits, error branches, conditional skips — not just happy path.
487- **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.
488- **Verify sub-agent results after context recovery.** Background agents may finish while parent compacted — grep-verify output, don't trust assumed completion.
489- **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.
490- **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).
491- **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.
492- **When debugging, ask "whose responsibility?" before fixing.** Trace caller (wrong data) vs callee (wrong handling). Fix at responsible layer — never patch symptom site.
493- **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.
494- **Grep ALL removed names after extraction/refactoring.** Primary file "done" ≠ secondary files clean. Grep entire scope for every removed symbol before declaring complete.
495- **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.
496- **Verify ALL affected outputs, not just the first.** One build green ≠ all green. Multi-stack changes (backend/frontend/tests/docs) require verifying EVERY output.
497- **Evaluate fit before copying a nearby pattern.** Closest example ≠ matching preconditions — verify the new context shares the same constraints, base classes, scope, lifetime.
498- **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.
499- **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.
500- **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.
501- **[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.
502- **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".
503- **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.
504- **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.
505- **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.
506- **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.
507- **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.
508
509<!-- CODEX:SYNC-PROMPT-PROTOCOLS:END -->