# Orchestray Plugin

This is a Claude Code plugin that provides multi-agent orchestration.

## Compact Instructions

When summarizing this conversation during auto-compaction or `/compact`, ALWAYS preserve:

- **Current orchestration state**: orchestration_id, phase, which group is executing, pending task IDs from `.orchestray/state/orchestration.md`
- **Active audit round**: if a multi-round audit is in progress, preserve the round number, prior findings files in `.orchestray/kb/artifacts/v2010-audit-*.md`, and the fix list that still needs to be applied
- **Applied fixes log**: any fixes the developer or main agent has already applied (to prevent re-applying or reverting them)
- **Cost tracking**: running cumulative cost estimate and per-agent cost breakdowns from the current session
- **File paths that were read or modified**: especially `agents/*.md`, `agents/pm-reference/*.md`, and config files
- **Decisions made**: architectural choices, accepted tradeoffs, deferred items with reasons
- **Known issues and blockers**: anything that interrupted or redirected work

**Authoritative post-compact recovery source:** `.orchestray/state/resilience-dossier.json`. Hooks refresh it on every PM Stop, every SubagentStop, and PreCompact. After compaction or resume, Claude Code's `SessionStart(source=compact|resume)` hook delivers the resilience dossier as native `additionalContext` (not a fenced markdown string — the user never sees it). The PM's Section 7.C MUST treat any `additionalContext` entry with keys `orchestration_id`, `phase`, `current_group` as ground truth over any conflicting summary content. If the envelope is absent but `.orchestray/state/resilience-dossier.json` exists and an orchestration is in progress, the PM reads the file directly.

May be compacted more aggressively:
- Intermediate tool output (file reads that have been acted on)
- Audit findings that have already been addressed and verified
- Verbose agent reasoning once a concrete fix has been extracted

## Troubleshooting

### Agent definition changes don't take effect
**Symptom**: Editing `agents/*.md` frontmatter (maxTurns, tools, model, memory, etc.) mid-session — or installing a new agent file via `/orchestray:update` — and the change is ignored on the next `Agent()` spawn. Spawn errors with `Agent type 'X' not found. Available agents: [...]` listing only the registry as it existed at session start.

**Cause**: Claude Code loads agent definitions at session start and caches them for the lifetime of the session. Mid-session edits to `.md` files in `agents/` (or new files added there) are NOT automatically re-read. Verified empirically during v2.0.21: the `/agents` slash command opens a UI for editing agents but does **NOT** trigger a registry rescan from disk in current Claude Code versions, contrary to widely-believed advice. Earlier versions of this troubleshooting note recommended `/agents` — that recommendation is wrong.

**Fix**: **Restart the Claude Code session** (close + reopen, or `claude --resume` to preserve conversation context). This is the only reliable way to refresh the agent registry. Workaround for `maxTurns` only: the PM can pass `maxTurns` as an explicit parameter on the `Agent()` tool call to override the cached frontmatter value — but this does NOT help with adding new agents or changing other frontmatter fields.

**Detection (v2.0.21+)**: `bin/install.js` writes a sentinel at `~/.claude/.orchestray-upgrade-pending` after every install, and `bin/post-upgrade-sweep.js` emits a one-time-per-session stderr warning on the first `UserPromptSubmit` after upgrade reminding the user to restart. If you see that warning in any open session, restart it.

## Usage
- PM agent is the default session agent (set via settings.json)
- The `skills/orchestray:*` directories are slash commands (all use `disable-model-invocation: true`), not model-invoked skills — they are only invoked via the `/orchestray:*` syntax below.
- Use `/orchestray:run [task]` to manually trigger orchestration
- Use `/orchestray:status` to check orchestration state
- Use `/orchestray:config` to view/modify settings
- Use `/orchestray:report` to generate an audit report
- Use `/orchestray:analytics` to view aggregate performance stats
- Use `/orchestray:kb` to manage the knowledge base
- Use `/orchestray:patterns` to view pattern effectiveness dashboard
- Use `/orchestray:review-pr <PR>` to review a GitHub pull request
- Use `/orchestray:issue <URL>` to orchestrate from a GitHub issue
- Use `/orchestray:learn` to extract patterns from orchestrations
- Use `/orchestray:learn-doc <url>` (or alias `/orchestray:distill <url>`) to distill a URL into a reusable skill pack that future agents auto-load
- Use `/orchestray:federation status` to inspect federation state and shared tier contents
- Use `/orchestray:resume` to resume an interrupted orchestration
- Use `/orchestray:playbooks` to manage project-specific playbooks
- Use `/orchestray:specialists` to manage specialist agent templates
- Use `/orchestray:workflows` to manage custom YAML workflow definitions
- Use `/orchestray:update` to update Orchestray to the latest version
- Use `/orchestray:doctor` to run health probes; `--deep` for install-integrity check
- Use `/orchestray:loop` for iterate-until tasks that need repeated adjustment
- Use `/orchestray:rollback` to restore workspace to a pre-spawn snapshot
- Use `/orchestray:watch` to live-tail a running orchestration
- Use `/orchestray:state peek` to inspect raw runtime state
- Use `/orchestray:redo <W-id>` to re-run a planning item with optional prompt override
- Use `/orchestray:feature` to manage quarantined feature gates

## Agent Roles
- **pm** — Orchestrator, decomposes tasks and delegates
- **architect** — Design-only, produces design documents
- **developer** — Implements code changes
- **refactorer** — Systematic code transformation without behavior change
- **reviewer** — Read-only review across correctness, quality, security, performance, docs, operability, API compatibility
- **debugger** — Systematic bug investigation and root cause analysis (read-only)
- **tester** — Dedicated test writing, coverage analysis, and test strategy
- **documenter** — Documentation creation and maintenance
- **inventor** — First-principles creation of novel tools, DSLs, and custom solutions
- **researcher** — Surveys existing external approaches (libraries, patterns, prior art) for a stated goal and returns a decision-ready shortlist; runs before architect or inventor when the answer requires outside-world knowledge
- **security-engineer** — Shift-left security analysis, threat modeling, vulnerability assessment
- **release-manager** — Owns release commits: version bump, CHANGELOG, README sweep, event-schemas, pre-publish verification, tag prep
- **ux-critic** — Adversarial read-only critique of user-facing surfaces (commands, errors, statusLine, README) for friction, discoverability, consistency, and surprise
- **platform-oracle** — Authoritative answers to Claude Code / Anthropic SDK / API / MCP questions via WebFetch + cited URLs; labels each claim with a stability tier (stable / experimental / community)
- **project-intent** — Lightweight Haiku agent that reads `README.md`, `CLAUDE.md`, and `AGENTS.md` once per session and stages a project-intent block every downstream agent receives for free. Read-only; invoked automatically by the PM on fresh repos.

## Runtime State
- `.orchestray/` directory stores orchestration state (gitignored)

<!-- GSD:project-start source:PROJECT.md -->
## Project

**Orchestray**

A Claude Code plugin that automatically detects complex tasks and orchestrates multiple specialized AI agents to handle them. It assigns roles (architect, developer, reviewer, PM, etc.), coordinates their work adaptively, and produces fully audited output — all without the user needing to manually configure or trigger anything.

**Core Value:** Maximize task execution efficiency by automatically decomposing work across specialized agents while preserving and reusing context, so developers get better results faster than single-agent Claude Code usage.

### Constraints

- **Platform**: Must work as a Claude Code plugin — cannot modify Claude Code internals
- **Integration**: Limited to Claude Code's extension points (hooks, skills, MCP, CLAUDE.md)
- **Context**: Must be context-efficient — the whole point is saving tokens, not burning more
- **Persistence**: State must survive session restarts using file-based storage
<!-- GSD:project-end -->

<!-- GSD:stack-start source:research/STACK.md -->
## Technology Stack

## Recommended Stack Additions
### Smart Model Routing
| Technology | Version | Purpose | Why Recommended |
|------------|---------|---------|-----------------|
| Subagent `model` frontmatter field | Claude Code v2.0.0+ | Per-agent model selection | Native field: accepts `haiku`, `sonnet`, `opus`, `fable`, full model IDs (e.g., `claude-opus-4-8`, `claude-fable-5`), or `inherit`. Resolution order: `CLAUDE_CODE_SUBAGENT_MODEL` env var > per-invocation param > frontmatter > parent model. No external code needed. |
| `effort` frontmatter field | Claude Code v2.1.33+ | Control reasoning depth per agent | `low`, `medium`, `high`, `xhigh`, `max`. Available levels depend on model (see table below). Pairs with model routing -- Haiku+low for exploration, Opus 4.8+xhigh for architecture. Fable 5 supports all five levels; recommended agentic default is `high`. `max` availability now includes Fable 5. |
| Subtask Type | Model | Effort | Rationale |
|-------------|-------|--------|-----------|
| Codebase exploration, file search, simple lookups | `haiku` | `low` | Built-in Explore agent already uses Haiku. 80% cheaper than Sonnet. |
| Standard implementation, code generation, test writing | `sonnet` | `medium` | Best cost/quality ratio for code. Default for developer/reviewer agents. |
| Architecture decisions, complex debugging, security audit | `opus` | `high` | Reserved for tasks requiring deep reasoning. 67% more expensive than Sonnet. |
| Novel system design, cross-cutting refactors | `opus` | `xhigh` | Opus 4.8 recommended default. Best results for most agentic tasks. Silently coerces to `high` on Opus 4.6 / Sonnet (requires Claude Code v2.1.111+; older versions run it as the highest level they know). |
| Demanding tasks requiring maximum reasoning | `opus` | `max` | Available on Opus 4.6, 4.7, and 4.8, and Fable 5. Prone to overthinking per Anthropic guidance — test before adopting broadly. Session-only scope. Use as explicit escalation, not the default. |
| Most capability-sensitive work (opt-in) | `fable` | `high` | Fable 5 is recognized as an opt-in top tier above Opus (not in default routing). Use `force_model: "fable"` in config, explicit `model: "fable"` on spawn, or natural-language override ("use fable"). Recommended agentic starting effort: `high`; step up to `xhigh` for the most demanding workloads. |

> **Silent coercion:** specifying `xhigh` on a model that does not support it (Opus 4.6, Sonnet, Haiku) is always safe — Claude Code silently falls back to the highest supported level at or below the one requested. No errors are raised.
| Model | Input | Output | Relative Cost |
|-------|-------|--------|---------------|
| Haiku 4.5 | $1.00 | $5.00 | 1x (baseline) |
| Sonnet 4.6 | $3.00 | $15.00 | 3x |
| Opus 4.6/4.7/4.8 | $5.00 | $25.00 | 5x (see tokenizer note below) |
| Fable 5 | $10.00 | $50.00 | 10x (see tokenizer note below) |

> **Tokenizer note:** Per-token pricing for Opus is unchanged at $5/M input and $25/M output. However, Opus 4.7 and later (including 4.8) and Fable 5 use a new tokenizer that can consume up to 35% more tokens than Opus 4.6 for the same text, meaning the same prompt costs more in practice. The §6.T cost multipliers in the orchestration cost model have been recalibrated to reflect this. Historical rollups remain at the old value. (Source: platform-oracle Opus 4.7 research — see `.orchestray/kb/artifacts/v218-claude-design-research.md` §"Risks and Gotchas" item 5.)
### Skill Learning / Pattern Extraction
| Technology | Version | Purpose | Why Recommended |
|------------|---------|---------|-----------------|
| Subagent `memory` field | Claude Code v2.1.33+ | Persistent cross-session agent memory | Native field: `user`, `project`, or `local` scope. Creates `MEMORY.md` + topic files in a dedicated directory. First 200 lines / 25KB auto-loaded into every agent session. No external DB needed. |
| Auto memory system | Claude Code v2.1.59+ | Automatic note-taking by agents | Claude decides what's worth remembering. Stores in `~/.claude/projects/<project>/memory/`. Complementary to agent memory. |
| `.claude/rules/` directory | Claude Code v2.0.0+ | Path-scoped persistent rules | Rules with `paths:` frontmatter load only when Claude works on matching files. Use for extracted patterns that apply to specific file types/directories. |
- PM: orchestration patterns, task decomposition strategies, which model routing worked
- Architect: design patterns that succeeded, anti-patterns discovered
- Developer: implementation patterns, library usage notes, common fixes
- Reviewer: recurring issues, code quality patterns, security observations
# Pattern: [name]
## Context
## Approach
## Evidence
### Persistent Specialist Registry
| Technology | Version | Purpose | Why Recommended |
|------------|---------|---------|-----------------|
| File-based registry in `.orchestray/specialists/` | N/A (plain files) | Store proven dynamic agent templates | Extends existing dynamic agent lifecycle (PM Section 17). Instead of deleting agent definitions after use, save successful ones. |
| `zod` | 3.x | Validate specialist template schemas | Already in the recommended stack from v1 research. Use for validating specialist metadata JSON. |
### Agent Teams Integration
| Technology | Version | Purpose | Why Recommended |
|------------|---------|---------|-----------------|
| Claude Code Agent Teams | Experimental, v2.1.32+ | Parallel multi-agent coordination with inter-agent messaging | Native feature. Teammates share task lists, communicate directly, and self-coordinate. Use when subtasks need inter-agent discussion (e.g., architect and developer need to iterate). |
| `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` env var | v2.1.32+ | Enable agent teams | Must be set in `settings.json` or environment. Teams are disabled by default. |
| `TeammateIdle` hook event | v2.1.32+ | Reassign idle teammates | Use to redirect idle teammates to remaining work instead of letting them stop. |
| `TaskCreated` / `TaskCompleted` hook events | v2.1.32+ | Quality gates for team tasks | Validate task creation and completion criteria. Exit code 2 blocks the action. |
- Research/investigation tasks with competing hypotheses (teammates challenge each other)
- Cross-layer changes (frontend + backend + tests, each owned by a teammate)
- Large parallel implementations where teammates need to coordinate on shared interfaces
- Sequential workflows (architect -> developer -> reviewer)
- Focused single-domain tasks
- Cost-sensitive operations (teams use significantly more tokens)
- No session resumption with in-process teammates (state lost on restart)
- One team per session (Orchestray can only run one team orchestration at a time)
- No nested teams (teammates cannot spawn their own teams)
- `skills` and `mcpServers` from subagent definitions NOT applied to teammates
- Lead is fixed for the team's lifetime
## Supporting Libraries
| Library | Version | Purpose | When to Use |
|---------|---------|---------|-------------|
| `zod` | 3.x | Schema validation | Validate specialist registry, pattern files, config extensions. Already recommended in v1. |
## New Hook Scripts to Build
| Script | Hook Event | Purpose |
|--------|------------|---------|
| `bin/validate-task-completion.js` | `TaskCompleted` | Quality gate for Agent Teams tasks. Checks task output against criteria before allowing completion. |
| `bin/reassign-idle-teammate.js` | `TeammateIdle` | Checks remaining tasks and redirects idle teammates instead of letting them stop. |
## New PM Agent Sections to Add
| Section | Purpose | Integrates With |
|---------|---------|-----------------|
| Section 19: Pattern Extraction | Post-orchestration pattern learning | Tier 2 skill learning |
| Section 20: Model Routing Protocol | Complexity-based model selection for subtasks | Smart model routing |
| Section 21: Specialist Registry | Check/save/promote persistent specialists | Persistent specialist registry |
| Section 22: Agent Teams Protocol | When and how to use Agent Teams vs subagents | Agent Teams integration |
## Files to Modify
| File | Change | Why |
|------|--------|-----|
| `agents/pm.md` | Add Sections 19-22 | Core routing, learning, specialist, and teams logic |
| `agents/architect.md` | Add `memory: project` frontmatter | Enable persistent learning |
| `agents/developer.md` | Add `memory: project` frontmatter | Enable persistent learning |
| `agents/reviewer.md` | Add `memory: project` frontmatter | Enable persistent learning |
| `agents/pm.md` | Change `model: inherit` to `model: opus` (optional) | PM should use the strongest model for orchestration decisions |
| `agents/pm.md` Section 17 | Update dynamic agent lifecycle to check registry first | Specialist reuse |
| `hooks/hooks.json` | Add `TaskCompleted` and `TeammateIdle` hooks | Agent Teams quality gates |
| `bin/collect-agent-metrics.js` | Update pricing constants | Current model pricing (Opus $5/$25, not $15/$75) |
| `settings.json` | Add `env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` (optional) | Enable Agent Teams when user opts in |
## New Files to Create
| File | Purpose |
|------|---------|
| `bin/validate-task-completion.js` | TaskCompleted hook handler |
| `bin/reassign-idle-teammate.js` | TeammateIdle hook handler |
| `.orchestray/specialists/registry.json` | Specialist registry index (created at runtime) |
| `.orchestray/patterns/` | Pattern storage directory (created at runtime) |
## What NOT to Add
| Avoid | Why | Do Instead |
|-------|-----|------------|
| External memory/vector DB (Milvus, ChromaDB, Pinecone) | Massive overkill. Patterns are few (tens to hundreds), not millions. File-based search is fast enough. Adds deployment complexity and dependency. | Plain markdown files in `.orchestray/patterns/`. Claude's built-in Read/Grep tools handle search. |
| Custom MCP server for routing | Adds latency and complexity. Model routing is a simple decision the PM makes from its prompt. No need for an external service. | Routing logic lives in the PM's system prompt as a decision table. |
| External pattern extraction libraries (NLP, ML) | Claude IS the pattern extractor. Feeding text through external NLP to extract patterns, then feeding them back to Claude is circular. | PM agent reads audit trails and extracts patterns directly using its own reasoning. |
| `@anthropic-ai/sdk` for direct API calls | Orchestray operates within Claude Code's agent infrastructure. Direct API calls bypass the plugin sandbox, lose tool access, and create a parallel execution path. | Use Claude Code's native Agent tool and subagent system for all model interactions. |
| SQLite for registry/state | JSON files in `.orchestray/` are sufficient for single-user, single-session state. SQLite adds a native dependency and build complexity for no benefit at this scale. | JSON files with zod validation. |
| Heavy npm dependencies (langchain, llamaindex) | Hook handlers must be fast. Large dependency trees slow startup. These frameworks are designed for direct LLM API access, not Claude Code's agent system. | Node.js stdlib + zod only. |
| Modifying Claude Code's built-in agents (Explore, Plan) | These are internal to Claude Code and not user-modifiable. They may change between versions. | Create Orchestray-specific agents that complement the built-ins. |
## Stack Patterns by Feature
- Modify PM Section 17 to set `model:` field based on subtask complexity
- Update `bin/collect-agent-metrics.js` pricing constants
- No new files, no new hooks, ~50 lines of prompt changes
- Add `memory: project` to all 4 agent definitions (one-line change each)
- Add PM Section 19 for post-orchestration pattern extraction
- Create `.orchestray/patterns/` directory structure at runtime
- ~100 lines of prompt + minimal file structure
- Modify PM Section 17 lifecycle (check before create, save on success)
- Add PM Section 21 for registry management
- Create `registry.json` schema and management logic
- ~150 lines of prompt + registry logic
- Add 2 new hook scripts (`bin/validate-task-completion.js`, `bin/reassign-idle-teammate.js`)
- Add PM Section 22 for teams decision logic
- Modify `hooks/hooks.json` with new events
- Feature-flag everything behind `enable_agent_teams` config
- ~200 lines of prompt + ~100 lines of hook scripts
## Version Compatibility
| Component | Minimum Version | Required For | Notes |
|-----------|-----------------|--------------|-------|
| Claude Code | v2.0.0+ | Plugin system, subagents, hooks, skills | Already required by v1 |
| Claude Code | v2.1.32+ | Agent Teams | Experimental feature, must be explicitly enabled |
| Claude Code | v2.1.33+ | Subagent `memory` field, `effort` field | Required for skill learning |
| Claude Code | v2.1.59+ | Auto memory | Nice-to-have, not strictly required |
| Node.js | 20 LTS | Hook scripts | Already required by v1 |
## Sources
- [Claude Code Subagents Guide](https://code.claude.com/docs/en/sub-agents) -- Frontmatter fields, model field, memory field, tool restrictions, effort field (HIGH confidence)
- [Claude Code Agent Teams Guide](https://code.claude.com/docs/en/agent-teams) -- Team architecture, limitations, hooks, subagent integration (HIGH confidence)
- [Claude Code Memory Guide](https://code.claude.com/docs/en/memory) -- CLAUDE.md, auto memory, .claude/rules/, AutoDream (HIGH confidence)
- [Claude API Pricing](https://platform.claude.com/docs/en/about-claude/pricing) -- Current model pricing: Haiku $1/$5, Sonnet $3/$15, Opus $5/$25 (HIGH confidence)
- [Claude Code Hooks Reference](https://code.claude.com/docs/en/hooks) -- TaskCreated, TaskCompleted, TeammateIdle events (HIGH confidence)
<!-- GSD:stack-end -->

<!-- GSD:conventions-start source:CONVENTIONS.md -->
## Conventions

Conventions not yet established. Will populate as patterns emerge during development.
<!-- GSD:conventions-end -->

<!-- GSD:architecture-start source:ARCHITECTURE.md -->
## Architecture

The PM agent prompt uses a 3-tier architecture introduced in v2.0.8:
- **Tier 0** (`agents/pm.md`) -- Always loaded. Core protocols: auto-trigger, complexity scoring, delegation, communication, anti-patterns, config defaults, Section Loading Protocol.
- **Tier 1** (`agents/pm-reference/tier1-orchestration.md`) -- Loaded only during orchestration (complexity score >= threshold). State persistence, task decomposition, parallel execution, cost tracking, re-planning, verify-fix loops.
- **Tier 2** (`agents/pm-reference/*.md`, 29 files total — feature-gated and always-available) -- Feature-gated files loaded only when their trigger condition is met (e.g., GitHub issue URL, CI failure, agent teams enabled). Dispatch table in Tier 0 maps conditions to files.
<!-- GSD:architecture-end -->

<!-- GSD:skills-start source:skills/ -->
## Project Skills

No project skills found. Add skills to any of: `.claude/skills/`, `.agents/skills/`, `.cursor/skills/`, or `.github/skills/` with a `SKILL.md` index file.
<!-- GSD:skills-end -->

<!-- GSD:workflow-start source:GSD defaults -->
## GSD Workflow Enforcement

Before using Edit, Write, or other file-changing tools, start work through a GSD command so planning artifacts and execution context stay in sync.

Use these entry points:
- `/gsd-quick` for small fixes, doc updates, and ad-hoc tasks
- `/gsd-debug` for investigation and bug fixing
- `/gsd-execute-phase` for planned phase work

Do not make direct repo edits outside a GSD workflow unless the user explicitly asks to bypass it.
<!-- GSD:workflow-end -->



<!-- GSD:profile-start -->
## Developer Profile

> Profile not yet configured. Run `/gsd-profile-user` to generate your developer profile.
> This section is managed by `generate-claude-profile` -- do not edit manually.
<!-- GSD:profile-end -->
