Codex compatibility note:
- Invoke repository skills with
$skill-name in Codex; this mirrored copy rewrites legacy Claude /skill-name references.
- Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.
- User-question prompts mean to ask the user directly in Codex.
- Ignore Claude-specific mode-switch instructions when they appear.
- Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.
- Subagent authorization: when a skill is user-invoked or AI-detected and its protocol requires subagents, that skill activation authorizes use of the required
spawn_agent subagent(s) for that task.
- Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.
- For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.
- If a required step/tool cannot run in this environment, stop and ask the user before adapting.
Codex Project-Reference Loading (No Hooks)
Codex uses static project-reference loading instead of runtime-injected project docs.
When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.
Always read:
docs/project-config.json (project-specific paths, commands, modules, and workflow/test settings)
docs/project-reference/docs-index-reference.md (routes to the full docs/project-reference/* catalog)
docs/project-reference/lessons.md (always-on guardrails and anti-patterns)
Missing/stale context route: If docs/project-config.json, the docs index, lessons.md, CLAUDE.md, AGENTS.md, or any task-required reference doc is missing or stale, auto-run $project-init or the narrow setup route ($project-config, $docs-init, $scan-all, $scan --target=<key>, $claude-md-init) before ordinary project-specific work. If Codex mirrors or AGENTS.md are missing/stale, ask the user to run $sync-codex; do not auto-run it.
Situation-based docs:
- Project structure/architecture/tech-stack/deployment/setup (any layer — backend, frontend, or infra):
project-structure-reference.md
- Backend/CQRS/API/domain/entity changes:
backend-patterns-reference.md, domain-entities-reference.md
- Frontend/UI/styling/design-system:
frontend-patterns-reference.md, scss-styling-guide.md, design-system/README.md
- Spec authoring,
docs/specs/ pathing, or TC format: feature-spec-reference.md, spec-system-reference.md, spec-principles.md
- Behavior/public-contract changes or spec-test-code sync:
workflow-spec-test-code-cycle-reference.md plus the spec docs above
- Derived spec indexes/ERDs/reimplementation guides:
spec-system-reference.md and source Feature Specs under docs/specs/
- Integration test implementation/review:
integration-test-reference.md
- E2E test implementation/review:
e2e-test-reference.md
- Code review/audit work:
code-review-rules.md plus domain docs above based on changed files
Do not read all docs blindly. Start from docs-index-reference.md, then open only relevant files for the task.
Quick Summary
Goal: Two operations — (A) propagate updated content for existing SYNC: blocks across all skills, or (B) add a new SYNC: block to all skill/agent files that don't have it yet.
Renamed: formerly /sync-protocols — that name no longer resolves as a slash command; use $sync-skills-shared-protocols.
Canonical source: .claude/skills/shared/sync-inline-versions.md
Workflow
Operation A: Update Existing Block Content
Use when a SYNC: block already exists in files and push updated content to all of them.
Step 1: Identify What Changed
If user specifies a tag name (e.g., sync-skills-shared-protocols understand-code-first):
If no tag specified:
- Read
sync-inline-versions.md
- Ask user which tag(s) to sync, or "all"
Step 2: Read Canonical Content
For each tag to sync:
- Read
.claude/skills/shared/sync-inline-versions.md
- Extract content under
## SYNC:{tag-name} heading (everything between that heading and the next --- or ## SYNC:)
Step 3: Find All Skills with Tag
grep -rl "SYNC:{tag-name}" .claude/skills/*/SKILL.md
Step 4: Replace Content in Each Skill
For each file found:
- Find
<!-- SYNC:{tag-name} --> open tag
- Find
<!-- /SYNC:{tag-name} --> close tag
- Replace everything between them with the canonical content
- Do NOT touch
:reminder blocks — those are separate, shorter versions
Step 5: Verify
Run these checks after all replacements:
# 1. SYNC tag balance (all opens have matching closes)
# 2. Content matches canonical source
# 3. No content outside SYNC blocks was modified
Report:
- Tags synced
- Files updated (count)
- Any balance issues
Step 6: Reminder Blocks
:reminder blocks (<!-- SYNC:{tag}:reminder -->) are 1-line summaries at the bottom of skills for AI recency attention. These are NOT auto-synced — they are hand-written. Skip them unless user explicitly asks to update reminders too.
Operation B: Add a New Tiered Block
Use when a NEW SYNC: block needs tiered propagation. Derive the on-disk target inventory at runtime; never copy a fixed skill or agent count into this contract.
SKILL_BLOCK_ORDER is the base tier for every skill.
ORCHESTRATOR_SKILL_BLOCK_ORDER extends that base only for skills in ORCHESTRATOR_SKILLS.
- Agent tiers remain independently governed by the injector's explicit agent sets.
This is a bulk-insert operation, not a content update. Verify the computed target set before writing so orchestration-only rules never leak into every skill.
When to use: A new protocol rule is added to .claude/skills/shared/sync-inline-versions.md and should appear in static carriers (CLAUDE.md, AGENTS.md, Codex, skills, and agents).
Step B1: Add block content to canonical source
Edit .claude/skills/shared/sync-inline-versions.md and add a new section:
## SYNC:{new-block-name}
> **[Rule content here]**
---
Step B2: Add block to sync-hooks-to-skills.py
Edit .claude/scripts/sync-hooks-to-skills.py:
- Add entry to
BLOCKS dict:
BLOCKS = {
# ... existing blocks ...
"new-block-name": """\
<!-- SYNC:new-block-name -->
> **[Full block content here — exactly as it should appear in files]**
<!-- /SYNC:new-block-name -->""",
}
- Add 1-line reminder to
REMINDERS dict:
REMINDERS = {
# ... existing reminders ...
"new-block-name": """\
> **[IMPORTANT]** Use task tracking to break ALL work into small tasks BEFORE starting.
<!-- SYNC:new-block-name:reminder -->
**MUST ATTENTION** [one-line summary of the rule].
<!-- /SYNC:new-block-name:reminder -->""",
}
- Add the block name to the relevant tier list(s) (controls which targets receive it + insertion order):
# Skills-3: the two universal blocks + the orchestration block. Do NOT add
# agent-only rules here. `parallel-subagent-dispatch` is deliberately SKILL-ONLY
# — not because an agent cannot spawn, but because an agent receives ONE brief an
# orchestrator has ALREADY partitioned, so re-running the partitioning protocol in
# the leaf re-decides an upstream decision. It is ALSO declared in
# agent_protocol_matrix.py EXCLUDED_ORCHESTRATION and in the TC-UAR-017
# AGENT_ADOPTION_EXEMPT set (see "Skill-only blocks" below).
SKILL_BLOCK_ORDER = ["critical-thinking-mindset", "ai-mistake-prevention",
"parallel-subagent-dispatch"]
# Core-6: every agent (skills/SKILL.md is unaffected).
CORE_BLOCK_ORDER = ["critical-thinking-mindset", "ai-mistake-prevention",
"sequential-thinking-protocol", "task-tracking-external-report",
"project-reference-docs-guide", "agent-bootstrap"]
# Code-10: Core-6 + code-investigation blocks, for agents that read/review AND fix code.
CODE_BLOCK_ORDER = CORE_BLOCK_ORDER + ["understand-code-first", "evidence-based-reasoning",
"cross-service-check", "fix-layer-accountability"]
# Readonly-Code-8: Core-6 + reading-discipline blocks only, for read-only/design
# agents that locate/read/design code but never fix a layer or cross a service
# boundary (excludes the two mutation-oriented blocks).
READONLY_CODE_BLOCK_ORDER = CORE_BLOCK_ORDER + ["understand-code-first", "evidence-based-reasoning"]
Agent tiering: agents no longer share one block list. find_target_files() classifies each .claude/agents/*.md by explicit membership in one of three sets:
CODE_AGENTS (17 code/review/fix agents → CODE_BLOCK_ORDER, Code-10).
READONLY_CODE_AGENTS (4 read-only/design agents — researcher, scout, scout-external, ui-ux-designer → READONLY_CODE_BLOCK_ORDER, Core-6 + understand-code-first + evidence-based-reasoning; the mutation-oriented cross-service-check + fix-layer-accountability are deliberately excluded to save tokens on agents that only locate/read/design code).
CORE_ONLY_AGENTS (8 non-code agents → CORE_BLOCK_ORDER, Core-6).
An agent in none of the three sets (or in more than one) raises SystemExit — no silent default; classify it before the script will run. Skills always use SKILL_BLOCK_ORDER. Pass --agents-only to scope a run to agents (skip skills).
Adding a new agent: add its basename to exactly one of CODE_AGENTS / READONLY_CODE_AGENTS / CORE_ONLY_AGENTS in sync-hooks-to-skills.py and in the regression suite .claude/hooks/tests/suites/agent-universal-rules.test.cjs (TC-UAR-005 fails until both agree). The two enforce one invariant.
Note — the inserter is insert-only. Moving an agent from CODE to READONLY_CODE (or otherwise dropping a block from its tier) does NOT remove the now-excess SYNC block from its .md on disk — process_file only inserts missing blocks. Strip the excess block(s) from the agent .md source by hand (or a scoped one-off) so the regression suite's tier assertions pass.
Skill-only blocks (orchestration). A block in SKILL_BLOCK_ORDER but in NO agent tier reaches every skill and zero agents. TC-UAR-017 treats that shape as drift by default — a protocol that reached ≥3 skills but no agent is usually an oversight — so declare a genuinely skill-only block in BOTH lists:
.claude/hooks/tests/suites/agent-universal-rules.test.cjs → AGENT_ADOPTION_EXEMPT — the ONLY list TC-UAR-017 reads. Omit the block here and the suite fails.
.claude/scripts/agent_protocol_matrix.py → EXCLUDED_ORCHESTRATION — read only by that file's own --validate check (b) (agent_protocol_matrix.py:481), which rejects a per-agent manifest that assigns an excluded block without an ORCHESTRATION_WHITELIST entry. Omit it here and no test fails; the manifest is simply free to assign the block to an agent.
No cross-check exists. The two lists are enforced by two SEPARATE mechanisms and nothing verifies they agree — TC-UAR-017 never reads EXCLUDED_ORCHESTRATION (it appears in that test file only in a comment and a failure-message string). Keeping them in step is a convention, not an enforced invariant: update both by hand in the same change.
The bar for that exemption is caller-side ownership: the block must drive orchestration the leaf either cannot perform (it has no access to the parent conversation, workflow state, or the user) or has no basis to perform (the decision was already made upstream before its brief was issued). Current members — nested-task-creation, subagent-return-contract, sub-agent-selection, parallel-phase-advancement, parallel-subagent-dispatch, goal-contract-satisfaction-loop — expand workflow steps, choose/brief sub-agents, partition a task list into parallel waves, or drive a user-facing convergence loop. parallel-subagent-dispatch is the second kind: an agent CAN spawn (agent files generally carry no tools: restriction), but it receives one already-partitioned brief, so re-running PAR/SEQ tagging inside it re-decides upstream's call. An agent that legitimately fans out carries that instruction in its own .claude/agents/*.md definition instead.
Step B3: Run the script (dry-run first)
python .claude/scripts/sync-hooks-to-skills.py --dry-run --verbose
# Verify: expected N updated, 0 errors
python .claude/scripts/sync-hooks-to-skills.py --verbose
# Verify: the computed on-disk tier inventory was processed; already-current targets skip
Step B4: Verify
# Confirm target files now contain the new block. Expected count is TIER-AWARE.
# The skill tier and the agent tiers are INDEPENDENT lists — a block reaches
# agents only if it is ALSO in an agent tier, so union the rows that apply:
# - block in SKILL_BLOCK_ORDER ONLY → every discovered skill, 0 agents
# (skill-only ⇒ must be declared in BOTH
# exemption lists — see "Skill-only blocks")
# - block in SKILL_BLOCK_ORDER + CORE → every discovered skill + every discovered agent
# - block in CORE_BLOCK_ORDER → every discovered agent (skills excluded)
# - block in READONLY_CODE_BLOCK_ORDER → 21 agents (17 code + 4 readonly-code)
# - block in CODE_BLOCK_ORDER → 17 code agents only
grep -rl "SYNC:new-block-name" .claude/skills/*/SKILL.md .claude/agents/*.md | wc -l
# Then run the agent-coverage regression suite — it asserts tier membership,
# disjointness, and SYNC tag balance across the discovered agent inventory.
node .claude/hooks/tests/run-all-tests.cjs --filter=agent-universal
Check a representative file of each affected tier manually to confirm placement and formatting.
Usage Examples
$sync-skills-shared-protocols understand-code-first # Sync one tag (Operation A)
$sync-skills-shared-protocols all # Sync all tags (Operation A)
$sync-skills-shared-protocols # Interactive — asks which tags
# Adding new block: use Operation B workflow above (script-driven)
Rules
- ALWAYS edit
sync-inline-versions.md FIRST, then run this skill
- NEVER modify content outside
<!-- SYNC:tag --> boundaries
- NEVER touch
:reminder blocks unless explicitly asked
- If close tag is missing in a target file, SKIP that file and report it as an error
- Use the
Grep tool (not shell grep) per project conventions
- Verify tag balance after every sync run
- For bulk-insert (Operation B): use
sync-hooks-to-skills.py — NEVER do it manually across 288 files
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.
Shared Protocol Duplication Policy — Inline protocol content in skills (wrapped in <!-- SYNC:tag -->) is INTENTIONAL duplication. Do NOT extract, deduplicate, or replace with file references. AI compliance drops significantly when protocols are behind file-read indirection. To update: edit .claude/skills/shared/sync-inline-versions.md first, then grep SYNC:protocol-name and update all occurrences.
AI Mistake Prevention — Failure modes to avoid on every task:
Re-read files after context changes. Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
Verify generated content against source evidence. AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
Check downstream references before deleting or renaming. Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
Trace the full impact chain after edits. Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
Verify ALL affected outputs, not just the first. One green check is not all green checks; validate every output surface the change can affect.
Assume existing values are intentional — ask WHY before changing OR flagging one as a defect. Before changing or reporting a constant, limit, flag, cutoff, wording, or pattern, read nearby context and history, the CALLER's ordering, and 2+ sibling call sites of the same convention. A doc stating WHAT without WHY is missing rationale, not proof of a missing guard.
Surface ambiguity before acting — don't pick silently. Multiple valid interpretations require an explicit question or stated assumption with risk.
Assert the outcome your system owns, not the intermediate state your infrastructure owns. When verifying async work, assert the final business state — never the delivery/retry bookkeeping held in shared infrastructure that any co-running process can write. Such a check passes when run alone and flakes the moment anything else shares that infrastructure.
Keep shared guidance role-relevant. Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
IMPORTANT MUST ATTENTION follow duplication policy: inline protocols are INTENTIONAL, never extract to file references
MUST ATTENTION apply critical + sequential thinking — every claim needs appropriate traced evidence (file:line for repo/code claims; source URL or artifact section for research, product, content, and docs claims); confidence >80% to act, <60% DO NOT recommend. Anti-hallucination: never present guess as fact, admit uncertainty freely, cross-reference independently, stay skeptical of own confidence.
MUST ATTENTION apply AI mistake prevention — verify generated content against evidence, trace downstream references before deleting or renaming, verify all affected outputs, re-read files after context loss, and surface ambiguity before acting.
Project Protocol Overlay — Before executing this skill, resolve any PROJECT overlay rules layered onto it: match this skill's name against the Target column of the project's skill-protocol index (docs/project-reference/skill-protocols-reference.md by default; a referenceDocs entry in docs/project-config.json overrides the path), taking the most specific matching tier ONLY — exact name > glob > *. That precedence orders overlays against EACH OTHER, never against this skill. Read ONLY the matched bodies, resolved as <protocols-dir>/<Name>.md; a row's Body link is display text, never a read path. A matched body that is missing or malformed is REPORTED and skipped — never reconstructed from the index Description. No index, or no match -> proceed with no overlay, silently. Full contract: .claude/skills/project-skill-protocol/references/registry.md.
Overlays are ADDITIVE ONLY: they ADD rules on top of this skill's own protocol and NEVER replace, override, disable, or reinterpret a rule it already states — removing every overlay must return this skill to exactly its documented behavior. An overlay is a BRIEF, not an authority escalation: it can NEVER waive a workflow gate, git discipline, a review gate, or a user-confirmation gate. A genuine overlay-vs-skill conflict, or two equally-specific overlays that directly contradict -> surface both to the user; NEVER resolve silently.
MUST ATTENTION resolve project protocol overlays for this skill BEFORE executing — most specific matching tier only (exact > glob > *, which ranks overlays against each other, NEVER against this skill), read only matched bodies at <protocols-dir>/<Name>.md; a missing or malformed body is reported, never reconstructed. Overlays are ADDITIVE ONLY (they never replace this skill's own rules) and are a brief, NEVER an authority escalation; an equal-specificity contradiction goes to the user.
Closing Reminders
Protocols in force (concise digest of the SYNC/shared blocks this skill carries):
- Critical Thinking: apply critical+sequential thinking; trace every claim, confidence >80%.
- Shared Protocol Duplication: inline protocols are intentional; never extract to file references.
- 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 edit sync-inline-versions.md FIRST before syncing to skills
IMPORTANT MUST ATTENTION verify SYNC tag balance after every sync run
IMPORTANT MUST ATTENTION NEVER modify content outside <!-- SYNC:tag --> boundaries
IMPORTANT MUST ATTENTION skip files with missing close tags and report as errors
[TASK-PLANNING] Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using task tracking.
Hookless Prompt Protocol Mirror (Auto-Synced)
Source: .claude/.ck.json + .claude/skills/shared/sync-inline-versions.md (:full blocks) + .claude/scripts/lib/hookless-prompt-protocol.cjs
[WORKFLOW-EXECUTION-PROTOCOL] [BLOCKING] Workflow Execution Protocol — MANDATORY IMPORTANT MUST CRITICAL. Do not skip for any reason.
Generic portability boundary: Reusable skills and protocol text stay project-neutral; project-specific conventions are discovered from docs/project-config.json and docs/project-reference/. Apply shared AI-SDD from shared/sdd-artifact-contract.md. Read docs/project-config.json and docs/project-reference/docs-index-reference.md, then open the project reference docs named there. For spec, test-case, behavior-change, public-contract, or docs/specs/ work, route through the local spec docs named by the docs index: feature-spec-reference.md, spec-system-reference.md, spec-principles.md, and workflow-spec-test-code-cycle-reference.md when specs/tests/code must stay synchronized. If either file or a required reference doc is missing or stale, auto-run $project-init (or the narrow lower-level route such as $project-config, $docs-init, $scan-all, or $scan --target=<key>) before ordinary project-specific work. Any supported AI tool may execute when this shared context and local docs are available.
- DETECT: If the prompt starts with an explicit slash skill/workflow command, execute it directly. Otherwise match the prompt against the workflow catalog and skill list.
- ANALYZE: Choose the best option: execute directly, invoke a skill, activate a standard workflow, or compose a custom step combination.
- AUTO-SELECT: Pick the best option yourself. Do not ask the user to choose between direct execution, skill, standard workflow, or custom workflow.
- ACTIVATE: For a selected workflow, call
$start-workflow <workflowId>; for a selected skill, invoke that skill; for a custom workflow, sequence custom steps directly; for direct execution, proceed with the task.
- CREATE TASKS: task tracking for ALL workflow/skill/custom steps before execution when the selected path has multiple steps.
- PARALLELIZE: Before executing the task list, tag each task
PAR (independent inputs + write set disjoint from every other PAR task) or SEQ (name the blocking dependency), group PAR tasks into waves, declare the wave plan, and spawn each wave's sub-agents in ONE message — all-return barrier per wave, fan-out one level deep unless a sub-agent's own definition authorizes further fan-out. Sequential-by-default is a defect when tasks are independent; do not parallelize shared write targets, output-consuming tasks, trivial single-file work, ordering a skill or workflow explicitly fixes, or user-approval gates.
- EXECUTE: Advance per the Workflow Step Advancement & Parallel Phases rule in your context instructions — model-driven; a sub-agent completion advances a step identically to an inline call; a parallel-phase group is an all-return barrier (advance only after ALL members return, never serialize it)
Shared AI-SDD Protocol Markers
Source: .claude/skills/shared/sync-inline-versions.md
SYNC:ai-sdd-artifact-contract
AI-SDD Artifact Contract — Shared spec-driven development rules stay portable and source-owned.
- Keep reusable AI-SDD principles in
.claude; put repository-specific paths, commands, owners, products, and formats in project config/reference docs.
- Preserve cycle:
spec -> plan -> tasks -> implement -> verify -> update spec/docs.
- Trace every requirement or invariant through decision, task, TC/test, source evidence, and docs/spec update.
- Treat code-to-spec extraction as reference-only until accepted by the canonical spec owner.
- Any supported AI tool may plan, implement, review, or verify with synced context; using multiple tools is optional.
- Update
.claude source first, then sync generated mirrors; do not manually edit .agents, .codex, or AGENTS.md. — why: mirrors are generated artifacts; hand-edits are overwritten on the next sync
- If
docs/project-config.json, root instruction files, or a required project-reference doc is missing or stale, auto-run $project-init or the narrow lower-level route before ordinary project-specific work.
Active reference: shared/sdd-artifact-contract.md in the active skills root.
SYNC:ai-sdd-artifact-contract:reminder
- MANDATORY Apply
shared/sdd-artifact-contract.md; keep reusable AI-SDD in .claude and local rules in project docs.
- MANDATORY Code-to-spec extraction is reference-only until canonical acceptance; any supported AI tool may execute with synced context.
- MANDATORY Update
.claude source before syncing generated mirrors; do not manually edit .agents, .codex, or AGENTS.md.
- MANDATORY Missing or stale project config, root instruction files, or required reference docs route project-specific work through
$project-init or the narrow setup route automatically.
[TASK-PLANNING] [MANDATORY] BEFORE executing any workflow or skill step, create/update task tracking for all planned steps, then keep it synchronized as each step starts/completes.
[LESSON-LEARNED-REMINDER] [BLOCKING] Task Planning & Continuous Improvement — MANDATORY. Do not skip.
Break work into small tasks (task tracking) before starting. Add final task: "Analyze AI mistakes & lessons learned".
Extract lessons — ROOT CAUSE ONLY, not symptom fixes:
- Name the FAILURE MODE (reasoning/assumption failure), not symptom — "assumed API existed without reading source" not "used wrong enum value".
- Generality test: does this failure mode apply to ≥3 contexts/codebases? If not, abstract one level up.
- Write as a universal rule — strip project-specific names/paths/classes. Useful on any codebase.
- Consolidate: multiple mistakes sharing one failure mode → ONE lesson.
- Recurrence gate: "Would this recur in future session WITHOUT this reminder?" — No → skip
$learn.
- Auto-fix gate: "Could
$code-review/$code-simplifier/$security-review/$lint catch this?" — Yes → improve review skill instead.
- BOTH gates pass → ask user to run
$learn.
[CRITICAL-THINKING-MINDSET] Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
Anti-hallucination principle: Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination.
AI Attention principle (Primacy-Recency): Put the 3 most critical rules at both top and bottom of long prompts/protocols so instruction adherence survives long context windows.
Goal-driven execution: Define success criteria first, loop until verified, and stop only when observable checks pass.
Tests verify intent: Tests must protect business rules/invariants and fail when the protected intent breaks, not only mirror current behavior.
Common AI Mistake Prevention (System Lessons)
- Re-read files after context compaction. Edit requires prior Read in same context; compaction wipes read state. Re-read before editing.
- Grep for old terms after bulk replacements. AI over-trusts find/replace completeness. Grep full repo after bulk edits for missed refs in docs/configs/catalogs.
- Check downstream references before deleting. Deletions cascade doc/code staleness. Map referencing files before removal.
- After memory loss, check existing state before creating new. Compaction wipes prior-work memory. Query current state to resume — never blindly duplicate.
- Verify AI-generated content against actual code. AI hallucinates APIs, class names, method signatures. Grep to confirm existence before documenting/referencing.
- Trace full dependency chain after edits. Changing a definition misses downstream consumers. Trace the full chain.
- When renaming, grep ALL consumer file types. Some file types silently ignore missing refs (no compile error). Search code, templates, configs, generated files.
- Trace ALL code paths when verifying correctness. Code existing ≠ code executing. Trace early exits, error branches, conditional skips — not just happy path.
- Update docs that embed canonical data when source changes. Docs inlining derived data (workflows, schemas, configs) go stale silently. Update all embedding docs alongside source.
- Verify sub-agent results after context recovery. Background agents may finish while parent compacted — grep-verify output, don't trust assumed completion.
- Cross-check full target list against sub-agent assignments. Parallel sub-agents by category miss boundary items. Reconcile union of assignments against target list before proceeding.
- Sub-agents inherit knowledge only from their agent .md definition — use custom agent types, not built-in Explore. Tool adoption = permission + knowledge + enforcement (numbered workflow step).
- Persist sub-agent findings incrementally, not as a final batch. Long sub-agents hit cutoffs before final write — findings lost. Instruct append-per-section to report file.
- When debugging, ask "whose responsibility?" before fixing. Trace caller (wrong data) vs callee (wrong handling). Fix at responsible layer — never patch symptom site.
- Test failure → record a provisional verdict before trace/edit, then investigate. Use the full five-way taxonomy: SOURCE-WRONG (production violates intent), TEST-WRONG (assertion/setup is stale), TEST-NOT-OPTIMAL (valid but fragile or low-signal test), ENVIRONMENT-BLOCKED (external state prevents a verdict), or AMBIGUOUS (intent/evidence cannot choose safely). Then trace root cause and triangulate against the governing spec (
docs/specs/** if one exists) AND source. NEVER weaken an assertion, add a skip, relax a timeout, or change source merely to force green.
- Grep ALL removed names after extraction/refactoring. Primary file "done" ≠ secondary files clean. Grep entire scope for every removed symbol before declaring complete.
- Assume existing values are intentional — ask WHY before changing OR flagging one as a defect. Pattern-matching as "wrong" skips context. Before changing or reporting any constant/limit/flag/cutoff: read comments, git blame, the CALLER's ordering (the guarantee that makes the value correct usually lives in code running immediately BEFORE the cited line), and 2+ sibling call sites of the same convention. A doc stating WHAT without WHY is missing rationale, not proof of a missing guard — and in a validation pass, an accurate
file:line citation proves the transcription, never the defect.
- Verify ALL affected outputs, not just the first. One build green ≠ all green. Multi-stack changes (backend/frontend/tests/docs) require verifying EVERY output.
- Evaluate fit before copying a nearby pattern. Closest example ≠ matching preconditions — verify the new context shares the same constraints, base classes, scope, lifetime.
- Holistic-first debugging — resist nearest-attention trap. Don't dive into first plausible cause. List EVERY precondition (config, env vars, paths, DB, endpoints, creds, versions, DI, data). Verify each against evidence (grep/query — not reasoning). Ask "what would falsify this?" — if nothing, it's not a hypothesis. Most expensive failure: going deeper in "obvious" layer while bug sits in layer never questioned.
- Surgical changes — apply the diff test (context-aware). Two modes: (1) Bug fix → every line traces to the bug; no restyling; orphan cleanup only for imports YOUR changes made unused. (2) Review/enhancement → implement improvements AND announce as "Enhancement beyond main request: [what]". Never silently scope-creep. Diff test: "Would this line exist if I wasn't asked to do X?" — if no, delete or announce.
- Surface ambiguity before coding — don't pick silently. Multiple valid interpretations → present each with effort: "[Request] could mean (1) [N h], (2) [N h]. Which matters?" List scope/format/volume/constraints assumptions first. If simpler path exists, say so. Never silently pick.
- [MANDATORY FIRST ACTION] ALWAYS activate a suitable skill or workflow BEFORE responding. Match task against workflow catalog + skill list; invoke via skill invocation or
$start-workflow <workflowId>. NEVER answer or write code before checking. Skip = protocol violation.
- Why-Review adversarial mindset — apply when reviewing any plan, decision, or design. Default SKEPTIC not VALIDATOR: steel-man a rejected alternative, invert each stated reason ("what does it sacrifice?"), stress-test top 2-3 assumptions, run pre-mortem ("ships, fails in 3 months — what breaks?"), surface 1-2 alternatives author missed. Section presence ≠ quality; quality = causal reasoning + concrete mitigations + evidence, not "it's better" or "monitor closely".
- Front-load report-write in sub-agent prompts for large reviews. Many-file sub-agents hit budget before final write — findings lost. Design prompts so: (1) report-write is first explicit deliverable, (2) append per-file/section (not batched), (3) scope bounded so reads don't exhaust budget. Truncated mid-sentence with no report file → spawn narrower scope, don't retry same prompt.
- After context compaction, re-verify all prior phase outcomes before continuing. Summaries describe intent, not environment state (git index, filesystem, processes). On resume, FIRST audit: git status, re-read modified files, verify filesystem. Every "completed" claim is an untested hypothesis until evidence confirms.
- OOM/memory: check row count before row size. Triage: (1) Unbounded query — no DB filter for trigger? Push filter to DB; eliminates OOM. (2) Large rows? Projection reduces proportionally. Row reduction > projection in ROI.
- Assert the outcome your system OWNS, never the intermediate state your INFRASTRUCTURE owns. When testing anything asynchronous (queue/broker delivery, retries, background jobs, caches, replication), assert the final business/entity state. NEVER assert the delivery bookkeeping — consume/send status, attempt counts, last-error, row existence or counts in a broker, scheduler, or outbox/inbox table. That bookkeeping lives in shared infrastructure that ANY co-running process (a peer worker, a second replica, a leftover local container) can write, usually under a deterministic shared key, so the assertion silently tests the developer's environment instead of the system: green when run alone, flaky the instant anything else shares that broker + database. Gate question for every assertion: "would this hold no matter WHICH process did the work?" — if no, assert the converged data state instead. Corollary: process-local fault injection and in-process telemetry cannot gate work any process may perform — use them as stress amplifiers (arm → bounded window → disarm → assert convergence), never as preconditions.
- Keep domain concepts out of generic/shared/infrastructure layers. Reusable layer (shared library, framework, infra module) must reference NO consumer-specific domain concept — tenant/customer/product IDs, business entities, feature rules. Leak compiles + runs → passes review silently while coupling the "reusable" layer to one consumer. Keep shared type domain-free; push domain fields/logic down into the consumer via subclass/composition. — why: a layer coupled to one consumer's domain is no longer reusable.
1---2name: sync-skills-shared-protocols3description: [Skill Management] Use when shared protocol checklists change and need propagation across skills.4---5
6> Codex compatibility note:
7>
8> - Invoke repository skills with `$skill-name` in Codex; this mirrored copy rewrites legacy Claude `/skill-name` references.
9> - Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.
10> - User-question prompts mean to ask the user directly in Codex.
11> - Ignore Claude-specific mode-switch instructions when they appear.
12> - Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.
13> - Subagent authorization: when a skill is user-invoked or AI-detected and its protocol requires subagents, that skill activation authorizes use of the required `spawn_agent` subagent(s) for that task.
14> - Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.
15> - For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.
16> - If a required step/tool cannot run in this environment, stop and ask the user before adapting.
17
18<!-- CODEX:PROJECT-REFERENCE-LOADING:START -->
19
20## Codex Project-Reference Loading (No Hooks)
21
22Codex uses static project-reference loading instead of runtime-injected project docs.
23When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.
24
25**Always read:**
26
27- `docs/project-config.json` (project-specific paths, commands, modules, and workflow/test settings)
28- `docs/project-reference/docs-index-reference.md` (routes to the full `docs/project-reference/*` catalog)
29- `docs/project-reference/lessons.md` (always-on guardrails and anti-patterns)
30
31**Missing/stale context route:** If `docs/project-config.json`, the docs index, `lessons.md`, `CLAUDE.md`, `AGENTS.md`, or any task-required reference doc is missing or stale, auto-run `$project-init` or the narrow setup route (`$project-config`, `$docs-init`, `$scan-all`, `$scan --target=<key>`, `$claude-md-init`) before ordinary project-specific work. If Codex mirrors or `AGENTS.md` are missing/stale, ask the user to run `$sync-codex`; do not auto-run it.
32
33**Situation-based docs:**
34
35- Project structure/architecture/tech-stack/deployment/setup (any layer — backend, frontend, or infra): `project-structure-reference.md`
36- Backend/CQRS/API/domain/entity changes: `backend-patterns-reference.md`, `domain-entities-reference.md`
37- Frontend/UI/styling/design-system: `frontend-patterns-reference.md`, `scss-styling-guide.md`, `design-system/README.md`
38- Spec authoring, `docs/specs/` pathing, or TC format: `feature-spec-reference.md`, `spec-system-reference.md`, `spec-principles.md`
39- Behavior/public-contract changes or spec-test-code sync: `workflow-spec-test-code-cycle-reference.md` plus the spec docs above
40- Derived spec indexes/ERDs/reimplementation guides: `spec-system-reference.md` and source Feature Specs under `docs/specs/`
41- Integration test implementation/review: `integration-test-reference.md`
42- E2E test implementation/review: `e2e-test-reference.md`
43- Code review/audit work: `code-review-rules.md` plus domain docs above based on changed files
44
45Do not read all docs blindly. Start from `docs-index-reference.md`, then open only relevant files for the task.
46
47<!-- CODEX:PROJECT-REFERENCE-LOADING:END -->
48
49## Quick Summary
50
51**Goal:** Two operations — (A) propagate updated content for existing SYNC: blocks across all skills, or (B) add a new SYNC: block to all skill/agent files that don't have it yet.
52
53> **Renamed:** formerly `/sync-protocols` — that name no longer resolves as a slash command; use `$sync-skills-shared-protocols`.
54
55**Canonical source:** `.claude/skills/shared/sync-inline-versions.md`
56
57## Workflow
58
59### Operation A: Update Existing Block Content
60
61Use when a SYNC: block already exists in files and push updated content to all of them.
62
63### Step 1: Identify What Changed
64
65If user specifies a tag name (e.g., `sync-skills-shared-protocols understand-code-first`):
66
67- Sync only that tag
68
69If no tag specified:
70
71- Read `sync-inline-versions.md`
72- Ask user which tag(s) to sync, or "all"
73
74### Step 2: Read Canonical Content
75
76For each tag to sync:
77
781. Read `.claude/skills/shared/sync-inline-versions.md`
792. Extract content under `## SYNC:{tag-name}` heading (everything between that heading and the next `---` or `## SYNC:`)
80
81### Step 3: Find All Skills with Tag
82
83```bash
84grep -rl "SYNC:{tag-name}" .claude/skills/*/SKILL.md
85```
86
87### Step 4: Replace Content in Each Skill
88
89For each file found:
90
911. Find `<!-- SYNC:{tag-name} -->` open tag
922. Find `<!-- /SYNC:{tag-name} -->` close tag
933. Replace everything between them with the canonical content
944. Do NOT touch `:reminder` blocks — those are separate, shorter versions
95
96### Step 5: Verify
97
98Run these checks after all replacements:
99
100```python
101# 1. SYNC tag balance (all opens have matching closes)
102# 2. Content matches canonical source
103# 3. No content outside SYNC blocks was modified
104```
105
106Report:
107
108- Tags synced
109- Files updated (count)
110- Any balance issues
111
112### Step 6: Reminder Blocks
113
114`:reminder` blocks (`<!-- SYNC:{tag}:reminder -->`) are 1-line summaries at the bottom of skills for AI recency attention. These are NOT auto-synced — they are hand-written. Skip them unless user explicitly asks to update reminders too.
115
116---
117
118### Operation B: Add a New Tiered Block
119
120Use when a NEW SYNC: block needs tiered propagation. Derive the on-disk target inventory at runtime; never copy a fixed skill or agent count into this contract.
121
122- `SKILL_BLOCK_ORDER` is the base tier for every skill.
123- `ORCHESTRATOR_SKILL_BLOCK_ORDER` extends that base only for skills in `ORCHESTRATOR_SKILLS`.
124- Agent tiers remain independently governed by the injector's explicit agent sets.
125
126This is a bulk-insert operation, not a content update. Verify the computed target set before writing so orchestration-only rules never leak into every skill.
127
128**When to use:** A new protocol rule is added to `.claude/skills/shared/sync-inline-versions.md` and should appear in static carriers (`CLAUDE.md`, `AGENTS.md`, Codex, skills, and agents).
129
130#### Step B1: Add block content to canonical source
131
132Edit `.claude/skills/shared/sync-inline-versions.md` and add a new section:
133
134```markdown
135## SYNC:{new-block-name}
136
137> **[Rule content here]**
138
139---
140```
141
142#### Step B2: Add block to `sync-hooks-to-skills.py`
143
144Edit `.claude/scripts/sync-hooks-to-skills.py`:
145
1461. Add entry to `BLOCKS` dict:
147
148```python
149BLOCKS = {
150 # ... existing blocks ...
151 "new-block-name": """\
152<!-- SYNC:new-block-name -->
153
154> **[Full block content here — exactly as it should appear in files]**
155
156<!-- /SYNC:new-block-name -->""",
157}
158```
159
1602. Add 1-line reminder to `REMINDERS` dict:
161
162```python
163REMINDERS = {
164# ... existing reminders ...
165"new-block-name": """\
166
167> **[IMPORTANT]** Use task tracking to break ALL work into small tasks BEFORE starting.
168
169<!-- SYNC:new-block-name:reminder -->
170**MUST ATTENTION** [one-line summary of the rule].
171<!-- /SYNC:new-block-name:reminder -->""",
172}
173```
174
1753. Add the block name to the relevant tier list(s) (controls which targets receive it + insertion order):
176
177```python
178# Skills-3: the two universal blocks + the orchestration block. Do NOT add
179# agent-only rules here. `parallel-subagent-dispatch` is deliberately SKILL-ONLY
180# — not because an agent cannot spawn, but because an agent receives ONE brief an
181# orchestrator has ALREADY partitioned, so re-running the partitioning protocol in
182# the leaf re-decides an upstream decision. It is ALSO declared in
183# agent_protocol_matrix.py EXCLUDED_ORCHESTRATION and in the TC-UAR-017
184# AGENT_ADOPTION_EXEMPT set (see "Skill-only blocks" below).
185SKILL_BLOCK_ORDER = ["critical-thinking-mindset", "ai-mistake-prevention",
186 "parallel-subagent-dispatch"]
187
188# Core-6: every agent (skills/SKILL.md is unaffected).
189CORE_BLOCK_ORDER = ["critical-thinking-mindset", "ai-mistake-prevention",
190 "sequential-thinking-protocol", "task-tracking-external-report",
191 "project-reference-docs-guide", "agent-bootstrap"]
192
193# Code-10: Core-6 + code-investigation blocks, for agents that read/review AND fix code.
194CODE_BLOCK_ORDER = CORE_BLOCK_ORDER + ["understand-code-first", "evidence-based-reasoning",
195 "cross-service-check", "fix-layer-accountability"]
196
197# Readonly-Code-8: Core-6 + reading-discipline blocks only, for read-only/design
198# agents that locate/read/design code but never fix a layer or cross a service
199# boundary (excludes the two mutation-oriented blocks).
200READONLY_CODE_BLOCK_ORDER = CORE_BLOCK_ORDER + ["understand-code-first", "evidence-based-reasoning"]
201```
202
203**Agent tiering:** agents no longer share one block list. `find_target_files()` classifies each `.claude/agents/*.md` by explicit membership in one of three sets:
204
205- `CODE_AGENTS` (17 code/review/fix agents → `CODE_BLOCK_ORDER`, Code-10).
206- `READONLY_CODE_AGENTS` (4 read-only/design agents — `researcher`, `scout`, `scout-external`, `ui-ux-designer` → `READONLY_CODE_BLOCK_ORDER`, Core-6 + understand-code-first + evidence-based-reasoning; the mutation-oriented `cross-service-check` + `fix-layer-accountability` are deliberately excluded to save tokens on agents that only locate/read/design code).
207- `CORE_ONLY_AGENTS` (8 non-code agents → `CORE_BLOCK_ORDER`, Core-6).
208
209An agent in **none of the three sets (or in more than one)** raises `SystemExit` — no silent default; classify it before the script will run. Skills always use `SKILL_BLOCK_ORDER`. Pass `--agents-only` to scope a run to agents (skip skills).
210
211> **Adding a new agent:** add its basename to exactly one of `CODE_AGENTS` / `READONLY_CODE_AGENTS` / `CORE_ONLY_AGENTS` in `sync-hooks-to-skills.py` **and** in the regression suite `.claude/hooks/tests/suites/agent-universal-rules.test.cjs` (TC-UAR-005 fails until both agree). The two enforce one invariant.
212>
213> **Note — the inserter is insert-only.** Moving an agent from CODE to READONLY_CODE (or otherwise dropping a block from its tier) does NOT remove the now-excess SYNC block from its `.md` on disk — `process_file` only inserts missing blocks. Strip the excess block(s) from the agent `.md` source by hand (or a scoped one-off) so the regression suite's tier assertions pass.
214
215**Skill-only blocks (orchestration).** A block in `SKILL_BLOCK_ORDER` but in NO agent tier reaches every skill and zero agents. TC-UAR-017 treats that shape as drift by default — a protocol that reached ≥3 skills but no agent is usually an oversight — so declare a genuinely skill-only block in BOTH lists:
216
217- `.claude/hooks/tests/suites/agent-universal-rules.test.cjs` → `AGENT_ADOPTION_EXEMPT` — the ONLY list TC-UAR-017 reads. Omit the block here and the suite fails.
218- `.claude/scripts/agent_protocol_matrix.py` → `EXCLUDED_ORCHESTRATION` — read only by that file's own `--validate` check (b) (`agent_protocol_matrix.py:481`), which rejects a per-agent manifest that assigns an excluded block without an `ORCHESTRATION_WHITELIST` entry. Omit it here and no test fails; the manifest is simply free to assign the block to an agent.
219
220> **No cross-check exists.** The two lists are enforced by two SEPARATE mechanisms and nothing verifies they agree — TC-UAR-017 never reads `EXCLUDED_ORCHESTRATION` (it appears in that test file only in a comment and a failure-message string). Keeping them in step is a **convention**, not an enforced invariant: update both by hand in the same change.
221
222The bar for that exemption is caller-side ownership: the block must drive orchestration the leaf either **cannot perform** (it has no access to the parent conversation, workflow state, or the user) or **has no basis to perform** (the decision was already made upstream before its brief was issued). Current members — `nested-task-creation`, `subagent-return-contract`, `sub-agent-selection`, `parallel-phase-advancement`, `parallel-subagent-dispatch`, `goal-contract-satisfaction-loop` — expand workflow steps, choose/brief sub-agents, partition a task list into parallel waves, or drive a user-facing convergence loop. `parallel-subagent-dispatch` is the second kind: an agent CAN spawn (agent files generally carry no `tools:` restriction), but it receives one already-partitioned brief, so re-running PAR/SEQ tagging inside it re-decides upstream's call. An agent that legitimately fans out carries that instruction in its own `.claude/agents/*.md` definition instead.
223
224#### Step B3: Run the script (dry-run first)
225
226```bash
227python .claude/scripts/sync-hooks-to-skills.py --dry-run --verbose
228# Verify: expected N updated, 0 errors
229
230python .claude/scripts/sync-hooks-to-skills.py --verbose
231# Verify: the computed on-disk tier inventory was processed; already-current targets skip
232```
233
234#### Step B4: Verify
235
236```bash
237# Confirm target files now contain the new block. Expected count is TIER-AWARE.
238# The skill tier and the agent tiers are INDEPENDENT lists — a block reaches
239# agents only if it is ALSO in an agent tier, so union the rows that apply:
240# - block in SKILL_BLOCK_ORDER ONLY → every discovered skill, 0 agents
241# (skill-only ⇒ must be declared in BOTH
242# exemption lists — see "Skill-only blocks")
243# - block in SKILL_BLOCK_ORDER + CORE → every discovered skill + every discovered agent
244# - block in CORE_BLOCK_ORDER → every discovered agent (skills excluded)
245# - block in READONLY_CODE_BLOCK_ORDER → 21 agents (17 code + 4 readonly-code)
246# - block in CODE_BLOCK_ORDER → 17 code agents only
247grep -rl "SYNC:new-block-name" .claude/skills/*/SKILL.md .claude/agents/*.md | wc -l
248
249# Then run the agent-coverage regression suite — it asserts tier membership,
250# disjointness, and SYNC tag balance across the discovered agent inventory.
251node .claude/hooks/tests/run-all-tests.cjs --filter=agent-universal
252```
253
254Check a representative file of each affected tier manually to confirm placement and formatting.
255
256---
257
258## Usage Examples
259
260```
261$sync-skills-shared-protocols understand-code-first # Sync one tag (Operation A)
262$sync-skills-shared-protocols all # Sync all tags (Operation A)
263$sync-skills-shared-protocols # Interactive — asks which tags
264# Adding new block: use Operation B workflow above (script-driven)
265```
266
267## Rules
268
269- ALWAYS edit `sync-inline-versions.md` FIRST, then run this skill
270- NEVER modify content outside `<!-- SYNC:tag -->` boundaries
271- NEVER touch `:reminder` blocks unless explicitly asked
272- If close tag is missing in a target file, SKIP that file and report it as an error
273- Use the `Grep` tool (not shell grep) per project conventions
274- Verify tag balance after every sync run
275- For bulk-insert (Operation B): use `sync-hooks-to-skills.py` — NEVER do it manually across 288 files
276
277---
278
279<!-- SYNC:critical-thinking-mindset -->
280
281> **Critical Thinking Mindset** — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
282> **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.
283
284<!-- /SYNC:critical-thinking-mindset -->
285
286<!-- SYNC:shared-protocol-duplication-policy -->
287
288> **Shared Protocol Duplication Policy** — Inline protocol content in skills (wrapped in `<!-- SYNC:tag -->`) is INTENTIONAL duplication. Do NOT extract, deduplicate, or replace with file references. AI compliance drops significantly when protocols are behind file-read indirection. To update: edit `.claude/skills/shared/sync-inline-versions.md` first, then grep `SYNC:protocol-name` and update all occurrences.
289
290<!-- /SYNC:shared-protocol-duplication-policy -->
291
292<!-- SYNC:ai-mistake-prevention -->
293
294> **AI Mistake Prevention** — Failure modes to avoid on every task:
295>
296> **Re-read files after context changes.** Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
297> **Verify generated content against source evidence.** AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
298> **Check downstream references before deleting or renaming.** Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
299> **Trace the full impact chain after edits.** Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
300> **Verify ALL affected outputs, not just the first.** One green check is not all green checks; validate every output surface the change can affect.
301> **Assume existing values are intentional — ask WHY before changing OR flagging one as a defect.** Before changing or reporting a constant, limit, flag, cutoff, wording, or pattern, read nearby context and history, the CALLER's ordering, and 2+ sibling call sites of the same convention. A doc stating WHAT without WHY is missing rationale, not proof of a missing guard.
302> **Surface ambiguity before acting — don't pick silently.** Multiple valid interpretations require an explicit question or stated assumption with risk.
303> **Assert the outcome your system owns, not the intermediate state your infrastructure owns.** When verifying async work, assert the final business state — never the delivery/retry bookkeeping held in shared infrastructure that any co-running process can write. Such a check passes when run alone and flakes the moment anything else shares that infrastructure.
304> **Keep shared guidance role-relevant.** Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
305
306<!-- /SYNC:ai-mistake-prevention -->
307
308<!-- SYNC:shared-protocol-duplication-policy:reminder -->
309
310**IMPORTANT MUST ATTENTION** follow duplication policy: inline protocols are INTENTIONAL, never extract to file references
311
312<!-- /SYNC:shared-protocol-duplication-policy:reminder -->
313
314<!-- SYNC:critical-thinking-mindset:reminder -->
315
316**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.
317
318<!-- /SYNC:critical-thinking-mindset:reminder -->
319
320<!-- SYNC:ai-mistake-prevention:reminder -->
321
322**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.
323
324<!-- /SYNC:ai-mistake-prevention:reminder -->
325
326<!-- SYNC:project-protocol-overlay -->
327
328> **Project Protocol Overlay** — Before executing this skill, resolve any PROJECT overlay rules layered onto it: match this skill's name against the `Target` column of the project's skill-protocol index (`docs/project-reference/skill-protocols-reference.md` by default; a `referenceDocs` entry in `docs/project-config.json` overrides the path), taking the most specific matching tier ONLY — exact name > glob > `*`. **That precedence orders overlays against EACH OTHER, never against this skill.** Read ONLY the matched bodies, resolved as `<protocols-dir>/<Name>.md`; a row's Body link is display text, never a read path. A matched body that is missing or malformed is REPORTED and skipped — never reconstructed from the index Description. No index, or no match -> proceed with no overlay, silently. Full contract: `.claude/skills/project-skill-protocol/references/registry.md`.
329>
330> Overlays are **ADDITIVE ONLY**: they ADD rules on top of this skill's own protocol and NEVER replace, override, disable, or reinterpret a rule it already states — removing every overlay must return this skill to exactly its documented behavior. An overlay is a BRIEF, not an authority escalation: it can NEVER waive a workflow gate, git discipline, a review gate, or a user-confirmation gate. A genuine overlay-vs-skill conflict, or two equally-specific overlays that directly contradict -> surface both to the user; NEVER resolve silently.
331
332<!-- /SYNC:project-protocol-overlay -->
333
334<!-- SYNC:project-protocol-overlay:reminder -->
335
336**MUST ATTENTION** resolve project protocol overlays for this skill BEFORE executing — most specific matching tier only (exact > glob > `*`, which ranks overlays against each other, NEVER against this skill), read only matched bodies at `<protocols-dir>/<Name>.md`; a missing or malformed body is reported, never reconstructed. Overlays are ADDITIVE ONLY (they never replace this skill's own rules) and are a brief, NEVER an authority escalation; an equal-specificity contradiction goes to the user.
337
338<!-- /SYNC:project-protocol-overlay:reminder -->
339
340## Closing Reminders
341
342**Protocols in force (concise digest of the SYNC/shared blocks this skill carries):**
343
344- **Critical Thinking:** apply critical+sequential thinking; trace every claim, confidence >80%.
345- **Shared Protocol Duplication:** inline protocols are intentional; never extract to file references.
346- **AI Mistake Prevention:** verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
347
348**IMPORTANT MUST ATTENTION** edit `sync-inline-versions.md` FIRST before syncing to skills
349**IMPORTANT MUST ATTENTION** verify SYNC tag balance after every sync run
350**IMPORTANT MUST ATTENTION** NEVER modify content outside `<!-- SYNC:tag -->` boundaries
351**IMPORTANT MUST ATTENTION** skip files with missing close tags and report as errors
352
353**[TASK-PLANNING]** Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using task tracking.
354
355<!-- CODEX:SYNC-PROMPT-PROTOCOLS:START -->
356
357## Hookless Prompt Protocol Mirror (Auto-Synced)
358
359Source: `.claude/.ck.json` + `.claude/skills/shared/sync-inline-versions.md` (`:full` blocks) + `.claude/scripts/lib/hookless-prompt-protocol.cjs`
360
361## [WORKFLOW-EXECUTION-PROTOCOL] [BLOCKING] Workflow Execution Protocol — MANDATORY IMPORTANT MUST CRITICAL. Do not skip for any reason.
362
363**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.
364
3651. **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.
3662. **ANALYZE:** Choose the best option: execute directly, invoke a skill, activate a standard workflow, or compose a custom step combination.
3673. **AUTO-SELECT:** Pick the best option yourself. Do not ask the user to choose between direct execution, skill, standard workflow, or custom workflow.
3684. **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.
3695. **CREATE TASKS:** task tracking for ALL workflow/skill/custom steps before execution when the selected path has multiple steps.
3706. **PARALLELIZE:** Before executing the task list, tag each task `PAR` (independent inputs + write set disjoint from every other `PAR` task) or `SEQ` (name the blocking dependency), group `PAR` tasks into waves, declare the wave plan, and spawn each wave's sub-agents in ONE message — all-return barrier per wave, fan-out one level deep unless a sub-agent's own definition authorizes further fan-out. Sequential-by-default is a defect when tasks are independent; do not parallelize shared write targets, output-consuming tasks, trivial single-file work, ordering a skill or workflow explicitly fixes, or user-approval gates.
3717. **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)
372
373## Shared AI-SDD Protocol Markers
374
375Source: `.claude/skills/shared/sync-inline-versions.md`
376
377## SYNC:ai-sdd-artifact-contract
378
379> **AI-SDD Artifact Contract** — Shared spec-driven development rules stay portable and source-owned.
380>
381> 1. Keep reusable AI-SDD principles in `.claude`; put repository-specific paths, commands, owners, products, and formats in project config/reference docs.
382> 2. Preserve cycle: `spec -> plan -> tasks -> implement -> verify -> update spec/docs`.
383> 3. Trace every requirement or invariant through decision, task, TC/test, source evidence, and docs/spec update.
384> 4. Treat code-to-spec extraction as reference-only until accepted by the canonical spec owner.
385> 5. Any supported AI tool may plan, implement, review, or verify with synced context; using multiple tools is optional.
386> 6. Update `.claude` source first, then sync generated mirrors; do not manually edit `.agents`, `.codex`, or `AGENTS.md`. — why: mirrors are generated artifacts; hand-edits are overwritten on the next sync
387> 7. If `docs/project-config.json`, root instruction files, or a required project-reference doc is missing or stale, auto-run `$project-init` or the narrow lower-level route before ordinary project-specific work.
388>
389> **Active reference:** `shared/sdd-artifact-contract.md` in the active skills root.
390
391---
392
393## SYNC:ai-sdd-artifact-contract:reminder
394
395- **MANDATORY** Apply `shared/sdd-artifact-contract.md`; keep reusable AI-SDD in `.claude` and local rules in project docs.
396- **MANDATORY** Code-to-spec extraction is reference-only until canonical acceptance; any supported AI tool may execute with synced context.
397- **MANDATORY** Update `.claude` source before syncing generated mirrors; do not manually edit `.agents`, `.codex`, or `AGENTS.md`.
398- **MANDATORY** Missing or stale project config, root instruction files, or required reference docs route project-specific work through `$project-init` or the narrow setup route automatically.
399 **[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.
400
401## [LESSON-LEARNED-REMINDER] [BLOCKING] Task Planning & Continuous Improvement — MANDATORY. Do not skip.
402
403Break work into small tasks (task tracking) before starting. Add final task: "Analyze AI mistakes & lessons learned".
404
405**Extract lessons — ROOT CAUSE ONLY, not symptom fixes:**
406
4071. Name the FAILURE MODE (reasoning/assumption failure), not symptom — "assumed API existed without reading source" not "used wrong enum value".
4082. Generality test: does this failure mode apply to ≥3 contexts/codebases? If not, abstract one level up.
4093. Write as a universal rule — strip project-specific names/paths/classes. Useful on any codebase.
4104. Consolidate: multiple mistakes sharing one failure mode → ONE lesson.
4115. **Recurrence gate:** "Would this recur in future session WITHOUT this reminder?" — No → skip `$learn`.
4126. **Auto-fix gate:** "Could `$code-review`/`$code-simplifier`/`$security-review`/`$lint` catch this?" — Yes → improve review skill instead.
4137. BOTH gates pass → ask user to run `$learn`.
414 **[CRITICAL-THINKING-MINDSET]** Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
415 **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.
416 **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.
417 **Goal-driven execution:** Define success criteria first, loop until verified, and stop only when observable checks pass.
418 **Tests verify intent:** Tests must protect business rules/invariants and fail when the protected intent breaks, not only mirror current behavior.
419
420## Common AI Mistake Prevention (System Lessons)
421
422- **Re-read files after context compaction.** Edit requires prior Read in same context; compaction wipes read state. Re-read before editing.
423- **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.
424- **Check downstream references before deleting.** Deletions cascade doc/code staleness. Map referencing files before removal.
425- **After memory loss, check existing state before creating new.** Compaction wipes prior-work memory. Query current state to resume — never blindly duplicate.
426- **Verify AI-generated content against actual code.** AI hallucinates APIs, class names, method signatures. Grep to confirm existence before documenting/referencing.
427- **Trace full dependency chain after edits.** Changing a definition misses downstream consumers. Trace the full chain.
428- **When renaming, grep ALL consumer file types.** Some file types silently ignore missing refs (no compile error). Search code, templates, configs, generated files.
429- **Trace ALL code paths when verifying correctness.** Code existing ≠ code executing. Trace early exits, error branches, conditional skips — not just happy path.
430- **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.
431- **Verify sub-agent results after context recovery.** Background agents may finish while parent compacted — grep-verify output, don't trust assumed completion.
432- **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.
433- **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).
434- **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.
435- **When debugging, ask "whose responsibility?" before fixing.** Trace caller (wrong data) vs callee (wrong handling). Fix at responsible layer — never patch symptom site.
436- **Test failure → record a provisional verdict before trace/edit, then investigate.** Use the full five-way taxonomy: SOURCE-WRONG (production violates intent), TEST-WRONG (assertion/setup is stale), TEST-NOT-OPTIMAL (valid but fragile or low-signal test), ENVIRONMENT-BLOCKED (external state prevents a verdict), or AMBIGUOUS (intent/evidence cannot choose safely). Then trace root cause and triangulate against the governing spec (`docs/specs/**` if one exists) AND source. NEVER weaken an assertion, add a skip, relax a timeout, or change source merely to force green.
437- **Grep ALL removed names after extraction/refactoring.** Primary file "done" ≠ secondary files clean. Grep entire scope for every removed symbol before declaring complete.
438- **Assume existing values are intentional — ask WHY before changing OR flagging one as a defect.** Pattern-matching as "wrong" skips context. Before changing or reporting any constant/limit/flag/cutoff: read comments, git blame, the CALLER's ordering (the guarantee that makes the value correct usually lives in code running immediately BEFORE the cited line), and 2+ sibling call sites of the same convention. A doc stating WHAT without WHY is missing rationale, not proof of a missing guard — and in a validation pass, an accurate `file:line` citation proves the transcription, never the defect.
439- **Verify ALL affected outputs, not just the first.** One build green ≠ all green. Multi-stack changes (backend/frontend/tests/docs) require verifying EVERY output.
440- **Evaluate fit before copying a nearby pattern.** Closest example ≠ matching preconditions — verify the new context shares the same constraints, base classes, scope, lifetime.
441- **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.
442- **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.
443- **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.
444- **[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.
445- **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".
446- **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.
447- **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.
448- **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.
449- **Assert the outcome your system OWNS, never the intermediate state your INFRASTRUCTURE owns.** When testing anything asynchronous (queue/broker delivery, retries, background jobs, caches, replication), assert the final business/entity state. NEVER assert the delivery bookkeeping — consume/send status, attempt counts, last-error, row existence or counts in a broker, scheduler, or outbox/inbox table. That bookkeeping lives in shared infrastructure that ANY co-running process (a peer worker, a second replica, a leftover local container) can write, usually under a deterministic shared key, so the assertion silently tests the developer's environment instead of the system: green when run alone, flaky the instant anything else shares that broker + database. Gate question for every assertion: "would this hold no matter WHICH process did the work?" — if no, assert the converged data state instead. Corollary: process-local fault injection and in-process telemetry cannot gate work any process may perform — use them as stress amplifiers (arm → bounded window → disarm → assert convergence), never as preconditions.
450- **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.
451
452<!-- CODEX:SYNC-PROMPT-PROTOCOLS:END -->