@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.
- package/LICENSE +21 -0
- package/README.md +462 -2
- package/agents/claude-code.md +23 -0
- package/agents/planner.md +569 -0
- package/agents/reviewer.md +152 -0
- package/agents/scout.md +112 -0
- package/agents/visual-tester.md +202 -0
- package/agents/worker.md +109 -0
- package/config.json.example +6 -0
- package/config.schema.json +71 -0
- package/package.json +59 -4
- package/pi-extension/subagents/activity.ts +730 -0
- package/pi-extension/subagents/asks.ts +234 -0
- package/pi-extension/subagents/assignments.ts +395 -0
- package/pi-extension/subagents/config.ts +191 -0
- package/pi-extension/subagents/control.ts +172 -0
- package/pi-extension/subagents/dataroot.ts +52 -0
- package/pi-extension/subagents/delivered.ts +81 -0
- package/pi-extension/subagents/flow-env.ts +112 -0
- package/pi-extension/subagents/herdr.ts +323 -0
- package/pi-extension/subagents/inbox.ts +213 -0
- package/pi-extension/subagents/index.ts +5003 -0
- package/pi-extension/subagents/lock.ts +318 -0
- package/pi-extension/subagents/peer-bindings.ts +175 -0
- package/pi-extension/subagents/peers.ts +401 -0
- package/pi-extension/subagents/plan-skill.md +219 -0
- package/pi-extension/subagents/plugin/.claude-plugin/plugin.json +5 -0
- package/pi-extension/subagents/plugin/hooks/hooks.json +15 -0
- package/pi-extension/subagents/plugin/hooks/on-stop.sh +68 -0
- package/pi-extension/subagents/retention.ts +918 -0
- package/pi-extension/subagents/retirement.ts +216 -0
- package/pi-extension/subagents/session.ts +194 -0
- package/pi-extension/subagents/snapshot.ts +151 -0
- package/pi-extension/subagents/spawn.ts +237 -0
- package/pi-extension/subagents/spawnseq.ts +116 -0
- package/pi-extension/subagents/state-events.ts +152 -0
- package/pi-extension/subagents/status.ts +886 -0
- package/pi-extension/subagents/store.ts +245 -0
- package/pi-extension/subagents/subagent-done.ts +1452 -0
- package/pi-extension/subagents/surface.ts +365 -0
- package/pi-extension/subagents/task-composition.ts +113 -0
- package/pi-extension/subagents/tool-effects.ts +203 -0
- package/pi-extension/subagents/usage.ts +330 -0
- package/pi-extension/subagents/watermark.ts +126 -0
- package/pi-extension/subagents/worktrees.ts +147 -0
- package/skills/subagent-orchestration/SKILL.md +57 -0
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// Context retirement (PMR-1EC3). Port of herdsman's contextRetirement
|
|
2
|
+
// policy (ADR 0010: finish-and-hand-off, deterministic, governable),
|
|
3
|
+
// re-scoped to the PARENT session: once automatic compaction pressure
|
|
4
|
+
// arrives (session_before_compact, reason threshold/overflow), settled
|
|
5
|
+
// subagent payloads (subagent_result / subagent_ask / subagent_message
|
|
6
|
+
// custom messages) are retired per provider request to durable refs on
|
|
7
|
+
// disk. The session file keeps full records — only the model-visible
|
|
8
|
+
// context stops growing with child history. We never cancel or replace
|
|
9
|
+
// pi's native compaction, so manual/emergency compaction is untouched
|
|
10
|
+
// and there is no loop-block risk.
|
|
11
|
+
import { createHash } from 'node:crypto'
|
|
12
|
+
import { closeSync, existsSync, fsyncSync, openSync, writeSync } from 'node:fs'
|
|
13
|
+
import { join } from 'node:path'
|
|
14
|
+
import { ensureSubagentsDataDir, subagentsDataRoot } from './dataroot.ts'
|
|
15
|
+
|
|
16
|
+
// AIDEV-NOTE: narrow structural type for the subset of pi's AgentMessage
|
|
17
|
+
// union we inspect (pi's CustomMessage). pi-coding-agent does not
|
|
18
|
+
// re-export AgentMessage, and a type-only dependency on pi-agent-core is
|
|
19
|
+
// not declared in this package.
|
|
20
|
+
export interface RetirableMessage {
|
|
21
|
+
role: string
|
|
22
|
+
customType?: string
|
|
23
|
+
content?: unknown
|
|
24
|
+
details?: unknown
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const RETIRABLE_CUSTOM_TYPES: readonly string[] = [
|
|
28
|
+
'subagent_result',
|
|
29
|
+
'subagent_ask',
|
|
30
|
+
'subagent_message',
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
/** Stub prefix doubles as the already-retired marker (idempotent re-runs). */
|
|
34
|
+
export const RETIRED_STUB_PREFIX = '[retired subagent payload]'
|
|
35
|
+
|
|
36
|
+
/** Payloads smaller than this stay inline — retiring them buys nothing. */
|
|
37
|
+
export const DEFAULT_RETIREMENT_MIN_BYTES = 2048
|
|
38
|
+
|
|
39
|
+
/** Newest N retirable payloads keep their full text for the parent. */
|
|
40
|
+
export const DEFAULT_RETIREMENT_KEEP_RECENT = 1
|
|
41
|
+
|
|
42
|
+
export interface RetirementOptions {
|
|
43
|
+
minBytes?: number
|
|
44
|
+
keepRecent?: number
|
|
45
|
+
/** Data-root override for tests; defaults to subagentsDataRoot(). */
|
|
46
|
+
root?: string
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface RetirementOutcome<T> {
|
|
50
|
+
messages: T[]
|
|
51
|
+
retired: number
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Pure arming decision (unit-tested). Retirement arms on automatic context
|
|
56
|
+
* pressure only: threshold and overflow. Manual /compact never arms it —
|
|
57
|
+
* the user asked for summarization, not retirement.
|
|
58
|
+
*/
|
|
59
|
+
export function shouldArmRetirement(
|
|
60
|
+
reason: 'manual' | 'threshold' | 'overflow',
|
|
61
|
+
enabled: boolean,
|
|
62
|
+
): boolean {
|
|
63
|
+
if (!enabled) return false
|
|
64
|
+
if (reason === 'manual') return false
|
|
65
|
+
return true
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
interface RetirableDetails {
|
|
69
|
+
name?: string
|
|
70
|
+
resultPath?: string
|
|
71
|
+
resultRef?: string
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function narrowDetails(details: unknown): RetirableDetails {
|
|
75
|
+
if (typeof details !== 'object' || details === null) return {}
|
|
76
|
+
const raw = details as Record<string, unknown>
|
|
77
|
+
const narrowed: RetirableDetails = {}
|
|
78
|
+
if (typeof raw.name === 'string') narrowed.name = raw.name
|
|
79
|
+
if (typeof raw.resultPath === 'string') narrowed.resultPath = raw.resultPath
|
|
80
|
+
if (typeof raw.resultRef === 'string') narrowed.resultRef = raw.resultRef
|
|
81
|
+
return narrowed
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function isRetirableCandidate(
|
|
85
|
+
msg: RetirableMessage,
|
|
86
|
+
minBytes: number,
|
|
87
|
+
): boolean {
|
|
88
|
+
if (msg.role !== 'custom') return false
|
|
89
|
+
if (msg.customType === undefined) return false
|
|
90
|
+
if (!RETIRABLE_CUSTOM_TYPES.includes(msg.customType)) return false
|
|
91
|
+
if (typeof msg.content !== 'string') return false
|
|
92
|
+
if (msg.content.startsWith(RETIRED_STUB_PREFIX)) return false
|
|
93
|
+
return Buffer.byteLength(msg.content, 'utf8') >= minBytes
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// AIDEV-NOTE: hash-named records make retirement idempotent across requests —
|
|
97
|
+
// the context hook re-runs on a fresh clone every provider call, and the same
|
|
98
|
+
// payload always resolves to the same path (exclusive create, losers reuse).
|
|
99
|
+
function writeRetiredPayload(
|
|
100
|
+
customType: string,
|
|
101
|
+
content: string,
|
|
102
|
+
details: unknown,
|
|
103
|
+
root?: string,
|
|
104
|
+
): string | null {
|
|
105
|
+
const hash = createHash('sha256')
|
|
106
|
+
.update(customType)
|
|
107
|
+
.update('\0')
|
|
108
|
+
.update(content)
|
|
109
|
+
.digest('hex')
|
|
110
|
+
const dir = ensureSubagentsDataDir('retired', root ?? subagentsDataRoot())
|
|
111
|
+
const path = join(dir, `${hash}.json`)
|
|
112
|
+
if (existsSync(path)) return path
|
|
113
|
+
const record: Record<string, unknown> = {
|
|
114
|
+
customType,
|
|
115
|
+
content,
|
|
116
|
+
retiredAt: new Date().toISOString(),
|
|
117
|
+
}
|
|
118
|
+
if (details !== undefined) record.details = details
|
|
119
|
+
const serialized = JSON.stringify(record)
|
|
120
|
+
try {
|
|
121
|
+
const fd = openSync(path, 'wx', 0o600)
|
|
122
|
+
try {
|
|
123
|
+
writeSync(fd, serialized)
|
|
124
|
+
fsyncSync(fd)
|
|
125
|
+
} finally {
|
|
126
|
+
closeSync(fd)
|
|
127
|
+
}
|
|
128
|
+
} catch {
|
|
129
|
+
if (existsSync(path)) return path
|
|
130
|
+
return null
|
|
131
|
+
}
|
|
132
|
+
return path
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function buildRetirementStub(
|
|
136
|
+
customType: string,
|
|
137
|
+
name: string | undefined,
|
|
138
|
+
refPath: string,
|
|
139
|
+
resultRef: string | undefined,
|
|
140
|
+
): string {
|
|
141
|
+
let subject = customType
|
|
142
|
+
if (name !== undefined) subject = `${customType} "${name}"`
|
|
143
|
+
let ref = refPath
|
|
144
|
+
if (resultRef !== undefined) ref = `${refPath} (${resultRef})`
|
|
145
|
+
return `${RETIRED_STUB_PREFIX} ${subject} — full text retired to ${ref}. Read that file if you need the complete payload.`
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Replace large settled-subagent payloads with durable-ref stubs. Returns
|
|
150
|
+
* the input untouched (same array identity, retired 0) when nothing
|
|
151
|
+
* qualifies; otherwise a new array with copied message objects. Never
|
|
152
|
+
* mutates the input messages. The most recent `keepRecent` candidates stay
|
|
153
|
+
* inline so the parent keeps the freshest result in full.
|
|
154
|
+
*/
|
|
155
|
+
export function retireSettledSubagentPayloads<T extends RetirableMessage>(
|
|
156
|
+
messages: T[],
|
|
157
|
+
opts: RetirementOptions = {},
|
|
158
|
+
): RetirementOutcome<T> {
|
|
159
|
+
const minBytes = opts.minBytes ?? DEFAULT_RETIREMENT_MIN_BYTES
|
|
160
|
+
const keepRecent = opts.keepRecent ?? DEFAULT_RETIREMENT_KEEP_RECENT
|
|
161
|
+
|
|
162
|
+
const candidates: number[] = []
|
|
163
|
+
for (let i = 0; i < messages.length; i++) {
|
|
164
|
+
const msg = messages[i]
|
|
165
|
+
if (msg !== undefined && isRetirableCandidate(msg, minBytes)) {
|
|
166
|
+
candidates.push(i)
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const retireCount = candidates.length - keepRecent
|
|
170
|
+
if (retireCount <= 0) return { messages, retired: 0 }
|
|
171
|
+
|
|
172
|
+
const out = messages.slice()
|
|
173
|
+
let retired = 0
|
|
174
|
+
for (let c = 0; c < retireCount; c++) {
|
|
175
|
+
const index = candidates[c]
|
|
176
|
+
if (index === undefined) continue
|
|
177
|
+
const msg = out[index]
|
|
178
|
+
if (msg === undefined || typeof msg.content !== 'string') continue
|
|
179
|
+
const customType = msg.customType
|
|
180
|
+
if (customType === undefined) continue
|
|
181
|
+
|
|
182
|
+
const details = narrowDetails(msg.details)
|
|
183
|
+
// subagent_result already has a durable record in the store (see
|
|
184
|
+
// store.ts) — point at it instead of writing a second copy.
|
|
185
|
+
let refPath: string | null = null
|
|
186
|
+
let resultRef: string | undefined
|
|
187
|
+
if (customType === 'subagent_result' && details.resultPath !== undefined) {
|
|
188
|
+
if (existsSync(details.resultPath)) {
|
|
189
|
+
refPath = details.resultPath
|
|
190
|
+
resultRef = details.resultRef
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
if (refPath === null) {
|
|
194
|
+
refPath = writeRetiredPayload(
|
|
195
|
+
customType,
|
|
196
|
+
msg.content,
|
|
197
|
+
msg.details,
|
|
198
|
+
opts.root,
|
|
199
|
+
)
|
|
200
|
+
}
|
|
201
|
+
if (refPath === null) continue
|
|
202
|
+
|
|
203
|
+
out[index] = {
|
|
204
|
+
...msg,
|
|
205
|
+
content: buildRetirementStub(
|
|
206
|
+
customType,
|
|
207
|
+
details.name,
|
|
208
|
+
refPath,
|
|
209
|
+
resultRef,
|
|
210
|
+
),
|
|
211
|
+
}
|
|
212
|
+
retired++
|
|
213
|
+
}
|
|
214
|
+
if (retired === 0) return { messages, retired: 0 }
|
|
215
|
+
return { messages: out, retired }
|
|
216
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { randomBytes, randomUUID } from 'node:crypto'
|
|
2
|
+
import {
|
|
3
|
+
appendFileSync,
|
|
4
|
+
copyFileSync,
|
|
5
|
+
mkdirSync,
|
|
6
|
+
readFileSync,
|
|
7
|
+
writeFileSync,
|
|
8
|
+
} from 'node:fs'
|
|
9
|
+
import { dirname, join } from 'node:path'
|
|
10
|
+
|
|
11
|
+
export interface SessionEntry {
|
|
12
|
+
type: string
|
|
13
|
+
id: string
|
|
14
|
+
parentId?: string
|
|
15
|
+
[key: string]: unknown
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface MessageEntry extends SessionEntry {
|
|
19
|
+
type: 'message'
|
|
20
|
+
message: {
|
|
21
|
+
role: 'user' | 'assistant' | 'toolResult'
|
|
22
|
+
content: Array<{ type: string; text?: string; [key: string]: unknown }>
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export type SeededSubagentSessionMode = 'lineage-only' | 'fork'
|
|
27
|
+
|
|
28
|
+
function getForkContentLines(parentSessionFile: string): string[] {
|
|
29
|
+
const raw = readFileSync(parentSessionFile, 'utf8')
|
|
30
|
+
const lines = raw.split('\n').filter((line) => line.trim())
|
|
31
|
+
|
|
32
|
+
let truncateAt = lines.length
|
|
33
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
34
|
+
try {
|
|
35
|
+
const entry = JSON.parse(lines[i])
|
|
36
|
+
if (entry.type === 'message' && entry.message?.role === 'user') {
|
|
37
|
+
truncateAt = i
|
|
38
|
+
break
|
|
39
|
+
}
|
|
40
|
+
} catch {
|
|
41
|
+
// ignore malformed lines
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return lines.slice(0, truncateAt).filter((line) => {
|
|
46
|
+
try {
|
|
47
|
+
return JSON.parse(line).type !== 'session'
|
|
48
|
+
} catch {
|
|
49
|
+
return true
|
|
50
|
+
}
|
|
51
|
+
})
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function seedSubagentSessionFile(params: {
|
|
55
|
+
mode: SeededSubagentSessionMode
|
|
56
|
+
parentSessionFile: string
|
|
57
|
+
childSessionFile: string
|
|
58
|
+
childCwd: string
|
|
59
|
+
}): void {
|
|
60
|
+
const header = {
|
|
61
|
+
type: 'session',
|
|
62
|
+
version: 3,
|
|
63
|
+
id: randomUUID(),
|
|
64
|
+
timestamp: new Date().toISOString(),
|
|
65
|
+
cwd: params.childCwd,
|
|
66
|
+
parentSession: params.parentSessionFile,
|
|
67
|
+
}
|
|
68
|
+
const contentLines =
|
|
69
|
+
params.mode === 'fork' ? getForkContentLines(params.parentSessionFile) : []
|
|
70
|
+
const lines = [JSON.stringify(header), ...contentLines]
|
|
71
|
+
|
|
72
|
+
mkdirSync(dirname(params.childSessionFile), { recursive: true })
|
|
73
|
+
writeFileSync(params.childSessionFile, `${lines.join('\n')}\n`, 'utf8')
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function readEntries(sessionFile: string): SessionEntry[] {
|
|
77
|
+
const raw = readFileSync(sessionFile, 'utf8')
|
|
78
|
+
return raw
|
|
79
|
+
.split('\n')
|
|
80
|
+
.filter((line) => line.trim())
|
|
81
|
+
.map((line) => JSON.parse(line) as SessionEntry)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Return the id of the last entry in the session file (current branch point / leaf).
|
|
86
|
+
*/
|
|
87
|
+
export function getLeafId(sessionFile: string): string | null {
|
|
88
|
+
const entries = readEntries(sessionFile)
|
|
89
|
+
return entries.length > 0 ? entries[entries.length - 1].id : null
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Return entries added after `afterLine` (1-indexed count of existing entries).
|
|
94
|
+
*/
|
|
95
|
+
export function getNewEntries(
|
|
96
|
+
sessionFile: string,
|
|
97
|
+
afterLine: number,
|
|
98
|
+
): SessionEntry[] {
|
|
99
|
+
const raw = readFileSync(sessionFile, 'utf8')
|
|
100
|
+
const lines = raw.split('\n').filter((line) => line.trim())
|
|
101
|
+
return lines.slice(afterLine).map((line) => JSON.parse(line) as SessionEntry)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Find the last assistant message text in a list of entries.
|
|
106
|
+
*
|
|
107
|
+
* Falls back to the `errorMessage` field when the last assistant message has
|
|
108
|
+
* `stopReason: "error"` and no usable text content — this happens when
|
|
109
|
+
* auto-retry exhausts on a provider overload / rate limit / server error, and
|
|
110
|
+
* without this fallback the parent would silently see a stale earlier message.
|
|
111
|
+
*/
|
|
112
|
+
export function findLastAssistantMessage(
|
|
113
|
+
entries: SessionEntry[],
|
|
114
|
+
): string | null {
|
|
115
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
116
|
+
const entry = entries[i]
|
|
117
|
+
if (entry.type !== 'message') continue
|
|
118
|
+
const msg = entry as MessageEntry
|
|
119
|
+
if (msg.message.role !== 'assistant') continue
|
|
120
|
+
|
|
121
|
+
const texts = msg.message.content
|
|
122
|
+
.filter(
|
|
123
|
+
(block) =>
|
|
124
|
+
block.type === 'text' &&
|
|
125
|
+
typeof block.text === 'string' &&
|
|
126
|
+
block.text.trim() !== '',
|
|
127
|
+
)
|
|
128
|
+
.map((block) => block.text as string)
|
|
129
|
+
|
|
130
|
+
if (texts.length > 0 && texts.join('').trim()) return texts.join('\n')
|
|
131
|
+
|
|
132
|
+
const stopReason = (msg.message as { stopReason?: unknown }).stopReason
|
|
133
|
+
const errorMessage = (msg.message as { errorMessage?: unknown })
|
|
134
|
+
.errorMessage
|
|
135
|
+
if (
|
|
136
|
+
stopReason === 'error' &&
|
|
137
|
+
typeof errorMessage === 'string' &&
|
|
138
|
+
errorMessage.trim() !== ''
|
|
139
|
+
) {
|
|
140
|
+
return `Subagent error: ${errorMessage.trim()}`
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return null
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Append a branch_summary entry to the session file.
|
|
148
|
+
* Returns the new entry's id.
|
|
149
|
+
*/
|
|
150
|
+
export function appendBranchSummary(
|
|
151
|
+
sessionFile: string,
|
|
152
|
+
branchPointId: string,
|
|
153
|
+
fromId: string | null,
|
|
154
|
+
summary: string,
|
|
155
|
+
): string {
|
|
156
|
+
const id = randomBytes(4).toString('hex')
|
|
157
|
+
const entry = {
|
|
158
|
+
type: 'branch_summary',
|
|
159
|
+
id,
|
|
160
|
+
parentId: branchPointId,
|
|
161
|
+
timestamp: new Date().toISOString(),
|
|
162
|
+
fromId: fromId ?? branchPointId,
|
|
163
|
+
summary,
|
|
164
|
+
}
|
|
165
|
+
appendFileSync(sessionFile, `${JSON.stringify(entry)}\n`, 'utf8')
|
|
166
|
+
return id
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Copy the session file to destDir for parallel worker isolation.
|
|
171
|
+
* Returns the path of the copy.
|
|
172
|
+
*/
|
|
173
|
+
export function copySessionFile(sessionFile: string, destDir: string): string {
|
|
174
|
+
const id = randomBytes(4).toString('hex')
|
|
175
|
+
const dest = join(destDir, `subagent-${id}.jsonl`)
|
|
176
|
+
copyFileSync(sessionFile, dest)
|
|
177
|
+
return dest
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Read new entries from sourceFile (after afterLine), append them to targetFile.
|
|
182
|
+
* Returns the appended entries.
|
|
183
|
+
*/
|
|
184
|
+
export function mergeNewEntries(
|
|
185
|
+
sourceFile: string,
|
|
186
|
+
targetFile: string,
|
|
187
|
+
afterLine: number,
|
|
188
|
+
): SessionEntry[] {
|
|
189
|
+
const entries = getNewEntries(sourceFile, afterLine)
|
|
190
|
+
for (const entry of entries) {
|
|
191
|
+
appendFileSync(targetFile, `${JSON.stringify(entry)}\n`, 'utf8')
|
|
192
|
+
}
|
|
193
|
+
return entries
|
|
194
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// taskGraph-style aggregate snapshot for the status-refresh loop (PMR-YJC5).
|
|
2
|
+
// AIDEV-NOTE: ONE pass per tick folds durable records into a single
|
|
3
|
+
// childId-keyed snapshot instead of scattered per-child reads. New record
|
|
4
|
+
// types plug in by adding one fold step here — never a new per-tick read
|
|
5
|
+
// loop. Atomicity discipline is unchanged: records keep their atomic
|
|
6
|
+
// writers; this module only reads. Not a durable record type — a pure fold,
|
|
7
|
+
// rebuilt every tick.
|
|
8
|
+
//
|
|
9
|
+
// AIDEV-NOTE: folds are opt-in per consumer. The tick currently consumes
|
|
10
|
+
// only the owner-inbox fold (the drain input); the asks fold runs only when
|
|
11
|
+
// includeAsks is passed — an unconsumed per-tick fold is a readdir burned
|
|
12
|
+
// for nothing. Wire includeAsks in when a tick consumer for askPending
|
|
13
|
+
// arrives.
|
|
14
|
+
import { readdirSync, readFileSync } from 'node:fs'
|
|
15
|
+
import { join } from 'node:path'
|
|
16
|
+
import type { AskRecord } from './asks.ts'
|
|
17
|
+
import { asksDir } from './asks.ts'
|
|
18
|
+
import type { OwnerInboxEntry, OwnerMessage } from './inbox.ts'
|
|
19
|
+
import { MESSAGE_VERSION, ownerInboxDir } from './inbox.ts'
|
|
20
|
+
|
|
21
|
+
/** Injectable read surface so tests can count per-tick file reads. */
|
|
22
|
+
export interface SnapshotReadIo {
|
|
23
|
+
readdir: (path: string) => string[]
|
|
24
|
+
readFile: (path: string) => string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const defaultSnapshotReadIo: SnapshotReadIo = {
|
|
28
|
+
readdir: (path) => readdirSync(path),
|
|
29
|
+
readFile: (path) => readFileSync(path, 'utf8'),
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface AggregateChildEntry {
|
|
33
|
+
/** Parent session id this snapshot was folded for (inbox owner). */
|
|
34
|
+
owner: string
|
|
35
|
+
/** Durable ask record when the child is blocked-asking; null otherwise. */
|
|
36
|
+
askPending: AskRecord | null
|
|
37
|
+
/** Count of undrained owner-inbox messages from this child. */
|
|
38
|
+
inboxPending: number
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface AggregateSnapshot {
|
|
42
|
+
children: Map<string, AggregateChildEntry>
|
|
43
|
+
/** All undrained inbox entries, filename (seq) order — drain input. */
|
|
44
|
+
inboxEntries: OwnerInboxEntry[]
|
|
45
|
+
/** Debug metric: file reads this pass (readdir + readFile). */
|
|
46
|
+
reads: number
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function parseAskRecord(raw: string, childId: string): AskRecord | null {
|
|
50
|
+
try {
|
|
51
|
+
const parsed: unknown = JSON.parse(raw)
|
|
52
|
+
if (parsed == null || typeof parsed !== 'object') return null
|
|
53
|
+
const record = parsed as Record<string, unknown>
|
|
54
|
+
if (typeof record.askId !== 'string') return null
|
|
55
|
+
if (record.childId !== childId) return null
|
|
56
|
+
if (typeof record.question !== 'string') return null
|
|
57
|
+
if (typeof record.sessionFile !== 'string') return null
|
|
58
|
+
return parsed as AskRecord
|
|
59
|
+
} catch {
|
|
60
|
+
return null
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function parseInboxMessage(raw: string): OwnerMessage | null {
|
|
65
|
+
try {
|
|
66
|
+
const parsed: unknown = JSON.parse(raw)
|
|
67
|
+
if (parsed == null || typeof parsed !== 'object') return null
|
|
68
|
+
const candidate = parsed as Record<string, unknown>
|
|
69
|
+
if (candidate.version !== MESSAGE_VERSION) return null
|
|
70
|
+
if (typeof candidate.messageId !== 'string') return null
|
|
71
|
+
if (typeof candidate.childId !== 'string') return null
|
|
72
|
+
if (typeof candidate.message !== 'string') return null
|
|
73
|
+
if (typeof candidate.sentAt !== 'string') return null
|
|
74
|
+
return parsed as OwnerMessage
|
|
75
|
+
} catch {
|
|
76
|
+
return null
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Fold all per-child ask + owner-inbox records into one snapshot in a single
|
|
82
|
+
* pass: one readdir of asks/, one readdir of the owner's inbox dir, then one
|
|
83
|
+
* read per existing record. Malformed records fail closed (omitted), matching
|
|
84
|
+
* readAskRecord/readOwnerInbox semantics.
|
|
85
|
+
*/
|
|
86
|
+
export function buildAggregateSnapshot(params: {
|
|
87
|
+
ownerSessionId: string
|
|
88
|
+
childIds: readonly string[]
|
|
89
|
+
root?: string
|
|
90
|
+
io?: SnapshotReadIo
|
|
91
|
+
/** Run the asks fold (one readdir + one read per present record). Only
|
|
92
|
+
* enable when a consumer for askPending exists. */
|
|
93
|
+
includeAsks?: boolean
|
|
94
|
+
}): AggregateSnapshot {
|
|
95
|
+
const io = params.io ?? defaultSnapshotReadIo
|
|
96
|
+
const root = params.root
|
|
97
|
+
let reads = 0
|
|
98
|
+
|
|
99
|
+
const children = new Map<string, AggregateChildEntry>()
|
|
100
|
+
for (const childId of params.childIds) {
|
|
101
|
+
children.set(childId, {
|
|
102
|
+
owner: params.ownerSessionId,
|
|
103
|
+
askPending: null,
|
|
104
|
+
inboxPending: 0,
|
|
105
|
+
})
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Fold 1 (opt-in): ask records — one readdir, then read only files present.
|
|
109
|
+
if (params.includeAsks) {
|
|
110
|
+
try {
|
|
111
|
+
const dir = asksDir(root)
|
|
112
|
+
reads += 1
|
|
113
|
+
const seen = new Set(io.readdir(dir))
|
|
114
|
+
for (const childId of params.childIds) {
|
|
115
|
+
const entry = children.get(childId)
|
|
116
|
+
if (!entry || entry.askPending) continue
|
|
117
|
+
const fileName = `${childId}.json`
|
|
118
|
+
if (!seen.has(fileName)) continue
|
|
119
|
+
reads += 1
|
|
120
|
+
entry.askPending = parseAskRecord(
|
|
121
|
+
io.readFile(join(dir, fileName)),
|
|
122
|
+
childId,
|
|
123
|
+
)
|
|
124
|
+
}
|
|
125
|
+
} catch {
|
|
126
|
+
// Missing asks dir — no pending asks; never fatal.
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Fold 2: owner inbox — one readdir, one read per record, fold counts per child.
|
|
131
|
+
const inboxEntries: OwnerInboxEntry[] = []
|
|
132
|
+
try {
|
|
133
|
+
const dir = ownerInboxDir(params.ownerSessionId, root)
|
|
134
|
+
reads += 1
|
|
135
|
+
const names = io.readdir(dir).sort()
|
|
136
|
+
for (const name of names) {
|
|
137
|
+
if (!name.endsWith('.json')) continue
|
|
138
|
+
const path = join(dir, name)
|
|
139
|
+
reads += 1
|
|
140
|
+
const message = parseInboxMessage(io.readFile(path))
|
|
141
|
+
if (!message) continue
|
|
142
|
+
inboxEntries.push({ path, message })
|
|
143
|
+
const entry = children.get(message.childId)
|
|
144
|
+
if (entry) entry.inboxPending += 1
|
|
145
|
+
}
|
|
146
|
+
} catch {
|
|
147
|
+
// Missing inbox dir — nothing pending.
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return { children, inboxEntries, reads }
|
|
151
|
+
}
|