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: Analyze an implementation plan, assess its impact on the codebase, and update specification documents accordingly.
Workflow:
- Discovery — Parse plan, extract requirements, catalog planned changes
- Knowledge Graph — Build detailed component-level impact map with test/spec mappings
- Analysis — Assess architecture impact, business logic changes, testing strategy
- Approval Gate — Present findings for explicit user approval before any spec updates
- Spec Update — Execute approved changes to specification documents
Key Rules:
- Planning-only skill -- never implement code changes
- Always collaborate and get user approval before proceeding
- Maintain bidirectional traceability between plan and specification
Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).
Implementation Plan Analysis & Specification Update
PLANNING-ONLY — Collaboration Required
DO NOT use the manual plan-mode switching tool — you are ALREADY in a planning workflow.
DO NOT implement or execute any code changes.
COLLABORATE with the user: ask decision questions, present options with recommendations.
After plan analysis, validate findings with user approval.
ASK user to confirm the analysis before any next steps.
You are to operate as an expert full-stack principal developer, software architect, and technical analyst to analyze a detailed implementation plan, perform comprehensive impact analysis, and update specification documents using the configured repository stack.
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.
Prerequisites:
PHASE 1: EXTERNAL MEMORY-DRIVEN IMPLEMENTATION PLAN ANALYSIS
Build a structured knowledge model in .ai/workspace/analysis/[plan-name].analysis.md.
PHASE 1A: INITIALIZATION AND DISCOVERY
- Initialize the analysis file with standard headings
IMPLEMENTATION PLAN COMPREHENSIVE ANALYSIS
IMPLEMENTATION_PLAN_DEEP_ANALYSIS: Thorough analysis of the implementation plan file:
Plan Structure Analysis:
- Read and parse the implementation plan completely
- Extract all planned features, requirements, and changes
- Identify implementation phases and dependencies
- Document under
## Implementation Plan Overview
Requirements Extraction:
- Parse Knowledge Graph from implementation plan
- Extract new business requirements
- Map functional and non-functional requirements
- Identify changed business workflows
- Document under
## Extracted Requirements
Planned Changes Analysis:
- Catalog all planned code changes (new files, modifications, deletions)
- Identify affected components, services, and layers
- Map file-level changes to business capabilities
- Extract integration points
- Document under
## Planned Changes Analysis
Architecture Impact Assessment:
- Analyze how changes affect overall system architecture
- Identify CQRS pattern impacts (new Commands/Queries/Events)
- Map domain entity changes and repository patterns
- Document under
## Architecture Impact Assessment
Existing Specification Analysis:
- Read and analyze existing specification document structure
- Identify current test cases, requirements, entity relationships
- Map existing test coverage to planned changes
- Document under
## Current Specification Analysis
AFFECTED_COMPONENTS_DISCOVERY: For each planned change, discover:
- Direct Dependencies
- Indirect Dependencies
- Test Coverage Impact
- API Integration Impact
- Cross-Service Communication
- Database Schema Impact
Save to ## Comprehensive File List with:
filePath, changeType, relationshipType, impactLevel
serviceContext, planContext, specificationRelevance
PHASE 1B: KNOWLEDGE GRAPH CONSTRUCTION
IMPORTANT: MUST ATTENTION DO WITH TODO LIST
For each file, document in ## Knowledge Graph:
- Standard fields plus plan-specific:
currentContent: Existing functionality (if file exists)
plannedChanges: Specific changes planned
changeImpactAnalysis: How changes affect other components
testingRequirements: New test cases needed
specificationMapping: How component maps to spec sections
testCaseImpact: Existing test cases needing modification
PHASE 1C: SPECIFICATION MAPPING ANALYSIS
- Test Case Mapping: Which existing test cases are affected
- Business Requirement Mapping: How new requirements relate to existing
- Entity Relationship Impact: Changes to entity relationships
- Workflow Integration: How new workflows integrate with existing
- Coverage Gap Analysis: Areas where new test cases needed
PHASE 1D: OVERALL ANALYSIS
Write comprehensive summary showing:
- Complete end-to-end workflows affected
- Architectural patterns impacted
- Business logic workflow changes
- Integration points affected
- Comprehensive test coverage requirements
PHASE 2: COMPREHENSIVE ANALYSIS AND PLANNING
Generate detailed analysis under these headings:
Implementation Impact Analysis: Component impact, integration points, data flow changes, architectural-pattern compliance
Business Logic Analysis: New business rules, modified workflows, validation requirements
Testing Strategy Analysis: Test coverage requirements, new test scenarios, regression testing needs
Specification Update Strategy: How to integrate new requirements, maintain traceability, preserve existing coverage
Rollback and Safety Strategy: Backup procedures, rollback plan, validation checkpoints
PHASE 3: APPROVAL GATE
CRITICAL: Present comprehensive analysis for explicit approval. DO NOT proceed without it.
PHASE 4: SPECIFICATION UPDATE EXECUTION
Once approved, execute with MANDATORY steps:
- Backup Original Specification
- Read and Parse Existing Specification
- Execute Planned Updates:
- New Requirements Integration
- Entity Relationship Updates
- Test Case Enhancement
- Traceability Matrix Updates
- Coverage Analysis Updates
- Maintain Specification Structure
- Quality Assurance Validation
SUCCESS VALIDATION
Verify under ## Specification Validation:
- Requirements Traceability: All plan requirements mapped
- Test Coverage Validation: All changes covered by tests
- Business Workflow Validation: End-to-end workflows documented
- Integration Testing Coverage: Cross-service impacts covered
- Regression Prevention: Existing functionality protected
Plan Analysis Guidelines
- Plan-Driven Analysis: Base all analysis on the detailed implementation plan
- Specification Structure Preservation: Maintain standardized specification format
- Comprehensive Impact Assessment: Analyze direct and indirect effects
- End-to-End Workflow Mapping: Understand affected business processes
- Enterprise Architecture Awareness: Respect the project's architectural patterns
- Quality-Focused Testing: Create comprehensive test specifications
- Specification Completeness: Ensure full traceability
- Risk Assessment and Mitigation: Identify risks and provide rollback strategies
- Bidirectional Traceability: Maintain clear mapping between plan and spec
- Coverage Preservation: Maintain existing test coverage while adding new
Related
REMINDER — Planning-Only Skill
DO NOT use manual plan-mode switching tool.
DO NOT start implementing.
ALWAYS validate with user approval after analysis.
ASK user to confirm findings before any execution begins.
ASK user for clarification when multiple approaches exist.
[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.
Prerequisites:
docs/specs/ — Test specifications by module (read existing TCs to include test strategy in plan)
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.
Understand Code First — HARD-GATE: Do NOT write, plan, or fix until you READ existing code.
- Search 3+ similar patterns (
grep/glob) — cite file:line evidence
- Read existing files in target area — understand structure, base classes, conventions
- Run
python .claude/scripts/code_graph trace <file> --direction both --json when .code-graph/graph.db exists
- Map dependencies via
connections or callers_of — know what depends on your target
- Write investigation to
.ai/workspace/analysis/ for non-trivial tasks (3+ files)
- Re-read analysis file before implementing — never work from memory alone. — why: long context drifts from the file; the file is ground truth
- NEVER invent new patterns when existing ones work — match exactly or document deviation. — why: divergent patterns fragment the codebase and slow every future reader
BLOCKED until: - [ ] Read target files - [ ] Grep 3+ patterns - [ ] Graph trace (if graph.db exists) - [ ] Assumptions verified with evidence
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: [...]."
Nested Task Expansion Contract — For workflow-step invocation, the [Workflow] ... row is only a parent container; the child skill still creates visible phase tasks.
- Call the current task list first. If a matching active parent workflow row exists, set
nested=true and record parentTaskId; otherwise run standalone.
- Create one task per declared phase before phase work. When nested, prefix subjects
[N.M] $skill-name — phase.
- When nested, link the parent with
TaskUpdate(parentTaskId, addBlockedBy: [childIds]).
- Orchestrators must pre-expand a child skill's phase list and link the workflow row before invoking that child skill or sub-agent.
- Mark exactly one child
in_progress before work and completed immediately after evidence is written.
- Complete the parent only after all child tasks are completed or explicitly cancelled with reason.
Blocked until: the current task list done, child phases created, parent linked when nested, first child marked in_progress.
Project Reference Docs Gate — Run after task-tracking bootstrap and before target/source file reads, grep, edits, or analysis. Project docs override generic framework assumptions.
- Identify scope: file types, domain area, and operation.
- Read
docs/project-config.json first — the project's machine-readable map. It is the single source of truth for THIS repo (modules/paths, framework + search keywords, test/E2E/integration run-commands, design system, architecture rules, workflow patterns); ground exact paths, run-commands, and conventions on it before investigating, planning, or coding — never assume framework defaults (CLAUDE.md + reference docs are derived from it). If it — or the docs index, lessons.md, CLAUDE.md, AGENTS.md, or any required reference doc — is missing or stale, auto-run $project-init or the narrow route ($project-config, $docs-init, $scan-all, $scan --target=<key>, $claude-md-init) first; if Codex mirrors or AGENTS.md are stale, ask the user to run $sync-codex (never auto-run it).
- Required docs by trigger: always
docs/project-reference/lessons.md; doc lookup docs-index-reference.md; review code-review-rules.md; backend/CQRS/API backend-patterns-reference.md; domain/entity domain-entities-reference.md; frontend/UI frontend-patterns-reference.md; styles/design scss-styling-guide.md + design-system/design-system-canonical.md; integration tests integration-test-reference.md; E2E e2e-test-reference.md; feature docs/specs feature-spec-reference.md + spec-system-reference.md + spec-principles.md; behavior/public-contract/spec-test-code sync workflow-spec-test-code-cycle-reference.md; derived spec index/ERD/reimplementation guides spec-system-reference.md + source Feature Specs under docs/specs/; architecture/new area project-structure-reference.md.
- Read every required doc, then before target work state:
Reference docs read: ... | Not applicable: ....
Ready when: scope evaluated, docs/project-config.json consulted, required docs checked/read or setup route completed, lessons.md confirmed, citation emitted.
Task Tracking & External Report Persistence — Bootstrap this before execution; then run project-reference doc prefetch before target/source work.
- Create a small task breakdown before target file reads, grep, edits, or analysis. On context loss, inspect the current task list first.
- Mark one task
in_progress before work and completed immediately after evidence; never batch transitions.
- For plan/review work, create
plans/reports/{skill}-{YYMMDD}-{HHmm}-{slug}.md before first finding.
- Append findings after each file/section/decision and synthesize from the report file at the end.
- Final output cites
Full report: plans/reports/{filename}.
Blocked until: task breakdown exists, report path declared for plan/review work, first finding persisted before the next finding.
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.
Sequential Thinking Protocol — Structured multi-step reasoning for complex/ambiguous work. Use when planning, reviewing, debugging, or refining ideas where one-shot reasoning is unsafe.
Trigger when: complex problem decomposition · adaptive plans needing revision · analysis with course correction · unclear/emerging scope · multi-step solutions · hypothesis-driven debugging · cross-cutting trade-off evaluation.
Format (explicit mode — visible thought trail):
Thought N/M: [aspect] — one aspect per thought, state assumptions/uncertainty
Thought N/M [REVISION of Thought K]: ... — when prior reasoning invalidated; state Original / Why revised / Impact
Thought N/M [BRANCH A from Thought K]: ... — explore alternative; converge with decision rationale
Thought N/M [HYPOTHESIS]: ... then [VERIFICATION]: ... — test before acting
Thought N/N [FINAL] — only when verified, all critical aspects addressed, confidence >80%
Mandatory closers: Confidence % stated · Assumptions listed · Open questions surfaced · Next action concrete.
Stop conditions: confidence <80% on any critical decision → escalate by asking the user directly · ≥3 revisions on same thought → re-frame the problem · branch count >3 → split into sub-task.
Implicit mode: apply methodology internally without visible markers when adding markers would clutter the response (routine work where reasoning aids accuracy).
Deep-dive: see $sequential-thinking skill (.claude/skills/sequential-thinking/SKILL.md) for worked examples (API design, debugging, architecture), advanced techniques (spiral refinement, hypothesis testing, convergence), and meta-strategies (uncertainty handling, revision cascades).
Plan Quality — Every plan phase MUST ATTENTION include test specifications.
- Add
## Test Specifications section with TC-{FEATURE}-{NNN} IDs to every phase file
- Map every functional requirement to ≥1 TC (or explicit
TBD with rationale)
- TC IDs follow
TC-{FEATURE}-{NNN} format — reference by ID, never embed full content
- Before any new workflow step: call the current task list and re-read the phase file
- On context compaction: call the current task list FIRST — never create duplicate tasks
- Verify TC satisfaction per phase before marking complete (evidence must be
file:line, not TBD)
Mode: TDD-first → reference existing TCs with Evidence: TBD. Implement-first → use TBD → $spec [mode=tests] fills after.
Iterative Phase Quality — Score complexity BEFORE planning.
Complexity signals: >5 files +2, cross-service +3, new pattern +2, DB migration +2
Score >=6 → MUST ATTENTION decompose into phases. Each phase:
- ≤5 files modified
- ≤3h effort
- Follows cycle: plan → implement → review → fix → verify
- Start Phase N+1 only after Phase N passes VERIFY — why: building on an unverified phase compounds errors downstream
Phase success = all TCs pass + code-reviewer agent approves + no CRITICAL findings.
- MANDATORY IMPORTANT MUST ATTENTION include
## Test Specifications with TC IDs per phase. Call the current task list before creating new tasks.
- MANDATORY IMPORTANT MUST ATTENTION search 3+ existing patterns and read code BEFORE any modification. Run graph trace when graph.db exists.
- MANDATORY IMPORTANT MUST ATTENTION cite
file:line evidence for every claim. Confidence >80% to act, <60% = do NOT recommend.
- MANDATORY IMPORTANT MUST ATTENTION score complexity first. Score >=6 → decompose. Each phase: plan → implement → review → fix → verify. No skipping.
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 sequential-thinking — multi-step Thought N/M, REVISION/BRANCH/HYPOTHESIS markers, confidence % closer; see $sequential-thinking skill.
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.
- MANDATORY Bootstrap task tracking before target work; transition one task at a time.
- MANDATORY Persist plan/review findings to
plans/reports/ incrementally and synthesize from disk.
- MANDATORY Before investigating, planning, or coding, read
docs/project-config.json (the project map: modules/paths, run-commands, conventions, architecture/workflow rules) + the required project-reference docs, and cite Reference docs read: ....
- MANDATORY Always include
lessons.md; project config + conventions override generic framework defaults.
- MANDATORY If project config, root instruction files, or any required reference doc is missing or stale, auto-run
$project-init or the narrow lower-level route before ordinary project-specific work.
- MANDATORY Parent workflow rows do not replace child phase tracking; expand phases and link the parent when nested.
- MANDATORY Orchestrators pre-expand child skill phases before invocation; use
[N.M] $skill-name — phase prefixes and one-in_progress discipline.
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
IMPORTANT MUST ATTENTION — Protocols in force (concise digest of the SYNC/shared blocks this skill carries):
AI Mistake Prevention: verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
Understand Code First: read code and grep 3+ patterns before modifying.
Evidence: cite file:line; confidence >80% to act.
Nested Task Creation: expand child phases, link parent when nested.
Project Reference Docs: read required project docs before target work.
Task Tracking & External Report: bootstrap tasks, persist findings to plans/reports/.
Critical Thinking: traced proof per claim, skeptical of own confidence.
Sequential Thinking: multi-step Thought N/M with confidence closer.
Plan Quality: ## Test Specifications with TC IDs per phase.
Iterative Phase Quality: score complexity, decompose at >=6, plan→implement→review→fix→verify.
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 include Test Specifications section and story_points in plan frontmatter
[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 dat
…(truncated)
1---2name: plan-analysis3description: [Planning] Use when the user provides an implementation plan file and asks to analyze it, assess impact, update specifications, or verify planned changes.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:** Analyze an implementation plan, assess its impact on the codebase, and update specification documents accordingly.
52
53**Workflow:**
54
551. **Discovery** — Parse plan, extract requirements, catalog planned changes
562. **Knowledge Graph** — Build detailed component-level impact map with test/spec mappings
573. **Analysis** — Assess architecture impact, business logic changes, testing strategy
584. **Approval Gate** — Present findings for explicit user approval before any spec updates
595. **Spec Update** — Execute approved changes to specification documents
60
61**Key Rules:**
62
63- Planning-only skill -- never implement code changes
64- Always collaborate and get user approval before proceeding
65- Maintain bidirectional traceability between plan and specification
66
67**Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).**
68
69# Implementation Plan Analysis & Specification Update
70
71## PLANNING-ONLY — Collaboration Required
72
73> **DO NOT** use the manual plan-mode switching tool — you are ALREADY in a planning workflow.
74> **DO NOT** implement or execute any code changes.
75> **COLLABORATE** with the user: ask decision questions, present options with recommendations.
76> After plan analysis, validate findings with user approval.
77> **ASK** user to confirm the analysis before any next steps.
78
79You are to operate as an expert full-stack principal developer, software architect, and technical analyst to analyze a detailed implementation plan, perform comprehensive impact analysis, and update specification documents using the configured repository stack.
80
81**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.
82
83**Prerequisites:**
84
85---
86
87## PHASE 1: EXTERNAL MEMORY-DRIVEN IMPLEMENTATION PLAN ANALYSIS
88
89Build a structured knowledge model in `.ai/workspace/analysis/[plan-name].analysis.md`.
90
91### PHASE 1A: INITIALIZATION AND DISCOVERY
92
931. **Initialize** the analysis file with standard headings
94
95### IMPLEMENTATION PLAN COMPREHENSIVE ANALYSIS
96
97**IMPLEMENTATION_PLAN_DEEP_ANALYSIS**: Thorough analysis of the implementation plan file:
98
991. **Plan Structure Analysis**:
100 - Read and parse the implementation plan completely
101 - Extract all planned features, requirements, and changes
102 - Identify implementation phases and dependencies
103 - Document under `## Implementation Plan Overview`
104
1052. **Requirements Extraction**:
106 - Parse Knowledge Graph from implementation plan
107 - Extract new business requirements
108 - Map functional and non-functional requirements
109 - Identify changed business workflows
110 - Document under `## Extracted Requirements`
111
1123. **Planned Changes Analysis**:
113 - Catalog all planned code changes (new files, modifications, deletions)
114 - Identify affected components, services, and layers
115 - Map file-level changes to business capabilities
116 - Extract integration points
117 - Document under `## Planned Changes Analysis`
118
1194. **Architecture Impact Assessment**:
120 - Analyze how changes affect overall system architecture
121 - Identify CQRS pattern impacts (new Commands/Queries/Events)
122 - Map domain entity changes and repository patterns
123 - Document under `## Architecture Impact Assessment`
124
1255. **Existing Specification Analysis**:
126 - Read and analyze existing specification document structure
127 - Identify current test cases, requirements, entity relationships
128 - Map existing test coverage to planned changes
129 - Document under `## Current Specification Analysis`
130
131**AFFECTED_COMPONENTS_DISCOVERY**: For each planned change, discover:
132
133- Direct Dependencies
134- Indirect Dependencies
135- Test Coverage Impact
136- API Integration Impact
137- Cross-Service Communication
138- Database Schema Impact
139
140Save to `## Comprehensive File List` with:
141
142- `filePath`, `changeType`, `relationshipType`, `impactLevel`
143- `serviceContext`, `planContext`, `specificationRelevance`
144
145### PHASE 1B: KNOWLEDGE GRAPH CONSTRUCTION
146
147**IMPORTANT: MUST ATTENTION DO WITH TODO LIST**
148
149For each file, document in `## Knowledge Graph`:
150
151- Standard fields plus plan-specific:
152- `currentContent`: Existing functionality (if file exists)
153- `plannedChanges`: Specific changes planned
154- `changeImpactAnalysis`: How changes affect other components
155- `testingRequirements`: New test cases needed
156- `specificationMapping`: How component maps to spec sections
157- `testCaseImpact`: Existing test cases needing modification
158
159### PHASE 1C: SPECIFICATION MAPPING ANALYSIS
160
161- **Test Case Mapping**: Which existing test cases are affected
162- **Business Requirement Mapping**: How new requirements relate to existing
163- **Entity Relationship Impact**: Changes to entity relationships
164- **Workflow Integration**: How new workflows integrate with existing
165- **Coverage Gap Analysis**: Areas where new test cases needed
166
167### PHASE 1D: OVERALL ANALYSIS
168
169Write comprehensive summary showing:
170
171- Complete end-to-end workflows affected
172- Architectural patterns impacted
173- Business logic workflow changes
174- Integration points affected
175- Comprehensive test coverage requirements
176
177---
178
179## PHASE 2: COMPREHENSIVE ANALYSIS AND PLANNING
180
181Generate detailed analysis under these headings:
182
1831. **Implementation Impact Analysis**: Component impact, integration points, data flow changes, architectural-pattern compliance
184
1852. **Business Logic Analysis**: New business rules, modified workflows, validation requirements
186
1873. **Testing Strategy Analysis**: Test coverage requirements, new test scenarios, regression testing needs
188
1894. **Specification Update Strategy**: How to integrate new requirements, maintain traceability, preserve existing coverage
190
1915. **Rollback and Safety Strategy**: Backup procedures, rollback plan, validation checkpoints
192
193---
194
195## PHASE 3: APPROVAL GATE
196
197**CRITICAL**: Present comprehensive analysis for explicit approval. **DO NOT** proceed without it.
198
199---
200
201## PHASE 4: SPECIFICATION UPDATE EXECUTION
202
203Once approved, execute with MANDATORY steps:
204
2051. **Backup Original Specification**
2062. **Read and Parse Existing Specification**
2073. **Execute Planned Updates**:
208 - New Requirements Integration
209 - Entity Relationship Updates
210 - Test Case Enhancement
211 - Traceability Matrix Updates
212 - Coverage Analysis Updates
2134. **Maintain Specification Structure**
2145. **Quality Assurance Validation**
215
216---
217
218## SUCCESS VALIDATION
219
220Verify under `## Specification Validation`:
221
222- **Requirements Traceability**: All plan requirements mapped
223- **Test Coverage Validation**: All changes covered by tests
224- **Business Workflow Validation**: End-to-end workflows documented
225- **Integration Testing Coverage**: Cross-service impacts covered
226- **Regression Prevention**: Existing functionality protected
227
228---
229
230## Plan Analysis Guidelines
231
232- **Plan-Driven Analysis**: Base all analysis on the detailed implementation plan
233- **Specification Structure Preservation**: Maintain standardized specification format
234- **Comprehensive Impact Assessment**: Analyze direct and indirect effects
235- **End-to-End Workflow Mapping**: Understand affected business processes
236- **Enterprise Architecture Awareness**: Respect the project's architectural patterns
237- **Quality-Focused Testing**: Create comprehensive test specifications
238- **Specification Completeness**: Ensure full traceability
239- **Risk Assessment and Mitigation**: Identify risks and provide rollback strategies
240- **Bidirectional Traceability**: Maintain clear mapping between plan and spec
241- **Coverage Preservation**: Maintain existing test coverage while adding new
242
243## Related
244
245- `plan`
246- `workflow-feature`
247
248- **MANDATORY FINAL TASKS:** After creating all planning todo tasks, ALWAYS add these three final tasks:
249 1. **Task: "Write test specifications for each phase"** — Add `## Test Specifications` with TC-{FEATURE}-{NNN} IDs to every phase file. Use `$spec [mode=tests]` if feature docs exist. Use `Evidence: TBD` for TDD-first mode.
250 2. **Task: "Run $plan-validate"** — Trigger `$plan-validate` skill to interview the user with critical questions and validate plan assumptions
251 3. **Task: "Run $plan-review"** — Trigger `$plan-review` skill to auto-review plan for validity, correctness, and best practices
252
253## REMINDER — Planning-Only Skill
254
255> **DO NOT** use manual plan-mode switching tool.
256> **DO NOT** start implementing.
257> **ALWAYS** validate with user approval after analysis.
258> **ASK** user to confirm findings before any execution begins.
259> **ASK** user for clarification when multiple approaches exist.
260
261---
262
263> **[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.
264
265**Prerequisites:**
266
267- `docs/specs/` — Test specifications by module (read existing TCs to include test strategy in plan)
268
269<!-- SYNC:ai-mistake-prevention -->
270
271> **AI Mistake Prevention** — Failure modes to avoid on every task:
272>
273> **Re-read files after context changes.** Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
274> **Verify generated content against source evidence.** AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
275> **Check downstream references before deleting or renaming.** Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
276> **Trace the full impact chain after edits.** Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
277> **Verify ALL affected outputs, not just the first.** One green check is not all green checks; validate every output surface the change can affect.
278> **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.
279> **Surface ambiguity before acting — don't pick silently.** Multiple valid interpretations require an explicit question or stated assumption with risk.
280> **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.
281> **Keep shared guidance role-relevant.** Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
282
283<!-- /SYNC:ai-mistake-prevention -->
284
285<!-- SYNC:understand-code-first -->
286
287> **Understand Code First** — HARD-GATE: Do NOT write, plan, or fix until you READ existing code.
288>
289> 1. Search 3+ similar patterns (`grep`/`glob`) — cite `file:line` evidence
290> 2. Read existing files in target area — understand structure, base classes, conventions
291> 3. Run `python .claude/scripts/code_graph trace <file> --direction both --json` when `.code-graph/graph.db` exists
292> 4. Map dependencies via `connections` or `callers_of` — know what depends on your target
293> 5. Write investigation to `.ai/workspace/analysis/` for non-trivial tasks (3+ files)
294> 6. Re-read analysis file before implementing — never work from memory alone. — why: long context drifts from the file; the file is ground truth
295> 7. NEVER invent new patterns when existing ones work — match exactly or document deviation. — why: divergent patterns fragment the codebase and slow every future reader
296>
297> **BLOCKED until:** `- [ ]` Read target files `- [ ]` Grep 3+ patterns `- [ ]` Graph trace (if graph.db exists) `- [ ]` Assumptions verified with evidence
298
299<!-- /SYNC:understand-code-first -->
300
301<!-- SYNC:evidence-based-reasoning -->
302
303> **Evidence-Based Reasoning** — Speculation is FORBIDDEN. Every claim needs proof.
304>
305> 1. Cite `file:line`, grep results, or framework docs for EVERY claim
306> 2. Declare confidence: >80% act freely, 60-80% verify first, <60% DO NOT recommend
307> 3. Cross-service validation required for architectural changes
308> 4. "I don't have enough evidence" is valid and expected output
309>
310> **BLOCKED until:** `- [ ]` Evidence file path (`file:line`) `- [ ]` Grep search performed `- [ ]` 3+ similar patterns found `- [ ]` Confidence level stated
311>
312> **Forbidden without proof:** "obviously", "I think", "should be", "probably", "this is because"
313> **If incomplete →** output: `"Insufficient evidence. Verified: [...]. Not verified: [...]."`
314
315<!-- /SYNC:evidence-based-reasoning -->
316
317<!-- SYNC:nested-task-creation -->
318
319> **Nested Task Expansion Contract** — For workflow-step invocation, the `[Workflow] ...` row is only a parent container; the child skill still creates visible phase tasks.
320>
321> 1. Call the current task list first. If a matching active parent workflow row exists, set `nested=true` and record `parentTaskId`; otherwise run standalone.
322> 2. Create one task per declared phase before phase work. When nested, prefix subjects `[N.M] $skill-name — phase`.
323> 3. When nested, link the parent with `TaskUpdate(parentTaskId, addBlockedBy: [childIds])`.
324> 4. Orchestrators must pre-expand a child skill's phase list and link the workflow row before invoking that child skill or sub-agent.
325> 5. Mark exactly one child `in_progress` before work and `completed` immediately after evidence is written.
326> 6. Complete the parent only after all child tasks are completed or explicitly cancelled with reason.
327>
328> **Blocked until:** the current task list done, child phases created, parent linked when nested, first child marked `in_progress`.
329
330<!-- /SYNC:nested-task-creation -->
331
332<!-- SYNC:project-reference-docs-guide -->
333
334> **Project Reference Docs Gate** — Run after task-tracking bootstrap and before target/source file reads, grep, edits, or analysis. Project docs override generic framework assumptions.
335>
336> 1. Identify scope: file types, domain area, and operation.
337> 2. **Read `docs/project-config.json` first — the project's machine-readable map.** It is the single source of truth for THIS repo (modules/paths, framework + search keywords, test/E2E/integration run-commands, design system, architecture rules, workflow patterns); ground exact paths, run-commands, and conventions on it **before investigating, planning, or coding** — never assume framework defaults (`CLAUDE.md` + reference docs are derived from it). If it — or the docs index, `lessons.md`, `CLAUDE.md`, `AGENTS.md`, or any required reference doc — is missing or stale, auto-run `$project-init` or the narrow route (`$project-config`, `$docs-init`, `$scan-all`, `$scan --target=<key>`, `$claude-md-init`) first; if Codex mirrors or `AGENTS.md` are stale, ask the user to run `$sync-codex` (never auto-run it).
338> 3. Required docs by trigger: always `docs/project-reference/lessons.md`; doc lookup `docs-index-reference.md`; review `code-review-rules.md`; backend/CQRS/API `backend-patterns-reference.md`; domain/entity `domain-entities-reference.md`; frontend/UI `frontend-patterns-reference.md`; styles/design `scss-styling-guide.md` + `design-system/design-system-canonical.md`; integration tests `integration-test-reference.md`; E2E `e2e-test-reference.md`; feature docs/specs `feature-spec-reference.md` + `spec-system-reference.md` + `spec-principles.md`; behavior/public-contract/spec-test-code sync `workflow-spec-test-code-cycle-reference.md`; derived spec index/ERD/reimplementation guides `spec-system-reference.md` + source Feature Specs under `docs/specs/`; architecture/new area `project-structure-reference.md`.
339> 4. Read every required doc, then before target work state: `Reference docs read: ... | Not applicable: ...`.
340>
341> **Ready when:** scope evaluated, `docs/project-config.json` consulted, required docs checked/read or setup route completed, `lessons.md` confirmed, citation emitted.
342
343<!-- /SYNC:project-reference-docs-guide -->
344
345<!-- SYNC:task-tracking-external-report -->
346
347> **Task Tracking & External Report Persistence** — Bootstrap this before execution; then run project-reference doc prefetch before target/source work.
348>
349> 1. Create a small task breakdown before target file reads, grep, edits, or analysis. On context loss, inspect the current task list first.
350> 2. Mark one task `in_progress` before work and `completed` immediately after evidence; never batch transitions.
351> 3. For plan/review work, create `plans/reports/{skill}-{YYMMDD}-{HHmm}-{slug}.md` before first finding.
352> 4. Append findings after each file/section/decision and synthesize from the report file at the end.
353> 5. Final output cites `Full report: plans/reports/{filename}`.
354>
355> **Blocked until:** task breakdown exists, report path declared for plan/review work, first finding persisted before the next finding.
356
357<!-- /SYNC:task-tracking-external-report -->
358
359<!-- SYNC:critical-thinking-mindset -->
360
361> **Critical Thinking Mindset** — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
362> **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.
363
364<!-- /SYNC:critical-thinking-mindset -->
365
366<!-- SYNC:sequential-thinking-protocol -->
367
368> **Sequential Thinking Protocol** — Structured multi-step reasoning for complex/ambiguous work. Use when planning, reviewing, debugging, or refining ideas where one-shot reasoning is unsafe.
369>
370> **Trigger when:** complex problem decomposition · adaptive plans needing revision · analysis with course correction · unclear/emerging scope · multi-step solutions · hypothesis-driven debugging · cross-cutting trade-off evaluation.
371>
372> **Format (explicit mode — visible thought trail):**
373>
374> 1. `Thought N/M: [aspect]` — one aspect per thought, state assumptions/uncertainty
375> 2. `Thought N/M [REVISION of Thought K]: ...` — when prior reasoning invalidated; state Original / Why revised / Impact
376> 3. `Thought N/M [BRANCH A from Thought K]: ...` — explore alternative; converge with decision rationale
377> 4. `Thought N/M [HYPOTHESIS]: ...` then `[VERIFICATION]: ...` — test before acting
378> 5. `Thought N/N [FINAL]` — only when verified, all critical aspects addressed, confidence >80%
379>
380> **Mandatory closers:** Confidence % stated · Assumptions listed · Open questions surfaced · Next action concrete.
381>
382> **Stop conditions:** confidence <80% on any critical decision → escalate by asking the user directly · ≥3 revisions on same thought → re-frame the problem · branch count >3 → split into sub-task.
383>
384> **Implicit mode:** apply methodology internally without visible markers when adding markers would clutter the response (routine work where reasoning aids accuracy).
385>
386> **Deep-dive:** see `$sequential-thinking` skill (`.claude/skills/sequential-thinking/SKILL.md`) for worked examples (API design, debugging, architecture), advanced techniques (spiral refinement, hypothesis testing, convergence), and meta-strategies (uncertainty handling, revision cascades).
387
388<!-- /SYNC:sequential-thinking-protocol -->
389
390<!-- SYNC:plan-quality -->
391
392> **Plan Quality** — Every plan phase MUST ATTENTION include test specifications.
393>
394> 1. Add `## Test Specifications` section with TC-{FEATURE}-{NNN} IDs to every phase file
395> 2. Map every functional requirement to ≥1 TC (or explicit `TBD` with rationale)
396> 3. TC IDs follow `TC-{FEATURE}-{NNN}` format — reference by ID, never embed full content
397> 4. Before any new workflow step: call the current task list and re-read the phase file
398> 5. On context compaction: call the current task list FIRST — never create duplicate tasks
399> 6. Verify TC satisfaction per phase before marking complete (evidence must be `file:line`, not TBD)
400>
401> **Mode:** TDD-first → reference existing TCs with `Evidence: TBD`. Implement-first → use TBD → `$spec [mode=tests]` fills after.
402
403<!-- /SYNC:plan-quality -->
404
405<!-- SYNC:iterative-phase-quality -->
406
407> **Iterative Phase Quality** — Score complexity BEFORE planning.
408>
409> **Complexity signals:** >5 files +2, cross-service +3, new pattern +2, DB migration +2
410> **Score >=6 →** MUST ATTENTION decompose into phases. Each phase:
411>
412> - ≤5 files modified
413> - ≤3h effort
414> - Follows cycle: plan → implement → review → fix → verify
415> - Start Phase N+1 only after Phase N passes VERIFY — why: building on an unverified phase compounds errors downstream
416>
417> **Phase success = all TCs pass + code-reviewer agent approves + no CRITICAL findings.**
418
419<!-- /SYNC:iterative-phase-quality -->
420
421<!-- SYNC:plan-quality:reminder -->
422
423- **MANDATORY IMPORTANT MUST ATTENTION** include `## Test Specifications` with TC IDs per phase. Call the current task list before creating new tasks.
424 <!-- /SYNC:plan-quality:reminder -->
425
426<!-- SYNC:understand-code-first:reminder -->
427
428- **MANDATORY IMPORTANT MUST ATTENTION** search 3+ existing patterns and read code BEFORE any modification. Run graph trace when graph.db exists.
429 <!-- /SYNC:understand-code-first:reminder -->
430
431<!-- SYNC:evidence-based-reasoning:reminder -->
432
433- **MANDATORY IMPORTANT MUST ATTENTION** cite `file:line` evidence for every claim. Confidence >80% to act, <60% = do NOT recommend.
434 <!-- /SYNC:evidence-based-reasoning:reminder -->
435
436<!-- SYNC:iterative-phase-quality:reminder -->
437
438- **MANDATORY IMPORTANT MUST ATTENTION** score complexity first. Score >=6 → decompose. Each phase: plan → implement → review → fix → verify. No skipping.
439 <!-- /SYNC:iterative-phase-quality:reminder -->
440
441<!-- SYNC:critical-thinking-mindset:reminder -->
442
443**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.
444
445<!-- /SYNC:critical-thinking-mindset:reminder -->
446
447<!-- SYNC:sequential-thinking-protocol:reminder -->
448
449**MUST ATTENTION** apply sequential-thinking — multi-step Thought N/M, REVISION/BRANCH/HYPOTHESIS markers, confidence % closer; see `$sequential-thinking` skill.
450
451<!-- /SYNC:sequential-thinking-protocol:reminder -->
452
453<!-- SYNC:ai-mistake-prevention:reminder -->
454
455**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.
456
457<!-- /SYNC:ai-mistake-prevention:reminder -->
458
459<!-- SYNC:task-tracking-external-report:reminder -->
460
461- **MANDATORY** Bootstrap task tracking before target work; transition one task at a time.
462- **MANDATORY** Persist plan/review findings to `plans/reports/` incrementally and synthesize from disk.
463
464<!-- /SYNC:task-tracking-external-report:reminder -->
465
466<!-- SYNC:project-reference-docs-guide:reminder -->
467
468- **MANDATORY** Before investigating, planning, or coding, read `docs/project-config.json` (the project map: modules/paths, run-commands, conventions, architecture/workflow rules) + the required project-reference docs, and cite `Reference docs read: ...`.
469- **MANDATORY** Always include `lessons.md`; project config + conventions override generic framework defaults.
470- **MANDATORY** If project config, root instruction files, or any required reference doc is missing or stale, auto-run `$project-init` or the narrow lower-level route before ordinary project-specific work.
471
472<!-- /SYNC:project-reference-docs-guide:reminder -->
473
474<!-- SYNC:nested-task-creation:reminder -->
475
476- **MANDATORY** Parent workflow rows do not replace child phase tracking; expand phases and link the parent when nested.
477- **MANDATORY** Orchestrators pre-expand child skill phases before invocation; use `[N.M] $skill-name — phase` prefixes and one-`in_progress` discipline.
478
479<!-- /SYNC:nested-task-creation:reminder -->
480
481<!-- SYNC:project-protocol-overlay -->
482
483> **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`.
484>
485> 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.
486
487<!-- /SYNC:project-protocol-overlay -->
488
489<!-- SYNC:project-protocol-overlay:reminder -->
490
491**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.
492
493<!-- /SYNC:project-protocol-overlay:reminder -->
494
495## Closing Reminders
496
497**IMPORTANT MUST ATTENTION — Protocols in force (concise digest of the SYNC/shared blocks this skill carries):**
498
499- **AI Mistake Prevention:** verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
500- **Understand Code First:** read code and grep 3+ patterns before modifying.
501- **Evidence:** cite `file:line`; confidence >80% to act.
502- **Nested Task Creation:** expand child phases, link parent when nested.
503- **Project Reference Docs:** read required project docs before target work.
504- **Task Tracking & External Report:** bootstrap tasks, persist findings to `plans/reports/`.
505- **Critical Thinking:** traced proof per claim, skeptical of own confidence.
506- **Sequential Thinking:** multi-step Thought N/M with confidence closer.
507- **Plan Quality:** `## Test Specifications` with TC IDs per phase.
508- **Iterative Phase Quality:** score complexity, decompose at >=6, plan→implement→review→fix→verify.
509
510- **MANDATORY IMPORTANT MUST ATTENTION** break work into small todo tasks using task tracking BEFORE starting
511- **MANDATORY IMPORTANT MUST ATTENTION** search codebase for 3+ similar patterns before creating new code
512- **MANDATORY IMPORTANT MUST ATTENTION** cite `file:line` evidence for every claim (confidence >80% to act)
513- **MANDATORY IMPORTANT MUST ATTENTION** add a final review todo task to verify work quality
514- **MANDATORY IMPORTANT MUST ATTENTION** include Test Specifications section and story_points in plan frontmatter
515
516**[TASK-PLANNING]** Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using task tracking.
517
518<!-- CODEX:SYNC-PROMPT-PROTOCOLS:START -->
519
520## Hookless Prompt Protocol Mirror (Auto-Synced)
521
522Source: `.claude/.ck.json` + `.claude/skills/shared/sync-inline-versions.md` (`:full` blocks) + `.claude/scripts/lib/hookless-prompt-protocol.cjs`
523
524## [WORKFLOW-EXECUTION-PROTOCOL] [BLOCKING] Workflow Execution Protocol — MANDATORY IMPORTANT MUST CRITICAL. Do not skip for any reason.
525
526**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.
527
5281. **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.
5292. **ANALYZE:** Choose the best option: execute directly, invoke a skill, activate a standard workflow, or compose a custom step combination.
5303. **AUTO-SELECT:** Pick the best option yourself. Do not ask the user to choose between direct execution, skill, standard workflow, or custom workflow.
5314. **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.
5325. **CREATE TASKS:** task tracking for ALL workflow/skill/custom steps before execution when the selected path has multiple steps.
5336. **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.
5347. **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)
535
536## Shared AI-SDD Protocol Markers
537
538Source: `.claude/skills/shared/sync-inline-versions.md`
539
540## SYNC:ai-sdd-artifact-contract
541
542> **AI-SDD Artifact Contract** — Shared spec-driven development rules stay portable and source-owned.
543>
544> 1. Keep reusable AI-SDD principles in `.claude`; put repository-specific paths, commands, owners, products, and formats in project config/reference docs.
545> 2. Preserve cycle: `spec -> plan -> tasks -> implement -> verify -> update spec/docs`.
546> 3. Trace every requirement or invariant through decision, task, TC/test, source evidence, and docs/spec update.
547> 4. Treat code-to-spec extraction as reference-only until accepted by the canonical spec owner.
548> 5. Any supported AI tool may plan, implement, review, or verify with synced context; using multiple tools is optional.
549> 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
550> 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.
551>
552> **Active reference:** `shared/sdd-artifact-contract.md` in the active skills root.
553
554---
555
556## SYNC:ai-sdd-artifact-contract:reminder
557
558- **MANDATORY** Apply `shared/sdd-artifact-contract.md`; keep reusable AI-SDD in `.claude` and local rules in project docs.
559- **MANDATORY** Code-to-spec extraction is reference-only until canonical acceptance; any supported AI tool may execute with synced context.
560- **MANDATORY** Update `.claude` source before syncing generated mirrors; do not manually edit `.agents`, `.codex`, or `AGENTS.md`.
561- **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.
562 **[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.
563
564## [LESSON-LEARNED-REMINDER] [BLOCKING] Task Planning & Continuous Improvement — MANDATORY. Do not skip.
565
566Break work into small tasks (task tracking) before starting. Add final task: "Analyze AI mistakes & lessons learned".
567
568**Extract lessons — ROOT CAUSE ONLY, not symptom fixes:**
569
5701. Name the FAILURE MODE (reasoning/assumption failure), not symptom — "assumed API existed without reading source" not "used wrong enum value".
5712. Generality test: does this failure mode apply to ≥3 contexts/codebases? If not, abstract one level up.
5723. Write as a universal rule — strip project-specific names/paths/classes. Useful on any codebase.
5734. Consolidate: multiple mistakes sharing one failure mode → ONE lesson.
5745. **Recurrence gate:** "Would this recur in future session WITHOUT this reminder?" — No → skip `$learn`.
5756. **Auto-fix gate:** "Could `$code-review`/`$code-simplifier`/`$security-review`/`$lint` catch this?" — Yes → improve review skill instead.
5767. BOTH gates pass → ask user to run `$learn`.
577 **[CRITICAL-THINKING-MINDSET]** Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
578 **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.
579 **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.
580 **Goal-driven execution:** Define success criteria first, loop until verified, and stop only when observable checks pass.
581 **Tests verify intent:** Tests must protect business rules/invariants and fail when the protected intent breaks, not only mirror current behavior.
582
583## Common AI Mistake Prevention (System Lessons)
584
585- **Re-read files after context compaction.** Edit requires prior Read in same context; compaction wipes read state. Re-read before editing.
586- **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.
587- **Check downstream references before deleting.** Deletions cascade doc/code staleness. Map referencing files before removal.
588- **After memory loss, check existing state before creating new.** Compaction wipes prior-work memory. Query current state to resume — never blindly duplicate.
589- **Verify AI-generated content against actual code.** AI hallucinates APIs, class names, method signatures. Grep to confirm existence before documenting/referencing.
590- **Trace full dependency chain after edits.** Changing a definition misses downstream consumers. Trace the full chain.
591- **When renaming, grep ALL consumer file types.** Some file types silently ignore missing refs (no compile error). Search code, templates, configs, generated files.
592- **Trace ALL code paths when verifying correctness.** Code existing ≠ code executing. Trace early exits, error branches, conditional skips — not just happy path.
593- **Update docs that embed canonical dat
594
595…(truncated)