[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M72S6MGPM5H79FWQED562TA0":3,"skill-same:01M72S6MGPM5H79FWQED562TA0":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":14,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":46},"01M72S6MGPM5H79FWQED562TA0","orchestrate",null,"End-to-end orchestrator for quantum-vault. Takes a Linear ticket OR a PR branch and runs the entire workflow: context gathering, implementation across files with parallel agents, build\u002Freview\u002Ffix loop, smart test generation, commit and draft PR creation. Also supports exhaustive PR review mode with a review agent per quality dimension.","p-11\u002Fquantum-vault","p-11","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F187643446?v=4","01M72S62G38VYPMH9WSPQHE8MA","Project Eleven","01M72S62H61Y0MHGKSG7JTBZ1D",3,"MIT","https:\u002F\u002Fgithub.com\u002Fp-11\u002Fquantum-vault\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Forchestrate\u002FSKILL.md",[],[],"2026-11-10 22:39:42",false,"---\nname: orchestrate\ndescription: >-\n  End-to-end orchestrator for quantum-vault. Takes a Linear ticket OR a PR branch and runs the\n  entire workflow: context gathering, implementation across files with parallel agents,\n  build\u002Freview\u002Ffix loop, smart test generation, commit and draft PR creation. Also supports\n  exhaustive PR review mode with a review agent per quality dimension.\nargument-hint: '[ticket-id or PR branch\u002FURL] [--review] [--auto]'\ndisable-model-invocation: true\n---\n\n# Orchestrator: End-to-End Workflow\n\nTwo operating modes:\n\n## Mode A - Feature Delivery (default)\n\nTakes a Linear ticket ID and handles the entire pipeline:\n\n1. Fetch and understand the ticket\n2. Parallel context gathering across `src\u002F`, shared utilities, and `libqc` sibling SDK\n3. Create the git branch\n4. Plan implementation with parallelization strategy\n5. Implement across files with maximum parallelism\n6. Orchestrator review + integration pass\n7. Build\u002Freview\u002Ffix loop until clean\n8. Smart test generation (unit + E2E where applicable)\n9. Commit\n10. Ask user for permission to push and create the draft PR\n\n## Mode B - PR Review (`--review`)\n\nTakes a PR branch name or URL and performs an exhaustive audit:\n\n1. Fetch commits, diff, changed files\n2. Spawn parallel review agents across every quality dimension\n3. Report findings with `file:line` references and fix suggestions\n4. Optionally auto-fix and re-validate\n\n---\n\n## Architecture: Opus Orchestrator + Opus Reasoning Agents\n\nUse as many parallel agents as needed. There is no artificial cap on concurrency - spawn agents aggressively for independent work streams. The goal is perfection at maximum speed. The user has unlimited resources; **default to Opus 4.6 for every agent whose work requires reasoning, judgment, bug hunting, or test design**. Fall back to the default model only for purely mechanical operations.\n\n### Model Selection Rule\n\nPass `model: \"opus\"` (Claude Opus 4.6) to every agent in the following categories - these are the reasoning-heavy surfaces that benefit most from the stronger model:\n\n- **Exploration** (`subagent_type: \"Explore\"`) when the goal is to synthesize architectural context, trace data flow, or judge pattern fit. Reserve the default model only for \"find this exact string\" lookups.\n- **Planning** (`subagent_type: \"Plan\"`) - always Opus.\n- **Implementation agents** building anything non-trivial: new modules, provider wiring, libqc seam code, anything touching security\u002Flock\u002Ftimeout.\n- **Code review agents** (`code-reviewer`, Type Safety, Pattern Matching, Provider Architecture, Extension Security, Screen Navigation, Performance, Architecture) - always Opus.\n- **Test generation** (`test-writer`): what to test, where, how to guard against regressions - always Opus.\n- **Bug-finding \u002F investigation** (`investigator`): dependency tracing and judgment calls - always Opus.\n- **Refactoring** (`refactorer`): architectural judgment and safety-critical edits - always Opus.\n- **Styling review** (`styling`): token usage + design token decisions - always Opus.\n- **PR body writing** and **PR review synthesis** - orchestrator handles directly (already Opus).\n\nUse the default model only for:\n\n- Pure shell operations (git branch setup, stage + push commands)\n- Running a single quality-gate command and reporting PASS\u002FFAIL\n- Mechanical scaffolding where every line is already specified by the orchestrator (see `\u002Fdelegate`)\n\nWhen in doubt, choose Opus. The user explicitly wants reasoning quality over token cost.\n\n### How to spawn Opus agents\n\nWhen using the `Agent` tool, pass `model: \"opus\"` alongside `subagent_type` and `description`:\n\n```\nAgent({\n  description: \"Review extension security impact\",\n  subagent_type: \"code-reviewer\",\n  model: \"opus\",\n  prompt: \"...\"\n})\n```\n\nProject agents (`code-reviewer`, `investigator`, `refactorer`, `styling`, `test-writer`, `pr-preparer`) already declare `model: opus` in their frontmatter. The parent invocation should still pass `model: \"opus\"` explicitly to make the contract visible in the orchestrator log.\n\n```\n+---------------------------------------------------+\n|               ORCHESTRATOR (Opus)                  |\n|  Planning - Architecture - Judgment - Integration  |\n|  libqc API semantics - Sync - Final review         |\n+---+---------+---------+---------+---------+-------+\n    |         |         |         |         |\n +--v--+   +--v--+   +--v--+   +--v--+   +--v--+\n | A   |   | B   |   | C   |   | D   |   | ... |\n | fast|   | fast|   | fast|   | fast|   | fast|\n +-----+   +-----+   +-----+   +-----+   +-----+\n```\n\n### Orchestrator Responsibilities (never delegate)\n\n- **Planning**: decompose the ticket into work streams with dependencies\n- **Architecture decisions**: which patterns, where to put code, module boundaries\n- **libqc API semantics**: verify SDK field meanings and return shapes before any runtime logic\n- **Provider topology**: ordering, `LibQC` instance ownership, context usage\n- **Cross-cutting integration**: wire together outputs from multiple agents\n- **Final review**: read every file touched by agents, fix integration issues\n- **Security review**: vault lock\u002Funlock behavior, idle timeout, secret hygiene\n- **PR body writing**: requires understanding the full change\n\n### Delegable Work (still Opus by default)\n\nWith unlimited resources, lean Opus for anything involving judgment. Delegation is about parallelism, not about cost minimization:\n\n- **Architectural exploration** (Opus): synthesizing patterns, tracing data flow, judging pattern fit\n- **Component implementation** (Opus): building UI from a precise spec - even \"clear\" specs hit type-safety edges\n- **Hook scaffolding** (Opus): React Query composition, boundary handling, assert hooks\n- **Test generation** (Opus via `test-writer`): deciding coverage, regression guards, selector stability\n- **PR review dimensions** (Opus): type safety, pattern matching, provider architecture, security, performance - one Opus agent per dimension for maximum parallelism\n- **Refactor passes** (Opus via `refactorer`): safety-critical changes preserving provider\u002Fnavigation\u002Fsecurity invariants\n\n### Truly Mechanical Work (default model OK)\n\n- **Exact string lookups** in the codebase (one grep, no synthesis needed)\n- **Pure shell operations**: `git checkout`, `git add`, `git push`\n- **Running a single quality-gate command** and reporting PASS\u002FFAIL verbatim\n- **Screen registry wiring** when the exact lines to add are already specified\n\n### Worker Coordination Protocol\n\n1. **File isolation** - each agent owns distinct files. Never two agents on the same file.\n2. **Cross-agent synthesis** - when Agent A produces output Agent B needs, the orchestrator reads A's deliverables and feeds them into B's prompt. Workers never talk directly - the orchestrator is the routing layer.\n3. **Quality gates with push-back** - no agent's work is marked done until deliverables are reviewed. Bad output goes back with specific fix instructions.\n4. **Stall detection** - if an agent keeps failing after 2 attempts, reassess: provide specific unblocking instructions, simplify the task, or take it over directly.\n5. **Convergence collapse** - when parallel agents produce overlapping concerns (shared types, cross-module imports), collapse remaining work to sequential. Parallel is for independent work; the moment dependencies emerge, go sequential.\n\n---\n\n## Repo Paths\n\n| Repo          | Location (relative to quantum-vault repo root) | Default branch | Role                              |\n| ------------- | ---------------------------------------------- | -------------- | --------------------------------- |\n| quantum-vault | `.` (this repo)                                | `main`         | Chrome Extension (MV3)            |\n| libqc         | `..\u002Flibqc` (sibling checkout)                  | `main`         | Published SDK (pinned in package) |\n\n`quantum-vault` consumes `@project-eleven\u002Flibqc` as a pinned published package (see `package.json`); the sibling `libqc` checkout is required for source-level verification and coordinated SDK changes. Breaking changes to the SDK's public surface require a new release and a matching pin bump, plus validation of extension imports and runtime flows.\n\n## Package Manager + Commands\n\n`pnpm` only (pinned to `pnpm@10.20.0`). Never use `yarn` or `npm`.\n\n| Task                 | Command                                  |\n| -------------------- | ---------------------------------------- |\n| Install deps         | `pnpm install`                           |\n| Dev server           | `pnpm dev`                               |\n| Dev build            | `pnpm build:dev`                         |\n| Lint check           | `pnpm l:c`                               |\n| Lint fix             | `pnpm l:f`                               |\n| Prettier check       | `pnpm p:c`                               |\n| Prettier write       | `pnpm p:f`                               |\n| Unit tests           | `pnpm test:unit`                         |\n| E2E parse check      | `pnpm test:e2e:check`                    |\n| E2E run (local)      | `pnpm exec playwright test`              |\n| Full CI gate         | `pnpm ci:pr`                             |\n\n`pnpm ci:pr` runs lint check, prettier check, unit tests, dev build, E2E parse check, and the `dep-doc` audit in sequence. Use it as the final pre-PR gate.\n\n---\n\n# Mode A: Feature Delivery\n\n## Step 1: Fetch Ticket + Parallel Context Gathering\n\n### 1a: Fetch ticket (orchestrator)\n\n```\nLinear MCP: get_issue({ id: \"\u003CTICKET-ID>\", includeRelations: true })\n```\n\nExtract: title, description, acceptance criteria, `gitBranchName`, blockers, Figma URLs, libqc dependencies, extension-runtime concerns.\n\n### 1b: Parallel context exploration\n\nWhile the orchestrator analyzes the ticket, spawn parallel Explore agents:\n\n- Agent A: search `src\u002F` for related feature modules, screens, providers, hooks, shared utilities. Return file paths, existing patterns, reusable primitives.\n- Agent B: search `libqc\u002Fsrc\u002F` for SDK functions, types, resolvers, storage interfaces relevant to the feature. Return public API signatures and chain-dispatch points.\n- Agent C: search `__tests__\u002Fe2e\u002F` for existing test selectors and flows that touch the same surface. Return fixture data and selector patterns at risk.\n- Agent D+: any additional context gathering (design refs, CLAUDE.md reference docs, prior PRs touching the same module).\n\nAdd more Explore agents as needed - there is no cap on context gathering.\n\n### 1c: Fetch design (orchestrator, if Figma URL present)\n\nExtract `fileKey` and `nodeId`. Map Figma variables to Tailwind v4 CSS-first tokens from `src\u002Findex.css` and existing `src\u002Fcomponents\u002Fui\u002F` primitives. Never implement UI without actually retrieving the design via MCP.\n\n### 1d: Synthesize (orchestrator)\n\nRead all agent outputs. Produce a unified context document:\n\n```markdown\n## Existing Codebase Context\n- Relevant screens\u002Fproviders: [paths]\n- Relevant hooks\u002Futilities: [paths]\n- Reusable components: [paths]\n- libqc surface touched: [exported functions + types]\n- Design tokens needed: [from Figma]\n- Reference implementations: [best example files]\n- E2E coverage at risk: [test files + selectors]\n- Constraints: [blockers, missing libqc exports, CSP implications]\n```\n\n---\n\n## Step 2: Git Branch Setup\n\nRun from repo root:\n\n```bash\ngit checkout main && git pull\ngit checkout -b {gitBranchName-from-linear}\n```\n\nIf the branch already exists: `git checkout {branch} && git rebase origin\u002Fmain`.\n\nAlways use the exact `gitBranchName` from Linear - do not modify it.\n\n---\n\n## Step 3: Plan Implementation\n\nSynthesize the ticket, design, and exploration context into a plan. Present to the user unless `--auto`.\n\n### Plan Template\n\n```markdown\n## Implementation Plan for \u003CTICKET-ID>: \u003Ctitle>\n\n### Work Streams\n\n#### Stream 1: \u003Cname> [owner: fast-agent | orchestrator]\n- Files: [exact paths to create or modify]\n- Depends on: [other streams, or \"none\"]\n- Description: [what to implement]\n- Parallelizable with: [other stream names]\n\n#### Stream 2: ...\n\n### Execution Order\n1. [Streams A + B + C] - parallel (no shared files)\n2. [Stream D] - sequential (needs A output types)\n3. [Integration] - orchestrator assembles everything\n\n### Agent Allocation\n| Stream | Owner        | Reason                              |\n| ------ | ------------ | ----------------------------------- |\n| ...    | fast-agent   | Mechanical: clear contract, one file|\n| ...    | orchestrator | Needs judgment on libqc semantics   |\n```\n\n### Work Stream Decomposition Rules\n\n1. **File isolation** - each agent owns distinct files\n2. **Clear contracts** - each agent gets exact input types, output types, file paths\n3. **No ambiguity** - full code for patterns, exact class names, exact imports\n4. **Dependency ordering** - agents producing types must complete before consumers start\n\n---\n\n## Step 4: Parallel Implementation\n\nExecute the plan with parallel agents. The orchestrator monitors, validates, and integrates.\n\n### Parallelization Patterns\n\n**Pattern A: UI + Data Layer Parallel**\n\n```\nPHASE 1 - Parallel scaffolding\n├── Agent A: core.ts + types.ts for the feature module\n├── Agent B: data\u002Fhooks.ts + data\u002Fmappers\u002F\n├── Agent C: UI components (one per file, from design spec)\n└── Agent Explore: verify pattern consistency with existing modules\n\nPHASE 2 - Orchestrator integration\n├── Read all agent output\n├── Verify libqc API semantics (NEVER delegate)\n├── Wire components together, fix cross-cutting issues\n└── Register in screen registry + provider tree if needed\n\nPHASE 3 - Parallel completion\n├── Agent: unit tests for pure logic\n├── Agent: E2E impact check\n└── Orchestrator: final review pass\n```\n\n**Pattern B: Multi-Component Feature**\n\n```\nPHASE 1 - Parallel build (one agent per independent file)\n├── Agent A: components\u002Ffeature\u002Fpart-a.tsx\n├── Agent B: components\u002Ffeature\u002Fpart-b.tsx\n├── Agent C: hooks\u002Fuse-feature.ts\n└── Agent D: providers\u002Ffeature-provider.tsx (if needed)\n\nPHASE 2 - Orchestrator assembly\n├── Compose parts into parent screen\n├── Wire screen into registry\n└── Verify type flow end-to-end\n```\n\n**Pattern C: Sequential Core + Parallel Polish**\n\n```\nPHASE 1 - Orchestrator implements core logic (tight dependencies)\nPHASE 2 - Parallel completion\n├── Agent: styling\u002Ftokens pass\n├── Agent: quality gates\n└── Agent: test scaffolding\n```\n\n### Spawning Fast Agents\n\n**UI implementation agent prompt template:**\n\n```\nYou are implementing a component for quantum-vault (Chrome Extension MV3).\n\nPROJECT: React 19 + Vite + TypeScript, Tailwind v4 CSS-first + shadcn\u002Fui, libqc SDK\nFILE: {exact path to create or modify}\n\n## Existing Code (reference)\n{paste relevant existing patterns, types, imports, design tokens}\n\n## What to Build\n{exact spec: imports, types, component structure, exports}\n\n## Rules (MUST follow - see .claude\u002Frules\u002F and CLAUDE.md)\n- `type` not `interface` (interface only for class contracts)\n- No `useMemo` or `useCallback` (React Compiler handles memoization)\n- No `as` assertions - use type narrowing, discriminated unions, `ensurePresent()`\n- No `?.` \u002F `??` on non-optional types - trust the type system\n- No `switch\u002Fcase` - use `Record\u003CKey, Value>`, `match()`, `\u003CMatch>`, config arrays\n- Never hardcode hex colors in feature components - use tokens from src\u002Findex.css\n- Use `cn()` for class merging\n- One component per file, feature-based organization (no generic `components\u002F`)\n- core.ts for runtime values + derived types, types.ts for pure types only\n- Object params for functions with >1 arg\n- Colocate state with consumers - no prop drilling\n\n## Pattern to Follow\n{paste a real example from the codebase}\n```\n\n**Shared utility or hook agent prompt template:**\n\n```\nYou are implementing a pure utility\u002Fhook for quantum-vault.\n\nFILE: {exact path}\nPROJECT: TypeScript strict mode\n\n## Existing Code (reference)\n{paste relevant patterns from src\u002Flib\u002F or src\u002Fhooks\u002F}\n\n## What to Build\n{exact spec with signatures, examples, error handling}\n\n## Rules\n- `attempt()` over try-catch (only when user-facing error needed)\n- `ensurePresent()` at runtime boundaries\n- No side effects in mappers\n- Pure functions for data transformation\n- Derive types from const arrays (source of truth)\n- Check shared utilities before creating new helpers\n\n## Pattern to Follow\n{paste a real example}\n```\n\n---\n\n## Step 5: Orchestrator Review + Integration\n\nNever skip this step. After all agents complete:\n\n### 5a: Read every file touched by agents\n\nCheck for:\n\n- Correct imports and type references across files\n- Consistent naming between layers (`core.ts` ↔ types.ts ↔ consumers)\n- No `as` assertions, no `useMemo`\u002F`useCallback`\n- Provider order preserved (CurrencyProvider -> WalletProvider -> ScreenProvider)\n- `LibQC` instantiated only in `WalletProvider` (never in screens)\n- No hardcoded colors outside `src\u002Findex.css`\n- libqc API field semantics correct (verify against SDK source)\n- Timeout\u002Flock behavior still consistent for new authenticated screens\n- No sensitive data logged (mnemonic, password, private key)\n\n### 5b: Cross-agent integration\n\n1. Verify type flow: libqc types -> mappers -> hooks -> component props\n2. Verify screen wiring connects to the registry in `src\u002Fscreens.tsx`\n3. Verify provider integration (e.g., refresh list in `ScreenProvider` if balance-sensitive)\n4. Fix import paths, naming mismatches, missing type exports\n\n### 5c: Fix issues directly\n\nMake edits to resolve integration issues. Only re-delegate if the fix is large and mechanical.\n\n---\n\n## Step 6: Build\u002FReview\u002FFix Loop\n\nThis is a persistent loop. Do NOT stop until ALL gates pass.\n\n```\nwhile true:\n  1. pnpm l:c                -> fix errors (pnpm l:f for auto-fixable)\n  2. pnpm p:c                -> pnpm p:f to format\n  3. pnpm test:unit          -> fix logic, not assertions (unless assertion is wrong)\n  4. pnpm test:e2e:check     -> verify E2E tests still parse (selector stability)\n  5. pnpm build:dev          -> catch Vite\u002FTS build-only issues\n  6. If any fail -> read output, fix, go to 1\n  7. All pass -> break\n```\n\nCommon fixes:\n\n- ESLint unused import -> remove or switch to `import type`\n- ESLint suggests import sort -> `pnpm l:f`\n- TypeScript error -> fix at source. Never `as` cast. Add `ensurePresent()` at boundaries.\n- Prettier whitespace -> `pnpm p:f`\n- Unit test fails -> fix the code. Only edit the test when the spec actually changed.\n- E2E selector broken -> either restore the selector or update `__tests__\u002Fe2e\u002F*.test.ts` in the same PR.\n\n### Stall Detection\n\nIf the same error keeps failing after 2 iterations:\n\n1. Re-read the error carefully. Real issue or pre-existing?\n2. Try a different fix approach.\n3. If still stuck after 2 attempts, stop and surface the specific error to the user.\n\n---\n\n## Step 7: Smart Test Generation\n\nAfter quality checks pass, evaluate what tests are needed.\n\n### 7a: Evaluate (orchestrator)\n\n| What was built                           | Test type                                                   |\n| ---------------------------------------- | ----------------------------------------------------------- |\n| Pure utility or mapper                   | Unit test (Vitest) in `__tests__\u002F` colocated with source    |\n| Hook with state                          | Hook integration test (Vitest + `renderHook`)               |\n| Component with interaction               | Component integration test (Vitest + Testing Library)       |\n| New user-facing screen or critical flow  | E2E test (Playwright) in `__tests__\u002Fe2e\u002F`                   |\n| libqc integration seam logic             | Unit test against a mocked `LibQC` instance                 |\n| Config\u002Ftypes\u002Fbarrel only                 | Skip - no tests needed                                      |\n\n### 7b: Generate tests (parallel agents, one per test type)\n\n```\nUnit Test Agent    -> Vitest unit tests for pure logic. Arrange-Act-Assert.\n                      Edge cases: empty, zero, BigNumber boundaries, error paths.\nIntegration Agent  -> Testing Library component tests with user events.\n                      Assert on visible text\u002Froles, not implementation details.\nE2E Agent          -> Playwright in __tests__\u002Fe2e\u002F*.test.ts.\n                      Follow existing patterns; keep selectors\u002Ftest-ids stable.\n                      Mock chain RPC reads when feasible (see existing test scaffolding).\n```\n\n### 7c: Run + fix\n\n```bash\npnpm test:unit        # fix failures - fix the code, not the test unless spec changed\npnpm test:e2e:check   # parse-check all E2E files compile and register\n# Full E2E only when the flow is touched:\npnpm exec playwright test __tests__\u002Fe2e\u002F\u003Cfile>.test.ts\n```\n\nRepeat until all gates pass.\n\n---\n\n## Step 8: Commit\n\nRun the full gate before any commit:\n\n```bash\npnpm ci:pr   # or at minimum: pnpm l:c && pnpm p:c && pnpm test:unit && pnpm build:dev\n```\n\nStage specific files - never `git add .` or `git add -A`:\n\n```bash\ngit add \u003Cspecific-files>\ngit commit -m \"$(cat \u003C\u003C'EOF'\nfeat(scope): imperative description\n\n- Detail 1\n- Detail 2\n- Closes P11-1234\nEOF\n)\"\n```\n\nConventional commits. No `Co-Authored-By` trailer.\n\n---\n\n## Step 9: Ask User Before Pushing + Creating PR\n\nSTOP and ask before pushing or creating the PR. Present a summary:\n\n```markdown\n## Ready to push\n\n### Changes\n- {summary of files changed}\n- {summary of what was implemented}\n\n### Branch\n- `{gitBranchName}` in quantum-vault ({N} files changed)\n\n### Quality gates\n- `pnpm l:c` - pass\n- `pnpm p:c` - pass\n- `pnpm test:unit` - pass\n- `pnpm test:e2e:check` - pass\n- `pnpm build:dev` - pass\n\nShall I push and create a draft PR?\n```\n\nOnly proceed after explicit user confirmation.\n\n---\n\n## Step 10: Push + Draft PR\n\nAfter user confirms, push and create the PR as a draft:\n\n```bash\ngit push -u origin {branch}\ngh pr create --draft \\\n  --title \"feat(scope): description (P11-1234)\" \\\n  --body \"$(cat \u003C\u003C'EOF'\n## Summary\n- What this PR does and why\n\n## Test Plan\n- [ ] `pnpm l:c` passes\n- [ ] `pnpm p:c` passes\n- [ ] `pnpm test:unit` passes\n- [ ] `pnpm test:e2e:check` passes\n- [ ] `pnpm build:dev` passes\n- [ ] Extension loads unpacked from `build\u002F`\n- [ ] Lock\u002Funlock + idle timeout verified for any authenticated screen touched\n\n## Related\n- Closes P11-1234\nEOF\n)\"\n```\n\n### Before every `git push` + `gh pr create`\n\n1. `git remote -v` and confirm the remote org\n2. `gh auth status` and confirm the active account is authorized for the `p-11` GitHub org\n3. Verify `git config user.name` and `user.email` match the expected identity for this folder\n\nIf any check fails, stop and surface the mismatch to the user.\n\n---\n\n## Linear Ticket Status\n\nThe GitHub-Linear integration handles status transitions automatically:\n\n| GitHub PR event                   | Linear status change       |\n| --------------------------------- | -------------------------- |\n| PR created as draft               | no change                  |\n| PR moved from draft -> ready      | -> In Review \u002F In Progress |\n| PR merged                         | -> Done                    |\n\n- Always include `Closes P11-XXXX` in the PR body (links to the Linear ticket)\n- Always include `(P11-XXXX)` in the PR title\n- Do not call `save_issue` to change `state`\n- Do not call `save_comment` just to post the PR link\n\nOnly post a Linear comment when there is meaningful context beyond the PR link (implementation decisions, open questions, deferred scope).\n\n---\n\n# Mode B: PR Review\n\n## Stage 1: Gather PR Context (parallel)\n\n- Agent A (shell): `git fetch origin && git log --oneline origin\u002Fmain..HEAD`, `git diff --stat origin\u002Fmain..HEAD`, full diff. Report commits + changed files.\n- Agent B (explore): categorize touched domains (screens, providers, hooks, data, styling, libqc seam, tests). For each, list the relevant rules from `.claude\u002Frules\u002F`.\n\n## Stage 2: Deep Review (parallel, one agent per dimension)\n\nSpawn a review agent for EACH quality dimension across ALL changed files:\n\n### Type Safety Agent\nCheck for:\n- `as` assertions (forbidden - use type narrowing or discriminated unions)\n- Unnecessary `?.` on non-optional properties\n- `?? ''` or `?? 0` fallbacks on non-optional values\n- `any` types (use `unknown` + narrow)\n- Missing `ensurePresent()` at boundary lookups\n- `interface` for data shapes (should be `type`)\n- Derived union types from const arrays (single source of truth)\n- `core.ts` vs `types.ts` split respected\n\n### Pattern Matching Agent\nCheck for:\n- `switch\u002Fcase` (forbidden - use Record lookups, `match()`, `\u003CMatch>`, config arrays)\n- Nested ternaries (>=2 levels - extract to `match()` \u002F `\u003CMatch>`)\n- Manual `if (isLoading)` instead of `\u003CMatchQuery>`\n- Non-exhaustive record lookups (should `Record\u003CVariant, V>` not `Partial\u003C...>` unless intentional)\n\n### React Patterns Agent\nCheck for:\n- `useMemo`\u002F`useCallback` (forbidden - React Compiler)\n- Multiple components per file (one per file, small helpers \u003C 10 lines excepted)\n- Prop drilling where hook-based autonomy would be clearer\n- Domain components receiving domain data as props (should use hooks directly)\n- Conditional hook calls (use guard components instead)\n\n### Provider Architecture Agent\nCheck for:\n- Provider order changes (CurrencyProvider -> WalletProvider -> ScreenProvider)\n- `LibQC` instantiated outside `WalletProvider`\n- Deep imports into libqc internals from app code\n- Missing paired `useX` hook that throws outside provider context\n- Data fetching inside a provider (providers distribute state, hooks fetch)\n\n### Extension Security Agent\nCheck for:\n- New authenticated screens not added to `AUTHENTICATED_SCREENS` in `useSessionTimeout`\n- Lock flow not clearing wallet in-memory state\n- CSP drift in `manifest.json`\n- `console.log` with sensitive data (mnemonic, password, private key, raw vault)\n- `.env*` files committed or referenced\n- Missing `VITE_*` prefix for new env variables\n\n### Screen Navigation Agent\nCheck for:\n- Imperative navigation that bypasses `ScreenProvider` hydration\n- New screen not registered in `src\u002Fscreens.tsx`\n- Missing `ScreenKey` usage (raw strings instead of registry keys)\n- Balance-sensitive screen added without updating refresh list\n\n### Styling Agent\nCheck for:\n- Hardcoded hex colors outside `src\u002Findex.css`\n- Inline font-size\u002Fweight instead of typography tokens\n- `!important` overrides (fix specificity)\n- Mixing ad-hoc styled components with shadcn primitives\n- Popup shell width deviating from ~400px baseline\n\n### Performance Agent\nCheck for:\n- State not colocated with consumers (re-render blast radius)\n- O(n^2) operations where O(n) works\n- Redundant state that could be derived\n- Unnecessary re-renders from parent prop changes\n- Missing key-based remount when needed\n\n### Code Quality Agent\nCheck for:\n- Magic numbers\u002Fstrings not extracted to named constants\n- DRY violations (same value\u002Flogic repeated 2+ times)\n- Missing `attempt()` where user-facing errors are handled\n- Shared utilities not reused (local helper duplicates something in `src\u002Flib\u002F`)\n- Boolean params at call sites that should be object params or split functions\n- `console.log` in production paths\n- Commented-out code committed\n\n### Architecture Agent\nCheck for:\n- Generic `components\u002F` folder at feature level (should be feature-based)\n- `hooks\u002F` folder at module level (should be `data\u002Fhooks.ts` or colocated)\n- Missing one-component-per-file rule\n- `index.ts` barrel exports that re-export everything (import directly instead)\n- Cross-layer leakage (e.g., UI importing from API response types directly)\n\n### Test Impact Agent\nCheck for:\n- `data-testid` changes that break existing E2E tests\n- New user-facing flow without E2E coverage\n- Timing-sensitive assertions introduced to E2E\n- Unit tests that assert implementation instead of behavior\n\n## Stage 3: Synthesize + Report (orchestrator)\n\n1. Read every review agent's output\n2. Deduplicate (multiple agents may flag the same line)\n3. Prioritize: **critical** (breaks at runtime) > **important** (violates standards) > **nitpick** (style)\n4. Present a structured report:\n\n```markdown\n## PR Review: {branch-name}\n\n### Critical (must fix)\n- `src\u002Fpath\u002Ffile.tsx:42` - {issue} -> {fix}\n\n### Important (should fix)\n- `src\u002Fpath\u002Ffile.ts:15` - {issue} -> {fix}\n\n### Nitpick (consider)\n- `src\u002Fpath\u002Ffile.tsx:88` - {issue} -> {fix}\n\n### Summary\n- {X} critical, {Y} important, {Z} nitpick findings\n- Overall assessment: APPROVE | REQUEST CHANGES\n```\n\n5. If the user says \"fix\" or `--fix` was passed: auto-apply fixes, run `pnpm ci:pr`, re-validate.\n\n---\n\n# Agent Allocation Matrix\n\nDefault model is **Opus 4.6** unless the task is purely mechanical. The user has unlimited resources - choose Opus whenever reasoning, judgment, or bug-finding is involved.\n\n| Task                                  | Owner         | Model   | Why                                                  |\n| ------------------------------------- | ------------- | ------- | ---------------------------------------------------- |\n| Ticket analysis + scope detection     | orchestrator  | Opus    | Requires judgment                                    |\n| Codebase exploration (architectural)  | Explore agent | Opus    | Synthesize patterns, judge fit                       |\n| Codebase exploration (exact lookup)   | Explore agent | default | Pure search for a known string                       |\n| libqc API semantics verification      | orchestrator  | Opus    | Critical - errors cause silent bugs                  |\n| Provider topology decisions           | orchestrator  | Opus    | Must preserve ordering invariants                    |\n| Architecture + plan creation          | orchestrator  | Opus    | Judgment on module boundaries                        |\n| Component from clear spec             | agent         | Opus    | Even \"clear spec\" hits edge cases at implementation  |\n| Component with complex state          | orchestrator  | Opus    | Architectural judgment                               |\n| Hook scaffolding from spec            | agent         | Opus    | Type safety + boundary handling                      |\n| Screen registry wiring                | agent         | default | Mechanical file update                               |\n| Cross-component integration           | orchestrator  | Opus    | Multi-output assembly                                |\n| Quality gates (`pnpm ci:pr`)          | agent         | default | Command execution + error reporting                  |\n| Quality gate fixes                    | orchestrator  | Opus    | Requires understanding why it failed                 |\n| Test strategy + generation            | test-writer   | Opus    | Decide what to test, find regressions                |\n| Test failure diagnosis                | orchestrator  | Opus    | Root cause analysis                                  |\n| Git operations (branch, push)         | agent         | default | Mechanical commands                                  |\n| PR body writing                       | orchestrator  | Opus    | Full-change understanding                            |\n| PR review - type safety               | review agent  | Opus    | Judgment on narrowing and invariants                 |\n| PR review - pattern matching          | review agent  | Opus    | Spot exhaustive\u002Fnon-exhaustive dispatch              |\n| PR review - React patterns            | review agent  | Opus    | React Compiler compliance + autonomy judgment        |\n| PR review - provider architecture     | review agent  | Opus    | Provider order, `LibQC` singleton, guard boundaries  |\n| PR review - extension security        | review agent  | Opus    | Lock\u002Ftimeout\u002FCSP\u002Fsecret hygiene                      |\n| PR review - screen navigation         | review agent  | Opus    | Registry + hydration contracts                       |\n| PR review - styling                   | review agent  | Opus    | Token discipline + hardcode detection                |\n| PR review - performance               | review agent  | Opus    | Re-render blast radius, state colocation             |\n| PR review - code quality              | review agent  | Opus    | DRY + magic values + shared utility reuse            |\n| PR review - architecture              | review agent  | Opus    | Module layout + boundary leakage                     |\n| PR review - test impact               | review agent  | Opus    | Selector stability + flake risk                      |\n| PR review synthesis                   | orchestrator  | Opus    | Dedup, prioritize, assess                            |\n| Linear status updates                 | NEVER         | -       | GitHub-Linear integration handles this               |\n\n---\n\n# Synchronization Protocol\n\n### When agents finish\n\n1. **Read the full output** of every completed agent\n2. **Validate file isolation** - confirm no agent wrote to another agent's files\n3. **Check type flow** - libqc types -> mappers -> hook outputs -> component props\n4. **Resolve naming conflicts** - pick one canonical name, fix every reference\n5. **Merge integration points** - add imports that cross agents' files\n\n### Context handoff between sequential agents\n\n```\nTask prompt: \"...\n\n## Context from Previous Work\nFile `{path}` was created with this content:\n{paste the relevant code}\n\nYour task depends on the types above. Specifically:\n- Use type `{TypeName}` from `{import path}`\n- The hook returns `{describe shape}`\n...\"\n```\n\n### When to collapse parallel to sequential\n\n- Two agents need to modify the same file\n- Agent B's implementation depends on Agent A's output type\n- An agent's output reveals an architectural issue requiring replanning\n- libqc API semantics ambiguous and need investigation\n\n### Stall detection and recovery\n\n1. Read the agent's output - identify the specific failure\n2. Provide targeted fix instructions and re-delegate with more context\n3. If still failing after 2 attempts, take over directly\n4. Never let a stuck agent block the pipeline - route around it\n\n---\n\n# Decision Trees\n\n### Should I create a new feature module?\n\n- YES: own state\u002Fdata layer, used in multiple places, significant enough to isolate\n- NO: small component in an existing module, used in one place, UI-only change\n\n### Should this be delegated to a fast agent?\n\n```\nDoes the task require architectural judgment?\n  YES -> orchestrator\n  NO  -> Does it modify files another agent is touching?\n    YES -> orchestrator (or wait)\n    NO  -> Is the spec unambiguous and complete?\n      YES -> fast agent\n      NO  -> orchestrator writes the spec first, then delegates\n```\n\n### React Query vs provider vs local `useState`?\n\n- Server\u002Fasync data -> React Query (`useQuery`, `useSuspenseQuery`, `\u003CMatchQuery>`)\n- Cross-cutting client state -> Zustand (only when provider nesting becomes unwieldy)\n- Subtree siblings sharing mutable state -> `setupStateProvider`\n- Read-only computed value for a subtree -> `setupValueProvider`\n- Persisted across refresh -> `usePersistentState`\n- Component-only, no sharing -> `useState`\n- Derived from existing state -> inline computation (no extra state)\n\n### Custom hook vs shared utility?\n\n- Shared utility (`src\u002Flib\u002F`) - pure function, no React, reusable across contexts\n- Custom hook - uses React APIs (useState, useEffect, useContext), component-specific logic\n\n### What tests are needed?\n\n- Pure function -> unit test (highest ROI)\n- Hook with state -> `renderHook` test\n- Interactive component -> component test\n- New user flow -> E2E test\n- Config\u002Ftypes\u002Fbarrel only -> skip\n\n---\n\n# Pre-Submit Gate\n\nBefore the branch is considered ready:\n\n- [ ] Ticket fetched and understood\n- [ ] Branch created from Linear `gitBranchName`\n- [ ] Implementation complete (exhaustive typing + pattern matching)\n- [ ] All agent output reviewed by the orchestrator before commit\n- [ ] libqc API semantics verified (not delegated)\n- [ ] Provider order invariants preserved\n- [ ] Extension-security rules satisfied (timeout, lock, CSP, secret hygiene)\n- [ ] E2E selector\u002Flabel stability preserved (or tests updated in the same PR)\n- [ ] `pnpm l:c` passes\n- [ ] `pnpm p:c` passes\n- [ ] `pnpm test:unit` passes\n- [ ] `pnpm test:e2e:check` passes\n- [ ] `pnpm build:dev` passes\n- [ ] `pnpm ci:pr` passes (final gate)\n- [ ] Conventional commit(s) created (no Co-Authored-By)\n- [ ] User confirmed push + PR creation\n- [ ] PR created as draft with test plan and `Closes P11-XXXX`\n- [ ] All `.claude\u002Frules\u002F` satisfied\n\n---\n\n# Troubleshooting\n\n| Problem                             | Fix                                                                                  |\n| ----------------------------------- | ------------------------------------------------------------------------------------ |\n| `pnpm l:c` fails                    | Read output. `pnpm l:f` for auto-fixable. TypeScript errors -> fix at source.         |\n| `pnpm p:c` fails                    | `pnpm p:f` to format touched files.                                                  |\n| `pnpm test:unit` fails              | Fix the code (not the test) unless the spec changed.                                 |\n| `pnpm test:e2e:check` fails         | Selector\u002Flabel broke - restore selector or update E2E tests in the same PR.          |\n| `pnpm build:dev` fails              | Read the Vite error. Likely a type\u002Fimport boundary that ESLint missed.               |\n| Branch behind main                  | `git pull --rebase origin main && git push --force-with-lease` (confirm account).    |\n| Wrong git identity                  | `gh auth switch` to the account authorized for `p-11`; align `git config user.*` too. |\n| libqc API mismatch                  | Inspect `..\u002Flibqc\u002Fsrc\u002Findex.ts` (sibling checkout) and the relevant export.           |\n| Agent produced wrong pattern        | Orchestrator fixes directly. Re-delegate only if the fix is large + mechanical.      |\n| Agent modified the wrong file       | Revert. Re-delegate with a stricter file list.                                       |\n| Parallel agents created type clash  | Orchestrator picks canonical name, updates all references.                           |\n| Agent stuck \u002F no progress           | Provide specific unblocking instructions. After 2 attempts, take over directly.      |\n| Review agents disagree              | Orchestrator resolves by reading the actual code and project rules.                  |\n\n---\n\n# Examples\n\n## Feature Delivery\n\n```\n\u002Forchestrate P11-1234\n\nStep 1: Fetch ticket -> \"Add token details screen\"\n  ├── Parallel Explore agents:\n  │   ├── src\u002F Explorer -> found existing screen registry + `DepositAccessGuard` pattern\n  │   ├── libqc Explorer -> found `getCoinBalance` + `AccountCoin` types\n  │   └── Test Explorer -> found wallet.test.ts touches similar flow, no collision\n  └── Orchestrator synthesizes, no Figma URL (design is in ticket attachments)\n\nStep 2: Create branch from Linear gitBranchName\n\nStep 3: Plan with 3 streams\n  Stream 1 (fast): core.ts + types.ts + hooks skeleton\n  Stream 2 (fast): UI components (header, balance, actions)\n  Stream 3 (orchestrator): screen registration + provider integration\n  Streams 1+2 parallel, Stream 3 sequential after both\n\nStep 4: Execute\n  ├── Fast Agent A -> module scaffolding + hooks\n  ├── Fast Agent B -> UI components\n  ├── Orchestrator -> verify libqc semantics, wait for agents\n  └── Orchestrator -> register screen + wire transitions\n\nStep 5: Integration review -> fix import paths, wire MatchQuery\n\nStep 6: Quality gates -> lint, prettier, unit, e2e:check, build:dev all PASS\n\nStep 7: Smart test eval -> unit tests for mapper, add selector-stable test ids\n\nStep 8-10: Commit -> ask user -> push + draft PR (with Closes P11-XXXX)\n```\n\n## PR Review\n\n```\n\u002Forchestrate feat\u002Ftoken-details --review\n\nStage 1: Parallel context\n  ├── shell: fetch diff (9 files, 2 commits)\n  └── explore: categorize domains (2 providers, 3 screens, 4 components)\n\nStage 2: Parallel review (10 agents)\n  ├── Type Safety -> 1 finding (`as Chain` at L42)\n  ├── Pattern Matching -> 2 findings (nested ternary L18, switch on chain kind L67)\n  ├── React Patterns -> 1 finding (`useMemo` at L12)\n  ├── Provider Architecture -> 0 findings\n  ├── Extension Security -> 1 critical (new authenticated screen not in AUTHENTICATED_SCREENS)\n  ├── Screen Navigation -> 0 findings\n  ├── Styling -> 1 finding (`#111827` at L55 - use token)\n  ├── Performance -> 0 findings\n  ├── Code Quality -> 1 finding (magic number `300_000` - extract)\n  └── Architecture -> 0 findings\n\nStage 3: Orchestrator report\n  1 critical, 5 important, 0 nitpick\n  -> REQUEST CHANGES with fix suggestions\n```\n\n---\n\nRun with:\n\n- `\u002Forchestrate P11-1234` - feature delivery\n- `\u002Forchestrate P11-1234 --auto` - skip plan confirmation\n- `\u002Forchestrate feat\u002Fmy-branch --review` - exhaustive PR review\n- `\u002Forchestrate 42 --review` - PR review by number (if the harness recognizes it)\n","# Orchestrator: End-to-End Workflow\n\nTwo operating modes:\n\n## Mode A - Feature Delivery (default)\n\nTakes a Linear ticket ID and handles the entire pipeline:\n\n1. Fetch and understand the ticket\n2. Parallel context gathering across `src\u002F`, shared utilities, and `libqc` sibling SDK\n3. Create the git branch\n4. Plan implementation with parallelization strategy\n5. Implement across files with maximum parallelism\n6. Orchestrator review + integration pass\n7. Build\u002Freview\u002Ffix loop until clean\n8. Smart test generation (unit + E2E where applicable)\n9. Commit\n10. Ask user for permission to push and create the draft PR\n\n## Mode B - PR Review (`--review`)\n\nTakes a PR branch name or URL and performs an exhaustive audit:\n\n1. Fetch commits, diff, changed files\n2. Spawn parallel review agents across every quality dimension\n3. Report findings with `file:line` references and fix suggestions\n4. Optionally auto-fix and re-validate\n\n---\n\n## Architecture: Opus Orchestrator + Opus Reasoning Agents\n\nUse as many parallel agents as needed. There is no artificial cap on concurrency - spawn agents aggressively for independent work streams. The goal is perfection at maximum speed. The user has unlimited resources; **default to Opus 4.6 for every agent whose work requires reasoning, judgment, bug hunting, or test design**. Fall back to the default model only for purely mechanical operations.\n\n### Model Selection Rule\n\nPass `model: \"opus\"` (Claude Opus 4.6) to every agent in the following categories - these are the reasoning-heavy surfaces that benefit most from the stronger model:\n\n- **Exploration** (`subagent_type: \"Explore\"`) when the goal is to synthesize architectural context, trace data flow, or judge pattern fit. Reserve the default model only for \"find this exact string\" lookups.\n- **Planning** (`subagent_type: \"Plan\"`) - always Opus.\n- **Implementation agents** building anything non-trivial: new modules, provider wiring, libqc seam code, anything touching security\u002Flock\u002Ftimeout.\n- **Code review agents** (`code-reviewer`, Type Safety, Pattern Matching, Provider Architecture, Extension Security, Screen Navigation, Performance, Architecture) - always Opus.\n- **Test generation** (`test-writer`): what to test, where, how to guard against regressions - always Opus.\n- **Bug-finding \u002F investigation** (`investigator`): dependency tracing and judgment calls - always Opus.\n- **Refactoring** (`refactorer`): architectural judgment and safety-critical edits - always Opus.\n- **Styling review** (`styling`): token usage + design token decisions - always Opus.\n- **PR body writing** and **PR review synthesis** - orchestrator handles directly (already Opus).\n\nUse the default model only for:\n\n- Pure shell operations (git branch setup, stage + push commands)\n- Running a single quality-gate command and reporting PASS\u002FFAIL\n- Mechanical scaffolding where every line is already specified by the orchestrator (see `\u002Fdelegate`)\n\nWhen in doubt, choose Opus. The user explicitly wants reasoning quality over token cost.\n\n### How to spawn Opus agents\n\nWhen using the `Agent` tool, pass `model: \"opus\"` alongside `subagent_type` and `description`:\n\n```\nAgent({\n  description: \"Review extension security impact\",\n  subagent_type: \"code-reviewer\",\n  model: \"opus\",\n  prompt: \"...\"\n})\n```\n\nProject agents (`code-reviewer`, `investigator`, `refactorer`, `styling`, `test-writer`, `pr-preparer`) already declare `model: opus` in their frontmatter. The parent invocation should still pass `model: \"opus\"` explicitly to make the contract visible in the orchestrator log.\n\n```\n+---------------------------------------------------+\n|               ORCHESTRATOR (Opus)                  |\n|  Planning - Architecture - Judgment - Integration  |\n|  libqc API semantics - Sync - Final review         |\n+---+---------+---------+---------+---------+-------+\n    |         |         |         |         |\n +--v--+   +--v--+   +--v--+   +--v--+   +--v--+\n | A   |   | B   |   | C   |   | D   |   | ... |\n | fast|   | fast|   | fast|   | fast|   | fast|\n +-----+   +-----+   +-----+   +-----+   +-----+\n```\n\n### Orchestrator Responsibilities (never delegate)\n\n- **Planning**: decompose the ticket into work streams with dependencies\n- **Architecture decisions**: which patterns, where to put code, module boundaries\n- **libqc API semantics**: verify SDK field meanings and return shapes before any runtime logic\n- **Provider topology**: ordering, `LibQC` instance ownership, context usage\n- **Cross-cutting integration**: wire together outputs from multiple agents\n- **Final review**: read every file touched by agents, fix integration issues\n- **Security review**: vault lock\u002Funlock behavior, idle timeout, secret hygiene\n- **PR body writing**: requires understanding the full change\n\n### Delegable Work (still Opus by default)\n\nWith unlimited resources, lean Opus for anything involving judgment. Delegation is about parallelism, not about cost minimization:\n\n- **Architectural exploration** (Opus): synthesizing patterns, tracing data flow, judging pattern fit\n- **Component implementation** (Opus): building UI from a precise spec - even \"clear\" specs hit type-safety edges\n- **Hook scaffolding** (Opus): React Query composition, boundary handling, assert hooks\n- **Test generation** (Opus via `test-writer`): deciding coverage, regression guards, selector stability\n- **PR review dimensions** (Opus): type safety, pattern matching, provider architecture, security, performance - one Opus agent per dimension for maximum parallelism\n- **Refactor passes** (Opus via `refactorer`): safety-critical changes preserving provider\u002Fnavigation\u002Fsecurity invariants\n\n### Truly Mechanical Work (default model OK)\n\n- **Exact string lookups** in the codebase (one grep, no synthesis needed)\n- **Pure shell operations**: `git checkout`, `git add`, `git push`\n- **Running a single quality-gate command** and reporting PASS\u002FFAIL verbatim\n- **Screen registry wiring** when the exact lines to add are already specified\n\n### Worker Coordination Protocol\n\n1. **File isolation** - each agent owns distinct files. Never two agents on the same file.\n2. **Cross-agent synthesis** - when Agent A produces output Agent B needs, the orchestrator reads A's deliverables and feeds them into B's prompt. Workers never talk directly - the orchestrator is the routing layer.\n3. **Quality gates with push-back** - no agent's work is marked done until deliverables are reviewed. Bad output goes back with specific fix instructions.\n4. **Stall detection** - if an agent keeps failing after 2 attempts, reassess: provide specific unblocking instructions, simplify the task, or take it over directly.\n5. **Convergence collapse** - when parallel agents produce overlapping concerns (shared types, cross-module imports), collapse remaining work to sequential. Parallel is for independent work; the moment dependencies emerge, go sequential.\n\n---\n\n## Repo Paths\n\n| Repo          | Location (relative to quantum-vault repo root) | Default branch | Role                              |\n| ------------- | ---------------------------------------------- | -------------- | --------------------------------- |\n| quantum-vault | `.` (this repo)                                | `main`         | Chrome Extension (MV3)            |\n| libqc         | `..\u002Flibqc` (sibling checkout)                  | `main`         | Published SDK (pinned in package) |\n\n`quantum-vault` consumes `@project-eleven\u002Flibqc` as a pinned published package (see `package.json`); the sibling `libqc` checkout is required for source-level verification and coordinated SDK changes. Breaking changes to the SDK's public surface require a new release and a matching pin bump, plus validation of extension imports and runtime flows.\n\n## Package Manager + Commands\n\n`pnpm` only (pinned to `pnpm@10.20.0`). Never use `yarn` or `npm`.\n\n| Task                 | Command                                  |\n| -------------------- | ---------------------------------------- |\n| Install deps         | `pnpm install`                           |\n| Dev server           | `pnpm dev`                               |\n| Dev build            | `pnpm build:dev`                         |\n| Lint check           | `pnpm l:c`                               |\n| Lint fix             | `pnpm l:f`                               |\n| Prettier check       | `pnpm p:c`                               |\n| Prettier write       | `pnpm p:f`                               |\n| Unit tests           | `pnpm test:unit`                         |\n| E2E parse check      | `pnpm test:e2e:check`                    |\n| E2E run (local)      | `pnpm exec playwright test`              |\n| Full CI gate         | `pnpm ci:pr`                             |\n\n`pnpm ci:pr` runs lint check, prettier check, unit tests, dev build, E2E parse check, and the `dep-doc` audit in sequence. Use it as the final pre-PR gate.\n\n---\n\n# Mode A: Feature Delivery\n\n## Step 1: Fetch Ticket + Parallel Context Gathering\n\n### 1a: Fetch ticket (orchestrator)\n\n```\nLinear MCP: get_issue({ id: \"\u003CTICKET-ID>\", includeRelations: true })\n```\n\nExtract: title, description, acceptance criteria, `gitBranchName`, blockers, Figma URLs, libqc dependencies, extension-runtime concerns.\n\n### 1b: Parallel context exploration\n\nWhile the orchestrator analyzes the ticket, spawn parallel Explore agents:\n\n- Agent A: search `src\u002F` for related feature modules, screens, providers, hooks, shared utilities. Return file paths, existing patterns, reusable primitives.\n- Agent B: search `libqc\u002Fsrc\u002F` for SDK functions, types, resolvers, storage interfaces relevant to the feature. Return public API signatures and chain-dispatch points.\n- Agent C: search `__tests__\u002Fe2e\u002F` for existing test selectors and flows that touch the same surface. Return fixture data and selector patterns at risk.\n- Agent D+: any additional context gathering (design refs, CLAUDE.md reference docs, prior PRs touching the same module).\n\nAdd more Explore agents as needed - there is no cap on context gathering.\n\n### 1c: Fetch design (orchestrator, if Figma URL present)\n\nExtract `fileKey` and `nodeId`. Map Figma variables to Tailwind v4 CSS-first tokens from `src\u002Findex.css` and existing `src\u002Fcomponents\u002Fui\u002F` primitives. Never implement UI without actually retrieving the design via MCP.\n\n### 1d: Synthesize (orchestrator)\n\nRead all agent outputs. Produce a unified context document:\n\n```markdown\n## Existing Codebase Context\n- Relevant screens\u002Fproviders: [paths]\n- Relevant hooks\u002Futilities: [paths]\n- Reusable components: [paths]\n- libqc surface touched: [exported functions + types]\n- Design tokens needed: [from Figma]\n- Reference implementations: [best example files]\n- E2E coverage at risk: [test files + selectors]\n- Constraints: [blockers, missing libqc exports, CSP implications]\n```\n\n---\n\n## Step 2: Git Branch Setup\n\nRun from repo root:\n\n```bash\ngit checkout main && git pull\ngit checkout -b {gitBranchName-from-linear}\n```\n\nIf the branch already exists: `git checkout {branch} && git rebase origin\u002Fmain`.\n\nAlways use the exact `gitBranchName` from Linear - do not modify it.\n\n---\n\n## Step 3: Plan Implementation\n\nSynthesize the ticket, design, and exploration context into a plan. Present to the user unless `--auto`.\n\n### Plan Template\n\n```markdown\n## Implementation Plan for \u003CTICKET-ID>: \u003Ctitle>\n\n### Work Streams\n\n#### Stream 1: \u003Cname> [owner: fast-agent | orchestrator]\n- Files: [exact paths to create or modify]\n- Depends on: [other streams, or \"none\"]\n- Description: [what to implement]\n- Parallelizable with: [other stream names]\n\n#### Stream 2: ...\n\n### Execution Order\n1. [Streams A + B + C] - parallel (no shared files)\n2. [Stream D] - sequential (needs A output types)\n3. [Integration] - orchestrator assembles everything\n\n### Agent Allocation\n| Stream | Owner        | Reason                              |\n| ------ | ------------ | ----------------------------------- |\n| ...    | fast-agent   | Mechanical: clear contract, one file|\n| ...    | orchestrator | Needs judgment on libqc semantics   |\n```\n\n### Work Stream Decomposition Rules\n\n1. **File isolation** - each agent owns distinct files\n2. **Clear contracts** - each agent gets exact input types, output types, file paths\n3. **No ambiguity** - full code for patterns, exact class names, exact imports\n4. **Dependency ordering** - agents producing types must complete before consumers start\n\n---\n\n## Step 4: Parallel Implementation\n\nExecute the plan with parallel agents. The orchestrator monitors, validates, and integrates.\n\n### Parallelization Patterns\n\n**Pattern A: UI + Data Layer Parallel**\n\n```\nPHASE 1 - Parallel scaffolding\n├── Agent A: core.ts + types.ts for the feature module\n├── Agent B: data\u002Fhooks.ts + data\u002Fmappers\u002F\n├── Agent C: UI components (one per file, from design spec)\n└── Agent Explore: verify pattern consistency with existing modules\n\nPHASE 2 - Orchestrator integration\n├── Read all agent output\n├── Verify libqc API semantics (NEVER delegate)\n├── Wire components together, fix cross-cutting issues\n└── Register in screen registry + provider tree if needed\n\nPHASE 3 - Parallel completion\n├── Agent: unit tests for pure logic\n├── Agent: E2E impact check\n└── Orchestrator: final review pass\n```\n\n**Pattern B: Multi-Component Feature**\n\n```\nPHASE 1 - Parallel build (one agent per independent file)\n├── Agent A: components\u002Ffeature\u002Fpart-a.tsx\n├── Agent B: components\u002Ffeature\u002Fpart-b.tsx\n├── Agent C: hooks\u002Fuse-feature.ts\n└── Agent D: providers\u002Ffeature-provider.tsx (if needed)\n\nPHASE 2 - Orchestrator assembly\n├── Compose parts into parent screen\n├── Wire screen into registry\n└── Verify type flow end-to-end\n```\n\n**Pattern C: Sequential Core + Parallel Polish**\n\n```\nPHASE 1 - Orchestrator implements core logic (tight dependencies)\nPHASE 2 - Parallel completion\n├── Agent: styling\u002Ftokens pass\n├── Agent: quality gates\n└── Agent: test scaffolding\n```\n\n### Spawning Fast Agents\n\n**UI implementation agent prompt template:**\n\n```\nYou are implementing a component for quantum-vault (Chrome Extension MV3).\n\nPROJECT: React 19 + Vite + TypeScript, Tailwind v4 CSS-first + shadcn\u002Fui, libqc SDK\nFILE: {exact path to create or modify}\n\n## Existing Code (reference)\n{paste relevant existing patterns, types, imports, design tokens}\n\n## What to Build\n{exact spec: imports, types, component structure, exports}\n\n## Rules (MUST follow - see .claude\u002Frules\u002F and CLAUDE.md)\n- `type` not `interface` (interface only for class contracts)\n- No `useMemo` or `useCallback` (React Compiler handles memoization)\n- No `as` assertions - use type narrowing, discriminated unions, `ensurePresent()`\n- No `?.` \u002F `??` on non-optional types - trust the type system\n- No `switch\u002Fcase` - use `Record\u003CKey, Value>`, `match()`, `\u003CMatch>`, config arrays\n- Never hardcode hex colors in feature components - use tokens from src\u002Findex.css\n- Use `cn()` for class merging\n- One component per file, feature-based organization (no generic `components\u002F`)\n- core.ts for runtime values + derived types, types.ts for pure types only\n- Object params for functions with >1 arg\n- Colocate state with consumers - no prop drilling\n\n## Pattern to Follow\n{paste a real example from the codebase}\n```\n\n**Shared utility or hook agent prompt template:**\n\n```\nYou are implementing a pure utility\u002Fhook for quantum-vault.\n\nFILE: {exact path}\nPROJECT: TypeScript strict mode\n\n## Existing Code (reference)\n{paste relevant patterns from src\u002Flib\u002F or src\u002Fhooks\u002F}\n\n## What to Build\n{exact spec with signatures, examples, error handling}\n\n## Rules\n- `attempt()` over try-catch (only when user-facing error needed)\n- `ensurePresent()` at runtime boundaries\n- No side effects in mappers\n- Pure functions for data transformation\n- Derive types from const arrays (source of truth)\n- Check shared utilities before creating new helpers\n\n## Pattern to Follow\n{paste a real example}\n```\n\n---\n\n## Step 5: Orchestrator Review + Integration\n\nNever skip this step. After all agents complete:\n\n### 5a: Read every file touched by agents\n\nCheck for:\n\n- Correct imports and type references across files\n- Consistent naming between layers (`core.ts` ↔ types.ts ↔ consumers)\n- No `as` assertions, no `useMemo`\u002F`useCallback`\n- Provider order preserved (CurrencyProvider -> WalletProvider -> ScreenProvider)\n- `LibQC` instantiated only in `WalletProvider` (never in screens)\n- No hardcoded colors outside `src\u002Findex.css`\n- libqc API field semantics correct (verify against SDK source)\n- Timeout\u002Flock behavior still consistent for new authenticated screens\n- No sensitive data logged (mnemonic, password, private key)\n\n### 5b: Cross-agent integration\n\n1. Verify type flow: libqc types -> mappers -> hooks -> component props\n2. Verify screen wiring connects to the registry in `src\u002Fscreens.tsx`\n3. Verify provider integration (e.g., refresh list in `ScreenProvider` if balance-sensitive)\n4. Fix import paths, naming mismatches, missing type exports\n\n### 5c: Fix issues directly\n\nMake edits to resolve integration issues. Only re-delegate if the fix is large and mechanical.\n\n---\n\n## Step 6: Build\u002FReview\u002FFix Loop\n\nThis is a persistent loop. Do NOT stop until ALL gates pass.\n\n```\nwhile true:\n  1. pnpm l:c                -> fix errors (pnpm l:f for auto-fixable)\n  2. pnpm p:c                -> pnpm p:f to format\n  3. pnpm test:unit          -> fix logic, not assertions (unless assertion is wrong)\n  4. pnpm test:e2e:check     -> verify E2E tests still parse (selector stability)\n  5. pnpm build:dev          -> catch Vite\u002FTS build-only issues\n  6. If any fail -> read output, fix, go to 1\n  7. All pass -> break\n```\n\nCommon fixes:\n\n- ESLint unused import -> remove or switch to `import type`\n- ESLint suggests import sort -> `pnpm l:f`\n- TypeScript error -> fix at source. Never `as` cast. Add `ensurePresent()` at boundaries.\n- Prettier whitespace -> `pnpm p:f`\n- Unit test fails -> fix the code. Only edit the test when the spec actually changed.\n- E2E selector broken -> either restore the selector or update `__tests__\u002Fe2e\u002F*.test.ts` in the same PR.\n\n### Stall Detection\n\nIf the same error keeps failing after 2 iterations:\n\n1. Re-read the error carefully. Real issue or pre-existing?\n2. Try a different fix approach.\n3. If still stuck after 2 attempts, stop and surface the specific error to the user.\n\n---\n\n## Step 7: Smart Test Generation\n\nAfter quality checks pass, evaluate what tests are needed.\n\n### 7a: Evaluate (orchestrator)\n\n| What was built                           | Test type                                                   |\n| ---------------------------------------- | ----------------------------------------------------------- |\n| Pure utility or mapper                   | Unit test (Vitest) in `__tests__\u002F` colocated with source    |\n| Hook with state                          | Hook integration test (Vitest + `renderHook`)               |\n| Component with interaction               | Component integration test (Vitest + Testing Library)       |\n| New user-facing screen or critical flow  | E2E test (Playwright) in `__tests__\u002Fe2e\u002F`                   |\n| libqc integration seam logic             | Unit test against a mocked `LibQC` instance                 |\n| Config\u002Ftypes\u002Fbarrel only                 | Skip - no tests needed                                      |\n\n### 7b: Generate tests (parallel agents, one per test type)\n\n```\nUnit Test Agent    -> Vitest unit tests for pure logic. Arrange-Act-Assert.\n                      Edge cases: empty, zero, BigNumber boundaries, error paths.\nIntegration Agent  -> Testing Library component tests with user events.\n                      Assert on visible text\u002Froles, not implementation details.\nE2E Agent          -> Playwright in __tests__\u002Fe2e\u002F*.test.ts.\n                      Follow existing patterns; keep selectors\u002Ftest-ids stable.\n                      Mock chain RPC reads when feasible (see existing test scaffolding).\n```\n\n### 7c: Run + fix\n\n```bash\npnpm test:unit        # fix failures - fix the code, not the test unless spec changed\npnpm test:e2e:check   # parse-check all E2E files compile and register\n# Full E2E only when the flow is touched:\npnpm exec playwright test __tests__\u002Fe2e\u002F\u003Cfile>.test.ts\n```\n\nRepeat until all gates pass.\n\n---\n\n## Step 8: Commit\n\nRun the full gate before any commit:\n\n```bash\npnpm ci:pr   # or at minimum: pnpm l:c && pnpm p:c && pnpm test:unit && pnpm build:dev\n```\n\nStage specific files - never `git add .` or `git add -A`:\n\n```bash\ngit add \u003Cspecific-files>\ngit commit -m \"$(cat \u003C\u003C'EOF'\nfeat(scope): imperative description\n\n- Detail 1\n- Detail 2\n- Closes P11-1234\nEOF\n)\"\n```\n\nConventional commits. No `Co-Authored-By` trailer.\n\n---\n\n## Step 9: Ask User Before Pushing + Creating PR\n\nSTOP and ask before pushing or creating the PR. Present a summary:\n\n```markdown\n## Ready to push\n\n### Changes\n- {summary of files changed}\n- {summary of what was implemented}\n\n### Branch\n- `{gitBranchName}` in quantum-vault ({N} files changed)\n\n### Quality gates\n- `pnpm l:c` - pass\n- `pnpm p:c` - pass\n- `pnpm test:unit` - pass\n- `pnpm test:e2e:check` - pass\n- `pnpm build:dev` - pass\n\nShall I push and create a draft PR?\n```\n\nOnly proceed after explicit user confirmation.\n\n---\n\n## Step 10: Push + Draft PR\n\nAfter user confirms, push and create the PR as a draft:\n\n```bash\ngit push -u origin {branch}\ngh pr create --draft \\\n  --title \"feat(scope): description (P11-1234)\" \\\n  --body \"$(cat \u003C\u003C'EOF'\n## Summary\n- What this PR does and why\n\n## Test Plan\n- [ ] `pnpm l:c` passes\n- [ ] `pnpm p:c` passes\n- [ ] `pnpm test:unit` passes\n- [ ] `pnpm test:e2e:check` passes\n- [ ] `pnpm build:dev` passes\n- [ ] Extension loads unpacked from `build\u002F`\n- [ ] Lock\u002Funlock + idle timeout verified for any authenticated screen touched\n\n## Related\n- Closes P11-1234\nEOF\n)\"\n```\n\n### Before every `git push` + `gh pr create`\n\n1. `git remote -v` and confirm the remote org\n2. `gh auth status` and confirm the active account is authorized for the `p-11` GitHub org\n3. Verify `git config user.name` and `user.email` match the expected identity for this folder\n\nIf any check fails, stop and surface the mismatch to the user.\n\n---\n\n## Linear Ticket Status\n\nThe GitHub-Linear integration handles status transitions automatically:\n\n| GitHub PR event                   | Linear status change       |\n| --------------------------------- | -------------------------- |\n| PR created as draft               | no change                  |\n| PR moved from draft -> ready      | -> In Review \u002F In Progress |\n| PR merged                         | -> Done                    |\n\n- Always include `Closes P11-XXXX` in the PR body (links to the Linear ticket)\n- Always include `(P11-XXXX)` in the PR title\n- Do not call `save_issue` to change `state`\n- Do not call `save_comment` just to post the PR link\n\nOnly post a Linear comment when there is meaningful context beyond the PR link (implementation decisions, open questions, deferred scope).\n\n---\n\n# Mode B: PR Review\n\n## Stage 1: Gather PR Context (parallel)\n\n- Agent A (shell): `git fetch origin && git log --oneline origin\u002Fmain..HEAD`, `git diff --stat origin\u002Fmain..HEAD`, full diff. Report commits + changed files.\n- Agent B (explore): categorize touched domains (screens, providers, hooks, data, styling, libqc seam, tests). For each, list the relevant rules from `.claude\u002Frules\u002F`.\n\n## Stage 2: Deep Review (parallel, one agent per dimension)\n\nSpawn a review agent for EACH quality dimension across ALL changed files:\n\n### Type Safety Agent\nCheck for:\n- `as` assertions (forbidden - use type narrowing or discriminated unions)\n- Unnecessary `?.` on non-optional properties\n- `?? ''` or `?? 0` fallbacks on non-optional values\n- `any` types (use `unknown` + narrow)\n- Missing `ensurePresent()` at boundary lookups\n- `interface` for data shapes (should be `type`)\n- Derived union types from const arrays (single source of truth)\n- `core.ts` vs `types.ts` split respected\n\n### Pattern Matching Agent\nCheck for:\n- `switch\u002Fcase` (forbidden - use Record lookups, `match()`, `\u003CMatch>`, config arrays)\n- Nested ternaries (>=2 levels - extract to `match()` \u002F `\u003CMatch>`)\n- Manual `if (isLoading)` instead of `\u003CMatchQuery>`\n- Non-exhaustive record lookups (should `Record\u003CVariant, V>` not `Partial\u003C...>` unless intentional)\n\n### React Patterns Agent\nCheck for:\n- `useMemo`\u002F`useCallback` (forbidden - React Compiler)\n- Multiple components per file (one per file, small helpers \u003C 10 lines excepted)\n- Prop drilling where hook-based autonomy would be clearer\n- Domain components receiving domain data as props (should use hooks directly)\n- Conditional hook calls (use guard components instead)\n\n### Provider Architecture Agent\nCheck for:\n- Provider order changes (CurrencyProvider -> WalletProvider -> ScreenProvider)\n- `LibQC` instantiated outside `WalletProvider`\n- Deep imports into libqc internals from app code\n- Missing paired `useX` hook that throws outside provider context\n- Data fetching inside a provider (providers distribute state, hooks fetch)\n\n### Extension Security Agent\nCheck for:\n- New authenticated screens not added to `AUTHENTICATED_SCREENS` in `useSessionTimeout`\n- Lock flow not clearing wallet in-memory state\n- CSP drift in `manifest.json`\n- `console.log` with sensitive data (mnemonic, password, private key, raw vault)\n- `.env*` files committed or referenced\n- Missing `VITE_*` prefix for new env variables\n\n### Screen Navigation Agent\nCheck for:\n- Imperative navigation that bypasses `ScreenProvider` hydration\n- New screen not registered in `src\u002Fscreens.tsx`\n- Missing `ScreenKey` usage (raw strings instead of registry keys)\n- Balance-sensitive screen added without updating refresh list\n\n### Styling Agent\nCheck for:\n- Hardcoded hex colors outside `src\u002Findex.css`\n- Inline font-size\u002Fweight instead of typography tokens\n- `!important` overrides (fix specificity)\n- Mixing ad-hoc styled components with shadcn primitives\n- Popup shell width deviating from ~400px baseline\n\n### Performance Agent\nCheck for:\n- State not colocated with consumers (re-render blast radius)\n- O(n^2) operations where O(n) works\n- Redundant state that could be derived\n- Unnecessary re-renders from parent prop changes\n- Missing key-based remount when needed\n\n### Code Quality Agent\nCheck for:\n- Magic numbers\u002Fstrings not extracted to named constants\n- DRY violations (same value\u002Flogic repeated 2+ times)\n- Missing `attempt()` where user-facing errors are handled\n- Shared utilities not reused (local helper duplicates something in `src\u002Flib\u002F`)\n- Boolean params at call sites that should be object params or split functions\n- `console.log` in production paths\n- Commented-out code committed\n\n### Architecture Agent\nCheck for:\n- Generic `components\u002F` folder at feature level (should be feature-based)\n- `hooks\u002F` folder at module level (should be `data\u002Fhooks.ts` or colocated)\n- Missing one-component-per-file rule\n- `index.ts` barrel exports that re-export everything (import directly instead)\n- Cross-layer leakage (e.g., UI importing from API response types directly)\n\n### Test Impact Agent\nCheck for:\n- `data-testid` changes that break existing E2E tests\n- New user-facing flow without E2E coverage\n- Timing-sensitive assertions introduced to E2E\n- Unit tests that assert implementation instead of behavior\n\n## Stage 3: Synthesize + Report (orchestrator)\n\n1. Read every review agent's output\n2. Deduplicate (multiple agents may flag the same line)\n3. Prioritize: **critical** (breaks at runtime) > **important** (violates standards) > **nitpick** (style)\n4. Present a structured report:\n\n```markdown\n## PR Review: {branch-name}\n\n### Critical (must fix)\n- `src\u002Fpath\u002Ffile.tsx:42` - {issue} -> {fix}\n\n### Important (should fix)\n- `src\u002Fpath\u002Ffile.ts:15` - {issue} -> {fix}\n\n### Nitpick (consider)\n- `src\u002Fpath\u002Ffile.tsx:88` - {issue} -> {fix}\n\n### Summary\n- {X} critical, {Y} important, {Z} nitpick findings\n- Overall assessment: APPROVE | REQUEST CHANGES\n```\n\n5. If the user says \"fix\" or `--fix` was passed: auto-apply fixes, run `pnpm ci:pr`, re-validate.\n\n---\n\n# Agent Allocation Matrix\n\nDefault model is **Opus 4.6** unless the task is purely mechanical. The user has unlimited resources - choose Opus whenever reasoning, judgment, or bug-finding is involved.\n\n| Task                                  | Owner         | Model   | Why                                                  |\n| ------------------------------------- | ------------- | ------- | ---------------------------------------------------- |\n| Ticket analysis + scope detection     | orchestrator  | Opus    | Requires judgment                                    |\n| Codebase exploration (architectural)  | Explore agent | Opus    | Synthesize patterns, judge fit                       |\n| Codebase exploration (exact lookup)   | Explore agent | default | Pure search for a known string                       |\n| libqc API semantics verification      | orchestrator  | Opus    | Critical - errors cause silent bugs                  |\n| Provider topology decisions           | orchestrator  | Opus    | Must preserve ordering invariants                    |\n| Architecture + plan creation          | orchestrator  | Opus    | Judgment on module boundaries                        |\n| Component from clear spec             | agent         | Opus    | Even \"clear spec\" hits edge cases at implementation  |\n| Component with complex state          | orchestrator  | Opus    | Architectural judgment                               |\n| Hook scaffolding from spec            | agent         | Opus    | Type safety + boundary handling                      |\n| Screen registry wiring                | agent         | default | Mechanical file update                               |\n| Cross-component integration           | orchestrator  | Opus    | Multi-output assembly                                |\n| Quality gates (`pnpm ci:pr`)          | agent         | default | Command execution + error reporting                  |\n| Quality gate fixes                    | orchestrator  | Opus    | Requires understanding why it failed                 |\n| Test strategy + generation            | test-writer   | Opus    | Decide what to test, find regressions                |\n| Test failure diagnosis                | orchestrator  | Opus    | Root cause analysis                                  |\n| Git operations (branch, push)         | agent         | default | Mechanical commands                                  |\n| PR body writing                       | orchestrator  | Opus    | Full-change understanding                            |\n| PR review - type safety               | review agent  | Opus    | Judgment on narrowing and invariants                 |\n| PR review - pattern matching          | review agent  | Opus    | Spot exhaustive\u002Fnon-exhaustive dispatch              |\n| PR review - React patterns            | review agent  | Opus    | React Compiler compliance + autonomy judgment        |\n| PR review - provider architecture     | review agent  | Opus    | Provider order, `LibQC` singleton, guard boundaries  |\n| PR review - extension security        | review agent  | Opus    | Lock\u002Ftimeout\u002FCSP\u002Fsecret hygiene                      |\n| PR review - screen navigation         | review agent  | Opus    | Registry + hydration contracts                       |\n| PR review - styling                   | review agent  | Opus    | Token discipline + hardcode detection                |\n| PR review - performance               | review agent  | Opus    | Re-render blast radius, state colocation             |\n| PR review - code quality              | review agent  | Opus    | DRY + magic values + shared utility reuse            |\n| PR review - architecture              | review agent  | Opus    | Module layout + boundary leakage                     |\n| PR review - test impact               | review agent  | Opus    | Selector stability + flake risk                      |\n| PR review synthesis                   | orchestrator  | Opus    | Dedup, prioritize, assess                            |\n| Linear status updates                 | NEVER         | -       | GitHub-Linear integration handles this               |\n\n---\n\n# Synchronization Protocol\n\n### When agents finish\n\n1. **Read the full output** of every completed agent\n2. **Validate file isolation** - confirm no agent wrote to another agent's files\n3. **Check type flow** - libqc types -> mappers -> hook outputs -> component props\n4. **Resolve naming conflicts** - pick one canonical name, fix every reference\n5. **Merge integration points** - add imports that cross agents' files\n\n### Context handoff between sequential agents\n\n```\nTask prompt: \"...\n\n## Context from Previous Work\nFile `{path}` was created with this content:\n{paste the relevant code}\n\nYour task depends on the types above. Specifically:\n- Use type `{TypeName}` from `{import path}`\n- The hook returns `{describe shape}`\n...\"\n```\n\n### When to collapse parallel to sequential\n\n- Two agents need to modify the same file\n- Agent B's implementation depends on Agent A's output type\n- An agent's output reveals an architectural issue requiring replanning\n- libqc API semantics ambiguous and need investigation\n\n### Stall detection and recovery\n\n1. Read the agent's output - identify the specific failure\n2. Provide targeted fix instructions and re-delegate with more context\n3. If still failing after 2 attempts, take over directly\n4. Never let a stuck agent block the pipeline - route around it\n\n---\n\n# Decision Trees\n\n### Should I create a new feature module?\n\n- YES: own state\u002Fdata layer, used in multiple places, significant enough to isolate\n- NO: small component in an existing module, used in one place, UI-only change\n\n### Should this be delegated to a fast agent?\n\n```\nDoes the task require architectural judgment?\n  YES -> orchestrator\n  NO  -> Does it modify files another agent is touching?\n    YES -> orchestrator (or wait)\n    NO  -> Is the spec unambiguous and complete?\n      YES -> fast agent\n      NO  -> orchestrator writes the spec first, then delegates\n```\n\n### React Query vs provider vs local `useState`?\n\n- Server\u002Fasync data -> React Query (`useQuery`, `useSuspenseQuery`, `\u003CMatchQuery>`)\n- Cross-cutting client state -> Zustand (only when provider nesting becomes unwieldy)\n- Subtree siblings sharing mutable state -> `setupStateProvider`\n- Read-only computed value for a subtree -> `setupValueProvider`\n- Persisted across refresh -> `usePersistentState`\n- Component-only, no sharing -> `useState`\n- Derived from existing state -> inline computation (no extra state)\n\n### Custom hook vs shared utility?\n\n- Shared utility (`src\u002Flib\u002F`) - pure function, no React, reusable across contexts\n- Custom hook - uses React APIs (useState, useEffect, useContext), component-specific logic\n\n### What tests are needed?\n\n- Pure function -> unit test (highest ROI)\n- Hook with state -> `renderHook` test\n- Interactive component -> component test\n- New user flow -> E2E test\n- Config\u002Ftypes\u002Fbarrel only -> skip\n\n---\n\n# Pre-Submit Gate\n\nBefore the branch is considered ready:\n\n- [ ] Ticket fetched and understood\n- [ ] Branch created from Linear `gitBranchName`\n- [ ] Implementation complete (exhaustive typing + pattern matching)\n- [ ] All agent output reviewed by the orchestrator before commit\n- [ ] libqc API semantics verified (not delegated)\n- [ ] Provider order invariants preserved\n- [ ] Extension-security rules satisfied (timeout, lock, CSP, secret hygiene)\n- [ ] E2E selector\u002Flabel stability preserved (or tests updated in the same PR)\n- [ ] `pnpm l:c` passes\n- [ ] `pnpm p:c` passes\n- [ ] `pnpm test:unit` passes\n- [ ] `pnpm test:e2e:check` passes\n- [ ] `pnpm build:dev` passes\n- [ ] `pnpm ci:pr` passes (final gate)\n- [ ] Conventional commit(s) created (no Co-Authored-By)\n- [ ] User confirmed push + PR creation\n- [ ] PR created as draft with test plan and `Closes P11-XXXX`\n- [ ] All `.claude\u002Frules\u002F` satisfied\n\n---\n\n# Troubleshooting\n\n| Problem                             | Fix                                                                                  |\n| ----------------------------------- | ------------------------------------------------------------------------------------ |\n| `pnpm l:c` fails                    | Read output. `pnpm l:f` for auto-fixable. TypeScript errors -> fix at source.         |\n| `pnpm p:c` fails                    | `pnpm p:f` to format touched files.                                                  |\n| `pnpm test:unit` fails              | Fix the code (not the test) unless the spec changed.                                 |\n| `pnpm test:e2e:check` fails         | Selector\u002Flabel broke - restore selector or update E2E tests in the same PR.          |\n| `pnpm build:dev` fails              | Read the Vite error. Likely a type\u002Fimport boundary that ESLint missed.               |\n| Branch behind main                  | `git pull --rebase origin main && git push --force-with-lease` (confirm account).    |\n| Wrong git identity                  | `gh auth switch` to the account authorized for `p-11`; align `git config user.*` too. |\n| libqc API mismatch                  | Inspect `..\u002Flibqc\u002Fsrc\u002Findex.ts` (sibling checkout) and the relevant export.           |\n| Agent produced wrong pattern        | Orchestrator fixes directly. Re-delegate only if the fix is large + mechanical.      |\n| Agent modified the wrong file       | Revert. Re-delegate with a stricter file list.                                       |\n| Parallel agents created type clash  | Orchestrator picks canonical name, updates all references.                           |\n| Agent stuck \u002F no progress           | Provide specific unblocking instructions. After 2 attempts, take over directly.      |\n| Review agents disagree              | Orchestrator resolves by reading the actual code and project rules.                  |\n\n---\n\n# Examples\n\n## Feature Delivery\n\n```\n\u002Forchestrate P11-1234\n\nStep 1: Fetch ticket -> \"Add token details screen\"\n  ├── Parallel Explore agents:\n  │   ├── src\u002F Explorer -> found existing screen registry + `DepositAccessGuard` pattern\n  │   ├── libqc Explorer -> found `getCoinBalance` + `AccountCoin` types\n  │   └── Test Explorer -> found wallet.test.ts touches similar flow, no collision\n  └── Orchestrator synthesizes, no Figma URL (design is in ticket attachments)\n\nStep 2: Create branch from Linear gitBranchName\n\nStep 3: Plan with 3 streams\n  Stream 1 (fast): core.ts + types.ts + hooks skeleton\n  Stream 2 (fast): UI components (header, balance, actions)\n  Stream 3 (orchestrator): screen registration + provider integration\n  Streams 1+2 parallel, Stream 3 sequential after both\n\nStep 4: Execute\n  ├── Fast Agent A -> module scaffolding + hooks\n  ├── Fast Agent B -> UI components\n  ├── Orchestrator -> verify libqc semantics, wait for agents\n  └── Orchestrator -> register screen + wire transitions\n\nStep 5: Integration review -> fix import paths, wire MatchQuery\n\nStep 6: Quality gates -> lint, prettier, unit, e2e:check, build:dev all PASS\n\nStep 7: Smart test eval -> unit tests for mapper, add selector-stable test ids\n\nStep 8-10: Commit -> ask user -> push + draft PR (with Closes P11-XXXX)\n```\n\n## PR Review\n\n```\n\u002Forchestrate feat\u002Ftoken-details --review\n\nStage 1: Parallel context\n  ├── shell: fetch diff (9 files, 2 commits)\n  └── explore: categorize domains (2 providers, 3 screens, 4 components)\n\nStage 2: Parallel review (10 agents)\n  ├── Type Safety -> 1 finding (`as Chain` at L42)\n  ├── Pattern Matching -> 2 findings (nested ternary L18, switch on chain kind L67)\n  ├── React Patterns -> 1 finding (`useMemo` at L12)\n  ├── Provider Architecture -> 0 findings\n  ├── Extension Security -> 1 critical (new authenticated screen not in AUTHENTICATED_SCREENS)\n  ├── Screen Navigation -> 0 findings\n  ├── Styling -> 1 finding (`#111827` at L55 - use token)\n  ├── Performance -> 0 findings\n  ├── Code Quality -> 1 finding (magic number `300_000` - extract)\n  └── Architecture -> 0 findings\n\nStage 3: Orchestrator report\n  1 critical, 5 important, 0 nitpick\n  -> REQUEST CHANGES with fix suggestions\n```\n\n---\n\nRun with:\n\n- `\u002Forchestrate P11-1234` - feature delivery\n- `\u002Forchestrate P11-1234 --auto` - skip plan confirmation\n- `\u002Forchestrate feat\u002Fmy-branch --review` - exhaustive PR review\n- `\u002Forchestrate 42 --review` - PR review by number (if the harness recognizes it)\n",{"name":5,"description":7,"argument-hint":24,"disable-model-invocation":25},"[ticket-id or PR branch\u002FURL] [--review] [--auto]",true,"main","94843b628446f86d412a5c5661cf42a26c828b51",".claude\u002Fskills\u002Forchestrate","https:\u002F\u002Fgithub.com\u002Fp-11\u002Fquantum-vault","https:\u002F\u002Fgithub.com\u002Fp-11","https:\u002F\u002Fwww.projecteleven.com","Securing digital assets for the post-quantum era","2026-10-22 17:23:20",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":25},[36,39,42],{"tool":37,"command":38},"npx","npx skills add p-11\u002Fquantum-vault --skill orchestrate",{"tool":40,"command":41},"bunx","bunx skills add p-11\u002Fquantum-vault --skill orchestrate",{"tool":43,"command":44},"pnpm","pnpm dlx skills add p-11\u002Fquantum-vault --skill orchestrate","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fp-11\u002Fquantum-vault\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Forchestrate\u002FSKILL.md",[],[48,54,59,65,71,77],{"skillNo":49,"name":50,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":19},"01M72S75MAGAJ9BT5N5CM75TJ1","resolve-pr-comments","https:\u002F\u002Fgithub.com\u002Fp-11\u002Fquantum-vault\u002Fblob\u002Fmain\u002F.cursor\u002Fskills\u002Fresolve-pr-comments\u002FSKILL.md",[],[],{"skillNo":55,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M72S74P33WDYNZZVQB9PPSYQ","https:\u002F\u002Fgithub.com\u002Fp-11\u002Fquantum-vault\u002Fblob\u002Fmain\u002F.cursor\u002Fskills\u002Forchestrate\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":19},"01M72S73TEY2KR8F7ZKKWE1BTA","finish","https:\u002F\u002Fgithub.com\u002Fp-11\u002Fquantum-vault\u002Fblob\u002Fmain\u002F.cursor\u002Fskills\u002Ffinish\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M72S72X56SDNX8TGRV3MHB5J","figma","https:\u002F\u002Fgithub.com\u002Fp-11\u002Fquantum-vault\u002Fblob\u002Fmain\u002F.cursor\u002Fskills\u002Ffigma\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M72S7218NT062SK66MMZJYJD","delegate","https:\u002F\u002Fgithub.com\u002Fp-11\u002Fquantum-vault\u002Fblob\u002Fmain\u002F.cursor\u002Fskills\u002Fdelegate\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M72S7144W92BM272E9CDAJM6","commit","https:\u002F\u002Fgithub.com\u002Fp-11\u002Fquantum-vault\u002Fblob\u002Fmain\u002F.cursor\u002Fskills\u002Fcommit\u002FSKILL.md",[],[]]