# Engineering Standards — Claude Code

> Stack-agnostic guardrails for all projects. Managed by Open Orchestra.

## Orchestra Workflow — REQUIRED

This repo uses Open Orchestra for all development work. Every feature or fix MUST go through the workflow:

1. **Task registration**: `orchestra task add --id <ID> --title "..." --owner <role> --paths "..." --goal "..."` before any code is written.
2. **Effort baseline**: `orchestra estimate --task <ID> --sizing <xs|s|m|l|xl> --solo-days N --ai-unguided-days N --ai-guided-days N` before starting implementation.
3. **Autonomous run**: `orchestra workflow run --task <ID> --gates phase` to execute the PM→PO→Architect→Developer→QA→Release phase sequence.
4. **Sizing decision**: `orchestra decision add --task <ID> --owner architect --title "Story sizing" --decision "<sizing> [N points]" ...` is required before the developer phase proceeds.
5. **Architect sizing format**: always use `"<xs|s|m|l|xl> [N points]"` in `--decision` so the sizing gate reads it correctly (e.g. `"m [5 points]"`).
6. **Benchmark**: `orchestra benchmark --task <ID>` after completion to record actual vs declared effort.

Do NOT start implementation without a registered task and workflow run. Use `orchestra workflow runs` to check active runs. Use `orchestra benchmark --summary` to review effectiveness.

## Rule Composition

- Keep root files concise. Put detailed guidance in neutral rule sources and render runtime-specific files such as Cursor `.mdc` only as target outputs.
- Treat specialized rule files like skills: load the smallest relevant set for the task, and load roles, collaboration, testing, security, and delivery gates for broad delivery work.
- Detailed rules are selected by Orchestra from task, phase, role, capability, risk, and path signals; use the root file as an index and universal baseline.

## Work Intake & Sequencing

- Before each work block, confirm the GitHub issue exists, is technically refined, and provides the Backlog Item ID.
- Refine expected domain/model changes, service/integration changes, controller/entry-point changes, data flow, risks, and test evidence before coding.
- Implement in order: models/domain first, service/integration second, controllers/entry points third, evidence and handoff last.
- Run Security review when work touches auth, secrets, PII, file paths, shell execution, network calls, dependencies, TLS, cookies, sessions, CORS, webhooks, or infrastructure.

## UX/UI Product Experience

- User-facing work must be mobile-first, responsive, accessible, and designed around complete end-user flows.
- Screens must include friendly copy, clear next steps, tooltips for unclear controls, and usable loading, empty, error, success, and recovery states.
- Game UI must teach controls, objectives, feedback loops, and failure recovery through contextual guides or progressive prompts.
- UI delivery should include screenshots or recordings for key responsive breakpoints when practical.

## SOLID & Clean Architecture

- **SRP**: One module = one reason to change. Max 300 lines/file, 30 lines/function, 5 params.
- **OCP**: Data-driven designs over per-variant functions. Handler maps over large switch blocks (>5 cases).
- **LSP**: Subclasses honor parent contracts. Never override to throw "not supported".
- **ISP**: No `any`, `object`, or `Record<string, unknown>` in public APIs. Use narrow types and generics.
- **DIP**: Import from barrel exports, not deep paths. Static imports only — no `require()` in TypeScript.
- **Separation of Concerns**: View = layout + events. Service = orchestration. Data = I/O + queries.

## DRY & Clean Code

- Single Source of Truth for all data, types, and config. Never copy-paste across packages.
- Extract a function when two blocks share >5 identical lines.
- Names reveal intent: `validateOrderItems()` not `processData()`. Booleans: `is`/`has`/`can`/`should`.
- No hardcoded timeouts, CLI commands, or error messages. Use named constants.
- Never commit dead code, `console.log` debris, or lint suppressions without a linked issue.
- Comments explain **why**, not **what**. Delete obvious comments.

## Development Engineering

- APIs are product contracts: define request, response, error shape, auth, pagination, rate limits, compatibility, and idempotency before implementation.
- Data models must use domain language, explicit invariants, clear ownership, safe migrations, and indexes based on real query patterns.
- Frontend code must separate presentation, state, data access, and domain logic while preserving accessibility and responsive behavior.
- Performance-sensitive work needs budgets, hot-path review, caching ownership, timeouts, retries, backoff, and measurement evidence.
- Async workflows must be idempotent, observable, retry-safe, and explicit about ordering, partial failure, and dead-letter handling.
- Config must be typed, centralized, environment-isolated, and validated at startup; feature flags need owners, rollout, and cleanup plans.
- AI-assisted code must be grounded in the existing codebase, scoped to the agreed plan, tested, reviewed, and treated as untrusted until verified.

## DevOps Tooling & Operations

- Choose DevOps tools by capability: IaC, CI/CD, GitOps/deploy, orchestration, scalability, downtime strategy, observability, alerting, SLOs, FinOps, security, secrets, backups, load testing, and synthetic monitoring.
- Non-trivial designs must include scalability, downtime, observability, security, cost, and recovery considerations.
- Production services need actionable dashboards and alerts for availability, latency, errors, saturation, cost/capacity, and business-critical signals.
- Rollouts must define strategy, rollback, feature flags, migrations, ownership, RTO/RPO when relevant, and post-release monitoring.

## Security — Non-Negotiable

- **No shell interpolation.** Use `execFile`/`spawn` with args arrays, not `exec` with template literals.
- **No raw innerHTML with user data.** Escape or use `textContent` + `createElement`.
- **Validate URLs** (`https://` only before `fetch()`). Validate file paths (no traversal).
- **Never hardcode secrets.** Use env vars or secret managers. Rotate if accidentally committed.
- Never expose stack traces, internal paths, or DB errors to users.
- Static analysis and secret scanning must run before commit and in CI.

## Data, Infrastructure & Encryption

- **Encrypt at rest**: all databases, object storage, and backups must use AES-256 or equivalent. Enable by default.
- **Encrypt in transit**: TLS 1.2+ for all connections. No plain HTTP, no self-signed certs in production.
- **Passwords**: never store plaintext. Use bcrypt/scrypt/argon2 with per-user salt. Never use MD5/SHA for passwords.
- **PII & sensitive data**: classify fields at design time. Apply column-level encryption or tokenization for SSN, credit cards, health data.
- **Secrets management**: use a vault (AWS Secrets Manager, Azure Key Vault, HashiCorp Vault). Never env vars in container images.
- **Environment segregation**: dev/staging/prod must be isolated (separate accounts/subscriptions, separate credentials, separate networks).
- **Infrastructure as Code**: all infra must be reproducible via IaC (Terraform, Pulumi, CloudFormation). No manual console changes in staging/prod.
- **Least privilege**: every service, user, and CI runner gets the minimum permissions needed. Review IAM quarterly.
- **Database migrations**: version-controlled, idempotent, reversible. Never run DDL manually in production.
- **Backups & DR**: automated daily backups with tested restore. Define RPO/RTO per environment.

## Testing

- Write tests before or alongside implementation. One assertion per test. Name as specifications.
- **Arrange → Act → Assert.** Deterministic: no clock, network, or randomness without seeding.
- Target 90%+ coverage for business logic. Page Object pattern for E2E.
- Every development task must include unit tests for new or changed business logic before QA handoff.
- Prefer Playwright for browser-based E2E, smoke, and regression automation.

## Error Handling

- Empty `catch {}` is forbidden. Log, propagate, or convert to user-friendly message.
- Operational errors: handle gracefully. Programmer errors: crash fast, log, fix.
- Include context in logs: operation name, IDs, duration.

## Agent Roles

- Use roles to force complete thinking, not to create silos. A single agent may cover multiple roles, but it must state which role is active when making a decision.
- Start non-trivial tasks by identifying the needed roles and the lead role. Do not activate every role by default.
- **Product Owner**: user value, acceptance criteria, scope boundaries, release readiness.
- **Product Manager**: product strategy, trade-offs, sequencing, success metrics.
- **Analyst**: requirements discovery, domain modeling, workflows, edge cases.
- **Architect**: system boundaries, integration contracts, data flow, maintainability.
- **Developer**: implementation quality, local consistency, typed and tested code.
- **QA**: verification strategy, regression risk, release confidence.
- **DevOps**: deployment, CI/CD, observability, rollback, operational readiness.
- **Security**: threat modeling, data classification, identity, secrets, dependency risk.
- **UX/UI Designer**: user experience, accessibility, responsive behavior, UI copy, and flow clarity.
- **SRE**: SLOs, error budgets, incident response, capacity, resilience, and production reliability.
- **Data Engineer/Analyst**: pipelines, analytics, reporting definitions, data quality, lineage, and metric correctness.
- **DBA**: database performance, indexes, locking, migrations, replication, backups, and restore safety.
- **Tech Lead/Engineering Manager**: technical coordination, sequencing, ownership, integration, and delivery coherence.
- **Release Manager**: release coordination, rollout, rollback, communication, and go/no-go checklist.
- **Support/Customer Success**: customer impact, support readiness, known issues, FAQs, and feedback loops.
- **Compliance/Privacy**: regulatory requirements, PII, retention, consent, auditability, and data processing risk.
- **Content/Technical Writer**: user docs, technical docs, runbooks, release notes, API examples, and help content.
- **Game Designer**: mechanics, progression, difficulty, economy, onboarding, feedback loops, and player engagement.

## Agent Collaboration

- Agents must collaborate through explicit artifacts and review checkpoints, not isolated workstreams.
- Start with a shared task brief: goal, backlog item, constraints, assumptions, risks, and definition of done.
- Before implementation, discuss the proposed solution and architecture with the user: scope, modules, data flow, risks, trade-offs, test strategy, and expected evidence.
- Product Owner and Analyst define acceptance criteria before Developer or QA treat the task as ready.
- Architect and Security review designs before implementation when work touches boundaries, data, auth, infra, or external integrations.
- UX, SRE, DBA, Release, Compliance, Technical Writer, and Game Designer review when their ownership area is impacted.
- Every handoff must include: status, touched files/components, decisions, risks, test evidence, and remaining work.
- Developer-to-QA handoff must include unit tests, exact test commands, known gaps, and recommended Playwright coverage.
- Parallel work must be split by stable boundaries. Avoid duplicate edits to the same files; if overlap is unavoidable, assign one integration owner.
- Review findings must include severity, affected artifact, expected behavior, actual risk, and a concrete recommendation.
- Product, technical, verification, and security conflicts are resolved by Product Owner, Architect, QA, and Security respectively.

## Delivery Quality Gates

- Work must meet Definition of Ready before implementation and Definition of Done before release.
- Development is complete only after developer verification, QA review, automation planning, and evidence capture.
- Code review must verify behavior, data safety, security, reliability, tests, user impact, and evidence before style.
- QA must produce a test plan covering acceptance criteria, regression areas, edge cases, data setup, and environment assumptions.
- Completed delivery must include evidence: commands run, pass/fail result, logs, screenshots, traces, videos, and unresolved risks when relevant.
- Product Owner gives go/no-go using QA results, automation status, unresolved defects, and accepted risks.
- Important architecture choices need lightweight ADRs. Releases must include rollback, observability, and documentation updates when impacted.
- Dependencies are treated as product risk: justify additions, pin via lockfiles, scan for CVEs, and keep updates atomic.

## Git Discipline

- Each commit compiles and passes tests. One logical change per commit.
- A version-controlled pre-commit hook must run static analysis before every commit.
- Never bypass hooks with `--no-verify` unless the user explicitly approves and a follow-up item records the reason.
- Ask for **Backlog Item ID** first. Use Conventional Commits with backlog scope: `type(ID): short description`.
- Mark breaking changes with `!` and a `BREAKING CHANGE:` footer.
- Keep PRs <400 lines. Review your own diff before requesting review.
- **Never run `git push` without explicit user instruction.** Completing a task, finishing QA, or closing a workflow run does not authorize a push. Wait for the user to say so.

## Interaction Preferences

- Concise, but detailed in architectural justifications.
- Correct mistakes directly without apologizing.
- **No Ninja Edits.** Summarize proposed changes and get agreement before modifying files.

<!-- open-orchestra:start block-id="runtime-bootstrap" generator="open-orchestra runtime bootstrap" version="2" target="claude" source-manifest="open-orchestra command-manifest,runtime-bootstrap" content-sha256="b140b319d7f05229738feaead4458c2ed73951c986f5b538504fd3a53ac0ca14" updated-at="2026-07-07T17:39:53.158Z" -->
# Open Orchestra Runtime Bootstrap

Runtime target: Claude. Reference compact Open Orchestra blocks from CLAUDE.md and load task skills on demand.

## Non-Negotiable Runtime Rules

These rules are non-negotiable. Follow them in every conversation and every work block:

- Use Orchestra for all project work: planning, implementation, fixes, reviews, QA, release, CI, research, and documentation.
- Do not edit files, run implementation work, or dispatch agents before a matching Orchestra task exists and a workflow run is active.
- Always run the runtime health preflight, inspect active tasks, and validate pre-run context before work.
- If a gate is paused, stop and wait for explicit user approval before continuing.
- Record real evidence: commands, files, outputs, logs, screenshots, traces, or explicit deferred-risk rationale.
- Never treat simulated handoffs, generated summaries, or workflow state alone as proof of completed QA.
- Never push, tag, publish, or deploy without explicit user instruction.

Use Open Orchestra as the local control plane when `.agent-workflow/` exists.
The active LLM runtime is the parent agent. Orchestra renders spawn requests and records lifecycle; it does not call provider APIs directly.

## Orchestra Workflow — Required for All Work

Every piece of work — feature, bug fix, architecture decision, stack definition, PO refinement, or research spike —
MUST go through the Orchestra workflow. Do not start any work without a registered task and a running workflow.

### Managed Work Routing for External Runtimes

External runtimes and provider-backed agents — including Claude, Codex, Cursor, VS Code, Windsurf, OpenCode, and generic LLM runners — must infer managed work intent from natural language.
When the user asks to implement, fix, review, release, deploy, plan, research, investigate, spike, groom, estimate, validate, QA, or document work in a project with `.agent-workflow/`, route the request through Orchestra instead of executing ad hoc.
The required routing sequence is:
1. Load workspace state with `orchestra health --json` and `orchestra task list --json --status pending,blocked,in_progress`.
2. Reuse the matching active task when one exists; otherwise create or refine a task with `orchestra task add` before doing implementation, research, or provider calls.
3. Record the estimate and run `orchestra validate --pre-run --task <ID> --json`; if context is missing, resume or register the workflow before editing files.
4. Start or resume the workflow with `orchestra workflow run --task <ID> --gates phase` or `orchestra workflow run --task <ID> --resume <run-id>`.
5. If acceptance criteria, sizing, or gate approval is missing, stop and record clarification/review instead of bypassing the workflow.
This hardening is for external runtimes. The local provider/backbone path may stay tightly coupled to Orchestra internals, but it must not be used as a precedent for Claude, Codex, Cursor, VS Code, Windsurf, OpenCode, or generic provider behavior.

### Step 1 — Register the task
```
orchestra task add --id <ID> --title "<title>" --owner <role> --paths "<files>" --goal "<goal>"
```
Use the correct owner role for the type of work:
- Architecture / stack decisions → `architect`
- Product strategy / roadmap → `product_manager`
- Backlog refinement / acceptance criteria → `product_owner`
- Implementation → `developer`
- Verification / QA → `qa`
- Release / deploy → `release_manager`

### Step 2 — Declare effort baseline
```
orchestra estimate --task <ID> --sizing <xs|s|m|l|xl> --solo-days <N> --ai-unguided-days <N> --ai-guided-days <N>
```
Do not run `orchestra workflow run` until this estimate is recorded; an unestimated task signals incomplete planning.

### Step 3 — Run the autonomous workflow
```
orchestra workflow run --task <ID> --gates phase
```
The workflow sequences PM → PO → Architect → Developer → QA → Release.
Execution mode is selected from sizing when no explicit `--phase-execution` is provided:
- `xs` (1 point): `single-agent` so all phases run inline without spawn overhead.
- `s` (2–3 points): `single-agent` by default; use `subagents` when the work is separable.
- `m`, `l`, `xl`: `subagents` so phase work is isolated and reviewable.
For xs/s tasks, prefer `orchestra workflow run --task <ID> --gates phase --phase-execution single-agent` when you need to be explicit. The parent agent still produces handoffs, evidence, and reviews for every phase.
The agent (Claude Code) is responsible for executing every phase in sequence — acting as PM, then PO, then Architect, then Developer, then QA, then Release — before marking work complete.
Never pass `--from-phase`, `--skip-phases`, or any phase-shortcut flag. If a phase seems irrelevant, record a bypass rationale with `orchestra validate --pre-run --task <ID> --bypass --bypass-rationale "..."` instead.
Gates pause at `po→architect` and `qa→release` for human review.
The architect phase requires a sizing decision before proceeding:
```
orchestra decision add --task <ID> --owner architect --title "Story sizing" \
  --decision "<xs|s|m|l|xl> [N points]" --context "..." --consequences "..." --status accepted
```

### Step 4 — Collaborate through the phases
Each phase routes work to the right role. Pass your comments, requirements, or context via:
- `orchestra decision add` — architecture decisions, stack choices, accepted trade-offs
- `orchestra review` — review findings from any role
- `orchestra workflow clarify` — blocking questions from developer/QA to PO or architect
- `orchestra evidence add` — artifacts, commands run, test results

### Step 5 — Resume after gates
```
orchestra workflow run --task <ID> --resume <run-id>
```
At a `po→architect` or `qa→release` gate, stop work, surface the handoff artifact to the user, and wait for explicit approval before resuming — do not self-approve or continue autonomously.
Gate approval is not automatic. Before approving `po→architect`, verify the GitHub issue or Orchestra task has user-validated acceptance criteria, non-goals, assumptions, priority, and sizing context.
Before approving `qa→release`, verify real implementation evidence exists: changed files, exact validation commands, test results, QA findings, BA/PO acceptance, and Architect review when technical contracts changed.
If a generated handoff says `Acceptance Criteria: none`, treat it as incomplete. Pull criteria from the linked issue/task, record a review finding, and do not approve release until the gap is fixed or explicitly risk-accepted.

### Step 6 — Benchmark after completion
```
orchestra benchmark --task <ID>
```
A task is not complete until `orchestra benchmark` has run. Do not close the task or mark it done beforehand.

## Active Work
- At session start, run `orchestra health --runtime claude-cli --json` before implementation or file edits.
- Run `orchestra task list --json --status pending,blocked,in_progress` and identify resumable work before creating a new task.
- For the active task, run context, delegation, plan, skills, protocol, and workflow render commands.
- Run `orchestra validate --pre-run --task <ID> --json` before implementation; resolve missing estimate, workflow run, evidence, or review checks.
- Loading or estimating a task is not enough. If validation reports `workflowRun` missing, run `orchestra workflow run --task <ID> --gates phase` or resume the existing run before implementation, handoff, QA, or release work.
- If a user accepts a smaller/advisory path, record it with `orchestra validate --pre-run --task <ID> --bypass --bypass-rationale "..."`.
- After `orchestra workflow run` completes a phase or reports a pending action, immediately run `orchestra runtime parent-actions --task <ID> --json` and dispatch any actionable `claude-agent-request` items before continuing.
- Claude recurring preflight: after each phase completes, after a subagent returns, and after any context compaction or session resume, rerun `orchestra health --runtime claude-cli --json` and `orchestra validate --pre-run --task <ID> --json` before continuing.
- Treat a non-empty `missingActiveContext` or missing workflow run as a signal to re-register or resume the workflow before editing files.

## Runtime-Native Background Spawn
- When a workflow phase returns `completionMode=detached`, keep the parent conversation available and do not block on the child unless the user explicitly asks to wait.
- After `orchestra workflow run` reports a pending parent runtime action, immediately inspect `orchestra runtime parent-actions --task <ID> --json` and consume safe actions supported by the active runtime.
- Do not auto-consume actions when the user explicitly asked to pause, when the action is queued, or when the runtime/tool is unavailable or unsafe.
- Use `orchestra runtime spawn-request --task <ID> --role <role> --phase <phase> --run-id <run-id>` to render the assignment packet.
- Record child state with `orchestra runtime spawn-lifecycle --session <session-id> --status <spawned|active|completed|failed> --agent-id <id>`.
- Resume the workflow after the child completes with `orchestra workflow run --task <ID> --resume <run-id>`.
- Claude Code parent runtimes should launch the rendered packet with the native Agent/Subagent tool; use Task only when that is the exposed legacy alias.
- Prefer a role-named Claude subagent and record the resulting id or label in spawn lifecycle.

### Claude Subagent Delegation — Exact Sequence

When the user asks to delegate, or a workflow phase requires a subagent, follow this sequence without skipping steps:

1. `orchestra workflow run --task <ID> --gates phase` — generates the spawn packet and session id.
2. `orchestra runtime parent-actions --task <ID> --json` — inspect pending `claude-agent-request` actions.
3. Read the `payload.promptArtifact` file from the action — this is the subagent prompt.
4. Launch a subagent using the native **Agent** tool with the prompt artifact content as the prompt.
5. `orchestra runtime spawn-lifecycle --session <sessionId> --status spawned --agent-id <label>` — record the child.
6. After the subagent writes its handoff artifact, run: `orchestra runtime parent-actions --task <ID> --dispatch --runtime claude-cli --until-idle` — this auto-detects completion and promotes queued sessions.
7. `orchestra workflow run --task <ID> --resume <run-id>` — advance the workflow to the next phase.

**Never skip step 1.** The session id, spawn packet, and expected handoff path come from `orchestra workflow run`. Do not invent child context or launch subagents with ad-hoc prompts outside this sequence.
After the developer subagent completes, run `orchestra workflow run --task <ID> --resume <run-id>` to drive the QA phase; do not mark work done until QA evidence is recorded and the `qa→release` gate has been surfaced to the user.

## Task Loop
- `orchestra health` - Check local tools and workflow readiness. With --runtime, persists the active runtime to .agent-workflow/active-runtime.json so subsequent commands know who the parent is.
- `orchestra task list` - List local workflow tasks. Workflow phase subtasks are hidden by default.
- `orchestra delegation decide --task <id>` - Decide whether to delegate.
- `orchestra skills plan --task <id>` - Select task-scoped skills.
- `orchestra skills render --target <generic|claude|cursor|codex|vscode|windsurf>` - Render skills for a runtime.
- `orchestra protocol render` - Render subagent protocol.
- `orchestra workflow render --task <id>` - Render workflow templates.
- `orchestra summary` - Summarize workspace state.
- `orchestra context --task <id>` - Read task context bundle.
- `orchestra plan --task <id>` - Render role execution plan.
- `orchestra gate --gate <architecture> --task <id>` - Evaluate workflow gate.
- `orchestra review --task <id> --role <role> --result <approve|block|changes> --findings <text> --recommendation <text>` - Record reviewer outcome.
- `orchestra evidence add --task <id> --role <role> --type <command|file|screenshot|trace|video|log|report> --summary <text>` - Record delivery evidence.

## Completion
- Run the project validation gate.
- Record command/file/browser evidence with `orchestra evidence add`.
- Record review outcome with `orchestra review`.
- Update task status only after evidence and review are present.
- **Never run `git push` without explicit user instruction.** Completing a task, finishing QA, or closing a workflow run does not authorize a push.

## Command Discovery
- Use `orchestra commands manifest --json` for command metadata.
- Use `orchestra --help` for human-readable help.
<!-- open-orchestra:end block-id="runtime-bootstrap" -->
