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: Deploy and manage cloud infrastructure across Cloudflare (Workers, R2, D1), Docker containers, and Google Cloud.
Workflow:
- Provider Selection — Choose Cloudflare (edge/low-latency), Docker (containers/microservices), or GCP (enterprise/K8s)
- Project Setup — Initialize with Wrangler CLI, Dockerfile, or gcloud CLI
- Local Development — Test locally before deploying
- Deploy & Verify — Deploy to the target provider/runtime with health checks
Key Rules:
- Run containers as non-root user; scan images for vulnerabilities
- Use multi-stage Docker builds to minimize image size
- Store secrets in environment variables, never in code
- Use R2 over S3 when zero egress cost matters
Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).
DevOps Skill
Comprehensive guide for deploying and managing cloud infrastructure across Cloudflare edge services, Docker containerization, and Google Cloud.
When to Use This Skill
Use this skill when:
- Deploying serverless applications to Cloudflare Workers
- Containerizing applications with Docker
- Managing Google Cloud infrastructure with gcloud CLI
- Setting up CI/CD pipelines across platforms
- Optimizing cloud infrastructure costs
- Implementing multi-region deployments
- Building edge-first architectures
- Managing container orchestration with Kubernetes
- Configuring cloud storage solutions (R2, Cloud Storage)
- Automating infrastructure with scripts and IaC
Provider Selection Guide
When to Use Cloudflare
Best For:
- Edge-first applications with global distribution
- Ultra-low latency requirements (<50ms)
- Static sites with serverless functions
- Zero egress cost scenarios (R2 storage)
- WebSocket/real-time applications (Durable Objects)
- AI/ML at the edge (Workers AI)
Key Products:
- Workers (serverless functions)
- R2 (object storage, S3-compatible)
- D1 (SQLite database with global replication)
- KV (key-value store)
- Pages (static hosting + functions)
- Durable Objects (stateful compute)
- Browser Rendering (headless browser automation)
Cost Profile: Pay-per-request, generous free tier, zero egress fees
When to Use Docker
Best For:
- Local development consistency
- Microservices architectures
- Multi-language stack applications
- Traditional VPS/VM deployments
- Kubernetes orchestration
- CI/CD build environments
- Database containerization (dev/test)
Key Capabilities:
- Application isolation and portability
- Multi-stage builds for optimization
- Docker Compose for multi-container apps
- Volume management for data persistence
- Network configuration and service discovery
- Cross-architecture compatibility (amd64, arm64)
Cost Profile: Infrastructure cost only (compute + storage)
When to Use Google Cloud
Best For:
- Enterprise-scale applications
- Data analytics and ML pipelines (BigQuery, Vertex AI)
- Hybrid/multi-cloud deployments
- Kubernetes at scale (GKE)
- Managed databases (Cloud SQL, Firestore, Spanner)
- Complex IAM and compliance requirements
Key Services:
- Compute Engine (VMs)
- GKE (managed Kubernetes)
- Cloud Run (containerized serverless)
- App Engine (PaaS)
- Cloud Storage (object storage)
- Cloud SQL (managed databases)
Cost Profile: Varied pricing, sustained use discounts, committed use contracts
Quick Start
Cloudflare Workers
# Install Wrangler CLI
npm install -g wrangler
# Create and deploy Worker
wrangler init my-worker
cd my-worker
wrangler deploy
See: references/cloudflare-workers-basics.md
Docker Container
# Create Dockerfile
cat > Dockerfile <<EOF
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
EOF
# Build and run
docker build -t myapp .
docker run -p 3000:3000 myapp
See: references/docker-basics.md
Google Cloud Deployment
# Install and authenticate
curl https://sdk.cloud.google.com | bash
gcloud init
gcloud auth login
# Deploy to Cloud Run
gcloud run deploy my-service \
--image gcr.io/project/image \
--region us-central1
See the Google Cloud reference in references/
Reference Navigation
Cloudflare Developer Stack
- Cloudflare reference - Edge computing overview, key components
cloudflare-workers-basics.md - Getting started, handler types, basic patterns
cloudflare-workers-advanced.md - Advanced patterns, performance, optimization
cloudflare-workers-apis.md - Runtime APIs, bindings, integrations
cloudflare-r2-storage.md - R2 object storage, S3 compatibility, best practices
cloudflare-d1-kv.md - D1 SQLite database, KV store, use cases
browser-rendering.md - Puppeteer/Playwright automation on Cloudflare
Docker Containerization
docker-basics.md - Core concepts, Dockerfile, images, containers
docker-compose.md - Multi-container apps, networking, volumes
Google Cloud
- Google Cloud reference - GCP overview, gcloud CLI, authentication
gcloud-services.md - Compute Engine, GKE, Cloud Run, App Engine
Python Utilities
scripts/cloudflare-deploy.py - Automate Cloudflare Worker deployments
scripts/docker-optimize.py - Analyze and optimize Dockerfiles
Common Workflows
Edge + Container Hybrid
# Cloudflare Workers (API Gateway)
# -> Docker containers on Cloud Run (Backend Services)
# -> R2 (Object Storage)
# Benefits:
# - Edge caching and routing
# - Containerized business logic
# - Global distribution
Multi-Stage Docker Build
# Build stage
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production stage
FROM node:20-alpine
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
USER node
CMD ["node", "dist/server.js"]
CI/CD Pipeline Pattern
# 1. Build: Docker multi-stage build
# 2. Test: Run tests in container
# 3. Push: Push to registry (GCR, Docker Hub)
# 4. Deploy: Deploy to Cloudflare Workers / Cloud Run
# 5. Verify: Health checks and smoke tests
Best Practices
Security
- Run containers as non-root user
- Use service account impersonation (GCP)
- Store secrets in environment variables, not code
- Scan images for vulnerabilities (Docker Scout)
- Use API tokens with minimal permissions
Performance
- Multi-stage Docker builds to reduce image size
- Edge caching with Cloudflare KV
- Use R2 for zero egress cost storage
- Implement health checks for containers
- Set appropriate timeouts and resource limits
Cost Optimization
- Use Cloudflare R2 instead of S3 for large egress
- Implement caching strategies (edge + KV)
- Right-size container resources
- Use sustained use discounts (GCP)
- Monitor usage with cloud provider dashboards
Development
- Use Docker Compose for local development
- Wrangler dev for local Worker testing
- Named gcloud configurations for multi-environment
- Version control infrastructure code
- Implement automated testing in CI/CD
Decision Matrix
| Need |
Choose |
| Sub-50ms latency globally |
Cloudflare Workers |
| Large file storage (zero egress) |
Cloudflare R2 |
| SQL database (global reads) |
Cloudflare D1 |
| Containerized workloads |
Docker + Cloud Run/GKE |
| Enterprise Kubernetes |
GKE |
| Managed relational DB |
Cloud SQL |
| Static site + API |
Cloudflare Pages |
| WebSocket/real-time |
Cloudflare Durable Objects |
| ML/AI pipelines |
GCP Vertex AI |
| Browser automation |
Cloudflare Browser Rendering |
Resources
Implementation Checklist
Cloudflare Workers
Docker
Google Cloud
Related
[IMPORTANT] Use task tracking to break ALL work into small tasks BEFORE starting — including tasks for each file read. This prevents context loss from long files. For simple tasks, AI MUST ATTENTION ask user whether to skip.
AI Mistake Prevention — Failure modes to avoid on every task:
Re-read files after context changes. Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
Verify generated content against source evidence. AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
Check downstream references before deleting or renaming. Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
Trace the full impact chain after edits. Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
Verify ALL affected outputs, not just the first. One green check is not all green checks; validate every output surface the change can affect.
Assume existing values are intentional — ask WHY before changing OR flagging one as a defect. Before changing or reporting a constant, limit, flag, cutoff, wording, or pattern, read nearby context and history, the CALLER's ordering, and 2+ sibling call sites of the same convention. A doc stating WHAT without WHY is missing rationale, not proof of a missing guard.
Surface ambiguity before acting — don't pick silently. Multiple valid interpretations require an explicit question or stated assumption with risk.
Assert the outcome your system owns, not the intermediate state your infrastructure owns. When verifying async work, assert the final business state — never the delivery/retry bookkeeping held in shared infrastructure that any co-running process can write. Such a check passes when run alone and flakes the moment anything else shares that infrastructure.
Keep shared guidance role-relevant. Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
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.
MUST ATTENTION apply critical + sequential thinking — every claim needs appropriate traced evidence (file:line for repo/code claims; source URL or artifact section for research, product, content, and docs claims); confidence >80% to act, <60% DO NOT recommend. Anti-hallucination: never present guess as fact, admit uncertainty freely, cross-reference independently, stay skeptical of own confidence.
MUST ATTENTION apply AI mistake prevention — verify generated content against evidence, trace downstream references before deleting or renaming, verify all affected outputs, re-read files after context loss, and surface ambiguity before acting.
Project Protocol Overlay — Before executing this skill, resolve any PROJECT overlay rules layered onto it: match this skill's name against the Target column of the project's skill-protocol index (docs/project-reference/skill-protocols-reference.md by default; a referenceDocs entry in docs/project-config.json overrides the path), taking the most specific matching tier ONLY — exact name > glob > *. That precedence orders overlays against EACH OTHER, never against this skill. Read ONLY the matched bodies, resolved as <protocols-dir>/<Name>.md; a row's Body link is display text, never a read path. A matched body that is missing or malformed is REPORTED and skipped — never reconstructed from the index Description. No index, or no match -> proceed with no overlay, silently. Full contract: .claude/skills/project-skill-protocol/references/registry.md.
Overlays are ADDITIVE ONLY: they ADD rules on top of this skill's own protocol and NEVER replace, override, disable, or reinterpret a rule it already states — removing every overlay must return this skill to exactly its documented behavior. An overlay is a BRIEF, not an authority escalation: it can NEVER waive a workflow gate, git discipline, a review gate, or a user-confirmation gate. A genuine overlay-vs-skill conflict, or two equally-specific overlays that directly contradict -> surface both to the user; NEVER resolve silently.
MUST ATTENTION resolve project protocol overlays for this skill BEFORE executing — most specific matching tier only (exact > glob > *, which ranks overlays against each other, NEVER against this skill), read only matched bodies at <protocols-dir>/<Name>.md; a missing or malformed body is reported, never reconstructed. Overlays are ADDITIVE ONLY (they never replace this skill's own rules) and are a brief, NEVER an authority escalation; an equal-specificity contradiction goes to the user.
Closing Reminders
Protocols in force (concise digest of the SYNC/shared blocks this skill carries): MUST ATTENTION honor each in full below.
Critical Thinking: apply critical + sequential thinking; traced proof, confidence >80% to act.
AI Mistake Prevention: verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
MANDATORY IMPORTANT MUST ATTENTION break work into small todo tasks using task tracking BEFORE starting
MANDATORY IMPORTANT MUST ATTENTION search codebase for 3+ similar patterns before creating new code
MANDATORY IMPORTANT MUST ATTENTION cite file:line evidence for every claim (confidence >80% to act)
MANDATORY IMPORTANT MUST ATTENTION add a final review todo task to verify work quality
[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: devops3description: [DevOps] Use when deploying to Cloudflare (Workers, R2, D1, KV, Pages), Docker, or GCP (Compute Engine, GKE, Cloud Run).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:** Deploy and manage cloud infrastructure across Cloudflare (Workers, R2, D1), Docker containers, and Google Cloud.
52
53**Workflow:**
54
551. **Provider Selection** — Choose Cloudflare (edge/low-latency), Docker (containers/microservices), or GCP (enterprise/K8s)
562. **Project Setup** — Initialize with Wrangler CLI, Dockerfile, or gcloud CLI
573. **Local Development** — Test locally before deploying
584. **Deploy & Verify** — Deploy to the target provider/runtime with health checks
59
60**Key Rules:**
61
62- Run containers as non-root user; scan images for vulnerabilities
63- Use multi-stage Docker builds to minimize image size
64- Store secrets in environment variables, never in code
65- Use R2 over S3 when zero egress cost matters
66
67**Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).**
68
69# DevOps Skill
70
71Comprehensive guide for deploying and managing cloud infrastructure across Cloudflare edge services, Docker containerization, and Google Cloud.
72
73## When to Use This Skill
74
75Use this skill when:
76
77- Deploying serverless applications to Cloudflare Workers
78- Containerizing applications with Docker
79- Managing Google Cloud infrastructure with gcloud CLI
80- Setting up CI/CD pipelines across platforms
81- Optimizing cloud infrastructure costs
82- Implementing multi-region deployments
83- Building edge-first architectures
84- Managing container orchestration with Kubernetes
85- Configuring cloud storage solutions (R2, Cloud Storage)
86- Automating infrastructure with scripts and IaC
87
88## Provider Selection Guide
89
90### When to Use Cloudflare
91
92**Best For:**
93
94- Edge-first applications with global distribution
95- Ultra-low latency requirements (<50ms)
96- Static sites with serverless functions
97- Zero egress cost scenarios (R2 storage)
98- WebSocket/real-time applications (Durable Objects)
99- AI/ML at the edge (Workers AI)
100
101**Key Products:**
102
103- Workers (serverless functions)
104- R2 (object storage, S3-compatible)
105- D1 (SQLite database with global replication)
106- KV (key-value store)
107- Pages (static hosting + functions)
108- Durable Objects (stateful compute)
109- Browser Rendering (headless browser automation)
110
111**Cost Profile:** Pay-per-request, generous free tier, zero egress fees
112
113### When to Use Docker
114
115**Best For:**
116
117- Local development consistency
118- Microservices architectures
119- Multi-language stack applications
120- Traditional VPS/VM deployments
121- Kubernetes orchestration
122- CI/CD build environments
123- Database containerization (dev/test)
124
125**Key Capabilities:**
126
127- Application isolation and portability
128- Multi-stage builds for optimization
129- Docker Compose for multi-container apps
130- Volume management for data persistence
131- Network configuration and service discovery
132- Cross-architecture compatibility (amd64, arm64)
133
134**Cost Profile:** Infrastructure cost only (compute + storage)
135
136### When to Use Google Cloud
137
138**Best For:**
139
140- Enterprise-scale applications
141- Data analytics and ML pipelines (BigQuery, Vertex AI)
142- Hybrid/multi-cloud deployments
143- Kubernetes at scale (GKE)
144- Managed databases (Cloud SQL, Firestore, Spanner)
145- Complex IAM and compliance requirements
146
147**Key Services:**
148
149- Compute Engine (VMs)
150- GKE (managed Kubernetes)
151- Cloud Run (containerized serverless)
152- App Engine (PaaS)
153- Cloud Storage (object storage)
154- Cloud SQL (managed databases)
155
156**Cost Profile:** Varied pricing, sustained use discounts, committed use contracts
157
158## Quick Start
159
160### Cloudflare Workers
161
162```bash
163# Install Wrangler CLI
164npm install -g wrangler
165
166# Create and deploy Worker
167wrangler init my-worker
168cd my-worker
169wrangler deploy
170```
171
172See: `references/cloudflare-workers-basics.md`
173
174### Docker Container
175
176```bash
177# Create Dockerfile
178cat > Dockerfile <<EOF
179FROM node:20-alpine
180WORKDIR /app
181COPY package*.json ./
182RUN npm ci --production
183COPY . .
184EXPOSE 3000
185CMD ["node", "server.js"]
186EOF
187
188# Build and run
189docker build -t myapp .
190docker run -p 3000:3000 myapp
191```
192
193See: `references/docker-basics.md`
194
195### Google Cloud Deployment
196
197```bash
198# Install and authenticate
199curl https://sdk.cloud.google.com | bash
200gcloud init
201gcloud auth login
202
203# Deploy to Cloud Run
204gcloud run deploy my-service \
205 --image gcr.io/project/image \
206 --region us-central1
207```
208
209See the Google Cloud reference in `references/`
210
211## Reference Navigation
212
213### Cloudflare Developer Stack
214
215- Cloudflare reference - Edge computing overview, key components
216- `cloudflare-workers-basics.md` - Getting started, handler types, basic patterns
217- `cloudflare-workers-advanced.md` - Advanced patterns, performance, optimization
218- `cloudflare-workers-apis.md` - Runtime APIs, bindings, integrations
219- `cloudflare-r2-storage.md` - R2 object storage, S3 compatibility, best practices
220- `cloudflare-d1-kv.md` - D1 SQLite database, KV store, use cases
221- `browser-rendering.md` - Puppeteer/Playwright automation on Cloudflare
222
223### Docker Containerization
224
225- `docker-basics.md` - Core concepts, Dockerfile, images, containers
226- `docker-compose.md` - Multi-container apps, networking, volumes
227
228### Google Cloud
229
230- Google Cloud reference - GCP overview, gcloud CLI, authentication
231- `gcloud-services.md` - Compute Engine, GKE, Cloud Run, App Engine
232
233### Python Utilities
234
235- `scripts/cloudflare-deploy.py` - Automate Cloudflare Worker deployments
236- `scripts/docker-optimize.py` - Analyze and optimize Dockerfiles
237
238## Common Workflows
239
240### Edge + Container Hybrid
241
242```yaml
243# Cloudflare Workers (API Gateway)
244# -> Docker containers on Cloud Run (Backend Services)
245# -> R2 (Object Storage)
246
247# Benefits:
248# - Edge caching and routing
249# - Containerized business logic
250# - Global distribution
251```
252
253### Multi-Stage Docker Build
254
255```dockerfile
256# Build stage
257FROM node:20-alpine AS build
258WORKDIR /app
259COPY package*.json ./
260RUN npm ci
261COPY . .
262RUN npm run build
263
264# Production stage
265FROM node:20-alpine
266WORKDIR /app
267COPY --from=build /app/dist ./dist
268COPY --from=build /app/node_modules ./node_modules
269USER node
270CMD ["node", "dist/server.js"]
271```
272
273### CI/CD Pipeline Pattern
274
275```yaml
276# 1. Build: Docker multi-stage build
277# 2. Test: Run tests in container
278# 3. Push: Push to registry (GCR, Docker Hub)
279# 4. Deploy: Deploy to Cloudflare Workers / Cloud Run
280# 5. Verify: Health checks and smoke tests
281```
282
283## Best Practices
284
285### Security
286
287- Run containers as non-root user
288- Use service account impersonation (GCP)
289- Store secrets in environment variables, not code
290- Scan images for vulnerabilities (Docker Scout)
291- Use API tokens with minimal permissions
292
293### Performance
294
295- Multi-stage Docker builds to reduce image size
296- Edge caching with Cloudflare KV
297- Use R2 for zero egress cost storage
298- Implement health checks for containers
299- Set appropriate timeouts and resource limits
300
301### Cost Optimization
302
303- Use Cloudflare R2 instead of S3 for large egress
304- Implement caching strategies (edge + KV)
305- Right-size container resources
306- Use sustained use discounts (GCP)
307- Monitor usage with cloud provider dashboards
308
309### Development
310
311- Use Docker Compose for local development
312- Wrangler dev for local Worker testing
313- Named gcloud configurations for multi-environment
314- Version control infrastructure code
315- Implement automated testing in CI/CD
316
317## Decision Matrix
318
319| Need | Choose |
320| -------------------------------- | ---------------------------- |
321| Sub-50ms latency globally | Cloudflare Workers |
322| Large file storage (zero egress) | Cloudflare R2 |
323| SQL database (global reads) | Cloudflare D1 |
324| Containerized workloads | Docker + Cloud Run/GKE |
325| Enterprise Kubernetes | GKE |
326| Managed relational DB | Cloud SQL |
327| Static site + API | Cloudflare Pages |
328| WebSocket/real-time | Cloudflare Durable Objects |
329| ML/AI pipelines | GCP Vertex AI |
330| Browser automation | Cloudflare Browser Rendering |
331
332## Resources
333
334- **Cloudflare Docs:** https://developers.cloudflare.com
335- **Docker Docs:** https://docs.docker.com
336- **GCP Docs:** https://cloud.google.com/docs
337- **Wrangler CLI:** https://developers.cloudflare.com/workers/wrangler/
338- **gcloud CLI:** https://cloud.google.com/sdk/gcloud
339
340## Implementation Checklist
341
342### Cloudflare Workers
343
344- [ ] Install Wrangler CLI
345- [ ] Create Worker project
346- [ ] Configure wrangler.toml (bindings, routes)
347- [ ] Test locally with `wrangler dev`
348- [ ] Deploy with `wrangler deploy`
349
350### Docker
351
352- [ ] Write Dockerfile with multi-stage builds
353- [ ] Create .dockerignore file
354- [ ] Test build locally
355- [ ] Push to registry
356- [ ] Deploy to target provider/runtime
357
358### Google Cloud
359
360- [ ] Install gcloud CLI
361- [ ] Authenticate with service account
362- [ ] Create project and enable APIs
363- [ ] Configure IAM permissions
364- [ ] Deploy and monitor resources
365
366## Related
367
368- `db-migrate`
369
370---
371
372> **[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.
373
374<!-- SYNC:ai-mistake-prevention -->
375
376> **AI Mistake Prevention** — Failure modes to avoid on every task:
377>
378> **Re-read files after context changes.** Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
379> **Verify generated content against source evidence.** AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
380> **Check downstream references before deleting or renaming.** Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
381> **Trace the full impact chain after edits.** Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
382> **Verify ALL affected outputs, not just the first.** One green check is not all green checks; validate every output surface the change can affect.
383> **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.
384> **Surface ambiguity before acting — don't pick silently.** Multiple valid interpretations require an explicit question or stated assumption with risk.
385> **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.
386> **Keep shared guidance role-relevant.** Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
387
388<!-- /SYNC:ai-mistake-prevention -->
389
390<!-- SYNC:critical-thinking-mindset -->
391
392> **Critical Thinking Mindset** — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
393> **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.
394
395<!-- /SYNC:critical-thinking-mindset -->
396
397<!-- SYNC:critical-thinking-mindset:reminder -->
398
399**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.
400
401<!-- /SYNC:critical-thinking-mindset:reminder -->
402
403<!-- SYNC:ai-mistake-prevention:reminder -->
404
405**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.
406
407<!-- /SYNC:ai-mistake-prevention:reminder -->
408
409<!-- SYNC:project-protocol-overlay -->
410
411> **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`.
412>
413> 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.
414
415<!-- /SYNC:project-protocol-overlay -->
416
417<!-- SYNC:project-protocol-overlay:reminder -->
418
419**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.
420
421<!-- /SYNC:project-protocol-overlay:reminder -->
422
423## Closing Reminders
424
425**Protocols in force (concise digest of the SYNC/shared blocks this skill carries):** MUST ATTENTION honor each in full below.
426
427- **Critical Thinking:** apply critical + sequential thinking; traced proof, confidence >80% to act.
428- **AI Mistake Prevention:** verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
429
430- **MANDATORY IMPORTANT MUST ATTENTION** break work into small todo tasks using task tracking BEFORE starting
431- **MANDATORY IMPORTANT MUST ATTENTION** search codebase for 3+ similar patterns before creating new code
432- **MANDATORY IMPORTANT MUST ATTENTION** cite `file:line` evidence for every claim (confidence >80% to act)
433- **MANDATORY IMPORTANT MUST ATTENTION** add a final review todo task to verify work quality
434
435**[TASK-PLANNING]** Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using task tracking.
436
437<!-- CODEX:SYNC-PROMPT-PROTOCOLS:START -->
438
439## Hookless Prompt Protocol Mirror (Auto-Synced)
440
441Source: `.claude/.ck.json` + `.claude/skills/shared/sync-inline-versions.md` (`:full` blocks) + `.claude/scripts/lib/hookless-prompt-protocol.cjs`
442
443## [WORKFLOW-EXECUTION-PROTOCOL] [BLOCKING] Workflow Execution Protocol — MANDATORY IMPORTANT MUST CRITICAL. Do not skip for any reason.
444
445**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.
446
4471. **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.
4482. **ANALYZE:** Choose the best option: execute directly, invoke a skill, activate a standard workflow, or compose a custom step combination.
4493. **AUTO-SELECT:** Pick the best option yourself. Do not ask the user to choose between direct execution, skill, standard workflow, or custom workflow.
4504. **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.
4515. **CREATE TASKS:** task tracking for ALL workflow/skill/custom steps before execution when the selected path has multiple steps.
4526. **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.
4537. **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)
454
455## Shared AI-SDD Protocol Markers
456
457Source: `.claude/skills/shared/sync-inline-versions.md`
458
459## SYNC:ai-sdd-artifact-contract
460
461> **AI-SDD Artifact Contract** — Shared spec-driven development rules stay portable and source-owned.
462>
463> 1. Keep reusable AI-SDD principles in `.claude`; put repository-specific paths, commands, owners, products, and formats in project config/reference docs.
464> 2. Preserve cycle: `spec -> plan -> tasks -> implement -> verify -> update spec/docs`.
465> 3. Trace every requirement or invariant through decision, task, TC/test, source evidence, and docs/spec update.
466> 4. Treat code-to-spec extraction as reference-only until accepted by the canonical spec owner.
467> 5. Any supported AI tool may plan, implement, review, or verify with synced context; using multiple tools is optional.
468> 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
469> 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.
470>
471> **Active reference:** `shared/sdd-artifact-contract.md` in the active skills root.
472
473---
474
475## SYNC:ai-sdd-artifact-contract:reminder
476
477- **MANDATORY** Apply `shared/sdd-artifact-contract.md`; keep reusable AI-SDD in `.claude` and local rules in project docs.
478- **MANDATORY** Code-to-spec extraction is reference-only until canonical acceptance; any supported AI tool may execute with synced context.
479- **MANDATORY** Update `.claude` source before syncing generated mirrors; do not manually edit `.agents`, `.codex`, or `AGENTS.md`.
480- **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.
481 **[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.
482
483## [LESSON-LEARNED-REMINDER] [BLOCKING] Task Planning & Continuous Improvement — MANDATORY. Do not skip.
484
485Break work into small tasks (task tracking) before starting. Add final task: "Analyze AI mistakes & lessons learned".
486
487**Extract lessons — ROOT CAUSE ONLY, not symptom fixes:**
488
4891. Name the FAILURE MODE (reasoning/assumption failure), not symptom — "assumed API existed without reading source" not "used wrong enum value".
4902. Generality test: does this failure mode apply to ≥3 contexts/codebases? If not, abstract one level up.
4913. Write as a universal rule — strip project-specific names/paths/classes. Useful on any codebase.
4924. Consolidate: multiple mistakes sharing one failure mode → ONE lesson.
4935. **Recurrence gate:** "Would this recur in future session WITHOUT this reminder?" — No → skip `$learn`.
4946. **Auto-fix gate:** "Could `$code-review`/`$code-simplifier`/`$security-review`/`$lint` catch this?" — Yes → improve review skill instead.
4957. BOTH gates pass → ask user to run `$learn`.
496 **[CRITICAL-THINKING-MINDSET]** Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
497 **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.
498 **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.
499 **Goal-driven execution:** Define success criteria first, loop until verified, and stop only when observable checks pass.
500 **Tests verify intent:** Tests must protect business rules/invariants and fail when the protected intent breaks, not only mirror current behavior.
501
502## Common AI Mistake Prevention (System Lessons)
503
504- **Re-read files after context compaction.** Edit requires prior Read in same context; compaction wipes read state. Re-read before editing.
505- **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.
506- **Check downstream references before deleting.** Deletions cascade doc/code staleness. Map referencing files before removal.
507- **After memory loss, check existing state before creating new.** Compaction wipes prior-work memory. Query current state to resume — never blindly duplicate.
508- **Verify AI-generated content against actual code.** AI hallucinates APIs, class names, method signatures. Grep to confirm existence before documenting/referencing.
509- **Trace full dependency chain after edits.** Changing a definition misses downstream consumers. Trace the full chain.
510- **When renaming, grep ALL consumer file types.** Some file types silently ignore missing refs (no compile error). Search code, templates, configs, generated files.
511- **Trace ALL code paths when verifying correctness.** Code existing ≠ code executing. Trace early exits, error branches, conditional skips — not just happy path.
512- **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.
513- **Verify sub-agent results after context recovery.** Background agents may finish while parent compacted — grep-verify output, don't trust assumed completion.
514- **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.
515- **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).
516- **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.
517- **When debugging, ask "whose responsibility?" before fixing.** Trace caller (wrong data) vs callee (wrong handling). Fix at responsible layer — never patch symptom site.
518- **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.
519- **Grep ALL removed names after extraction/refactoring.** Primary file "done" ≠ secondary files clean. Grep entire scope for every removed symbol before declaring complete.
520- **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.
521- **Verify ALL affected outputs, not just the first.** One build green ≠ all green. Multi-stack changes (backend/frontend/tests/docs) require verifying EVERY output.
522- **Evaluate fit before copying a nearby pattern.** Closest example ≠ matching preconditions — verify the new context shares the same constraints, base classes, scope, lifetime.
523- **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.
524- **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.
525- **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.
526- **[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.
527- **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".
528- **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.
529- **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.
530- **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.
531- **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.
532- **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.
533
534<!-- CODEX:SYNC-PROMPT-PROTOCOLS:END -->