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.
[BLOCKING] Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval.
[BLOCKING] Before each step or sub-skill call, update task tracking: set in_progress when step starts, set completed when step ends.
[BLOCKING] Every completed/skipped step MUST include brief evidence or explicit skip reason.
[BLOCKING] If Task tools are unavailable, create and maintain an equivalent step-by-step plan tracker with the same status transitions.
Quick Summary
Goal: Before a single line of a new Feature Spec is authored, deliver the pre-spec landscape — every existing Feature Spec the idea relates to / overlaps / depends on / would affect, the related code logic, the missing features and missing test cases / user stories, the system unknowns, and the invariant landscape the new spec must respect — so the author never ships a duplicate, contradicts a [HARD] rule, or specs into a blind spot.
Summary:
- This is BOTH spec-aware and code-aware: it reads
docs/specs/** (the canonical Feature Specs) AND delegates to $scout + code-graph for the code logic the idea touches. Spec-only or code-only discovery misses half the landscape.
- It runs BEFORE
spec [mode=draft] and feeds it. Its job is to decide WHETHER a new standalone spec is even the right move — the alternative is extending an existing spec, which only a spec-corpus scan can reveal.
- It is INLINE on the main agent (NOT a sub-agent) because step 5 is a BLOCKING ask the user directly scope-decision gate that only works inline. It MAY spawn sub-agents for parallel spec reads, but it orchestrates and gates inline.
- Greenfield short-circuit: when there are no specs AND no code, auto-detect it, record the reason, skip the heavy discovery, and hand off a minimal landscape — never grind through empty discovery.
- Main steps (0→6) — do ALL in order: (0) frame scope = keywords/entities/bucket → (1) spec-corpus discovery = Glob all candidate specs, read §1/§4/§5/§8, classify each EXTENDS/OVERLAPS/DEPENDS-ON/AFFECTED/UNRELATED with
file:line → (2) code-logic discovery = $scout + MANDATORY graph expansion, bridge code→spec via §8 [Source:] → (3) gap & invariant analysis = missing features, missing TCs/user stories, system unknowns, [HARD]/§5 invariant landscape → (4) report incrementally to plans/.../spec-discovery-{slug}.md → (5) BLOCKING ask the user directly scope gate = recommend NEW / EXTEND X / SPLIT, confirm cross-refs → (6) handoff to domain-analysis + spec [mode=draft|update].
Workflow:
- Scope — read the framed capability (brainstorm/idea output); extract keywords, candidate entities/actors, target spec bucket.
- Spec-corpus discovery —
Glob docs/specs/**/README.*.md; read §1/§4/§5/§8 of each candidate; classify each as EXTENDS / OVERLAPS / DEPENDS-ON / AFFECTED / UNRELATED.
- Code-logic discovery —
$scout {keywords} + MANDATORY graph expansion on key files when .code-graph/graph.db exists; bridge code→spec via §8 [Source:] anchors.
- Gap & invariant analysis — missing features, missing test cases / user stories, system unknowns (<80% confidence), and the existing [HARD] rules / §5 invariants the idea must respect.
- Report — write
plans/{plan-dir}/research/spec-discovery-{slug}.md incrementally (Related Specs · Related Code · Affected Specs · Gaps · Invariant Landscape · Open Questions).
- Scope-decision gate (BLOCKING ask the user directly) — recommend NEW / EXTEND existing X / SPLIT into N, and confirm which existing specs to cross-reference.
- Handoff — feed entities, invariants, cross-refs, and gaps into
domain-analysis + spec [mode=draft].
Key Rules:
- Landscape over implementation — surface related/overlapping/affected specs + the invariant landscape fast; this is NOT the spec author and NOT a deep investigation.
- INLINE execution — the step 5 user gate is BLOCKING and only works inline; spawn sub-agents only for parallel spec reads, never delegate the whole skill.
- NEVER auto-pick NEW — step 5 is a BLOCKING user gate. OVERLAPS is exactly what the spec scan exists to catch; recommend, then let the user decide scope.
- NEVER skip graph expansion when
.code-graph/graph.db exists; when absent, grep + read still bridge code→spec via [Source:] anchors.
Spec-Discovery — Pre-Spec Landscape Investigation
When to Use
- About to author a NEW Feature Spec from an idea / requirement / brainstorm output, before
spec [mode=draft] runs.
- Need to know whether the idea is genuinely new or overlaps an existing spec (duplicate-spec prevention).
- Need the invariant landscape — the existing [HARD] rules and §5 invariants a new capability must respect or might violate.
NOT for: authoring the spec (use spec [mode=draft]), deep root-cause analysis of existing code (use investigate), generating Section 8 test cases (use spec [mode=tests]), regenerating the derived bucket index/ERD (use spec-index).
Phase 0: Classify Corpus & Short-Circuit
Before any discovery, classify what landscape exists. This decides which steps run.
| Corpus state |
Detection |
Route |
| Specs + code |
docs/specs/**/README.*.md present AND source files for keywords |
Full run — steps 1, 2, 3, 4, 5, 6 |
| Specs only |
Specs present, no code yet (provisional/draft-era project) |
Steps 1, 3, 4, 5 — skip step 2 code discovery (record "no code yet") |
| Code only |
No specs yet, code exists |
Steps 2, 3, 4, 5 — step 1 records "no existing specs", bridge gaps from code |
| Greenfield (empty) |
No specs AND no source for keywords |
Short-circuit — record reason, skip heavy discovery, minimal handoff |
Greenfield / empty-corpus short-circuit. When Phase 0 detects no specs AND no code: record Corpus: greenfield — no specs, no code for {keywords} with the Glob/grep evidence that proved it, skip steps 1–3, write a minimal landscape report (just the framed scope + open questions), and hand off to spec [mode=draft]. Run the step 5 scope gate ONLY if there is something to decide (e.g. two plausible buckets); with nothing to decide, default to NEW and state the assumption in one line.
Workflow
Step 0: Frame the Scope
Read the framed capability — the brainstorm / idea / requirement text that triggered this. Extract:
- Keywords — domain nouns and verbs the idea names (entities, actions, features).
- Candidate entities / actors — the business objects and roles the idea implies.
- Target spec bucket — which
docs/specs/{Bucket}/ the new spec would most likely live in (per the project's module mapping; resolve from docs/project-reference/feature-spec-reference.md / spec-system-reference.md).
State the framed scope in one line before continuing (e.g. Discovering for: "bulk order export" — keywords [order, export, batch], bucket Orders).
Step 0.5: Declare the Discovery Wave
Step 1 (specs), Step 2 (code), and the invariant/test-case sweep read DIFFERENT inputs and produce DIFFERENT report sections — they are PAR. Running them one after another triples the wall time of the gate that stands between an idea and a duplicate spec, for zero safety gain. Declare the wave before Step 1, then spawn its members in ONE message:
| Wave-1 member |
Scope (read-only) |
Route to |
Feeds |
| Spec-corpus sweep |
the docs/specs/** candidates the keywords touch — §1/§4/§5/§8 ONLY, never whole specs |
one scout per bucket when the corpus is large; inline for a small one |
Related Specs · Affected Specs |
| Related-code discovery |
the code the idea touches (the Step 2 delegation) |
$scout {keywords} |
Related Code |
| Invariant / test-case landscape |
[HARD] BRs (§4), §5 entity invariants, existing §8 TC coverage of the touched specs |
one scout; fold into the corpus sweep when the corpus is small |
Invariant Landscape · Missing TCs |
Rules binding this wave: each member owns a unique artifact path under plans/reports/spec-discovery-{slug}/; no worker writes spec-discovery-{slug}.md. After the barrier, YOU are the sole reducer: read and validate every artifact, then synthesize the final report in section order. A missing artifact is rerun or reported, never silently replaced by a bounded summary.
SEQ — keep these OUT of the wave (each names its blocker): the Step 2 graph expansion (YOU run it, and only after the code member returns its key files) · Step 3 gap & invariant reconciliation (consumes all three members) · the Step 5 scope-decision gate (a BLOCKING ask the user directly cannot block from inside a sub-agent) · Step 6 handoff.
Phase 0's corpus state shrinks the wave: Specs only → drop the code member · Code only → drop the corpus sweep · Greenfield → no wave at all (short-circuit).
Step 1: Spec-Corpus Discovery
# Enumerate every canonical Feature Spec
ls docs/specs/**/README.*.md 2>/dev/null # or: Glob docs/specs/**/README.*.md
If NONE → record No existing specs and skip to Step 2.
Else, for each candidate spec the keywords touch, read the high-signal sections only (do NOT read whole specs — landscape, not deep-dive):
- §1 Overview — what the spec covers (scope boundary).
- §4 Business-Rule headers — the BR-{FC}-NN IDs and their [HARD]/[SOFT] tags (feeds invariant landscape).
- §5 Domain Model — entities + ERD (overlap detection by shared entities).
- §8 Test-Case summary — the TC count + summary table (coverage baseline; missing-TC detection).
Use the bucket INDEX.md (produced by $spec-index) as a fast navigation map when present — it lists the specs and their entities so you read fewer full files.
Classify each candidate spec's relationship to the idea (one label per spec, with file:line evidence):
| Relationship |
Meaning |
| EXTENDS |
The idea is a natural addition to this spec's capability — likely an UPDATE, not NEW. |
| OVERLAPS (dup risk) |
The idea re-states behavior this spec already owns — authoring NEW would duplicate. |
| DEPENDS-ON |
The idea needs this spec's entities/rules to function — cross-reference required. |
| AFFECTED |
The idea would change behavior this spec documents — forward-impact, may need amend. |
| UNRELATED |
Shares a keyword but no real relationship — record to show it was checked. |
Step 2: Code-Logic Discovery (only if code exists)
Bridge the idea to the implementation so the spec reflects what actually exists (or what the idea will touch).
- Delegate to
$scout {keywords} — fast parallel file discovery of the code the idea relates to. Use scout's numbered, prioritized list as targets; do NOT re-grep what scout already mapped.
- MANDATORY graph expansion — when
.code-graph/graph.db exists, run graph commands YOURSELF (sub-agents cannot) on 2–3 key files scout surfaced:python .claude/scripts/code_graph trace <key-entity-or-command> --direction both --json
python .claude/scripts/code_graph connections <key-file> --json
Graph reveals callers, consumers, event chains, and tests grep cannot find — exactly the downstream the new spec must account for.
- Delegate ambiguous areas to
$investigate — when scout + graph surface a flow whose behavior is unclear (the idea hinges on how it works), hand that narrow slice to investigate rather than guessing.
- Bridge code → spec — for each key code file, find its governing spec via the §8
[Source: namespace/service/id] anchors / Related Files. A code area with NO governing spec is a gap (record in Step 3); a code area WITH a governing spec strengthens the Step 1 relationship classification.
Step 3: Gap & Invariant Analysis
From Steps 1–2, synthesize four lists (every item file:line-cited or marked "inferred"):
- Missing features — behavior the idea implies that NO existing spec or code covers. These are the net-new surface the spec must define.
- Missing test cases / user stories — in the specs the idea touches (EXTENDS/AFFECTED), the AC / TC the idea's behavior would require but that are absent today.
- System unknowns — anything the discovery could not resolve to >80% confidence (unverified flows, ambiguous ownership, unread cross-service consumers). Name each explicitly — an unknown surfaced is cheaper than a wrong spec.
- Invariant landscape — the existing [HARD] business rules (§4) and §5 entity invariants the idea must respect or might violate. This is the single most load-bearing output: a new spec that contradicts a [HARD] rule of a DEPENDS-ON spec ships a defect. List each invariant as "for ALL {inputs}, {invariant} holds — owned by {spec/BR-id}".
Step 4: Report
Write plans/{plan-dir}/research/spec-discovery-{slug}.md (resolve {plan-dir} from the active plan; fall back to plans/reports/spec-discovery-{YYMMDD}-{HHmm}-{slug}.md when no plan dir exists). Persist incrementally — append each section as it is produced, never hold the whole report in memory:
# Spec-Discovery: {idea}
## Framed Scope
{keywords, candidate entities/actors, target bucket}
## Related Specs
| Spec | Relationship | Overlap evidence | Action implied |
| ---- | ------------ | ---------------- | -------------- |
## Related Code
{scout's prioritized files + graph evidence — callers/consumers/tests}
## Affected Specs (forward-impact)
{specs whose documented behavior the idea would change}
## Gaps
- Missing features: ...
- Missing TCs / user stories: ...
## Invariant Landscape
- for ALL {inputs}, {invariant} — owned by {spec/BR-id} — idea must {respect/extend}
## Open Questions
- {system unknowns, <80% confidence items}
Step 5: Scope-Decision Gate (BLOCKING ask the user directly)
MANDATORY MUST ATTENTION — NO EXCEPTIONS: before any spec is authored, MUST ATTENTION use ask the user directly to present the recommended scope. NEVER auto-pick — OVERLAPS detection is the whole reason this skill exists; assuming NEW silently ships duplicates.
Recommend ONE option (with the evidence behind it) and confirm the cross-references:
- (a) NEW standalone spec — no EXTENDS/OVERLAPS match; the idea is genuinely net-new. Hand off to
spec [mode=draft].
- (b) EXTEND existing spec X — an EXTENDS/OVERLAPS match means the idea belongs inside X. Reroute to
$spec [mode=update] against X instead of drafting a new file.
- (c) SPLIT into N specs — the idea spans N distinct capabilities (or would breach the size caps); author N specs, each with its own bucket.
Also confirm WHICH existing specs (the DEPENDS-ON / AFFECTED set) the author must cross-reference, so the new/updated spec links them and respects their invariants.
Step 6: Handoff
Feed the discovery forward:
- →
domain-analysis — the related entities + invariant landscape (so the domain model is consistent with existing specs).
- →
spec [mode=draft] (or spec [mode=update] if Step 5 chose EXTEND) — the framed scope, the missing features/TCs, the cross-references to link, and the [HARD] rules to respect.
Results Format
## Spec-Discovery Results: {idea}
### Recommended Scope
**{NEW | EXTEND spec X | SPLIT into N}** — because {evidence-backed reason}
### Related Specs
| Spec | Relationship | Evidence | Implied action |
| ----------------------------------- | ------------ | ------------------------------ | -------------------------- |
| `docs/specs/{Bucket}/README.{X}.md` | OVERLAPS | §4 BR-X-03 already states this | route to $spec mode=update |
### Related Code
1. `{file}` — {role} — graph: {callers/consumers found}
### Affected Specs (forward-impact)
- `{spec}` — {documented behavior the idea changes}
### Gaps
- Missing features: {list}
- Missing TCs / user stories: {list}
### Invariant Landscape (must respect)
- for ALL {inputs}, {invariant} — owned by {spec/BR-id}
### Open Questions
- {system unknowns, <80% confidence}
**Full report:** plans/{plan-dir}/research/spec-discovery-{slug}.md
Related Skills
scout (code file discovery — Step 2) | investigate (deep-dive ambiguous flows — Step 2) | spec [mode=draft] (authors §1–7 from the idea — Step 6 handoff) | spec [mode=update] (the EXTEND reroute — Step 5) | domain-analysis (entity/invariant modeling — Step 6) | spec-index (derived bucket INDEX.md used in Step 1)
[IMPORTANT] Use task tracking to break ALL work into small tasks BEFORE starting — including a task per candidate spec read. This prevents context loss from long specs. For trivial single-spec scopes, AI MUST ATTENTION ask user whether to skip.
docs/project-reference/feature-spec-reference.md — Feature Spec conventions, bucket/module mapping (read before reading any spec).
docs/project-reference/spec-system-reference.md — canonical vs derived spec artifacts, TC format, spec paths.
docs/project-reference/domain-entities-reference.md — Domain entity catalog, relationships, cross-service sync (read when the idea involves business entities/models).
External Memory: Complex/lengthy discovery → write findings incrementally to the research report. Prevents context loss.
Evidence Gate: MANDATORY MUST ATTENTION — every relationship classification, gap, and invariant requires file:line proof with confidence % (>80% act, <80% verify first).
Graph-Assisted Investigation — MANDATORY when .code-graph/graph.db exists.
HARD-GATE: MUST ATTENTION run at least ONE graph command on key files before concluding any investigation.
Pattern: Grep finds files → trace --direction both reveals full system flow → Grep verifies details
| Task |
Minimum Graph Action |
| Investigation/Scout |
trace --direction both on 2-3 entry files |
| Fix/Debug |
callers_of on buggy function + tests_for |
| Feature/Enhancement |
connections on files to be modified |
| Code Review |
tests_for on changed functions |
| Blast Radius |
trace --direction downstream |
CLI: python .claude/scripts/code_graph {command} --json. Use --node-mode file first (10-30x less noise), then --node-mode function for detail.
Incremental Result Persistence — MANDATORY for all sub-agents or heavy inline steps processing >3 files.
- Before starting: Create report file
plans/reports/{skill}-{date}-{slug}.md
- After each file/section reviewed: Append findings to report immediately — never hold in memory
- Return to main agent: Summary only (per SYNC:subagent-return-contract) with
Full report: path
- Main agent: Reads report file only when resolving specific blockers
Why: Context cutoff mid-execution loses ALL in-memory findings. Each disk write survives compaction. Partial results are better than no results.
Report naming: plans/reports/{skill-name}-{YYMMDD}-{HHmm}-{slug}.md
Sub-Agent Return Contract — When this skill spawns a sub-agent, the sub-agent MUST return ONLY this structure. Main agent reads only this summary — NEVER requests full sub-agent output inline.
## Sub-Agent Result: [skill-name]
Status: ✅ PASS | ⚠️ PARTIAL | ❌ FAIL
Confidence: [0-100]%
### Findings (Critical/High only — max 10 bullets)
- [severity] [file:line] [finding]
### Actions Taken
- [file changed] [what changed]
### Blockers (if any)
- [blocker description]
Full report: plans/reports/[skill-name]-[date]-[slug].md
Main agent reads Full report file ONLY when: (a) resolving a specific blocker, or (b) building a fix plan.
Sub-agent writes full report incrementally (per SYNC:incremental-persistence) — not held in memory.
Context budget — the return payload is a SUMMARY, not a transcript: ≤10 finding bullets, no raw file contents / full diffs / verbatim logs inline, no re-pasted source. Everything beyond the summary lives in the Full report on disk. A sub-agent that would exceed the summary shape MUST write the detail to its report and return only the pointer — the orchestrator's context is the scarce resource the whole map-reduce protects.
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.
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: [...]."
Cross-Service Check — Microservices/event-driven: MANDATORY before concluding investigation, plan, spec, or feature doc. Missing downstream consumer = silent regression.
| Boundary |
Grep terms |
| Event producers |
Publish, Dispatch, Send, emit, EventBus, outbox, IntegrationEvent |
| Event consumers |
Consumer, EventHandler, Subscribe, @EventListener, inbox |
| Sagas/orchestration |
Saga, ProcessManager, Choreography, Workflow, Orchestrator |
| Sync service calls |
HTTP/gRPC calls to/from other services |
| Shared contracts |
OpenAPI spec, proto, shared DTO — flag breaking changes |
| Data ownership |
Other service reads/writes same table/collection → Shared-DB anti-pattern |
Per touchpoint: owner service · message name · consumers · risk (NONE / ADDITIVE / BREAKING).
BLOCKED until: Producers scanned · Consumers scanned · Sagas checked · Contracts reviewed · Breaking-change risk flagged
Rationalization Prevention — AI skips steps via these evasions. Recognize and reject:
| Evasion |
Rebuttal |
| "Too simple for a plan" |
Simple + wrong assumptions = wasted time. Plan anyway. |
| "I'll test after" |
RED before GREEN. Write/verify test first. |
| "Already searched" |
Show grep evidence with file:line. No proof = no search. |
| "Just do it" |
Still need task tracking. Skip depth, never skip tracking. |
| "Just a small fix" |
Small fix in wrong location cascades. Verify file:line first. |
| "Code is self-explanatory" |
Future readers need evidence trail. Document anyway. |
| "Combine steps to save time" |
Combined steps dilute focus. Each step has distinct purpose. |
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.
MUST ATTENTION cite file:line evidence for every claim. Confidence >80% to act, <60% = do NOT recommend.
MUST ATTENTION never skip steps via evasions. Plan anyway. Test first. Show grep evidence with file:line.
MUST ATTENTION run at least ONE graph command on key files before concluding when .code-graph/graph.db exists.
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.
- 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.
Prompt-Enhance Closing Anchors
IMPORTANT MUST ATTENTION follow declared step order for this skill; NEVER skip, reorder, or merge steps without explicit user approval
IMPORTANT MUST ATTENTION for every step/sub-skill call: set in_progress before execution, set completed after execution
IMPORTANT MUST ATTENTION every skipped step MUST include explicit reason; every completed step MUST include concise evidence
IMPORTANT MUST ATTENTION if Task tools unavailable, maintain an equivalent step-by-step plan tracker with synchronized statuses
Parallel Sub-Agent Dispatch — Plan parallelism the moment a task breakdown exists, BEFORE executing it — running provably independent tasks sequentially wastes wall-clock. Applies to every multi-step job: workflow steps, planning, batch updates, investigation, research, scans, reviews, doc sync. Plan execution is metadata-gated, NEVER default-parallel — fan-out follows ONLY what the plan declares (PAR/SEQ tags + per-phase write set); an untagged plan runs sequentially — why: a derived write set cannot see cascade or generated writes.
- Tag every task
PAR or SEQ. PAR = inputs exclude every pending task's output AND write set disjoint from every other PAR. Else SEQ — MUST ATTENTION name the dependency forcing it.
- Group
PAR into waves. No edge between members. Two writers of one file NEVER share a wave. Read-only work (search, investigation, review, research) parallelizes freely.
- Declare before dispatch:
Parallel plan: wave 1 = [...] · wave 2 = [...] · SEQ = [...] (reason).
- Spawn each wave in ONE message — every
spawn_agent call in one respon
…(truncated)
1---2name: spec-discovery3description: [Investigation] Use when about to author a new Feature Spec from an idea — investigate all existing Feature Specs AND related code logic first to surface related/overlapping/affected specs, missing features, missing test cases/user stories, system unknowns, and the invariant landscape, before any spec is drafted.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<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:START -->
50
51> **[BLOCKING]** Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval.
52> **[BLOCKING]** Before each step or sub-skill call, update task tracking: set `in_progress` when step starts, set `completed` when step ends.
53> **[BLOCKING]** Every completed/skipped step MUST include brief evidence or explicit skip reason.
54> **[BLOCKING]** If Task tools are unavailable, create and maintain an equivalent step-by-step plan tracker with the same status transitions.
55
56<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:END -->
57
58## Quick Summary
59
60**Goal:** Before a single line of a new Feature Spec is authored, deliver the pre-spec landscape — every existing Feature Spec the idea relates to / overlaps / depends on / would affect, the related code logic, the missing features and missing test cases / user stories, the system unknowns, and the invariant landscape the new spec must respect — so the author never ships a duplicate, contradicts a [HARD] rule, or specs into a blind spot.
61
62**Summary:**
63
64- This is BOTH spec-aware and code-aware: it reads `docs/specs/**` (the canonical Feature Specs) AND delegates to `$scout` + code-graph for the code logic the idea touches. Spec-only or code-only discovery misses half the landscape.
65- It runs BEFORE `spec [mode=draft]` and feeds it. Its job is to decide WHETHER a new standalone spec is even the right move — the alternative is extending an existing spec, which only a spec-corpus scan can reveal.
66- It is INLINE on the main agent (NOT a sub-agent) because step 5 is a BLOCKING ask the user directly scope-decision gate that only works inline. It MAY spawn sub-agents for parallel spec reads, but it orchestrates and gates inline.
67- Greenfield short-circuit: when there are no specs AND no code, auto-detect it, record the reason, skip the heavy discovery, and hand off a minimal landscape — never grind through empty discovery.
68- **Main steps (0→6) — do ALL in order:** (0) frame scope = keywords/entities/bucket → (1) spec-corpus discovery = Glob all candidate specs, read §1/§4/§5/§8, classify each EXTENDS/OVERLAPS/DEPENDS-ON/AFFECTED/UNRELATED with `file:line` → (2) code-logic discovery = `$scout` + MANDATORY graph expansion, bridge code→spec via §8 `[Source:]` → (3) gap & invariant analysis = missing features, missing TCs/user stories, system unknowns, [HARD]/§5 invariant landscape → (4) report incrementally to `plans/.../spec-discovery-{slug}.md` → (5) BLOCKING ask the user directly scope gate = recommend NEW / EXTEND X / SPLIT, confirm cross-refs → (6) handoff to `domain-analysis` + `spec [mode=draft|update]`.
69
70**Workflow:**
71
720. **Scope** — read the framed capability (brainstorm/idea output); extract keywords, candidate entities/actors, target spec bucket.
731. **Spec-corpus discovery** — `Glob docs/specs/**/README.*.md`; read §1/§4/§5/§8 of each candidate; classify each as EXTENDS / OVERLAPS / DEPENDS-ON / AFFECTED / UNRELATED.
742. **Code-logic discovery** — `$scout {keywords}` + MANDATORY graph expansion on key files when `.code-graph/graph.db` exists; bridge code→spec via §8 `[Source:]` anchors.
753. **Gap & invariant analysis** — missing features, missing test cases / user stories, system unknowns (<80% confidence), and the existing [HARD] rules / §5 invariants the idea must respect.
764. **Report** — write `plans/{plan-dir}/research/spec-discovery-{slug}.md` incrementally (Related Specs · Related Code · Affected Specs · Gaps · Invariant Landscape · Open Questions).
775. **Scope-decision gate (BLOCKING ask the user directly)** — recommend NEW / EXTEND existing X / SPLIT into N, and confirm which existing specs to cross-reference.
786. **Handoff** — feed entities, invariants, cross-refs, and gaps into `domain-analysis` + `spec [mode=draft]`.
79
80**Key Rules:**
81
82- Landscape over implementation — surface related/overlapping/affected specs + the invariant landscape fast; this is NOT the spec author and NOT a deep investigation.
83- INLINE execution — the step 5 user gate is BLOCKING and only works inline; spawn sub-agents only for parallel spec reads, never delegate the whole skill.
84- NEVER auto-pick NEW — step 5 is a BLOCKING user gate. OVERLAPS is exactly what the spec scan exists to catch; recommend, then let the user decide scope.
85- NEVER skip graph expansion when `.code-graph/graph.db` exists; when absent, grep + read still bridge code→spec via `[Source:]` anchors.
86
87# Spec-Discovery — Pre-Spec Landscape Investigation
88
89---
90
91## When to Use
92
93- About to author a NEW Feature Spec from an idea / requirement / brainstorm output, before `spec [mode=draft]` runs.
94- Need to know whether the idea is genuinely new or overlaps an existing spec (duplicate-spec prevention).
95- Need the invariant landscape — the existing [HARD] rules and §5 invariants a new capability must respect or might violate.
96
97**NOT for:** authoring the spec (use `spec [mode=draft]`), deep root-cause analysis of existing code (use `investigate`), generating Section 8 test cases (use `spec [mode=tests]`), regenerating the derived bucket index/ERD (use `spec-index`).
98
99---
100
101## Phase 0: Classify Corpus & Short-Circuit
102
103**Before any discovery**, classify what landscape exists. This decides which steps run.
104
105| Corpus state | Detection | Route |
106| ---------------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------------------- |
107| **Specs + code** | `docs/specs/**/README.*.md` present AND source files for keywords | Full run — steps 1, 2, 3, 4, 5, 6 |
108| **Specs only** | Specs present, no code yet (provisional/draft-era project) | Steps 1, 3, 4, 5 — skip step 2 code discovery (record "no code yet") |
109| **Code only** | No specs yet, code exists | Steps 2, 3, 4, 5 — step 1 records "no existing specs", bridge gaps from code |
110| **Greenfield (empty)** | No specs AND no source for keywords | **Short-circuit** — record reason, skip heavy discovery, minimal handoff |
111
112> **Greenfield / empty-corpus short-circuit.** When Phase 0 detects no specs AND no code: record `Corpus: greenfield — no specs, no code for {keywords}` with the `Glob`/grep evidence that proved it, skip steps 1–3, write a minimal landscape report (just the framed scope + open questions), and hand off to `spec [mode=draft]`. Run the step 5 scope gate ONLY if there is something to decide (e.g. two plausible buckets); with nothing to decide, default to NEW and state the assumption in one line.
113
114---
115
116## Workflow
117
118### Step 0: Frame the Scope
119
120Read the framed capability — the brainstorm / idea / requirement text that triggered this. Extract:
121
122- **Keywords** — domain nouns and verbs the idea names (entities, actions, features).
123- **Candidate entities / actors** — the business objects and roles the idea implies.
124- **Target spec bucket** — which `docs/specs/{Bucket}/` the new spec would most likely live in (per the project's module mapping; resolve from `docs/project-reference/feature-spec-reference.md` / `spec-system-reference.md`).
125
126State the framed scope in one line before continuing (e.g. `Discovering for: "bulk order export" — keywords [order, export, batch], bucket Orders`).
127
128### Step 0.5: Declare the Discovery Wave
129
130Step 1 (specs), Step 2 (code), and the invariant/test-case sweep read DIFFERENT inputs and produce DIFFERENT report sections — they are PAR. Running them one after another triples the wall time of the gate that stands between an idea and a duplicate spec, for zero safety gain. Declare the wave before Step 1, then spawn its members in ONE message:
131
132| Wave-1 member | Scope (read-only) | Route to | Feeds |
133| ----------------------------------- | --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | --------------------------------- |
134| **Spec-corpus sweep** | the `docs/specs/**` candidates the keywords touch — §1/§4/§5/§8 ONLY, never whole specs | one `scout` per bucket when the corpus is large; inline for a small one | Related Specs · Affected Specs |
135| **Related-code discovery** | the code the idea touches (the Step 2 delegation) | `$scout {keywords}` | Related Code |
136| **Invariant / test-case landscape** | [HARD] BRs (§4), §5 entity invariants, existing §8 TC coverage of the touched specs | one `scout`; fold into the corpus sweep when the corpus is small | Invariant Landscape · Missing TCs |
137
138Rules binding this wave: each member owns a **unique artifact path** under `plans/reports/spec-discovery-{slug}/`; no worker writes `spec-discovery-{slug}.md`. After the barrier, YOU are the sole reducer: read and validate every artifact, then synthesize the final report in section order. A missing artifact is rerun or reported, never silently replaced by a bounded summary.
139
140**SEQ — keep these OUT of the wave (each names its blocker):** the Step 2 graph expansion (YOU run it, and only after the code member returns its key files) · Step 3 gap & invariant reconciliation (consumes all three members) · the Step 5 scope-decision gate (a BLOCKING ask the user directly cannot block from inside a sub-agent) · Step 6 handoff.
141
142Phase 0's corpus state shrinks the wave: **Specs only** → drop the code member · **Code only** → drop the corpus sweep · **Greenfield** → no wave at all (short-circuit).
143
144### Step 1: Spec-Corpus Discovery
145
146```bash
147# Enumerate every canonical Feature Spec
148ls docs/specs/**/README.*.md 2>/dev/null # or: Glob docs/specs/**/README.*.md
149```
150
151If NONE → record `No existing specs` and skip to Step 2.
152
153Else, for each candidate spec the keywords touch, read the high-signal sections only (do NOT read whole specs — landscape, not deep-dive):
154
155- **§1 Overview** — what the spec covers (scope boundary).
156- **§4 Business-Rule headers** — the BR-{FC}-NN IDs and their [HARD]/[SOFT] tags (feeds invariant landscape).
157- **§5 Domain Model** — entities + ERD (overlap detection by shared entities).
158- **§8 Test-Case summary** — the TC count + summary table (coverage baseline; missing-TC detection).
159
160Use the bucket `INDEX.md` (produced by `$spec-index`) as a fast navigation map when present — it lists the specs and their entities so you read fewer full files.
161
162**Classify each candidate spec's relationship to the idea** (one label per spec, with `file:line` evidence):
163
164| Relationship | Meaning |
165| ----------------------- | ------------------------------------------------------------------------------------- |
166| **EXTENDS** | The idea is a natural addition to this spec's capability — likely an UPDATE, not NEW. |
167| **OVERLAPS (dup risk)** | The idea re-states behavior this spec already owns — authoring NEW would duplicate. |
168| **DEPENDS-ON** | The idea needs this spec's entities/rules to function — cross-reference required. |
169| **AFFECTED** | The idea would change behavior this spec documents — forward-impact, may need amend. |
170| **UNRELATED** | Shares a keyword but no real relationship — record to show it was checked. |
171
172### Step 2: Code-Logic Discovery (only if code exists)
173
174Bridge the idea to the implementation so the spec reflects what actually exists (or what the idea will touch).
175
1761. **Delegate to `$scout {keywords}`** — fast parallel file discovery of the code the idea relates to. Use scout's numbered, prioritized list as targets; do NOT re-grep what scout already mapped.
1772. **MANDATORY graph expansion** — when `.code-graph/graph.db` exists, run graph commands YOURSELF (sub-agents cannot) on 2–3 key files scout surfaced:
178 ```bash
179 python .claude/scripts/code_graph trace <key-entity-or-command> --direction both --json
180 python .claude/scripts/code_graph connections <key-file> --json
181 ```
182 Graph reveals callers, consumers, event chains, and tests grep cannot find — exactly the downstream the new spec must account for.
1833. **Delegate ambiguous areas to `$investigate`** — when scout + graph surface a flow whose behavior is unclear (the idea hinges on how it works), hand that narrow slice to `investigate` rather than guessing.
1844. **Bridge code → spec** — for each key code file, find its governing spec via the §8 `[Source: namespace/service/id]` anchors / Related Files. A code area with NO governing spec is a gap (record in Step 3); a code area WITH a governing spec strengthens the Step 1 relationship classification.
185
186### Step 3: Gap & Invariant Analysis
187
188From Steps 1–2, synthesize four lists (every item `file:line`-cited or marked "inferred"):
189
190- **Missing features** — behavior the idea implies that NO existing spec or code covers. These are the net-new surface the spec must define.
191- **Missing test cases / user stories** — in the specs the idea touches (EXTENDS/AFFECTED), the AC / TC the idea's behavior would require but that are absent today.
192- **System unknowns** — anything the discovery could not resolve to >80% confidence (unverified flows, ambiguous ownership, unread cross-service consumers). Name each explicitly — an unknown surfaced is cheaper than a wrong spec.
193- **Invariant landscape** — the existing [HARD] business rules (§4) and §5 entity invariants the idea must respect or might violate. This is the single most load-bearing output: a new spec that contradicts a [HARD] rule of a DEPENDS-ON spec ships a defect. List each invariant as "for ALL {inputs}, {invariant} holds — owned by {spec/BR-id}".
194
195### Step 4: Report
196
197Write `plans/{plan-dir}/research/spec-discovery-{slug}.md` (resolve `{plan-dir}` from the active plan; fall back to `plans/reports/spec-discovery-{YYMMDD}-{HHmm}-{slug}.md` when no plan dir exists). Persist **incrementally** — append each section as it is produced, never hold the whole report in memory:
198
199```markdown
200# Spec-Discovery: {idea}
201
202## Framed Scope
203
204{keywords, candidate entities/actors, target bucket}
205
206## Related Specs
207
208| Spec | Relationship | Overlap evidence | Action implied |
209| ---- | ------------ | ---------------- | -------------- |
210
211## Related Code
212
213{scout's prioritized files + graph evidence — callers/consumers/tests}
214
215## Affected Specs (forward-impact)
216
217{specs whose documented behavior the idea would change}
218
219## Gaps
220
221- Missing features: ...
222- Missing TCs / user stories: ...
223
224## Invariant Landscape
225
226- for ALL {inputs}, {invariant} — owned by {spec/BR-id} — idea must {respect/extend}
227
228## Open Questions
229
230- {system unknowns, <80% confidence items}
231```
232
233### Step 5: Scope-Decision Gate (BLOCKING ask the user directly)
234
235> **MANDATORY MUST ATTENTION — NO EXCEPTIONS:** before any spec is authored, MUST ATTENTION use ask the user directly to present the recommended scope. NEVER auto-pick — OVERLAPS detection is the whole reason this skill exists; assuming NEW silently ships duplicates.
236
237Recommend ONE option (with the evidence behind it) and confirm the cross-references:
238
239- **(a) NEW standalone spec** — no EXTENDS/OVERLAPS match; the idea is genuinely net-new. Hand off to `spec [mode=draft]`.
240- **(b) EXTEND existing spec X** — an EXTENDS/OVERLAPS match means the idea belongs inside X. **Reroute to `$spec [mode=update]`** against X instead of drafting a new file.
241- **(c) SPLIT into N specs** — the idea spans N distinct capabilities (or would breach the size caps); author N specs, each with its own bucket.
242
243Also confirm WHICH existing specs (the DEPENDS-ON / AFFECTED set) the author must cross-reference, so the new/updated spec links them and respects their invariants.
244
245### Step 6: Handoff
246
247Feed the discovery forward:
248
249- **→ `domain-analysis`** — the related entities + invariant landscape (so the domain model is consistent with existing specs).
250- **→ `spec [mode=draft]`** (or `spec [mode=update]` if Step 5 chose EXTEND) — the framed scope, the missing features/TCs, the cross-references to link, and the [HARD] rules to respect.
251
252---
253
254## Results Format
255
256```markdown
257## Spec-Discovery Results: {idea}
258
259### Recommended Scope
260
261**{NEW | EXTEND spec X | SPLIT into N}** — because {evidence-backed reason}
262
263### Related Specs
264
265| Spec | Relationship | Evidence | Implied action |
266| ----------------------------------- | ------------ | ------------------------------ | -------------------------- |
267| `docs/specs/{Bucket}/README.{X}.md` | OVERLAPS | §4 BR-X-03 already states this | route to $spec mode=update |
268
269### Related Code
270
2711. `{file}` — {role} — graph: {callers/consumers found}
272
273### Affected Specs (forward-impact)
274
275- `{spec}` — {documented behavior the idea changes}
276
277### Gaps
278
279- Missing features: {list}
280- Missing TCs / user stories: {list}
281
282### Invariant Landscape (must respect)
283
284- for ALL {inputs}, {invariant} — owned by {spec/BR-id}
285
286### Open Questions
287
288- {system unknowns, <80% confidence}
289
290**Full report:** plans/{plan-dir}/research/spec-discovery-{slug}.md
291```
292
293---
294
295## Related Skills
296
297`scout` (code file discovery — Step 2) | `investigate` (deep-dive ambiguous flows — Step 2) | `spec [mode=draft]` (authors §1–7 from the idea — Step 6 handoff) | `spec [mode=update]` (the EXTEND reroute — Step 5) | `domain-analysis` (entity/invariant modeling — Step 6) | `spec-index` (derived bucket INDEX.md used in Step 1)
298
299---
300
301> **[IMPORTANT]** Use task tracking to break ALL work into small tasks BEFORE starting — including a task per candidate spec read. This prevents context loss from long specs. For trivial single-spec scopes, AI MUST ATTENTION ask user whether to skip.
302
303- `docs/project-reference/feature-spec-reference.md` — Feature Spec conventions, bucket/module mapping (read before reading any spec).
304- `docs/project-reference/spec-system-reference.md` — canonical vs derived spec artifacts, TC format, spec paths.
305- `docs/project-reference/domain-entities-reference.md` — Domain entity catalog, relationships, cross-service sync (read when the idea involves business entities/models).
306
307> **External Memory:** Complex/lengthy discovery → write findings incrementally to the research report. Prevents context loss.
308
309> **Evidence Gate:** MANDATORY MUST ATTENTION — every relationship classification, gap, and invariant requires `file:line` proof with confidence % (>80% act, <80% verify first).
310
311<!-- SYNC:graph-assisted-investigation -->
312
313> **Graph-Assisted Investigation** — MANDATORY when `.code-graph/graph.db` exists.
314>
315> **HARD-GATE:** MUST ATTENTION run at least ONE graph command on key files before concluding any investigation.
316>
317> **Pattern:** Grep finds files → `trace --direction both` reveals full system flow → Grep verifies details
318>
319> | Task | Minimum Graph Action |
320> | ------------------- | -------------------------------------------- |
321> | Investigation/Scout | `trace --direction both` on 2-3 entry files |
322> | Fix/Debug | `callers_of` on buggy function + `tests_for` |
323> | Feature/Enhancement | `connections` on files to be modified |
324> | Code Review | `tests_for` on changed functions |
325> | Blast Radius | `trace --direction downstream` |
326>
327> **CLI:** `python .claude/scripts/code_graph {command} --json`. Use `--node-mode file` first (10-30x less noise), then `--node-mode function` for detail.
328
329<!-- /SYNC:graph-assisted-investigation -->
330
331<!-- SYNC:incremental-persistence -->
332
333> **Incremental Result Persistence** — MANDATORY for all sub-agents or heavy inline steps processing >3 files.
334>
335> 1. **Before starting:** Create report file `plans/reports/{skill}-{date}-{slug}.md`
336> 2. **After each file/section reviewed:** Append findings to report immediately — never hold in memory
337> 3. **Return to main agent:** Summary only (per SYNC:subagent-return-contract) with `Full report:` path
338> 4. **Main agent:** Reads report file only when resolving specific blockers
339>
340> **Why:** Context cutoff mid-execution loses ALL in-memory findings. Each disk write survives compaction. Partial results are better than no results.
341>
342> **Report naming:** `plans/reports/{skill-name}-{YYMMDD}-{HHmm}-{slug}.md`
343
344<!-- /SYNC:incremental-persistence -->
345
346<!-- SYNC:subagent-return-contract -->
347
348> **Sub-Agent Return Contract** — When this skill spawns a sub-agent, the sub-agent MUST return ONLY this structure. Main agent reads only this summary — NEVER requests full sub-agent output inline.
349>
350> ```markdown
351> ## Sub-Agent Result: [skill-name]
352>
353> Status: ✅ PASS | ⚠️ PARTIAL | ❌ FAIL
354> Confidence: [0-100]%
355>
356> ### Findings (Critical/High only — max 10 bullets)
357>
358> - [severity] [file:line] [finding]
359>
360> ### Actions Taken
361>
362> - [file changed] [what changed]
363>
364> ### Blockers (if any)
365>
366> - [blocker description]
367>
368> Full report: plans/reports/[skill-name]-[date]-[slug].md
369> ```
370>
371> Main agent reads `Full report` file ONLY when: (a) resolving a specific blocker, or (b) building a fix plan.
372> Sub-agent writes full report incrementally (per SYNC:incremental-persistence) — not held in memory.
373>
374> **Context budget** — the return payload is a SUMMARY, not a transcript: ≤10 finding bullets, no raw file contents / full diffs / verbatim logs inline, no re-pasted source. Everything beyond the summary lives in the `Full report` on disk. A sub-agent that would exceed the summary shape MUST write the detail to its report and return only the pointer — the orchestrator's context is the scarce resource the whole map-reduce protects.
375
376<!-- /SYNC:subagent-return-contract -->
377
378<!-- SYNC:nested-task-creation -->
379
380> **Nested Task Expansion Contract** — For workflow-step invocation, the `[Workflow] ...` row is only a parent container; the child skill still creates visible phase tasks.
381>
382> 1. Call the current task list first. If a matching active parent workflow row exists, set `nested=true` and record `parentTaskId`; otherwise run standalone.
383> 2. Create one task per declared phase before phase work. When nested, prefix subjects `[N.M] $skill-name — phase`.
384> 3. When nested, link the parent with `TaskUpdate(parentTaskId, addBlockedBy: [childIds])`.
385> 4. Orchestrators must pre-expand a child skill's phase list and link the workflow row before invoking that child skill or sub-agent.
386> 5. Mark exactly one child `in_progress` before work and `completed` immediately after evidence is written.
387> 6. Complete the parent only after all child tasks are completed or explicitly cancelled with reason.
388>
389> **Blocked until:** the current task list done, child phases created, parent linked when nested, first child marked `in_progress`.
390
391<!-- /SYNC:nested-task-creation -->
392
393<!-- SYNC:project-reference-docs-guide -->
394
395> **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.
396>
397> 1. Identify scope: file types, domain area, and operation.
398> 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).
399> 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`.
400> 4. Read every required doc, then before target work state: `Reference docs read: ... | Not applicable: ...`.
401>
402> **Ready when:** scope evaluated, `docs/project-config.json` consulted, required docs checked/read or setup route completed, `lessons.md` confirmed, citation emitted.
403
404<!-- /SYNC:project-reference-docs-guide -->
405
406<!-- SYNC:task-tracking-external-report -->
407
408> **Task Tracking & External Report Persistence** — Bootstrap this before execution; then run project-reference doc prefetch before target/source work.
409>
410> 1. Create a small task breakdown before target file reads, grep, edits, or analysis. On context loss, inspect the current task list first.
411> 2. Mark one task `in_progress` before work and `completed` immediately after evidence; never batch transitions.
412> 3. For plan/review work, create `plans/reports/{skill}-{YYMMDD}-{HHmm}-{slug}.md` before first finding.
413> 4. Append findings after each file/section/decision and synthesize from the report file at the end.
414> 5. Final output cites `Full report: plans/reports/{filename}`.
415>
416> **Blocked until:** task breakdown exists, report path declared for plan/review work, first finding persisted before the next finding.
417
418<!-- /SYNC:task-tracking-external-report -->
419
420<!-- SYNC:critical-thinking-mindset -->
421
422> **Critical Thinking Mindset** — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
423> **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.
424
425<!-- /SYNC:critical-thinking-mindset -->
426
427<!-- SYNC:evidence-based-reasoning -->
428
429> **Evidence-Based Reasoning** — Speculation is FORBIDDEN. Every claim needs proof.
430>
431> 1. Cite `file:line`, grep results, or framework docs for EVERY claim
432> 2. Declare confidence: >80% act freely, 60-80% verify first, <60% DO NOT recommend
433> 3. Cross-service validation required for architectural changes
434> 4. "I don't have enough evidence" is valid and expected output
435>
436> **BLOCKED until:** `- [ ]` Evidence file path (`file:line`) `- [ ]` Grep search performed `- [ ]` 3+ similar patterns found `- [ ]` Confidence level stated
437>
438> **Forbidden without proof:** "obviously", "I think", "should be", "probably", "this is because"
439> **If incomplete →** output: `"Insufficient evidence. Verified: [...]. Not verified: [...]."`
440
441<!-- /SYNC:evidence-based-reasoning -->
442
443<!-- SYNC:cross-service-check -->
444
445> **Cross-Service Check** — Microservices/event-driven: MANDATORY before concluding investigation, plan, spec, or feature doc. Missing downstream consumer = silent regression.
446>
447> | Boundary | Grep terms |
448> | ------------------- | ------------------------------------------------------------------------------- |
449> | Event producers | `Publish`, `Dispatch`, `Send`, `emit`, `EventBus`, `outbox`, `IntegrationEvent` |
450> | Event consumers | `Consumer`, `EventHandler`, `Subscribe`, `@EventListener`, `inbox` |
451> | Sagas/orchestration | `Saga`, `ProcessManager`, `Choreography`, `Workflow`, `Orchestrator` |
452> | Sync service calls | HTTP/gRPC calls to/from other services |
453> | Shared contracts | OpenAPI spec, proto, shared DTO — flag breaking changes |
454> | Data ownership | Other service reads/writes same table/collection → Shared-DB anti-pattern |
455>
456> **Per touchpoint:** owner service · message name · consumers · risk (NONE / ADDITIVE / BREAKING).
457>
458> **BLOCKED until:** Producers scanned · Consumers scanned · Sagas checked · Contracts reviewed · Breaking-change risk flagged
459
460<!-- /SYNC:cross-service-check -->
461
462<!-- SYNC:rationalization-prevention -->
463
464> **Rationalization Prevention** — AI skips steps via these evasions. Recognize and reject:
465>
466> | Evasion | Rebuttal |
467> | ---------------------------- | ------------------------------------------------------------- |
468> | "Too simple for a plan" | Simple + wrong assumptions = wasted time. Plan anyway. |
469> | "I'll test after" | RED before GREEN. Write/verify test first. |
470> | "Already searched" | Show grep evidence with `file:line`. No proof = no search. |
471> | "Just do it" | Still need task tracking. Skip depth, never skip tracking. |
472> | "Just a small fix" | Small fix in wrong location cascades. Verify file:line first. |
473> | "Code is self-explanatory" | Future readers need evidence trail. Document anyway. |
474> | "Combine steps to save time" | Combined steps dilute focus. Each step has distinct purpose. |
475
476<!-- /SYNC:rationalization-prevention -->
477
478<!-- SYNC:ai-mistake-prevention -->
479
480> **AI Mistake Prevention** — Failure modes to avoid on every task:
481>
482> **Re-read files after context changes.** Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
483> **Verify generated content against source evidence.** AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
484> **Check downstream references before deleting or renaming.** Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
485> **Trace the full impact chain after edits.** Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
486> **Verify ALL affected outputs, not just the first.** One green check is not all green checks; validate every output surface the change can affect.
487> **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.
488> **Surface ambiguity before acting — don't pick silently.** Multiple valid interpretations require an explicit question or stated assumption with risk.
489> **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.
490> **Keep shared guidance role-relevant.** Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
491
492<!-- /SYNC:ai-mistake-prevention -->
493
494<!-- SYNC:evidence-based-reasoning:reminder -->
495
496**MUST ATTENTION** cite `file:line` evidence for every claim. Confidence >80% to act, <60% = do NOT recommend.
497
498<!-- /SYNC:evidence-based-reasoning:reminder -->
499
500<!-- SYNC:rationalization-prevention:reminder -->
501
502**MUST ATTENTION** never skip steps via evasions. Plan anyway. Test first. Show grep evidence with `file:line`.
503
504<!-- /SYNC:rationalization-prevention:reminder -->
505
506<!-- SYNC:graph-assisted-investigation:reminder -->
507
508**MUST ATTENTION** run at least ONE graph command on key files before concluding when `.code-graph/graph.db` exists.
509
510<!-- /SYNC:graph-assisted-investigation:reminder -->
511
512<!-- SYNC:critical-thinking-mindset:reminder -->
513
514**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.
515
516<!-- /SYNC:critical-thinking-mindset:reminder -->
517
518<!-- SYNC:ai-mistake-prevention:reminder -->
519
520**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.
521
522<!-- /SYNC:ai-mistake-prevention:reminder -->
523
524<!-- SYNC:task-tracking-external-report:reminder -->
525
526- **MANDATORY** Bootstrap task tracking before target work; transition one task at a time.
527- **MANDATORY** Persist plan/review findings to `plans/reports/` incrementally and synthesize from disk.
528
529<!-- /SYNC:task-tracking-external-report:reminder -->
530
531<!-- SYNC:project-reference-docs-guide:reminder -->
532
533- **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: ...`.
534- **MANDATORY** Always include `lessons.md`; project config + conventions override generic framework defaults.
535- **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.
536
537<!-- /SYNC:project-reference-docs-guide:reminder -->
538
539<!-- SYNC:nested-task-creation:reminder -->
540
541- **MANDATORY** Parent workflow rows do not replace child phase tracking; expand phases and link the parent when nested.
542- **MANDATORY** Orchestrators pre-expand child skill phases before invocation; use `[N.M] $skill-name — phase` prefixes and one-`in_progress` discipline.
543
544<!-- /SYNC:nested-task-creation:reminder -->
545
546<!-- PROMPT-ENHANCE:STEP-TASK-CLOSING:START -->
547
548## Prompt-Enhance Closing Anchors
549
550**IMPORTANT MUST ATTENTION** follow declared step order for this skill; NEVER skip, reorder, or merge steps without explicit user approval
551**IMPORTANT MUST ATTENTION** for every step/sub-skill call: set `in_progress` before execution, set `completed` after execution
552**IMPORTANT MUST ATTENTION** every skipped step MUST include explicit reason; every completed step MUST include concise evidence
553**IMPORTANT MUST ATTENTION** if Task tools unavailable, maintain an equivalent step-by-step plan tracker with synchronized statuses
554
555<!-- PROMPT-ENHANCE:STEP-TASK-CLOSING:END -->
556
557<!-- SYNC:parallel-subagent-dispatch -->
558
559> **Parallel Sub-Agent Dispatch** — Plan parallelism the moment a task breakdown exists, BEFORE executing it — running provably independent tasks sequentially wastes wall-clock. Applies to every multi-step job: workflow steps, planning, batch updates, investigation, research, scans, reviews, doc sync. **Plan execution is metadata-gated, NEVER default-parallel** — fan-out follows ONLY what the plan declares (`PAR`/`SEQ` tags + per-phase write set); an untagged plan runs sequentially — why: a derived write set cannot see cascade or generated writes.
560>
561> 1. **Tag every task `PAR` or `SEQ`.** `PAR` = inputs exclude every pending task's output AND write set disjoint from every other `PAR`. Else `SEQ` — MUST ATTENTION name the dependency forcing it.
562> 2. **Group `PAR` into waves.** No edge between members. Two writers of one file NEVER share a wave. Read-only work (search, investigation, review, research) parallelizes freely.
563> 3. **Declare before dispatch:** `Parallel plan: wave 1 = [...] · wave 2 = [...] · SEQ = [...] (reason)`.
564> 4. **Spawn each wave in ONE message** — every `spawn_agent` call in one respon
565
566…(truncated)