diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 490f9ab8..1f330b5e 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -12,7 +12,7 @@ "name": "PACT", "source": "./pact-plugin", "description": "PACT Framework - VSM-enhanced orchestration with specialist agents and viability sensing", - "version": "2.8.0", + "version": "3.0.0", "author": { "name": "ProfSynapse" }, diff --git a/pact-plugin/.claude-plugin/plugin.json b/pact-plugin/.claude-plugin/plugin.json index 5b58c4ab..41dd4bf7 100644 --- a/pact-plugin/.claude-plugin/plugin.json +++ b/pact-plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "PACT", - "version": "2.8.0", + "version": "3.0.0", "description": "PACT Framework - Prepare, Architect, Code, Test methodology with VSM-enhanced orchestration, specialist agents, and viability sensing for systematic AI-assisted development", "author": { "name": "ProfSynapse", @@ -25,7 +25,6 @@ "commands": [ "./commands/orchestrate.md", "./commands/comPACT.md", - "./commands/rePACT.md", "./commands/imPACT.md", "./commands/peer-review.md", "./commands/plan-mode.md", diff --git a/pact-plugin/CLAUDE.md b/pact-plugin/CLAUDE.md index dccf1d26..f898aeb3 100644 --- a/pact-plugin/CLAUDE.md +++ b/pact-plugin/CLAUDE.md @@ -104,7 +104,7 @@ Delegate to `pact-memory-agent` with a clear intent: - **Save**: `"Save memory: [context of what was done, decisions, lessons]"` - **Search**: `"Retrieve memories about: [topic/query]"` -See **Always Run Agents in Background** for the mandatory `run_in_background=true` requirement. +See **Team Lifecycle** in the PACT Agent Orchestration section for how teammates are spawned. #### Three-Layer Memory Architecture @@ -241,12 +241,12 @@ When making decisions, consider which horizon applies. Misalignment indicates mo | Writing, editing, refactoring code | coders | | Writing or running tests | test engineer | -⚠️ Bug fixes, logic, refactoring, tests—NOT exceptions. **DELEGATE**. -⚠️ "Simple" tasks, post-review cleanup—NOT exceptions. **DELEGATE**. -⚠️ Urgent fixes, production issues—NOT exceptions. **DELEGATE**. -⚠️ Rationalizing "it's small", "I know exactly how", "it's quick" = failure mode. **DELEGATE**. +Bug fixes, logic, refactoring, tests—NOT exceptions. **DELEGATE**. +"Simple" tasks, post-review cleanup—NOT exceptions. **DELEGATE**. +Urgent fixes, production issues—NOT exceptions. **DELEGATE**. +Rationalizing "it's small", "I know exactly how", "it's quick" = failure mode. **DELEGATE**. -**Checkpoint**: Knowing the fix ≠ permission to fix. **DELEGATE**. +**Checkpoint**: Knowing the fix does not equal permission to fix. **DELEGATE**. **Checkpoint**: Need to understand the codebase? Use **Explore agent** freely. Starting a PACT cycle is where true delegation begins. @@ -258,39 +258,39 @@ Explicit user override ("you code this, don't delegate") should be honored; casu #### Invoke Multiple Specialists Concurrently -> ⚠️ **DEFAULT TO CONCURRENT**: When delegating, dispatch multiple specialists together in a single response unless tasks share files or have explicit dependencies. This is not optional—it's the expected mode of orchestration. +> **DEFAULT TO CONCURRENT**: When spawning teammates, dispatch multiple specialists together in a single response unless tasks share files or have explicit dependencies. This is not optional—it's the expected mode of orchestration. -**Core Principle**: If specialist tasks can run independently, invoke them at once. Sequential dispatch is only for tasks with true dependencies. +**Core Principle**: If specialist tasks can run independently, spawn them at once. Sequential dispatch is only for tasks with true dependencies. -**How**: Include multiple `Task` tool calls in a single response. Each specialist runs concurrently. +**How**: Include multiple `Task` tool calls in a single response. Each teammate runs concurrently within the team. | Scenario | Action | |----------|--------| -| Same phase, independent tasks | Dispatch multiple specialists simultaneously | -| Same domain, multiple items (3 bugs, 5 endpoints) | Invoke multiple specialists of same type at once | -| Different domains touched | Dispatch specialists across domains together | -| Tasks share files or have dependencies | Dispatch sequentially (exception, not default) | +| Same phase, independent tasks | Spawn multiple teammates simultaneously | +| Same domain, multiple items (3 bugs, 5 endpoints) | Spawn multiple teammates of same type at once | +| Different domains touched | Spawn teammates across domains together | +| Tasks share files or have dependencies | Spawn sequentially (exception, not default) | #### Agent Task Tracking -> ⚠️ **AGENTS MUST HAVE TANDEM TRACKING TASKS**: Whenever invoking a specialist agent, you must also track what they are working on by using the Claude Code Task Management system (TaskCreate, TaskUpdate, TaskList, TaskGet). +> **TEAMMATES MUST HAVE TRACKING TASKS**: Whenever spawning a teammate, you must also track what they are working on by using the Claude Code Task Management system (TaskCreate, TaskUpdate, TaskList, TaskGet). -**Tracking Task lifecycle**: +**Task lifecycle with Agent Teams**: | Event | Task Operation | |-------|----------------| -| Before dispatching agent | `TaskCreate(subject, description, activeForm)` | -| After dispatching agent | `TaskUpdate(taskId, status: "in_progress", addBlocks: [PARENT_TASK_ID])` | -| Agent completes (handoff) | `TaskUpdate(taskId, status: "completed")` | -| Agent reports blocker | `TaskCreate(subject: "BLOCKER: ...")` then `TaskUpdate(agent_taskId, addBlockedBy: [blocker_taskId])` | -| Agent reports algedonic signal | `TaskCreate(subject: "[HALT\|ALERT]: ...")` then amplify scope via `addBlockedBy` on phase/feature task | +| Before spawning teammate | `TaskCreate(subject, description, owner="{teammate-name}")` | +| Teammate claims task | Teammate calls `TaskUpdate(taskId, status: "in_progress")` | +| Teammate completes | Teammate calls `TaskUpdate(taskId, status: "completed")` + sends HANDOFF via SendMessage | +| Teammate reports blocker | Teammate sends BLOCKER via SendMessage to "team-lead" | +| Teammate reports algedonic signal | Teammate sends HALT (broadcast) or ALERT (direct message to "team-lead") | -**Key principle**: Agents communicate status via structured text in their responses. The orchestrator reads agent output and translates it into Task operations. This separation ensures Task state is always managed by the process that has the tools. +**Key principle**: Teammates self-manage their tasks using Task tools directly (TaskUpdate, TaskList, TaskCreate). The orchestrator creates top-level feature and phase tasks. Teammates claim, update, and complete their own agent-level tasks. The orchestrator monitors progress via TaskList and receives HANDOFFs via SendMessage. ##### Signal Task Handling -When an agent reports a blocker or algedonic signal via text: +When a teammate reports a blocker or algedonic signal via SendMessage: 1. Create a signal Task (blocker or algedonic type) -2. Block the agent's task via `addBlockedBy` +2. Block the teammate's task via `addBlockedBy` 3. For algedonic signals, amplify scope: - ALERT → block current phase task - HALT → block feature task (stops all work) @@ -341,44 +341,42 @@ This is not punitive—it's corrective. The goal is maintaining role boundaries. ### Delegate to Specialist Agents -When delegating a task, these specialist agents are available to execute PACT phases: -- **📚 pact-preparer** (Prepare): Research, documentation, requirements gathering -- **🏛️ pact-architect** (Architect): System design, component planning, interface definition -- **💻 pact-backend-coder** (Code): Server-side implementation -- **🎨 pact-frontend-coder** (Code): Client-side implementation -- **🗄️ pact-database-engineer** (Code): Data layer implementation -- **⚡ pact-n8n** (Code): Creates JSONs for n8n workflow automations -- **🧪 pact-test-engineer** (Test): Testing and quality assurance -- **🧠 pact-memory-agent** (Memory): Memory management, context preservation, post-compaction recovery - -### Always Run Agents in Background - -> ⚠️ **MANDATORY**: Every `Task` call to a specialist agent MUST include `run_in_background=true`. No exceptions. - -**Why always background?** -- Agent work should never block the user conversation -- The orchestrator can continue coordinating while agents execute -- Multiple specialists can run concurrently -- Results are reported back when ready - -```python -# Correct - always use run_in_background=true -Task( - subagent_type="pact-backend-coder", - run_in_background=true, # ← REQUIRED - never omit or set to false - prompt="Implement the user authentication endpoint..." -) -``` +When delegating a task, these specialist agents are available as teammates: +- **pact-preparer** (Prepare): Research, documentation, requirements gathering +- **pact-architect** (Architect): System design, component planning, interface definition +- **pact-backend-coder** (Code): Server-side implementation +- **pact-frontend-coder** (Code): Client-side implementation +- **pact-database-engineer** (Code): Data layer implementation +- **pact-n8n** (Code): Creates JSONs for n8n workflow automations +- **pact-test-engineer** (Test): Testing and quality assurance +- **pact-memory-agent** (Memory): Memory management, context preservation, post-compaction recovery + +### Team Lifecycle + +The session team is created at session start by the `session_init.py` hook, which instructs the orchestrator to call `TeamCreate`. The team persists for the entire session and is shared across commands. + +**If the team was not created** (e.g., hook failure, manual session), call `TeamCreate(team_name="{feature-slug}")` before spawning teammates. + +**Teammate lifecycle**: +- Teammates are spawned per phase into the session team using `Task` with `team_name` and `name` parameters +- Between phases, shut down current teammates before spawning next-phase teammates +- The team itself persists for the entire session + +**Naming convention**: `{role}-{number}` (e.g., `"backend-1"`, `"architect-2"`, `"preparer-1"`). For scoped orchestration: `"scope-{scope}-{role}"` (e.g., `"scope-auth-backend"`). + +**Plan Approval**: All teammates are spawned with `mode="plan"`. Review all plans for a phase before approving any to identify conflicts or gaps. + +**Shutting down teammates**: Between phases, shut down all current-phase teammates and wait for acknowledgment before spawning next-phase teammates. ### Recommended Agent Prompting Structure -Use this structure in the `prompt` field to ensure agents have adequate context: +Use this structure in the `prompt` field to ensure teammates have adequate context: **CONTEXT** [Brief background, what phase we are in, and relevant state] **MISSION** -[What you need the agent to do, how it will know it's completed its job] +[What you need the teammate to do, how it will know it's completed its job] **INSTRUCTIONS** 1. [Step 1] @@ -393,7 +391,7 @@ A list of things that include the following: #### Expected Agent HANDOFF Format -Every agent ends their response with a structured HANDOFF. Expect this format: +Every teammate ends their work with a structured HANDOFF delivered via SendMessage to "team-lead". Expect this format: ``` HANDOFF: @@ -409,7 +407,7 @@ HANDOFF: All five items are always present. Use this to update Task metadata and inform subsequent phases. -If the `validate_handoff` hook warns about a missing HANDOFF, extract available context from the agent's response and update the Task accordingly. +If a teammate's HANDOFF is missing items, send a message asking for the missing information before proceeding. ### How to Delegate @@ -417,17 +415,14 @@ Use these commands to trigger PACT workflows for delegating tasks: - `/PACT:plan-mode`: Multi-agent planning consultation before implementation (no code changes) - `/PACT:orchestrate`: Delegate a task to PACT specialist agents (multi-agent, full ceremony) - `/PACT:comPACT`: Delegate a focused task to a single specialist (light ceremony) -- `/PACT:rePACT`: Recursive nested PACT cycle for complex sub-tasks (single or multi-domain) - `/PACT:imPACT`: Triage when blocked (Redo prior phase? Additional agents needed?) - `/PACT:peer-review`: Peer review of current work (commit, create PR, multi-agent review) See @~/.claude/protocols/pact-plugin/pact-workflows.md for workflow details. **How to Handle Blockers** -- If an agent hits a blocker, they are instructed to stop working and report the blocker to you -- As soon as a blocker is reported, execute `/PACT:imPACT` with the report as the command argument - -When delegating tasks to agents, remind them of their blocker-handling protocol +- If a teammate hits a blocker, they send a BLOCKER message via SendMessage to "team-lead" +- As soon as a blocker is received, execute `/PACT:imPACT` with the report as the command argument ### Agent Workflow @@ -435,23 +430,24 @@ When delegating tasks to agents, remind them of their blocker-handling protocol **Optional**: Run `/PACT:plan-mode` first for complex tasks. Creates plan in `docs/plans/` with specialist consultation. When `/PACT:orchestrate` runs, it checks for approved plans and passes relevant sections to each phase. -To invoke specialist agents, follow this sequence: -1. **PREPARE Phase**: Invoke `pact-preparer` → outputs to `docs/preparation/` -2. **ARCHITECT Phase**: Invoke `pact-architect` → outputs to `docs/architecture/` -3. **CODE Phase**: Invoke relevant coders (includes smoke tests + decision log) -4. **TEST Phase**: Invoke `pact-test-engineer` (for all substantive testing) +To execute a task, follow this sequence: +1. **Team exists** (created at session start by hook, or manually via TeamCreate) +2. **PREPARE Phase**: Spawn `pact-preparer` teammate(s) → outputs to `docs/preparation/` +3. **ARCHITECT Phase**: Spawn `pact-architect` teammate(s) → outputs to `docs/architecture/` +4. **CODE Phase**: Spawn relevant coder teammate(s) (includes smoke tests + decision log) +5. **TEST Phase**: Spawn `pact-test-engineer` teammate(s) (for all substantive testing) -Within each phase, invoke **multiple specialists concurrently** for non-conflicting tasks. +Within each phase, spawn **multiple teammates concurrently** for non-conflicting tasks. Between phases, shut down current teammates before spawning next-phase teammates. -> ⚠️ **Single domain ≠ single agent.** "Backend domain" with 3 bugs = 3 backend-coders in parallel. Default to concurrent dispatch unless tasks share files or have dependencies. +> **Single domain does not equal single teammate.** "Backend domain" with 3 bugs = 3 backend-coders in parallel. Default to concurrent spawning unless tasks share files or have dependencies. **After all phases complete**: Run `/PACT:peer-review` to create a PR. ### PR Review Workflow -Invoke **at least 3 agents in parallel**: -- **pact-architect**: Design coherence, architectural patterns, interface contracts, separation of concerns -- **pact-test-engineer**: Test coverage, testability, performance implications, edge cases +Spawn **at least 3 reviewer teammates** into the session team: +- **pact-architect** (name: `"architect-reviewer"`): Design coherence, architectural patterns, interface contracts, separation of concerns +- **pact-test-engineer** (name: `"test-reviewer"`): Test coverage, testability, performance implications, edge cases - **Domain specialist coder(s)**: Implementation quality specific to PR focus - Select the specialist(s) based on PR focus: - Frontend changes → **pact-frontend-coder** (UI implementation quality, accessibility, state management) @@ -459,8 +455,11 @@ Invoke **at least 3 agents in parallel**: - Database changes → **pact-database-engineer** (Query efficiency, schema design, data integrity) - Multiple domains → Specialist for domain with most significant changes, or all relevant specialists if multiple domains are equally significant -After agent reviews completed: +Reviewer teammates deliver their findings via SendMessage to "team-lead". + +After reviewer HANDOFFs received: - Synthesize findings and recommendations in `docs/review/` (note agreements and conflicts) +- Shut down all reviewer teammates - Execute `/PACT:pin-memory` --- diff --git a/pact-plugin/README.md b/pact-plugin/README.md index e303949b..2a575343 100644 --- a/pact-plugin/README.md +++ b/pact-plugin/README.md @@ -1,9 +1,15 @@ # PACT Framework Plugin -> **Version**: 2.0.0 +> **Version**: 3.0.0 > **License**: MIT -VSM-enhanced orchestration framework for AI-assisted software development with Claude Code. +VSM-enhanced orchestration framework for AI-assisted software development with Claude Code. PACT uses Agent Teams for multi-agent orchestration, spawning specialist teammates that communicate via SendMessage for coordinated development workflows. + +## Prerequisites + +- **Claude Code** CLI installed and configured +- **Agent Teams** enabled (experimental feature). Enable via Claude Code settings before using PACT. +- **Delegate Mode** (optional, recommended): Press Shift+Tab to enable Delegate Mode, which restricts the orchestrator to coordination-only tools. This adds platform-level enforcement on top of PACT's convention-based delegation rules. ## Installation @@ -66,8 +72,8 @@ After restart, test with: | Component | Description | |-----------|-------------| -| **8 Specialist Agents** | Preparer, Architect, Backend/Frontend/Database Coders, n8n, Test Engineer, Memory Agent | -| **8 Commands** | orchestrate, comPACT, rePACT, plan-mode, imPACT, peer-review, pin-memory, wrap-up | +| **8 Specialist Agents** | Preparer, Architect, Backend/Frontend/Database Coders, n8n, Test Engineer, Memory Agent (spawned as teammates) | +| **7 Commands** | orchestrate, comPACT, plan-mode, imPACT, peer-review, pin-memory, wrap-up | | **13 Skills** | Domain knowledge for architecture, coding, testing, security, n8n workflows | | **Protocols** | VSM-based coordination, algedonic signals, variety management | @@ -81,8 +87,9 @@ After installing this plugin, use these commands: /PACT:plan-mode # Strategic planning before implementation ``` -## Key Features (v2.0) +## Key Features (v3.0) +- **Agent Teams**: Specialists spawned as teammates via TeamCreate/SendMessage for real-time coordination - **Variety Management**: Tasks scored on complexity; ceremony scales accordingly - **Viability Sensing**: Agents emit HALT/ALERT signals for security, data, ethics issues - **Adaptive Workflow**: From quick fixes to full orchestration based on task complexity diff --git a/pact-plugin/agents/pact-architect.md b/pact-plugin/agents/pact-architect.md index 43441e5a..63c9bcac 100644 --- a/pact-plugin/agents/pact-architect.md +++ b/pact-plugin/agents/pact-architect.md @@ -160,22 +160,8 @@ See [algedonic.md](../protocols/algedonic.md) for signal format and full trigger **BEFORE COMPLETING** -Before returning your final output to the orchestrator: - -1. **Save Memory**: Invoke the `pact-memory` skill and save a memory documenting: - - Context: What you were designing and why - - Goal: The architectural objective - - Lessons learned: Design insights, trade-offs discovered, patterns that worked - - Decisions: Key architectural choices with rationale - - Entities: Components, services, interfaces involved - -This ensures your design context persists across sessions and is searchable by future agents. +See the pact-task-tracking skill for the full completion workflow: memory preservation, pre-completion checklist, HANDOFF delivery via SendMessage, and task status update. **HOW TO HANDLE BLOCKERS** -If you run into a blocker, STOP what you're doing and report the blocker to the orchestrator, so they can take over and invoke `/PACT:imPACT`. - -Examples of blockers: -- Same error after multiple fixes -- Missing info needed to proceed -- Task goes beyond your specialty +See the pact-task-tracking skill for the blocker protocol. Stop work immediately and report via SendMessage to the team lead. diff --git a/pact-plugin/agents/pact-backend-coder.md b/pact-plugin/agents/pact-backend-coder.md index ea5e9969..9cf78f82 100644 --- a/pact-plugin/agents/pact-backend-coder.md +++ b/pact-plugin/agents/pact-backend-coder.md @@ -100,7 +100,7 @@ Your success is measured by delivering backend code that: **DATABASE BOUNDARY** -Database Engineer delivers schema first, then you implement ORM. If you need a complex query, coordinate via the orchestrator. +Database Engineer delivers schema first, then you implement ORM. If you need a complex query, coordinate via the team lead. **TESTING** @@ -108,15 +108,7 @@ Your work isn't done until smoke tests pass. Smoke tests verify: "Does it compil **HANDOFF** -End with a structured handoff for the orchestrator: -1. **Produced**: Files created/modified -2. **Key decisions**: Decisions with rationale, assumptions that could be wrong -3. **Areas of uncertainty** (PRIORITIZED): - - [HIGH] {description} — Why risky, suggested test focus - - [MEDIUM] {description} - - [LOW] {description} -4. **Integration points**: Other components touched -5. **Open questions**: Unresolved items +See the pact-task-tracking skill for the full HANDOFF format, pre-completion checklist, and delivery via SendMessage to the team lead. **AUTONOMY CHARTER** @@ -148,22 +140,8 @@ See [algedonic.md](../protocols/algedonic.md) for signal format and full trigger **BEFORE COMPLETING** -Before returning your final output to the orchestrator: - -1. **Save Memory**: Invoke the `pact-memory` skill and save a memory documenting: - - Context: What you were working on and why - - Goal: What you were trying to achieve - - Lessons learned: What worked, what didn't, gotchas discovered - - Decisions: Key choices made with rationale - - Entities: Components, files, services involved - -This ensures your work context persists across sessions and is searchable by future agents. +See the pact-task-tracking skill for the full completion workflow: memory preservation, pre-completion checklist, HANDOFF delivery via SendMessage, and task status update. **HOW TO HANDLE BLOCKERS** -If you run into a blocker, STOP what you're doing and report the blocker to the orchestrator, so they can take over and invoke `/PACT:imPACT`. - -Examples of blockers: -- Same error after multiple fixes -- Missing info needed to proceed -- Task goes beyond your specialty +See the pact-task-tracking skill for the blocker protocol. Stop work immediately and report via SendMessage to the team lead. diff --git a/pact-plugin/agents/pact-database-engineer.md b/pact-plugin/agents/pact-database-engineer.md index 3ef1e7d9..58c67530 100644 --- a/pact-plugin/agents/pact-database-engineer.md +++ b/pact-plugin/agents/pact-database-engineer.md @@ -126,15 +126,7 @@ Your work isn't done until smoke tests pass. Smoke tests verify: "Does the schem **HANDOFF** -End with a structured handoff for the orchestrator: -1. **Produced**: Files created/modified (schemas, migrations, queries) -2. **Key decisions**: Decisions with rationale (normalization, indexes), assumptions that could be wrong -3. **Areas of uncertainty** (PRIORITIZED): - - [HIGH] {description} — Why risky, suggested test focus - - [MEDIUM] {description} - - [LOW] {description} -4. **Integration points**: Other components touched -5. **Open questions**: Unresolved items +See the pact-task-tracking skill for the full HANDOFF format, pre-completion checklist, and delivery via SendMessage to the team lead. **AUTONOMY CHARTER** @@ -166,22 +158,8 @@ See [algedonic.md](../protocols/algedonic.md) for signal format and full trigger **BEFORE COMPLETING** -Before returning your final output to the orchestrator: - -1. **Save Memory**: Invoke the `pact-memory` skill and save a memory documenting: - - Context: What you were working on and why - - Goal: What you were trying to achieve - - Lessons learned: Schema insights, query optimizations, gotchas discovered - - Decisions: Key choices made with rationale - - Entities: Tables, indexes, migrations involved - -This ensures your work context persists across sessions and is searchable by future agents. +See the pact-task-tracking skill for the full completion workflow: memory preservation, pre-completion checklist, HANDOFF delivery via SendMessage, and task status update. **HOW TO HANDLE BLOCKERS** -If you run into a blocker, STOP what you're doing and report the blocker to the orchestrator, so they can take over and invoke `/PACT:imPACT`. - -Examples of blockers: -- Same error after multiple fixes -- Missing info needed to proceed -- Task goes beyond your specialty +See the pact-task-tracking skill for the blocker protocol. Stop work immediately and report via SendMessage to the team lead. diff --git a/pact-plugin/agents/pact-frontend-coder.md b/pact-plugin/agents/pact-frontend-coder.md index 5ef75702..c492a9a9 100644 --- a/pact-plugin/agents/pact-frontend-coder.md +++ b/pact-plugin/agents/pact-frontend-coder.md @@ -99,15 +99,7 @@ Your work isn't done until smoke tests pass. Smoke tests verify: "Does it compil **HANDOFF** -End with a structured handoff for the orchestrator: -1. **Produced**: Files created/modified -2. **Key decisions**: Decisions with rationale, assumptions that could be wrong -3. **Areas of uncertainty** (PRIORITIZED): - - [HIGH] {description} — Why risky, suggested test focus - - [MEDIUM] {description} - - [LOW] {description} -4. **Integration points**: Other components touched -5. **Open questions**: Unresolved items +See the pact-task-tracking skill for the full HANDOFF format, pre-completion checklist, and delivery via SendMessage to the team lead. **AUTONOMY CHARTER** @@ -139,22 +131,8 @@ See [algedonic.md](../protocols/algedonic.md) for signal format and full trigger **BEFORE COMPLETING** -Before returning your final output to the orchestrator: - -1. **Save Memory**: Invoke the `pact-memory` skill and save a memory documenting: - - Context: What you were working on and why - - Goal: What you were trying to achieve - - Lessons learned: What worked, what didn't, gotchas discovered - - Decisions: Key choices made with rationale - - Entities: Components, files, services involved - -This ensures your work context persists across sessions and is searchable by future agents. +See the pact-task-tracking skill for the full completion workflow: memory preservation, pre-completion checklist, HANDOFF delivery via SendMessage, and task status update. **HOW TO HANDLE BLOCKERS** -If you run into a blocker, STOP what you're doing and report the blocker to the orchestrator, so they can take over and invoke `/PACT:imPACT`. - -Examples of blockers: -- Same error after multiple fixes -- Missing info needed to proceed -- Task goes beyond your specialty +See the pact-task-tracking skill for the blocker protocol. Stop work immediately and report via SendMessage to the team lead. diff --git a/pact-plugin/agents/pact-memory-agent.md b/pact-plugin/agents/pact-memory-agent.md index 75692af4..4d26ba03 100644 --- a/pact-plugin/agents/pact-memory-agent.md +++ b/pact-plugin/agents/pact-memory-agent.md @@ -104,7 +104,7 @@ When context has been compacted (lost to summarization): You do NOT need to manually edit CLAUDE.md. Just call `memory.save({...})` and the sync happens automatically. -**Relationship to auto-memory**: The platform's auto-memory (MEMORY.md) captures free-form session learnings automatically. Working Memory provides a complementary structured view -- PACT-specific context (goals, decisions, lessons) sourced from the SQLite database. Both are loaded into the system prompt independently. The reduced entry count (3 instead of 5) limits token overlap while retaining the structured format that auto-memory does not provide. +**Relationship to auto-memory**: The platform's auto-memory (MEMORY.md) captures free-form session learnings automatically. Working Memory provides a complementary structured view — PACT-specific context (goals, decisions, lessons) sourced from the SQLite database. Both are loaded into the system prompt independently. The reduced entry count (3 instead of 5) limits token overlap while retaining the structured format that auto-memory does not provide. ## 5. Memory Cleanup @@ -154,18 +154,13 @@ See [algedonic.md](../protocols/algedonic.md) for signal format and full trigger **HOW TO HANDLE BLOCKERS** -If you run into a blocker, STOP what you're doing and report the blocker to the orchestrator, so they can take over and invoke `/PACT:imPACT`. - -Examples of blockers: -- Same error after multiple fixes -- Missing info needed to proceed -- Task goes beyond your specialty +See the pact-task-tracking skill for the blocker protocol. Stop work immediately and report via SendMessage to the team lead. **DOMAIN-SPECIFIC BLOCKERS** If you encounter issues with the memory system: 1. Check memory status with `get_status()` -2. Report specific error to orchestrator +2. Report specific error to the team lead via SendMessage 3. Suggest fallback (e.g., manual context capture in docs/) Common memory-specific issues: diff --git a/pact-plugin/agents/pact-n8n.md b/pact-plugin/agents/pact-n8n.md index f6ca799e..41694037 100644 --- a/pact-plugin/agents/pact-n8n.md +++ b/pact-plugin/agents/pact-n8n.md @@ -130,15 +130,7 @@ Provide: **HANDOFF** -End with a structured handoff for the orchestrator: -1. **Produced**: Workflow created, key node configurations -2. **Key decisions**: Pattern selection rationale with assumptions that could be wrong -3. **Areas of uncertainty** (PRIORITIZED): - - [HIGH] {description} — Why risky, suggested test focus - - [MEDIUM] {description} - - [LOW] {description} -4. **Integration points**: Other components touched -5. **Open questions**: Unresolved items +See the pact-task-tracking skill for the full HANDOFF format, pre-completion checklist, and delivery via SendMessage to the team lead. **AUTONOMY CHARTER** @@ -170,17 +162,7 @@ See [algedonic.md](../protocols/algedonic.md) for signal format and full trigger **BEFORE COMPLETING** -Before returning your final output to the orchestrator: - -1. **Save Memory**: Invoke the `pact-memory` skill and save a memory documenting: - - Context: What workflow you were building and why - - Goal: The automation objective - - Lessons learned: n8n patterns that worked, validation insights, expression gotchas - - Decisions: Workflow design choices with rationale - - Entities: Nodes used, webhooks configured, integrations involved - -This ensures your workflow context persists across sessions and is searchable by future agents. - +See the pact-task-tracking skill for the full completion workflow: memory preservation, pre-completion checklist, HANDOFF delivery via SendMessage, and task status update. # TEMPLATE DEPLOYMENT @@ -194,12 +176,7 @@ Templates provide battle-tested starting points that you can customize. **HOW TO HANDLE BLOCKERS** -If you run into a blocker, STOP what you're doing and report the blocker to the orchestrator, so they can take over and invoke `/PACT:imPACT`. - -Examples of blockers: -- Same error after multiple fixes -- Missing info needed to proceed -- Task goes beyond your specialty +See the pact-task-tracking skill for the blocker protocol. Stop work immediately and report via SendMessage to the team lead. **DOMAIN-SPECIFIC BLOCKERS** diff --git a/pact-plugin/agents/pact-preparer.md b/pact-plugin/agents/pact-preparer.md index a438383f..0b787577 100644 --- a/pact-plugin/agents/pact-preparer.md +++ b/pact-plugin/agents/pact-preparer.md @@ -129,7 +129,7 @@ When evaluating multiple options: Remember: Your research forms the foundation for the entire project. Be thorough, accurate, and practical. When uncertain about conflicting information, present multiple viewpoints with clear source attribution. Your goal is to empower the Architect and subsequent phases with comprehensive, reliable information with a comprehensive markdown file. Save to the `docs/preparation` folder. -MANDATORY: Pass back to the Orchestrator upon completion of your markdown files. +MANDATORY: Send your HANDOFF to the team lead upon completion of your markdown files. **AUTONOMY CHARTER** @@ -142,7 +142,7 @@ You must escalate when: - Findings contradict architectural assumptions - Scope change exceeds 20% of original estimate - Security implications emerge that affect project direction -- Cross-domain research is needed (coordinate via orchestrator) +- Cross-domain research is needed (coordinate via the team lead) **Nested PACT**: For complex sub-research, you may run a mini prepare cycle. Declare it, execute it, integrate results. Max nesting: 1 level. See [pact-s1-autonomy.md](../protocols/pact-s1-autonomy.md) for S1 Autonomy & Recursion rules. @@ -161,22 +161,8 @@ See [algedonic.md](../protocols/algedonic.md) for signal format and full trigger **BEFORE COMPLETING** -Before returning your final output to the orchestrator: - -1. **Save Memory**: Invoke the `pact-memory` skill and save a memory documenting: - - Context: What you were researching and why - - Goal: The research objective - - Lessons learned: Key findings, surprising discoveries, research dead-ends - - Decisions: Technology/approach recommendations with rationale - - Entities: APIs, libraries, services researched - -This ensures your research context persists across sessions and is searchable by future agents. +See the pact-task-tracking skill for the full completion workflow: memory preservation, pre-completion checklist, HANDOFF delivery via SendMessage, and task status update. **HOW TO HANDLE BLOCKERS** -If you run into a blocker, STOP what you're doing and report the blocker to the orchestrator, so they can take over and invoke `/PACT:imPACT`. - -Examples of blockers: -- Same error after multiple fixes -- Missing info needed to proceed -- Task goes beyond your specialty +See the pact-task-tracking skill for the blocker protocol. Stop work immediately and report via SendMessage to the team lead. diff --git a/pact-plugin/agents/pact-test-engineer.md b/pact-plugin/agents/pact-test-engineer.md index 926e2e8f..a911c900 100644 --- a/pact-plugin/agents/pact-test-engineer.md +++ b/pact-plugin/agents/pact-test-engineer.md @@ -144,7 +144,7 @@ Engage **after** Code phase. You own ALL substantive testing: Coders provide smoke tests only (compile, run, happy path). You provide comprehensive coverage. -Route failures back to the relevant coder. +Route failures back to the relevant coder via the team lead. ### Risk-Tiered Testing Framework @@ -184,7 +184,7 @@ When coders flag areas of uncertainty in their handoff: ### Signal Output System -Report your findings to the orchestrator using this signal format: +Report your findings to the team lead using this signal format: ``` Risk Tier: {CRITICAL|HIGH|STANDARD|LIGHT} @@ -199,13 +199,13 @@ If no HIGH areas were flagged in the handoff, report: `Uncertainty Coverage: N/A | Signal | Meaning | Action | |--------|---------|--------| | 🟢 **GREEN** | All tests pass, adequate coverage, no concerns | Continue to PR | -| 🟡 **YELLOW** | Tests pass but concerns noted (coverage gaps, flaky tests, edge cases not covered) | Document concerns, orchestrator decides | +| 🟡 **YELLOW** | Tests pass but concerns noted (coverage gaps, flaky tests, edge cases not covered) | Document concerns, team lead decides | | 🔴 **RED** | Critical issues found (test failures, security vulnerabilities, data integrity risks) | Route back to coders for fix, re-test | **RED → Coder Loop**: When you emit RED: 1. Document the specific failures/issues 2. Include the coder domain (backend/frontend/database) to enable proper routing when multiple coders worked on the code -3. Orchestrator routes back to relevant coder(s) +3. Team lead routes back to relevant coder(s) 4. After fix, re-run affected tests 5. Re-emit signal based on new results @@ -218,26 +218,18 @@ concern, not application logic. Deferred to ops team for NTP monitoring. **CODE PHASE CONTEXT** -The orchestrator passes CODE phase handoff summaries. Use these for context: +The team lead passes CODE phase handoff summaries. Use these for context: - What was implemented - Key decisions and assumptions - Areas of uncertainty (where bugs might hide—prioritize these) **Use handoff as context, not prescription.** You decide what and how to test. -**If handoff context seems incomplete** (missing what was implemented, or no areas of uncertainty flagged), ask the orchestrator for clarification before proceeding with limited context. +**If handoff context seems incomplete** (missing what was implemented, or no areas of uncertainty flagged), ask the team lead for clarification via SendMessage before proceeding with limited context. **HANDOFF** -End with a structured handoff for the orchestrator: -1. **Produced**: Test files created, coverage achieved -2. **Key decisions**: Testing approach with rationale, assumptions that could be wrong -3. **Areas of uncertainty** (PRIORITIZED): - - [HIGH] {description} — Why risky, suggested test focus - - [MEDIUM] {description} - - [LOW] {description} -4. **Integration points**: Other components touched -5. **Open questions**: Unresolved items +See the pact-task-tracking skill for the full HANDOFF format, pre-completion checklist, and delivery via SendMessage to the team lead. **AUTONOMY CHARTER** @@ -245,7 +237,7 @@ You have authority to: - Adjust testing approach based on discoveries during test implementation - Recommend scope changes when testing reveals complexity differs from estimate - Invoke **nested PACT** for complex test sub-systems (e.g., a comprehensive integration test suite needing its own design) -- Route failures back to coders without orchestrator approval +- Route failures back to coders via the team lead You must escalate when: - Discovery contradicts the architecture (code behavior doesn't match spec) @@ -270,22 +262,8 @@ See [algedonic.md](../protocols/algedonic.md) for signal format and full trigger **BEFORE COMPLETING** -Before returning your final output to the orchestrator: - -1. **Save Memory**: Invoke the `pact-memory` skill and save a memory documenting: - - Context: What you were testing and why - - Goal: The testing objective - - Lessons learned: Testing insights, edge cases found, patterns that emerged - - Decisions: Testing strategy choices with rationale - - Entities: Components tested, test suites created - -This ensures your testing context persists across sessions and is searchable by future agents. +See the pact-task-tracking skill for the full completion workflow: memory preservation, pre-completion checklist, HANDOFF delivery via SendMessage, and task status update. **HOW TO HANDLE BLOCKERS** -If you run into a blocker, STOP what you're doing and report the blocker to the orchestrator, so they can take over and invoke `/PACT:imPACT`. - -Examples of blockers: -- Same error after multiple fixes -- Missing info needed to proceed -- Task goes beyond your specialty +See the pact-task-tracking skill for the blocker protocol. Stop work immediately and report via SendMessage to the team lead. diff --git a/pact-plugin/commands/comPACT.md b/pact-plugin/commands/comPACT.md index b28bdb24..86c0e8c2 100644 --- a/pact-plugin/commands/comPACT.md +++ b/pact-plugin/commands/comPACT.md @@ -1,12 +1,12 @@ --- -description: Delegate within a single domain—concurrent agents for independent sub-tasks +description: Delegate within a single domain—concurrent teammates for independent sub-tasks argument-hint: [backend|frontend|database|prepare|test|architect] --- Delegate this focused task within a single PACT domain: $ARGUMENTS **MANDATORY: invoke concurrently for independent sub-tasks.** Sequential requires explicit file conflict or data dependency. If the task contains multiple independent items (bugs, endpoints, components), dispatch multiple specialists of the same type together unless they share files. -> ⚠️ **Single domain ≠ single agent.** "Backend domain" with 3 bugs = 3 backend-coders in parallel. The domain is singular; the agents are not. +> **Single domain does not equal single agent.** "Backend domain" with 3 bugs = 3 backend-coders in parallel. The domain is singular; the agents are not. --- @@ -17,17 +17,19 @@ Create a simpler Task hierarchy than full orchestrate: ``` 1. TaskCreate: Feature task "{verb} {feature}" (single-domain work) 2. TaskUpdate: Feature task status = "in_progress" -3. Analyze: How many agents needed? -4. TaskCreate: Agent task(s) — direct children of feature +3. Analyze: How many teammates needed? +4. TaskCreate: Agent task(s) —direct children of feature 5. TaskUpdate: Agent tasks status = "in_progress" 6. TaskUpdate: Feature task addBlockedBy = [all agent IDs] -7. Dispatch agents concurrently with task IDs -8. Monitor via TaskList until all agents complete -9. TaskUpdate: Agent tasks status = "completed" (as each completes) -10. TaskUpdate: Feature task status = "completed" +7. Spawn teammates with task IDs in their prompts +8. Review/approve teammate plans +9. Monitor via TaskList and incoming SendMessage until all teammates complete +10. Send shutdown_request to completed teammates +11. TaskUpdate: Agent tasks status = "completed" (as each completes) +12. TaskUpdate: Feature task status = "completed" ``` -> Steps 8-10 are detailed in the [After Specialist Completes](#after-specialist-completes) section below (includes test verification and commit steps). +> Steps 8-12 are detailed in the [After Teammate Completes](#after-teammate-completes) section below (includes plan review, test verification, and commit steps). **Example structure:** ``` @@ -69,7 +71,7 @@ If the first word isn't a recognized shorthand, treat the entire argument as the - Generic verbs without domain context (fix, improve, update) - Feature-level scope that spans domains (login, user profile, dashboard) - Performance/optimization without specific layer -- → Use `AskUserQuestion` tool: +- Use `AskUserQuestion` tool: - Question: "Which specialist should handle this task?" - Options: List the 2-3 most likely specialists based on context (e.g., "Backend" / "Frontend" / "Database") @@ -85,8 +87,8 @@ Invoke concurrently when: - Same patterns/conventions apply to all **Examples:** -| Task | Agents Invoked | -|------|----------------| +| Task | Teammates Spawned | +|------|-------------------| | "Fix 3 backend bugs" | 3 backend-coders at once | | "Add validation to 5 endpoints" | Multiple backend-coders simultaneously | | "Update styling on 3 components" | Multiple frontend-coders together | @@ -100,7 +102,7 @@ Invoke concurrently when: ## S2 Light Coordination (Required Before Concurrent Dispatch) -Before invoking multiple specialists concurrently, perform this coordination check: +Before spawning multiple specialists concurrently, perform this coordination check: 1. **Identify potential conflicts** - List files each sub-task will touch @@ -108,7 +110,7 @@ Before invoking multiple specialists concurrently, perform this coordination che 2. **Resolve conflicts (if any)** - **Same file**: Sequence those sub-tasks OR assign clear section boundaries - - **Style/convention**: First agent's choice becomes standard + - **Style/convention**: First teammate's choice becomes standard 3. **Set boundaries** - Clearly state which sub-task handles which files/components @@ -125,7 +127,7 @@ Before invoking multiple specialists concurrently, perform this coordination che | Internal (don't show) | External (show) | |----------------------|-----------------| | S2 coordination analysis, conflict checking | `Delegating to backend coder` | -| Concurrency reasoning, file boundary decisions | `Invoking 3 frontend coders in parallel` | +| Concurrency reasoning, file boundary decisions | `Spawning 3 frontend coders in parallel` | | Specialist selection logic | `Auto-selected: database (SQL keywords detected)` | **User can always ask** for details (e.g., "Why that specialist?" or "Show me the conflict analysis"). @@ -139,54 +141,65 @@ Before invoking multiple specialists concurrently, perform this coordination che ## Pre-Invocation (Required) -1. **Set up worktree** — If already in a worktree for this feature, reuse it. Otherwise, invoke `/PACT:worktree-setup` with the feature branch name. All subsequent work happens in the worktree. -2. **S2 coordination** (if concurrent) — Check for file conflicts, assign boundaries +1. **Set up worktree** —If already in a worktree for this feature, reuse it. Otherwise, invoke `/PACT:worktree-setup` with the feature branch name. All subsequent work happens in the worktree. +2. **S2 coordination** (if concurrent) —Check for file conflicts, assign boundaries --- -## Invocation +## Spawning Teammates + +Spawn teammates into the existing session team (created by the session-start hook). No `TeamCreate` needed. + +**Spawn tasks and teammates together in a single message** (parallel tool calls): +``` +Single message (all parallel): +├── TaskCreate("Fix auth bug", owner="backend-1") +├── TaskCreate("Fix cache bug", owner="backend-2") +├── Task(spawn backend-1 teammate) +└── Task(spawn backend-2 teammate) +``` ### Multiple Specialists Concurrently (Default) -When the task contains multiple independent items, invoke multiple specialists together with boundary context: +When the task contains multiple independent items, spawn multiple teammates together with boundary context: ``` -comPACT mode (concurrent): You are one of [N] specialists working concurrently. +comPACT mode (concurrent): You are one of [N] specialists working concurrently as teammates. You are working in a git worktree at [worktree_path]. All file paths must be absolute and within this worktree. YOUR SCOPE: [specific sub-task and files this agent owns] -OTHER AGENTS' SCOPE: [what other agents are handling - do not touch] +OTHER AGENTS' SCOPE: [what other agents are handling —do not touch] Work directly from this task description. -Check docs/plans/, docs/preparation/, docs/architecture/ briefly if they exist—reference relevant context. +Check docs/plans/, docs/preparation/, docs/architecture/ briefly if they exist —reference relevant context. Do not create new documentation artifacts in docs/. -Stay within your assigned scope—do not modify files outside your boundary. +Stay within your assigned scope —do not modify files outside your boundary. Testing responsibilities: - New unit tests: Required for logic changes. - Existing tests: If your changes break existing tests, fix them. - Before handoff: Run the test suite for your scope. -If you hit a blocker or need to modify files outside your scope, STOP and report it. +If you hit a blocker or need to modify files outside your scope, STOP and report it via SendMessage to the lead. Task: [this agent's specific sub-task] ``` -**After all concurrent agents complete**: Verify no conflicts occurred, run full test suite. +**After all concurrent teammates complete**: Verify no conflicts occurred, run full test suite. -### Single Specialist Agent (When Required) +### Single Specialist Teammate (When Required) -Use a single specialist agent only when: +Use a single specialist only when: - Task is atomic (one bug, one endpoint, one component) - Sub-tasks modify the same files - Sub-tasks have dependencies on each other - Conventions haven't been established yet (run one first to set patterns) -**Invoke the specialist with**: +**Spawn the specialist with**: ``` comPACT mode: Work directly from this task description. You are working in a git worktree at [worktree_path]. All file paths must be absolute and within this worktree. -Check docs/plans/, docs/preparation/, docs/architecture/ briefly if they exist—reference relevant context. +Check docs/plans/, docs/preparation/, docs/architecture/ briefly if they exist —reference relevant context. Do not create new documentation artifacts in docs/. Focus on the task at hand. Testing responsibilities: @@ -194,52 +207,50 @@ Testing responsibilities: - Existing tests: If your changes break existing tests, fix them. - Before handoff: Run the test suite and ensure all tests pass. -> **Smoke vs comprehensive tests**: These are verification tests—enough to confirm your implementation works. Comprehensive coverage (edge cases, integration, E2E, adversarial) is TEST phase work handled by `pact-test-engineer`. +> **Smoke vs comprehensive tests**: These are verification tests —enough to confirm your implementation works. Comprehensive coverage (edge cases, integration, E2E, adversarial) is TEST phase work handled by `pact-test-engineer`. -If you hit a blocker, STOP and report it so the orchestrator can run /PACT:imPACT. +If you hit a blocker, STOP and report it via SendMessage to the lead. Task: [user's task description] ``` --- -## Signal Monitoring +## Plan Approval -Check TaskList for blocker/algedonic signals: -- After each agent dispatch -- When agent reports completion -- On any unexpected agent stoppage - -On signal detected: Follow Signal Task Handling in CLAUDE.md. - -For agent stall detection and recovery, see [Agent Stall Detection](orchestrate.md#agent-stall-detection). +All teammates are spawned with `mode="plan"`. Review each plan for: +- Does it align with the task scope? +- Are file boundaries respected (for concurrent work)? +- Is the approach reasonable? --- -## After Specialist Completes +## After Teammate Completes + +Teammates deliver their HANDOFF via `SendMessage` to the lead, then mark their task complete via `TaskUpdate`. -1. **Receive handoff** from specialist(s) -2. **TaskUpdate**: Agent tasks status = "completed" (as each completes) -3. **Run tests** — verify work passes. If tests fail → return to specialist for fixes (create new agent task, repeat from step 1). -4. **Create atomic commit(s)** — stage and commit before proceeding +1. **Receive HANDOFF** via SendMessage from teammate(s) +2. **Run tests** —verify work passes. If tests fail, message the teammate with details for fixes. +3. **Shutdown teammate** after successful completion +4. **Create atomic commit(s)** —stage and commit before proceeding 5. **TaskUpdate**: Feature task status = "completed" -**Next steps** — After commit, ask: "Work committed. Create PR?" -- **Yes (Recommended)** → invoke `/PACT:peer-review` -- **Not yet** → worktree persists; user resumes later. Clean up manually with `/PACT:worktree-cleanup` when done. -- **More work** → continue with comPACT or orchestrate +**Next steps** —After commit, ask: "Work committed. Create PR?" +- **Yes (Recommended)** —invoke `/PACT:peer-review` (reviewers spawn into the SAME existing team) +- **Not yet** —worktree persists; user resumes later. Clean up manually with `/PACT:worktree-cleanup` when done. +- **More work** —continue with comPACT or orchestrate -**If blocker reported**: +**If blocker reported** (teammate sends BLOCKER via SendMessage): Examples of blockers: - Task requires a different specialist's domain - Missing dependencies, access, or information - Same error persists after multiple fix attempts - Scope exceeds single-domain capability (needs cross-domain coordination) -- Concurrent agents have unresolvable conflicts +- Concurrent teammates have unresolvable conflicts When blocker is reported: -1. Receive blocker report from specialist +1. Receive blocker report from teammate via SendMessage 2. Run `/PACT:imPACT` to triage 3. May escalate to `/PACT:orchestrate` if task exceeds single-domain scope diff --git a/pact-plugin/commands/imPACT.md b/pact-plugin/commands/imPACT.md index ee0cb37e..4e79e38d 100644 --- a/pact-plugin/commands/imPACT.md +++ b/pact-plugin/commands/imPACT.md @@ -10,19 +10,19 @@ You hit a blocker: $ARGUMENTS imPACT operates on blocker Tasks reported by agents. -These are orchestrator-side operations (agents report blockers via text; the orchestrator manages Tasks): +These are orchestrator-side operations (teammates report blockers via SendMessage; the orchestrator manages Tasks): ``` 1. TaskGet(blocker_id) — understand the blocker context 2. Triage: redo prior phase? need specialist? need user? 3. On resolution path chosen: - - If delegating: TaskCreate resolution agent task + - If delegating: TaskCreate resolution task, spawn teammate - If self-resolving: proceed directly 4. On resolution complete: TaskUpdate(blocker_id, status="completed") 5. Blocked agent task is now unblocked ``` -**Note**: Agents report blockers via text ("BLOCKER: {description}"). The orchestrator creates blocker Tasks and uses `addBlockedBy` to block the agent's task. When the blocker is resolved (marked completed), the agent's task becomes unblocked. +**Note**: Teammates report blockers via SendMessage to the lead using the `BLOCKER:` prefix format. The orchestrator creates blocker Tasks and uses `addBlockedBy` to track resolution. --- @@ -47,7 +47,7 @@ Common traps to avoid: imPACT is **S3-level triage**—operational problem-solving within normal workflow. It is NOT S5 algedonic escalation (emergency bypass to user). -**imPACT handles**: Blockers that can be resolved by redoing a phase or adding agents. +**imPACT handles**: Blockers that can be resolved by redoing a phase or adding teammates. **Algedonic escalation handles**: Viability threats (security, data, ethics violations). See [algedonic.md](../protocols/algedonic.md). @@ -77,8 +77,8 @@ imPACT is for operational problem-solving. If you're questioning whether the wor | Internal (don't show) | External (show) | |----------------------|-----------------| | Question-by-question analysis | `imPACT: Redo ARCHITECT — interface mismatch` | -| Full diagnostic reasoning | `imPACT: Augmenting with parallel backend coder` | -| Context-gathering details | `imPACT: Not blocked — clarifying guidance to agent` | +| Full diagnostic reasoning | `imPACT: Augmenting with parallel backend teammate` | +| Context-gathering details | `imPACT: Not blocked — clarifying guidance to teammate` | **User can always ask** for triage details (e.g., "Why redo that phase?" or "What was the diagnosis?"). @@ -102,22 +102,22 @@ This context informs whether the blocker is isolated or systemic. Answer two questions: 1. **Redo prior phase?** — Is the issue upstream in P→A→C→T? -2. **Additional agents needed?** — Do we need help beyond the blocked agent's scope/specialty? +2. **Additional teammates needed?** — Do we need help beyond the blocked teammate's scope/specialty? ## Outcomes | Outcome | When | Action | |---------|------|--------| -| **Redo prior phase** | Issue is upstream in P→A→C→T | Re-delegate to relevant agent(s) to redo the prior phase | -| **Augment present phase** | Need help in current phase | Re-invoke blocked agent with additional context + parallel agents | -| **Invoke rePACT** | Sub-task needs own P→A→C→T cycle | Use `/PACT:rePACT` for nested cycle | -| **Not truly blocked** | Neither question is "Yes" | Instruct agent to continue with clarified guidance | -| **Escalate to user** | 3+ imPACT cycles without resolution | Proto-algedonic signal—systemic issue needs user input | - -**When to consider rePACT**: -If the blocker reveals that a sub-task is more complex than expected and needs its own research/design phase, use `/PACT:rePACT` instead of just augmenting: +| **Redo prior phase** | Issue is upstream in P→A→C→T | Spawn teammate(s) to redo the prior phase | +| **Augment present phase** | Need help in current phase | Message blocked teammate with additional context + spawn parallel teammates | +| **Escalate to orchestrate** | Sub-task needs its own P→A→C→T cycle | Use `/PACT:orchestrate` for a standalone cycle | +| **Not truly blocked** | Neither question is "Yes" | Message teammate with clarified guidance to continue | +| **Escalate to user** | 3+ imPACT cycles without resolution | Proto-algedonic signal —systemic issue needs user input | + +**When to consider escalating to orchestrate**: +If the blocker reveals that a sub-task is more complex than expected and needs its own research/design phases, escalate to `/PACT:orchestrate` instead of just augmenting: ``` -/PACT:rePACT backend "implement the OAuth2 token refresh that's blocking us" +/PACT:orchestrate "implement the OAuth2 token refresh that's blocking us" ``` --- @@ -126,7 +126,7 @@ If the blocker reveals that a sub-task is more complex than expected and needs i **Context**: Invoked from [orchestrate.md](orchestrate.md) when redoing a prior phase. Complete original blocker first ([Task Operations](#task-operations) step 4). Retry failure triggers 3+ cycle escalation (ALERT: META-BLOCK). -**Worktree context**: Phase re-entry operates within the current worktree. The re-entered phase inherits the same worktree path -- no new worktree is created. +**Worktree context**: Phase re-entry operates within the current worktree. The re-entered phase inherits the same worktree path —no new worktree is created. When imPACT decides to redo a prior phase (e.g., "redo ARCHITECT because the design was wrong"), follow this Task lifecycle: @@ -134,6 +134,6 @@ When imPACT decides to redo a prior phase (e.g., "redo ARCHITECT because the des 2. **Create a new retry phase task**: `TaskCreate("ARCHITECT (retry): {feature-slug}")` 3. **Set retry task to `in_progress`** 4. **Block the current phase** (the one that hit the blocker): `TaskUpdate(currentPhaseId, addBlockedBy=[retryPhaseId])` -5. **Dispatch agent(s)** for the retry phase +5. **Spawn teammate(s)** for the retry phase 6. **On retry completion**: `TaskUpdate(retryPhaseId, status="completed")` — unblocks the current phase 7. **Retry the current phase** with a new agent task using the updated outputs diff --git a/pact-plugin/commands/orchestrate.md b/pact-plugin/commands/orchestrate.md index c1a5c75f..d40596c9 100644 --- a/pact-plugin/commands/orchestrate.md +++ b/pact-plugin/commands/orchestrate.md @@ -6,6 +6,19 @@ Orchestrate specialist PACT agents through the PACT workflow to address: $ARGUME --- +## Team Lifecycle + +The session team is created by the SessionStart hook at session initialization. Commands do not need to create teams. + +**Ensure team exists**: If the team was not created (e.g., hook failure, manual session), call `TeamCreate(team_name="{feature-slug}")` before proceeding. + +**Teammate lifecycle within orchestrate**: +- Teammates are spawned per phase into the session team +- Between phases, shut down current teammates before spawning next-phase teammates +- The team itself persists for the entire session (shared across commands) + +--- + ## Task Hierarchy Create the full Task hierarchy upfront for workflow visibility: @@ -35,12 +48,12 @@ For each phase execution: ``` a. TaskUpdate: phase status = "in_progress" b. Analyze work needed (QDCL for CODE) -c. TaskCreate: agent task(s) as children of phase -d. TaskUpdate: agent tasks status = "in_progress" -e. TaskUpdate: next phase addBlockedBy = [agent IDs] -f. Dispatch agents with task IDs in their prompts -g. Monitor via TaskList until agents complete -h. TaskUpdate: agent tasks status = "completed" (as each completes) +c. TaskCreate: agent task(s) with owner="{teammate-name}" +d. Spawn teammates (Task with team_name/name/mode="plan") +e. Review and approve teammate plans +f. Monitor: teammates self-update tasks, send HANDOFFs via SendMessage +g. Receive HANDOFFs, verify completeness +h. Shut down phase teammates i. TaskUpdate: phase status = "completed" ``` @@ -53,20 +66,20 @@ Valid reasons: `"approved_plan_exists"`, `"plan_section_complete"`, `"requiremen - "requirements_explicit": Task description contains all needed context - "existing_docs_cover_scope": docs/preparation/ or docs/architecture/ already complete - "trivial_change": Change too small to warrant this phase - - "decomposition_active": Scope detection triggered decomposition; sub-scopes handle this phase via rePACT + - "decomposition_active": Scope detection triggered decomposition; sub-scopes handle this phase --> --- ## S3/S4 Mode Awareness -This command primarily operates in **S3 mode** (operational control)—executing the plan and coordinating agents. However, mode transitions are important: +This command primarily operates in **S3 mode** (operational control)—executing the plan and coordinating teammates. However, mode transitions are important: | Phase | Primary Mode | Mode Checks | |-------|--------------|-------------| | **Before Starting** | S4 | Understand task, assess complexity, check for plans | | **Context Assessment** | S4 | Should phases be skipped? What's the right approach? | -| **Phase Execution** | S3 | Coordinate agents, track progress, clear blockers | +| **Phase Execution** | S3 | Coordinate teammates, track progress, clear blockers | | **On Blocker** | S4 | Assess before responding—is this operational or strategic? | | **Between Phases** | S4 | Still on track? Adaptation needed? | | **After Completion** | S4 | Retrospective—what worked, what didn't? | @@ -79,6 +92,12 @@ When transitioning to S4 mode, pause and ask: "Are we still building the right t For algedonic signal handling (HALT/ALERT responses, algedonic vs imPACT distinction), see [algedonic.md](../protocols/algedonic.md). +**HALT signal handling with teammates**: When a teammate broadcasts a HALT signal, all teammates receive it via broadcast and should stop work. The lead must: +1. Acknowledge the HALT +2. Send shutdown requests to all active teammates +3. Present the signal to the user +4. Await user decision before resuming + --- ## Output Conciseness @@ -102,7 +121,7 @@ For algedonic signal handling (HALT/ALERT responses, algedonic vs imPACT distinc | Verbose (avoid) | Concise (prefer) | |-----------------|------------------| | "Let me assess variety and check for the approved plan" | (just do it, show result) | -| "I'm now going to invoke the backend coder" | `Invoking backend coder` | +| "I'm now going to spawn the backend coder teammate" | `Spawning backend-1` | | "S4 Mode — Task Assessment" | (implicit, don't announce) | --- @@ -152,7 +171,7 @@ If comPACT selected, hand off to `/PACT:comPACT`. ## Execution Philosophy -**MANDATORY: Invoke concurrently unless blocked.** The burden of proof is on sequential dispatch. If you cannot cite a specific file conflict or data dependency, you MUST invoke them concurrently. +**MANDATORY: Spawn concurrently unless blocked.** The burden of proof is on sequential dispatch. If you cannot cite a specific file conflict or data dependency, you MUST spawn them concurrently. This applies across ALL phases, not just CODE: - PREPARE with multiple research areas → multiple preparers at once @@ -160,7 +179,7 @@ This applies across ALL phases, not just CODE: - CODE with multiple domains or independent tasks → multiple coders together - TEST with independent test suites → multiple test engineers concurrently -Sequential execution is the exception requiring explicit justification. When assessing any phase, ask: "Can specialists be invoked concurrently?" The answer is usually yes. +Sequential execution is the exception requiring explicit justification. When assessing any phase, ask: "Can specialists be spawned concurrently?" The answer is usually yes. --- @@ -238,6 +257,32 @@ When a phase is skipped but a coder encounters a decision that would have been h --- +## Teammate Spawning Pattern + +### Spawning Teammates + +Spawn teammates using `Task` with team parameters. All teammates for a phase are spawned in a single message as parallel tool calls: + +``` +Lead: Single message (all parallel tool calls): +├── TaskCreate("Research area A", owner="preparer-1") +├── TaskCreate("Research area B", owner="preparer-2") +├── Task(subagent_type="pact-preparer", team_name="{team}", name="preparer-1", mode="plan", prompt="...") +└── Task(subagent_type="pact-preparer", team_name="{team}", name="preparer-2", mode="plan", prompt="...") +``` + +**Naming convention**: `{role}-{number}` (e.g., `"backend-1"`, `"architect-2"`, `"preparer-1"`). For scoped orchestration: `"scope-{scope}-{role}"` (e.g., `"scope-auth-backend"`, `"scope-billing-frontend"`). + +### Plan Approval + +All teammates are spawned with `mode="plan"`. **Review all plans for a phase before approving any** — this allows the lead to identify conflicts, overlaps, or gaps across the phase's work items before implementation begins. + +### Shutting Down Teammates Between Phases + +Shut down all current-phase teammates and wait for acknowledgment before spawning next-phase teammates. If a teammate rejects shutdown, check TaskList for its task status — it may still be completing work. + +--- + ### PREPARE Phase → `pact-preparer` **Skip criteria met (including completeness check)?** → Proceed to ARCHITECT phase. @@ -246,18 +291,26 @@ When a phase is skipped but a coder encounters a decision that would have been h - "Preparation Phase" - "Open Questions > Require Further Research" -**Invoke `pact-preparer` with**: +**Spawn `pact-preparer` teammate(s) with**: - Task description - Plan sections above (if any) - "Reference the approved plan at `docs/plans/{slug}-plan.md` for full context." +**Example spawn**: +``` +TaskCreate("Research auth patterns and API contracts", owner="preparer-1") +Task(subagent_type="pact-preparer", team_name="{team}", name="preparer-1", mode="plan", + prompt="CONTEXT: ... MISSION: ... INSTRUCTIONS: ... GUIDELINES: ...") +``` + **Before next phase**: - [ ] Outputs exist in `docs/preparation/` -- [ ] Specialist handoff received -- [ ] If blocker reported → `/PACT:imPACT` +- [ ] HANDOFF received from each preparer (via SendMessage) +- [ ] If blocker reported (via SendMessage) → `/PACT:imPACT` +- [ ] Shut down all preparer teammates - [ ] **S4 Checkpoint** (see [pact-s4-checkpoints.md](../protocols/pact-s4-checkpoints.md)): Environment stable? Model aligned? Plan viable? -**Concurrent dispatch within PREPARE**: If research spans multiple independent areas (e.g., "research auth options AND caching strategies"), invoke multiple preparers together with clear scope boundaries. +**Concurrent dispatch within PREPARE**: If research spans multiple independent areas (e.g., "research auth options AND caching strategies"), spawn multiple preparers together with clear scope boundaries. --- @@ -288,7 +341,7 @@ After PREPARE completes (or is skipped with plan context), evaluate whether the | Result | Action | |--------|--------| -| Score below threshold | Single scope — continue with today's behavior | +| Score below threshold | Single scope — continue with standard flow | | Score at/above threshold | Propose decomposition (see Evaluation Response below) | | All strong signals fire, no counter-signals, autonomous enabled | Auto-decompose (see Evaluation Response below) | @@ -298,7 +351,7 @@ After PREPARE completes (or is skipped with plan context), evaluate whether the When detection fires (score >= threshold), follow the evaluation response protocol in [pact-scope-detection.md](../protocols/pact-scope-detection.md) — S5 confirmation flow, user response mapping, and autonomous tier. -**On confirmed decomposition**: Generate a scope contract for each sub-scope before invoking rePACT. See [pact-scope-contract.md](../protocols/pact-scope-contract.md) for the contract format and generation process. Skip top-level ARCHITECT and CODE — mark both `completed` with `{"skipped": true, "skip_reason": "decomposition_active"}`. The workflow switches to scoped PACT phases: ATOMIZE (dispatch sub-scopes) → CONSOLIDATE (verify contracts) → TEST (comprehensive feature testing). See ATOMIZE Phase and CONSOLIDATE Phase below. +**On confirmed decomposition**: Generate a scope contract for each sub-scope before spawning teammates. See [pact-scope-contract.md](../protocols/pact-scope-contract.md) for the contract format and generation process. Skip top-level ARCHITECT and CODE — mark both `completed` with `{"skipped": true, "skip_reason": "decomposition_active"}`. The workflow switches to scoped PACT phases: ATOMIZE (dispatch sub-scopes) → CONSOLIDATE (verify contracts) → TEST (comprehensive feature testing). See ATOMIZE Phase and CONSOLIDATE Phase below. --- @@ -311,7 +364,7 @@ When detection fires (score >= threshold), follow the evaluation response protoc - "Key Decisions" - "Interface Contracts" -**Invoke `pact-architect` with**: +**Spawn `pact-architect` teammate(s) with**: - Task description - PREPARE phase outputs: - Tell `pact-architect` where to find them (e.g., "Read `docs/preparation/{feature}.md` for research context") @@ -320,13 +373,21 @@ When detection fires (score >= threshold), follow the evaluation response protoc - Plan sections above (if any) - "Reference the approved plan at `docs/plans/{slug}-plan.md` for full context." +**Example spawn**: +``` +TaskCreate("Design auth service architecture", owner="architect-1") +Task(subagent_type="pact-architect", team_name="{team}", name="architect-1", mode="plan", + prompt="CONTEXT: ... MISSION: ... INSTRUCTIONS: ... GUIDELINES: ...") +``` + **Before next phase**: - [ ] Outputs exist in `docs/architecture/` -- [ ] Specialist handoff received -- [ ] If blocker reported → `/PACT:imPACT` +- [ ] HANDOFF received from each architect (via SendMessage) +- [ ] If blocker reported (via SendMessage) → `/PACT:imPACT` +- [ ] Shut down all architect teammates - [ ] **S4 Checkpoint**: Environment stable? Model aligned? Plan viable? -**Concurrent dispatch within ARCHITECT**: If designing multiple independent components (e.g., "design user service AND notification service"), invoke multiple architects simultaneously. Ensure interface contracts between components are defined as a coordination checkpoint. +**Concurrent dispatch within ARCHITECT**: If designing multiple independent components (e.g., "design user service AND notification service"), spawn multiple architects simultaneously. Ensure interface contracts between components are defined as a coordination checkpoint. --- @@ -334,7 +395,7 @@ When detection fires (score >= threshold), follow the evaluation response protoc **Always runs.** This is the core work. -> **S5 Policy Checkpoint (Pre-CODE)**: Before invoking coders, verify: +> **S5 Policy Checkpoint (Pre-CODE)**: Before spawning coders, verify: > 1. "Does the architecture align with project principles?" > 2. "Am I delegating ALL code changes to specialists?" (orchestrator writes no application code) > 3. "Are there any S5 non-negotiables at risk?" @@ -351,9 +412,9 @@ When detection fires (score >= threshold), follow the evaluation response protoc - `pact-frontend-coder` — UI, client-side - `pact-database-engineer` — schema, queries, migrations -#### Invoke Concurrently by Default +#### Spawn Concurrently by Default -**Default stance**: Dispatch specialists together unless proven dependent. Sequential requires explicit justification. +**Default stance**: Spawn specialists together unless proven dependent. Sequential requires explicit justification. **Required decision output** (no exceptions): - "**Concurrent**: [groupings]" — the expected outcome @@ -366,7 +427,7 @@ When detection fires (score >= threshold), follow the evaluation response protoc #### Execution Strategy Analysis -**REQUIRED**: Complete the QDCL internally before invoking coders. +**REQUIRED**: Complete the QDCL internally before spawning coders. **Quick Dependency Checklist (QDCL)** — run mentally, don't output: @@ -376,7 +437,7 @@ For each pair of work units, check: - Shared interface undefined? → Define interface first, then concurrent - None of above? → Concurrent -**Output format**: Decision only. Example: `Invoking backend + frontend coders in parallel` or `Sequential: database first, then backend (schema dependency)` +**Output format**: Decision only. Example: `Spawning backend-1 + frontend-1 in parallel` or `Sequential: database-1 first, then backend-1 (schema dependency)` **If QDCL shows no dependencies**: Concurrent is your answer. Don't second-guess. @@ -384,17 +445,17 @@ For each pair of work units, check: Before concurrent dispatch, check internally: shared files? shared interfaces? conventions established? -- **Shared files**: Sequence those agents OR assign clear boundaries -- **Conventions**: First agent's choice becomes standard; propagate to others -- **Resolution authority**: Technical disagreements → Architect arbitrates; Style/convention → First agent's choice +- **Shared files**: Sequence those teammates OR assign clear boundaries +- **Conventions**: First teammate's choice becomes standard; propagate to others +- **Resolution authority**: Technical disagreements → Architect arbitrates; Style/convention → First teammate's choice -**Output**: Silent if no conflicts; only mention if conflicts found (e.g., `S2 check: types.ts shared — backend writes, frontend reads`). +**Output**: Silent if no conflicts; only mention if conflicts found (e.g., `S2 check: types.ts shared — backend-1 writes, frontend-1 reads`). **Include in prompts for concurrent specialists**: "You are working concurrently with other specialists. Your scope is [files]. Do not modify files outside your scope." -**Include worktree path in all agent prompts**: "You are working in a git worktree at [worktree_path]. All file paths must be absolute and within this worktree." +**Include worktree path in all teammate prompts**: "You are working in a git worktree at [worktree_path]. All file paths must be absolute and within this worktree." -**Invoke coder(s) with**: +**Spawn coder teammate(s) with**: - Task description - ARCHITECT phase outputs: - Tell the coder(s) where to find them (e.g., "Read `docs/architecture/{feature}.md` for design context") @@ -405,28 +466,36 @@ Before concurrent dispatch, check internally: shared files? shared interfaces? c - If PREPARE/ARCHITECT were skipped, include: "PREPARE and/or ARCHITECT were skipped based on existing context. Minor decisions (naming, local structure) are yours to make. For moderate decisions (interface shape, error patterns), decide and implement but flag the decision with your rationale in the handoff so it can be validated. Major decisions affecting other components are blockers—don't implement, escalate." - "Smoke Testing: Run the test suite before completing. If your changes break existing tests, fix them. Your tests are verification tests—enough to confirm your implementation works. Comprehensive coverage (edge cases, integration, E2E, adversarial) is TEST phase work." +**Example spawn (concurrent)**: +``` +TaskCreate("Implement auth endpoint", owner="backend-1") +TaskCreate("Implement billing endpoint", owner="backend-2") +TaskCreate("Build dashboard UI", owner="frontend-1") +Task(subagent_type="pact-backend-coder", team_name="{team}", name="backend-1", mode="plan", + prompt="CONTEXT: ... MISSION: Implement auth endpoint ... GUIDELINES: ...") +Task(subagent_type="pact-backend-coder", team_name="{team}", name="backend-2", mode="plan", + prompt="CONTEXT: ... MISSION: Implement billing endpoint ... GUIDELINES: ...") +Task(subagent_type="pact-frontend-coder", team_name="{team}", name="frontend-1", mode="plan", + prompt="CONTEXT: ... MISSION: Build dashboard UI ... GUIDELINES: ...") +``` + **Before next phase**: -- [ ] Implementation complete +- [ ] Implementation complete (all coder HANDOFFs received via SendMessage) - [ ] All tests passing (full test suite; fix any tests your changes break) -- [ ] Specialist handoff(s) received -- [ ] If blocker reported → `/PACT:imPACT` +- [ ] If blocker reported (via SendMessage) → `/PACT:imPACT` +- [ ] Shut down all coder teammates - [ ] **Create atomic commit(s)** of CODE phase work (preserves work before strategic re-assessment) - [ ] **S4 Checkpoint**: Environment stable? Model aligned? Plan viable? #### Handling Complex Sub-Tasks During CODE -If a sub-task emerges that is too complex for a single specialist invocation: +If a sub-task emerges that is too complex for a single specialist: | Sub-Task Complexity | Indicators | Use | |---------------------|------------|-----| -| **Simple** | Code-only, clear requirements | Direct specialist invocation | +| **Simple** | Code-only, clear requirements | Direct specialist teammate | | **Focused** | Single domain, no research needed | `/PACT:comPACT` | -| **Complex** | Needs own P→A→C→T cycle | `/PACT:rePACT` | - -**When to use `/PACT:rePACT`:** -- Sub-task needs its own research/preparation phase -- Sub-task requires architectural decisions before coding -- Sub-task spans multiple concerns within a domain +| **Complex** | Needs own P→A→C→T cycle | `/PACT:orchestrate` (new orchestration) | **Phase re-entry** (via `/PACT:imPACT`): When imPACT decides to redo a prior phase, create a new retry phase task — do not reopen the completed one. See [imPACT.md Phase Re-Entry Task Protocol](imPACT.md#phase-re-entry-task-protocol) for details. @@ -436,7 +505,22 @@ If a sub-task emerges that is too complex for a single specialist invocation: Execute the [ATOMIZE Phase protocol](../protocols/pact-scope-phases.md#atomize-phase). -**Worktree isolation**: Before dispatching each sub-scope's rePACT, invoke `/PACT:worktree-setup` with the suffix branch name (e.g., `feature-X--backend`). Pass the resulting worktree path to the rePACT invocation. +**Teammate spawning for sub-scopes**: All sub-scope teammates join the flat session team. Use scoped naming (`"scope-{scope}-{role}"`) for clear identification. Each sub-scope teammate receives its scope contract in the prompt. + +**Worktree isolation**: Before spawning sub-scope teammates, invoke `/PACT:worktree-setup` with the suffix branch name (e.g., `feature-X--backend`). Pass the resulting worktree path to each sub-scope teammate's prompt. + +**Example spawn (ATOMIZE)**: +``` +TaskCreate("Scope-auth: design + implement", owner="scope-auth-architect") +TaskCreate("Scope-auth: implement backend", owner="scope-auth-backend") +TaskCreate("Scope-billing: design + implement", owner="scope-billing-architect") +Task(subagent_type="pact-architect", team_name="{team}", name="scope-auth-architect", mode="plan", + prompt="SCOPE CONTRACT: {auth scope contract} ... WORKTREE: {auth-worktree-path} ...") +Task(subagent_type="pact-backend-coder", team_name="{team}", name="scope-auth-backend", mode="plan", + prompt="SCOPE CONTRACT: {auth scope contract} ... WORKTREE: {auth-worktree-path} ... BLOCKED UNTIL scope-auth-architect completes design") +Task(subagent_type="pact-architect", team_name="{team}", name="scope-billing-architect", mode="plan", + prompt="SCOPE CONTRACT: {billing scope contract} ... WORKTREE: {billing-worktree-path} ...") +``` --- @@ -457,20 +541,48 @@ Execute the [CONSOLIDATE Phase protocol](../protocols/pact-scope-phases.md#conso - "Test Scenarios" - "Coverage Targets" -**Invoke `pact-test-engineer` with**: +**Spawn `pact-test-engineer` teammate(s) with**: - Task description -- CODE phase handoff(s): Pass coder handoff summaries (agent response text, not files on disk) +- CODE phase handoff(s): Pass coder handoff summaries (received via SendMessage) - Plan sections above (if any) - "Reference the approved plan at `docs/plans/{slug}-plan.md` for full context." - "You own ALL substantive testing: unit tests, integration, E2E, edge cases." +**Example spawn**: +``` +TaskCreate("Unit and integration tests", owner="test-1") +TaskCreate("E2E and performance tests", owner="test-2") +Task(subagent_type="pact-test-engineer", team_name="{team}", name="test-1", mode="plan", + prompt="CONTEXT: ... MISSION: Write unit and integration tests ... GUIDELINES: ...") +Task(subagent_type="pact-test-engineer", team_name="{team}", name="test-2", mode="plan", + prompt="CONTEXT: ... MISSION: Write E2E and performance tests ... GUIDELINES: ...") +``` + **Before completing**: - [ ] All tests passing -- [ ] Specialist handoff received -- [ ] If blocker reported → `/PACT:imPACT` +- [ ] HANDOFF received from each test engineer (via SendMessage) +- [ ] If blocker reported (via SendMessage) → `/PACT:imPACT` +- [ ] Shut down all test engineer teammates - [ ] **Create atomic commit(s)** of TEST phase work (preserves work before strategic re-assessment) -**Concurrent dispatch within TEST**: If test suites are independent (e.g., "unit tests AND E2E tests" or "API tests AND UI tests"), invoke multiple test engineers at once with clear suite boundaries. +**Concurrent dispatch within TEST**: If test suites are independent (e.g., "unit tests AND E2E tests" or "API tests AND UI tests"), spawn multiple test engineers at once with clear suite boundaries. + +--- + +## Teammate Monitoring + +### Handling Teammate Messages + +| Message Type | Action | +|--------------|--------| +| Plan approval request | Review plan, approve or reject | +| HANDOFF | Verify completeness (5 items), mark phase progress | +| BLOCKER | Assess severity → `/PACT:imPACT` if needed | +| ALGEDONIC HALT | Stop all work, present to user immediately | +| ALGEDONIC ALERT | Pause, assess, present to user | +| Peer coordination question | Typically no lead action needed (teammate-to-teammate) | + +**Check TaskList** after spawning teammates, on HANDOFF/BLOCKER receipt, and periodically during long-running phases. --- @@ -478,14 +590,21 @@ Execute the [CONSOLIDATE Phase protocol](../protocols/pact-scope-phases.md#conso For stall detection indicators, recovery protocol, prevention, and non-happy-path task termination, see [pact-agent-stall.md](../protocols/pact-agent-stall.md). +**Teammate-specific stall indicators**: +- Teammate has not sent any message for an extended period +- TaskList shows task stuck in `in_progress` with no recent updates +- Teammate's plan approval was sent but no plan received + +**Recovery**: Send a message to the teammate asking for status. If no response, send a shutdown request and re-spawn a new teammate for the task. + --- ## Signal Monitoring -Check TaskList for blocker/algedonic signals: -- After each agent dispatch -- When agent reports completion -- On any unexpected agent stoppage +Check TaskList and inbox for blocker/algedonic signals: +- After spawning each phase's teammates +- When a teammate sends a message +- On any unexpected teammate stoppage On signal detected: Follow Signal Task Handling in CLAUDE.md. diff --git a/pact-plugin/commands/peer-review.md b/pact-plugin/commands/peer-review.md index 32efe87f..38967c52 100644 --- a/pact-plugin/commands/peer-review.md +++ b/pact-plugin/commands/peer-review.md @@ -18,33 +18,34 @@ Create a review Task hierarchy: 1. TaskCreate: Review task "Review: {feature}" 2. TaskUpdate: Review task status = "in_progress" 3. Analyze PR: Which reviewers needed? -4. TaskCreate: Reviewer agent tasks (architect, test-engineer, domain specialists) -5. TaskUpdate: Reviewer tasks status = "in_progress" -6. TaskUpdate: Review task addBlockedBy = [reviewer IDs] -7. Dispatch reviewers in parallel -8. Monitor until reviewers complete -9. TaskUpdate: Reviewer tasks status = "completed" (as each completes) -10. Synthesize findings -11. If major issues: +4. TaskCreate: Reviewer tasks (architect, test-engineer, domain specialists) +5. Spawn reviewer teammates into the session team +6. Reviewers submit review plans for lead approval +7. After approval, reviewers analyze and send reviews via SendMessage +8. Collect reviews as messages arrive +9. Shutdown reviewers after all reviews received +10. TaskUpdate: Reviewer tasks status = "completed" +11. Synthesize findings +12. If major issues: a. TaskCreate: Remediation agent tasks - b. TaskUpdate: Remediation tasks status = "in_progress" - c. Dispatch, monitor until complete + b. Spawn remediation teammates, collect fixes via SendMessage + c. Shutdown remediation teammates d. TaskUpdate: Remediation tasks status = "completed" -12. TaskCreate: "User: review minor issues" step task -13. Present minor issues to user, record decisions in step metadata -14. TaskUpdate: Step task status = "completed" -15. If "fix now" decisions: +13. TaskCreate: "User: review minor issues" step task +14. Present minor issues to user, record decisions in step metadata +15. TaskUpdate: Step task status = "completed" +16. If "fix now" decisions: a. TaskCreate: Remediation agent tasks - b. TaskUpdate: Remediation tasks status = "in_progress" - c. Dispatch, monitor until complete + b. Spawn remediation teammates, collect fixes via SendMessage + c. Shutdown remediation teammates d. TaskUpdate: Remediation tasks status = "completed" -16. TaskCreate: "Awaiting merge decision" approval task -17. Present to user, await approval -18. On approval: TaskUpdate approval task status = "completed" -19. TaskUpdate: Review task status = "completed", metadata.artifact = PR URL +17. TaskCreate: "Awaiting merge decision" approval task +18. Present to user, await approval +19. On approval: TaskUpdate approval task status = "completed" +20. TaskUpdate: Review task status = "completed", metadata.artifact = PR URL ``` -> **Convention**: Synchronous user steps (step tasks, approval tasks) skip the `in_progress` transition — they go directly from `pending` to `completed` since the orchestrator handles them inline without background dispatch. +> **Convention**: Synchronous user steps (step tasks, approval tasks) skip the `in_progress` transition —they go directly from `pending` to `completed` since the orchestrator handles them inline without background dispatch. **Example structure:** ``` @@ -64,18 +65,18 @@ Create a review Task hierarchy: ``` Review task: in_progress (persists until merge-ready) -├─ Cycle N: remediation tasks → re-review (verify-only) → check -├─ After 2 failed cycles: BLOCKER task → addBlockedBy review → /PACT:imPACT -└─ On resolution: blocker completed → review resumes +├── Cycle N: remediation tasks → re-review (verify-only) → check +├── After 2 failed cycles: BLOCKER task → addBlockedBy review → /PACT:imPACT +└── On resolution: blocker completed → review resumes ``` **Key rules**: Review stays `in_progress` until merge-ready; fresh tasks per cycle; re-review is verify-only (minimal scope); imPACT escalation blocks (doesn't complete/delete) review; resume after resolution. --- -**PR Review Workflow** +## Spawning Reviewer Teammates -Pull request reviews should mirror real-world team practices where multiple reviewers sign off before merging. Invoke **at least 3 agents in parallel** to provide comprehensive review coverage: +Pull request reviews should mirror real-world team practices where multiple reviewers sign off before merging. Spawn **at least 3 reviewer teammates** to provide comprehensive review coverage. Standard reviewer combination: - **pact-architect**: Design coherence, architectural patterns, interface contracts, separation of concerns @@ -83,10 +84,78 @@ Standard reviewer combination: - **Domain specialist coder** (selected below): Implementation quality specific to the domain Select the domain coder based on PR focus: -- Frontend changes → **pact-frontend-coder** (UI implementation quality, accessibility, state management) -- Backend changes → **pact-backend-coder** (Server-side implementation quality, API design, error handling) -- Database changes → **pact-database-engineer** (Query efficiency, schema design, data integrity) -- Multiple domains → Coder for domain with most significant changes, or all relevant domain coders if changes are equally significant +- Frontend changes →**pact-frontend-coder** (UI implementation quality, accessibility, state management) +- Backend changes →**pact-backend-coder** (Server-side implementation quality, API design, error handling) +- Database changes →**pact-database-engineer** (Query efficiency, schema design, data integrity) +- Multiple domains →Coder for domain with most significant changes, or all relevant domain coders if changes are equally significant + +### Reviewer Spawn Pattern + +Spawn all reviewers into the existing session team. Reviewers use `mode="plan"` so they submit a review plan before analyzing. + +``` +Task( + subagent_type="pact-architect", + team_name="{team}", + name="architect-reviewer", + mode="plan", + prompt="..." +) + +Task( + subagent_type="pact-test-engineer", + team_name="{team}", + name="test-reviewer", + mode="plan", + prompt="..." +) + +Task( + subagent_type="{domain-coder}", + team_name="{team}", + name="{domain}-reviewer", + mode="plan", + prompt="..." +) +``` + +### Reviewer Prompt Template + +``` +PEER REVIEW —You are a reviewer teammate on this PR. + +PR: {PR URL or description} +Branch: {branch name} +Changed files: {list of changed files} + +As the {role} specialist, review the PR for: +{role-specific review criteria from the reviewer combination above} + +WORKFLOW: +1. Submit a review plan (via ExitPlanMode) describing what you will examine and why. +2. After plan approval, perform the review. +3. Send your review to the lead via SendMessage with the format below. +4. Mark your task complete via TaskUpdate. + +REVIEW FORMAT (send via SendMessage to "team-lead"): +- Summary: One-paragraph assessment +- Findings table: + | Finding | Severity | File(s) | Details | + |---------|----------|---------|---------| + | ... | Blocking/Minor/Future | ... | ... | +- Recommendation: Approve / Request Changes +``` + +### Plan Approval for Reviewers + +Review each reviewer's plan to ensure it covers the reviewer's assigned domain. If rejecting, provide specific guidance on what to cover. + +### Collecting Reviews + +As each review arrives via SendMessage: +1. Record the review content +2. Mark the reviewer's task as `completed` +3. When all reviews are collected, shut down reviewers and proceed to synthesis --- @@ -97,7 +166,7 @@ Select the domain coder based on PR focus: | Internal (don't show) | External (show) | |----------------------|-----------------| | Each reviewer's raw output | Recommendations table + `See docs/review/` | -| Reviewer selection reasoning | `Invoking architect + test engineer + backend coder` | +| Reviewer selection reasoning | `Spawning architect + test engineer + backend reviewer` | | Agreement/conflict analysis details | `Ready to merge` or `Changes requested: [specifics]` | **User can always ask** for full reviewer output (e.g., "What did the architect say?" or "Show me all findings"). @@ -109,7 +178,7 @@ Select the domain coder based on PR focus: --- -**After all reviews complete**: +**After all reviews collected and reviewers shut down**: 1. Synthesize findings into a unified review summary with consolidated recommendations 2. Present **all** findings to user as a **markdown table** **before asking any questions** (blocking, minor, and future): @@ -125,20 +194,20 @@ Select the domain coder based on PR focus: - **No recommendations**: If the table is empty (no blocking, minor, or future items), proceed directly to step 4. - **Blocking**: Automatically address all blocking items: - Batch fixes by selecting appropriate workflow(s) based on combined scope: - - Single-domain items → `/PACT:comPACT` (invoke concurrently if independent) - - Multi-domain items → `/PACT:orchestrate` - - Mixed (both single and multi-domain) → Use `/PACT:comPACT` for the single-domain batch AND `/PACT:orchestrate` for the multi-domain batch (can run in parallel if independent) + - Single-domain items →`/PACT:comPACT` (invoke concurrently if independent) + - Multi-domain items →`/PACT:orchestrate` + - Mixed (both single and multi-domain) →Use `/PACT:comPACT` for the single-domain batch AND `/PACT:orchestrate` for the multi-domain batch (can run in parallel if independent) - After all fixes complete, re-run review to verify fixes only (not a full PR re-review) - - **Termination**: If blocking items persist after 2 fix-verify cycles → escalate via `/PACT:imPACT` + - **Termination**: If blocking items persist after 2 fix-verify cycles →escalate via `/PACT:imPACT` - **Minor + Future**: - **Step A — Initial Gate Question** (Yes/No only): + **Step A —Initial Gate Question** (Yes/No only): - Use `AskUserQuestion` tool: "Would you like to review the minor and future recommendations?" - Options: **Yes** (review each item) / **No** (skip to merge readiness) - If **No**: Skip to step 4 directly - If **Yes**: Continue to Step B - **Step B — Preemptive Context Gathering**: + **Step B —Preemptive Context Gathering**: - Before asking per-recommendation questions, gather and present context for ALL minor and future recommendations - For each recommendation, provide: - Why it matters (impact on code quality, maintainability, security, performance) @@ -148,41 +217,43 @@ Select the domain coder based on PR focus: - Present as a formatted list (one entry per recommendation) so user can review all context at once. - After presenting all context, proceed to Step C. - **Step C — Per-Recommendation Questions** (after context presented): + **Step C —Per-Recommendation Questions** (after context presented): - Use `AskUserQuestion` tool with one question per recommendation - For each **minor** recommendation, ask "Address [recommendation] now?" with options: - - **Yes** — Fix it in this PR - - **No** — Skip for now - - **More context** — Get additional details (if more detail is needed) + - **Yes** —Fix it in this PR + - **No** —Skip for now + - **More context** —Get additional details (if more detail is needed) - For each **future** recommendation, ask "What would you like to do with [recommendation]?" with options: - - **Create GitHub issue** — Track for future work - - **Skip** — Don't track or address - - **Address now** — Fix it in this PR - - **More context** — Get additional details (if more detail is needed) + - **Create GitHub issue** —Track for future work + - **Skip** —Don't track or address + - **Address now** —Fix it in this PR + - **More context** —Get additional details (if more detail is needed) - Note: Tool supports 2-4 options per question and 1-4 questions per call. If >4 recommendations exist, make multiple `AskUserQuestion` calls to cover all items. - **Handling "More context" responses**: - When user selects "More context", provide deeper explanation beyond the preemptive context (e.g., implementation specifics, examples, related patterns) - After providing additional context, re-ask the same question for that specific recommendation (without the "More context" option) - Handle inline: provide context immediately, get the answer, then continue to the next recommendation - **Collect all answers first**, then batch work: - - Group all minor=Yes items AND future="Address now" items → Select workflow based on combined scope: - - Single-domain items → `/PACT:comPACT` (invoke concurrently if independent) - - Multi-domain items → `/PACT:orchestrate` - - Group all future="Create GitHub issue" items → Create GitHub issues - - If any items fixed (minor or future addressed now) → re-run review to verify fixes only (not a full PR re-review) + - Group all minor=Yes items AND future="Address now" items →Select workflow based on combined scope: + - Single-domain items →`/PACT:comPACT` (invoke concurrently if independent) + - Multi-domain items →`/PACT:orchestrate` + - Group all future="Create GitHub issue" items →Create GitHub issues + - If any items fixed (minor or future addressed now) →re-run review to verify fixes only (not a full PR re-review) 4. State merge readiness (only after ALL blocking fixes complete AND minor/future item handling is done): "Ready to merge" or "Changes requested: [specifics]" -5. Present to user and **stop** — merging requires explicit user authorization (S5 policy) +5. Present to user and **stop** —merging requires explicit user authorization (S5 policy) --- ## Signal Monitoring -Check TaskList for blocker/algedonic signals: -- After each reviewer dispatch +Monitor for blocker/algedonic signals: +- After spawning each reviewer +- After plan approval for each reviewer +- When reviewer sends their review - After each remediation dispatch -- On any unexpected agent stoppage +- On any unexpected teammate stoppage On signal detected: Follow Signal Task Handling in CLAUDE.md. diff --git a/pact-plugin/commands/plan-mode.md b/pact-plugin/commands/plan-mode.md index e4382844..189a7f89 100644 --- a/pact-plugin/commands/plan-mode.md +++ b/pact-plugin/commands/plan-mode.md @@ -4,7 +4,7 @@ argument-hint: [e.g., add user authentication with JWT] --- Create a comprehensive implementation plan for: $ARGUMENTS -**This is PLANNING ONLY** — no code changes, no git branches, no implementation. +**This is PLANNING ONLY** —no code changes, no git branches, no implementation. --- @@ -16,14 +16,15 @@ Create a planning Task hierarchy: 1. TaskCreate: Planning task "Plan: {feature}" 2. TaskUpdate: Planning task status = "in_progress" 3. Analyze: Which specialists to consult? -4. TaskCreate: Consultation task(s) — one per specialist -5. TaskUpdate: Consultation tasks status = "in_progress" -6. TaskUpdate: Planning task addBlockedBy = [consultation IDs] -7. Dispatch specialists in parallel (planning-only mode) -8. Monitor until consultations complete -9. TaskUpdate: Consultation tasks status = "completed" (as each completes) -10. Synthesize → write plan document -11. TaskUpdate: Planning task status = "completed", metadata.artifact = plan path +4. TaskCreate: Consultation task(s) —one per specialist +5. Spawn consultant teammates into the session team (planning-only mode) +6. Consultants submit analysis plans for lead approval +7. After approval, consultants analyze and send perspectives via SendMessage +8. Collect perspectives as messages arrive +9. Shutdown consultants after all perspectives received +10. TaskUpdate: Consultation tasks status = "completed" +11. Synthesize →write plan document +12. TaskUpdate: Planning task status = "completed", metadata.artifact = plan path ``` **Example structure:** @@ -44,7 +45,7 @@ This command is the primary **S4 (Intelligence)** activity in PACT. While `/PACT - **Future focus**: What approach will lead to long-term success? - **Strategic thinking**: What are the risks? What could change? -The output—an approved plan—bridges S4 intelligence to S3 execution. When `/PACT:orchestrate` runs, it shifts to S3 mode while referencing the S4 plan. +The output —an approved plan —bridges S4 intelligence to S3 execution. When `/PACT:orchestrate` runs, it shifts to S3 mode while referencing the S4 plan. **S4 Questions to Hold Throughout**: - Are we solving the right problem? @@ -78,12 +79,12 @@ Using extended thinking, analyze the task: - What's the estimated complexity (Low/Medium/High/Very High)? Determine which specialists to invoke based on the task: -- **📚 pact-preparer**: Always include for research/context needs -- **🏛️ pact-architect**: Include for any structural or design decisions -- **💻 pact-backend-coder**: Include if server-side work is involved -- **🎨 pact-frontend-coder**: Include if client-side work is involved -- **🗄️ pact-database-engineer**: Include if data layer work is involved -- **🧪 pact-test-engineer**: Always include for testing strategy +- **pact-preparer**: Always include for research/context needs +- **pact-architect**: Include for any structural or design decisions +- **pact-backend-coder**: Include if server-side work is involved +- **pact-frontend-coder**: Include if client-side work is involved +- **pact-database-engineer**: Include if data layer work is involved +- **pact-test-engineer**: Always include for testing strategy Skip specialists clearly not relevant (e.g., skip database engineer for pure UI work). @@ -91,18 +92,58 @@ Skip specialists clearly not relevant (e.g., skip database engineer for pure UI - Convert task to lowercase kebab-case - Keep it concise (3-5 words max) - Examples: - - "Add user authentication with JWT" → `user-auth-jwt` - - "Refactor payment processing module" → `refactor-payment-processing` - - "Fix dashboard loading performance" → `fix-dashboard-performance` + - "Add user authentication with JWT" →`user-auth-jwt` + - "Refactor payment processing module" →`refactor-payment-processing` + - "Fix dashboard loading performance" →`fix-dashboard-performance` -### Phase 1: Parallel Specialist Consultation +### Phase 1: Spawn Consultant Teammates -Invoke relevant specialists **in parallel**, each in **planning-only mode**. +Spawn relevant specialists **in parallel** into the session team, each in **planning-only mode** using `mode="plan"`. -**Use this prompt template for each specialist:** +#### Consultant Spawn Pattern ``` -PLANNING CONSULTATION ONLY — No implementation, no code changes. +Task( + subagent_type="pact-preparer", + team_name="{team}", + name="preparer-consultant", + mode="plan", + prompt="..." +) + +Task( + subagent_type="pact-architect", + team_name="{team}", + name="architect-consultant", + mode="plan", + prompt="..." +) + +Task( + subagent_type="pact-test-engineer", + team_name="{team}", + name="test-consultant", + mode="plan", + prompt="..." +) +``` + +Add domain coders as needed: +``` +Task( + subagent_type="pact-backend-coder", + team_name="{team}", + name="backend-consultant", + mode="plan", + prompt="..." +) +``` + +#### Consultant Prompt Template + +``` +PLANNING CONSULTATION ONLY —No implementation, no code changes. +You are a consultant teammate providing planning perspective. Task: {task description} @@ -132,18 +173,23 @@ As the {role} specialist, provide your planning perspective: - What sequence of steps do you recommend? - What should be done first? -Output your analysis with clear headers matching the 5 sections above. -Do NOT implement anything — planning consultation only. +WORKFLOW: +1. Submit an analysis plan (via ExitPlanMode) describing what you will examine. +2. After plan approval, perform your analysis. +3. Send your perspective to the lead via SendMessage with clear headers matching the 5 sections above. +4. Mark your task complete via TaskUpdate. + +Do NOT implement anything —planning consultation only. ``` **Domain-specific additions to the template:** -For **📚 pact-preparer**, also ask: +For **pact-preparer**, also ask: - What documentation/research is needed before implementation? - What external APIs or libraries need investigation? - What stakeholder clarifications are needed? -For **🏛️ pact-architect**, also ask: +For **pact-architect**, also ask: - What components/modules are affected or needed? - What design patterns should be applied? - What interface contracts need definition? @@ -153,20 +199,31 @@ For **coders** (backend/frontend/database), also ask: - What existing patterns in the codebase should be followed? - What's the implementation sequence? -For **🧪 pact-test-engineer**, also ask: +For **pact-test-engineer**, also ask: - What test scenarios are critical (happy path, errors, edge cases)? - What coverage targets make sense? - What test data or fixtures are needed? +#### Plan Approval for Consultants + +Review each consultant's plan to ensure it covers the consultant's assigned domain. If rejecting, provide specific guidance on what to analyze. + +#### Collecting Perspectives + +As each perspective arrives via SendMessage: +1. Record the perspective content +2. Mark the consultant's task as `completed` +3. When all perspectives are collected, shut down consultants and proceed to synthesis + **Handling incomplete or missing responses**: -If a specialist provides minimal, incomplete, or off-topic output: -1. Note the gap — record which specialist and which sections are missing -2. Proceed with synthesis — use the inputs you have -3. Flag in the plan — add to "Limitations" section with specific gaps identified -4. Do NOT re-invoke — avoid infinite loops; missing input is data for the plan +If a consultant provides minimal, incomplete, or off-topic output: +1. Note the gap —record which consultant and which sections are missing +2. Proceed with synthesis —use the inputs you have +3. Flag in the plan —add to "Limitations" section with specific gaps identified +4. Do NOT re-invoke —avoid infinite loops; missing input is data for the plan -If a specialist fails entirely (timeout, error): +If a consultant fails entirely (timeout, error, unexpected stoppage): 1. Log the failure in synthesis notes 2. Proceed without that perspective 3. Flag prominently in "Open Questions" that this domain was not consulted @@ -174,7 +231,7 @@ If a specialist fails entirely (timeout, error): ### Phase 2: Orchestrator Synthesis -After collecting all specialist outputs, use extended thinking to synthesize: +After collecting all consultant outputs, use extended thinking to synthesize: 1. **Identify Agreements** - Where do specialists align? @@ -221,7 +278,7 @@ After collecting all specialist outputs, use extended thinking to synthesize: - [ ] Unchecked questions to resolve - [ ] Empty/placeholder sections - [ ] Unresolved open questions - - **Any signal present** → mark phase as REQUIRED + - **Any signal present** →mark phase as REQUIRED - For more details on incompleteness signals, see [pact-completeness.md](../protocols/pact-completeness.md) 6. **Risk Assessment** @@ -238,9 +295,9 @@ After collecting all specialist outputs, use extended thinking to synthesize: - [ ] Cross-cutting concerns have been considered If validation fails: - - For insufficient specialist input → Flag in "Limitations", proceed with available data - - For unresolved blocking conflict → Present partial plan with BLOCKED status - - For missing mandatory sections → Populate with "TBD - requires {specific input}" + - For insufficient specialist input →Flag in "Limitations", proceed with available data + - For unresolved blocking conflict →Present partial plan with BLOCKED status + - For missing mandatory sections →Populate with "TBD - requires {specific input}" ### Phase 3: Plan Output @@ -281,16 +338,16 @@ If a plan already exists for this feature slug: > Status: PENDING APPROVAL