@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,365 @@
1
+ import {
2
+ existsSync,
3
+ mkdirSync,
4
+ readFileSync,
5
+ rmSync,
6
+ writeFileSync,
7
+ } from 'node:fs'
8
+ import { tmpdir } from 'node:os'
9
+ import { dirname, join } from 'node:path'
10
+ import {
11
+ herdrReadPane,
12
+ herdrSendEscape,
13
+ herdrSendReturn,
14
+ herdrSendText,
15
+ runHerdr,
16
+ } from './herdr.ts'
17
+ import { herdrPaneAlive } from './spawn.ts'
18
+
19
+ // AIDEV-NOTE: herdr-only surface layer (PMR-TABUX). The cmux/tmux/zellij/
20
+ // wezterm backends and the PI_SUBAGENT_MUX override were deleted; every
21
+ // surface operation goes through the herdr verb layer. Kept public names:
22
+ // isMuxAvailable/muxSetupHint (pi-test-runner, pi-flow) and the text-send /
23
+ // screen-read helpers the still-alive WXG0 answer path uses until Phase 5
24
+ // replaces pane typing with the mailbox pump.
25
+
26
+ export type MuxBackend = 'herdr'
27
+
28
+ const commandAvailability = new Map<string, boolean>()
29
+
30
+ function hasCommand(command: string): boolean {
31
+ const cached = commandAvailability.get(command)
32
+ if (cached !== undefined) return cached
33
+ let available = false
34
+ try {
35
+ runHerdr(['--version'])
36
+ available = true
37
+ } catch {
38
+ available = false
39
+ }
40
+ commandAvailability.set(command, available)
41
+ return available
42
+ }
43
+
44
+ export function getMuxBackend(): MuxBackend | null {
45
+ return hasCommand('herdr') ? 'herdr' : null
46
+ }
47
+
48
+ /**
49
+ * Herdr availability = binary present + server reachable (status preflight,
50
+ * which also enforces the >= HERDR_MIN_VERSION gate at spawn time).
51
+ */
52
+ export function isMuxAvailable(): boolean {
53
+ if (!hasCommand('herdr')) return false
54
+ try {
55
+ runHerdr(['status', '--json'])
56
+ return true
57
+ } catch {
58
+ return false
59
+ }
60
+ }
61
+
62
+ export function muxSetupHint(): string {
63
+ return (
64
+ 'Install herdr (https://github.com/steipete/herdr), start it with `herdr`, ' +
65
+ 'and run pi inside it (`herdr pi`). If it is already installed, upgrade ' +
66
+ 'with `herdr upgrade` — this extension needs herdr >= 0.9.1.'
67
+ )
68
+ }
69
+
70
+ /** Close a herdr pane; when the caller knows the owning tab, close it too. */
71
+ export function closeSurface(surface: string, tabId?: string): void {
72
+ try {
73
+ runHerdr(['pane', 'close', surface])
74
+ } catch {
75
+ // Already gone.
76
+ }
77
+ if (tabId) {
78
+ try {
79
+ runHerdr(['tab', 'close', tabId])
80
+ } catch {
81
+ // Already gone.
82
+ }
83
+ }
84
+ }
85
+
86
+ /** Send one Escape keypress (canonical `esc`, never raw byte 27). */
87
+ export function sendEscape(surface: string): void {
88
+ herdrSendEscape(surface)
89
+ }
90
+
91
+ /** Type text into a pane and submit it (Enter). */
92
+ export function sendCommand(surface: string, command: string): void {
93
+ herdrSendText(surface, command)
94
+ herdrSendReturn(surface)
95
+ }
96
+
97
+ /**
98
+ * Send a long command via a script file + short `bash <file>` line (herdr
99
+ * rejects oversized input lines). Kept for the WXG0 answer path; Phase 5
100
+ * deletes the last pane-typing dependency. Returns the script path.
101
+ */
102
+ export function sendLongCommand(
103
+ surface: string,
104
+ command: string,
105
+ options?: { scriptPath?: string; scriptPreamble?: string },
106
+ ): string {
107
+ const scriptPath =
108
+ options?.scriptPath ??
109
+ join(
110
+ tmpdir(),
111
+ 'pi-subagent-scripts',
112
+ `cmd-${Date.now()}-${Math.random().toString(16).slice(2, 8)}.sh`,
113
+ )
114
+ mkdirSync(dirname(scriptPath), { recursive: true })
115
+
116
+ const scriptParts = ['#!/bin/bash']
117
+ if (options?.scriptPreamble) {
118
+ scriptParts.push(options.scriptPreamble.trimEnd())
119
+ }
120
+ scriptParts.push(command)
121
+
122
+ writeFileSync(scriptPath, `${scriptParts.join('\n')}\n`, { mode: 0o755 })
123
+ sendCommand(surface, `bash ${scriptPath}`)
124
+ return scriptPath
125
+ }
126
+
127
+ function tailLines(text: string, lines: number): string {
128
+ const split = text.split('\n')
129
+ if (split.length <= lines) return text
130
+ return split.slice(-lines).join('\n')
131
+ }
132
+
133
+ /** Read pane terminal output (recent-unwrapped: stable logical lines). */
134
+ export function readScreen(surface: string, lines = 50): string {
135
+ return tailLines(
136
+ herdrReadPane(surface, { lines, source: 'recent-unwrapped' }),
137
+ lines,
138
+ )
139
+ }
140
+
141
+ /** Read pane terminal output (async wrapper). */
142
+ export async function readScreenAsync(
143
+ surface: string,
144
+ lines = 50,
145
+ ): Promise<string> {
146
+ return readScreen(surface, lines)
147
+ }
148
+
149
+ export function shellEscape(s: string): string {
150
+ return `'${s.replace(/'/g, "'\\''")}'`
151
+ }
152
+
153
+ export interface PollResult {
154
+ /** How the subagent exited */
155
+ reason: 'done' | 'ping' | 'sentinel' | 'error'
156
+ /** Shell exit code (from sentinel). 0 for file-based exits. */
157
+ exitCode: number
158
+ /** Ping data if reason is "ping" */
159
+ ping?: { name: string; message: string }
160
+ /** Error message if reason is "error" (auto-retry exhausted, crash, etc.) */
161
+ errorMessage?: string
162
+ }
163
+
164
+ /**
165
+ * Interpret an `.exit` sidecar payload (written by subagent_done / caller_ping /
166
+ * the error path in subagent-done.ts). Centralized so both the fast and slow
167
+ * paths in pollForExit decode the payload the same way.
168
+ */
169
+ function interpretExitSidecar(data: any): PollResult {
170
+ if (data?.type === 'ping') {
171
+ return {
172
+ reason: 'ping',
173
+ exitCode: 0,
174
+ ping: { name: data.name, message: data.message },
175
+ }
176
+ }
177
+ if (data?.type === 'error') {
178
+ const errorMessage =
179
+ typeof data.errorMessage === 'string' && data.errorMessage.trim() !== ''
180
+ ? data.errorMessage
181
+ : 'Subagent exited with stopReason=error (no errorMessage in sidecar).'
182
+ return { reason: 'error', exitCode: 1, errorMessage }
183
+ }
184
+ return { reason: 'done', exitCode: 0 }
185
+ }
186
+
187
+ export const __pollForExitTest__ = { interpretExitSidecar }
188
+
189
+ /**
190
+ * Poll check order for one pollForExit tick. Exported for tests — the order is
191
+ * load-bearing: `.ask` (blocked-but-alive, PMR-WXG0) must be observed BEFORE
192
+ * the liveness probe, or a blocked child gets misclassified as crashed.
193
+ *
194
+ * AIDEV-NOTE (PMR-TABUX): the screen-sentinel scrape and the wrapper-shell
195
+ * `.code` crash file are gone — `agent start` runs pi directly in the pane, so
196
+ * there is no wrapper shell to capture the exit code. Crash inference is now
197
+ * herdr liveness: pane definitively gone + no `.exit` ⇒ crashed, fail-closed
198
+ * (surfaced as an error result, never guessed success). Probe errors fail OPEN
199
+ * (treated alive) so a herdr hiccup can't kill a live watcher.
200
+ *
201
+ * `stall` is last by design (PMR-YFRB): a verified `.exit`/sentinel and
202
+ * definitive crash inference always win over a would-be stall escalation —
203
+ * we never report "turn stalled" for a child that demonstrably exited or
204
+ * crashed, and the blocked-`.ask` carve-out (PMR-WXG0) likewise outranks
205
+ * the watchdog.
206
+ */
207
+ export type PollCheckPhase = 'exit' | 'ask' | 'liveness' | 'stall'
208
+ export const POLL_CHECK_ORDER: readonly PollCheckPhase[] = [
209
+ 'exit',
210
+ 'ask',
211
+ 'liveness',
212
+ 'stall',
213
+ ]
214
+
215
+ /**
216
+ * Timeout bound for the default herdr liveness probe (PMR-YFRB): a hung
217
+ * `herdr pane get` must not block the poll tick indefinitely; execFileSync
218
+ * kills it after this budget and the probe fails OPEN (treated alive).
219
+ */
220
+ export const LIVENESS_PROBE_TIMEOUT_MS = 10_000
221
+
222
+ /** Wait one poll interval; rejects on abort. */
223
+ function waitPollInterval(signal: AbortSignal, ms: number): Promise<void> {
224
+ return new Promise<void>((resolve, reject) => {
225
+ if (signal.aborted) return reject(new Error('Aborted'))
226
+ const timer = setTimeout(() => {
227
+ signal.removeEventListener('abort', onAbort)
228
+ resolve()
229
+ }, ms)
230
+ function onAbort() {
231
+ clearTimeout(timer)
232
+ reject(new Error('Aborted'))
233
+ }
234
+ signal.addEventListener('abort', onAbort, { once: true })
235
+ })
236
+ }
237
+
238
+ function readExitSidecar(sessionFile: string): PollResult | null {
239
+ try {
240
+ const exitFile = `${sessionFile}.exit`
241
+ if (!existsSync(exitFile)) return null
242
+ const data = JSON.parse(readFileSync(exitFile, 'utf8'))
243
+ rmSync(exitFile, { force: true })
244
+ return interpretExitSidecar(data)
245
+ } catch {
246
+ return null
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Poll until the subagent exits. Primary completion signal = the `.exit`
252
+ * sidecar (written by subagent_done / caller_ping). A blocked `.ask` keeps
253
+ * the poll alive. Crash inference: when the herdr pane is definitively gone
254
+ * and no `.exit` ever appeared, return a fail-closed error result.
255
+ */
256
+ export async function pollForExit(
257
+ surface: string,
258
+ signal: AbortSignal,
259
+ options: {
260
+ interval: number
261
+ sessionFile?: string
262
+ sentinelFile?: string
263
+ onTick?: (elapsed: number) => void
264
+ /** Called each tick while a `.ask` sidecar is present (blocked child). */
265
+ onAsk?: () => void
266
+ /**
267
+ * Called when a VERIFIED completion signal is observed (the `.exit`
268
+ * sidecar or the claude sentinel file) — as opposed to crash inference
269
+ * from liveness. Assignment cleanup (PMR-Z5KR) gates record removal on
270
+ * this distinction.
271
+ */
272
+ onVerifiedExit?: () => void
273
+ /** Liveness probe; defaults to herdr pane liveness. Injectable for tests. */
274
+ isAlive?: (paneId: string) => boolean
275
+ /**
276
+ * Stall watchdog hook (PMR-YFRB), checked each tick AFTER onTick and
277
+ * BEFORE the wait — and after `.ask` and liveness, so verified exits,
278
+ * definitive crash inference, and the blocked carve-out always win.
279
+ * Return a PollResult to resolve the poll with it; return null to keep
280
+ * polling.
281
+ */
282
+ checkStall?: () => PollResult | null
283
+ },
284
+ ): Promise<PollResult> {
285
+ const start = Date.now()
286
+ // Default probe bounded by LIVENESS_PROBE_TIMEOUT_MS so a hung herdr CLI
287
+ // fails OPEN promptly instead of blocking the tick loop (PMR-YFRB).
288
+ const isAlive =
289
+ options.isAlive ??
290
+ ((paneId: string) => herdrPaneAlive(paneId, LIVENESS_PROBE_TIMEOUT_MS))
291
+
292
+ for (;;) {
293
+ if (signal.aborted) {
294
+ throw new Error('Aborted while waiting for subagent to finish')
295
+ }
296
+
297
+ // Primary path: `.exit` sidecar (subagent_done / caller_ping).
298
+ if (options.sessionFile) {
299
+ const exit = readExitSidecar(options.sessionFile)
300
+ if (exit) {
301
+ options.onVerifiedExit?.()
302
+ return exit
303
+ }
304
+ }
305
+
306
+ // Claude sentinel file (written by the plugin Stop hook).
307
+ if (options.sentinelFile) {
308
+ try {
309
+ if (existsSync(options.sentinelFile)) {
310
+ options.onVerifiedExit?.()
311
+ return { reason: 'sentinel', exitCode: 0 }
312
+ }
313
+ } catch {}
314
+ }
315
+
316
+ // Blocked-ask observation (PMR-WXG0): `.ask` sidecar present ⇒ the child
317
+ // is blocked-asking and ALIVE. Checked BEFORE the liveness probe. The poll
318
+ // deliberately does NOT resolve — the watcher keeps waiting for `.exit`.
319
+ if (options.sessionFile) {
320
+ try {
321
+ if (existsSync(`${options.sessionFile}.ask`)) {
322
+ options.onAsk?.()
323
+ options.onTick?.(Math.floor((Date.now() - start) / 1000))
324
+ await waitPollInterval(signal, options.interval)
325
+ continue
326
+ }
327
+ } catch (err) {
328
+ // Abort must propagate — swallowing it here would let the loop fall
329
+ // through to the stall watchdog and resolve on a blocked child.
330
+ if (signal.aborted) throw err
331
+ }
332
+ }
333
+
334
+ // Crash inference (PMR-TABUX): pane gone + no `.exit` ⇒ crashed or killed.
335
+ // Fail closed as an error result — never guess success. A probe that
336
+ // itself throws fails OPEN (treated alive) so a herdr hiccup can't kill
337
+ // a live watcher.
338
+ if (options.sessionFile) {
339
+ let alive = true
340
+ try {
341
+ alive = isAlive(surface)
342
+ } catch {}
343
+ if (!alive) {
344
+ return {
345
+ reason: 'error',
346
+ exitCode: 1,
347
+ errorMessage:
348
+ 'Subagent pane disappeared without an exit sidecar (crashed or killed).',
349
+ }
350
+ }
351
+ }
352
+
353
+ const elapsed = Math.floor((Date.now() - start) / 1000)
354
+ options.onTick?.(elapsed)
355
+
356
+ // Stall watchdog (PMR-YFRB): last check of the tick. A non-null verdict
357
+ // resolves the poll; verified exits and crash inference above outrank it.
358
+ const stall = options.checkStall?.()
359
+ if (stall) {
360
+ return stall
361
+ }
362
+
363
+ await waitPollInterval(signal, options.interval)
364
+ }
365
+ }
@@ -0,0 +1,113 @@
1
+ // AIDEV-NOTE: Pure task-composition module. Split into a stable layer (the
2
+ // wrapper/role strings: identity, flag, modeHint, summaryInstruction —
3
+ // deterministic given the same role inputs, safe to cache/prefix-stabilize
4
+ // across spawns) and a dynamic layer (the task body, which differs per
5
+ // spawn). No fs/process/env access by design so it stays unit-testable and
6
+ // side-effect free. Extracted from subagents/index.ts spawn logic (PMR-ECJK
7
+ // removed the originals). The wrapper strings below are load-bearing: the
8
+ // byte-exactness invariant is enforced by the top-level asserts in
9
+ // test/task-composition.test.ts.
10
+
11
+ export type SystemPromptMode = 'append' | 'replace'
12
+
13
+ export interface ComposeChildTaskInput {
14
+ task: string
15
+ identity: string | null
16
+ systemPromptMode: 'append' | 'replace' | undefined
17
+ autoExit: boolean
18
+ inheritsConversationContext: boolean
19
+ }
20
+
21
+ export interface ComposeChildTaskResult {
22
+ systemPromptIdentity: string | null
23
+ systemPromptFlag: '--system-prompt' | '--append-system-prompt' | null
24
+ taskMessage: string
25
+ }
26
+
27
+ // Historical: copied byte-for-byte from subagents/index.ts (~2502–2507),
28
+ // since removed (PMR-ECJK). The byte-exact values are pinned by the
29
+ // top-level asserts in test/task-composition.test.ts — change them together.
30
+ export const AUTO_EXIT_HINT = 'Complete your task autonomously.'
31
+ export const DEFAULT_HINT =
32
+ 'Complete your task. When finished, call the subagent_done tool. The user can interact with you at any time.'
33
+ export const AUTO_EXIT_SUMMARY_INSTRUCTION =
34
+ 'Your FINAL assistant message should summarize what you accomplished.'
35
+ export const DEFAULT_SUMMARY_INSTRUCTION =
36
+ 'Your FINAL assistant message (before calling subagent_done or before the user exits) should summarize what you accomplished.'
37
+
38
+ function isExplicitMode(
39
+ mode: 'append' | 'replace' | undefined,
40
+ ): mode is SystemPromptMode {
41
+ return mode === 'append' || mode === 'replace'
42
+ }
43
+
44
+ function flagForMode(
45
+ mode: SystemPromptMode,
46
+ ): '--system-prompt' | '--append-system-prompt' {
47
+ if (mode === 'replace') {
48
+ return '--system-prompt'
49
+ }
50
+ return '--append-system-prompt'
51
+ }
52
+
53
+ function modeHintFor(autoExit: boolean): string {
54
+ if (autoExit) {
55
+ return AUTO_EXIT_HINT
56
+ }
57
+ return DEFAULT_HINT
58
+ }
59
+
60
+ function summaryInstructionFor(autoExit: boolean): string {
61
+ if (autoExit) {
62
+ return AUTO_EXIT_SUMMARY_INSTRUCTION
63
+ }
64
+ return DEFAULT_SUMMARY_INSTRUCTION
65
+ }
66
+
67
+ export function composeChildTask(
68
+ input: ComposeChildTaskInput,
69
+ ): ComposeChildTaskResult {
70
+ const { task, systemPromptMode, autoExit, inheritsConversationContext } =
71
+ input
72
+
73
+ // AIDEV-NOTE: PMR-W2EP — normalize '' to null up front, matching the old
74
+ // consumer truthiness in index.ts: an empty identity must not produce a
75
+ // system-prompt flag (a `!== null` consumer would otherwise write an empty
76
+ // sysprompt file).
77
+ const identity = input.identity === '' ? null : input.identity
78
+
79
+ const explicitMode = isExplicitMode(systemPromptMode)
80
+
81
+ // Identity flag routing.
82
+ let systemPromptFlag: ComposeChildTaskResult['systemPromptFlag'] = null
83
+ if (identity === null) {
84
+ systemPromptFlag = null
85
+ } else if (explicitMode) {
86
+ systemPromptFlag = flagForMode(systemPromptMode)
87
+ } else if (inheritsConversationContext) {
88
+ // Fork with no explicit mode keeps existing semantics: identity is dropped.
89
+ systemPromptFlag = null
90
+ } else {
91
+ // Non-fork with no/invalid mode: append is the new default.
92
+ systemPromptFlag = '--append-system-prompt'
93
+ }
94
+
95
+ let systemPromptIdentity: string | null = null
96
+ if (systemPromptFlag !== null) {
97
+ systemPromptIdentity = identity
98
+ }
99
+
100
+ const modeHint = modeHintFor(autoExit)
101
+ const summaryInstruction = summaryInstructionFor(autoExit)
102
+
103
+ let taskMessage: string
104
+ if (inheritsConversationContext) {
105
+ // Fork: bare task; identity (if any) is delivered only via an explicit
106
+ // mode flag above.
107
+ taskMessage = task
108
+ } else {
109
+ taskMessage = `${modeHint}\n\n${task}\n\n${summaryInstruction}`
110
+ }
111
+
112
+ return { systemPromptIdentity, systemPromptFlag, taskMessage }
113
+ }
@@ -0,0 +1,203 @@
1
+ // Durable per-logical-tool-call effect memo for child side-effect tools
2
+ // (PMR-ZJCP).
3
+ //
4
+ // Memo-after-effect discipline (delivered.ts PMR-KY0E precedent): a child
5
+ // tool handler performs its durable effect, THEN writes an exclusive-create
6
+ // memo keyed by a logical fingerprint of the call. On replay after an
7
+ // interrupted run, a memo hit means the earlier effect already happened and
8
+ // the handler returns the memoized result instead of repeating the effect.
9
+ //
10
+ // AIDEV-NOTE (PMR-ZJCP): mark-after-effect discipline — the memo is written
11
+ // only AFTER the durable effect succeeded, so a memo hit is trustworthy
12
+ // evidence of completion. Narrow send→mark crash windows are NOT covered by
13
+ // the memo alone; handlers consult the effect's own durable records (ask
14
+ // record, recipient inbox, .exit payload) as additional evidence. Memos are
15
+ // deliberately NEVER cleaned up — no wipe, no GC, no TTL — so they survive
16
+ // the PMR-WXG0 resume wipe (removeAskRecordsForSession) and remain the
17
+ // durable record of an interrupted child's effects forever.
18
+ import { createHash } from 'node:crypto'
19
+ import {
20
+ closeSync,
21
+ fsyncSync,
22
+ mkdirSync,
23
+ openSync,
24
+ readFileSync,
25
+ renameSync,
26
+ writeSync,
27
+ } from 'node:fs'
28
+ import { join } from 'node:path'
29
+ import { ensureSubagentsDataDir, subagentsDataRoot } from './dataroot.ts'
30
+
31
+ export type ChildEffectTool =
32
+ | 'ask_owner'
33
+ | 'caller_ping'
34
+ | 'subagent_done'
35
+ | 'message_owner'
36
+ | 'message_peer'
37
+
38
+ export interface ChildToolEffectMemo {
39
+ version: 1
40
+ childId: string
41
+ tool: ChildEffectTool
42
+ fingerprint: string
43
+ createdAt: string
44
+ result: Record<string, unknown>
45
+ }
46
+
47
+ function sanitizeChildId(childId: string): string {
48
+ const safe = childId.replace(/[^A-Za-z0-9._-]/g, '_')
49
+ if (safe === '' || safe === '.' || safe === '..') return '_'
50
+ return safe
51
+ }
52
+
53
+ // AIDEV-NOTE: canonical JSON — recursively sorted object keys, undefined
54
+ // values dropped — so pi-core param ordering can never split a fingerprint.
55
+ function canonicalJson(value: unknown): string {
56
+ if (value === undefined) return 'null'
57
+ if (value === null) return 'null'
58
+ if (Array.isArray(value)) {
59
+ const items: string[] = []
60
+ for (const item of value) {
61
+ if (item === undefined) {
62
+ items.push('null')
63
+ } else {
64
+ items.push(canonicalJson(item))
65
+ }
66
+ }
67
+ return `[${items.join(',')}]`
68
+ }
69
+ if (typeof value === 'object') {
70
+ const record = value as Record<string, unknown>
71
+ const keys = Object.keys(record).sort()
72
+ const parts: string[] = []
73
+ for (const key of keys) {
74
+ const member = record[key]
75
+ if (member === undefined) continue
76
+ parts.push(`${JSON.stringify(key)}:${canonicalJson(member)}`)
77
+ }
78
+ return `{${parts.join(',')}}`
79
+ }
80
+ return JSON.stringify(value)
81
+ }
82
+
83
+ /** sha256 over canonical JSON: recursively sorted keys, undefined dropped. */
84
+ export function effectFingerprint(
85
+ tool: ChildEffectTool,
86
+ childId: string,
87
+ params: unknown,
88
+ ): string {
89
+ return createHash('sha256')
90
+ .update(canonicalJson({ tool, childId, params }))
91
+ .digest('hex')
92
+ }
93
+
94
+ /** Memo path: `<dataRoot>/tool-effects/<childId>/<tool>-<fingerprint>.json`. */
95
+ export function effectMemoPath(
96
+ childId: string,
97
+ tool: ChildEffectTool,
98
+ fingerprint: string,
99
+ root: string = subagentsDataRoot(),
100
+ ): string {
101
+ return join(
102
+ ensureSubagentsDataDir('tool-effects', root),
103
+ sanitizeChildId(childId),
104
+ `${tool}-${fingerprint}.json`,
105
+ )
106
+ }
107
+
108
+ /** Hand-rolled structural validator (never TypeBox for durable records). */
109
+ export function isChildToolEffectMemo(
110
+ value: unknown,
111
+ ): value is ChildToolEffectMemo {
112
+ if (value == null || typeof value !== 'object') return false
113
+ const record = value as Record<string, unknown>
114
+ if (record.version !== 1) return false
115
+ if (typeof record.childId !== 'string') return false
116
+ if (
117
+ record.tool !== 'ask_owner' &&
118
+ record.tool !== 'caller_ping' &&
119
+ record.tool !== 'subagent_done' &&
120
+ record.tool !== 'message_owner' &&
121
+ record.tool !== 'message_peer'
122
+ ) {
123
+ return false
124
+ }
125
+ if (typeof record.fingerprint !== 'string') return false
126
+ if (typeof record.createdAt !== 'string') return false
127
+ if (record.result == null || typeof record.result !== 'object') return false
128
+ if (Array.isArray(record.result)) return false
129
+ return true
130
+ }
131
+
132
+ /** Fail closed: null on missing or malformed (asks.ts readAskRecord style). */
133
+ export function readEffectMemo(
134
+ childId: string,
135
+ tool: ChildEffectTool,
136
+ fingerprint: string,
137
+ root?: string,
138
+ ): ChildToolEffectMemo | null {
139
+ let raw: string
140
+ try {
141
+ raw = readFileSync(effectMemoPath(childId, tool, fingerprint, root), 'utf8')
142
+ } catch {
143
+ return null
144
+ }
145
+ try {
146
+ const parsed = JSON.parse(raw) as unknown
147
+ if (!isChildToolEffectMemo(parsed)) return null
148
+ return parsed
149
+ } catch {
150
+ return null
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Exclusive create (openSync 'wx', 0o600, write+fsync+close). Returns true
156
+ * when newly written, false when the memo already exists (EEXIST).
157
+ */
158
+ export function writeEffectMemo(
159
+ memo: ChildToolEffectMemo,
160
+ root?: string,
161
+ ): boolean {
162
+ const path = effectMemoPath(memo.childId, memo.tool, memo.fingerprint, root)
163
+ mkdirSync(join(path, '..'), { recursive: true, mode: 0o700 })
164
+ let fd: number
165
+ try {
166
+ fd = openSync(path, 'wx', 0o600)
167
+ } catch (error) {
168
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') return false
169
+ throw error
170
+ }
171
+ try {
172
+ writeSync(fd, JSON.stringify(memo))
173
+ fsyncSync(fd)
174
+ } finally {
175
+ closeSync(fd)
176
+ }
177
+ return true
178
+ }
179
+
180
+ function atomicWrite(path: string, contents: string): void {
181
+ const tmpPath = `${path}.${process.pid}.tmp`
182
+ const fd = openSync(tmpPath, 'w', 0o600)
183
+ try {
184
+ writeSync(fd, contents)
185
+ fsyncSync(fd)
186
+ } finally {
187
+ closeSync(fd)
188
+ }
189
+ renameSync(tmpPath, path)
190
+ }
191
+
192
+ // AIDEV-NOTE (PMR-ZJCP): atomic rewrite (tmp + fsync + rename, asks.ts
193
+ // atomicWrite shape) — used ONLY on the ask_owner orphan-fallback replay
194
+ // path, where a stale memo from a pre-wipe run must be replaced by the
195
+ // fresh ask's result. Exclusive create alone cannot express that update.
196
+ export function rewriteEffectMemo(
197
+ memo: ChildToolEffectMemo,
198
+ root?: string,
199
+ ): void {
200
+ const path = effectMemoPath(memo.childId, memo.tool, memo.fingerprint, root)
201
+ mkdirSync(join(path, '..'), { recursive: true, mode: 0o700 })
202
+ atomicWrite(path, JSON.stringify(memo))
203
+ }