From be52783fac60182208cb99ef1ea789793d401ae8 Mon Sep 17 00:00:00 2001 From: michael-wojcik <5386199+michael-wojcik@users.noreply.github.com> Date: Fri, 6 Feb 2026 16:07:30 -0500 Subject: [PATCH 01/28] feat: rewrite pact-task-tracking skill for Agent Teams model Replace the subagent text-based reporting model with Agent Teams SendMessage-based communication and Task tool self-management. 10 sections: task self-management, progress reporting, blocker delivery, algedonic signals (dual-delivery HALT + direct ALERT), pre-completion self-validation, memory preservation, HANDOFF format/delivery, peer communication guidance, plan approval workflow. --- .../skills/pact-task-tracking/SKILL.md | 163 +++++++++++++++--- 1 file changed, 138 insertions(+), 25 deletions(-) diff --git a/pact-plugin/skills/pact-task-tracking/SKILL.md b/pact-plugin/skills/pact-task-tracking/SKILL.md index e40221ba..186ac9fa 100644 --- a/pact-plugin/skills/pact-task-tracking/SKILL.md +++ b/pact-plugin/skills/pact-task-tracking/SKILL.md @@ -1,64 +1,124 @@ --- name: pact-task-tracking description: | - Task tracking protocol for PACT specialist agents. Auto-loaded via agent frontmatter. - Defines how to report progress, blockers, and completion status via text-based reporting. + Task tracking and communication protocol for PACT specialist agents operating + as Agent Teams teammates. Auto-loaded via agent frontmatter. Defines task + self-management, message-based communication, and completion workflows. --- # Task Tracking Protocol > **Architecture**: See [pact-task-hierarchy.md](../../protocols/pact-task-hierarchy.md) for the full hierarchy model. -## Important: Agents Do Not Have Task Tools +## Task Self-Management -Agents do **NOT** have access to Task tools (TaskCreate, TaskUpdate, TaskGet, TaskList). All Task operations are performed by the orchestrator. Agents communicate status through structured text in their responses, and the orchestrator translates these into Task operations. +You have direct access to Task tools. Use them to manage your own work: -## On Start +- **TaskUpdate**: Claim unassigned tasks in your domain, mark tasks in-progress or complete. +- **TaskList**: View team progress and discover unassigned tasks. +- **TaskCreate**: Create sub-tasks if your work expands beyond the original scope. -Begin working immediately. The orchestrator tracks your task status — no status reporting is needed from you. +### Conventions + +- The team lead is always named **"team-lead"**. +- Claim only tasks within your specialist domain. Do not claim cross-domain tasks. +- When claiming an unassigned task, use `TaskUpdate(taskId, status: "in_progress")`. +- When your task is done, use `TaskUpdate(taskId, status: "completed")` as part of your HANDOFF delivery (see section 8). ## Progress Reporting -Report progress naturally in your responses. The orchestrator monitors your output and updates task status accordingly. +Report progress naturally in your responses. For significant milestones, update your task status via TaskUpdate. You do not need to send progress messages to the lead unless you have a specific question or finding to share. ## On Blocker If you cannot proceed: -1. **Stop work immediately** -2. Report: `BLOCKER: {description of what is blocking you}` -3. Provide a partial HANDOFF (see format below) with whatever work you completed - -Do not attempt to work around the blocker. The orchestrator will triage and resolve it. +1. **Stop work immediately.** +2. Send the blocker to the lead: + ``` + SendMessage(type: "message", recipient: "team-lead", + content: "BLOCKER: {description of what is blocking you}\n\nPartial HANDOFF:\n1. Produced: {files}\n2. Key decisions: {decisions}\n3. Areas of uncertainty: {uncertainties}\n4. Integration points: {points}\n5. Open questions: {questions}", + summary: "BLOCKER: {brief description}") + ``` +3. Do not attempt to work around the blocker. The lead will triage and resolve it. ## On Algedonic Signal -When you detect a viability threat (security, data integrity, ethics): +When you detect a viability threat (security, data integrity, ethics), the delivery method depends on the signal level. + +See the [algedonic protocol](../../protocols/algedonic.md) for trigger categories and severity guidance. + +### HALT Signal (Dual-Delivery) -1. **Stop work immediately** -2. Report using this format: +HALT signals (SECURITY, DATA, ETHICS) must reach both the lead AND all peers. Use two SendMessage calls: + +1. **Stop work immediately.** +2. **Direct message to lead** (guaranteed delivery): + ``` + SendMessage(type: "message", recipient: "team-lead", + content: "⚠️ ALGEDONIC HALT: {CATEGORY}\n\n**Issue**: {one-line description}\n**Evidence**: {file, line, what you observed}\n**Impact**: {why this threatens viability}\n**Recommended Action**: {what you suggest}", + summary: "HALT: {category}") + ``` +3. **Broadcast to all peers** (so they stop work): ``` - ⚠️ ALGEDONIC [HALT|ALERT]: {Category} + SendMessage(type: "broadcast", + content: "⚠️ ALGEDONIC HALT: {CATEGORY}\n\n**Issue**: {one-line description}\n**Evidence**: {file, line, what you observed}\n**Impact**: {why this threatens viability}\n**Recommended Action**: {what you suggest}\n\nSTOP ALL WORK IMMEDIATELY. Await lead instructions.", + summary: "HALT: {category}") + ``` +4. **Send partial HANDOFF** to the lead via a separate SendMessage (see HANDOFF format in section 8). + +### ALERT Signal (Direct Message Only) - Issue: {One-line description} - Evidence: {Specific details — file, line, what you observed} - Impact: {Why this threatens viability} - Recommended Action: {What you suggest} +ALERT signals (QUALITY, SCOPE, META-BLOCK) go to the lead only. The lead decides whether peers need to be notified. + +1. **Stop work immediately.** +2. **Direct message to lead**: + ``` + SendMessage(type: "message", recipient: "team-lead", + content: "⚠️ ALGEDONIC ALERT: {CATEGORY}\n\n**Issue**: {one-line description}\n**Evidence**: {file, line, what you observed}\n**Impact**: {why this threatens viability}\n**Recommended Action**: {what you suggest}", + summary: "ALERT: {category}") ``` -3. Provide a partial HANDOFF with whatever work you completed +3. **Send partial HANDOFF** to the lead via a separate SendMessage (see HANDOFF format in section 8). + +## Pre-Completion Checklist (Self-Validation) + +Before sending your HANDOFF, verify ALL of these are present: + +1. [ ] **Produced**: At least one file or artifact listed +2. [ ] **Key decisions**: At least one decision with rationale (or "No decisions required" if truly none) +3. [ ] **Areas of uncertainty**: Prioritized list OR explicit "No areas of uncertainty flagged" +4. [ ] **Integration points**: Components touched OR "None" +5. [ ] **Open questions**: Items listed OR "None" + +If any item is missing, add it before completing. Do NOT send an incomplete HANDOFF. -See the algedonic protocol for trigger categories and severity guidance. +## Memory Preservation -## On Completion — HANDOFF (Required) +After completing your work but BEFORE sending your HANDOFF message, save your work context: -End every response with a structured HANDOFF. This is mandatory — the orchestrator uses it to coordinate subsequent work. +1. Load the `pact-memory` skill. +2. Save a memory with: + - `context`: What you were working on and why + - `goal`: The objective of your task + - `lessons_learned`: Insights, patterns, things that worked or did not + - `decisions`: Key choices with rationale + - `entities`: Components, files, services involved + - `files`: File paths you created or modified + +Do this BEFORE sending your HANDOFF. Memory saves that happen after your process ends may be lost. + +## On Completion -- HANDOFF (Required) + +Every completed task must end with a structured HANDOFF delivered to the lead. + +### Format ``` HANDOFF: 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 + - [HIGH] {description} -- Why risky, suggested test focus - [MEDIUM] {description} - [LOW] {description} 4. Integration points: Other components touched @@ -66,3 +126,56 @@ HANDOFF: ``` All five items are required. Not all priority levels need to be present in Areas of uncertainty. If you have no uncertainties, explicitly state "No areas of uncertainty flagged." + +### Delivery + +Send the HANDOFF via SendMessage AND mark your task complete: + +``` +SendMessage(type: "message", recipient: "team-lead", + content: "HANDOFF:\n1. Produced: ...\n2. Key decisions: ...\n3. Areas of uncertainty: ...\n4. Integration points: ...\n5. Open questions: ...", + summary: "HANDOFF: {brief description of what was completed}") +``` + +Then mark the task complete: + +``` +TaskUpdate(taskId, status: "completed") +``` + +## Peer Communication Guidance + +You can communicate with peer teammates when coordination is needed. + +### When to Message a Peer + +- Sharing findings directly relevant to a peer's current task +- Coordinating on a shared interface or contract +- Reporting an issue that affects a peer's work + +### When NOT to Message a Peer + +- General status updates (use TaskUpdate instead) +- Questions that should go to the lead (use SendMessage to "team-lead") +- Anything requiring lead approval or triage + +### How to Message a Peer + +``` +SendMessage(type: "message", recipient: "{peer-name}", + content: "{your message}", + summary: "{5-10 word summary}") +``` + +Peer names are visible via TaskList (task owners) or your team configuration. + +## Plan Approval Workflow + +When you are spawned with `plan_mode_required`, you must submit a plan before implementing. + +1. **Analyze your task**: Read relevant documentation, understand requirements, identify approach. +2. **Create your plan**: Outline what you will do, in what order, and why. +3. **Submit via ExitPlanMode**: The lead receives your plan and reviews it. +4. **Wait for approval**: Do not begin implementation until the lead approves your plan. +5. **If rejected**: Revise your plan based on the lead's feedback and resubmit via ExitPlanMode. +6. **After approval**: Proceed with implementation following your approved plan. From 8e53b092723fcd040cc58fc0889b94530ffbc9ee Mon Sep 17 00:00:00 2001 From: michael-wojcik <5386199+michael-wojcik@users.noreply.github.com> Date: Fri, 6 Feb 2026 16:16:04 -0500 Subject: [PATCH 02/28] feat: rewrite orchestrate.md for Agent Teams teammate model Replace subagent dispatch with teammate spawning pattern. Add Team Lifecycle, Plan Approval workflow, SendMessage-based monitoring, teammate shutdown between phases, and HALT signal handling for concurrent teammates. --- pact-plugin/commands/orchestrate.md | 276 ++++++++++++++++++++++------ 1 file changed, 222 insertions(+), 54 deletions(-) diff --git a/pact-plugin/commands/orchestrate.md b/pact-plugin/commands/orchestrate.md index c1a5c75f..de0d4ea4 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/plan_mode_required) +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,63 @@ 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="...") +``` + +**Parameters**: +- `subagent_type`: The agent definition to use (e.g., `"pact-backend-coder"`) +- `team_name`: The session team name (from hook or TeamCreate) +- `name`: A discoverable name for the teammate (e.g., `"backend-1"`, `"preparer-1"`) +- `mode`: Set to `"plan"` to require Plan Approval before implementation +- `prompt`: The task description, context, and instructions + +**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 Workflow + +All teammates are spawned with `mode="plan"` (plan approval required). The workflow: + +1. **Teammate analyzes task** and creates a plan. +2. **Teammate submits plan** via ExitPlanMode. +3. **Lead reviews the plan** — receives it as a plan approval request message. +4. **Lead approves or rejects**: + ``` + SendMessage(type: "plan_approval_response", request_id: "{id}", recipient: "{teammate-name}", approve: true) + ``` + Or to reject with feedback: + ``` + SendMessage(type: "plan_approval_response", request_id: "{id}", recipient: "{teammate-name}", approve: false, content: "Please also consider X") + ``` +5. **After approval**, teammate proceeds with implementation. +6. **If rejected**, teammate revises and resubmits. + +**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 + +Before proceeding to the next phase, shut down all current-phase teammates: + +``` +SendMessage(type: "shutdown_request", recipient: "{teammate-name}", content: "Phase complete. Shutting down.") +``` + +Send shutdown requests to each active teammate. Teammates respond with shutdown approval or rejection. Wait for all shutdowns to be acknowledged before spawning next-phase teammates. + +**If a teammate rejects shutdown**: It may still be completing work. Check TaskList for its task status. If the task is complete, re-send the shutdown request. If incomplete, wait for completion. + +--- + ### PREPARE Phase → `pact-preparer` **Skip criteria met (including completeness check)?** → Proceed to ARCHITECT phase. @@ -246,18 +322,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 +372,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 +382,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 +395,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 +404,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 +426,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 +443,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 +458,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 +468,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 +476,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 +497,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 +536,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 +572,66 @@ 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 + +### How Teammates Communicate + +Teammates communicate via SendMessage. The lead's inbox receives these automatically: +- **HANDOFF messages**: Structured completion report (5-item format) +- **BLOCKER messages**: Stop-work notification with partial handoff +- **ALGEDONIC messages**: HALT (broadcast to all) or ALERT (direct to lead) +- **Plan approval requests**: Teammate submitting plan for review + +### Monitoring Progress + +Use TaskList to monitor teammate progress: +- Teammates self-update their task status via TaskUpdate +- TaskList shows all tasks with current status and owner + +**Check TaskList**: +- After spawning each phase's teammates +- When a teammate sends a HANDOFF message +- When a teammate reports a blocker +- Periodically during long-running phases + +### 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) | --- @@ -478,14 +639,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. From eb20054d38b5e6719874f535361b5aefc5820dea Mon Sep 17 00:00:00 2001 From: michael-wojcik <5386199+michael-wojcik@users.noreply.github.com> Date: Fri, 6 Feb 2026 16:16:10 -0500 Subject: [PATCH 03/28] feat: rewrite comPACT.md and update imPACT.md for Agent Teams comPACT: Replace subagent dispatch with teammate spawning into session team. Add Plan Approval, shutdown pattern, peer-review team reuse. imPACT: Remove rePACT references, update terminology to teammate model, use SendMessage for blocker reporting. --- pact-plugin/commands/comPACT.md | 155 ++++++++++++++++++++------------ pact-plugin/commands/imPACT.md | 34 +++---- 2 files changed, 116 insertions(+), 73 deletions(-) diff --git a/pact-plugin/commands/comPACT.md b/pact-plugin/commands/comPACT.md index b28bdb24..7b11f2c9 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,24 +17,26 @@ 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:** ``` [Feature] "Fix 3 backend bugs" (blockedBy: agent1, agent2, agent3) -├── [Agent] "backend-coder: fix bug A" -├── [Agent] "backend-coder: fix bug B" -└── [Agent] "backend-coder: fix bug C" ++-- [Agent] "backend-coder: fix bug A" ++-- [Agent] "backend-coder: fix bug B" ++-- [Agent] "backend-coder: fix bug C" ``` --- @@ -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,77 @@ 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 + +Teammates are spawned into the existing session team using: + +``` +Task( + subagent_type="pact-{specialist}", + team_name="{team}", + name="{specialist-N}", + prompt="...", + plan_mode_required=true +) +``` + +The team already exists (created by the session-start hook). comPACT spawns specialists INTO the existing team. 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 +219,70 @@ 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 - -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). +## Plan Approval + +All teammates are spawned with `plan_mode_required=true`. Before implementing, each teammate submits a plan for lead review. + +**Lead workflow**: +1. Teammate submits plan via `ExitPlanMode` +2. Lead receives `plan_approval_request` message +3. Lead reviews the plan: + - Does it align with the task scope? + - Are file boundaries respected (for concurrent work)? + - Is the approach reasonable? +4. Approve or reject: + ``` + SendMessage(type: "plan_approval_response", request_id: "...", + recipient: "{teammate-name}", approve: true) + ``` + Or reject with feedback: + ``` + SendMessage(type: "plan_approval_response", request_id: "...", + recipient: "{teammate-name}", approve: false, + content: "Adjust approach: {feedback}") + ``` --- -## 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: + ``` + SendMessage(type: "shutdown_request", recipient: "{teammate-name}", + content: "Work complete, shutting down") + ``` +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..4f067f15 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(type: "message", recipient: "team-lead", content: "BLOCKER: {description}")`. The orchestrator creates blocker Tasks and uses `addBlockedBy` to block the teammate's task. When the blocker is resolved (marked completed), the teammate's task becomes unblocked. --- @@ -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" ``` --- @@ -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 From e7318e8d8a91427aa721ba03a78a5de4e96b9aaa Mon Sep 17 00:00:00 2001 From: michael-wojcik <5386199+michael-wojcik@users.noreply.github.com> Date: Fri, 6 Feb 2026 16:16:17 -0500 Subject: [PATCH 04/28] feat: rewrite peer-review.md and plan-mode.md for Agent Teams peer-review: Spawn reviewer teammates with SendMessage-based review delivery, plan_mode_required for all reviewers, structured shutdown. plan-mode: Spawn consultant teammates in planning-only mode with SendMessage-based perspective collection and plan approval workflow. --- pact-plugin/commands/peer-review.md | 221 +++++++++++++++++++-------- pact-plugin/commands/plan-mode.md | 222 +++++++++++++++++++--------- 2 files changed, 310 insertions(+), 133 deletions(-) diff --git a/pact-plugin/commands/peer-review.md b/pact-plugin/commands/peer-review.md index 32efe87f..beaf236f 100644 --- a/pact-plugin/commands/peer-review.md +++ b/pact-plugin/commands/peer-review.md @@ -18,64 +18,65 @@ 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:** ``` [Review] "Review: user authentication" -├── [Agent] "architect: design review" -├── [Agent] "test-engineer: coverage review" -├── [Agent] "backend-coder: implementation review" -├── [Remediation] (dynamic, for major issues) -│ └── [Agent] "fix: auth vulnerability" -├── [Step] "User: review minor issues" -├── [Remediation] (dynamic, for "fix now" minors) -│ └── [Agent] "fix: input validation" -└── [Approval] "Awaiting merge decision" +|-- [Agent] "architect: design review" +|-- [Agent] "test-engineer: coverage review" +|-- [Agent] "backend-coder: implementation review" +|-- [Remediation] (dynamic, for major issues) +| +-- [Agent] "fix: auth vulnerability" +|-- [Step] "User: review minor issues" +|-- [Remediation] (dynamic, for "fix now" minors) +| +-- [Agent] "fix: input validation" ++-- [Approval] "Awaiting merge decision" ``` ## Remediation Task State ``` 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,100 @@ 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 `plan_mode_required` so they submit a review plan before analyzing. + +``` +Task( + subagent_type="pact-architect", + team_name="{team}", + name="architect-reviewer", + plan_mode_required=true, + prompt="..." +) + +Task( + subagent_type="pact-test-engineer", + team_name="{team}", + name="test-reviewer", + plan_mode_required=true, + prompt="..." +) + +Task( + subagent_type="{domain-coder}", + team_name="{team}", + name="{domain}-reviewer", + plan_mode_required=true, + 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 + +When a reviewer submits their review plan via ExitPlanMode: +1. Receive the plan approval request message +2. Review the plan -- ensure it covers the reviewer's assigned domain +3. Approve or reject with feedback: + ``` + SendMessage(type: "plan_approval_response", + request_id: "{request_id}", + recipient: "{reviewer-name}", + approve: true) + ``` +4. If rejected, provide specific guidance on what to cover + +### Collecting Reviews + +Reviews arrive as SendMessage deliveries from reviewer teammates. As each review arrives: +1. Record the review content +2. TaskUpdate the reviewer's task as `completed` +3. When all reviews are collected, proceed to shutdown and synthesis + +### Shutting Down Reviewers + +After all reviews are collected, shutdown each reviewer: + +``` +SendMessage(type: "shutdown_request", + recipient: "{reviewer-name}", + content: "Review complete, shutting down") +``` + +Reviewers will approve the shutdown via their pact-task-tracking protocol. --- @@ -97,7 +188,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 +200,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 +216,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 +239,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..d73bc8bc 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,22 +16,23 @@ 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:** ``` [Planning] "Plan: user authentication" (blockedBy: consult1, consult2, consult3) -├── [Consult] "preparer: research auth patterns" -├── [Consult] "architect: design auth service" -└── [Consult] "test-engineer: testing strategy" +|-- [Consult] "preparer: research auth patterns" +|-- [Consult] "architect: design auth service" ++-- [Consult] "test-engineer: testing strategy" ``` --- @@ -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,62 @@ 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", + plan_mode_required=true, + prompt="..." +) + +Task( + subagent_type="pact-architect", + team_name="{team}", + name="architect-consultant", + mode="plan", + plan_mode_required=true, + prompt="..." +) + +Task( + subagent_type="pact-test-engineer", + team_name="{team}", + name="test-consultant", + mode="plan", + plan_mode_required=true, + prompt="..." +) +``` + +Add domain coders as needed: +``` +Task( + subagent_type="pact-backend-coder", + team_name="{team}", + name="backend-consultant", + mode="plan", + plan_mode_required=true, + 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 +177,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 +203,53 @@ 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 + +When a consultant submits their analysis plan via ExitPlanMode: +1. Receive the plan approval request message +2. Review the plan -- ensure it covers the consultant's assigned domain +3. Approve or reject with feedback: + ``` + SendMessage(type: "plan_approval_response", + request_id: "{request_id}", + recipient: "{consultant-name}", + approve: true) + ``` +4. If rejected, provide specific guidance on what to analyze + +#### Collecting Perspectives + +Perspectives arrive as SendMessage deliveries from consultant teammates. As each perspective arrives: +1. Record the perspective content +2. TaskUpdate the consultant's task as `completed` +3. When all perspectives are collected, proceed to shutdown and synthesis + +#### Shutting Down Consultants + +After all perspectives are collected, shutdown each consultant: + +``` +SendMessage(type: "shutdown_request", + recipient: "{consultant-name}", + content: "Planning consultation complete, shutting down") +``` + +Consultants will approve the shutdown via their pact-task-tracking protocol. + **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 +257,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 +304,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 +321,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 +364,16 @@ If a plan already exists for this feature slug: > Status: PENDING APPROVAL