
Plan
- 48 installs
- 7 repo stars
- Updated June 18, 2026
- duc01226/easyplatform
Creates an implementation plan with prompt enhancement, plus CI-fix and CRO planning modes.
About
A skill for intelligent plan creation with optional CI-fix and CRO modes. A developer uses it to turn a task into an enhanced, structured plan.
- Prompt-enhanced plan creation
- CI and CRO planning modes
Plan by the numbers
- 48 all-time installs (skills.sh)
- Ranked #1,641 of 3,282 Productivity & Planning skills by installs in the Skillselion catalog
- Data as of Jul 29, 2026 (Skillselion catalog sync)
npx skills add https://github.com/duc01226/easyplatform --skill planAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 48 |
|---|---|
| repo stars | ★ 7 |
| Last updated | June 18, 2026 |
| Repository | duc01226/easyplatform ↗ |
What it does
Creates an implementation plan with prompt enhancement, plus CI-fix and CRO planning modes.
Files
Codex compatibility note:
>
- Invoke repository skills with$skill-namein Codex; this mirrored copy rewrites legacy Claude/skill-namereferences.
- 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:START -->
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 fulldocs/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:
- Backend/CQRS/API/domain/entity changes:
backend-patterns-reference.md,domain-entities-reference.md,project-structure-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.mdplus the spec docs above - Derived spec indexes/ERDs/reimplementation guides:
spec-system-reference.mdand source Feature Specs underdocs/specs/ - Integration test implementation/review:
integration-test-reference.md - E2E test implementation/review:
e2e-test-reference.md - Code review/audit work:
code-review-rules.mdplus 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.
<!-- CODEX:PROJECT-REFERENCE-LOADING:END -->
<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:START -->
[BLOCKING] Execute skill steps in declared order. NEVER skip, reorder, merge steps without explicit user approval.
[BLOCKING] Before each step or sub-skill call, update task tracking:in_progresson start,completedon end.
[BLOCKING] Every completed/skipped step MUST include evidence or explicit skip reason.
[BLOCKING] If Task tools unavailable, maintain equivalent step-by-step plan tracker with same status transitions.
<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:END -->
Quick Summary
Goal: Research the codebase and collaborate with the user to deliver a validated, implementation-ready phased plan — every phase startable immediately (exact file paths, zero open decisions, mapped TC IDs) — so coding proceeds without rework at minimum future change cost.
Summary:
- PLANNING ONLY — never implement or execute code; this skill produces
plan.md+ per-phase files plus agoal.mdGoal Contract, then hands off. - Default mode is HARD (full rigor: parallel researcher subagents, project-reference docs, 3-round
$plan-review); opt to fast mode ONLY when every trivial-task condition holds. - Every phase must pass the 5-point granularity check ("Can I start coding RIGHT NOW?"), carry
## Test Specificationswith TC IDs, and use bottom-up estimation (phase-hours drive man-days; SP derived). - Two mandatory gates: detect any new tech/lib and create a validation task before approval, and ALWAYS run
$plan-reviewafter creation — confirm with the user via a direct user question before any next step.
Workflow:
1. Pre-Check — Detect active/suggested plan or create new directory 2. Research — Parallel researcher subagents explore aspects (max 5 tool calls each) 3. Codebase Analysis — Search for project reference docs (patterns-reference, project-structure, architecture, adr); scout if not found 4. Plan Creation — Planner subagent creates plan.md + phase-XX files with full sections 5. Post-Validation — Optionally interview user to confirm decisions via $plan-validate
Key Rules:
- PLANNING ONLY: do NOT implement or execute code changes
- Always run $plan-review after plan creation
- Ask user to confirm before any next step
- MANDATORY IMPORTANT MUST ATTENTION detect new tech/lib in plan and create validation task (see New Tech/Lib Gate below)
First Principle — Easy to Change
The success metric of every coding decision is _future change cost_.
DRY, SRP, abstraction, design patterns, naming, layering, tests — every
technique exists to serve one goal: making the next change cheaper.
Evaluating code, refactor, test, abstraction, ask: does this make next change cheaper or more expensive?
- Reject "best practices" raising change cost (premature abstraction,
speculative generality, leaky indirection, ceremony without payoff).
- Name real enemies in findings: **coupling, hidden state, duplicated
knowledge, unclear intent, irreversible decisions exposed too early**.
- Simpler design easy to change beats sophisticated design that isn't.
Apply this lens before invoking any specific rule, pattern, or checklist below — if a downstream rule raises change cost, this principle wins.
---
Default Mode Policy
Default mode HARD (full rigor). Every section below — parallel researcher subagents, 3-round $plan-review, base-class greps, microservices/event-driven analysis, mandatory user approval — applies by default.>
Opt out to fast mode ONLY when ALL true (task genuinely trivial):
>
- Single-file edit, ≤30 lines changed
- No design choice (only one reasonable approach)
- No cross-service impact, no contract change, no new dependency
- No new pattern — follows existing codebase pattern
- User explicitly asked for a quick change
>
Any condition fails → use full protocol below. When in doubt, default hard. Skipping rigor for non-trivial task wastes more time on rework than rigor saves.
>
Fast mode skips (and only skips): parallel researcher subagents (use direct grep instead), 3-round$plan-review(1 round),$plan-validateinterview (inline confirm only), New Tech/Lib Gate (only if truly no new deps).
New Tech/Lib Gate (MANDATORY for all plans)
MANDATORY IMPORTANT MUST ATTENTION after plan creation, detect new tech/packages/libraries not in project. If found: task tracking per lib → WebSearch top 3 alternatives → compare (fit, size, community, learning curve, license) → recommend with confidence % → a direct user question to confirm. Skip if plan uses only existing dependencies.
Greenfield Mode
Auto-detected: No existing codebase found (no discovered source directories, no manifest files, no populated project-config.json) → skill auto-switches to greenfield mode. Planning artifacts (docs/, plans/, .claude/) don't count — repository must have actual code directories with content.When greenfield detected:
1. Skip codebase analysis phase (researcher subagents grepping code) 2. Replace with: market research + business evaluation phase via WebSearch + WebFetch 3. Delegate architecture decisions to solution-architect agent 4. Output: plans/{id}/plan.md with greenfield-specific phases (domain model, tech stack, project structure) 5. Skip reading project reference docs (won't exist in greenfield) 6. Enable broad web research for tech landscape, best practices, framework comparisons 7. Every decision point requires ask the user directly with 2-4 options + confidence % 8. [CRITICAL] Business-First Protocol: Tech stack decisions come AFTER full business analysis. Do NOT ask user to pick tech stack upfront. Instead: complete business evaluation → derive technical requirements → research current market options → produce comparison report → present to user for decision. See solution-architect agent for full tech stack research methodology.
- Research reports <=150 lines; plan.md <=80 lines
- External Memory: Write all research and analysis to
.ai/workspace/analysis/{task-name}.analysis.md. Re-read ENTIRE analysis file before generating plan.
Run the planning methodology engine. Load the relevant references/engine-*.md for each phase (skip a phase per its own skip rule):
references/engine-research.md— Research & Analysis (skip if given researcher reports)references/engine-figma.md— Design Context Extraction (skip if no Figma URLs / backend-only)references/engine-codebase-understanding.md— Codebase Understanding (skip if given scout reports)references/engine-solution-design.md— Solution Design (trade-offs, security, performance, edge cases, architecture)references/engine-plan-organization.md— Plan Creation, Organization & Output Standards
Mode Dispatch (--mode={ci|cro})
Default (no `--mode` flag): IGNORE this section — run the standard plan flow below, byte-for-byte unchanged.--modeonly adds a domain-specific reference load + intake convention on top of the SAME engine, the SAME mandatory$plan-reviewgate, and the SAMEplanneragent. It never replaces the engine.
| Flag | Positional $ARGUMENTS | Load before planning | Plan frontmatter overrides |
|---|---|---|---|
--mode=ci | a GitHub Actions run/log URL | references/mode-ci.md (CI failure classes: build/test/env/Docker/dependencies) | priority: P1, tags: [ci, bugfix] |
--mode=cro | content/issues to optimize (optional screenshots/URL) | references/mode-cro.md (25-item CRO framework + multimodal intake) | priority: P2, tags: [cro, conversion] |
When a --mode is present: (1) read the matching references/mode-*.md; (2) apply its intake + domain focus to $ARGUMENTS; (3) run the standard plan workflow below — same planner subagent, same phase-file structure, same mandatory $plan-review. The mode adds a reference payload only.
Scaffolding-First Protocol (Conditional)
Activation conditions (ALL must be true):
1. Active workflow is workflow-greenfield-init OR workflow-big-feature 2. AI MUST ATTENTION self-investigate for existing base/foundational abstractions using these patterns:
- Abstract/base classes:
abstract class.*Base|Base[A-Z]\w+|Abstract[A-Z]\w+ - Generic interfaces:
interface I\w+<|IGeneric|IBase - Infrastructure abstractions:
IRepository|IUnitOfWork|IService|IHandler - Utility/extension layers:
Extensions|Helpers|Utils|Common(directories or classes) - Frontend foundations:
base.*component|base.*service|base.*store|abstract.*component(if frontend present) - DI/IoC registration: search for DI registration patterns idiomatic to project's framework
3. If existing scaffolding found → SKIP. Log: "Existing scaffolding detected at {file:line}. Skipping Phase 1 scaffolding." 4. If NO foundational abstractions found → PROCEED with scaffolding phase.
When activated:
Phase 1 of plan MUST ATTENTION be Architecture Scaffolding — all base abstract classes, generic interfaces, infrastructure abstractions, DI registration with OOP/SOLID principles. Runs BEFORE feature stories. AI self-investigates what base classes the tech stack needs. All infrastructure behind interfaces with at least one concrete implementation (Dependency Inversion).
When skipped: Plan proceeds normally — feature stories build on existing base classes.
PLANNING-ONLY — Collaboration Required
DO NOT use the manual plan-mode switching tool — already in a planning workflow.
DO NOT implement or execute any code changes.
COLLABORATE with user: ask decision questions, present options with recommendations.
After plan creation, ALWAYS run $plan-review to validate plan.ASK user to confirm plan before any next step.
Your mission
<task> $ARGUMENTS </task>
Pre-Creation Check (Active vs Suggested Plan)
Check ## Plan Context section in injected context:
- If "Plan:" shows a path → Active plan exists. Ask user: "Continue with this? [Y/n]"
- If "Suggested:" shows a path → Branch-matched hint only. Ask if user wants to activate or create new.
- If "Plan: none" → Create new plan using naming from
## Namingsection.
Workflow
1. If creating new: Create directory using Plan dir: from ## Naming section, then run node .claude/scripts/set-active-plan.cjs {plan-dir}. If reusing: Use active plan path from Plan Context. Pass directory path to every subagent during process. 2. Goal Contract bootstrap (BEFORE investigation and phase writing): resolve the active goal per SYNC:goal-contract-satisfaction-loop — create or update {plan-dir}/goal.md from .claude/templates/goal-contract-template.md, recording original request, purpose, success criteria, constraints, and required evidence. Every plan phase's success criteria must map to a saved goal criterion. Redact secrets. 3. Follow strictly the "Plan Creation & Organization" rules in references/engine-plan-organization.md. 4. Use researcher agents (max 2) in parallel: Each agent researches a different aspect; max 5 tool calls per agent. 5. Analyze codebase: search for project reference docs (patterns-reference, project-structure, architecture, adr); read those found. ONLY IF docs not found or older than 3 days: Use $scout <instructions> to search codebase for needed files. 6. Main agent gathers research/scout report filepaths; pass to planner subagent with prompt to create implementation plan. 7. Main agent receives implementation plan from planner subagent; ask user to review.
Post-Plan Validation (Optional)
After plan creation, offer validation interview to confirm decisions before implementation.
Check `## Plan Context` → `Validation: mode=X, questions=MIN-MAX`:
| Mode | Behavior |
|---|---|
prompt | Ask user: "Validate this plan with a brief interview?" → Yes (Recommended) / No |
auto | Automatically execute $plan-validate {plan-path} |
off | Skip validation step entirely |
If mode is `prompt`: Use a direct user question tool with options above. If user chooses validation or mode is `auto`: Execute $plan-validate {plan-path} SlashCommand.
Output Requirements
Plan Directory Structure (use Plan dir: from ## Naming section)
{plan-dir}/
├── research/
│ ├── researcher-XX-report.md
│ └── ...
├── reports/
│ ├── XX-report.md
│ └── ...
├── scout/
│ ├── scout-XX-report.md
│ └── ...
├── plan.md
├── phase-XX-phase-name-here.md
└── ...Research Output Requirements
- Research markdown reports concise (<=150 lines); cover all topics + citations.
Plan File Specification
- Every
plan.mdMUST ATTENTION start with YAML frontmatter:
---
title: '{Brief title}'
description: '{One sentence for card preview}'
status: pending
priority: P2
effort: { sum of phases, e.g., 4h }
story_points: { sum of phase SPs, e.g., 8 }
man_days_traditional: '{ total e.g., 6d (4d code + 2d test) }'
man_days_ai: '{ total with AI e.g., 3d (2d code + 1d test) }'
branch: { current git branch }
tags: [relevant, tags]
created: { YYYY-MM-DD }
---- Save overview at
{plan-dir}/plan.md(<80 lines): list each phase with status, progress, links to phase files. - For each phase, create
{plan-dir}/phase-XX-phase-name-here.mdwith sections: Context links, Overview, Key Insights, Requirements, Alternatives Considered (minimum 2 approaches with pros/cons), Design Rationale (WHY chosen approach), Architecture, UI Layout (see below), Related code files, Implementation Steps, Todo list, Success Criteria, Risk Assessment, Security Considerations, Next steps. - UI Layout: For frontend-facing phases, include ASCII wireframe. Classify components by tier (common/domain-shared/page-app). For backend-only phases:
## UI Layout→N/A — Backend-only change.
Behavior/Sync Planning Checks
- For behavior-changing work, every phase should name changed behavior, unchanged behavior to preserve, TC/test proof, and docs/spec sync action.
- For AI-extracted specs/TCs, plan must mark them reference-only until canonical acceptance.
- For
.claudeskills/hooks/workflows/sync tooling, plan must include generated mirror sync or explicit no-sync evidence.
IMPORTANT Task Planning Notes (MUST ATTENTION FOLLOW)
- Always plan and break work into many small todo tasks using task tracking
- Always add a final review todo task to verify work quality and identify fixes/enhancements
- MANDATORY FINAL TASKS: After creating all planning todo tasks, ALWAYS add these final tasks:
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. 2. Task: "Run $plan-validate" — Trigger $plan-validate skill to interview user with critical questions and validate plan assumptions 3. Task: "Run $plan-review" — Trigger $plan-review skill with deep 3-round protocol (R1: checklist, R2: code-proof trace, R3: adversarial simulation). Review depth based on SP: ≤3 → 2 rounds min, 4-8 → 3 rounds, >8 → 3 rounds + code-proof mandatory. 4. Task: "Run $why-review (standalone only)" — If NOT inside a workflow, trigger $why-review to validate design rationale, alternatives considered, and risk assessment in plan. Skip if a workflow already includes $why-review in its sequence. 5. Task: "Re-evaluate estimation against finalized plan" — Pre-completion estimates anchor on scope guesses; finalized phases reveal true cost. After phases/TCs/decisions are locked: (a) re-derive bottom_up_hours = Σ phase_hours from finalized phase files; (b) recompute likely_days, risk_margin_pct, min-max range per SYNC:estimation-framework; (c) compare to current frontmatter man_days_traditional / story_points. If |delta| > 20% → UPDATE frontmatter, add reestimate_delta_pct: <signed> + 1-line reestimate_reason. If |delta| > 50% → flag SHOULD-RESCOPE and surface to user via a direct user question before implementation.
Important Notes
- Activate needed skills from catalog during process.
- Token efficiency without sacrificing quality. Sacrifice grammar for concision in reports.
- Unresolved questions → list at end of report.
---
Standalone Review Gate (Non-Workflow Only)
MANDATORY IMPORTANT MUST ATTENTION: If skill is called outside a workflow (standalone$plan), generated plan MUST ATTENTION include$review-changesas a final phase/task in plan. Ensures all implementation changes get reviewed before commit even without a workflow enforcing it.
>
If already running inside a workflow (e.g.,workflow-feature,workflow-bugfix), skip this — workflow sequence handles$review-changesat appropriate step.
Next Steps (Standalone: MUST ATTENTION ask user via a direct user question. Skip if inside workflow.)
MANDATORY IMPORTANT MUST ATTENTION — NO EXCEPTIONS after completing this skill, MUST ATTENTION use a direct user question to present these options. Do NOT skip because task seems "simple" or "obvious" — user decides:
- "Proceed with full workflow (Recommended)" — Detect best workflow to continue from here (plan created). Ensures review, validation, implementation, testing steps aren't skipped.
- "$why-review" — Validate design rationale in plan before implementation (standalone only — skipped when workflow includes it)
- "$plan-review" — Validate plan before implementation
- "$plan-validate" — Interview user to confirm plan decisions
- "$plan-execute" — Start coding & testing the finalized plan (execute-the-plan implementation step). Recommended implementation route after the plan is validated.
- "Skip, continue manually" — user decides
Post-Plan Granularity Self-Check (MANDATORY)
After creating all phase files, run recursive decomposition loop:
1. Score each phase against 5-point criteria (file paths, no planning verbs, ≤30min steps, ≤5 files, no open decisions) 2. Each FAILING phase → create task to decompose into sub-plan (with own $plan → $plan-review → $plan-validate → fix cycle) 3. Re-score new phases. Repeat until ALL leaf phases pass (max depth: 3) 4. Self-question: "For each phase, can I start coding RIGHT NOW? If any needs 'figuring out' → sub-plan it."
Preservation Inventory (MANDATORY for bugfixes)
[IMPORTANT] Use task tracking to break ALL work into small tasks BEFORE starting — including tasks for each file read. Prevents context loss from long files. For simple tasks, MUST ATTENTION ask user whether to skip.
docs/project-reference/domain-entities-reference.md— Domain entity catalog, relationships, cross-service sync (read when task involves business entities/models)docs/specs/— Test specifications by module (read existing TCs to include test strategy in plan)
Each phase file MUST ATTENTION satisfy: <=5 files per phase, <=3h effort, clear success criteria, mapped test cases.
Evidence Gate: MANDATORY IMPORTANT MUST ATTENTION — every claim, finding, recommendation requires file:line proof or traced evidence with confidence percentage (>80% to act, <80% must verify first).External Memory: For complex or lengthy work (research, analysis, scan, review), write intermediate findings and final results to a report file in plans/reports/ — prevents context loss and serves as deliverable.<!-- SYNC:plan-granularity -->
Plan Granularity — Every phase must pass 5-point check before implementation:
>
1. Lists exact file paths to modify (not generic "implement X")
2. No planning verbs (research, investigate, analyze, determine, figure out)
3. Steps ≤30min each, phase total ≤3h
4. ≤5 files per phase
5. No open decisions or TBDs in approach
>
Failing phases → create sub-plan. Repeat until ALL leaf phases pass (max depth: 3).
Self-question: "Can I start coding RIGHT NOW? If any step needs 'figuring out' → sub-plan it."
<!-- /SYNC:plan-granularity -->
<!-- SYNC:preservation-inventory -->
Preservation Inventory — MANDATORY for bugfix plans. Trigger keywords in plan title/frontmatter:fix,bug,regression,broken,defect. Author MUST produce this table BEFORE writing implementation steps.
>
Columns: Invariant | file:line | Why (data consequence if broken) | Verification (TC-ID or grep)>
BLOCKED until: ≥3 rows · every File cell has file:line · every Verification cell has TC-ID or grep (not "manually verify")<!-- /SYNC:preservation-inventory -->
<!-- SYNC:nested-task-creation -->
Nested Task Expansion Contract — For workflow-step invocation, the [Workflow] ... row is only a parent container; the child skill still creates visible phase tasks.>
1. Call the current task list first. If a matching active parent workflow row exists, setnested=trueand recordparentTaskId; otherwise run standalone.
2. Create one task per declared phase before phase work. When nested, prefix subjects [N.M] $skill-name — phase.3. When nested, link the parent with TaskUpdate(parentTaskId, addBlockedBy: [childIds]).4. Orchestrators must pre-expand a child skill's phase list and link the workflow row before invoking that child skill or sub-agent.
5. Mark exactly one childin_progressbefore work andcompletedimmediately after evidence is written.
6. 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.<!-- /SYNC:nested-task-creation -->
<!-- SYNC:project-reference-docs-guide -->
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.
>
1. Identify scope: file types, domain area, and operation.
2. Required docs by trigger: alwaysdocs/project-reference/lessons.md; doc lookupdocs-index-reference.md; reviewcode-review-rules.md; backend/CQRS/APIbackend-patterns-reference.md; domain/entitydomain-entities-reference.md; frontend/UIfrontend-patterns-reference.md; styles/designscss-styling-guide.md+design-system/design-system-canonical.md; integration testsintegration-test-reference.md; E2Ee2e-test-reference.md; feature docs/specsfeature-spec-reference.md+spec-system-reference.md+spec-principles.md; behavior/public-contract/spec-test-code syncworkflow-spec-test-code-cycle-reference.md; derived spec index/ERD/reimplementation guidesspec-system-reference.md+ source Feature Specs underdocs/specs/; architecture/new areaproject-structure-reference.md.
3. Read every required doc. Ifdocs/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-initor the narrow lower-level route ($project-config,$docs-init,$scan-all,$scan --target=<key>,$claude-md-init) before ordinary project-specific work. If Codex mirrors orAGENTS.mdare missing/stale, ask the user to run$sync-codex; do not auto-run it.
4. Before target work, state: Reference docs read: ... | Not applicable: ....>
Ready when: scope evaluated, required docs checked/read or setup route completed, lessons.md confirmed, citation emitted.<!-- /SYNC:project-reference-docs-guide -->
<!-- SYNC:task-tracking-external-report -->
Task Tracking & External Report Persistence — Bootstrap this before execution; then run project-reference doc prefetch before target/source work.
>
1. Create a small task breakdown before target file reads, grep, edits, or analysis. On context loss, inspect the current task list first.
2. Mark one taskin_progressbefore work andcompletedimmediately after evidence; never batch transitions.
3. For plan/review work, create plans/reports/{skill}-{YYMMDD}-{HHmm}-{slug}.md before first finding.4. Append findings after each file/section/decision and synthesize from the report file at the end.
5. 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.
<!-- /SYNC:task-tracking-external-report -->
<!-- SYNC:critical-thinking-mindset -->
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.
<!-- /SYNC:critical-thinking-mindset -->
<!-- SYNC:sequential-thinking-protocol -->
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):
>
1. Thought N/M: [aspect] — one aspect per thought, state assumptions/uncertainty2. Thought N/M [REVISION of Thought K]: ... — when prior reasoning invalidated; state Original / Why revised / Impact3. Thought N/M [BRANCH A from Thought K]: ... — explore alternative; converge with decision rationale4.Thought N/M [HYPOTHESIS]: ...then[VERIFICATION]: ...— test before acting
5. 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 via ask 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-thinkingskill (.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).
<!-- /SYNC:sequential-thinking-protocol -->
<!-- SYNC:understand-code-first -->
Understand Code First — HARD-GATE: Do NOT write, plan, or fix until you READ existing code.
>
1. Search 3+ similar patterns (grep/glob) — citefile:lineevidence
2. Read existing files in target area — understand structure, base classes, conventions
3. Runpython .claude/scripts/code_graph trace <file> --direction both --jsonwhen.code-graph/graph.dbexists
4. Map dependencies viaconnectionsorcallers_of— know what depends on your target
5. Write investigation to .ai/workspace/analysis/ for non-trivial tasks (3+ files)6. Re-read analysis file before implementing — never work from memory alone. — why: long context drifts from the file; the file is ground truth
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
>
BLOCKED until:- [ ]Read target files- [ ]Grep 3+ patterns- [ ]Graph trace (if graph.db exists)- [ ]Assumptions verified with evidence
<!-- /SYNC:understand-code-first -->
<!-- SYNC:cross-service-check -->
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
<!-- /SYNC:cross-service-check -->
<!-- SYNC:estimation-framework -->
Estimation Framework — Bottom-up first; SP DERIVED; output min-max range when likely ≥3d. Stack-agnostic. Baseline: 3-5yr dev, 6 productive hrs/day. AI estimate assumes Claude Code + project context.
>
Method:
>
1. Blast Radius pass (below) — drives code AND test cost
2. Decompose phases → hours/phase → bottom_up_hours = Σ phase_hours3. likely_days = ceil(bottom_up_hours / 6) × productivity_factor4. Sum Risk Margin (base + add-ons) → max_days = likely_days × (1 + margin)5. min_days = likely_days × 0.96. Output as range whenlikely_days ≥3; single point allowed<3(still record margin)
7. man_days_ai = same range × AI speedup8.story_pointsDERIVED fromlikely_daysvia SP-Days — NEVER driver. Disagreement >50% → trust bottom-up
>
Productivity factor: 0.8 strong scaffolding+codegen+AI hooks · 1.0 mature default · 1.2 weak patterns · 1.5 greenfield
>
Cost Driver Heuristic (apply BEFORE work-type row):
>
- UI dominates in CRUD/business apps — 1.5-3x backend (states, validation, responsive, a11y, polish)
- Backend dominates ONLY: multi-aggregate invariants, cross-service contracts, schema migrations, heavy query/perf, new event flows
>
Reuse-vs-Create axis (PRIMARY lever, per layer):
>
| UI tier | Cost |
| -------------------------------------------- | -------- |
| Reuse component on existing screen | 0.1-0.3d |
| Add control/column to existing screen | 0.3-0.8d |
| Compose components into NEW screen | 1-2d |
| NEW screen, custom layout/states/validation | 2-4d |
| NEW shared/common component (themed, tested) | 3-6d+ |
>
| Backend tier | Cost |
| ---------------------------------------------------- | --------- |
| Reuse query/handler from new place | 0.1-0.3d |
| Small update existing handler/entity | 0.3-0.8d |
| NEW query on existing repo/model | 0.5-1d |
| NEW command/handler on existing aggregate (additive) | 1-2d |
| NEW aggregate/entity (repo, validation, events) | 2-4d |
| NEW cross-service contract OR schema migration | 2-4d each |
| Multi-aggregate invariant / heavy domain rule | 3-5d |
>
Rule: Sum tiers across UI+backend+tests, apply productivity factor. Reuse short-circuits tiers — call out.
>
Test-Scope drivers (compute test_count EXPLICITLY — "+tests" hand-wave is #1 failure):
>
| Driver | Count |
| --------------------------------- | ------------------------------------------------------ |
| Happy-path journeys | 1 per story / AC main flow |
| State-machine transitions | reachable transitions × allowed actors |
| Multi-entity state combos | state(A) × state(B) — REACHABLE only, not Cartesian |
| Authorization matrix | (owner, non-owner, elevated, unauth) × each mutation |
| Validation rules | 1 per required field / boundary / format / cross-field |
| UI states (per new screen/dialog) | happy, loading, empty, error, partial — present only |
| Negative paths / invariants | 1 per violatable business rule |
>
| Test tier (Trad, incl. setup+assert+flake) | Cost |
| ------------------------------------------ | -------- |
| 1-5 cases, fixtures reused | 0.3-0.5d |
| 6-12 cases, 1 new fixture | 0.5-1d |
| 13-25 cases, multi-entity setup | 1-2d |
| 26-50 cases OR new state-machine coverage | 2-3d |
| >50 cases OR full E2E journey | 3-5d |
>
Test multipliers: new fixture/seed harness +0.5d · cross-service/bus assertion +0.3d each · UI E2E ×1.5 · each new role +1-2 cases
>
Blast Radius (mandatory pre-pass — affects code AND test):
>
1. Files/components directly modified — count
2. Of those, "complex" (>500 LOC, multi-handler, central, frequently-modified) — count
3. Downstream consumers (callers, event subscribers, cross-service) — list
4. Shared/common code touched (multi-app blast) — yes/no
5. Regression scope — areas needing re-test
>
Rule: Complex touch → add risk_factors. Each downstream consumer → +1-3 regression cases. Blast >5 areas OR >2 complex → re-evaluate SPLIT before estimating.>
Risk Margin (drives max bound):
>
| likely_days | Base margin |
| ------------------- | ------------------------------- |
| <1d trivial | +10% |
| 1-2d small additive | +20% |
| 3-4d real feature | +35% |
| 5-7d large | +50% |
| 8-10d very large | +75% |
| >10d | +100% AND flag SHOULD SPLIT |
>
Risk-factor add-ons (additive — enumerate in `risk_factors`):
>
| Factor | +margin |
| --------------------------------------------------------------------- | ------- |
| touches-complex-existing-feature (>500 LOC, multi-handler, central) | +20% || cross-service-contract change | +25% || schema-migration-on-populated-data | +25% || new-tech-or-unfamiliar-pattern | +30% || regression-fan-out (≥3 downstream areas re-test) | +20% || performance-or-latency-critical | +20% || concurrency-race-event-ordering | +25% || shared-common-code (multi-consumer/multi-app) | +25% || unclear-requirements-or-design | +30% |>
Collapse rule: total margin >100% → STOP, split (padding past 2x is dishonesty). Margin <15% on likely_days ≥5 → under-estimated, widen.>
Work-Type Caps (hard ceilings on `likely_days`):
| Work type | Max SP | Max likely |
| --- | --- | --- |
| Single field / config flag / style fix | 1 | 0.5d |
| Add property to existing model + bind to existing UI | 2 | 1d |
| Additive endpoint + minor UI control (button/menu/column), reuses fixtures | 3 | 2-3d |
| Additive endpoint + NEW UI surface OR additive multi-layer + new domain rule + 2+ test files | 5 | 3-5d |
| NEW model/aggregate OR migration OR cross-module contract OR heavy test (>1.5d) OR NEW UI + non-trivial backend | 8 | 5-7d |
| NEW UI surface + (NEW aggregate OR migration OR cross-service contract) | 13 | SHOULD split |
| Cross-service contract + migration combined | 13 | SHOULD split |
| Beyond | 21 | MUST split |
>
SP→Days (validation only): 1=0.5d/0.25d · 2=1d/0.35d · 3=2d/0.65d · 5=4d/1.0d · 8=6d/1.5d · 13=10d/2.0d (Trad/AI likely)
AI speedup: SP 1≈2x · 2-3≈3x · 5-8≈4x · 13+≈5x. AI cost = (code_gen × 1.3) + (test_gen × 1.3) (30% review overhead).>
MANDATORY frontmatter:
>
```yaml
story_points: <n>
complexity: low | medium | high | critical
man_days_traditional: '<min>-<max>d' # range when likely ≥3d; '<N>d' when <3d
man_days_ai: '<min>-<max>d'
risk_margin_pct: <n> # base + add-ons
risk_factors: [touches-complex-existing-feature, regression-fan-out] # closed-list from add-ons; [] if none
blast_radius:
touched_areas: <n>
complex_touched: <n>
downstream_consumers: [list or count]
shared_common_code: yes | no
estimate_scope_included: [code, integration-tests, frontend, i18n, docs]
estimate_scope_excluded: [unit-tests, e2e, perf, deployment, code-review-rounds]
estimate_reasoning: |
5-7 lines covering:
(a) UI tier — row applied
(b) Backend tier — row applied
(c) Test scope — case breakdown by driver, file count, fixtures, tier row
(d) Cost driver — dominant tier + why
(e) Blast radius — touched, complex, regression scope
(f) Risk factors — list driving margin; why not larger/smaller
Example: "UI: compose Form/Table/Dialog → NEW screen (~1.5d). Backend: NEW command on existing aggregate,
reuses validation+repo (~1d). Tests: 4 transitions × 2 actors + 3 validation + 2 UI states = 13 cases,
1 new fixture → tier 13-25 ~1.5d. Driver: UI composition + new states. Blast: 4 areas, 1 complex.
Risk: base 35% + touches-complex +20% = 55% → max 3.9d → range 2.5-4d."
```
>
Sanity self-check:
>
- likely_days ≥3d and single-point? → reject, must be range- Margin <15% on likely_days ≥5d? → under-estimated, widen- Margin >100%? → STOP, split instead of buffer
- Complex existing feature touched, no regression budget in (c)? → reject- Blast>5areas OR>2complex, no split discussion? → reject
- Purely additive on existing model AND existing UI? → cap SP 3 unless tests >1.5d
- NEW UI surface (page/complex form/dashboard)? → SP 5+ even if backend one endpoint
- Backend cross-service / migration / multi-aggregate? → SP 8+ regardless of UI
- bottom_up_hours / 6 vs SP-Days disagreement >50%? → trust bottom-up, downgrade SP- Without tests, SP drops ≥1 bucket? → tests dominate; state explicitly
- Reasoning called out UI vs backend vs blast vs risk factors? → if missing, add
<!-- /SYNC:estimation-framework -->
<!-- SYNC:plan-quality -->
Plan Quality — Every plan phase MUST ATTENTION include test specifications.
>
1. Add ## Test Specifications section with TC-{FEATURE}-{NNN} IDs to every phase file2. Map every functional requirement to ≥1 TC (or explicit TBD with rationale)3. TC IDs follow TC-{FEATURE}-{NNN} format — reference by ID, never embed full content4. Before any new workflow step: call the current task list and re-read the phase file
5. On context compaction: call the current task list FIRST — never create duplicate tasks
6. Verify TC satisfaction per phase before marking complete (evidence must be file:line, not TBD)>
Mode: TDD-first → reference existing TCs withEvidence: TBD. Implement-first → use TBD →$spec [mode=tests]fills after.
<!-- /SYNC:plan-quality -->
<!-- SYNC:iterative-phase-quality -->
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.
<!-- /SYNC:iterative-phase-quality -->
<!-- SYNC:fix-layer-accountability -->
Fix-Layer Accountability — NEVER fix at the crash site. Trace the full flow, fix at the owning layer.
>
AI default behavior: see error at Place A → fix Place A. This is WRONG. The crash site is a SYMPTOM, not the cause.
>
MANDATORY before ANY fix:
>
1. Trace full data flow — Map the complete path from data origin to crash site across ALL layers (storage → backend → API → frontend → UI). Identify where the bad state ENTERS, not where it CRASHES.
2. Identify the invariant owner — Which layer's contract guarantees this value is valid? That layer is responsible. Fix at the LOWEST layer that owns the invariant — not the highest layer that consumes it.
3. One fix, maximum protection — Ask: "If I fix here, does it protect ALL downstream consumers with ONE change?" If fix requires touching 3+ files with defensive checks, you are at the wrong layer — go lower.
4. Verify no bypass paths — Confirm all data flows through the fix point. Check for: direct construction skipping factories, clone/spread without re-validation, raw data not wrapped in domain models, mutations outside the model layer.
>
BLOCKED until:- [ ]Full data flow traced (origin → crash)- [ ]Invariant owner identified withfile:lineevidence- [ ]All access sites audited (grep count)- [ ]Fix layer justified (lowest layer that protects most consumers)
>
Anti-patterns (REJECT these):
>
- "Fix it where it crashes" — Crash site ≠ cause site. Trace upstream.
- "Add defensive checks at every consumer" — Scattered defense = wrong layer. One authoritative fix > many scattered guards.
- "Both fix is safer" — Pick ONE authoritative layer. Redundant checks across layers send mixed signals about who owns the invariant.
<!-- /SYNC:fix-layer-accountability -->
<!-- SYNC:ai-mistake-prevention -->
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. Before changing a constant, limit, flag, wording, or pattern, read nearby context and history.
Surface ambiguity before acting — don't pick silently. Multiple valid interpretations require an explicit question or stated assumption with risk.
Keep shared guidance role-relevant. Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
<!-- /SYNC:ai-mistake-prevention -->
<!-- SYNC:estimation-framework:reminder -->
- MANDATORY MUST ATTENTION estimation: bottom-up phase hours drive
man_days_traditional(Σh/6 × productivity_factor); SP DERIVED. UI cost usually dominates — bump SP one bucket if NEW UI surface (page/complex form/dashboard). Frontmatter MUST includestory_points,complexity,man_days_traditional,man_days_ai,estimate_scope_included,estimate_scope_excluded,estimate_reasoning(UI vs backend cost driver). Cap SP 3 for additive-on-existing-model+existing-UI unless test scope >1.5d. SP 13 SHOULD split, SP 21 MUST split.
<!-- /SYNC:estimation-framework:reminder -->
<!-- SYNC:plan-quality:reminder -->
IMPORTANT MUST ATTENTION include ## Test Specifications with TC IDs per phase. Call the current task list before creating new tasks.
<!-- /SYNC:plan-quality:reminder -->
<!-- SYNC:plan-granularity:reminder -->
IMPORTANT MUST ATTENTION verify all phases pass 5-point granularity check. Failing phases → sub-plan. "Can I start coding RIGHT NOW?"
<!-- /SYNC:plan-granularity:reminder -->
<!-- SYNC:understand-code-first:reminder -->
IMPORTANT MUST ATTENTION search 3+ existing patterns and read code BEFORE any modification. Run graph trace when graph.db exists.
<!-- /SYNC:understand-code-first:reminder -->
<!-- SYNC:evidence-based-reasoning:reminder -->
- MANDATORY IMPORTANT MUST ATTENTION cite
file:lineevidence for every claim. Confidence >80% to act, <60% = do NOT recommend.
<!-- /SYNC:evidence-based-reasoning:reminder -->
<!-- SYNC:iterative-phase-quality:reminder -->
IMPORTANT MUST ATTENTION score complexity first. Score >=6 → decompose. Each phase: plan → implement → review → fix → verify. No skipping.
<!-- /SYNC:iterative-phase-quality:reminder -->
<!-- SYNC:fix-layer-accountability:reminder -->
IMPORTANT MUST ATTENTION trace full data flow and fix at the owning layer, not the crash site. Audit all access sites before adding ?..
<!-- /SYNC:fix-layer-accountability:reminder -->
<!-- SYNC:cross-service-check:reminder -->
IMPORTANT MUST ATTENTION microservices/event-driven: scan producers, consumers, sagas, contracts in task scope. Per touchpoint: owner · message · consumers · risk (NONE/ADDITIVE/BREAKING). Missing consumer = silent regression.
<!-- /SYNC:cross-service-check:reminder -->
<!-- SYNC:critical-thinking-mindset:reminder -->
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.
<!-- /SYNC:critical-thinking-mindset:reminder -->
<!-- SYNC:sequential-thinking-protocol:reminder -->
MUST ATTENTION apply sequential-thinking — multi-step Thought N/M, REVISION/BRANCH/HYPOTHESIS markers, confidence % closer; see $sequential-thinking skill.
<!-- /SYNC:sequential-thinking-protocol:reminder -->
<!-- SYNC:ai-mistake-prevention:reminder -->
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.
<!-- /SYNC:ai-mistake-prevention:reminder -->
<!-- SYNC:task-tracking-external-report:reminder -->
- 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.
<!-- /SYNC:task-tracking-external-report:reminder -->
<!-- SYNC:project-reference-docs-guide:reminder -->
- MANDATORY After task-tracking bootstrap and before target/source work, read required project-reference docs and cite
Reference docs read: .... - MANDATORY Always include
lessons.md; project conventions override generic defaults. - MANDATORY If project config, root instruction files, or any required reference doc is missing or stale, auto-run
$project-initor the narrow lower-level route before ordinary project-specific work.
<!-- /SYNC:project-reference-docs-guide:reminder -->
<!-- SYNC:nested-task-creation:reminder -->
- 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 — phaseprefixes and one-in_progressdiscipline.
<!-- /SYNC:nested-task-creation:reminder -->
<!-- SYNC:goal-contract-satisfaction-loop:reminder -->
- MANDATORY Resolve the active Goal Contract BEFORE work (active plan
goal.md→plans/goals/{YYMMDD-HHmm}-{slug}/goal.md→ create from current request) and read saved success criteria before editing. - MANDATORY Append iteration evidence after execution; emit a Goal Satisfaction matrix (PASS/FAIL/BLOCKED) before reporting PASS; loop on validated FAIL; escalate repeated no-progress or blockers. NEVER store secrets in goal files.
<!-- /SYNC:goal-contract-satisfaction-loop:reminder -->
Closing Reminders
IMPORTANT MUST ATTENTION Goal: deliver a validated, implementation-ready plan — every phase startable immediately (exact file paths, zero open decisions, mapped TC IDs) — so coding runs without rework at minimum future change cost.
Protocols in force (concise digest of the SYNC/shared blocks this skill carries):
- Plan Granularity: every phase passes the 5-point check or sub-plans.
- Preservation Inventory: bugfix plans tabulate invariants with
file:line+ verification. - Nested Task Creation: child skills expand visible phase tasks; link parent when nested.
- Project Reference Docs Guide: ALWAYS read required project docs before target work.
- Task Tracking & External Report: bootstrap tasks; persist findings to
plans/reports/. - Critical Thinking: every claim needs traced proof; confidence >80% to act.
- Sequential Thinking: multi-step Thought N/M with REVISION/BRANCH/HYPOTHESIS markers.
- Understand Code First: read code + grep 3+ patterns before planning.
- Cross-Service Check: scan producers, consumers, sagas, contracts for breaking risk.
- Estimation Framework: bottom-up phase hours drive man-days; SP DERIVED.
- Plan Quality: every phase carries
## Test Specificationswith TC IDs. - Iterative Phase Quality: score complexity first; decompose at score ≥6.
- Fix-Layer Accountability: NEVER fix at the crash site; fix the invariant owner.
- AI Mistake Prevention: verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
IMPORTANT MUST ATTENTION PLANNING ONLY — NEVER implement or execute code; produce plan.md + per-phase files + goal.md Goal Contract, then hand off — why: this skill's contract is a plan, not a change. IMPORTANT MUST ATTENTION default mode HARD — opt out to fast mode ONLY when ALL trivial-task conditions hold — why: skipping rigor on a non-trivial task costs more rework than rigor saves. MANDATORY IMPORTANT MUST ATTENTION break work into small todo tasks via task tracking BEFORE starting; add a final review todo; on context loss call the current task list first — never duplicate tasks. MANDATORY IMPORTANT MUST ATTENTION bootstrap the Goal Contract (goal.md from goal-contract-template.md) BEFORE investigation; every phase success criterion maps to a saved goal criterion. Redact secrets. MANDATORY IMPORTANT MUST ATTENTION validate decisions with user via a direct user question — NEVER auto-decide because a task seems "obvious"; the user decides the next step. MANDATORY IMPORTANT MUST ATTENTION every phase passes the 5-point granularity check ("Can I start coding RIGHT NOW?") — failing phases → sub-plan (max depth 3). MANDATORY IMPORTANT MUST ATTENTION detect new tech/lib not in project → task tracking per lib → WebSearch top 3 → compare → recommend with confidence % → a direct user question — why: an unvetted dependency is an irreversible decision exposed too early. MANDATORY IMPORTANT MUST ATTENTION estimation is bottom-up — phase hours drive man_days_traditional (Σh/6 × productivity_factor); SP DERIVED, never the driver; UI cost usually dominates; emit full estimate_reasoning frontmatter. MANDATORY IMPORTANT MUST ATTENTION every phase carries ## Test Specifications with TC-{FEATURE}-{NNN} IDs; map every functional requirement to ≥1 TC (or explicit Evidence: TBD for TDD-first). MANDATORY IMPORTANT MUST ATTENTION for .claude skills/hooks/workflows/sync work, plans MUST include generated-mirror sync action or explicit no-sync evidence — why: a silently stale mirror diverges from source. MANDATORY IMPORTANT MUST ATTENTION NEVER skip $plan-review after plan creation — run it standalone or as the workflow step; standalone $plan also appends $review-changes as a final task. IMPORTANT MUST ATTENTION search 3+ existing patterns and read target code BEFORE planning; cite file:line; run graph trace when .code-graph/graph.db exists — why: local conventions override generic framework defaults.
Anti-Rationalization:
| Evasion | Rebuttal |
|---|---|
| "Task too simple to plan" | Default mode HARD. Opt out ONLY when ALL trivial conditions hold. |
| "I already know the codebase" | Show file:line from 3+ patterns + graph trace. No proof = not read. |
| "Phase is clear enough" | Run the 5-point granularity check: "Can I start coding RIGHT NOW?" — else sub-plan. |
| "Plan looks good, skip review" | NEVER skip $plan-review — fresh eyes catch author blind spots. |
| "Only existing libs, skip the gate" | Prove it — grep manifests. Any new tech/lib → WebSearch + a direct user question before approval. |
| "I'll just estimate SP directly" | SP is DERIVED from bottom-up phase hours, never the driver. Σh/6 × productivity first. |
"It's a .claude change, no sync" | State the mirror action or explicit no-sync evidence — stale mirrors fail the oracle. |
[TASK-PLANNING] Before acting, analyze task scope and systematically break into small todo tasks and sub-tasks via task tracking.
IMPORTANT MUST ATTENTION PLANNING ONLY — never implement; cite file:line evidence (confidence >80% to act); NEVER skip $plan-review and the New Tech/Lib + Goal-Contract gates.
---
Closing reminder — Easy to Change is the success metric. Every finding,
test, refactor, and abstraction must answer one question: _does this make
the next change cheaper or more expensive?_ If it doesn't reduce future
change cost, reject it. Coupling, hidden state, duplicated knowledge, and
unclear intent are the real enemies — call them out by name.
<!-- CODEX:SYNC-PROMPT-PROTOCOLS:START -->
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.
1. 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. 2. ANALYZE: Choose the best option: execute directly, invoke a skill, activate a standard workflow, or compose a custom step combination. 3. AUTO-SELECT: Pick the best option yourself. Do not ask the user to choose between direct execution, skill, standard workflow, or custom workflow. 4. 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. 5. CREATE TASKS: task tracking for ALL workflow/skill/custom steps before execution when the selected path has multiple steps. 6. 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.
>
1. Keep reusable AI-SDD principles in .claude; put repository-specific paths, commands, owners, products, and formats in project config/reference docs.2. Preserve cycle: spec -> plan -> tasks -> implement -> verify -> update spec/docs.3. Trace every requirement or invariant through decision, task, TC/test, source evidence, and docs/spec update.
4. Treat code-to-spec extraction as reference-only until accepted by the canonical spec owner.
5. Any supported AI tool may plan, implement, review, or verify with synced context; using multiple tools is optional.
6. Update.claudesource first, then sync generated mirrors; do not manually edit.agents,.codex, orAGENTS.md. — why: mirrors are generated artifacts; hand-edits are overwritten on the next sync
7. Ifdocs/project-config.json, root instruction files, or a required project-reference doc is missing or stale, auto-run$project-initor 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.claudeand 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
.claudesource before syncing generated mirrors; do not manually edit.agents,.codex, orAGENTS.md. - MANDATORY Missing or stale project config, root instruction files, or required reference docs route project-specific work through
$project-initor 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:
1. Name the FAILURE MODE (reasoning/assumption failure), not symptom — "assumed API existed without reading source" not "used wrong enum value". 2. Generality test: does this failure mode apply to ≥3 contexts/codebases? If not, abstract one level up. 3. Write as a universal rule — strip project-specific names/paths/classes. Useful on any codebase. 4. Consolidate: multiple mistakes sharing one failure mode → ONE lesson. 5. Recurrence gate: "Would this recur in future session WITHOUT this reminder?" — No → skip $learn. 6. Auto-fix gate: "Could $code-review/$code-simplifier/$security-review/$lint catch this?" — Yes → improve review skill instead. 7. BOTH gates pass → ask user to run $learn. [CRITICAL-THINKING-MINDSET] Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act. Anti-hallucination principle: Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination. AI Attention principle (Primacy-Recency): Put the 3 most critical rules at both top and bottom of long prompts/protocols so instruction adherence survives long context windows. Goal-driven execution: Define success criteria first, loop until verified, and stop only when observable checks pass. Tests verify intent: Tests must protect business rules/invariants and fail when the protected intent breaks, not only mirror current behavior.
Common AI Mistake Prevention (System Lessons)
- Re-read files after context compaction. Edit requires prior Read in same context; compaction wipes read state. Re-read before editing.
- Grep for old terms after bulk replacements. AI over-trusts find/replace completeness. Grep full repo after bulk edits for missed refs in docs/configs/catalogs.
- Check downstream references before deleting. Deletions cascade doc/code staleness. Map referencing files before removal.
- After memory loss, check existing state before creating new. Compaction wipes prior-work memory. Query current state to resume — never blindly duplicate.
- Verify AI-generated content against actual code. AI hallucinates APIs, class names, method signatures. Grep to confirm existence before documenting/referencing.
- Trace full dependency chain after edits. Changing a definition misses downstream consumers. Trace the full chain.
- When renaming, grep ALL consumer file types. Some file types silently ignore missing refs (no compile error). Search code, templates, configs, generated files.
- Trace ALL code paths when verifying correctness. Code existing ≠ code executing. Trace early exits, error branches, conditional skips — not just happy path.
- Update docs that embed canonical data when source changes. Docs inlining derived data (workflows, schemas, configs) go stale silently. Update all embedding docs alongside source.
- Verify sub-agent results after context recovery. Background agents may finish while parent compacted — grep-verify output, don't trust assumed completion.
- Cross-check full target list against sub-agent assignments. Parallel sub-agents by category miss boundary items. Reconcile union of assignments against target list before proceeding.
- Sub-agents inherit knowledge only from their agent .md definition — use custom agent types, not built-in Explore. Tool adoption = permission + knowledge + enforcement (numbered workflow step).
- Persist sub-agent findings incrementally, not as a final batch. Long sub-agents hit cutoffs before final write — findings lost. Instruct append-per-section to report file.
- When debugging, ask "whose responsibility?" before fixing. Trace caller (wrong data) vs callee (wrong handling). Fix at responsible layer — never patch symptom site.
- Grep ALL removed names after extraction/refactoring. Primary file "done" ≠ secondary files clean. Grep entire scope for every removed symbol before declaring complete.
- Assume existing values are intentional — ask WHY before changing. Pattern-matching as "wrong" skips context. Before changing any constant/limit/flag: read comments, git blame, surrounding code.
- Verify ALL affected outputs, not just the first. One build green ≠ all green. Multi-stack changes (backend/frontend/tests/docs) require verifying EVERY output.
- Evaluate fit before copying a nearby pattern. Closest example ≠ matching preconditions — verify the new context shares the same constraints, base classes, scope, lifetime.
- Holistic-first debugging — resist nearest-attention trap. Don't dive into first plausible cause. List EVERY precondition (config, env vars, paths, DB, endpoints, creds, versions, DI, data). Verify each against evidence (grep/query — not reasoning). Ask "what would falsify this?" — if nothing, it's not a hypothesis. Most expensive failure: going deeper in "obvious" layer while bug sits in layer never questioned.
- Surgical changes — apply the diff test (context-aware). Two modes: (1) Bug fix → every line traces to the bug; no restyling; orphan cleanup only for imports YOUR changes made unused. (2) Review/enhancement → implement improvements AND announce as "Enhancement beyond main request: [what]". Never silently scope-creep. Diff test: "Would this line exist if I wasn't asked to do X?" — if no, delete or announce.
- Surface ambiguity before coding — don't pick silently. Multiple valid interpretations → present each with effort: "[Request] could mean (1) [N h], (2) [N h]. Which matters?" List scope/format/volume/constraints assumptions first. If simpler path exists, say so. Never silently pick.
- [MANDATORY FIRST ACTION] ALWAYS activate a suitable skill or workflow BEFORE responding. Match task against workflow catalog + skill list; invoke via skill invocation or
$start-workflow <workflowId>. NEVER answer or write code before checking. Skip = protocol violation. - Why-Review adversarial mindset — apply when reviewing any plan, decision, or design. Default SKEPTIC not VALIDATOR: steel-man a rejected alternative, invert each stated reason ("what does it sacrifice?"), stress-test top 2-3 assumptions, run pre-mortem ("ships, fails in 3 months — what breaks?"), surface 1-2 alternatives author missed. Section presence ≠ quality; quality = causal reasoning + concrete mitigations + evidence, not "it's better" or "monitor closely".
- Front-load report-write in sub-agent prompts for large reviews. Many-file sub-agents hit budget before final write — findings lost. Design prompts so: (1) report-write is first explicit deliverable, (2) append per-file/section (not batched), (3) scope bounded so reads don't exhaust budget. Truncated mid-sentence with no report file → spawn narrower scope, don't retry same prompt.
- After context compaction, re-verify all prior phase outcomes before continuing. Summaries describe intent, not environment state (git index, filesystem, processes). On resume, FIRST audit: git status, re-read modified files, verify filesystem. Every "completed" claim is an untested hypothesis until evidence confirms.
- OOM/memory: check row count before row size. Triage: (1) Unbounded query — no DB filter for trigger? Push filter to DB; eliminates OOM. (2) Large rows? Projection reduces proportionally. Row reduction > projection in ROI.
- Keep domain concepts out of generic/shared/infrastructure layers. Reusable layer (shared library, framework, infra module) must reference NO consumer-specific domain concept — tenant/customer/product IDs, business entities, feature rules. Leak compiles + runs → passes review silently while coupling the "reusable" layer to one consumer. Keep shared type domain-free; push domain fields/logic down into the consumer via subclass/composition. — why: a layer coupled to one consumer's domain is no longer reusable.
<!-- CODEX:SYNC-PROMPT-PROTOCOLS:END -->
Planning Engine — Codebase Understanding
3. Codebase Understanding (Skip if: Provided with scout reports)
Core Activities
Parallel Scout Agents
- Use
$scout --ext(external engine) or$scout(internal, default) slash command to search the codebase for files needed to complete the task - Each scout locates files needed for specific task aspects
- Wait for all scout agents to report back before analysis
- Efficient for finding relevant code across large codebases
Essential Documentation Review
ALWAYS read these files first:
1. `./.claude/docs/development-rules.md` (IMPORTANT)
- File Name Conventions
- File Size Management
- Development rules and best practices
- Code quality standards
- Security guidelines
2. `./docs/project-reference/backend-patterns-reference.md` + `./docs/project-reference/frontend-patterns-reference.md`
- Backend: CQRS, repositories, entities, validation, message bus
- Frontend: component base classes, state management, API services
- Naming conventions and coding standards
3. `./docs/project-reference/project-structure-reference.md`
- Service architecture, ports, directory tree
- Tech stack and module codes
4. `./docs/design-guidelines.md` (if exists)
- Design system guidelines
- Branding and UI/UX conventions
- Component library usage
Environment Analysis
- Review development environment setup
- Analyze dotenv files and configuration
- Identify required dependencies
- Understand build and deployment processes
Pattern Recognition
- Study existing patterns in codebase
- Identify conventions and architectural decisions
- Note consistency in implementation approaches
- Understand error handling patterns
Integration Planning
- Identify how new features integrate with existing architecture
- Map dependencies between components
- Understand data flow and state management
- Consider backward compatibility
Codebase Understanding Best Practices
- Start with documentation before diving into code
- Use scouts for targeted file discovery
- Document patterns found for consistency
- Note any inconsistencies or technical debt
- Consider impact on existing features
Planning Engine — Design Context Extraction (Figma)
2. Design Context Extraction
Skip if: No Figma URLs in source artifacts OR backend-only changes
When planning UI features:
1. Check source PBI/design-spec for Figma URLs 2. Extract design context via Figma MCP (if available) 3. Include design specifications in plan phases 4. Map design tokens to implementation
When to Apply
Apply when:
- Source artifact contains Figma URLs
- Task involves UI/frontend implementation
- Design specifications are referenced
Skip when:
- Backend-only changes
- No Figma URLs in artifacts
- Figma MCP not available (graceful degradation)
Detection Phase
1. Scan Source Artifacts
Check these locations for Figma URLs:
- PBI
## Design Referencesection - Design spec
figma_file:andfigma_nodes:frontmatter - Feature doc (if design reference exists in any section)
2. Parse URLs
Extract from each URL:
file_key: Figma file identifiernode_id: Specific frame/component (URL format:1-3)- Convert to API format:
1-3→1:3
URL Pattern:
https://figma.com/design/{file_key}/{name}?node-id={node_id}Extraction Phase
1. Check MCP Availability
If Figma MCP available:
→ Proceed with extraction
Else:
→ Log: "Figma MCP not configured, skipping design extraction"
→ Continue with URL references only2. Call MCP for Each Node
Prefer specific nodes over full files:
For each {file_key, node_id} pair:
If node_id exists:
Call: mcp__figma__get_file_nodes(file_key, [node_id])
Else:
Skip file-level extraction (too expensive)3. Extract Key Information
From response, extract:
| Property | Source Field |
|---|---|
| Structure | children[].name, children[].type |
| Layout | layoutMode, itemSpacing, padding* |
| Dimensions | absoluteBoundingBox.width/height |
| Colors | fills[].color (r,g,b,a → rgba) |
| Typography | style.fontFamily/fontSize/fontWeight |
4. Token Budget Enforcement
| Response Size | Action |
|---|---|
| <2K tokens | Use full response |
| 2K-5K tokens | Summarize to key properties |
| >5K tokens | Extract only critical info, warn user |
Integration Phase
1. Add to Plan Context
Include in plan.md overview:
## Design Context
Design specifications extracted from Figma:
| Component | Figma Node | Key Specs |
| --------- | ------------------ | ---------------------- |
| {name} | [{node_id}]({url}) | {dimensions}, {layout} |
### Extracted Specifications
{Formatted design context from extraction}2. Reference in Implementation Phases
For frontend phases, include:
## Design Specifications
From Figma node `{node_id}`:
### Layout
- Direction: {Horizontal/Vertical}
- Gap: {spacing}px
- Padding: {T/R/B/L}px
### Visual
- Background: {color} → map to `--color-bg-*`
- Border: {width}px {color} → map to `--border-*`
### Typography (if text)
- Font: {family} → map to `--font-family-*`
- Size: {size}px → map to `--font-size-*`
- Weight: {weight} → map to `--font-weight-*`3. Design Token Mapping
Map extracted values to existing tokens:
| Figma Value | Design Token | Notes |
|---|---|---|
| #FFFFFF | --color-bg-primary | Exact match |
| 16px | --spacing-md | Standard spacing |
| Inter 400 14px | --font-body | Body text |
Reference: docs/project-reference/design-system/design-tokens.scss for available tokens.
Fallback Behavior
When extraction fails:
1. MCP Not Available:
- Log warning
- Note in plan: "Design context not extracted (MCP unavailable)"
- Continue with URL references only
2. Node Not Found:
- Try parent node
- Note which nodes failed
- Continue with available data
3. Rate Limited:
- Extract first 3 nodes only
- Note in plan which nodes were skipped
4. Token Budget Exceeded:
- Summarize aggressively
- Include only dimensions, colors, layout
- Link to full Figma for details
Figma Output Template
## Figma Design Context
> Extracted via Figma MCP on {date}
### Source Designs
| Design | Node | Status |
| ------ | ------------- | --------- |
| {name} | [{id}]({url}) | Extracted |
### {Component Name}
**Node:** `{node_id}`
**Type:** {Frame/Component/Group}
**Dimensions:** {width} x {height}px
#### Layout
- Direction: {layoutMode}
- Gap: {itemSpacing}px
- Padding: {paddingTop}/{paddingRight}/{paddingBottom}/{paddingLeft}px
#### Visual
| Property | Value | Token Mapping |
| ------------- | ---------------- | ------------------- |
| Background | {fill color} | `--color-*` |
| Border | {stroke} | `--border-*` |
| Corner Radius | {cornerRadius}px | `--border-radius-*` |
#### Children
- {child1}: {type}
- {child2}: {type}No Design Context Template
When no Figma URLs present:
## Design Context
No Figma designs referenced. If UI changes are needed:
1. Add Figma links to source PBI `## Design Reference` section
2. Re-run planning to extract design contextPlanning Engine — Plan Creation, Organization & Output Standards
5. Plan Creation and Organization
Directory Structure
Plan Location
Use Plan dir: from ## Naming section injected by hooks. This is the full computed path.
Example: plans/251101-1505-authentication/ or ai_docs/feature/MRR-1453/
File Organization
{plan-dir}/ # From `Plan dir:` in ## Naming
├── research/
│ ├── researcher-XX-report.md
│ └── ...
├── reports/
│ ├── scout-report.md
│ ├── researcher-report.md
│ └── ...
├── plan.md # Overview access point
├── phase-01-setup-environment.md # Setup environment
├── phase-02-implement-database.md # Database models
├── phase-03-implement-api-endpoints.md # API endpoints
├── phase-04-implement-ui-components.md # UI components
├── phase-05-implement-authentication.md # Auth & authorization
├── phase-06-implement-profile.md # Profile page
└── phase-07-write-tests.md # TestsActive Plan State Tracking
Check the ## Plan Context section injected by hooks:
- "Plan: {path}" = Active plan - use for reports
- "Suggested: {path}" = Branch-matched, hint only - do NOT auto-use
- "Plan: none" = No active plan
Pre-Creation Check:
1. If "Plan:" shows a path → ask "Continue with existing plan? [Y/n]" 2. If "Suggested:" shows a path → inform user (hint only, do NOT auto-use) 3. If "Plan: none" → create new plan using naming from ## Naming section
After Creating Plan:
# Update session state so subagents get the new plan context:
node .claude/scripts/set-active-plan.cjs {plan-dir}Report Output Rules:
1. Use Report: and Plan dir: from ## Naming section 2. Active plans use plan-specific reports path 3. Suggested plans use default reports path to prevent old plan pollution
Plan File Structure
Overview Plan (plan.md)
IMPORTANT: All plan.md files MUST ATTENTION include YAML frontmatter. See output standards below for schema.
Example plan.md structure:
---
title: 'Feature Implementation Plan'
description: 'Add user authentication with OAuth2 support'
status: pending
priority: P1
effort: 8h
story_points: 8
complexity: High
man_days_traditional: '6d (4d code + 2d test)'
man_days_ai: '3d (2d code + 1d test)'
issue: 123
branch: kai/feat/oauth-auth
tags: [auth, backend, security]
created: 2025-12-16
---
# Feature Implementation Plan
## Overview
Brief description of what this plan accomplishes.
## Phases
| # | Phase | Status | Effort | SP | Link |
| --- | -------------- | ------- | ------ | --- | ------------------------------- |
| 1 | Setup | Pending | 2h | 3 | [phase-01](./phase-01-setup.md) |
| 2 | Implementation | Pending | 4h | 5 | [phase-02](./phase-02-impl.md) |
| 3 | Testing | Pending | 2h | 3 | [phase-03](./phase-03-test.md) |
## Dependencies
- List key dependencies hereGuidelines:
- Keep generic and under 80 lines
- List each phase with status/progress
- Link to detailed phase files
- Key dependencies
Phase Files (phase-XX-name.md)
Fully respect the ./.claude/docs/development-rules.md file. Each phase file should contain:
Context Links
- Links to related reports, files, documentation
Phase Overview
- Priority
- Current status
- Brief description
Key Insights
- Important findings from research
- Critical considerations
Requirements
- Functional requirements
- Non-functional requirements
Architecture
- System design
- Component interactions
- Data flow
Related Code Files
- List of files to modify
- List of files to create
- List of files to delete
Implementation Steps
- Detailed, numbered steps
- Specific instructions
Todo List
- Checkbox list for tracking
Success Criteria
- Definition of done
- Validation methods
Risk Assessment
- Potential issues
- Mitigation strategies
Security Considerations
- Auth/authorization
- Data protection
Test Specifications
| TC ID | Requirement | Priority | Evidence |
|---|---|---|---|
| TC-{FEATURE}-{NNN} | {requirement from this phase} | P0-P3 | {file:line} or TBD |
Coverage: {X}/{Y} requirements mapped to TCs
Next Steps
- Dependencies
- Follow-up tasks
6. Task Breakdown and Output Standards
Plan File Format
YAML Frontmatter (Required for plan.md)
All plan.md files MUST ATTENTION include YAML frontmatter at the top:
---
title: '{Brief plan title}'
description: '{One-sentence summary for card preview}'
status: pending # pending | in-progress | completed | cancelled
priority: P2 # P1 (High) | P2 (Medium) | P3 (Low)
effort: 4h # Estimated total effort
issue: 74 # GitHub issue number (if applicable)
branch: kai/feat/feature-name
tags: [frontend, api] # Category tags
created: 2025-12-16
---Auto-Population Rules
When creating plans, auto-populate these fields:
- title: Extract from task description
- description: First sentence of Overview section
- status: Always
pendingfor new plans - priority: From user request or default
P2 - effort: Sum of phase estimates
- issue: Parse from branch name or context
- branch: Current git branch (
git branch --show-current) - tags: Infer from task keywords (e.g., frontend, backend, api, auth)
- created: Today's date in YYYY-MM-DD format
Tag Vocabulary (Recommended)
Use these predefined tags for consistency:
- Type:
feature,bugfix,refactor,docs,infra - Domain:
frontend,backend,database,api,auth - Scope:
critical,tech-debt,experimental
Task Breakdown Rules
- Transform complex requirements into manageable, actionable tasks
- Each task independently executable with clear dependencies
- Prioritize by dependencies, risk, business value
- Eliminate ambiguity in instructions
- Include specific file paths for all modifications
- Provide clear acceptance criteria per task
File Management
List affected files with:
- Full paths (not relative)
- Action type (modify/create/delete)
- Brief change description
- Dependencies on other changes
- Fully respect the
./.claude/docs/development-rules.mdfile.
Output Workflow Process
1. Initial Analysis → Read docs, understand context 2. Research Phase → Spawn researchers in parallel, investigate approaches 3. Synthesis → Analyze reports, identify optimal solution 4. Design Phase → Create architecture, implementation design 5. Plan Documentation → Write comprehensive plan in Markdown 6. Review & Refine → Ensure completeness, clarity, actionability
Output Requirements
What Planners Do
- Create plans ONLY (no implementation)
- Provide plan file path and summary
- Self-contained plans with necessary context
- Code snippets/pseudocode when clarifying
- Multiple options with trade-offs when appropriate
- Fully respect the
./.claude/docs/development-rules.mdfile.
Writing Style
IMPORTANT: Sacrifice grammar for concision
- Focus clarity over eloquence
- Use bullets and lists
- Short sentences
- Remove unnecessary words
- Prioritize actionable info
Unresolved Questions
IMPORTANT: List unresolved questions at end
- Questions needing clarification
- Technical decisions requiring input
- Unknowns impacting implementation
- Trade-offs requiring business decisions
Design Context for UI Phases
If Figma designs were extracted, include in phase files:
## Design Specifications
> From Figma: [{component_name}]({figma_url})
### Layout
{Extracted layout specifications}
### Visual Styling
| Property | Figma Value | Token |
| -------- | ----------- | -------------- |
| {prop} | {value} | `--token-name` |
### Implementation Notes
- {Note about design-to-code mapping}
- {Any deviations from design system}When no Figma context:
- Omit section or note "No design specifications provided"
Output Quality Standards
Thoroughness
- Thorough and specific in research/planning
- Consider edge cases, failure modes
- Think through entire user journey
- Document all assumptions
Maintainability
- Consider long-term maintainability
- Design for future modifications
- Document decision rationale
- Keep designs minimal — avoid over-engineering
- Fully respect the
./.claude/docs/development-rules.mdfile.
Research Depth
- When uncertain, research more
- Multiple options with clear trade-offs
- Validate against best practices
- Consider industry standards
Security and Performance
- Address all security concerns
- Identify performance implications
- Plan for scalability
- Consider resource constraints
Implementability
- Detailed enough for junior developers
- Validate against existing patterns
- Ensure codebase standards consistency
- Provide clear examples
Remember: Plan quality determines implementation success. Be comprehensive, consider all solution aspects.
Workflow Process
1. Initial Analysis → Read codebase docs, understand context 2. Design Context → Extract Figma design specs (if URLs present) 3. Research Phase → Spawn researchers, investigate approaches 4. Synthesis → Analyze reports, identify optimal solution 5. Design Phase → Create architecture, implementation design 6. Plan Documentation → Write comprehensive plan (include design context) 7. Review & Refine → Ensure completeness, clarity, actionability
Top-Level Output Requirements
- DO NOT implement code - only create plans
- Respond with plan file path and summary
- Ensure self-contained plans with necessary context
- Include code snippets/pseudocode when clarifying
- Provide multiple options with trade-offs when appropriate
- Fully respect the
./.claude/docs/development-rules.mdfile.
Plan Directory Structure
plans/
└── {date}-plan-name/
├── research/
│ ├── researcher-XX-report.md
│ └── ...
├── reports/
│ ├── XX-report.md
│ └── ...
├── scout/
│ ├── scout-XX-report.md
│ └── ...
├── plan.md
├── phase-XX-phase-name-here.md
└── ...Active Plan State
Prevents version proliferation by tracking current working plan via session state.
Active vs Suggested Plans
Check the ## Plan Context section injected by hooks:
- "Plan: {path}" = Active plan, explicitly set via
set-active-plan.cjs- use for reports - "Suggested: {path}" = Branch-matched, hint only - do NOT auto-use
- "Plan: none" = No active plan
Rules
1. If "Plan:" shows a path: Ask "Continue with existing plan? [Y/n]" 2. If "Suggested:" shows a path: Inform user, ask if they want to activate or create new 3. If "Plan: none": Create new plan using naming from ## Naming section 4. Update on create: Run node .claude/scripts/set-active-plan.cjs {plan-dir}
Report Output Location
All agents writing reports MUST ATTENTION:
1. Check ## Naming section injected by hooks for the computed naming pattern 2. Active plans use plan-specific reports path 3. Suggested plans use default reports path (not plan folder)
Important: Suggested plans do NOT get plan-specific reports - this prevents pollution of old plan folders.
Quality Standards
- Be thorough and specific
- Consider long-term maintainability
- Research thoroughly when uncertain
- Address security and performance concerns
- Make plans detailed enough for junior developers
- Validate against existing codebase patterns
Remember: Plan quality determines implementation success. Be comprehensive and consider all solution aspects.
Related
workflow-featureproblem-solvingplan-analysis
---
IMPORTANT Task Planning Notes (MUST ATTENTION FOLLOW)
- Always plan and break work into many small todo tasks using task tracking
- Always add a final review todo task to verify work quality and identify fixes/enhancements
- MANDATORY FINAL TASKS: After creating all planning todo tasks, ALWAYS add these three final tasks:
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. 2. Task: "Run $plan-validate" — Trigger $plan-validate skill to interview the user with critical questions and validate plan assumptions 3. Task: "Run $plan-review" — Trigger $plan-review skill to auto-review plan for validity, correctness, and best practices
Important Notes
IMPORTANT: Analyze the skills catalog and activate the skills that are needed for the task during the process. IMPORTANT: Ensure token efficiency while maintaining high quality. IMPORTANT: Sacrifice grammar for the sake of concision when writing reports. IMPORTANT: In reports, list any unresolved questions at the end, if any.
REMINDER — Planning-Only Skill
DO NOT use manual plan-mode switching tool.
DO NOT start implementing.
ALWAYS validate with $plan-review after plan creation.ASK user to confirm the plan before any implementation begins.
ASK user decision questions with your recommendations when multiple approaches exist.
---
Post-Plan Granularity Self-Check (MANDATORY)
After creating all phase files, run the recursive decomposition loop:
1. Score each phase against the 5-point criteria (file paths, no planning verbs, ≤30min steps, ≤5 files, no open decisions) 2. For each FAILING phase → create task to decompose it into a sub-plan (with its own $plan → $plan-review → $plan-validate → fix cycle) 3. Re-score new phases. Repeat until ALL leaf phases pass (max depth: 3) 4. Self-question: "For each phase, can I start coding RIGHT NOW? If any needs 'figuring out' → sub-plan it."
[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.
docs/specs/— Test specifications by module (read existing TCs to include test strategy in plan)
Planning Engine — Research & Analysis
1. Research & Analysis (Skip if: Provided with researcher reports)
Core Activities
Parallel Researcher Agents
- Spawn multiple
researcheragents in parallel to investigate different approaches - Wait for all researcher agents to report back before proceeding
- Each researcher investigates a specific aspect or approach
Sequential Thinking
- Use
sequential-thinkingskill for dynamic and reflective problem-solving - Structured thinking process for complex analysis
- Enables multi-step reasoning with revision capability
Documentation Research
- Use
docs-seekerskill to read and understand documentation - Research plugins, packages, and frameworks
- Find latest technical documentation using llms.txt standard
GitHub Analysis
- Use
ghcommand to read and analyze: - GitHub Actions logs
- Pull requests
- Issues and discussions
- Extract relevant technical context from GitHub resources
Remote Repository Analysis
When given GitHub repository URL, generate fresh codebase summary:
# usage:
repomix --remote <github-repo-url>
# example:
repomix --remote https://github.com/mrgoonie/human-mcpDebugger Delegation
- Delegate to
debuggeragent for root cause analysis - Use when investigating complex issues or bugs
- Debugger agent specializes in diagnostic tasks
Search Strategy
Primary: Gemini CLI
Check if gemini bash command is available:
gemini -m gemini-2.5-flash -p "...your search prompt..."
# Timeout: 10 minutesSave output using Report: path from ## Naming section (include all citations).
Fallback: WebSearch Tool
If gemini unavailable, use WebSearch tool. Run multiple searches in parallel.
Query Crafting
- Craft precise search queries with relevant keywords
- Include terms like "best practices", "2024", "latest", "security", "performance"
- Search for official documentation, GitHub repositories, and authoritative blogs
- Prioritize results from recognized authorities (official docs, major tech companies, respected developers)
IMPORTANT: 5-Research Limit
You are allowed to perform at most 5 researches (max 5 tool calls). User might request less. Think carefully based on the task before performing each research.
Deep Content Analysis
- When you find a potential GitHub repository URL, use
docs-seekerskill to read it - Focus on official documentation, API references, and technical specifications
- Analyze README files from popular GitHub repositories
- Review changelog and release notes for version-specific information
Video Content Research
- Prioritize content from official channels, recognized experts, and major conferences
- Focus on practical demonstrations and real-world implementations
Cross-Reference Validation
- Verify information across multiple independent sources
- Check publication dates to ensure currency
- Identify consensus vs. controversial approaches
- Note any conflicting information or debates in the community
Research Report Template
# Research Report: [Topic]
## Executive Summary
[2-3 paragraph overview of key findings and recommendations]
## Research Methodology
- Sources consulted: [number]
- Date range of materials: [earliest to most recent]
- Key search terms used: [list]
## Key Findings
### 1. Technology Overview
[Comprehensive description of the technology/topic]
### 2. Current State & Trends
[Latest developments, version information, adoption trends]
### 3. Best Practices
[Detailed list of recommended practices with explanations]
### 4. Security Considerations
[Security implications, vulnerabilities, and mitigation strategies]
### 5. Performance Insights
[Performance characteristics, optimization techniques, benchmarks]
## Comparative Analysis
[If applicable, comparison of different solutions/approaches]
## Implementation Recommendations
### Quick Start Guide
[Step-by-step getting started instructions]
### Code Examples
[Relevant code snippets with explanations]
### Common Pitfalls
[Mistakes to avoid and their solutions]
## Resources & References
### Official Documentation
- [Linked list of official docs]
### Recommended Tutorials
- [Curated list with descriptions]
### Community Resources
- [Forums, Discord servers, Stack Overflow tags]
## Appendices
### A. Glossary
### B. Version Compatibility Matrix
### C. Raw Research Notes (optional)Research Quality Standards
Ensure all research meets these criteria:
- Accuracy: Information is verified across multiple sources
- Currency: Prioritize information from the last 12 months unless historical context is needed
- Completeness: Cover all aspects requested by the user
- Actionability: Provide practical, implementable recommendations
- Clarity: Use clear language, define technical terms, provide examples
- Attribution: Always cite sources and provide links for verification
Special Considerations
- When researching security topics, always check for recent CVEs and security advisories
- For performance-related research, look for benchmarks and real-world case studies
- When investigating new technologies, assess community adoption and support levels
- For API documentation, verify endpoint availability and authentication requirements
- Always note deprecation warnings and migration paths for older technologies
Research Best Practices
- Research breadth before depth
- Document findings for synthesis phase
- Identify multiple approaches for comparison
- Consider edge cases during research
- Note security implications early
- Sacrifice grammar for concision in reports
- List unresolved questions at the end
Planning Engine — Solution Design
4. Solution Design
Core Principles
- YAGNI (You Aren't Gonna Need It) - Don't add functionality until necessary
- KISS (Keep It Simple, Stupid) - Prefer simple solutions over complex ones
- DRY (Don't Repeat Yourself) - Avoid code duplication
Design Activities
Technical Trade-off Analysis
- Evaluate multiple approaches for each requirement
- Compare pros and cons of different solutions
- Consider short-term vs long-term implications
- Balance complexity with maintainability
- Assess development effort vs benefit
- Recommend optimal solution based on current best practices
Security Assessment
- Identify potential vulnerabilities during design phase
- Consider authentication and authorization requirements
- Assess data protection needs
- Evaluate input validation requirements
- Plan for secure configuration management
- Address OWASP Top 10 concerns
- Consider API security (rate limiting, CORS, etc.)
Performance and Scalability
- Identify potential bottlenecks early
- Consider database query optimization needs
- Plan for caching strategies
- Assess resource usage (memory, CPU, network)
- Design for horizontal/vertical scaling
- Plan for load distribution
- Consider asynchronous processing where appropriate
Edge Cases and Failure Modes
- Think through error scenarios
- Plan for network failures
- Consider partial failure handling
- Design retry and fallback mechanisms
- Plan for data consistency
- Consider race conditions
- Design for graceful degradation
Architecture Design
- Create scalable system architectures
- Design for maintainability
- Plan component interactions
- Design data flow
- Consider microservices vs monolith trade-offs
- Plan API contracts
- Design state management
Frontend Solution Design
When designing frontend solutions with Figma context:
Design Context Integration
1. Check for Figma Context
- Review extracted design specifications
- Verify dimensions and spacing match design system
- Note any custom values needing tokens
2. Component Structure
- Match Figma hierarchy to the configured frontend component tree
- Identify reusable components
- Map to existing shared library components
3. Token Mapping
- Map Figma colors to design tokens
- Verify spacing uses standard tokens
- Flag any values needing new tokens
4. Responsive Considerations
- Check if Figma shows breakpoint variants
- Plan responsive behavior for unlisted breakpoints
- Note any mobile-specific layouts
Solution Design Best Practices
- Document design decisions and rationale
- Consider both technical and business requirements
- Think through the entire user journey
- Plan for monitoring and observability
- Design with testing in mind
- Consider deployment and rollback strategies
$plan --mode=ci — CI / GitHub Actions failure-analysis reference
Loaded byplan/SKILL.md's Mode Dispatch when invoked as$plan --mode=ci <github-actions-log-url>. Adds a CI-failure domain focus on top of the standard plan engine +$plan-reviewgate +planneragent — it does NOT replace them. (Migrated verbatim from the formerplan-ciskill, consolidation M22.)
Goal
Analyze GitHub Actions CI logs and create a plan to fix the identified issues.
Positional argument
$ARGUMENTS = the GitHub Actions run / log URL.
Intake + focus
1. Fetch — Download / read the CI logs from the GitHub Actions run URL. 2. Analyze — Identify root causes from build/test failures. Focus on CI-specific failure classes: build, test, env, Docker, dependencies. 3. Plan — Create an implementation plan to fix the CI issues.
Use the planner subagent to read the GitHub Actions logs, analyze and find the root causes of the issues, then provide a detailed plan for implementing the fixes.
Plan frontmatter overrides (vs the standard plan defaults)
priority: P1
tags: [ci, bugfix]Output
Provide at least 2 implementation approaches with clear trade-offs, explain the pros and cons of each, and provide a recommended approach.
Key rules
- PLANNING-ONLY: do not implement, only create the fix plan.
- Always offer
$plan-reviewafter plan creation (standardplangate — unchanged). - Be skeptical; every claim needs traced proof, confidence >80% to act.
$plan --mode=cro — Conversion-Rate-Optimization reference
Loaded byplan/SKILL.md's Mode Dispatch when invoked as$plan --mode=cro <content/issues-to-optimize>. Adds the CRO domain framework + multimodal intake on top of the standard plan engine +$plan-reviewgate +planneragent — it does NOT replace them. (Migrated verbatim from the formerplan-croskill, consolidation M22.)
Goal
Create a CRO (Conversion Rate Optimization) plan for the given content or feature. You are an expert in conversion optimization; analyze the content based on the given issues.
Positional argument
$ARGUMENTS = the content / issues to optimize (optionally accompanied by screenshots, videos, or a URL — see Multimodal intake).
Conversion Optimization Framework (apply all 25)
1. Headline 4-U Formula: Useful, Unique, Urgent, Ultra-specific (80% won't read past this) 2. Above-Fold Value Proposition: Customer problem focus, no company story, zero scroll required 3. CTA First-Person Psychology: "Get MY Guide" vs "Get YOUR Guide" (90% more clicks) 4. 5-Field Form Maximum: Every field kills conversions, progressive profiling for the rest 5. Message Match Precision: Ad copy, landing page headline, broken promises = bounce 6. Social Proof Near CTAs: Testimonials with faces/names, results, placed at decision points 7. Cognitive Bias Stack: Loss aversion (fear), social proof (FOMO), anchoring (pricing) 8. PAS Copy Framework: Problem > Agitate > Solve, emotion before logic 9. Genuine Urgency Only: Real deadlines, actual limits, fake timers destroy trust forever 10. Price Anchoring Display: Show expensive option first, make real price feel like relief 11. Trust Signal Clustering: Security badges, guarantees, policies all visible together 12. Visual Hierarchy F-Pattern: Eyes scan F-shape, put conversions in the path 13. Lead Magnet Hierarchy: Templates > Checklists > Guides (instant > delayed gratification) 14. Objection Preemption: Address top 3 concerns before they think them, FAQ near CTA 15. Mobile Thumb Zone: CTAs where thumbs naturally rest, not stretching required 16. One-Variable Testing: Change one thing, measure impact, compound wins over time 17. Post-Conversion Momentum: Thank you page sells next step while excitement peaks 18. Cart Recovery Sequence: Email in 1 hour, retarget in 4 hours, incentive at 24 hours 19. Reading Level Grade 6: Smart people prefer simple, 11-word sentences, short paragraphs 20. TOFU/MOFU/BOFU Logic: Awareness content ≠ decision content, match intent precisely 21. White Space = Focus: Empty space makes CTAs impossible to miss, crowded = confused 22. Benefit-First Language: Features tell, benefits sell, transformations compel 23. Micro-Commitment Ladder: Small yes leads to big yes, start with email only 24. Performance Tracking Stack: Heatmaps show problems, recordings show why, events show what 25. Weekly Optimization Ritual: Review metrics Monday, test Tuesday, iterate or scale
Multimodal intake
- If the user provides screenshots or videos, use the
visual analysis toolingskill to describe the issue in as much detail as possible so the CRO analyst can fully understand it from the description. - If the user provides a URL, use the
web_fetchtool to fetch the content and analyze current issues. - You can use screenshot-capture tools with the
visual analysis toolingskill to capture the exact parent container and analyze issues with the appropriate Gemini analysis skills (visual analysis tooling,gemini-video-understanding, orgemini-document-processing).
Plan frontmatter overrides (vs the standard plan defaults)
priority: P2
tags: [cro, conversion]Key rules
- PLANNING-ONLY: do not implement, only create the CRO plan.
- Focus on user behavior, conversion funnels, and measurable outcomes.
- Always offer
$plan-reviewafter plan creation (standardplangate — unchanged). - Be skeptical; every claim needs traced proof, confidence >80% to act.