@gtheys/pi-interactive-subagents 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +462 -2
  3. package/agents/claude-code.md +23 -0
  4. package/agents/planner.md +569 -0
  5. package/agents/reviewer.md +152 -0
  6. package/agents/scout.md +112 -0
  7. package/agents/visual-tester.md +202 -0
  8. package/agents/worker.md +109 -0
  9. package/config.json.example +6 -0
  10. package/config.schema.json +71 -0
  11. package/package.json +59 -4
  12. package/pi-extension/subagents/activity.ts +730 -0
  13. package/pi-extension/subagents/asks.ts +234 -0
  14. package/pi-extension/subagents/assignments.ts +395 -0
  15. package/pi-extension/subagents/config.ts +191 -0
  16. package/pi-extension/subagents/control.ts +172 -0
  17. package/pi-extension/subagents/dataroot.ts +52 -0
  18. package/pi-extension/subagents/delivered.ts +81 -0
  19. package/pi-extension/subagents/flow-env.ts +112 -0
  20. package/pi-extension/subagents/herdr.ts +323 -0
  21. package/pi-extension/subagents/inbox.ts +213 -0
  22. package/pi-extension/subagents/index.ts +5003 -0
  23. package/pi-extension/subagents/lock.ts +318 -0
  24. package/pi-extension/subagents/peer-bindings.ts +175 -0
  25. package/pi-extension/subagents/peers.ts +401 -0
  26. package/pi-extension/subagents/plan-skill.md +219 -0
  27. package/pi-extension/subagents/plugin/.claude-plugin/plugin.json +5 -0
  28. package/pi-extension/subagents/plugin/hooks/hooks.json +15 -0
  29. package/pi-extension/subagents/plugin/hooks/on-stop.sh +68 -0
  30. package/pi-extension/subagents/retention.ts +918 -0
  31. package/pi-extension/subagents/retirement.ts +216 -0
  32. package/pi-extension/subagents/session.ts +194 -0
  33. package/pi-extension/subagents/snapshot.ts +151 -0
  34. package/pi-extension/subagents/spawn.ts +237 -0
  35. package/pi-extension/subagents/spawnseq.ts +116 -0
  36. package/pi-extension/subagents/state-events.ts +152 -0
  37. package/pi-extension/subagents/status.ts +886 -0
  38. package/pi-extension/subagents/store.ts +245 -0
  39. package/pi-extension/subagents/subagent-done.ts +1452 -0
  40. package/pi-extension/subagents/surface.ts +365 -0
  41. package/pi-extension/subagents/task-composition.ts +113 -0
  42. package/pi-extension/subagents/tool-effects.ts +203 -0
  43. package/pi-extension/subagents/usage.ts +330 -0
  44. package/pi-extension/subagents/watermark.ts +126 -0
  45. package/pi-extension/subagents/worktrees.ts +147 -0
  46. package/skills/subagent-orchestration/SKILL.md +57 -0
@@ -0,0 +1,401 @@
1
+ // Peer-to-peer messaging between same-role live subagents (PMR-98S6).
2
+ // Presence records `<dataRoot>/peers/<childId>.json` name the child's process
3
+ // lock claim; a record is VALID only while its claim is the live generation of
4
+ // the lock keyed on the child's session file (dead pid or superseded claim ⇒
5
+ // filtered). Messages land in a durable per-child inbox
6
+ // `<dataRoot>/peers/<childId>/inbox/<seq>.json`; the recipient's pump
7
+ // delivers them as new turns and deletes them afterwards.
8
+ //
9
+ // AIDEV-NOTE: at-least-once window — inbox messages are unlinked only AFTER
10
+ // sendMessage succeeds child-side. A crash before the unlink re-delivers the
11
+ // same message on the next pump tick (duplicate turn in the worst case).
12
+ // herdr pane/tab ids are display metadata only; identity correlates on
13
+ // childId + sessionFile (herdsman divergence #3 in the plan).
14
+ import { randomUUID } from 'node:crypto'
15
+ import {
16
+ closeSync,
17
+ fsyncSync,
18
+ mkdirSync,
19
+ openSync,
20
+ readdirSync,
21
+ readFileSync,
22
+ renameSync,
23
+ statSync,
24
+ unlinkSync,
25
+ writeSync,
26
+ } from 'node:fs'
27
+ import { basename, join } from 'node:path'
28
+ import { ensureSubagentsDataDir, subagentsDataRoot } from './dataroot.ts'
29
+ import {
30
+ acquireProcessLock,
31
+ isProcessLockClaim,
32
+ keyedProcessLockPath,
33
+ type ProcessLockClaim,
34
+ readProcessLockStatus,
35
+ } from './lock.ts'
36
+
37
+ const PRESENCE_VERSION = 1
38
+ const MESSAGE_VERSION = 1
39
+ export const PRESENCE_MAX_BYTES = 4096
40
+ export const MESSAGE_MAX_BYTES = 8192
41
+
42
+ export interface PeerPresence {
43
+ version: number
44
+ childId: string
45
+ sessionId: string
46
+ sessionFile: string
47
+ name: string
48
+ agent?: string
49
+ cwd: string
50
+ surface?: string
51
+ claim: ProcessLockClaim
52
+ updatedAt: string
53
+ }
54
+
55
+ export interface PeerMessage {
56
+ version: number
57
+ messageId: string
58
+ from: { childId: string; name?: string; agent?: string }
59
+ message: string
60
+ resultRef?: string
61
+ sentAt: string
62
+ }
63
+
64
+ /** Process lock key for a child's peer presence claim. */
65
+ export function peerLockKey(sessionFile: string): string {
66
+ return `pi-subagents-peer:${sessionFile}`
67
+ }
68
+
69
+ export function peerLockPath(sessionFile: string): string {
70
+ return keyedProcessLockPath(peerLockKey(sessionFile))
71
+ }
72
+
73
+ function peersDir(root?: string): string {
74
+ return ensureSubagentsDataDir('peers', root ?? subagentsDataRoot())
75
+ }
76
+
77
+ function sanitizeChildId(childId: string): string {
78
+ const safe = childId.replace(/[^A-Za-z0-9._-]/g, '_')
79
+ if (safe === '' || safe === '.' || safe === '..') return '_'
80
+ return safe
81
+ }
82
+
83
+ export function presencePath(childId: string, root?: string): string {
84
+ return join(peersDir(root), `${sanitizeChildId(childId)}.json`)
85
+ }
86
+
87
+ export function inboxDir(childId: string, root?: string): string {
88
+ const dir = join(peersDir(root), sanitizeChildId(childId), 'inbox')
89
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
90
+ return dir
91
+ }
92
+
93
+ function atomicWrite(path: string, contents: string): void {
94
+ const tmpPath = `${path}.${process.pid}.tmp`
95
+ const fd = openSync(tmpPath, 'w', 0o600)
96
+ try {
97
+ writeSync(fd, contents)
98
+ fsyncSync(fd)
99
+ } finally {
100
+ closeSync(fd)
101
+ }
102
+ renameSync(tmpPath, path)
103
+ }
104
+
105
+ /** Structural validation of a presence record (fail closed). */
106
+ export function isPeerPresence(value: unknown): value is PeerPresence {
107
+ if (value == null || typeof value !== 'object') return false
108
+ const record = value as Record<string, unknown>
109
+ if (record.version !== PRESENCE_VERSION) return false
110
+ if (typeof record.childId !== 'string' || record.childId === '') return false
111
+ if (typeof record.sessionId !== 'string') return false
112
+ if (typeof record.sessionFile !== 'string' || record.sessionFile === '') {
113
+ return false
114
+ }
115
+ if (typeof record.name !== 'string') return false
116
+ if (typeof record.cwd !== 'string') return false
117
+ if (typeof record.updatedAt !== 'string') return false
118
+ if (!isProcessLockClaim(record.claim)) return false
119
+ return true
120
+ }
121
+
122
+ export function readPresence(
123
+ childId: string,
124
+ root?: string,
125
+ ): PeerPresence | null {
126
+ let raw: string
127
+ try {
128
+ raw = readFileSync(presencePath(childId, root), 'utf8')
129
+ } catch {
130
+ return null
131
+ }
132
+ try {
133
+ const parsed: unknown = JSON.parse(raw)
134
+ return isPeerPresence(parsed) ? parsed : null
135
+ } catch {
136
+ return null
137
+ }
138
+ }
139
+
140
+ /**
141
+ * A presence record is valid only while its claim is the live generation of
142
+ * the lock keyed on the child's session file. Dead pid ⇒ not live; stale
143
+ * takeover ⇒ different claim id. Both fail closed.
144
+ */
145
+ export function presenceIsLive(record: PeerPresence, root?: string): boolean {
146
+ let status: { claim: ProcessLockClaim; live: boolean }
147
+ try {
148
+ status = readProcessLockStatus(peerLockPath(record.sessionFile))
149
+ } catch {
150
+ return false
151
+ }
152
+ if (!status.live) return false
153
+ return (
154
+ status.claim.pid === record.claim.pid && status.claim.id === record.claim.id
155
+ )
156
+ }
157
+
158
+ export interface ChildIdentity {
159
+ childId: string
160
+ sessionFile: string
161
+ name: string
162
+ agent?: string
163
+ surface?: string
164
+ cwd?: string
165
+ }
166
+
167
+ function sessionIdFromSessionFile(sessionFile: string): string {
168
+ const base = basename(sessionFile)
169
+ if (base.endsWith('.jsonl')) return base.slice(0, -'.jsonl'.length)
170
+ return base
171
+ }
172
+
173
+ /**
174
+ * Acquire this child's presence lock and publish its presence record. The
175
+ * caller owns the returned release function (call on session shutdown).
176
+ * Throws if the serialized record exceeds the 4 KiB cap.
177
+ */
178
+ export function publishPresence(
179
+ identity: ChildIdentity,
180
+ root?: string,
181
+ ): () => void {
182
+ // acquireProcessLock is imported at top level; it throws on contention.
183
+ const lease = acquireProcessLock(peerLockPath(identity.sessionFile), {
184
+ name: 'peer presence lock',
185
+ })
186
+ const record: PeerPresence = {
187
+ version: PRESENCE_VERSION,
188
+ childId: identity.childId,
189
+ sessionId: sessionIdFromSessionFile(identity.sessionFile),
190
+ sessionFile: identity.sessionFile,
191
+ name: identity.name,
192
+ cwd: identity.cwd ?? process.cwd(),
193
+ claim: lease.claim,
194
+ updatedAt: new Date().toISOString(),
195
+ }
196
+ if (identity.agent !== undefined) record.agent = identity.agent
197
+ if (identity.surface !== undefined) record.surface = identity.surface
198
+ const payload = JSON.stringify(record)
199
+ if (Buffer.byteLength(payload) > PRESENCE_MAX_BYTES) {
200
+ lease.release()
201
+ throw new Error(
202
+ `presence record exceeds ${PRESENCE_MAX_BYTES} bytes — refusing to publish`,
203
+ )
204
+ }
205
+ atomicWrite(presencePath(identity.childId, root), payload)
206
+ return () => {
207
+ try {
208
+ unlinkSync(presencePath(identity.childId, root))
209
+ } catch {}
210
+ lease.release()
211
+ }
212
+ }
213
+
214
+ export interface PeerListEntry {
215
+ childId: string
216
+ sessionId: string
217
+ sessionFile: string
218
+ name: string
219
+ agent?: string
220
+ cwd: string
221
+ surface?: string
222
+ self: boolean
223
+ }
224
+
225
+ /**
226
+ * Scan the peers dir, filter dead/stale/malformed records, return live peers
227
+ * (plus self, marked). This child's own record is included even before its
228
+ * lock status is re-verified — it holds the lease by definition.
229
+ */
230
+ export function listLivePeers(
231
+ identity: ChildIdentity,
232
+ root?: string,
233
+ ): PeerListEntry[] {
234
+ let entries: string[]
235
+ try {
236
+ entries = readdirSync(peersDir(root))
237
+ } catch {
238
+ return []
239
+ }
240
+ const result: PeerListEntry[] = []
241
+ for (const entry of entries) {
242
+ if (!entry.endsWith('.json')) continue
243
+ const childId = entry.slice(0, -'.json'.length)
244
+ const record = readPresence(childId, root)
245
+ if (!record) continue
246
+ const isSelf = record.childId === identity.childId
247
+ if (!isSelf && !presenceIsLive(record, root)) continue
248
+ const listItem: PeerListEntry = {
249
+ childId: record.childId,
250
+ sessionId: record.sessionId,
251
+ sessionFile: record.sessionFile,
252
+ name: record.name,
253
+ cwd: record.cwd,
254
+ self: isSelf,
255
+ }
256
+ if (record.agent !== undefined) listItem.agent = record.agent
257
+ if (record.surface !== undefined) listItem.surface = record.surface
258
+ result.push(listItem)
259
+ }
260
+ return result
261
+ }
262
+
263
+ /**
264
+ * Resolve a peer reference (childId or name) to a LIVE presence record.
265
+ * Self is resolvable too — messaging yourself is legal (the pump delivers it).
266
+ */
267
+ export function resolvePeer(
268
+ peer: string,
269
+ identity: ChildIdentity,
270
+ root?: string,
271
+ ): PeerListEntry {
272
+ const peers = listLivePeers(identity, root)
273
+ const matches = peers.filter((p) => p.childId === peer || p.name === peer)
274
+ if (matches.length === 0) {
275
+ throw new Error(
276
+ `No live peer found for "${peer}". Call list_peers to see who is available.`,
277
+ )
278
+ }
279
+ if (matches.length > 1) {
280
+ throw new Error(
281
+ `Peer reference "${peer}" is ambiguous (${matches.length} matches). Use the childId instead.`,
282
+ )
283
+ }
284
+ return matches[0]
285
+ }
286
+
287
+ function nextInboxSeq(dir: string): number {
288
+ let max = 0
289
+ for (const entry of readdirSync(dir)) {
290
+ const match = /^(\d+)\.json$/.exec(entry)
291
+ if (match) max = Math.max(max, Number.parseInt(match[1], 10))
292
+ }
293
+ return max + 1
294
+ }
295
+
296
+ function inboxMessagePath(dir: string, seq: number): string {
297
+ return join(dir, `${String(seq).padStart(6, '0')}.json`)
298
+ }
299
+
300
+ /**
301
+ * Write a durable inbox message to the recipient. Exclusive-create with
302
+ * retry on the allocated seq so two concurrent senders never overwrite each
303
+ * other. Throws a clear error above the 8 KiB cap.
304
+ */
305
+ export function sendPeerMessage(params: {
306
+ toChildId: string
307
+ from: ChildIdentity
308
+ message: string
309
+ resultRef?: string
310
+ root?: string
311
+ }): { path: string; messageId: string } {
312
+ const record: PeerMessage = {
313
+ version: MESSAGE_VERSION,
314
+ messageId: randomUUID(),
315
+ from: {
316
+ childId: params.from.childId,
317
+ name: params.from.name,
318
+ agent: params.from.agent,
319
+ },
320
+ message: params.message,
321
+ sentAt: new Date().toISOString(),
322
+ }
323
+ if (params.resultRef !== undefined) record.resultRef = params.resultRef
324
+ const payload = JSON.stringify(record)
325
+ const size = Buffer.byteLength(payload)
326
+ if (size > MESSAGE_MAX_BYTES) {
327
+ throw new Error(
328
+ `message is ${size} bytes; the inbox cap is ${MESSAGE_MAX_BYTES} bytes. Split or shorten the message.`,
329
+ )
330
+ }
331
+ const dir = inboxDir(params.toChildId, params.root)
332
+ // AIDEV-NOTE: seq allocation + exclusive create — a concurrent sender that
333
+ // wins the same seq bumps our attempt and we retry with the next number.
334
+ for (let attempt = 0; attempt < 5; attempt += 1) {
335
+ const seq = nextInboxSeq(dir)
336
+ const path = inboxMessagePath(dir, seq)
337
+ let fd: number
338
+ try {
339
+ fd = openSync(path, 'wx', 0o600)
340
+ } catch (error) {
341
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') continue
342
+ throw error
343
+ }
344
+ try {
345
+ writeSync(fd, payload)
346
+ fsyncSync(fd)
347
+ } finally {
348
+ closeSync(fd)
349
+ }
350
+ return { path, messageId: record.messageId }
351
+ }
352
+ throw new Error('inbox contention: could not allocate a message slot')
353
+ }
354
+
355
+ /** An inbox file plus its parsed message (only structurally valid ones). */
356
+ export interface InboxEntry {
357
+ path: string
358
+ message: PeerMessage
359
+ }
360
+
361
+ /** Read all valid inbox messages for a child, ordered by seq. */
362
+ export function readInbox(childId: string, root?: string): InboxEntry[] {
363
+ let entries: string[]
364
+ try {
365
+ entries = readdirSync(inboxDir(childId, root))
366
+ } catch {
367
+ return []
368
+ }
369
+ const result: InboxEntry[] = []
370
+ for (const entry of entries.sort()) {
371
+ if (!entry.endsWith('.json')) continue
372
+ const path = join(inboxDir(childId, root), entry)
373
+ try {
374
+ if (statSync(path).isDirectory()) continue
375
+ const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))
376
+ if (parsed == null || typeof parsed !== 'object') continue
377
+ const candidate = parsed as Record<string, unknown>
378
+ if (candidate.version !== MESSAGE_VERSION) continue
379
+ if (typeof candidate.messageId !== 'string') continue
380
+ if (typeof candidate.message !== 'string') continue
381
+ if (typeof candidate.sentAt !== 'string') continue
382
+ const from = candidate.from
383
+ if (from == null || typeof from !== 'object') continue
384
+ if (typeof (from as Record<string, unknown>).childId !== 'string')
385
+ continue
386
+ result.push({ path, message: parsed as PeerMessage })
387
+ } catch {
388
+ // Malformed / partially visible — never surfaced.
389
+ }
390
+ }
391
+ return result
392
+ }
393
+
394
+ export function removeInboxEntry(path: string): void {
395
+ try {
396
+ unlinkSync(path)
397
+ } catch {}
398
+ }
399
+
400
+ // AIDEV-NOTE: exported for tests — childId is a filesystem path component.
401
+ export const __peersInternals__ = { sanitizeChildId }
@@ -0,0 +1,219 @@
1
+ ---
2
+ name: plan
3
+ description: >
4
+ Planning workflow. Runs a pre-flight scout, then spawns the planner agent
5
+ which clarifies WHAT to build and figures out HOW, with the ability to
6
+ spawn its own scouts/researchers mid-session. Use when asked to "plan",
7
+ "brainstorm", "I want to build X", or "let's design". Requires the
8
+ subagents extension and a supported multiplexer (cmux/tmux/zellij).
9
+ ---
10
+
11
+ # Plan
12
+
13
+ A planning workflow. A scout maps the relevant codebase, then an interactive planner clarifies intent + requirements and designs the technical approach, producing a `plan.md` and todos.
14
+
15
+ **Announce at start:** "Let me take a quick look, then I'll send a scout to map the codebase before we start the planning session."
16
+
17
+ ---
18
+
19
+ ## The Flow
20
+
21
+ ```
22
+ Phase 1: Quick Assessment (main session — 30s orientation)
23
+ ↓
24
+ Phase 2: Scout (autonomous — codebase context)
25
+ ↓
26
+ Phase 3: Spawn Planner Agent (interactive — clarifies WHAT, plans HOW, creates todos)
27
+ ↓
28
+ (Planner may spawn its own scouts/researchers mid-session as needed)
29
+ ↓
30
+ Phase 4: Review Plan & Todos (main session)
31
+ ↓
32
+ Phase 5: Execute Todos (workers — receive plan + scout context)
33
+ ↓
34
+ Phase 6: Review
35
+ ```
36
+
37
+ ---
38
+
39
+ ## Phase 1: Quick Assessment
40
+
41
+ Quick orientation — just enough to give the scout a focused mission:
42
+
43
+ ```bash
44
+ ls -la
45
+ find . -type f -name "*.ts" | head -20 # or relevant extension
46
+ cat package.json 2>/dev/null | head -30
47
+ ```
48
+
49
+ Spend ~30 seconds. Tech stack, project shape, and the area relevant to the user's request. This tells you what to ask the scout to focus on.
50
+
51
+ ---
52
+
53
+ ## Artifact Paths
54
+
55
+ Every deliverable from a planning run lives in ONE shared directory. Resolve it **before** spawning any subagent, then pass explicit file paths in each subagent's task and read them back with the plain `read` tool when a subagent finishes.
56
+
57
+ **Primary — use the resolver tool.** When `resolve_feature_path` is available (it is registered by the pi-flow extension), call it with the feature name as `summary` — e.g. `resolve_feature_path` with `summary: "auth redesign"`. It returns the canonical `plan.md` path; the directory that contains it is your shared artifact directory. Prefer this: it honors `$PERSONAL_FEATURES`, so plans land in the developer's centralized features folder when one is configured.
58
+
59
+ **Fallback — only when the tool is unavailable** (pi-flow not installed): use the repo-local `.pi/plans/YYYY-MM-DD-<name>/`, with a short `<name>` (e.g. `auth-redesign`).
60
+
61
+ Standard filenames — `<resolved artifact dir>` below means the directory from whichever route you just took:
62
+
63
+ - `<resolved artifact dir>/scout-context.md`
64
+ - `<resolved artifact dir>/plan.md`
65
+ - `<resolved artifact dir>/review.md` (optional, for reviewer output)
66
+
67
+ AIDEV-NOTE: resolver-with-fallback is deliberate — this package is
68
+ independently installable and must never depend on pi-flow, so the tool is
69
+ "call it when present" and the repo-local path is explicitly the fallback, not
70
+ the contract.
71
+
72
+ ---
73
+
74
+ ## Phase 2: Scout
75
+
76
+ **Always spawn a scout before the planner.** The scout's context feeds into the planning session — it lets the planner skip re-asking questions whose answers live in the code, and gives it a solid base to design from.
77
+
78
+ ```typescript
79
+ subagent({
80
+ name: "🔍 Scout",
81
+ agent: "scout",
82
+ task: `Analyze the codebase for [user's request area]. Map file structure, key modules, patterns, conventions, and existing code related to [feature area]. Focus on what a planner would need to understand before designing this feature.
83
+
84
+ Save your findings to: <resolved artifact dir>/scout-context.md`,
85
+ });
86
+ ```
87
+
88
+ `<resolved artifact dir>` is the directory returned by `resolve_feature_path` (its
89
+ `plan.md` parent), or `.pi/plans/YYYY-MM-DD-<name>/` when that tool is unavailable —
90
+ substitute the real absolute path before spawning.
91
+
92
+ **Wait for the scout to finish.** Read the scout's context file with the `read` tool — you'll pass it to the planner.
93
+
94
+ The planner can spawn **additional** scouts or researchers mid-session if it hits a factual gap. That's expected — don't try to pre-scout every possible area.
95
+
96
+ ---
97
+
98
+ ## Phase 3: Spawn Planner Agent
99
+
100
+ Spawn the interactive planner with the scout's context and the user's request. The planner handles everything from here: clarifying intent, compact requirements engineering, ISC, approach exploration, design validation, premortem, plan artifact, and todos.
101
+
102
+ ```typescript
103
+ subagent({
104
+ name: "💬 Planner",
105
+ agent: "planner",
106
+ interactive: true,
107
+ task: `Plan: [what the user wants to build]
108
+
109
+ Scout context:
110
+ [paste scout findings here — file structure, conventions, patterns, relevant code]
111
+
112
+ Save the final plan to: <resolved artifact dir>/plan.md
113
+ Create todos tagged with: <name>`,
114
+ });
115
+ ```
116
+
117
+ As above, `<resolved artifact dir>` comes from the resolver (or the fallback) — pass the
118
+ resolved absolute path, never the placeholder.
119
+
120
+ **The user works with the planner.** It will clarify requirements lightly (1-2 rounds of questions, not a deep spec session), propose approaches, validate the design, run a premortem, write the plan, and create todos with mandatory code examples.
121
+
122
+ When done, the user presses Ctrl+D and the plan + todos are returned to the main session.
123
+
124
+ ### The planner may spawn its own specialists
125
+
126
+ During the session, the planner can spawn:
127
+ - **`scout`** — when a design decision depends on existing code it hasn't read
128
+ - **`researcher`** — when a decision depends on external facts (library tradeoffs, best practices, API behaviors)
129
+
130
+ These are internal to the planning session. You'll see them in the multiplexer but don't need to intervene.
131
+
132
+ ### Optional: extra scout after planning
133
+
134
+ If the planner significantly changed scope (new subsystems, areas the original scout didn't cover), spawn another scout targeting the new areas before workers start:
135
+
136
+ ```typescript
137
+ subagent({
138
+ name: "🔍 Scout (updated scope)",
139
+ agent: "scout",
140
+ task: "The plan changed scope. Gather context for [new areas]. Read the plan at [plan path]. Focus on [specific files/modules the planner identified that weren't in the original scout].",
141
+ });
142
+ ```
143
+
144
+ Fold the new context into the worker tasks.
145
+
146
+ ---
147
+
148
+ ## Phase 4: Review Plan & Todos
149
+
150
+ Once the planner closes, read the plan and list todos:
151
+
152
+ ```typescript
153
+ todo({ action: "list" });
154
+ ```
155
+
156
+ Review with the user:
157
+
158
+ > "Here's what the planner produced: [brief summary]. Ready to execute, or anything to adjust?"
159
+
160
+ ---
161
+
162
+ ## Phase 5: Execute Todos
163
+
164
+ Spawn workers sequentially. Each worker gets the plan path and scout context:
165
+
166
+ ```typescript
167
+ // Workers execute todos sequentially — one at a time
168
+ subagent({
169
+ name: "🔨 Worker 1/N",
170
+ agent: "worker",
171
+ task: "Implement TODO-xxxx. Mark the todo as done. Plan: [plan path]\n\nScout context: [paste scout summary from Phase 2, plus any re-scout from Phase 3]",
172
+ });
173
+
174
+ // Check result, then next todo
175
+ subagent({
176
+ name: "🔨 Worker 2/N",
177
+ agent: "worker",
178
+ task: "Implement TODO-yyyy. Mark the todo as done. Plan: [plan path]\n\nScout context: [paste scout summary]",
179
+ });
180
+ ```
181
+
182
+ **Always run workers sequentially in the same git repo** — parallel workers will conflict on commits.
183
+
184
+ ---
185
+
186
+ ## Phase 6: Review
187
+
188
+ After all todos are complete:
189
+
190
+ ```typescript
191
+ subagent({
192
+ name: "Reviewer",
193
+ agent: "reviewer",
194
+ interactive: false,
195
+ task: "Review the recent changes. Plan: [plan path]",
196
+ });
197
+ ```
198
+
199
+ Triage findings:
200
+
201
+ - **P0** — Real bugs, security issues → fix now
202
+ - **P1** — Genuine traps, maintenance dangers → fix before merging
203
+ - **P2** — Minor issues → fix if quick, note otherwise
204
+ - **P3** — Nits → skip
205
+
206
+ Create todos for P0/P1, run workers to fix, re-review only if fixes were substantial.
207
+
208
+ ---
209
+
210
+ ## ⚠️ Completion Checklist
211
+
212
+ Before reporting done:
213
+
214
+ 1. ✅ Scout ran before the planner?
215
+ 2. ✅ Scout context was passed to the planner?
216
+ 3. ✅ All worker todos closed?
217
+ 4. ✅ Every todo has a polished commit (using the `commit` skill)?
218
+ 5. ✅ Reviewer has run?
219
+ 6. ✅ Reviewer findings triaged and addressed?
@@ -0,0 +1,5 @@
1
+ {
2
+ "name": "pi-auto-exit",
3
+ "version": "1.0.0",
4
+ "description": "Auto-exit plugin for pi-spawned Claude sessions"
5
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "hooks": {
3
+ "Stop": [
4
+ {
5
+ "hooks": [
6
+ {
7
+ "type": "command",
8
+ "command": "${CLAUDE_PLUGIN_ROOT}/hooks/on-stop.sh",
9
+ "timeout": 10
10
+ }
11
+ ]
12
+ }
13
+ ]
14
+ }
15
+ }