@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,234 @@
1
+ // Durable ask/answer records for the blocking ask_owner flow (PMR-WXG0).
2
+ // A child writes `asks/<childId>.json` + a `<sessionFile>.ask` sidecar when it
3
+ // asks its owner mid-run; the parent's answer_subagent tool validates identity
4
+ // and writes `asks/<childId>.reply.json`; the child's mailbox pump delivers the
5
+ // reply into its own session and only then removes the reply/ask records.
6
+ //
7
+ // AIDEV-NOTE: at-least-once window — the reply record survives until the child
8
+ // confirms ingestion (its `.ack` sidecar + record cleanup). A lost pump tick or
9
+ // child crash re-delivers the same answer later (duplicate user turn in the
10
+ // worst case); a matched parent-side ack deletes the records idempotently.
11
+ import { randomUUID } from 'node:crypto'
12
+ import {
13
+ closeSync,
14
+ fsyncSync,
15
+ openSync,
16
+ readdirSync,
17
+ readFileSync,
18
+ renameSync,
19
+ unlinkSync,
20
+ writeSync,
21
+ } from 'node:fs'
22
+ import { join } from 'node:path'
23
+ import { ensureSubagentsDataDir, subagentsDataRoot } from './dataroot.ts'
24
+
25
+ export interface AskRecord {
26
+ askId: string
27
+ childId: string
28
+ name?: string
29
+ question: string
30
+ files?: string[]
31
+ sessionFile: string
32
+ createdAt: string
33
+ }
34
+
35
+ export interface AskReplyRecord {
36
+ askId: string
37
+ message: string
38
+ repliedAt: string
39
+ }
40
+
41
+ function sanitizeChildId(childId: string): string {
42
+ const safe = childId.replace(/[^A-Za-z0-9._-]/g, '_')
43
+ if (safe === '' || safe === '.' || safe === '..') return '_'
44
+ return safe
45
+ }
46
+
47
+ /** Asks directory (PMR-YJC5): the aggregate snapshot fold readdirs this. */
48
+ export function asksDir(root?: string): string {
49
+ return ensureSubagentsDataDir('asks', root ?? subagentsDataRoot())
50
+ }
51
+
52
+ /** Durable ask record path: `<dataRoot>/asks/<childId>.json`. */
53
+ export function askRecordPath(childId: string, root?: string): string {
54
+ return join(asksDir(root), `${sanitizeChildId(childId)}.json`)
55
+ }
56
+
57
+ /** Durable reply record path: `<dataRoot>/asks/<childId>.reply.json`. */
58
+ export function replyRecordPath(childId: string, root?: string): string {
59
+ return join(
60
+ ensureSubagentsDataDir('asks', root ?? subagentsDataRoot()),
61
+ `${sanitizeChildId(childId)}.reply.json`,
62
+ )
63
+ }
64
+
65
+ /** Ask sidecar path, colocated with the child session file. */
66
+ export function askSidecarPath(sessionFile: string): string {
67
+ return `${sessionFile}.ask`
68
+ }
69
+
70
+ function atomicWrite(path: string, contents: string): void {
71
+ const tmpPath = `${path}.${process.pid}.tmp`
72
+ const fd = openSync(tmpPath, 'w', 0o600)
73
+ try {
74
+ writeSync(fd, contents)
75
+ fsyncSync(fd)
76
+ } finally {
77
+ closeSync(fd)
78
+ }
79
+ renameSync(tmpPath, path)
80
+ }
81
+
82
+ // AIDEV-NOTE: atomic write (tmp + fsync + rename) so the parent's 1s poller
83
+ // never observes a partial ask record.
84
+ export function writeAskRecord(record: AskRecord, root?: string): void {
85
+ atomicWrite(askRecordPath(record.childId, root), JSON.stringify(record))
86
+ }
87
+
88
+ /** Read an ask record; null when missing or malformed (fail closed). */
89
+ export function readAskRecord(
90
+ childId: string,
91
+ root?: string,
92
+ ): AskRecord | null {
93
+ let raw: string
94
+ try {
95
+ raw = readFileSync(askRecordPath(childId, root), 'utf8')
96
+ } catch {
97
+ return null
98
+ }
99
+ try {
100
+ const parsed = JSON.parse(raw) as unknown
101
+ if (parsed == null || typeof parsed !== 'object') return null
102
+ const record = parsed as Record<string, unknown>
103
+ if (typeof record.askId !== 'string') return null
104
+ if (typeof record.childId !== 'string') return null
105
+ if (typeof record.question !== 'string') return null
106
+ if (typeof record.sessionFile !== 'string') return null
107
+ return parsed as AskRecord
108
+ } catch {
109
+ return null
110
+ }
111
+ }
112
+
113
+ export function removeAskRecord(childId: string, root?: string): void {
114
+ try {
115
+ unlinkSync(askRecordPath(childId, root))
116
+ } catch {}
117
+ }
118
+
119
+ /** Child side: write the `.ask` sidecar. */
120
+ export function writeAskSidecar(sessionFile: string, askId: string): void {
121
+ atomicWrite(askSidecarPath(sessionFile), JSON.stringify({ askId }))
122
+ }
123
+
124
+ /** Parent side: read the `.ask` sidecar; null when missing or malformed. */
125
+ export function readAskSidecar(sessionFile: string): { askId: string } | null {
126
+ try {
127
+ const parsed = JSON.parse(
128
+ readFileSync(askSidecarPath(sessionFile), 'utf8'),
129
+ ) as unknown
130
+ if (parsed == null || typeof parsed !== 'object') return null
131
+ const sidecar = parsed as Record<string, unknown>
132
+ if (typeof sidecar.askId !== 'string') return null
133
+ return parsed as { askId: string }
134
+ } catch {
135
+ return null
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Parent-owned cleanup — only the answer path deletes the sidecar, never the
141
+ * child (herdsman discipline: each side owns its half of the protocol).
142
+ */
143
+ export function removeAskSidecar(sessionFile: string): void {
144
+ try {
145
+ unlinkSync(askSidecarPath(sessionFile))
146
+ } catch {}
147
+ }
148
+
149
+ /** Durable reply record, written before the child's pump delivers it. */
150
+ export function writeReplyRecord(
151
+ childId: string,
152
+ reply: AskReplyRecord,
153
+ root?: string,
154
+ ): void {
155
+ atomicWrite(replyRecordPath(childId, root), JSON.stringify(reply))
156
+ }
157
+
158
+ export function readReplyRecord(
159
+ childId: string,
160
+ root?: string,
161
+ ): AskReplyRecord | null {
162
+ try {
163
+ const parsed = JSON.parse(
164
+ readFileSync(replyRecordPath(childId, root), 'utf8'),
165
+ ) as unknown
166
+ if (parsed == null || typeof parsed !== 'object') return null
167
+ const reply = parsed as Record<string, unknown>
168
+ if (typeof reply.askId !== 'string') return null
169
+ if (typeof reply.message !== 'string') return null
170
+ return parsed as AskReplyRecord
171
+ } catch {
172
+ return null
173
+ }
174
+ }
175
+
176
+ export function removeReplyRecord(childId: string, root?: string): void {
177
+ try {
178
+ unlinkSync(replyRecordPath(childId, root))
179
+ } catch {}
180
+ }
181
+
182
+ /**
183
+ * Identity revalidation before an answer is applied: the (optional) askId must
184
+ * match the record's, and the record must name the childId + sessionFile the
185
+ * caller is talking to. A mismatch is refused, never guessed from.
186
+ */
187
+ export function askIdentityMatches(params: {
188
+ record: AskRecord
189
+ askId?: string
190
+ childId: string
191
+ sessionFile: string
192
+ }): boolean {
193
+ if (params.record.childId !== params.childId) return false
194
+ if (params.record.sessionFile !== params.sessionFile) return false
195
+ if (params.askId != null && params.record.askId !== params.askId) return false
196
+ return true
197
+ }
198
+
199
+ /**
200
+ * Cleanup for resume/retry paths: ask records are keyed by childId, which a
201
+ * resuming parent does not know — scan the asks dir and drop records (and
202
+ * reply records) whose sessionFile matches. Returns removed ask-record count.
203
+ */
204
+ export function removeAskRecordsForSession(
205
+ sessionFile: string,
206
+ root?: string,
207
+ ): number {
208
+ const dir = ensureSubagentsDataDir('asks', root ?? subagentsDataRoot())
209
+ let entries: string[]
210
+ try {
211
+ entries = readdirSync(dir)
212
+ } catch {
213
+ return 0
214
+ }
215
+ let removed = 0
216
+ for (const entry of entries) {
217
+ if (!entry.endsWith('.json') || entry.endsWith('.reply.json')) continue
218
+ const childId = entry.slice(0, -'.json'.length)
219
+ const record = readAskRecord(childId, root)
220
+ if (!record || record.sessionFile !== sessionFile) continue
221
+ removeAskRecord(childId, root)
222
+ removeReplyRecord(childId, root)
223
+ removed += 1
224
+ }
225
+ return removed
226
+ }
227
+
228
+ /** Allocate a fresh ask id (exported for tests). */
229
+ export function newAskId(): string {
230
+ return randomUUID()
231
+ }
232
+
233
+ // AIDEV-NOTE: exported for tests — childId is a filesystem path component.
234
+ export const __asksInternals__ = { sanitizeChildId }
@@ -0,0 +1,395 @@
1
+ // Durable branch-owned assignment records (PMR-Z5KR). Ported from
2
+ // pi-herdsman's ProjectAssignment pattern (Apache-2.0, ADR 0017): authority
3
+ // is the RECORD under <dataRoot>/assignments/<childId>.json, not process
4
+ // memory. Children live in herdr-owned background tabs, so a parent death
5
+ // leaves them running — any new parent process rediscovers them here
6
+ // (orphan + resume hint) instead of losing track of the work.
7
+ //
8
+ // Lifecycle: written atomically at spawn, status updated on transitions
9
+ // (blocked/interrupted/stalled via the 1s status loop), REMOVED only on a
10
+ // verified completion signal (`.exit`/sentinel sidecar observed by the
11
+ // watcher) or explicit remove. Crash-inferred endings mark the record
12
+ // 'lost' and keep it — fail closed, never invent state.
13
+ //
14
+ // AIDEV-NOTE (PMR-8MQH): NODE-ONLY DAEMON SURFACE. This file is exported as
15
+ // the `@gtheys/pi-interactive-subagents/assignments` subpath (see package.json
16
+ // `exports`) and is module-imported by the pi-flow daemon
17
+ // (packages/pi-flow/server/daemon.ts), which runs in its own process with no pi
18
+ // extension runtime. The only non-builtin in the graph is `./dataroot.ts` →
19
+ // `@mariozechner/pi-coding-agent` (`getAgentDir`, default-param only — the same
20
+ // pre-existing acceptance as pi-flow's run-state.ts). Never import the root
21
+ // extension index (`./index.ts`) from here; the graph is locked by
22
+ // test/subpath-exports.test.ts.
23
+ // AIDEV-NOTE (worker-ask-wait fix): `hasPendingAskForParent` added a second
24
+ // relative edge, `./asks.ts` (readAskRecord). That stays inside the accepted
25
+ // graph: asks.ts imports node builtins plus `./dataroot.ts` only, so the
26
+ // pi-coding-agent reach is unchanged (dataroot.ts is still the single file that
27
+ // loads it) and the subpath-exports closure guard stays green.
28
+ import {
29
+ closeSync,
30
+ existsSync,
31
+ fsyncSync,
32
+ openSync,
33
+ readdirSync,
34
+ readFileSync,
35
+ renameSync,
36
+ unlinkSync,
37
+ writeSync,
38
+ } from 'node:fs'
39
+ import { join } from 'node:path'
40
+ import { readAskRecord } from './asks.ts'
41
+ import { ensureSubagentsDataDir, subagentsDataRoot } from './dataroot.ts'
42
+ import type { UsageTotals } from './usage.ts'
43
+
44
+ /** Coarse lifecycle status persisted on the record. Mirrors WidgetStateKind. */
45
+ export type AssignmentStatus =
46
+ | 'working'
47
+ | 'blocked'
48
+ | 'starting'
49
+ | 'waiting'
50
+ | 'stalled'
51
+ | 'lost'
52
+
53
+ export interface AssignmentRecord {
54
+ childId: string
55
+ name: string
56
+ task: string
57
+ agent?: string
58
+ sessionFile: string
59
+ paneId?: string
60
+ tabId?: string
61
+ workspaceId?: string
62
+ /** Child-side activity snapshot path (PMR-N53A) — lets a reattaching
63
+ * parent resume activity observation without knowing the original
64
+ * artifact dir. Absent on records written before PMR-N53A. */
65
+ activityFile?: string
66
+ cwd: string
67
+ /** Worktree placement (PMR-11TD): the branch-keyed authority fields. */
68
+ worktree?: string
69
+ branch?: string
70
+ /** Plan-task ref for 1:1 worker spawns (PMR-HFK1) — durable cost
71
+ * attribution: PI_FLOW_SUBTASK at spawn time and the record both carry
72
+ * it, so reassignments/takeovers keep attributing to the right subtask
73
+ * even after the spawning parent is gone. Absent on scouts. */
74
+ subtask?: string
75
+ status: AssignmentStatus
76
+ /**
77
+ * Owning parent identity. pid = the parent pi process; id = the parent
78
+ * session id (diagnostics/correlation).
79
+ *
80
+ * AIDEV-NOTE: stale detection is pid liveness only. Pid reuse could
81
+ * misclassify an orphan as owned — mitigate by treating 'owned' as
82
+ * display metadata only; every mutation path still revalidates identity
83
+ * (childId + sessionFile) before acting. Herdsman's full claim-generation
84
+ * machinery (lock.ts) is deliberately not coupled in here.
85
+ */
86
+ claim: { pid: number; id: string }
87
+ /** Session-accumulated token/cost totals (PMR-874G), recorded at settlement. */
88
+ usage?: UsageTotals
89
+ createdAt: string
90
+ updatedAt: string
91
+ }
92
+
93
+ /** New-record input: timestamps are assigned by writeAssignment. */
94
+ export type AssignmentDraft = Omit<AssignmentRecord, 'createdAt' | 'updatedAt'>
95
+
96
+ /** What a scan of the assignments dir can say about one record (fail closed). */
97
+ export type AssignmentView =
98
+ | { childId: string; state: 'unknown' }
99
+ | { childId: string; state: 'owned'; record: AssignmentRecord }
100
+ | {
101
+ childId: string
102
+ state: 'orphaned'
103
+ record: AssignmentRecord
104
+ resumeHint?: string
105
+ }
106
+
107
+ function sanitizeChildId(childId: string): string {
108
+ const safe = childId.replace(/[^A-Za-z0-9._-]/g, '_')
109
+ if (safe === '' || safe === '.' || safe === '..') return '_'
110
+ return safe
111
+ }
112
+
113
+ /** Canonical on-disk path for an assignment record. */
114
+ export function assignmentPath(childId: string, root?: string): string {
115
+ return join(
116
+ ensureSubagentsDataDir('assignments', root ?? subagentsDataRoot()),
117
+ `${sanitizeChildId(childId)}.json`,
118
+ )
119
+ }
120
+
121
+ export function hasAssignment(childId: string, root?: string): boolean {
122
+ return existsSync(assignmentPath(childId, root))
123
+ }
124
+
125
+ // AIDEV-NOTE: atomic write — tmp sibling + fsync + rename (same discipline
126
+ // as store.ts/control.ts). Readers never observe a partial record.
127
+ function writeRecordAtomic(path: string, record: AssignmentRecord): void {
128
+ const tmpPath = `${path}.tmp`
129
+ const fd = openSync(tmpPath, 'w', 0o600)
130
+ try {
131
+ writeSync(fd, JSON.stringify(record))
132
+ fsyncSync(fd)
133
+ } finally {
134
+ closeSync(fd)
135
+ }
136
+ renameSync(tmpPath, path)
137
+ }
138
+
139
+ /** Write the assignment record at spawn (latest full picture wins). */
140
+ export function writeAssignment(
141
+ draft: AssignmentDraft,
142
+ root?: string,
143
+ ): AssignmentRecord {
144
+ const now = new Date().toISOString()
145
+ const record: AssignmentRecord = {
146
+ ...draft,
147
+ createdAt: now,
148
+ updatedAt: now,
149
+ }
150
+ writeRecordAtomic(assignmentPath(record.childId, root), record)
151
+ return record
152
+ }
153
+
154
+ /** Read one record; null when missing or malformed (fail closed). */
155
+ export function readAssignment(
156
+ childId: string,
157
+ root?: string,
158
+ ): AssignmentRecord | null {
159
+ let raw: string
160
+ try {
161
+ raw = readFileSync(assignmentPath(childId, root), 'utf8')
162
+ } catch {
163
+ return null
164
+ }
165
+ return parseAssignment(raw)
166
+ }
167
+
168
+ function parseAssignment(raw: string): AssignmentRecord | null {
169
+ try {
170
+ const parsed = JSON.parse(raw) as unknown
171
+ if (parsed == null || typeof parsed !== 'object') return null
172
+ const record = parsed as Record<string, unknown>
173
+ if (typeof record.childId !== 'string') return null
174
+ if (typeof record.sessionFile !== 'string') return null
175
+ const claim = record.claim as Record<string, unknown> | undefined
176
+ if (claim == null || typeof claim.pid !== 'number') return null
177
+ return parsed as AssignmentRecord
178
+ } catch {
179
+ return null
180
+ }
181
+ }
182
+
183
+ // AIDEV-NOTE: read-modify-write; latest status wins. A MISSING record is a
184
+ // no-op (fail closed) — transitions never resurrect a removed assignment.
185
+ export function updateAssignmentStatus(
186
+ childId: string,
187
+ status: AssignmentStatus,
188
+ root?: string,
189
+ ): void {
190
+ const record = readAssignment(childId, root)
191
+ if (!record) return
192
+ if (record.status === status) return
193
+ writeRecordAtomic(assignmentPath(childId, root), {
194
+ ...record,
195
+ status,
196
+ updatedAt: new Date().toISOString(),
197
+ })
198
+ }
199
+
200
+ /** Explicit remove — callers gate this on verified completion or user intent. */
201
+ export function removeAssignment(childId: string, root?: string): void {
202
+ try {
203
+ unlinkSync(assignmentPath(childId, root))
204
+ } catch {}
205
+ }
206
+
207
+ // AIDEV-NOTE (PMR-874G): settle-time usage snapshot. Same read-modify-write
208
+ // discipline as updateAssignmentStatus — a missing record is a no-op. On the
209
+ // verified-completion path the record is removed right after, so this
210
+ // primarily keeps the accounting on records that SURVIVE (lost/orphaned),
211
+ // where it is the only durable usage evidence.
212
+ export function recordAssignmentUsage(
213
+ childId: string,
214
+ usage: UsageTotals,
215
+ root?: string,
216
+ ): void {
217
+ const record = readAssignment(childId, root)
218
+ if (!record) return
219
+ writeRecordAtomic(assignmentPath(childId, root), {
220
+ ...record,
221
+ usage,
222
+ updatedAt: new Date().toISOString(),
223
+ })
224
+ }
225
+
226
+ // AIDEV-NOTE (PMR-N53A): exported so the subagent_resume reattach probe
227
+ // reuses the same liveness semantics as listAssignments classification.
228
+ export function pidAlive(pid: number): boolean {
229
+ try {
230
+ process.kill(pid, 0)
231
+ return true
232
+ } catch (err: any) {
233
+ // EPERM = the process exists but is owned by another user.
234
+ return err?.code === 'EPERM'
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Scan the assignments dir and classify every record from FILES ALONE —
240
+ * this is the parent-restart discovery path. Live claim pid ⇒ owned; dead
241
+ * claim pid ⇒ orphaned with a resume hint; unreadable record ⇒ unknown
242
+ * (kept on disk, no action, no invented state).
243
+ */
244
+ export function listAssignments(root?: string): AssignmentView[] {
245
+ const dir = ensureSubagentsDataDir('assignments', root ?? subagentsDataRoot())
246
+ let entries: string[]
247
+ try {
248
+ entries = readdirSync(dir)
249
+ } catch {
250
+ return []
251
+ }
252
+ const views: AssignmentView[] = []
253
+ for (const entry of entries) {
254
+ if (!entry.endsWith('.json')) continue
255
+ const childId = entry.slice(0, -'.json'.length)
256
+ let raw: string
257
+ try {
258
+ raw = readFileSync(join(dir, entry), 'utf8')
259
+ } catch {
260
+ views.push({ childId, state: 'unknown' })
261
+ continue
262
+ }
263
+ const record = parseAssignment(raw)
264
+ if (!record) {
265
+ views.push({ childId, state: 'unknown' })
266
+ continue
267
+ }
268
+ if (pidAlive(record.claim.pid)) {
269
+ views.push({ childId, state: 'owned', record })
270
+ continue
271
+ }
272
+ const view: Extract<AssignmentView, { state: 'orphaned' }> = {
273
+ childId,
274
+ state: 'orphaned',
275
+ record,
276
+ }
277
+ // AIDEV-NOTE (PMR-YKAC): a 'starting' record with no paneId is a spawn
278
+ // that crashed between record-write and tab-create — deriveResumeHint
279
+ // tells the parent to re-issue the spawn; allocateSpawnIdentity will
280
+ // reuse this record.
281
+ view.resumeHint = deriveResumeHint(record)
282
+ views.push(view)
283
+ }
284
+ views.sort((a, b) => a.childId.localeCompare(b.childId))
285
+ return views
286
+ }
287
+
288
+ // AIDEV-NOTE (PMR-PCF7): assignment-derived guidance extracted from
289
+ // listAssignments so failure notices can reuse the same branches. Derived
290
+ // ONLY from durable record fields — never guessed state. A 'starting'
291
+ // record with no paneId cannot support a resume (the session likely never
292
+ // started) and yields re-issue-spawn guidance; anything else with a
293
+ // non-empty sessionFile yields the resume command. Callers that need a
294
+ // VERIFIED session path must additionally check the file exists (see
295
+ // recoveryGuidanceFor in index.ts).
296
+ export function deriveResumeHint(record: AssignmentRecord): string | undefined {
297
+ if (!record.sessionFile) return undefined
298
+ if (record.status === 'starting' && !record.paneId) {
299
+ return 'spawn crashed before tab create — re-issue the same spawn; the record will be reused'
300
+ }
301
+ return `subagent_resume({ sessionPath: "${record.sessionFile}" })`
302
+ }
303
+ /**
304
+ * True while the given parent pid has at least one in-flight child: an
305
+ * assignment record owned by that pid with a status other than 'lost'.
306
+ * Cross-extension guard (pi-flow's /flow loop) — records are removed only
307
+ * on verified completion, so presence means the child can still steer its
308
+ * parent. 'lost' fails closed to not-in-flight: a lost child never steers,
309
+ * so waiting on it would hang the caller's gate.
310
+ */
311
+ export function hasLiveAssignmentForParent(
312
+ pid: number,
313
+ root?: string,
314
+ ): boolean {
315
+ for (const view of listAssignments(root)) {
316
+ if (view.state !== 'owned') continue
317
+ if (view.record.claim.pid !== pid) continue
318
+ if (view.record.status === 'lost') continue
319
+ return true
320
+ }
321
+ return false
322
+ }
323
+
324
+ /**
325
+ * True when at least one in-flight child of `pid` is BLOCKED ON THE HUMAN
326
+ * through the ask_owner protocol (PMR-WXG0): it owns a live, non-lost
327
+ * assignment record AND an open ask record (`asks/<childId>.json`).
328
+ *
329
+ * AIDEV-NOTE (worker-ask-wait fix): consumer is pi-flow's /flow loop, which
330
+ * labels a settle with an in-flight child `waiting_machine{subagent_in_flight}`.
331
+ * An ask-blocked child is the opposite situation — nothing moves until a human
332
+ * answers — so the loop needs this second probe to keep those runs on the
333
+ * "Waiting on me — act now" board instead of the machine-wait rows. Same
334
+ * liveness semantics as hasLiveAssignmentForParent ('owned' + not 'lost'): a
335
+ * lost/orphaned child never steers its parent back, so its leftover ask record
336
+ * must not make the human a bottleneck. `readAskRecord` fails closed to null on
337
+ * a malformed record, so a corrupt ask file degrades to the old machine wait.
338
+ * A reply record does NOT count as answered here on purpose: the ask stays on
339
+ * disk until the child's pump confirms ingestion, and until then the child is
340
+ * still parked — the worst case is a wait that clears a few seconds after the
341
+ * human answered, never a missed one.
342
+ */
343
+ export function hasPendingAskForParent(pid: number, root?: string): boolean {
344
+ for (const view of listAssignments(root)) {
345
+ if (view.state !== 'owned') continue
346
+ if (view.record.claim.pid !== pid) continue
347
+ if (view.record.status === 'lost') continue
348
+ if (readAskRecord(view.childId, root) !== null) return true
349
+ }
350
+ return false
351
+ }
352
+
353
+ // AIDEV-NOTE (PMR-YKAC): replay lookup for spawn identity — the 'starting'
354
+ // record this parent wrote before its crashed spawn's tab create. Matches on
355
+ // parent session + name + task so a retried tool call finds its half-spawn;
356
+ // 'working'/'lost' records and other parents/tasks never match. Most recent
357
+ // wins when several match (shouldn't happen — one in-flight spawn per
358
+ // name+task — but fail toward the newest evidence).
359
+ export function findStartingAssignment(
360
+ options: { parentSessionId: string; name: string; task: string },
361
+ root?: string,
362
+ ): AssignmentRecord | null {
363
+ let best: AssignmentRecord | null = null
364
+ for (const view of listAssignments(root)) {
365
+ if (view.state === 'unknown') continue
366
+ const record = view.record
367
+ if (record.status !== 'starting') continue
368
+ if (record.claim.id !== options.parentSessionId) continue
369
+ if (record.name !== options.name) continue
370
+ if (record.task !== options.task) continue
371
+ if (!best || record.createdAt > best.createdAt) best = record
372
+ }
373
+ return best
374
+ }
375
+
376
+ // AIDEV-NOTE: branch-keyed authority lookup (herdsman ADR 0017). Exactly one
377
+ // current assignment may name a branch — zero or multiple matches are
378
+ // ambiguous and fail closed to an error, never a guessed record.
379
+ export function findAssignmentByBranch(
380
+ branch: string,
381
+ root?: string,
382
+ ): { record: AssignmentRecord } | { error: string } {
383
+ const matches: AssignmentRecord[] = []
384
+ for (const view of listAssignments(root)) {
385
+ if (view.state === 'unknown') continue
386
+ if (view.record.branch === branch) matches.push(view.record)
387
+ }
388
+ if (matches.length === 1) return { record: matches[0] }
389
+ if (matches.length === 0) {
390
+ return { error: `No assignment for branch "${branch}" — state unknown.` }
391
+ }
392
+ return {
393
+ error: `Ambiguous assignments for branch "${branch}" (${matches.length} records) — state unknown.`,
394
+ }
395
+ }