@timmyjl12/pi-subagents 0.20.0 → 0.21.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/CHANGELOG.md +862 -827
- package/README.md +1125 -1080
- package/dist/active-agents-prompt.d.ts +31 -9
- package/dist/active-agents-prompt.js +73 -9
- package/dist/agent-color.js +9 -1
- package/dist/agent-file-toggle.d.ts +1 -1
- package/dist/agent-manager.d.ts +405 -18
- package/dist/agent-manager.js +1661 -131
- package/dist/agent-runner.d.ts +45 -6
- package/dist/agent-runner.js +109 -18
- package/dist/agent-types.d.ts +30 -7
- package/dist/agent-types.js +38 -9
- package/dist/awaited-result.d.ts +37 -0
- package/dist/awaited-result.js +150 -0
- package/dist/child-session-shutdown.d.ts +19 -1
- package/dist/child-session-shutdown.js +60 -11
- package/dist/cleanup-plans.d.ts +10 -0
- package/dist/cleanup-plans.js +112 -0
- package/dist/cross-extension-rpc.d.ts +8 -1
- package/dist/cross-extension-rpc.js +59 -5
- package/dist/custom-agents.d.ts +34 -9
- package/dist/custom-agents.js +308 -111
- package/dist/default-agents.d.ts +1 -1
- package/dist/env.d.ts +1 -1
- package/dist/error-log.d.ts +6 -0
- package/dist/error-log.js +8 -0
- package/dist/force-main-model.d.ts +21 -0
- package/dist/force-main-model.js +28 -0
- package/dist/goal-bridge.d.ts +155 -0
- package/dist/goal-bridge.js +305 -0
- package/dist/group-join.d.ts +5 -1
- package/dist/group-join.js +52 -7
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2827 -333
- package/dist/invocation-config.d.ts +30 -3
- package/dist/invocation-config.js +30 -1
- package/dist/memory.d.ts +1 -1
- package/dist/mention-clone.d.ts +1 -1
- package/dist/model-scope.d.ts +1 -1
- package/dist/nested-tools.d.ts +22 -1
- package/dist/nested-tools.js +120 -26
- package/dist/output-file.d.ts +15 -4
- package/dist/output-file.js +146 -43
- package/dist/prompts.d.ts +1 -1
- package/dist/recovery.d.ts +1 -1
- package/dist/report-cleanup.d.ts +204 -0
- package/dist/report-cleanup.js +1632 -0
- package/dist/report-store.d.ts +738 -0
- package/dist/report-store.js +3612 -0
- package/dist/schedule-store.d.ts +14 -6
- package/dist/schedule-store.js +88 -58
- package/dist/schedule.d.ts +20 -8
- package/dist/schedule.js +135 -74
- package/dist/settings.d.ts +39 -11
- package/dist/settings.js +22 -5
- package/dist/status-note.d.ts +1 -1
- package/dist/structured-output.d.ts +1 -1
- package/dist/types.d.ts +32 -3
- package/dist/ui/agent-mention.d.ts +2 -2
- package/dist/ui/agent-widget.d.ts +82 -13
- package/dist/ui/agent-widget.js +155 -37
- package/dist/ui/cleanup-preview.d.ts +59 -0
- package/dist/ui/cleanup-preview.js +466 -0
- package/dist/ui/conversation-viewer.d.ts +4 -4
- package/dist/ui/conversation-viewer.js +10 -6
- package/dist/ui/fleet-list.d.ts +3 -3
- package/dist/ui/fleet-list.js +3 -3
- package/dist/ui/fleet-overlay.d.ts +37 -6
- package/dist/ui/fleet-overlay.js +214 -18
- package/dist/ui/hub-feed.d.ts +52 -0
- package/dist/ui/hub-feed.js +148 -0
- package/dist/ui/native-transcript.js +5 -1
- package/dist/ui/schedule-menu.d.ts +1 -1
- package/dist/ui/schedule-menu.js +1 -1
- package/dist/ui/workflow-card.d.ts +4 -4
- package/dist/ui/workflow-dialog.d.ts +4 -4
- package/dist/ui/workflow-dialog.js +8 -3
- package/dist/ui/workflow-menu.d.ts +2 -2
- package/dist/usage.d.ts +12 -0
- package/dist/usage.js +28 -1
- package/dist/workflow/entry.d.ts +3 -3
- package/dist/workflow/host.d.ts +7 -4
- package/dist/workflow/host.js +162 -48
- package/dist/workflow/journal.d.ts +23 -7
- package/dist/workflow/journal.js +80 -23
- package/dist/workflow/progress.d.ts +1 -1
- package/dist/workflow/runtime.d.ts +45 -6
- package/dist/workflow/runtime.js +105 -16
- package/dist/workflow/task.d.ts +13 -4
- package/dist/workflow/task.js +7 -1
- package/dist/workflow/tool-description.d.ts +7 -2
- package/dist/workflow/tool-description.js +10 -5
- package/docs/{FORK.md → DEVELOPMENT.md} +4 -4
- package/docs/artifacts.md +93 -0
- package/docs/rpc.md +252 -189
- package/docs/runtime-performance.md +53 -0
- package/docs/workflows.md +48 -18
- package/examples/agent-tool-description.md +2 -2
- package/examples/workflows/review-panel.js +6 -3
- package/package.json +5 -5
- package/src/active-agents-prompt.ts +115 -39
- package/src/agent-color.ts +10 -2
- package/src/agent-file-toggle.ts +2 -2
- package/src/agent-manager.ts +3312 -1601
- package/src/agent-runner.ts +164 -36
- package/src/agent-types.ts +56 -11
- package/src/awaited-result.ts +187 -0
- package/src/child-session-shutdown.ts +114 -46
- package/src/cleanup-plans.ts +112 -0
- package/src/cross-extension-rpc.ts +68 -9
- package/src/custom-agents.ts +384 -112
- package/src/default-agents.ts +1 -1
- package/src/enabled-models.ts +1 -1
- package/src/env.ts +1 -1
- package/src/error-log.ts +10 -1
- package/src/force-main-model.ts +29 -0
- package/src/goal-bridge.ts +468 -0
- package/src/group-join.ts +56 -9
- package/src/index.ts +2987 -349
- package/src/invocation-config.ts +50 -4
- package/src/memory.ts +1 -1
- package/src/mention-clone.ts +3 -3
- package/src/model-scope.ts +1 -1
- package/src/nested-tools.ts +164 -33
- package/src/output-file.ts +168 -46
- package/src/prompts.ts +1 -1
- package/src/recovery.ts +2 -2
- package/src/report-cleanup.ts +2044 -0
- package/src/report-store.ts +4130 -0
- package/src/schedule-store.ts +244 -201
- package/src/schedule.ts +144 -80
- package/src/settings.ts +61 -16
- package/src/skill-loader.ts +1 -1
- package/src/standalone-fallback.ts +2 -2
- package/src/status-note.ts +1 -1
- package/src/structured-output.ts +1 -1
- package/src/types.ts +33 -3
- package/src/ui/agent-mention.ts +3 -3
- package/src/ui/agent-widget.ts +179 -45
- package/src/ui/cleanup-preview.ts +518 -0
- package/src/ui/conversation-viewer.ts +19 -15
- package/src/ui/fleet-list.ts +7 -7
- package/src/ui/fleet-overlay.ts +1048 -847
- package/src/ui/hub-feed.ts +179 -0
- package/src/ui/native-transcript.ts +7 -3
- package/src/ui/schedule-menu.ts +4 -4
- package/src/ui/workflow-card.ts +4 -4
- package/src/ui/workflow-dialog.ts +10 -6
- package/src/ui/workflow-menu.ts +4 -4
- package/src/usage.ts +53 -3
- package/src/workflow/collisions.ts +1 -1
- package/src/workflow/entry.ts +3 -3
- package/src/workflow/host.ts +174 -54
- package/src/workflow/journal.ts +80 -23
- package/src/workflow/progress.ts +1 -1
- package/src/workflow/runtime.ts +146 -23
- package/src/workflow/saved.ts +3 -3
- package/src/workflow/task.ts +18 -7
- package/src/workflow/tool-description.ts +10 -5
|
@@ -0,0 +1,4130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* report-store.ts — Durable, plain-data completed reports, per root session.
|
|
3
|
+
*
|
|
4
|
+
* Runtime records are evicted after ten minutes and do not survive a reload.
|
|
5
|
+
* This module keeps the completed report itself — verbatim, with no character
|
|
6
|
+
* cap and no truncation markers — under
|
|
7
|
+
* `<getAgentDir()>/pi-subagents/reports/<rootSessionId>/`, one atomic JSON per
|
|
8
|
+
* agent plus small root metadata, lease and cleanup-lock files. It deliberately
|
|
9
|
+
* keeps no global mutable index and no raw transcript copies.
|
|
10
|
+
*
|
|
11
|
+
* Ownership rules:
|
|
12
|
+
* - an entry carries its root provenance and the same owner ids as the live
|
|
13
|
+
* record (`parentAgentId` / `workflowId`);
|
|
14
|
+
* - `find` is a top-level reader and never surfaces an owned entry as a root
|
|
15
|
+
* report;
|
|
16
|
+
* - `findOwned` is the narrow async reader an owner (the parent or the
|
|
17
|
+
* workflow) uses for its own archived entry;
|
|
18
|
+
* - aliases resolve only inside the bound root; canonical ids resolve across
|
|
19
|
+
* every root, exactly (the 17-character id `randomUUID().slice(0, 17)`
|
|
20
|
+
* produces) — there is intentionally no prefix matcher.
|
|
21
|
+
*
|
|
22
|
+
* Lifetime handshake:
|
|
23
|
+
* - every activation writes a unique `<pid>-<nonce>.json` lease;
|
|
24
|
+
* - cleanup creates an exclusive `cleanup.lock` first and then rechecks
|
|
25
|
+
* foreign leases;
|
|
26
|
+
* - activation checks the lock, writes its lease, rechecks the lock and
|
|
27
|
+
* refuses artifact writes when a lock appeared.
|
|
28
|
+
*
|
|
29
|
+
* Retention:
|
|
30
|
+
* - report bodies/details expire 30 days after `completedAt`; startup/save
|
|
31
|
+
* maintenance replaces them with a minimal ownership stub;
|
|
32
|
+
* - a deletion receipt lives 30 days and blocks re-import from parent history
|
|
33
|
+
* or a leftover transcript;
|
|
34
|
+
* - no read deletes anything and no timer is created here.
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
38
|
+
import {
|
|
39
|
+
createReadStream,
|
|
40
|
+
type Dirent,
|
|
41
|
+
readdirSync,
|
|
42
|
+
readFileSync,
|
|
43
|
+
type Stats,
|
|
44
|
+
} from "node:fs";
|
|
45
|
+
import {
|
|
46
|
+
chmod,
|
|
47
|
+
link,
|
|
48
|
+
lstat,
|
|
49
|
+
mkdir,
|
|
50
|
+
open,
|
|
51
|
+
readdir,
|
|
52
|
+
readFile,
|
|
53
|
+
realpath,
|
|
54
|
+
rename,
|
|
55
|
+
stat,
|
|
56
|
+
unlink,
|
|
57
|
+
writeFile,
|
|
58
|
+
} from "node:fs/promises";
|
|
59
|
+
import { tmpdir } from "node:os";
|
|
60
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
61
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
62
|
+
import { encodeCwd } from "./output-file.ts";
|
|
63
|
+
import type { AgentInvocation, AgentRecord } from "./types.ts";
|
|
64
|
+
import type { LifetimeUsage } from "./usage.ts";
|
|
65
|
+
|
|
66
|
+
/** Custom entry a child session carries to prove pi-subagents owns it. */
|
|
67
|
+
export const SESSION_OWNERSHIP_ENTRY_TYPE = "pi-subagents:ownership";
|
|
68
|
+
|
|
69
|
+
/** One month, in milliseconds. */
|
|
70
|
+
export const REPORT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
|
|
71
|
+
|
|
72
|
+
/** Store format version, written on every entry. */
|
|
73
|
+
export const REPORT_STORE_VERSION = 1;
|
|
74
|
+
|
|
75
|
+
/** Cleanup scope: one root session, or every project/session. */
|
|
76
|
+
export type CleanupScope = "session" | "global";
|
|
77
|
+
|
|
78
|
+
export type TerminalAgentStatus = "completed" | "steered" | "aborted" | "stopped" | "error";
|
|
79
|
+
|
|
80
|
+
const TERMINAL_STATUSES: ReadonlySet<string> = new Set([
|
|
81
|
+
"completed",
|
|
82
|
+
"steered",
|
|
83
|
+
"aborted",
|
|
84
|
+
"stopped",
|
|
85
|
+
"error",
|
|
86
|
+
]);
|
|
87
|
+
|
|
88
|
+
const WORKFLOW_STATUSES: ReadonlySet<string> = new Set([
|
|
89
|
+
"running",
|
|
90
|
+
"completed",
|
|
91
|
+
"failed",
|
|
92
|
+
"killed",
|
|
93
|
+
"paused",
|
|
94
|
+
]);
|
|
95
|
+
|
|
96
|
+
/** Exact canonical agent id: `randomUUID().slice(0, 17)` (`8-4-3`). */
|
|
97
|
+
const CANONICAL_AGENT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{3}$/;
|
|
98
|
+
|
|
99
|
+
/** One safe path component. Rejects separators, traversal and empty names. */
|
|
100
|
+
const SAFE_COMPONENT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
101
|
+
|
|
102
|
+
const RENAME_RETRIES = 5;
|
|
103
|
+
const RENAME_RETRY_MS = 20;
|
|
104
|
+
const SAVE_MAINTENANCE_INTERVAL_MS = 60_000;
|
|
105
|
+
const MAINTENANCE_RETRY_BASE_MS = 5_000;
|
|
106
|
+
const DEFAULT_FLUSH_TIMEOUT_MS = 30_000;
|
|
107
|
+
const DEFAULT_FLUSH_MAX_PASSES = 100;
|
|
108
|
+
const DIAGNOSTIC_READ_CHARS = 8 * 1024;
|
|
109
|
+
|
|
110
|
+
export function isCanonicalAgentId(value: string): boolean {
|
|
111
|
+
return CANONICAL_AGENT_ID.test(value);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function isTerminalAgentStatus(value: string): value is TerminalAgentStatus {
|
|
115
|
+
return TERMINAL_STATUSES.has(value);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function isSafePathComponent(value: string): boolean {
|
|
119
|
+
return SAFE_COMPONENT.test(value) && value !== "." && value !== "..";
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** The root context an activation binds. Plain data only, never an ExtensionContext. */
|
|
123
|
+
export interface ReportContext {
|
|
124
|
+
cwd: string;
|
|
125
|
+
rootSessionId: string;
|
|
126
|
+
rootSessionFile?: string;
|
|
127
|
+
/** false = keep results only in memory/current-parent recovery, write nothing. */
|
|
128
|
+
persistReports?: boolean;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** What a child session writes to prove pi-subagents, not the user, owns it. */
|
|
132
|
+
export interface SessionOwnershipData {
|
|
133
|
+
version: 1;
|
|
134
|
+
agentId: string;
|
|
135
|
+
rootSessionId: string;
|
|
136
|
+
rootCwd: string;
|
|
137
|
+
rootSessionFile?: string;
|
|
138
|
+
childSessionId: string;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* A complete completed report. Every string is verbatim; `toolUses`,
|
|
143
|
+
* `startedAt`, `lifetimeUsage` etc. stay absent when a legacy source never
|
|
144
|
+
* recorded them rather than being invented as zero.
|
|
145
|
+
*/
|
|
146
|
+
export interface ReportSnapshot {
|
|
147
|
+
id: string;
|
|
148
|
+
type: string;
|
|
149
|
+
description: string;
|
|
150
|
+
status: TerminalAgentStatus;
|
|
151
|
+
result?: string;
|
|
152
|
+
error?: string;
|
|
153
|
+
toolUses?: number;
|
|
154
|
+
startedAt?: number;
|
|
155
|
+
completedAt?: number;
|
|
156
|
+
sessionFile?: string;
|
|
157
|
+
sessionId?: string;
|
|
158
|
+
outputFile?: string;
|
|
159
|
+
invocation?: AgentInvocation;
|
|
160
|
+
lifetimeUsage?: LifetimeUsage;
|
|
161
|
+
compactionCount?: number;
|
|
162
|
+
isBackground?: boolean;
|
|
163
|
+
depth?: number;
|
|
164
|
+
handle?: string;
|
|
165
|
+
alias?: string;
|
|
166
|
+
groupId?: string;
|
|
167
|
+
runGeneration?: number;
|
|
168
|
+
structuredJson?: string;
|
|
169
|
+
structuredRetried?: boolean;
|
|
170
|
+
droppedSteers?: number;
|
|
171
|
+
/**
|
|
172
|
+
* Stale diagnostic only, never a read-state source: the runtime flag may have
|
|
173
|
+
* changed after settle. Cleanup derives unread/unknown exclusively from the
|
|
174
|
+
* refreshed live state getter.
|
|
175
|
+
*/
|
|
176
|
+
resultConsumed?: boolean;
|
|
177
|
+
parentAgentId?: string;
|
|
178
|
+
workflowId?: string;
|
|
179
|
+
/** Flat owner set; an entry with any owner is never a top-level report. */
|
|
180
|
+
ownerIds: string[];
|
|
181
|
+
rootSessionId: string;
|
|
182
|
+
rootCwd: string;
|
|
183
|
+
rootSessionFile?: string;
|
|
184
|
+
legacy?: boolean;
|
|
185
|
+
recoveredFrom?: "archive" | "parent-record" | "legacy-output";
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
interface ReportEntryBase {
|
|
189
|
+
version: typeof REPORT_STORE_VERSION;
|
|
190
|
+
id: string;
|
|
191
|
+
/** Bumped on every write; combined with the file hash for cleanup identity. */
|
|
192
|
+
entryGeneration: number;
|
|
193
|
+
createdAt: number;
|
|
194
|
+
updatedAt: number;
|
|
195
|
+
completedAt: number;
|
|
196
|
+
rootSessionId: string;
|
|
197
|
+
rootCwd: string;
|
|
198
|
+
rootSessionFile?: string;
|
|
199
|
+
type: string;
|
|
200
|
+
description: string;
|
|
201
|
+
handle?: string;
|
|
202
|
+
alias?: string;
|
|
203
|
+
parentAgentId?: string;
|
|
204
|
+
workflowId?: string;
|
|
205
|
+
ownerIds: string[];
|
|
206
|
+
sessionFile?: string;
|
|
207
|
+
sessionId?: string;
|
|
208
|
+
outputFile?: string;
|
|
209
|
+
runGeneration?: number;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export interface FullReportEntry extends ReportEntryBase {
|
|
213
|
+
state: "full";
|
|
214
|
+
report: ReportSnapshot;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Body/details expired; only the ownership index survives so cleanup can find it. */
|
|
218
|
+
export interface ExpiredReportEntry extends ReportEntryBase {
|
|
219
|
+
state: "expired";
|
|
220
|
+
expiredAt: number;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Deliberate removal receipt: blocks re-import from parent history/transcripts. */
|
|
224
|
+
export interface DeletedReportEntry extends ReportEntryBase {
|
|
225
|
+
state: "deleted";
|
|
226
|
+
deletedAt: number;
|
|
227
|
+
deletionReason?: string;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export type ReportEntry = FullReportEntry | ExpiredReportEntry | DeletedReportEntry;
|
|
231
|
+
|
|
232
|
+
/** Strict owner context for `findOwned`; parent and workflow namespaces never cross. */
|
|
233
|
+
export interface ReportOwnerContext {
|
|
234
|
+
kind: "parent" | "workflow";
|
|
235
|
+
id: string;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export type ReportLookup =
|
|
239
|
+
| {
|
|
240
|
+
status: "found";
|
|
241
|
+
report: ReportSnapshot;
|
|
242
|
+
entry: ReportEntry;
|
|
243
|
+
rootSessionId: string;
|
|
244
|
+
provenance: "archive" | "parent-record" | "legacy-output";
|
|
245
|
+
}
|
|
246
|
+
| {
|
|
247
|
+
status: "expired";
|
|
248
|
+
entry: ReportEntry;
|
|
249
|
+
rootSessionId: string;
|
|
250
|
+
expiredAt: number;
|
|
251
|
+
reason: string;
|
|
252
|
+
}
|
|
253
|
+
| {
|
|
254
|
+
status: "deleted";
|
|
255
|
+
entry: ReportEntry;
|
|
256
|
+
rootSessionId: string;
|
|
257
|
+
deletedAt: number;
|
|
258
|
+
reason?: string;
|
|
259
|
+
}
|
|
260
|
+
| { status: "missing"; ref: string; reason: string; candidates?: string[] }
|
|
261
|
+
| {
|
|
262
|
+
status: "ambiguous";
|
|
263
|
+
ref: string;
|
|
264
|
+
reason: string;
|
|
265
|
+
candidates: { rootSessionId: string; id: string; alias?: string }[];
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* One combined artifact scope for cleanup admission. Ids and session files are
|
|
270
|
+
* matched in a SINGLE scan; an empty scope matches any live selection, exactly
|
|
271
|
+
* like the legacy no-argument `isCleaning()`.
|
|
272
|
+
*/
|
|
273
|
+
export interface ReportArtifactScope {
|
|
274
|
+
agentId?: string;
|
|
275
|
+
sessionFiles?: readonly string[];
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Status-rich durable entry read. `absent` is only reported when absence is
|
|
280
|
+
* proven; an unreadable/unsafe root or entry is `uncertain` and must be refused
|
|
281
|
+
* by the caller instead of being treated as "no entry".
|
|
282
|
+
*/
|
|
283
|
+
export type ReportEntryState =
|
|
284
|
+
| { status: "verified"; entry: ReportEntry; path: string }
|
|
285
|
+
| { status: "absent" }
|
|
286
|
+
| { status: "uncertain"; reason: string };
|
|
287
|
+
|
|
288
|
+
export type ReportBinding =
|
|
289
|
+
| {
|
|
290
|
+
active: true;
|
|
291
|
+
rootSessionId: string;
|
|
292
|
+
persistence: boolean;
|
|
293
|
+
leaseId?: string;
|
|
294
|
+
reason?: undefined;
|
|
295
|
+
}
|
|
296
|
+
| {
|
|
297
|
+
active: false;
|
|
298
|
+
rootSessionId?: string;
|
|
299
|
+
persistence: false;
|
|
300
|
+
reason: string;
|
|
301
|
+
leaseId?: undefined;
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
export type ReportSaveResult =
|
|
305
|
+
| { saved: true; path: string; entry: ReportEntry | WorkflowArtifactEntry }
|
|
306
|
+
| { saved: false; reason: string };
|
|
307
|
+
|
|
308
|
+
export interface ReportFlushOptions {
|
|
309
|
+
/** Total wall-clock budget across every pass, including newly accepted writes. */
|
|
310
|
+
timeoutMs?: number;
|
|
311
|
+
/** Maximum snapshots of the ordered write chains to await. */
|
|
312
|
+
maxPasses?: number;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
export type ReportFlushResult =
|
|
316
|
+
| { status: "flushed"; pendingChains: 0; passes: number }
|
|
317
|
+
| {
|
|
318
|
+
status: "incomplete";
|
|
319
|
+
reason: "timeout" | "max-passes";
|
|
320
|
+
pendingChains: number;
|
|
321
|
+
passes: number;
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
export type WorkflowRunStatus = "running" | "completed" | "failed" | "killed" | "paused";
|
|
325
|
+
|
|
326
|
+
/** Registered independently of agents, so zero-agent workflows are still owned. */
|
|
327
|
+
export interface WorkflowArtifactRegistration {
|
|
328
|
+
id: string;
|
|
329
|
+
/** Exact generated inline copies/journals; always the copy, never the source. */
|
|
330
|
+
generatedPaths: readonly string[];
|
|
331
|
+
/** External/saved source paths; recorded for provenance and never deleted. */
|
|
332
|
+
externalPaths?: readonly string[];
|
|
333
|
+
status: WorkflowRunStatus;
|
|
334
|
+
startedAt: number;
|
|
335
|
+
completedAt?: number;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
export interface WorkflowArtifactEntry extends WorkflowArtifactRegistration {
|
|
339
|
+
version: typeof REPORT_STORE_VERSION;
|
|
340
|
+
rootSessionId: string;
|
|
341
|
+
rootCwd: string;
|
|
342
|
+
rootSessionFile?: string;
|
|
343
|
+
updatedAt: number;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export interface ReportLease {
|
|
347
|
+
version: typeof REPORT_STORE_VERSION;
|
|
348
|
+
pid: number;
|
|
349
|
+
nonce: string;
|
|
350
|
+
rootSessionId: string;
|
|
351
|
+
/** Plain bind identity: the main/root session path this activation owns. */
|
|
352
|
+
rootSessionFile?: string;
|
|
353
|
+
rootCwd?: string;
|
|
354
|
+
createdAt: number;
|
|
355
|
+
updatedAt: number;
|
|
356
|
+
own: boolean;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Shared cleanup-lock liveness. Corrupt/unreadable is never "stale". */
|
|
360
|
+
export type CleanupLockStatus = "absent" | "live" | "dead" | "uncertain";
|
|
361
|
+
|
|
362
|
+
export interface CleanupLockRead {
|
|
363
|
+
status: CleanupLockStatus;
|
|
364
|
+
lock?: CleanupLockData;
|
|
365
|
+
raw?: string;
|
|
366
|
+
reason?: string;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export interface CleanupLockOptions {
|
|
370
|
+
/**
|
|
371
|
+
* Legacy-only roots may not have a managed folder yet. The caller must have
|
|
372
|
+
* explicit legacy confirmation; this creates only the control namespace.
|
|
373
|
+
*/
|
|
374
|
+
createRoot?: boolean;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
export interface CleanupSelection {
|
|
378
|
+
scope: CleanupScope;
|
|
379
|
+
agentIds: readonly string[];
|
|
380
|
+
sessionFiles: readonly string[];
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export interface CleanupLockData extends CleanupSelection {
|
|
384
|
+
version: typeof REPORT_STORE_VERSION;
|
|
385
|
+
pid: number;
|
|
386
|
+
nonce: string;
|
|
387
|
+
rootSessionId: string;
|
|
388
|
+
createdAt: number;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
export interface CleanupLockHandle {
|
|
392
|
+
rootSessionId: string;
|
|
393
|
+
nonce: string;
|
|
394
|
+
selection: CleanupSelection;
|
|
395
|
+
acquiredAt: number;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
export interface ReportRootState {
|
|
399
|
+
rootSessionId: string;
|
|
400
|
+
rootDir: string;
|
|
401
|
+
rootCwd?: string;
|
|
402
|
+
rootSessionFile?: string;
|
|
403
|
+
generation: number;
|
|
404
|
+
metadataPresent: boolean;
|
|
405
|
+
reportEntries: ReportEntry[];
|
|
406
|
+
workflows: WorkflowArtifactEntry[];
|
|
407
|
+
leases: ReportLease[];
|
|
408
|
+
/** Present only for a parsed, valid lock; `cleanupLockState` is authoritative. */
|
|
409
|
+
cleanupLock?: CleanupLockData;
|
|
410
|
+
cleanupLockState: CleanupLockStatus;
|
|
411
|
+
cleanupLockReason?: string;
|
|
412
|
+
/** Why lease metadata could not be fully trusted (fail closed). */
|
|
413
|
+
leasesUncertain?: string;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Strict global identity inventory for cleanup protection. Unlike `list`, a
|
|
418
|
+
* partial read is reported as uncertainty instead of shrinking to an empty or
|
|
419
|
+
* shorter result: every root's main-session identity must be proven.
|
|
420
|
+
*/
|
|
421
|
+
export interface ReportIdentityScan {
|
|
422
|
+
states: ReportRootState[];
|
|
423
|
+
uncertainty?: string;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
export interface ReportStorage {
|
|
427
|
+
agentDir: string;
|
|
428
|
+
reportsRoot: string;
|
|
429
|
+
tempRoot: string;
|
|
430
|
+
sessionRoots: readonly string[];
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
export interface ReportStoreOptions {
|
|
434
|
+
/** Injected root for fixtures; defaults to `getAgentDir()` at call time. */
|
|
435
|
+
agentDir?: string;
|
|
436
|
+
/** Injected OS-temp root for `.output`/workflow ownership validation. */
|
|
437
|
+
tempRoot?: string;
|
|
438
|
+
/** Bounded pi session roots scanned only for legacy parent-record proof. */
|
|
439
|
+
sessionRoots?: readonly string[];
|
|
440
|
+
now?: () => number;
|
|
441
|
+
nonce?: () => string;
|
|
442
|
+
retentionMs?: number;
|
|
443
|
+
pidAlive?: (pid: number) => boolean;
|
|
444
|
+
diagnostics?: (message: string) => void;
|
|
445
|
+
/**
|
|
446
|
+
* Narrow deterministic interleaving seam for maintenance tests and callers that
|
|
447
|
+
* need an explicit checkpoint. Not a general observer: it only reports the
|
|
448
|
+
* shared lock acquisition and the pre-rewrite entry read.
|
|
449
|
+
*/
|
|
450
|
+
maintenanceHook?: (event: MaintenanceEvent) => void | Promise<void>;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
export interface MaintenanceEvent {
|
|
454
|
+
phase: "locked" | "entry-read";
|
|
455
|
+
rootSessionId: string;
|
|
456
|
+
agentId?: string;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
export interface FileIdentity {
|
|
460
|
+
path: string;
|
|
461
|
+
size: number;
|
|
462
|
+
mtimeMs: number;
|
|
463
|
+
fingerprint: string;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
export type FileInspection =
|
|
467
|
+
| { ok: true; identity: FileIdentity }
|
|
468
|
+
| { ok: false; reason: string };
|
|
469
|
+
|
|
470
|
+
export interface DeletionReceiptRequest {
|
|
471
|
+
deletedAt?: number;
|
|
472
|
+
reason?: string;
|
|
473
|
+
expectedEntryGeneration?: number;
|
|
474
|
+
/** Final authorization immediately before publication; a throw refuses the write. */
|
|
475
|
+
beforeCommit?: () => Promise<void>;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
export interface DeletionReceiptResult {
|
|
479
|
+
entry: DeletedReportEntry;
|
|
480
|
+
rootGeneration: number;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
export interface LegacyOutputInspection {
|
|
484
|
+
path: string;
|
|
485
|
+
agentId: string;
|
|
486
|
+
verified: boolean;
|
|
487
|
+
reason?: string;
|
|
488
|
+
snapshot?: ReportSnapshot;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
export class ReportUnavailableError extends Error {
|
|
492
|
+
readonly reason: string;
|
|
493
|
+
|
|
494
|
+
constructor(reason: string) {
|
|
495
|
+
super(`report store unavailable: ${reason}`);
|
|
496
|
+
this.name = "ReportUnavailableError";
|
|
497
|
+
this.reason = reason;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
type JsonRecord = Record<string, unknown>;
|
|
502
|
+
|
|
503
|
+
function isRecord(value: unknown): value is JsonRecord {
|
|
504
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
function stringField(record: JsonRecord, key: string): string | undefined {
|
|
508
|
+
const value = record[key];
|
|
509
|
+
return typeof value === "string" ? value : undefined;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function numberField(record: JsonRecord, key: string): number | undefined {
|
|
513
|
+
const value = record[key];
|
|
514
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function stringArray(value: unknown): string[] | undefined {
|
|
518
|
+
if (!Array.isArray(value)) return undefined;
|
|
519
|
+
const strings = value.filter((item): item is string => typeof item === "string");
|
|
520
|
+
return strings.length === value.length ? [...strings] : undefined;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function errorCode(error: unknown): string | undefined {
|
|
524
|
+
if (!isRecord(error)) return undefined;
|
|
525
|
+
return stringField(error, "code");
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function isNotFound(error: unknown): boolean {
|
|
529
|
+
return errorCode(error) === "ENOENT";
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
function pathKey(path: string): string {
|
|
533
|
+
const resolved = resolve(path);
|
|
534
|
+
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* Same-process reapers of one lock serialize here; cross-process exclusion uses
|
|
539
|
+
* the unique intent files below. This keeps exactly one local winner without
|
|
540
|
+
* weakening the fail-closed cross-process protocol.
|
|
541
|
+
*/
|
|
542
|
+
const processRecoveryChains = new Map<string, Promise<unknown>>();
|
|
543
|
+
const RECOVERY_INTENT_PREFIX = "cleanup.lock.intent-";
|
|
544
|
+
|
|
545
|
+
function withProcessRecoveryLock<T>(key: string, run: () => Promise<T>): Promise<T> {
|
|
546
|
+
const previous = processRecoveryChains.get(key) ?? Promise.resolve();
|
|
547
|
+
const next = previous.then(run, run);
|
|
548
|
+
const tracked = next.then(
|
|
549
|
+
() => undefined,
|
|
550
|
+
() => undefined,
|
|
551
|
+
);
|
|
552
|
+
processRecoveryChains.set(key, tracked);
|
|
553
|
+
void tracked.then(() => {
|
|
554
|
+
if (processRecoveryChains.get(key) === tracked) processRecoveryChains.delete(key);
|
|
555
|
+
});
|
|
556
|
+
return next;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
export function normalizeReportPath(path: string): string {
|
|
560
|
+
return pathKey(path);
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
export function isPathWithin(child: string, parent: string): boolean {
|
|
564
|
+
const rel = relative(resolve(parent), resolve(child));
|
|
565
|
+
return rel.length > 0 && !rel.startsWith("..") && !isAbsolute(rel);
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
function ownerIdsOf(record: {
|
|
569
|
+
parentAgentId?: string;
|
|
570
|
+
workflowId?: string;
|
|
571
|
+
}): string[] {
|
|
572
|
+
const owners: string[] = [];
|
|
573
|
+
if (record.parentAgentId) owners.push(record.parentAgentId);
|
|
574
|
+
if (record.workflowId) owners.push(record.workflowId);
|
|
575
|
+
return owners;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* The integrator adds `AgentRecord.ownerIds` at spawn: the whole ancestor chain,
|
|
580
|
+
* so an archived descendant stays owner-readable after an intermediate parent
|
|
581
|
+
* record is evicted. Older records have no such field — only then is the
|
|
582
|
+
* immediate parent/workflow id a safe fallback.
|
|
583
|
+
*/
|
|
584
|
+
function recordOwnerIds(record: AgentRecord): string[] {
|
|
585
|
+
if (record.ownerIds !== undefined) {
|
|
586
|
+
const ids = record.ownerIds.filter(
|
|
587
|
+
(item): item is string => typeof item === "string" && item.length > 0,
|
|
588
|
+
);
|
|
589
|
+
return [...new Set(ids)];
|
|
590
|
+
}
|
|
591
|
+
return ownerIdsOf(record);
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/** A top-level archive entry has no owner at all; ownerIds alone is not enough. */
|
|
595
|
+
function isUnownedEntry(entry: ReportEntry): boolean {
|
|
596
|
+
return (
|
|
597
|
+
entry.ownerIds.length === 0 &&
|
|
598
|
+
entry.parentAgentId === undefined &&
|
|
599
|
+
entry.workflowId === undefined
|
|
600
|
+
);
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
function cloneInvocation(invocation: AgentInvocation | undefined): AgentInvocation | undefined {
|
|
604
|
+
if (!invocation) return undefined;
|
|
605
|
+
return { ...invocation };
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
function cloneUsage(usage: LifetimeUsage | undefined): LifetimeUsage | undefined {
|
|
609
|
+
if (!usage) return undefined;
|
|
610
|
+
return {
|
|
611
|
+
input: usage.input,
|
|
612
|
+
output: usage.output,
|
|
613
|
+
cacheWrite: usage.cacheWrite,
|
|
614
|
+
...(usage.cacheRead === undefined ? {} : { cacheRead: usage.cacheRead }),
|
|
615
|
+
...(usage.cost === undefined ? {} : { cost: usage.cost }),
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* Capture every field synchronously, before any await. The caller may mutate
|
|
621
|
+
* the live record (or its session) immediately after the snapshot call.
|
|
622
|
+
*/
|
|
623
|
+
export function captureReportSnapshot(
|
|
624
|
+
record: AgentRecord,
|
|
625
|
+
context: ReportContext,
|
|
626
|
+
now: number,
|
|
627
|
+
): ReportSnapshot | undefined {
|
|
628
|
+
if (!isTerminalAgentStatus(record.status)) return undefined;
|
|
629
|
+
if (!isCanonicalAgentId(record.id)) return undefined;
|
|
630
|
+
const completedAt = record.completedAt ?? now;
|
|
631
|
+
const ownerIds = recordOwnerIds(record);
|
|
632
|
+
const sessionId = record.sessionId ?? record.session?.sessionId;
|
|
633
|
+
return {
|
|
634
|
+
id: record.id,
|
|
635
|
+
type: record.type,
|
|
636
|
+
description: record.description,
|
|
637
|
+
status: record.status,
|
|
638
|
+
...(record.result === undefined ? {} : { result: record.result }),
|
|
639
|
+
...(record.error === undefined ? {} : { error: record.error }),
|
|
640
|
+
toolUses: record.toolUses,
|
|
641
|
+
startedAt: record.startedAt,
|
|
642
|
+
completedAt,
|
|
643
|
+
...(record.sessionFile === undefined ? {} : { sessionFile: record.sessionFile }),
|
|
644
|
+
// Captured as a plain string; prefer the stable record field when present.
|
|
645
|
+
...(sessionId === undefined ? {} : { sessionId }),
|
|
646
|
+
...(record.outputFile === undefined ? {} : { outputFile: record.outputFile }),
|
|
647
|
+
...(record.invocation === undefined ? {} : { invocation: cloneInvocation(record.invocation) }),
|
|
648
|
+
...(record.lifetimeUsage === undefined ? {} : { lifetimeUsage: cloneUsage(record.lifetimeUsage) }),
|
|
649
|
+
compactionCount: record.compactionCount,
|
|
650
|
+
...(record.isBackground === undefined ? {} : { isBackground: record.isBackground }),
|
|
651
|
+
...(record.depth === undefined ? {} : { depth: record.depth }),
|
|
652
|
+
...(record.handle === undefined ? {} : { handle: record.handle }),
|
|
653
|
+
...(record.alias === undefined ? {} : { alias: record.alias }),
|
|
654
|
+
...(record.groupId === undefined ? {} : { groupId: record.groupId }),
|
|
655
|
+
...(record.runGeneration === undefined ? {} : { runGeneration: record.runGeneration }),
|
|
656
|
+
...(record.structuredJson === undefined ? {} : { structuredJson: record.structuredJson }),
|
|
657
|
+
...(record.structuredRetried === undefined ? {} : { structuredRetried: record.structuredRetried }),
|
|
658
|
+
...(record.droppedSteers === undefined ? {} : { droppedSteers: record.droppedSteers }),
|
|
659
|
+
...(record.resultConsumed === undefined ? {} : { resultConsumed: record.resultConsumed }),
|
|
660
|
+
...(record.parentAgentId === undefined ? {} : { parentAgentId: record.parentAgentId }),
|
|
661
|
+
...(record.workflowId === undefined ? {} : { workflowId: record.workflowId }),
|
|
662
|
+
ownerIds,
|
|
663
|
+
rootSessionId: context.rootSessionId,
|
|
664
|
+
rootCwd: context.cwd,
|
|
665
|
+
...(context.rootSessionFile === undefined ? {} : { rootSessionFile: context.rootSessionFile }),
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
class NotFoundError extends Error {
|
|
670
|
+
constructor() {
|
|
671
|
+
super("not found");
|
|
672
|
+
this.name = "NotFoundError";
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
/** Rename with a bounded retry; Windows AV/indexers hold fresh files briefly. */
|
|
677
|
+
async function renameWithRetry(
|
|
678
|
+
from: string,
|
|
679
|
+
to: string,
|
|
680
|
+
beforeCommit?: () => Promise<void>,
|
|
681
|
+
): Promise<void> {
|
|
682
|
+
for (let attempt = 0; ; attempt++) {
|
|
683
|
+
// Re-run the final authorization on every attempt so a late refusal still
|
|
684
|
+
// wins before the destination is published.
|
|
685
|
+
if (beforeCommit !== undefined) await beforeCommit();
|
|
686
|
+
try {
|
|
687
|
+
await rename(from, to);
|
|
688
|
+
return;
|
|
689
|
+
} catch (error) {
|
|
690
|
+
const code = errorCode(error);
|
|
691
|
+
const transient = code === "EPERM" || code === "EBUSY" || code === "EACCES";
|
|
692
|
+
if (!transient || attempt >= RENAME_RETRIES) {
|
|
693
|
+
try {
|
|
694
|
+
await unlink(from);
|
|
695
|
+
} catch (unlinkError) {
|
|
696
|
+
if (!isNotFound(unlinkError)) {
|
|
697
|
+
throw unlinkError;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
throw error;
|
|
701
|
+
}
|
|
702
|
+
await new Promise((done) => setTimeout(done, RENAME_RETRY_MS * (attempt + 1)));
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
async function chmodPrivate(path: string, mode: number): Promise<void> {
|
|
708
|
+
try {
|
|
709
|
+
await chmod(path, mode);
|
|
710
|
+
} catch (error) {
|
|
711
|
+
// Windows reports EPERM on some filesystems; there chmod is a no-op anyway.
|
|
712
|
+
if (process.platform !== "win32") throw error;
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
async function atomicWriteJson(
|
|
717
|
+
path: string,
|
|
718
|
+
value: unknown,
|
|
719
|
+
nonce: string,
|
|
720
|
+
beforeCommit?: () => Promise<void>,
|
|
721
|
+
): Promise<void> {
|
|
722
|
+
const dir = dirname(path);
|
|
723
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
724
|
+
await chmodPrivate(dir, 0o700);
|
|
725
|
+
const tmp = `${path}.${process.pid}.${nonce}.tmp`;
|
|
726
|
+
try {
|
|
727
|
+
await writeFile(tmp, JSON.stringify(value), { encoding: "utf8", mode: 0o600 });
|
|
728
|
+
await chmodPrivate(tmp, 0o600);
|
|
729
|
+
await renameWithRetry(tmp, path, beforeCommit);
|
|
730
|
+
await chmodPrivate(path, 0o600);
|
|
731
|
+
} catch (error) {
|
|
732
|
+
try {
|
|
733
|
+
await unlink(tmp);
|
|
734
|
+
} catch (unlinkError) {
|
|
735
|
+
if (!isNotFound(unlinkError)) throw unlinkError;
|
|
736
|
+
}
|
|
737
|
+
throw error;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
async function readFirstLine(path: string): Promise<string | undefined> {
|
|
742
|
+
const handle = await open(path, "r");
|
|
743
|
+
try {
|
|
744
|
+
const chunks: Buffer[] = [];
|
|
745
|
+
const buffer = Buffer.alloc(DIAGNOSTIC_READ_CHARS);
|
|
746
|
+
let position = 0;
|
|
747
|
+
for (;;) {
|
|
748
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, position);
|
|
749
|
+
if (bytesRead === 0) break;
|
|
750
|
+
const chunk = Buffer.from(buffer.subarray(0, bytesRead));
|
|
751
|
+
const newline = chunk.indexOf(0x0a);
|
|
752
|
+
if (newline >= 0) {
|
|
753
|
+
chunks.push(chunk.subarray(0, newline));
|
|
754
|
+
break;
|
|
755
|
+
}
|
|
756
|
+
chunks.push(chunk);
|
|
757
|
+
position += bytesRead;
|
|
758
|
+
}
|
|
759
|
+
if (chunks.length === 0) return undefined;
|
|
760
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
761
|
+
} finally {
|
|
762
|
+
await handle.close();
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* Full SHA-256 with bounded memory. `readFile` fails on files above Node's
|
|
768
|
+
* ~2 GiB buffer limit and spikes memory on large transcripts; streaming keeps
|
|
769
|
+
* the same complete-file fingerprint without either failure mode.
|
|
770
|
+
*/
|
|
771
|
+
async function hashFile(path: string): Promise<string> {
|
|
772
|
+
const hash = createHash("sha256");
|
|
773
|
+
const stream = createReadStream(path);
|
|
774
|
+
try {
|
|
775
|
+
for await (const chunk of stream) {
|
|
776
|
+
if (typeof chunk === "string") hash.update(chunk, "utf8");
|
|
777
|
+
else hash.update(chunk);
|
|
778
|
+
}
|
|
779
|
+
} catch (error) {
|
|
780
|
+
stream.destroy();
|
|
781
|
+
throw error;
|
|
782
|
+
}
|
|
783
|
+
return hash.digest("hex");
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/**
|
|
787
|
+
* Inspect one regular file below an allowed root. Every ancestor below the root
|
|
788
|
+
* is lstat-checked, so a symlinked/junctioned ancestor or file is refused even
|
|
789
|
+
* when the final `stat` would follow it. The root itself may be a symlink (macOS
|
|
790
|
+
* temp lives under `/var`); its real path is the boundary.
|
|
791
|
+
*/
|
|
792
|
+
export async function inspectRegularFile(
|
|
793
|
+
path: string,
|
|
794
|
+
allowedRoots: readonly string[],
|
|
795
|
+
): Promise<FileInspection> {
|
|
796
|
+
if (!isAbsolute(path)) return { ok: false, reason: "path-not-absolute" };
|
|
797
|
+
const target = resolve(path);
|
|
798
|
+
let matchedRoot: string | undefined;
|
|
799
|
+
for (const root of allowedRoots) {
|
|
800
|
+
const lexicalRoot = resolve(root);
|
|
801
|
+
try {
|
|
802
|
+
const realRoot = await realpath(lexicalRoot);
|
|
803
|
+
if (isPathWithin(target, lexicalRoot)) {
|
|
804
|
+
matchedRoot = lexicalRoot;
|
|
805
|
+
break;
|
|
806
|
+
}
|
|
807
|
+
if (isPathWithin(target, realRoot)) {
|
|
808
|
+
matchedRoot = realRoot;
|
|
809
|
+
break;
|
|
810
|
+
}
|
|
811
|
+
} catch (error) {
|
|
812
|
+
if (isNotFound(error)) continue;
|
|
813
|
+
return { ok: false, reason: `root-unreadable:${errorCode(error) ?? "unknown"}` };
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
if (!matchedRoot) return { ok: false, reason: "path-outside-allowed-roots" };
|
|
817
|
+
|
|
818
|
+
const rel = relative(matchedRoot, target);
|
|
819
|
+
const segments = rel.split(/[\\/]+/).filter((segment) => segment.length > 0);
|
|
820
|
+
if (segments.length === 0) return { ok: false, reason: "path-is-root" };
|
|
821
|
+
let current = matchedRoot;
|
|
822
|
+
for (let index = 0; index < segments.length; index++) {
|
|
823
|
+
current = join(current, segments[index]);
|
|
824
|
+
let info: Stats;
|
|
825
|
+
try {
|
|
826
|
+
info = await lstat(current);
|
|
827
|
+
} catch (error) {
|
|
828
|
+
if (isNotFound(error)) return { ok: false, reason: "already-missing" };
|
|
829
|
+
return { ok: false, reason: `inspect-failed:${errorCode(error) ?? "unknown"}` };
|
|
830
|
+
}
|
|
831
|
+
if (info.isSymbolicLink()) return { ok: false, reason: "symlink-or-junction" };
|
|
832
|
+
if (index < segments.length - 1 && !info.isDirectory()) {
|
|
833
|
+
return { ok: false, reason: "ancestor-not-directory" };
|
|
834
|
+
}
|
|
835
|
+
if (index === segments.length - 1 && !info.isFile()) {
|
|
836
|
+
return { ok: false, reason: "not-a-regular-file" };
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
let size: number;
|
|
840
|
+
let mtimeMs: number;
|
|
841
|
+
try {
|
|
842
|
+
const info = await stat(target);
|
|
843
|
+
size = info.size;
|
|
844
|
+
mtimeMs = info.mtimeMs;
|
|
845
|
+
} catch (error) {
|
|
846
|
+
if (isNotFound(error)) return { ok: false, reason: "already-missing" };
|
|
847
|
+
return { ok: false, reason: `stat-failed:${errorCode(error) ?? "unknown"}` };
|
|
848
|
+
}
|
|
849
|
+
let fingerprint: string;
|
|
850
|
+
try {
|
|
851
|
+
fingerprint = await hashFile(target);
|
|
852
|
+
} catch (error) {
|
|
853
|
+
return { ok: false, reason: `hash-failed:${errorCode(error) ?? "unknown"}` };
|
|
854
|
+
}
|
|
855
|
+
return { ok: true, identity: { path: target, size, mtimeMs, fingerprint } };
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
function defaultPidAlive(pid: number): boolean {
|
|
859
|
+
try {
|
|
860
|
+
process.kill(pid, 0);
|
|
861
|
+
return true;
|
|
862
|
+
} catch (error) {
|
|
863
|
+
return errorCode(error) !== "ESRCH";
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
function parseReportSnapshot(value: unknown, id: string): ReportSnapshot | undefined {
|
|
868
|
+
if (!isRecord(value)) return undefined;
|
|
869
|
+
if (stringField(value, "id") !== id) return undefined;
|
|
870
|
+
const status = stringField(value, "status");
|
|
871
|
+
if (!status || !isTerminalAgentStatus(status)) return undefined;
|
|
872
|
+
return value as unknown as ReportSnapshot;
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
function parseReportEntry(value: unknown): ReportEntry | undefined {
|
|
876
|
+
if (!isRecord(value)) return undefined;
|
|
877
|
+
if (numberField(value, "version") !== REPORT_STORE_VERSION) return undefined;
|
|
878
|
+
const id = stringField(value, "id");
|
|
879
|
+
const state = stringField(value, "state");
|
|
880
|
+
const rootSessionId = stringField(value, "rootSessionId");
|
|
881
|
+
const rootCwd = stringField(value, "rootCwd");
|
|
882
|
+
const type = stringField(value, "type");
|
|
883
|
+
const description = stringField(value, "description");
|
|
884
|
+
const completedAt = numberField(value, "completedAt");
|
|
885
|
+
const createdAt = numberField(value, "createdAt");
|
|
886
|
+
const updatedAt = numberField(value, "updatedAt");
|
|
887
|
+
if (
|
|
888
|
+
!id ||
|
|
889
|
+
!isCanonicalAgentId(id) ||
|
|
890
|
+
!state ||
|
|
891
|
+
!rootSessionId ||
|
|
892
|
+
!rootCwd ||
|
|
893
|
+
type === undefined ||
|
|
894
|
+
description === undefined ||
|
|
895
|
+
completedAt === undefined ||
|
|
896
|
+
createdAt === undefined ||
|
|
897
|
+
updatedAt === undefined
|
|
898
|
+
) {
|
|
899
|
+
return undefined;
|
|
900
|
+
}
|
|
901
|
+
const ownerIds = stringArray(value.ownerIds) ?? ownerIdsOf({
|
|
902
|
+
parentAgentId: stringField(value, "parentAgentId"),
|
|
903
|
+
workflowId: stringField(value, "workflowId"),
|
|
904
|
+
});
|
|
905
|
+
const base = {
|
|
906
|
+
version: REPORT_STORE_VERSION,
|
|
907
|
+
id,
|
|
908
|
+
entryGeneration: numberField(value, "entryGeneration") ?? 0,
|
|
909
|
+
createdAt,
|
|
910
|
+
updatedAt,
|
|
911
|
+
completedAt,
|
|
912
|
+
rootSessionId,
|
|
913
|
+
rootCwd,
|
|
914
|
+
...(stringField(value, "rootSessionFile") === undefined
|
|
915
|
+
? {}
|
|
916
|
+
: { rootSessionFile: stringField(value, "rootSessionFile") }),
|
|
917
|
+
type,
|
|
918
|
+
description,
|
|
919
|
+
...(stringField(value, "handle") === undefined ? {} : { handle: stringField(value, "handle") }),
|
|
920
|
+
...(stringField(value, "alias") === undefined ? {} : { alias: stringField(value, "alias") }),
|
|
921
|
+
...(stringField(value, "parentAgentId") === undefined
|
|
922
|
+
? {}
|
|
923
|
+
: { parentAgentId: stringField(value, "parentAgentId") }),
|
|
924
|
+
...(stringField(value, "workflowId") === undefined
|
|
925
|
+
? {}
|
|
926
|
+
: { workflowId: stringField(value, "workflowId") }),
|
|
927
|
+
ownerIds,
|
|
928
|
+
...(stringField(value, "sessionFile") === undefined
|
|
929
|
+
? {}
|
|
930
|
+
: { sessionFile: stringField(value, "sessionFile") }),
|
|
931
|
+
...(stringField(value, "sessionId") === undefined
|
|
932
|
+
? {}
|
|
933
|
+
: { sessionId: stringField(value, "sessionId") }),
|
|
934
|
+
...(stringField(value, "outputFile") === undefined
|
|
935
|
+
? {}
|
|
936
|
+
: { outputFile: stringField(value, "outputFile") }),
|
|
937
|
+
...(numberField(value, "runGeneration") === undefined
|
|
938
|
+
? {}
|
|
939
|
+
: { runGeneration: numberField(value, "runGeneration") }),
|
|
940
|
+
} satisfies ReportEntryBase;
|
|
941
|
+
|
|
942
|
+
if (state === "full") {
|
|
943
|
+
const report = parseReportSnapshot(value.report, id);
|
|
944
|
+
if (!report) return undefined;
|
|
945
|
+
return { ...base, state: "full", report };
|
|
946
|
+
}
|
|
947
|
+
if (state === "expired") {
|
|
948
|
+
const expiredAt = numberField(value, "expiredAt");
|
|
949
|
+
if (expiredAt === undefined) return undefined;
|
|
950
|
+
return { ...base, state: "expired", expiredAt };
|
|
951
|
+
}
|
|
952
|
+
if (state === "deleted") {
|
|
953
|
+
const deletedAt = numberField(value, "deletedAt");
|
|
954
|
+
if (deletedAt === undefined) return undefined;
|
|
955
|
+
return {
|
|
956
|
+
...base,
|
|
957
|
+
state: "deleted",
|
|
958
|
+
deletedAt,
|
|
959
|
+
...(stringField(value, "deletionReason") === undefined
|
|
960
|
+
? {}
|
|
961
|
+
: { deletionReason: stringField(value, "deletionReason") }),
|
|
962
|
+
};
|
|
963
|
+
}
|
|
964
|
+
return undefined;
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
function parseWorkflowEntry(value: unknown): WorkflowArtifactEntry | undefined {
|
|
968
|
+
if (!isRecord(value)) return undefined;
|
|
969
|
+
if (numberField(value, "version") !== REPORT_STORE_VERSION) return undefined;
|
|
970
|
+
const id = stringField(value, "id");
|
|
971
|
+
const status = stringField(value, "status");
|
|
972
|
+
const rootSessionId = stringField(value, "rootSessionId");
|
|
973
|
+
const rootCwd = stringField(value, "rootCwd");
|
|
974
|
+
const startedAt = numberField(value, "startedAt");
|
|
975
|
+
const updatedAt = numberField(value, "updatedAt");
|
|
976
|
+
const generatedPaths = stringArray(value.generatedPaths);
|
|
977
|
+
const externalPaths = stringArray(value.externalPaths) ?? [];
|
|
978
|
+
if (
|
|
979
|
+
!id ||
|
|
980
|
+
!isSafePathComponent(id) ||
|
|
981
|
+
!status ||
|
|
982
|
+
!WORKFLOW_STATUSES.has(status) ||
|
|
983
|
+
!rootSessionId ||
|
|
984
|
+
!rootCwd ||
|
|
985
|
+
startedAt === undefined ||
|
|
986
|
+
updatedAt === undefined ||
|
|
987
|
+
!generatedPaths
|
|
988
|
+
) {
|
|
989
|
+
return undefined;
|
|
990
|
+
}
|
|
991
|
+
return {
|
|
992
|
+
version: REPORT_STORE_VERSION,
|
|
993
|
+
id,
|
|
994
|
+
generatedPaths,
|
|
995
|
+
externalPaths,
|
|
996
|
+
status: status as WorkflowRunStatus,
|
|
997
|
+
startedAt,
|
|
998
|
+
...(numberField(value, "completedAt") === undefined
|
|
999
|
+
? {}
|
|
1000
|
+
: { completedAt: numberField(value, "completedAt") }),
|
|
1001
|
+
rootSessionId,
|
|
1002
|
+
rootCwd,
|
|
1003
|
+
...(stringField(value, "rootSessionFile") === undefined
|
|
1004
|
+
? {}
|
|
1005
|
+
: { rootSessionFile: stringField(value, "rootSessionFile") }),
|
|
1006
|
+
updatedAt,
|
|
1007
|
+
};
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
interface RootMetadata {
|
|
1011
|
+
version: typeof REPORT_STORE_VERSION;
|
|
1012
|
+
rootSessionId: string;
|
|
1013
|
+
rootCwd: string;
|
|
1014
|
+
rootSessionFile?: string;
|
|
1015
|
+
createdAt: number;
|
|
1016
|
+
updatedAt: number;
|
|
1017
|
+
generation: number;
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
function parseRootMetadata(value: unknown, rootSessionId: string): RootMetadata | undefined {
|
|
1021
|
+
if (!isRecord(value)) return undefined;
|
|
1022
|
+
if (numberField(value, "version") !== REPORT_STORE_VERSION) return undefined;
|
|
1023
|
+
if (stringField(value, "rootSessionId") !== rootSessionId) return undefined;
|
|
1024
|
+
const rootCwd = stringField(value, "rootCwd");
|
|
1025
|
+
const createdAt = numberField(value, "createdAt");
|
|
1026
|
+
const updatedAt = numberField(value, "updatedAt");
|
|
1027
|
+
const generation = numberField(value, "generation");
|
|
1028
|
+
if (!rootCwd || createdAt === undefined || updatedAt === undefined || generation === undefined) {
|
|
1029
|
+
return undefined;
|
|
1030
|
+
}
|
|
1031
|
+
return {
|
|
1032
|
+
version: REPORT_STORE_VERSION,
|
|
1033
|
+
rootSessionId,
|
|
1034
|
+
rootCwd,
|
|
1035
|
+
...(stringField(value, "rootSessionFile") === undefined
|
|
1036
|
+
? {}
|
|
1037
|
+
: { rootSessionFile: stringField(value, "rootSessionFile") }),
|
|
1038
|
+
createdAt,
|
|
1039
|
+
updatedAt,
|
|
1040
|
+
generation,
|
|
1041
|
+
};
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
function parseLease(value: unknown, rootSessionId: string): ReportLease | undefined {
|
|
1045
|
+
if (!isRecord(value)) return undefined;
|
|
1046
|
+
if (numberField(value, "version") !== REPORT_STORE_VERSION) return undefined;
|
|
1047
|
+
const pid = numberField(value, "pid");
|
|
1048
|
+
const nonce = stringField(value, "nonce");
|
|
1049
|
+
const leaseRoot = stringField(value, "rootSessionId");
|
|
1050
|
+
const createdAt = numberField(value, "createdAt");
|
|
1051
|
+
const updatedAt = numberField(value, "updatedAt");
|
|
1052
|
+
if (
|
|
1053
|
+
pid === undefined ||
|
|
1054
|
+
!nonce ||
|
|
1055
|
+
leaseRoot !== rootSessionId ||
|
|
1056
|
+
createdAt === undefined ||
|
|
1057
|
+
updatedAt === undefined
|
|
1058
|
+
) {
|
|
1059
|
+
return undefined;
|
|
1060
|
+
}
|
|
1061
|
+
return {
|
|
1062
|
+
version: REPORT_STORE_VERSION,
|
|
1063
|
+
pid,
|
|
1064
|
+
nonce,
|
|
1065
|
+
rootSessionId,
|
|
1066
|
+
...(stringField(value, "rootSessionFile") === undefined
|
|
1067
|
+
? {}
|
|
1068
|
+
: { rootSessionFile: stringField(value, "rootSessionFile") }),
|
|
1069
|
+
...(stringField(value, "rootCwd") === undefined
|
|
1070
|
+
? {}
|
|
1071
|
+
: { rootCwd: stringField(value, "rootCwd") }),
|
|
1072
|
+
createdAt,
|
|
1073
|
+
updatedAt,
|
|
1074
|
+
own: false,
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
function parseCleanupLock(value: unknown, rootSessionId: string): CleanupLockData | undefined {
|
|
1079
|
+
if (!isRecord(value)) return undefined;
|
|
1080
|
+
if (numberField(value, "version") !== REPORT_STORE_VERSION) return undefined;
|
|
1081
|
+
const pid = numberField(value, "pid");
|
|
1082
|
+
const nonce = stringField(value, "nonce");
|
|
1083
|
+
const lockRoot = stringField(value, "rootSessionId");
|
|
1084
|
+
const createdAt = numberField(value, "createdAt");
|
|
1085
|
+
const scope = stringField(value, "scope");
|
|
1086
|
+
const agentIds = stringArray(value.agentIds);
|
|
1087
|
+
const sessionFiles = stringArray(value.sessionFiles);
|
|
1088
|
+
if (
|
|
1089
|
+
pid === undefined ||
|
|
1090
|
+
!nonce ||
|
|
1091
|
+
lockRoot !== rootSessionId ||
|
|
1092
|
+
createdAt === undefined ||
|
|
1093
|
+
(scope !== "session" && scope !== "global") ||
|
|
1094
|
+
!agentIds ||
|
|
1095
|
+
!sessionFiles
|
|
1096
|
+
) {
|
|
1097
|
+
return undefined;
|
|
1098
|
+
}
|
|
1099
|
+
return {
|
|
1100
|
+
version: REPORT_STORE_VERSION,
|
|
1101
|
+
pid,
|
|
1102
|
+
nonce,
|
|
1103
|
+
rootSessionId,
|
|
1104
|
+
createdAt,
|
|
1105
|
+
scope,
|
|
1106
|
+
agentIds,
|
|
1107
|
+
sessionFiles,
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
/** Canonical lease name `<pid>-<nonce>.json`; the pid is proof material. */
|
|
1112
|
+
const LEASE_FILE_NAME = /^(\d+)-([A-Za-z0-9._-]+)\.json$/;
|
|
1113
|
+
|
|
1114
|
+
interface RecoveryClaim {
|
|
1115
|
+
version: typeof REPORT_STORE_VERSION;
|
|
1116
|
+
pid: number;
|
|
1117
|
+
nonce: string;
|
|
1118
|
+
rootSessionId: string;
|
|
1119
|
+
createdAt: number;
|
|
1120
|
+
lockNonce: string;
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
interface LeaseScan {
|
|
1124
|
+
leases: ReportLease[];
|
|
1125
|
+
uncertainty?: string;
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
/** No-follow stat result: only `info` may be trusted as a regular path. */
|
|
1129
|
+
type LstatScan =
|
|
1130
|
+
| { status: "missing" }
|
|
1131
|
+
| { status: "uncertain"; reason: string }
|
|
1132
|
+
| { status: "info"; info: Stats };
|
|
1133
|
+
|
|
1134
|
+
function parseRecoveryClaim(value: unknown, rootSessionId: string): RecoveryClaim | undefined {
|
|
1135
|
+
if (!isRecord(value)) return undefined;
|
|
1136
|
+
if (numberField(value, "version") !== REPORT_STORE_VERSION) return undefined;
|
|
1137
|
+
const pid = numberField(value, "pid");
|
|
1138
|
+
const nonce = stringField(value, "nonce");
|
|
1139
|
+
const lockNonce = stringField(value, "lockNonce");
|
|
1140
|
+
const claimRoot = stringField(value, "rootSessionId");
|
|
1141
|
+
const createdAt = numberField(value, "createdAt");
|
|
1142
|
+
if (
|
|
1143
|
+
pid === undefined ||
|
|
1144
|
+
!nonce ||
|
|
1145
|
+
!lockNonce ||
|
|
1146
|
+
claimRoot !== rootSessionId ||
|
|
1147
|
+
createdAt === undefined
|
|
1148
|
+
) {
|
|
1149
|
+
return undefined;
|
|
1150
|
+
}
|
|
1151
|
+
return {
|
|
1152
|
+
version: REPORT_STORE_VERSION,
|
|
1153
|
+
pid,
|
|
1154
|
+
nonce,
|
|
1155
|
+
rootSessionId,
|
|
1156
|
+
createdAt,
|
|
1157
|
+
lockNonce,
|
|
1158
|
+
};
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
export interface SessionHeader {
|
|
1162
|
+
id: string;
|
|
1163
|
+
cwd: string;
|
|
1164
|
+
timestamp?: string;
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
export interface ParsedSessionFile {
|
|
1168
|
+
header: SessionHeader;
|
|
1169
|
+
entries: unknown[];
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
function parseSessionFileText(text: string): ParsedSessionFile | undefined {
|
|
1173
|
+
const lines = text.split(/\r?\n/);
|
|
1174
|
+
let header: SessionHeader | undefined;
|
|
1175
|
+
const entries: unknown[] = [];
|
|
1176
|
+
for (const line of lines) {
|
|
1177
|
+
if (line.trim().length === 0) continue;
|
|
1178
|
+
let parsed: unknown;
|
|
1179
|
+
try {
|
|
1180
|
+
parsed = JSON.parse(line);
|
|
1181
|
+
} catch {
|
|
1182
|
+
return undefined;
|
|
1183
|
+
}
|
|
1184
|
+
if (isRecord(parsed) && stringField(parsed, "type") === "session" && !header) {
|
|
1185
|
+
const id = stringField(parsed, "id");
|
|
1186
|
+
const cwd = stringField(parsed, "cwd");
|
|
1187
|
+
if (id && cwd) {
|
|
1188
|
+
header = {
|
|
1189
|
+
id,
|
|
1190
|
+
cwd,
|
|
1191
|
+
...(stringField(parsed, "timestamp") === undefined
|
|
1192
|
+
? {}
|
|
1193
|
+
: { timestamp: stringField(parsed, "timestamp") }),
|
|
1194
|
+
};
|
|
1195
|
+
continue;
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
entries.push(parsed);
|
|
1199
|
+
}
|
|
1200
|
+
return header ? { header, entries } : undefined;
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
export function readSessionOwnershipData(data: unknown): SessionOwnershipData | undefined {
|
|
1204
|
+
if (!isRecord(data)) return undefined;
|
|
1205
|
+
if (numberField(data, "version") !== 1) return undefined;
|
|
1206
|
+
const agentId = stringField(data, "agentId");
|
|
1207
|
+
const rootSessionId = stringField(data, "rootSessionId");
|
|
1208
|
+
const rootCwd = stringField(data, "rootCwd");
|
|
1209
|
+
const childSessionId = stringField(data, "childSessionId");
|
|
1210
|
+
if (!agentId || !rootSessionId || !rootCwd || !childSessionId) return undefined;
|
|
1211
|
+
return {
|
|
1212
|
+
version: 1,
|
|
1213
|
+
agentId,
|
|
1214
|
+
rootSessionId,
|
|
1215
|
+
rootCwd,
|
|
1216
|
+
...(stringField(data, "rootSessionFile") === undefined
|
|
1217
|
+
? {}
|
|
1218
|
+
: { rootSessionFile: stringField(data, "rootSessionFile") }),
|
|
1219
|
+
childSessionId,
|
|
1220
|
+
};
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
function customRecordData(entry: unknown): JsonRecord | undefined {
|
|
1224
|
+
if (!isRecord(entry)) return undefined;
|
|
1225
|
+
const customType = stringField(entry, "customType") ?? stringField(entry, "type");
|
|
1226
|
+
if (customType !== "subagents:record") return undefined;
|
|
1227
|
+
return isRecord(entry.data) ? entry.data : undefined;
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
function parentRecordCandidates(parentEntries: readonly unknown[] | undefined): JsonRecord[] {
|
|
1231
|
+
if (!parentEntries) return [];
|
|
1232
|
+
const records: JsonRecord[] = [];
|
|
1233
|
+
for (const entry of parentEntries) {
|
|
1234
|
+
const data = customRecordData(entry);
|
|
1235
|
+
if (data) records.push(data);
|
|
1236
|
+
}
|
|
1237
|
+
return records;
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
/**
|
|
1241
|
+
* Snapshot a current-parent `subagents:record`. Only a top-level record is
|
|
1242
|
+
* accepted as a root report; the raw transcript stop reason is never read here.
|
|
1243
|
+
*/
|
|
1244
|
+
function snapshotFromParentRecord(
|
|
1245
|
+
data: JsonRecord,
|
|
1246
|
+
context: ReportContext | undefined,
|
|
1247
|
+
provenance: "parent-record" | "legacy-output",
|
|
1248
|
+
root: { rootSessionId?: string; rootCwd?: string; rootSessionFile?: string },
|
|
1249
|
+
): ReportSnapshot | undefined {
|
|
1250
|
+
const id = stringField(data, "id");
|
|
1251
|
+
const status = stringField(data, "status");
|
|
1252
|
+
const type = stringField(data, "type");
|
|
1253
|
+
const description = stringField(data, "description");
|
|
1254
|
+
if (!id || !isCanonicalAgentId(id) || !status || !isTerminalAgentStatus(status)) return undefined;
|
|
1255
|
+
if (stringField(data, "parentAgentId") !== undefined) return undefined;
|
|
1256
|
+
if (stringField(data, "workflowId") !== undefined) return undefined;
|
|
1257
|
+
const result = stringField(data, "result");
|
|
1258
|
+
const error = stringField(data, "error");
|
|
1259
|
+
const startedAt = numberField(data, "startedAt");
|
|
1260
|
+
const completedAt = numberField(data, "completedAt");
|
|
1261
|
+
const rootSessionId =
|
|
1262
|
+
root.rootSessionId ?? stringField(data, "rootSessionId") ?? context?.rootSessionId;
|
|
1263
|
+
const rootCwd = root.rootCwd ?? stringField(data, "rootCwd") ?? context?.cwd;
|
|
1264
|
+
if (!rootSessionId || !rootCwd) return undefined;
|
|
1265
|
+
const rootSessionFile =
|
|
1266
|
+
root.rootSessionFile ??
|
|
1267
|
+
stringField(data, "rootSessionFile") ??
|
|
1268
|
+
context?.rootSessionFile;
|
|
1269
|
+
return {
|
|
1270
|
+
id,
|
|
1271
|
+
type: type ?? "unknown",
|
|
1272
|
+
description: description ?? "",
|
|
1273
|
+
status,
|
|
1274
|
+
...(result === undefined ? {} : { result }),
|
|
1275
|
+
...(error === undefined ? {} : { error }),
|
|
1276
|
+
...(startedAt === undefined ? {} : { startedAt }),
|
|
1277
|
+
...(completedAt === undefined ? {} : { completedAt }),
|
|
1278
|
+
ownerIds: [],
|
|
1279
|
+
rootSessionId,
|
|
1280
|
+
rootCwd,
|
|
1281
|
+
...(rootSessionFile === undefined ? {} : { rootSessionFile }),
|
|
1282
|
+
legacy: true,
|
|
1283
|
+
recoveredFrom: provenance,
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
/** Fields a caller could read off a conversation without the live session. */
|
|
1288
|
+
interface ConversationMessage {
|
|
1289
|
+
role: string;
|
|
1290
|
+
content: unknown;
|
|
1291
|
+
toolName?: string;
|
|
1292
|
+
stopReason?: string;
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
function textFromContent(content: unknown): string {
|
|
1296
|
+
if (typeof content === "string") return content;
|
|
1297
|
+
if (!Array.isArray(content)) return "";
|
|
1298
|
+
const parts: string[] = [];
|
|
1299
|
+
for (const block of content) {
|
|
1300
|
+
if (!isRecord(block)) continue;
|
|
1301
|
+
if (stringField(block, "type") === "text") {
|
|
1302
|
+
const text = stringField(block, "text");
|
|
1303
|
+
if (text) parts.push(text);
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
return parts.join("\n");
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
function formatConversationMessage(message: ConversationMessage): string | undefined {
|
|
1310
|
+
if (message.role === "user") {
|
|
1311
|
+
const text = textFromContent(message.content).trim();
|
|
1312
|
+
return text ? `[User]: ${text}` : undefined;
|
|
1313
|
+
}
|
|
1314
|
+
if (message.role === "assistant") {
|
|
1315
|
+
const parts: string[] = [];
|
|
1316
|
+
const text = textFromContent(message.content).trim();
|
|
1317
|
+
if (text) parts.push(`[Assistant]: ${text}`);
|
|
1318
|
+
if (Array.isArray(message.content)) {
|
|
1319
|
+
const calls: string[] = [];
|
|
1320
|
+
for (const block of message.content) {
|
|
1321
|
+
if (!isRecord(block)) continue;
|
|
1322
|
+
if (stringField(block, "type") !== "toolCall") continue;
|
|
1323
|
+
calls.push(` Tool: ${stringField(block, "name") ?? stringField(block, "toolName") ?? "unknown"}`);
|
|
1324
|
+
}
|
|
1325
|
+
if (calls.length > 0) parts.push(`[Tool Calls]:\n${calls.join("\n")}`);
|
|
1326
|
+
}
|
|
1327
|
+
return parts.length > 0 ? parts.join("\n\n") : undefined;
|
|
1328
|
+
}
|
|
1329
|
+
if (message.role === "toolResult") {
|
|
1330
|
+
const text = textFromContent(message.content).trim();
|
|
1331
|
+
if (!text && !message.toolName) return undefined;
|
|
1332
|
+
return `[Tool Result${message.toolName ? ` (${message.toolName})` : ""}]: ${text}`;
|
|
1333
|
+
}
|
|
1334
|
+
return undefined;
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
function messageFromRecord(record: unknown): ConversationMessage | undefined {
|
|
1338
|
+
if (!isRecord(record)) return undefined;
|
|
1339
|
+
const message = record.message;
|
|
1340
|
+
if (!isRecord(message)) return undefined;
|
|
1341
|
+
const role = stringField(message, "role");
|
|
1342
|
+
if (!role) return undefined;
|
|
1343
|
+
return {
|
|
1344
|
+
role,
|
|
1345
|
+
content: message.content,
|
|
1346
|
+
...(stringField(message, "toolName") === undefined
|
|
1347
|
+
? {}
|
|
1348
|
+
: { toolName: stringField(message, "toolName") }),
|
|
1349
|
+
...(stringField(message, "stopReason") === undefined
|
|
1350
|
+
? {}
|
|
1351
|
+
: { stopReason: stringField(message, "stopReason") }),
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
function formatConversationLines(entries: readonly unknown[], outputTranscript: boolean): string {
|
|
1356
|
+
const parts: string[] = [];
|
|
1357
|
+
for (const entry of entries) {
|
|
1358
|
+
if (!isRecord(entry)) continue;
|
|
1359
|
+
if (outputTranscript) {
|
|
1360
|
+
const kind = stringField(entry, "type");
|
|
1361
|
+
if (kind === "diagnostic") continue;
|
|
1362
|
+
const message = messageFromRecord(entry);
|
|
1363
|
+
if (!message) continue;
|
|
1364
|
+
if (kind && kind !== message.role && !(kind === "toolResult" && message.role === "toolResult")) {
|
|
1365
|
+
// Output rows are user/assistant/toolResult plus diagnostics only.
|
|
1366
|
+
continue;
|
|
1367
|
+
}
|
|
1368
|
+
const formatted = formatConversationMessage(message);
|
|
1369
|
+
if (formatted) parts.push(formatted);
|
|
1370
|
+
continue;
|
|
1371
|
+
}
|
|
1372
|
+
if (stringField(entry, "type") !== "message") continue;
|
|
1373
|
+
const message = messageFromRecord(entry);
|
|
1374
|
+
if (!message) continue;
|
|
1375
|
+
const formatted = formatConversationMessage(message);
|
|
1376
|
+
if (formatted) parts.push(formatted);
|
|
1377
|
+
}
|
|
1378
|
+
return parts.join("\n\n");
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
export class ReportStore {
|
|
1382
|
+
private readonly options: ReportStoreOptions;
|
|
1383
|
+
private readonly writeChains = new Map<string, Promise<unknown>>();
|
|
1384
|
+
private readonly lastMaintenance = new Map<string, number>();
|
|
1385
|
+
private readonly maintenanceAttempts = new Map<string, { at: number; failures: number }>();
|
|
1386
|
+
private readonly cleanupLocks = new Map<string, CleanupLockHandle>();
|
|
1387
|
+
/** Manual lock admission is exclusive before its first filesystem await. */
|
|
1388
|
+
private readonly pendingCleanupLocks = new Set<string>();
|
|
1389
|
+
/**
|
|
1390
|
+
* Exact maintenance exemption: root session id -> the nonce reserved by THIS
|
|
1391
|
+
* store's maintenance attempt. Disk proof still requires our PID and nonce;
|
|
1392
|
+
* the row spans publication, validation and the awaited release.
|
|
1393
|
+
*/
|
|
1394
|
+
private readonly maintenanceLocks = new Map<string, string>();
|
|
1395
|
+
private readonly diagnosticsLog: string[] = [];
|
|
1396
|
+
private context?: ReportContext;
|
|
1397
|
+
private activation?: {
|
|
1398
|
+
leaseId?: string;
|
|
1399
|
+
leasePath?: string;
|
|
1400
|
+
persistence: boolean;
|
|
1401
|
+
rootDir?: string;
|
|
1402
|
+
};
|
|
1403
|
+
private closed = false;
|
|
1404
|
+
private closing = false;
|
|
1405
|
+
private closePromise?: Promise<ReportFlushResult>;
|
|
1406
|
+
|
|
1407
|
+
constructor(options: ReportStoreOptions = {}) {
|
|
1408
|
+
this.options = options;
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
/** Non-fatal store diagnostics (unreadable entries, skipped writes). */
|
|
1412
|
+
get diagnostics(): readonly string[] {
|
|
1413
|
+
return this.diagnosticsLog;
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
private diagnose(message: string): void {
|
|
1417
|
+
this.diagnosticsLog.push(message);
|
|
1418
|
+
this.options.diagnostics?.(message);
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
private now(): number {
|
|
1422
|
+
return this.options.now?.() ?? Date.now();
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
private nonce(): string {
|
|
1426
|
+
return this.options.nonce?.() ?? randomBytes(8).toString("hex");
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
private retentionMs(): number {
|
|
1430
|
+
return this.options.retentionMs ?? REPORT_RETENTION_MS;
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
private pidAlive(pid: number): boolean {
|
|
1434
|
+
if (pid === process.pid) return true;
|
|
1435
|
+
return (this.options.pidAlive ?? defaultPidAlive)(pid);
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
private agentDir(): string {
|
|
1439
|
+
return this.options.agentDir ?? getAgentDir();
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
storage(): ReportStorage {
|
|
1443
|
+
const agentDir = this.agentDir();
|
|
1444
|
+
const sessionRoots: string[] = [];
|
|
1445
|
+
const injected = this.options.sessionRoots;
|
|
1446
|
+
if (injected) {
|
|
1447
|
+
sessionRoots.push(...injected);
|
|
1448
|
+
} else {
|
|
1449
|
+
const envDir = process.env.PI_CODING_AGENT_SESSION_DIR?.trim();
|
|
1450
|
+
if (envDir) sessionRoots.push(envDir);
|
|
1451
|
+
sessionRoots.push(join(agentDir, "sessions"));
|
|
1452
|
+
}
|
|
1453
|
+
const unique: string[] = [];
|
|
1454
|
+
const seen = new Set<string>();
|
|
1455
|
+
for (const root of sessionRoots) {
|
|
1456
|
+
const key = pathKey(root);
|
|
1457
|
+
if (seen.has(key)) continue;
|
|
1458
|
+
seen.add(key);
|
|
1459
|
+
unique.push(resolve(root));
|
|
1460
|
+
}
|
|
1461
|
+
return {
|
|
1462
|
+
agentDir,
|
|
1463
|
+
reportsRoot: join(agentDir, "pi-subagents", "reports"),
|
|
1464
|
+
tempRoot: this.options.tempRoot ?? tmpdir(),
|
|
1465
|
+
sessionRoots: unique,
|
|
1466
|
+
};
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
private lockPath(rootSessionId: string): string {
|
|
1470
|
+
return join(this.storage().reportsRoot, rootSessionId, "cleanup.lock");
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
/**
|
|
1474
|
+
* The maintenance exemption is this store's in-memory ownership row, so the
|
|
1475
|
+
* nonce alone decides it. Only ever used for this store's own handle.
|
|
1476
|
+
*/
|
|
1477
|
+
private localMaintenanceExempt(rootSessionId: string, nonce: string): boolean {
|
|
1478
|
+
return this.maintenanceLocks.get(rootSessionId) === nonce;
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
/**
|
|
1482
|
+
* Disk proof for the same exemption: the lock must have been written by THIS
|
|
1483
|
+
* process with our recorded nonce. A replacement that copies the nonce but
|
|
1484
|
+
* carries a foreign (live) pid is a cleanup by someone else and must never
|
|
1485
|
+
* inherit the exemption.
|
|
1486
|
+
*/
|
|
1487
|
+
private maintenanceExempt(
|
|
1488
|
+
rootSessionId: string,
|
|
1489
|
+
lock: { pid: number; nonce: string } | undefined,
|
|
1490
|
+
): boolean {
|
|
1491
|
+
return (
|
|
1492
|
+
lock !== undefined &&
|
|
1493
|
+
lock.pid === process.pid &&
|
|
1494
|
+
this.localMaintenanceExempt(rootSessionId, lock.nonce)
|
|
1495
|
+
);
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
/** Drop this store's in-memory ownership of exactly this handle. */
|
|
1499
|
+
private forgetLocalOwnership(handle: CleanupLockHandle): void {
|
|
1500
|
+
const current = this.cleanupLocks.get(handle.rootSessionId);
|
|
1501
|
+
if (current?.nonce === handle.nonce) this.cleanupLocks.delete(handle.rootSessionId);
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
/**
|
|
1505
|
+
* End a maintenance exemption and its local ownership together. The exemption
|
|
1506
|
+
* must stay valid until the awaited release finishes, and must never survive a
|
|
1507
|
+
* failed one: the on-disk lock then stays in place and keeps failing closed.
|
|
1508
|
+
*/
|
|
1509
|
+
private async endMaintenanceLock(handle: CleanupLockHandle): Promise<void> {
|
|
1510
|
+
try {
|
|
1511
|
+
await this.releaseCleanupLock(handle);
|
|
1512
|
+
} finally {
|
|
1513
|
+
this.forgetLocalOwnership(handle);
|
|
1514
|
+
if (this.maintenanceLocks.get(handle.rootSessionId) === handle.nonce) {
|
|
1515
|
+
this.maintenanceLocks.delete(handle.rootSessionId);
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
private async ensureReportRootReal(): Promise<string> {
|
|
1521
|
+
const root = this.storage().reportsRoot;
|
|
1522
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
1523
|
+
await chmodPrivate(root, 0o700);
|
|
1524
|
+
const real = await realpath(root);
|
|
1525
|
+
const info = await lstat(real);
|
|
1526
|
+
if (!info.isDirectory()) throw new Error("reports root is not a directory");
|
|
1527
|
+
return real;
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
private async ensureRootDirectory(rootSessionId: string): Promise<string> {
|
|
1531
|
+
if (!isSafePathComponent(rootSessionId)) {
|
|
1532
|
+
throw new Error(`invalid root session id component: ${rootSessionId}`);
|
|
1533
|
+
}
|
|
1534
|
+
const root = await this.ensureReportRootReal();
|
|
1535
|
+
const rootDir = join(root, rootSessionId);
|
|
1536
|
+
try {
|
|
1537
|
+
const info = await lstat(rootDir);
|
|
1538
|
+
if (info.isSymbolicLink()) throw new Error("root session directory is a symlink");
|
|
1539
|
+
if (!info.isDirectory()) throw new Error("root session path is not a directory");
|
|
1540
|
+
} catch (error) {
|
|
1541
|
+
if (!isNotFound(error)) throw error;
|
|
1542
|
+
await mkdir(rootDir, { mode: 0o700 });
|
|
1543
|
+
}
|
|
1544
|
+
await chmodPrivate(rootDir, 0o700);
|
|
1545
|
+
return rootDir;
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
private async existingRootDirectory(rootSessionId: string): Promise<string | undefined> {
|
|
1549
|
+
return (await this.existingRootDirectoryScan(rootSessionId)).rootDir;
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
/**
|
|
1553
|
+
* Same best-effort resolution as `existingRootDirectory`, but a non-ENOENT
|
|
1554
|
+
* failure is reported instead of collapsing into "no such root". Strict
|
|
1555
|
+
* callers (the cleanup identity inventory) also pass `vanishedIsUncertain`:
|
|
1556
|
+
* for an already-enumerated root, ENOENT means it disappeared between the
|
|
1557
|
+
* listing and the lookup, which is partial evidence, never "absent".
|
|
1558
|
+
*/
|
|
1559
|
+
private async existingRootDirectoryScan(
|
|
1560
|
+
rootSessionId: string,
|
|
1561
|
+
options: { vanishedIsUncertain?: boolean; strayFileIsAbsent?: boolean } = {},
|
|
1562
|
+
): Promise<{ rootDir?: string; uncertainty?: string }> {
|
|
1563
|
+
if (!isSafePathComponent(rootSessionId)) return {};
|
|
1564
|
+
let root: string;
|
|
1565
|
+
try {
|
|
1566
|
+
root = await realpath(this.storage().reportsRoot);
|
|
1567
|
+
const info = await lstat(root);
|
|
1568
|
+
if (!info.isDirectory()) return { uncertainty: "reports-root-not-a-directory" };
|
|
1569
|
+
} catch (error) {
|
|
1570
|
+
if (isNotFound(error)) {
|
|
1571
|
+
return options.vanishedIsUncertain === true
|
|
1572
|
+
? { uncertainty: "reports-root-vanished" }
|
|
1573
|
+
: {};
|
|
1574
|
+
}
|
|
1575
|
+
this.diagnose(`reports root unreadable: ${errorCode(error) ?? "unknown"}`);
|
|
1576
|
+
return { uncertainty: "reports-root-unreadable" };
|
|
1577
|
+
}
|
|
1578
|
+
const rootDir = join(root, rootSessionId);
|
|
1579
|
+
try {
|
|
1580
|
+
const info = await lstat(rootDir);
|
|
1581
|
+
if (info.isSymbolicLink() || !info.isDirectory()) {
|
|
1582
|
+
this.diagnose(`ignoring unsafe root directory: ${rootSessionId}`);
|
|
1583
|
+
// A verified regular file cannot contain entries: absence is proven.
|
|
1584
|
+
// A link/junction or unknown type is never followed or assumed empty.
|
|
1585
|
+
if (options.strayFileIsAbsent === true && info.isFile()) return {};
|
|
1586
|
+
return { uncertainty: "root-directory-unsafe" };
|
|
1587
|
+
}
|
|
1588
|
+
return { rootDir };
|
|
1589
|
+
} catch (error) {
|
|
1590
|
+
if (isNotFound(error)) {
|
|
1591
|
+
return options.vanishedIsUncertain === true
|
|
1592
|
+
? { uncertainty: "root-directory-vanished" }
|
|
1593
|
+
: {};
|
|
1594
|
+
}
|
|
1595
|
+
this.diagnose(`root directory unreadable: ${errorCode(error) ?? "unknown"}`);
|
|
1596
|
+
return { uncertainty: "root-directory-unreadable" };
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1600
|
+
/**
|
|
1601
|
+
* `lstat` that never follows a link: a missing path is proven absence, every
|
|
1602
|
+
* other failure is uncertainty, and the caller decides what shape is allowed.
|
|
1603
|
+
*/
|
|
1604
|
+
private async lstatScan(path: string, label: string): Promise<LstatScan> {
|
|
1605
|
+
try {
|
|
1606
|
+
return { status: "info", info: await lstat(path) };
|
|
1607
|
+
} catch (error) {
|
|
1608
|
+
if (isNotFound(error)) return { status: "missing" };
|
|
1609
|
+
this.diagnose(`${label} unreadable: ${errorCode(error) ?? "unknown"}`);
|
|
1610
|
+
return { status: "uncertain", reason: `unreadable-${label}` };
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
private enqueue<T>(key: string, run: () => Promise<T>): Promise<T> {
|
|
1615
|
+
const previous = this.writeChains.get(key) ?? Promise.resolve();
|
|
1616
|
+
const next = previous.then(run, run);
|
|
1617
|
+
const tracked = next.then(
|
|
1618
|
+
() => undefined,
|
|
1619
|
+
() => undefined,
|
|
1620
|
+
);
|
|
1621
|
+
this.writeChains.set(key, tracked);
|
|
1622
|
+
void tracked.then(() => {
|
|
1623
|
+
if (this.writeChains.get(key) === tracked) this.writeChains.delete(key);
|
|
1624
|
+
});
|
|
1625
|
+
return next;
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
/**
|
|
1629
|
+
* Await accepted writes, including writes appended while an earlier pass was
|
|
1630
|
+
* in flight. Both the total wait and the number of passes are bounded: an
|
|
1631
|
+
* incomplete result never means that a durable read is current.
|
|
1632
|
+
*/
|
|
1633
|
+
async flush(options: ReportFlushOptions = {}): Promise<ReportFlushResult> {
|
|
1634
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_FLUSH_TIMEOUT_MS;
|
|
1635
|
+
const maxPasses = options.maxPasses ?? DEFAULT_FLUSH_MAX_PASSES;
|
|
1636
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs < 0) throw new RangeError("flush timeout must be finite and non-negative");
|
|
1637
|
+
if (!Number.isSafeInteger(maxPasses) || maxPasses < 0) throw new RangeError("flush maxPasses must be a non-negative safe integer");
|
|
1638
|
+
const startedAt = Date.now();
|
|
1639
|
+
let passes = 0;
|
|
1640
|
+
while (this.writeChains.size > 0) {
|
|
1641
|
+
if (passes >= maxPasses) {
|
|
1642
|
+
return { status: "incomplete", reason: "max-passes", pendingChains: this.writeChains.size, passes };
|
|
1643
|
+
}
|
|
1644
|
+
const remaining = timeoutMs - (Date.now() - startedAt);
|
|
1645
|
+
if (remaining <= 0) {
|
|
1646
|
+
return { status: "incomplete", reason: "timeout", pendingChains: this.writeChains.size, passes };
|
|
1647
|
+
}
|
|
1648
|
+
const pending = [...new Set(this.writeChains.values())];
|
|
1649
|
+
passes++;
|
|
1650
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
1651
|
+
const timeout = new Promise<"timeout">((resolve) => {
|
|
1652
|
+
timer = setTimeout(() => resolve("timeout"), remaining);
|
|
1653
|
+
});
|
|
1654
|
+
try {
|
|
1655
|
+
const settled = Promise.allSettled(pending).then(() => "settled" as const);
|
|
1656
|
+
const outcome = await Promise.race([settled, timeout]);
|
|
1657
|
+
if (outcome === "timeout" && this.writeChains.size > 0) {
|
|
1658
|
+
return { status: "incomplete", reason: "timeout", pendingChains: this.writeChains.size, passes };
|
|
1659
|
+
}
|
|
1660
|
+
} finally {
|
|
1661
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
return { status: "flushed", pendingChains: 0, passes };
|
|
1665
|
+
}
|
|
1666
|
+
|
|
1667
|
+
private async readJson<T>(
|
|
1668
|
+
path: string,
|
|
1669
|
+
parser: (value: unknown) => T | undefined,
|
|
1670
|
+
): Promise<T | undefined> {
|
|
1671
|
+
return (await this.readJsonScan(path, basename(path), parser)).value;
|
|
1672
|
+
}
|
|
1673
|
+
|
|
1674
|
+
/**
|
|
1675
|
+
* Best-effort reader plus an explicit reason when the stored value cannot be
|
|
1676
|
+
* trusted. `readJson` keeps the historic ignore-and-continue behavior.
|
|
1677
|
+
*/
|
|
1678
|
+
private async readJsonScan<T>(
|
|
1679
|
+
path: string,
|
|
1680
|
+
label: string,
|
|
1681
|
+
parser: (value: unknown) => T | undefined,
|
|
1682
|
+
): Promise<{ value?: T; uncertainty?: string }> {
|
|
1683
|
+
let text: string;
|
|
1684
|
+
try {
|
|
1685
|
+
text = await readFile(path, "utf8");
|
|
1686
|
+
} catch (error) {
|
|
1687
|
+
if (isNotFound(error)) return {};
|
|
1688
|
+
this.diagnose(`unreadable ${basename(path)}: ${errorCode(error) ?? "unknown"}`);
|
|
1689
|
+
return { uncertainty: `unreadable-${label}` };
|
|
1690
|
+
}
|
|
1691
|
+
let value: unknown;
|
|
1692
|
+
try {
|
|
1693
|
+
value = JSON.parse(text);
|
|
1694
|
+
} catch {
|
|
1695
|
+
this.diagnose(`invalid JSON in ${basename(path)}`);
|
|
1696
|
+
return { uncertainty: `invalid-json-${label}` };
|
|
1697
|
+
}
|
|
1698
|
+
const parsed = parser(value);
|
|
1699
|
+
if (parsed === undefined) return { uncertainty: `unrecognized-${label}` };
|
|
1700
|
+
return { value: parsed };
|
|
1701
|
+
}
|
|
1702
|
+
|
|
1703
|
+
/**
|
|
1704
|
+
* Lease metadata is proof material: a malformed, unreadable or unrecognized
|
|
1705
|
+
* lease is uncertainty, never "no lease". A canonical filename pid that
|
|
1706
|
+
* disagrees with its JSON body is an identity mismatch for the same reason.
|
|
1707
|
+
*/
|
|
1708
|
+
private async scanLeaseFiles(rootSessionId: string, rootDir: string): Promise<LeaseScan> {
|
|
1709
|
+
const dir = join(rootDir, "leases");
|
|
1710
|
+
let names: string[];
|
|
1711
|
+
try {
|
|
1712
|
+
names = await readdir(dir);
|
|
1713
|
+
} catch (error) {
|
|
1714
|
+
if (isNotFound(error)) return { leases: [] };
|
|
1715
|
+
this.diagnose(`lease directory unreadable: ${errorCode(error) ?? "unknown"}`);
|
|
1716
|
+
return { leases: [], uncertainty: "lease-directory-unreadable" };
|
|
1717
|
+
}
|
|
1718
|
+
const leases: ReportLease[] = [];
|
|
1719
|
+
let uncertainty: string | undefined;
|
|
1720
|
+
const ownNonce = this.activation?.leaseId;
|
|
1721
|
+
for (const name of names.sort()) {
|
|
1722
|
+
if (!name.endsWith(".json")) continue;
|
|
1723
|
+
const match = LEASE_FILE_NAME.exec(name);
|
|
1724
|
+
const namePid = match ? Number(match[1]) : Number.NaN;
|
|
1725
|
+
if (!match || !Number.isSafeInteger(namePid) || namePid <= 0) {
|
|
1726
|
+
uncertainty ??= "lease-name-unrecognized";
|
|
1727
|
+
this.diagnose(`unrecognized lease name: ${name}`);
|
|
1728
|
+
continue;
|
|
1729
|
+
}
|
|
1730
|
+
let text: string;
|
|
1731
|
+
try {
|
|
1732
|
+
text = await readFile(join(dir, name), "utf8");
|
|
1733
|
+
} catch (error) {
|
|
1734
|
+
if (isNotFound(error)) continue;
|
|
1735
|
+
uncertainty ??= "lease-unreadable";
|
|
1736
|
+
this.diagnose(`lease file unreadable: ${name} (${errorCode(error) ?? "unknown"})`);
|
|
1737
|
+
continue;
|
|
1738
|
+
}
|
|
1739
|
+
let value: unknown;
|
|
1740
|
+
try {
|
|
1741
|
+
value = JSON.parse(text);
|
|
1742
|
+
} catch {
|
|
1743
|
+
uncertainty ??= "lease-json-invalid";
|
|
1744
|
+
this.diagnose(`invalid lease JSON: ${name}`);
|
|
1745
|
+
continue;
|
|
1746
|
+
}
|
|
1747
|
+
const lease = parseLease(value, rootSessionId);
|
|
1748
|
+
if (!lease) {
|
|
1749
|
+
uncertainty ??= "lease-metadata-invalid";
|
|
1750
|
+
this.diagnose(`invalid lease metadata: ${name}`);
|
|
1751
|
+
continue;
|
|
1752
|
+
}
|
|
1753
|
+
if (lease.pid !== namePid) {
|
|
1754
|
+
uncertainty ??= "lease-identity-mismatch";
|
|
1755
|
+
this.diagnose(`lease pid disagrees with its canonical name: ${name}`);
|
|
1756
|
+
continue;
|
|
1757
|
+
}
|
|
1758
|
+
lease.own = lease.pid === process.pid && lease.nonce === ownNonce;
|
|
1759
|
+
leases.push(lease);
|
|
1760
|
+
}
|
|
1761
|
+
return uncertainty === undefined ? { leases } : { leases, uncertainty };
|
|
1762
|
+
}
|
|
1763
|
+
|
|
1764
|
+
private classifyCleanupLock(rootSessionId: string, raw: string): CleanupLockRead {
|
|
1765
|
+
let value: unknown;
|
|
1766
|
+
try {
|
|
1767
|
+
value = JSON.parse(raw);
|
|
1768
|
+
} catch {
|
|
1769
|
+
return { status: "uncertain", reason: "cleanup-lock-json-invalid", raw };
|
|
1770
|
+
}
|
|
1771
|
+
const lock = parseCleanupLock(value, rootSessionId);
|
|
1772
|
+
if (!lock) return { status: "uncertain", reason: "cleanup-lock-metadata-invalid", raw };
|
|
1773
|
+
return this.pidAlive(lock.pid)
|
|
1774
|
+
? { status: "live", lock, raw }
|
|
1775
|
+
: { status: "dead", lock, raw };
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
private async readCleanupLockRead(rootSessionId: string): Promise<CleanupLockRead> {
|
|
1779
|
+
let raw: string;
|
|
1780
|
+
try {
|
|
1781
|
+
raw = await readFile(this.lockPath(rootSessionId), "utf8");
|
|
1782
|
+
} catch (error) {
|
|
1783
|
+
if (isNotFound(error)) return { status: "absent" };
|
|
1784
|
+
this.diagnose(`cleanup lock unreadable: ${errorCode(error) ?? "unknown"}`);
|
|
1785
|
+
return {
|
|
1786
|
+
status: "uncertain",
|
|
1787
|
+
reason: `cleanup-lock-unreadable:${errorCode(error) ?? "unknown"}`,
|
|
1788
|
+
};
|
|
1789
|
+
}
|
|
1790
|
+
const read = this.classifyCleanupLock(rootSessionId, raw);
|
|
1791
|
+
if (read.status === "uncertain") {
|
|
1792
|
+
this.diagnose(`cleanup lock uncertain (${read.reason ?? "unknown"}); failing closed`);
|
|
1793
|
+
}
|
|
1794
|
+
return read;
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
private readCleanupLockReadSync(rootSessionId: string): CleanupLockRead {
|
|
1798
|
+
let raw: string;
|
|
1799
|
+
try {
|
|
1800
|
+
raw = readFileSync(this.lockPath(rootSessionId), "utf8");
|
|
1801
|
+
} catch (error) {
|
|
1802
|
+
if (isNotFound(error)) return { status: "absent" };
|
|
1803
|
+
return {
|
|
1804
|
+
status: "uncertain",
|
|
1805
|
+
reason: `cleanup-lock-unreadable:${errorCode(error) ?? "unknown"}`,
|
|
1806
|
+
};
|
|
1807
|
+
}
|
|
1808
|
+
return this.classifyCleanupLock(rootSessionId, raw);
|
|
1809
|
+
}
|
|
1810
|
+
|
|
1811
|
+
/**
|
|
1812
|
+
* Async guard shared by save/registerWorkflow write barriers. Dead locks do
|
|
1813
|
+
* not block; live locks block unless this is our own maintenance lock; anything
|
|
1814
|
+
* uncertain fails closed with an explicit reason (never silently active).
|
|
1815
|
+
*/
|
|
1816
|
+
private async writeBlockReason(rootSessionId: string): Promise<string | undefined> {
|
|
1817
|
+
const read = await this.readCleanupLockRead(rootSessionId);
|
|
1818
|
+
if (read.status === "uncertain") {
|
|
1819
|
+
this.diagnose(`cleanup lock uncertain (${read.reason ?? "unknown"}); refusing writes`);
|
|
1820
|
+
return "cleanup-lock-unreadable";
|
|
1821
|
+
}
|
|
1822
|
+
if (read.status !== "live") return undefined;
|
|
1823
|
+
if (this.maintenanceExempt(rootSessionId, read.lock)) return undefined;
|
|
1824
|
+
return "cleanup-lock";
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
/**
|
|
1828
|
+
* Publish a JSON control file atomically and exclusively: the full body is
|
|
1829
|
+
* written to a temp sibling first, then hard-linked into place. A crash can
|
|
1830
|
+
* leave an ignored temp file, never a truncated authoritative lock.
|
|
1831
|
+
*/
|
|
1832
|
+
private async publishExclusiveJson(
|
|
1833
|
+
path: string,
|
|
1834
|
+
value: unknown,
|
|
1835
|
+
nonce: string,
|
|
1836
|
+
): Promise<"created" | "exists"> {
|
|
1837
|
+
const serialized = JSON.stringify(value);
|
|
1838
|
+
const tmp = `${path}.${process.pid}.${nonce}.tmp`;
|
|
1839
|
+
try {
|
|
1840
|
+
await writeFile(tmp, serialized, { encoding: "utf8", mode: 0o600 });
|
|
1841
|
+
try {
|
|
1842
|
+
await link(tmp, path);
|
|
1843
|
+
return "created";
|
|
1844
|
+
} catch (error) {
|
|
1845
|
+
if (errorCode(error) === "EEXIST") return "exists";
|
|
1846
|
+
// A filesystem without working hard links cannot publish a complete body
|
|
1847
|
+
// atomically; fail closed instead of exposing the authoritative path early.
|
|
1848
|
+
throw error;
|
|
1849
|
+
}
|
|
1850
|
+
} finally {
|
|
1851
|
+
try {
|
|
1852
|
+
await unlink(tmp);
|
|
1853
|
+
} catch (error) {
|
|
1854
|
+
if (!isNotFound(error)) {
|
|
1855
|
+
this.diagnose(`control temp cleanup failed: ${errorCode(error) ?? "unknown"}`);
|
|
1856
|
+
}
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
}
|
|
1860
|
+
|
|
1861
|
+
private recoveryIntentPath(rootDir: string, intentNonce: string): string {
|
|
1862
|
+
return join(rootDir, `${RECOVERY_INTENT_PREFIX}${process.pid}-${intentNonce}.json`);
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
private async removeRecoveryIntent(path: string): Promise<void> {
|
|
1866
|
+
try {
|
|
1867
|
+
await unlink(path);
|
|
1868
|
+
} catch (error) {
|
|
1869
|
+
if (!isNotFound(error)) {
|
|
1870
|
+
this.diagnose(`recovery intent cleanup failed: ${errorCode(error) ?? "unknown"}`);
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
/**
|
|
1876
|
+
* Cross-process reaper exclusion. Every reaper publishes a unique intent and
|
|
1877
|
+
* then refuses when another live/unknown intent is visible. Unknown metadata
|
|
1878
|
+
* fails closed; a provably dead intent is removable because its unique name
|
|
1879
|
+
* can never belong to a newer reaper.
|
|
1880
|
+
*/
|
|
1881
|
+
private async reaperIntentsClear(
|
|
1882
|
+
rootSessionId: string,
|
|
1883
|
+
rootDir: string,
|
|
1884
|
+
ownPath: string,
|
|
1885
|
+
): Promise<"clear" | "busy" | "uncertain"> {
|
|
1886
|
+
let names: string[];
|
|
1887
|
+
try {
|
|
1888
|
+
names = await readdir(rootDir);
|
|
1889
|
+
} catch (error) {
|
|
1890
|
+
this.diagnose(`recovery intent scan failed: ${errorCode(error) ?? "unknown"}`);
|
|
1891
|
+
return "uncertain";
|
|
1892
|
+
}
|
|
1893
|
+
for (const name of names.sort()) {
|
|
1894
|
+
if (!name.startsWith(RECOVERY_INTENT_PREFIX) || !name.endsWith(".json")) continue;
|
|
1895
|
+
const path = join(rootDir, name);
|
|
1896
|
+
if (pathKey(path) === pathKey(ownPath)) continue;
|
|
1897
|
+
let text: string;
|
|
1898
|
+
try {
|
|
1899
|
+
text = await readFile(path, "utf8");
|
|
1900
|
+
} catch (error) {
|
|
1901
|
+
if (isNotFound(error)) continue;
|
|
1902
|
+
this.diagnose(`recovery intent unreadable: ${name} (${errorCode(error) ?? "unknown"})`);
|
|
1903
|
+
return "uncertain";
|
|
1904
|
+
}
|
|
1905
|
+
let value: unknown;
|
|
1906
|
+
try {
|
|
1907
|
+
value = JSON.parse(text);
|
|
1908
|
+
} catch {
|
|
1909
|
+
this.diagnose(`recovery intent invalid JSON: ${name}; failing closed`);
|
|
1910
|
+
return "uncertain";
|
|
1911
|
+
}
|
|
1912
|
+
const intent = parseRecoveryClaim(value, rootSessionId);
|
|
1913
|
+
if (!intent) {
|
|
1914
|
+
this.diagnose(`recovery intent metadata invalid: ${name}; failing closed`);
|
|
1915
|
+
return "uncertain";
|
|
1916
|
+
}
|
|
1917
|
+
if (intent.pid === process.pid || this.pidAlive(intent.pid)) return "busy";
|
|
1918
|
+
// Unique name, provably dead owner: safe to clear for a later attempt.
|
|
1919
|
+
try {
|
|
1920
|
+
await unlink(path);
|
|
1921
|
+
} catch (error) {
|
|
1922
|
+
if (!isNotFound(error)) {
|
|
1923
|
+
this.diagnose(`stale recovery intent cleanup failed: ${name}`);
|
|
1924
|
+
return "uncertain";
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
return "clear";
|
|
1929
|
+
}
|
|
1930
|
+
|
|
1931
|
+
/**
|
|
1932
|
+
* Recover a dead lock and publish this caller's replacement while still
|
|
1933
|
+
* holding the reaper intent. A new owner's lock is never unlinked: ordinary
|
|
1934
|
+
* creators use atomic EXCL publication, and a later reaper sees the intent.
|
|
1935
|
+
*/
|
|
1936
|
+
private async recoverAndPublishLock(
|
|
1937
|
+
rootSessionId: string,
|
|
1938
|
+
rootDir: string,
|
|
1939
|
+
expected: CleanupLockRead,
|
|
1940
|
+
data: CleanupLockData,
|
|
1941
|
+
nonce: string,
|
|
1942
|
+
): Promise<"acquired" | "busy" | "uncertain" | "changed" | "create-failed"> {
|
|
1943
|
+
const expectedLock = expected.lock;
|
|
1944
|
+
const expectedRaw = expected.raw;
|
|
1945
|
+
if (!expectedLock || expectedRaw === undefined) return "uncertain";
|
|
1946
|
+
const intentNonce = this.nonce();
|
|
1947
|
+
const intentPath = this.recoveryIntentPath(rootDir, intentNonce);
|
|
1948
|
+
const intent: RecoveryClaim = {
|
|
1949
|
+
version: REPORT_STORE_VERSION,
|
|
1950
|
+
pid: process.pid,
|
|
1951
|
+
nonce: intentNonce,
|
|
1952
|
+
rootSessionId,
|
|
1953
|
+
createdAt: this.now(),
|
|
1954
|
+
lockNonce: expectedLock.nonce,
|
|
1955
|
+
};
|
|
1956
|
+
try {
|
|
1957
|
+
const published = await this.publishExclusiveJson(intentPath, intent, intentNonce);
|
|
1958
|
+
if (published === "exists") return "busy";
|
|
1959
|
+
} catch (error) {
|
|
1960
|
+
this.diagnose(`recovery intent publish failed: ${errorCode(error) ?? "unknown"}`);
|
|
1961
|
+
return "uncertain";
|
|
1962
|
+
}
|
|
1963
|
+
try {
|
|
1964
|
+
const intents = await this.reaperIntentsClear(rootSessionId, rootDir, intentPath);
|
|
1965
|
+
if (intents === "busy") return "busy";
|
|
1966
|
+
if (intents === "uncertain") return "uncertain";
|
|
1967
|
+
|
|
1968
|
+
const lockPath = this.lockPath(rootSessionId);
|
|
1969
|
+
let currentRaw: string;
|
|
1970
|
+
try {
|
|
1971
|
+
currentRaw = await readFile(lockPath, "utf8");
|
|
1972
|
+
} catch (error) {
|
|
1973
|
+
return isNotFound(error) ? "changed" : "uncertain";
|
|
1974
|
+
}
|
|
1975
|
+
if (currentRaw !== expectedRaw) return "changed";
|
|
1976
|
+
const current = this.classifyCleanupLock(rootSessionId, currentRaw);
|
|
1977
|
+
if (current.status !== "dead" || current.lock?.nonce !== expectedLock.nonce) {
|
|
1978
|
+
return current.status === "uncertain" ? "uncertain" : "changed";
|
|
1979
|
+
}
|
|
1980
|
+
try {
|
|
1981
|
+
await unlink(lockPath);
|
|
1982
|
+
} catch (error) {
|
|
1983
|
+
if (isNotFound(error)) return "changed";
|
|
1984
|
+
this.diagnose(`dead cleanup lock removal failed: ${errorCode(error) ?? "unknown"}`);
|
|
1985
|
+
return "uncertain";
|
|
1986
|
+
}
|
|
1987
|
+
let published: "created" | "exists";
|
|
1988
|
+
try {
|
|
1989
|
+
published = await this.publishExclusiveJson(lockPath, data, nonce);
|
|
1990
|
+
} catch (error) {
|
|
1991
|
+
this.diagnose(`cleanup lock publish after recovery failed: ${errorCode(error) ?? "unknown"}`);
|
|
1992
|
+
return "create-failed";
|
|
1993
|
+
}
|
|
1994
|
+
// An ordinary creator won the EXCL race; never clobber it.
|
|
1995
|
+
return published === "created" ? "acquired" : "changed";
|
|
1996
|
+
} finally {
|
|
1997
|
+
await this.removeRecoveryIntent(intentPath);
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
|
|
2001
|
+
/**
|
|
2002
|
+
* Persist the minimal main-session identity for a persistent binding, before the
|
|
2003
|
+
* first agent report can create root metadata. Existing valid metadata and its
|
|
2004
|
+
* generation are preserved, a missing root file is filled, and unreadable or
|
|
2005
|
+
* malformed metadata refuses the binding instead of being blindly overwritten.
|
|
2006
|
+
*/
|
|
2007
|
+
private async ensureMainIdentityKeeper(
|
|
2008
|
+
rootDir: string,
|
|
2009
|
+
context: ReportContext,
|
|
2010
|
+
): Promise<{ ok: true } | { ok: false; reason: string }> {
|
|
2011
|
+
if (context.rootSessionFile === undefined) return { ok: true };
|
|
2012
|
+
const scan = await this.readJsonScan(
|
|
2013
|
+
join(rootDir, "root.json"),
|
|
2014
|
+
"root-metadata",
|
|
2015
|
+
(value) => parseRootMetadata(value, context.rootSessionId),
|
|
2016
|
+
);
|
|
2017
|
+
if (scan.uncertainty !== undefined) {
|
|
2018
|
+
return { ok: false, reason: `root-metadata-unreadable:${scan.uncertainty}` };
|
|
2019
|
+
}
|
|
2020
|
+
const existing = scan.value;
|
|
2021
|
+
if (existing?.rootSessionFile !== undefined) return { ok: true };
|
|
2022
|
+
try {
|
|
2023
|
+
await this.writeRootMetadata(
|
|
2024
|
+
rootDir,
|
|
2025
|
+
context.rootSessionId,
|
|
2026
|
+
context,
|
|
2027
|
+
existing?.generation ?? 0,
|
|
2028
|
+
);
|
|
2029
|
+
} catch (error) {
|
|
2030
|
+
return { ok: false, reason: `root-metadata-write-failed:${errorCode(error) ?? "unknown"}` };
|
|
2031
|
+
}
|
|
2032
|
+
return { ok: true };
|
|
2033
|
+
}
|
|
2034
|
+
|
|
2035
|
+
private async writeRootMetadata(
|
|
2036
|
+
rootDir: string,
|
|
2037
|
+
rootSessionId: string,
|
|
2038
|
+
context: ReportContext,
|
|
2039
|
+
generation: number,
|
|
2040
|
+
): Promise<RootMetadata> {
|
|
2041
|
+
const path = join(rootDir, "root.json");
|
|
2042
|
+
const existing = await this.readJson(path, (value) => parseRootMetadata(value, rootSessionId));
|
|
2043
|
+
const now = this.now();
|
|
2044
|
+
const metadata: RootMetadata = {
|
|
2045
|
+
version: REPORT_STORE_VERSION,
|
|
2046
|
+
rootSessionId,
|
|
2047
|
+
rootCwd: context.cwd,
|
|
2048
|
+
...(context.rootSessionFile === undefined ? {} : { rootSessionFile: context.rootSessionFile }),
|
|
2049
|
+
createdAt: existing?.createdAt ?? now,
|
|
2050
|
+
updatedAt: now,
|
|
2051
|
+
generation,
|
|
2052
|
+
};
|
|
2053
|
+
await atomicWriteJson(path, metadata, this.nonce());
|
|
2054
|
+
return metadata;
|
|
2055
|
+
}
|
|
2056
|
+
|
|
2057
|
+
private async bumpGenerationLocked(
|
|
2058
|
+
rootDir: string,
|
|
2059
|
+
rootSessionId: string,
|
|
2060
|
+
context: ReportContext,
|
|
2061
|
+
): Promise<number> {
|
|
2062
|
+
const existing = await this.readJson(
|
|
2063
|
+
join(rootDir, "root.json"),
|
|
2064
|
+
(value) => parseRootMetadata(value, rootSessionId),
|
|
2065
|
+
);
|
|
2066
|
+
const generation = (existing?.generation ?? 0) + 1;
|
|
2067
|
+
const rootSessionFile = existing?.rootSessionFile ?? context.rootSessionFile;
|
|
2068
|
+
// Maintenance may run across roots: preserve each root's recorded provenance
|
|
2069
|
+
// instead of rewriting it with whichever context happens to be bound now.
|
|
2070
|
+
await this.writeRootMetadata(
|
|
2071
|
+
rootDir,
|
|
2072
|
+
rootSessionId,
|
|
2073
|
+
{
|
|
2074
|
+
cwd: existing?.rootCwd ?? context.cwd,
|
|
2075
|
+
rootSessionId,
|
|
2076
|
+
...(rootSessionFile === undefined ? {} : { rootSessionFile }),
|
|
2077
|
+
},
|
|
2078
|
+
generation,
|
|
2079
|
+
);
|
|
2080
|
+
return generation;
|
|
2081
|
+
}
|
|
2082
|
+
|
|
2083
|
+
private async createLease(
|
|
2084
|
+
rootDir: string,
|
|
2085
|
+
context: ReportContext,
|
|
2086
|
+
): Promise<{ nonce: string; path: string }> {
|
|
2087
|
+
const dir = join(rootDir, "leases");
|
|
2088
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
2089
|
+
await chmodPrivate(dir, 0o700);
|
|
2090
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
2091
|
+
const nonce = this.nonce();
|
|
2092
|
+
const path = join(dir, `${process.pid}-${nonce}.json`);
|
|
2093
|
+
const now = this.now();
|
|
2094
|
+
const lease: ReportLease = {
|
|
2095
|
+
version: REPORT_STORE_VERSION,
|
|
2096
|
+
pid: process.pid,
|
|
2097
|
+
nonce,
|
|
2098
|
+
rootSessionId: context.rootSessionId,
|
|
2099
|
+
...(context.rootSessionFile === undefined
|
|
2100
|
+
? {}
|
|
2101
|
+
: { rootSessionFile: context.rootSessionFile }),
|
|
2102
|
+
rootCwd: context.cwd,
|
|
2103
|
+
createdAt: now,
|
|
2104
|
+
updatedAt: now,
|
|
2105
|
+
own: true,
|
|
2106
|
+
};
|
|
2107
|
+
try {
|
|
2108
|
+
await writeFile(path, JSON.stringify(lease), { encoding: "utf8", flag: "wx", mode: 0o600 });
|
|
2109
|
+
await chmodPrivate(path, 0o600);
|
|
2110
|
+
return { nonce, path };
|
|
2111
|
+
} catch (error) {
|
|
2112
|
+
if (errorCode(error) !== "EEXIST") throw error;
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
throw new Error("could not allocate a unique report lease");
|
|
2116
|
+
}
|
|
2117
|
+
|
|
2118
|
+
private async removeLeaseFile(path: string): Promise<void> {
|
|
2119
|
+
try {
|
|
2120
|
+
await unlink(path);
|
|
2121
|
+
} catch (error) {
|
|
2122
|
+
if (!isNotFound(error)) this.diagnose(`lease cleanup failed: ${errorCode(error) ?? "unknown"}`);
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
|
|
2126
|
+
private async releaseActivation(): Promise<void> {
|
|
2127
|
+
const activation = this.activation;
|
|
2128
|
+
// Clear first: a failed bind/cleanup-lock refusal must never leave a stale
|
|
2129
|
+
// activation pointing at the previous root while context names the new one.
|
|
2130
|
+
this.activation = undefined;
|
|
2131
|
+
if (!activation?.leasePath) return;
|
|
2132
|
+
await this.removeLeaseFile(activation.leasePath);
|
|
2133
|
+
}
|
|
2134
|
+
|
|
2135
|
+
private validateContext(context: ReportContext): string | undefined {
|
|
2136
|
+
if (!isSafePathComponent(context.rootSessionId)) return "invalid-root-session-id";
|
|
2137
|
+
if (typeof context.cwd !== "string" || !isAbsolute(context.cwd)) return "invalid-cwd";
|
|
2138
|
+
if (context.rootSessionFile !== undefined && !isAbsolute(context.rootSessionFile)) {
|
|
2139
|
+
return "invalid-root-session-file";
|
|
2140
|
+
}
|
|
2141
|
+
return undefined;
|
|
2142
|
+
}
|
|
2143
|
+
|
|
2144
|
+
/**
|
|
2145
|
+
* Acquire-side exclusion: check the lock, create this activation's lease,
|
|
2146
|
+
* recheck the lock, and refuse artifact work if a cleanup acquired it in the
|
|
2147
|
+
* window. Reads remain available even when the binding is inactive.
|
|
2148
|
+
*/
|
|
2149
|
+
async bind(context: ReportContext): Promise<ReportBinding> {
|
|
2150
|
+
if (this.closed || this.closing) return { active: false, persistence: false, reason: "store-closed" };
|
|
2151
|
+
const invalid = this.validateContext(context);
|
|
2152
|
+
if (invalid) {
|
|
2153
|
+
this.diagnose(`bind refused: ${invalid}`);
|
|
2154
|
+
return { active: false, persistence: false, reason: invalid };
|
|
2155
|
+
}
|
|
2156
|
+
const drained = await this.flush();
|
|
2157
|
+
if (drained.status !== "flushed") {
|
|
2158
|
+
const reason = `flush-${drained.reason}`;
|
|
2159
|
+
this.diagnose(`bind refused: ${reason}`);
|
|
2160
|
+
return { active: false, persistence: false, reason };
|
|
2161
|
+
}
|
|
2162
|
+
await this.releaseActivation();
|
|
2163
|
+
this.context = {
|
|
2164
|
+
cwd: context.cwd,
|
|
2165
|
+
rootSessionId: context.rootSessionId,
|
|
2166
|
+
...(context.rootSessionFile === undefined ? {} : { rootSessionFile: context.rootSessionFile }),
|
|
2167
|
+
...(context.persistReports === undefined ? {} : { persistReports: context.persistReports }),
|
|
2168
|
+
};
|
|
2169
|
+
if (context.persistReports === false) {
|
|
2170
|
+
this.activation = { persistence: false };
|
|
2171
|
+
return {
|
|
2172
|
+
active: true,
|
|
2173
|
+
persistence: false,
|
|
2174
|
+
rootSessionId: context.rootSessionId,
|
|
2175
|
+
};
|
|
2176
|
+
}
|
|
2177
|
+
try {
|
|
2178
|
+
const rootDir = await this.ensureRootDirectory(context.rootSessionId);
|
|
2179
|
+
const before = await this.readCleanupLockRead(context.rootSessionId);
|
|
2180
|
+
if (before.status === "live" || before.status === "uncertain") {
|
|
2181
|
+
this.diagnose(`bind refused: cleanup lock ${before.status}`);
|
|
2182
|
+
return {
|
|
2183
|
+
active: false,
|
|
2184
|
+
persistence: false,
|
|
2185
|
+
rootSessionId: context.rootSessionId,
|
|
2186
|
+
reason: before.status === "live" ? "cleanup-lock" : "cleanup-lock-unreadable",
|
|
2187
|
+
};
|
|
2188
|
+
}
|
|
2189
|
+
const lease = await this.createLease(rootDir, context);
|
|
2190
|
+
const after = await this.readCleanupLockRead(context.rootSessionId);
|
|
2191
|
+
if (after.status === "live" || after.status === "uncertain") {
|
|
2192
|
+
await this.removeLeaseFile(lease.path);
|
|
2193
|
+
this.diagnose(`bind refused: cleanup lock ${after.status} appeared`);
|
|
2194
|
+
return {
|
|
2195
|
+
active: false,
|
|
2196
|
+
persistence: false,
|
|
2197
|
+
rootSessionId: context.rootSessionId,
|
|
2198
|
+
reason: after.status === "live" ? "cleanup-lock" : "cleanup-lock-unreadable",
|
|
2199
|
+
};
|
|
2200
|
+
}
|
|
2201
|
+
this.activation = {
|
|
2202
|
+
persistence: true,
|
|
2203
|
+
leaseId: lease.nonce,
|
|
2204
|
+
leasePath: lease.path,
|
|
2205
|
+
rootDir,
|
|
2206
|
+
};
|
|
2207
|
+
// The minimal main-session identity must outlive this activation's lease: a
|
|
2208
|
+
// child history opened as another root's main conversation has to stay
|
|
2209
|
+
// provable after close and after an empty-root metadata cleanup.
|
|
2210
|
+
const keeper = await this.ensureMainIdentityKeeper(rootDir, context);
|
|
2211
|
+
if (!keeper.ok) {
|
|
2212
|
+
this.diagnose(`bind refused: ${keeper.reason}`);
|
|
2213
|
+
await this.releaseActivation();
|
|
2214
|
+
return {
|
|
2215
|
+
active: false,
|
|
2216
|
+
persistence: false,
|
|
2217
|
+
rootSessionId: context.rootSessionId,
|
|
2218
|
+
reason: keeper.reason,
|
|
2219
|
+
};
|
|
2220
|
+
}
|
|
2221
|
+
await this.expireRoot(context.rootSessionId);
|
|
2222
|
+
return {
|
|
2223
|
+
active: true,
|
|
2224
|
+
persistence: true,
|
|
2225
|
+
rootSessionId: context.rootSessionId,
|
|
2226
|
+
leaseId: lease.nonce,
|
|
2227
|
+
};
|
|
2228
|
+
} catch (error) {
|
|
2229
|
+
// Every exceptional exit after lease creation must drop the activation and
|
|
2230
|
+
// release its lease: an inactive binding must never keep writing protection.
|
|
2231
|
+
await this.releaseActivation();
|
|
2232
|
+
this.diagnose(`bind failed: ${errorCode(error) ?? "error"}`);
|
|
2233
|
+
return {
|
|
2234
|
+
active: false,
|
|
2235
|
+
persistence: false,
|
|
2236
|
+
rootSessionId: context.rootSessionId,
|
|
2237
|
+
reason: `storage-error:${errorCode(error) ?? "unknown"}`,
|
|
2238
|
+
};
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
|
|
2242
|
+
get bindingContext(): ReportContext | undefined {
|
|
2243
|
+
return this.context;
|
|
2244
|
+
}
|
|
2245
|
+
|
|
2246
|
+
/**
|
|
2247
|
+
* Stop accepting new writes BEFORE draining accepted ones. Releases the lease
|
|
2248
|
+
* only when the caller proved quiescence and the bounded drain completed.
|
|
2249
|
+
* Concurrent/repeated close calls share the same outcome.
|
|
2250
|
+
*/
|
|
2251
|
+
close(options: { quiescent?: boolean } = {}): Promise<ReportFlushResult> {
|
|
2252
|
+
if (this.closePromise) return this.closePromise;
|
|
2253
|
+
this.closing = true;
|
|
2254
|
+
this.closePromise = this.finishClose(options);
|
|
2255
|
+
return this.closePromise;
|
|
2256
|
+
}
|
|
2257
|
+
|
|
2258
|
+
private async finishClose(options: { quiescent?: boolean }): Promise<ReportFlushResult> {
|
|
2259
|
+
const drained = await this.flush();
|
|
2260
|
+
if (options.quiescent === true && drained.status === "flushed") {
|
|
2261
|
+
await this.releaseActivation();
|
|
2262
|
+
} else if (this.activation?.leasePath) {
|
|
2263
|
+
// Keep the lease: an uncertain teardown must remain protected.
|
|
2264
|
+
this.diagnose(`lease retained: ${drained.status === "flushed" ? "quiescence not proven" : `flush ${drained.reason}`}`);
|
|
2265
|
+
}
|
|
2266
|
+
this.activation = undefined;
|
|
2267
|
+
this.closed = true;
|
|
2268
|
+
return drained;
|
|
2269
|
+
}
|
|
2270
|
+
|
|
2271
|
+
get isClosed(): boolean {
|
|
2272
|
+
return this.closed || this.closing;
|
|
2273
|
+
}
|
|
2274
|
+
|
|
2275
|
+
private selectionMatches(selection: CleanupSelection, scope: ReportArtifactScope): boolean {
|
|
2276
|
+
const sessionFiles = scope.sessionFiles ?? [];
|
|
2277
|
+
if (scope.agentId === undefined && sessionFiles.length === 0) return true;
|
|
2278
|
+
if (scope.agentId !== undefined && selection.agentIds.includes(scope.agentId)) return true;
|
|
2279
|
+
if (sessionFiles.length === 0) return false;
|
|
2280
|
+
const keys = new Set(sessionFiles.map((path) => pathKey(path)));
|
|
2281
|
+
return selection.sessionFiles.some((path) => keys.has(pathKey(path)));
|
|
2282
|
+
}
|
|
2283
|
+
|
|
2284
|
+
private localLockCleans(scope: ReportArtifactScope): boolean {
|
|
2285
|
+
for (const [rootSessionId, handle] of this.cleanupLocks) {
|
|
2286
|
+
if (this.localMaintenanceExempt(rootSessionId, handle.nonce)) continue;
|
|
2287
|
+
if (this.selectionMatches(handle.selection, scope)) return true;
|
|
2288
|
+
}
|
|
2289
|
+
return false;
|
|
2290
|
+
}
|
|
2291
|
+
|
|
2292
|
+
/**
|
|
2293
|
+
* Combined sync cleanup scan: local selections first, then every root's lock in
|
|
2294
|
+
* ONE listing. A verified non-directory stray cannot hold a lock and is
|
|
2295
|
+
* ignored; a symlink/unknown entry or unreadable listing/metadata fails
|
|
2296
|
+
* closed. The maintenance exemption applies only to this store's exact nonce.
|
|
2297
|
+
*/
|
|
2298
|
+
isCleaningAny(scope: ReportArtifactScope): boolean {
|
|
2299
|
+
if (this.localLockCleans(scope)) return true;
|
|
2300
|
+
const root = this.storage().reportsRoot;
|
|
2301
|
+
let entries: Dirent[];
|
|
2302
|
+
try {
|
|
2303
|
+
entries = readdirSync(root, { withFileTypes: true });
|
|
2304
|
+
} catch (error) {
|
|
2305
|
+
if (isNotFound(error)) return false;
|
|
2306
|
+
this.diagnose(`reports root scan failed: ${errorCode(error) ?? "unknown"}`);
|
|
2307
|
+
return true;
|
|
2308
|
+
}
|
|
2309
|
+
for (const entry of [...entries].sort((a, b) => a.name.localeCompare(b.name))) {
|
|
2310
|
+
if (entry.isSymbolicLink()) {
|
|
2311
|
+
this.diagnose(`reports root entry is a link; refusing to follow: ${entry.name}`);
|
|
2312
|
+
return true;
|
|
2313
|
+
}
|
|
2314
|
+
if (!entry.isDirectory()) {
|
|
2315
|
+
if (entry.isFile()) continue;
|
|
2316
|
+
this.diagnose(`reports root entry type is unknown: ${entry.name}`);
|
|
2317
|
+
return true;
|
|
2318
|
+
}
|
|
2319
|
+
if (!isSafePathComponent(entry.name)) {
|
|
2320
|
+
this.diagnose(`unsafe root entry name: ${entry.name}`);
|
|
2321
|
+
return true;
|
|
2322
|
+
}
|
|
2323
|
+
const read = this.readCleanupLockReadSync(entry.name);
|
|
2324
|
+
// Uncertain metadata could select anything; fail closed.
|
|
2325
|
+
if (read.status === "uncertain") return true;
|
|
2326
|
+
if (read.status !== "live" || read.lock === undefined) continue;
|
|
2327
|
+
if (this.maintenanceExempt(entry.name, read.lock)) continue;
|
|
2328
|
+
if (this.selectionMatches(read.lock, scope)) return true;
|
|
2329
|
+
}
|
|
2330
|
+
return false;
|
|
2331
|
+
}
|
|
2332
|
+
|
|
2333
|
+
/**
|
|
2334
|
+
* Awaited form of `isCleaningAny`: bounded async filesystem work only (one
|
|
2335
|
+
* listing plus at most one lock read per root) and a fresh read on every call,
|
|
2336
|
+
* so no negative/positive result is cached across a cleanup window.
|
|
2337
|
+
*/
|
|
2338
|
+
async isCleaningAnyAsync(scope: ReportArtifactScope): Promise<boolean> {
|
|
2339
|
+
if (this.localLockCleans(scope)) return true;
|
|
2340
|
+
const root = this.storage().reportsRoot;
|
|
2341
|
+
let entries: Dirent[];
|
|
2342
|
+
try {
|
|
2343
|
+
entries = await readdir(root, { withFileTypes: true });
|
|
2344
|
+
} catch (error) {
|
|
2345
|
+
if (isNotFound(error)) return this.localLockCleans(scope);
|
|
2346
|
+
this.diagnose(`reports root scan failed: ${errorCode(error) ?? "unknown"}`);
|
|
2347
|
+
return true;
|
|
2348
|
+
}
|
|
2349
|
+
for (const entry of [...entries].sort((a, b) => a.name.localeCompare(b.name))) {
|
|
2350
|
+
if (entry.isSymbolicLink()) {
|
|
2351
|
+
this.diagnose(`reports root entry is a link; refusing to follow: ${entry.name}`);
|
|
2352
|
+
return true;
|
|
2353
|
+
}
|
|
2354
|
+
if (!entry.isDirectory()) {
|
|
2355
|
+
if (entry.isFile()) continue;
|
|
2356
|
+
this.diagnose(`reports root entry type is unknown: ${entry.name}`);
|
|
2357
|
+
return true;
|
|
2358
|
+
}
|
|
2359
|
+
if (!isSafePathComponent(entry.name)) {
|
|
2360
|
+
this.diagnose(`unsafe root entry name: ${entry.name}`);
|
|
2361
|
+
return true;
|
|
2362
|
+
}
|
|
2363
|
+
const read = await this.readCleanupLockRead(entry.name);
|
|
2364
|
+
if (read.status === "uncertain") return true;
|
|
2365
|
+
if (read.status !== "live" || read.lock === undefined) continue;
|
|
2366
|
+
if (this.maintenanceExempt(entry.name, read.lock)) continue;
|
|
2367
|
+
if (this.selectionMatches(read.lock, scope)) return true;
|
|
2368
|
+
}
|
|
2369
|
+
// A cleanup lock this store acquired while the scan was awaiting is live
|
|
2370
|
+
// even though the listing/read that preceded it saw the root idle.
|
|
2371
|
+
return this.localLockCleans(scope);
|
|
2372
|
+
}
|
|
2373
|
+
|
|
2374
|
+
/** Refuse artifact work while cleanup holds a lock for this id/session. */
|
|
2375
|
+
isCleaning(agentId?: string, sessionFile?: string): boolean {
|
|
2376
|
+
return this.isCleaningAny({
|
|
2377
|
+
...(agentId === undefined ? {} : { agentId }),
|
|
2378
|
+
...(sessionFile === undefined ? {} : { sessionFiles: [sessionFile] }),
|
|
2379
|
+
});
|
|
2380
|
+
}
|
|
2381
|
+
|
|
2382
|
+
/** Sync combined-scope refusal; see `isCleaningAny`. */
|
|
2383
|
+
assertAvailableAny(scope: ReportArtifactScope): void {
|
|
2384
|
+
if (this.closed || this.closing) throw new ReportUnavailableError("store-closed");
|
|
2385
|
+
if (this.isCleaningAny(scope)) throw new ReportUnavailableError("cleanup-lock");
|
|
2386
|
+
}
|
|
2387
|
+
|
|
2388
|
+
/** Async combined-scope refusal; see `isCleaningAnyAsync`. */
|
|
2389
|
+
async assertAvailableAnyAsync(scope: ReportArtifactScope): Promise<void> {
|
|
2390
|
+
if (this.closed || this.closing) throw new ReportUnavailableError("store-closed");
|
|
2391
|
+
if (await this.isCleaningAnyAsync(scope)) throw new ReportUnavailableError("cleanup-lock");
|
|
2392
|
+
// The scan awaited: a close that happened meanwhile revokes the answer.
|
|
2393
|
+
if (this.closed || this.closing) throw new ReportUnavailableError("store-closed");
|
|
2394
|
+
}
|
|
2395
|
+
|
|
2396
|
+
/**
|
|
2397
|
+
* Barrier used by spawn/resume/read acquisition and by selected cleanup:
|
|
2398
|
+
* a no-argument call checks this activation against the root lock; with an
|
|
2399
|
+
* id/session file it checks every root lock's selection.
|
|
2400
|
+
*/
|
|
2401
|
+
assertAvailable(agentId?: string, sessionFile?: string): void {
|
|
2402
|
+
if (this.closed || this.closing) throw new ReportUnavailableError("store-closed");
|
|
2403
|
+
if (agentId === undefined && sessionFile === undefined) {
|
|
2404
|
+
if (!this.activation) throw new ReportUnavailableError("inactive-activation");
|
|
2405
|
+
const rootSessionId = this.context?.rootSessionId;
|
|
2406
|
+
if (rootSessionId && this.activation.persistence) {
|
|
2407
|
+
const read = this.readCleanupLockReadSync(rootSessionId);
|
|
2408
|
+
if (read.status === "uncertain") {
|
|
2409
|
+
throw new ReportUnavailableError("cleanup-lock-unreadable");
|
|
2410
|
+
}
|
|
2411
|
+
if (read.status === "live" && !this.maintenanceExempt(rootSessionId, read.lock)) {
|
|
2412
|
+
throw new ReportUnavailableError("cleanup-lock");
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
return;
|
|
2416
|
+
}
|
|
2417
|
+
this.assertAvailableAny({
|
|
2418
|
+
...(agentId === undefined ? {} : { agentId }),
|
|
2419
|
+
...(sessionFile === undefined ? {} : { sessionFiles: [sessionFile] }),
|
|
2420
|
+
});
|
|
2421
|
+
}
|
|
2422
|
+
|
|
2423
|
+
/**
|
|
2424
|
+
* Awaited no-argument barrier with the same own-activation/own-root contract as
|
|
2425
|
+
* `assertAvailable()`: no synchronous filesystem read, so a caller that has
|
|
2426
|
+
* already suspended never blocks the main thread on its own root's lock.
|
|
2427
|
+
*/
|
|
2428
|
+
async assertAvailableAsync(): Promise<void> {
|
|
2429
|
+
if (this.closed || this.closing) throw new ReportUnavailableError("store-closed");
|
|
2430
|
+
const activation = this.activation;
|
|
2431
|
+
if (!activation) throw new ReportUnavailableError("inactive-activation");
|
|
2432
|
+
const rootSessionId = this.context?.rootSessionId;
|
|
2433
|
+
if (!rootSessionId || !activation.persistence) return;
|
|
2434
|
+
const read = await this.readCleanupLockRead(rootSessionId);
|
|
2435
|
+
// The read awaited: only the activation that started it may be authorized.
|
|
2436
|
+
// A close, rebind or lost activation in that window makes this answer stale.
|
|
2437
|
+
if (this.closed || this.closing) throw new ReportUnavailableError("store-closed");
|
|
2438
|
+
if (this.activation !== activation || this.context?.rootSessionId !== rootSessionId) {
|
|
2439
|
+
throw new ReportUnavailableError("inactive-activation");
|
|
2440
|
+
}
|
|
2441
|
+
if (read.status === "uncertain") {
|
|
2442
|
+
throw new ReportUnavailableError("cleanup-lock-unreadable");
|
|
2443
|
+
}
|
|
2444
|
+
if (read.status === "live" && !this.maintenanceExempt(rootSessionId, read.lock)) {
|
|
2445
|
+
throw new ReportUnavailableError("cleanup-lock");
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2448
|
+
|
|
2449
|
+
/** Persist one settled generation. Snapshot is captured before the first await. */
|
|
2450
|
+
async save(record: AgentRecord): Promise<ReportSaveResult> {
|
|
2451
|
+
if (this.closed || this.closing) return { saved: false, reason: "store-closed" };
|
|
2452
|
+
const context = this.context;
|
|
2453
|
+
if (!context || !this.activation) return { saved: false, reason: "not-bound" };
|
|
2454
|
+
if (!this.activation.persistence) return { saved: false, reason: "persist-disabled" };
|
|
2455
|
+
if (!isTerminalAgentStatus(record.status)) return { saved: false, reason: "not-terminal" };
|
|
2456
|
+
let snapshot: ReportSnapshot | undefined;
|
|
2457
|
+
try {
|
|
2458
|
+
// Capture synchronously, before the first await, so a settled record cannot
|
|
2459
|
+
// be mutated (or its session disposed) under the snapshot.
|
|
2460
|
+
snapshot = captureReportSnapshot(record, context, this.now());
|
|
2461
|
+
} catch (error) {
|
|
2462
|
+
this.diagnose(`snapshot failed for ${record.id}: ${errorCode(error) ?? "error"}`);
|
|
2463
|
+
return { saved: false, reason: "snapshot-failed" };
|
|
2464
|
+
}
|
|
2465
|
+
if (!snapshot) return { saved: false, reason: "invalid-snapshot" };
|
|
2466
|
+
if (!this.activation.rootDir) return { saved: false, reason: "root-unavailable" };
|
|
2467
|
+
const rootDir = this.activation.rootDir;
|
|
2468
|
+
const rootSessionId = context.rootSessionId;
|
|
2469
|
+
return this.enqueue(rootDir, async () => {
|
|
2470
|
+
if (this.closed) return { saved: false, reason: "store-closed" };
|
|
2471
|
+
const block = await this.writeBlockReason(rootSessionId);
|
|
2472
|
+
if (block) {
|
|
2473
|
+
this.diagnose(`save skipped for ${snapshot.id}: ${block}`);
|
|
2474
|
+
return { saved: false, reason: block };
|
|
2475
|
+
}
|
|
2476
|
+
try {
|
|
2477
|
+
const agentsDir = join(rootDir, "agents");
|
|
2478
|
+
await mkdir(agentsDir, { recursive: true, mode: 0o700 });
|
|
2479
|
+
await chmodPrivate(agentsDir, 0o700);
|
|
2480
|
+
const path = join(agentsDir, `${snapshot.id}.json`);
|
|
2481
|
+
const existing = await this.readJson(path, parseReportEntry);
|
|
2482
|
+
if (existing?.state === "deleted") {
|
|
2483
|
+
this.diagnose(`save skipped for ${snapshot.id}: deletion receipt present`);
|
|
2484
|
+
return { saved: false, reason: "deleted-receipt" };
|
|
2485
|
+
}
|
|
2486
|
+
const now = this.now();
|
|
2487
|
+
const ownerIds = snapshot.ownerIds;
|
|
2488
|
+
const entry: FullReportEntry = {
|
|
2489
|
+
version: REPORT_STORE_VERSION,
|
|
2490
|
+
id: snapshot.id,
|
|
2491
|
+
entryGeneration: (existing?.entryGeneration ?? 0) + 1,
|
|
2492
|
+
createdAt: existing?.createdAt ?? now,
|
|
2493
|
+
updatedAt: now,
|
|
2494
|
+
completedAt: snapshot.completedAt ?? now,
|
|
2495
|
+
rootSessionId,
|
|
2496
|
+
rootCwd: context.cwd,
|
|
2497
|
+
...(context.rootSessionFile === undefined
|
|
2498
|
+
? {}
|
|
2499
|
+
: { rootSessionFile: context.rootSessionFile }),
|
|
2500
|
+
type: snapshot.type,
|
|
2501
|
+
description: snapshot.description,
|
|
2502
|
+
...(snapshot.handle === undefined ? {} : { handle: snapshot.handle }),
|
|
2503
|
+
...(snapshot.alias === undefined ? {} : { alias: snapshot.alias }),
|
|
2504
|
+
...(snapshot.parentAgentId === undefined ? {} : { parentAgentId: snapshot.parentAgentId }),
|
|
2505
|
+
...(snapshot.workflowId === undefined ? {} : { workflowId: snapshot.workflowId }),
|
|
2506
|
+
ownerIds,
|
|
2507
|
+
...(snapshot.sessionFile === undefined ? {} : { sessionFile: snapshot.sessionFile }),
|
|
2508
|
+
...(snapshot.sessionId === undefined ? {} : { sessionId: snapshot.sessionId }),
|
|
2509
|
+
...(snapshot.outputFile === undefined ? {} : { outputFile: snapshot.outputFile }),
|
|
2510
|
+
...(snapshot.runGeneration === undefined ? {} : { runGeneration: snapshot.runGeneration }),
|
|
2511
|
+
state: "full",
|
|
2512
|
+
report: snapshot,
|
|
2513
|
+
};
|
|
2514
|
+
const block = await this.writeBlockReason(rootSessionId);
|
|
2515
|
+
if (block) return { saved: false, reason: block };
|
|
2516
|
+
await atomicWriteJson(path, entry, this.nonce());
|
|
2517
|
+
await this.bumpGenerationLocked(rootDir, rootSessionId, context);
|
|
2518
|
+
await this.maybeMaintainRootLocked(rootSessionId, rootDir, context);
|
|
2519
|
+
return { saved: true, path, entry };
|
|
2520
|
+
} catch (error) {
|
|
2521
|
+
this.diagnose(`save failed for ${snapshot.id}: ${errorCode(error) ?? "error"}`);
|
|
2522
|
+
return { saved: false, reason: `write-failed:${errorCode(error) ?? "unknown"}` };
|
|
2523
|
+
}
|
|
2524
|
+
});
|
|
2525
|
+
}
|
|
2526
|
+
|
|
2527
|
+
/**
|
|
2528
|
+
* Register a workflow's exact generated artifacts at creation and settlement,
|
|
2529
|
+
* independently of how many agents it eventually runs (zero included). The
|
|
2530
|
+
* caller captures inline copies before a saved/external scriptPath can replace
|
|
2531
|
+
* them; external paths are provenance only and never deletion candidates.
|
|
2532
|
+
*/
|
|
2533
|
+
async registerWorkflow(registration: WorkflowArtifactRegistration): Promise<ReportSaveResult> {
|
|
2534
|
+
if (this.closed || this.closing) return { saved: false, reason: "store-closed" };
|
|
2535
|
+
const context = this.context;
|
|
2536
|
+
if (!context || !this.activation) return { saved: false, reason: "not-bound" };
|
|
2537
|
+
if (!this.activation.persistence) return { saved: false, reason: "persist-disabled" };
|
|
2538
|
+
if (!isSafePathComponent(registration.id)) return { saved: false, reason: "invalid-workflow-id" };
|
|
2539
|
+
const rootDir = this.activation.rootDir;
|
|
2540
|
+
if (!rootDir) return { saved: false, reason: "root-unavailable" };
|
|
2541
|
+
const rootSessionId = context.rootSessionId;
|
|
2542
|
+
const generatedPaths = [...new Set(registration.generatedPaths.map((path) => resolve(path)))];
|
|
2543
|
+
const externalPaths = [...new Set((registration.externalPaths ?? []).map((path) => resolve(path)))];
|
|
2544
|
+
return this.enqueue(rootDir, async () => {
|
|
2545
|
+
const block = await this.writeBlockReason(rootSessionId);
|
|
2546
|
+
if (block) return { saved: false, reason: block };
|
|
2547
|
+
try {
|
|
2548
|
+
const dir = join(rootDir, "workflows");
|
|
2549
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
2550
|
+
await chmodPrivate(dir, 0o700);
|
|
2551
|
+
const path = join(dir, `${registration.id}.json`);
|
|
2552
|
+
const now = this.now();
|
|
2553
|
+
const entry: WorkflowArtifactEntry = {
|
|
2554
|
+
version: REPORT_STORE_VERSION,
|
|
2555
|
+
id: registration.id,
|
|
2556
|
+
generatedPaths,
|
|
2557
|
+
externalPaths,
|
|
2558
|
+
status: registration.status,
|
|
2559
|
+
startedAt: registration.startedAt,
|
|
2560
|
+
...(registration.completedAt === undefined
|
|
2561
|
+
? {}
|
|
2562
|
+
: { completedAt: registration.completedAt }),
|
|
2563
|
+
rootSessionId,
|
|
2564
|
+
rootCwd: context.cwd,
|
|
2565
|
+
...(context.rootSessionFile === undefined
|
|
2566
|
+
? {}
|
|
2567
|
+
: { rootSessionFile: context.rootSessionFile }),
|
|
2568
|
+
updatedAt: now,
|
|
2569
|
+
};
|
|
2570
|
+
const lateBlock = await this.writeBlockReason(rootSessionId);
|
|
2571
|
+
if (lateBlock) return { saved: false, reason: lateBlock };
|
|
2572
|
+
await atomicWriteJson(path, entry, this.nonce());
|
|
2573
|
+
await this.bumpGenerationLocked(rootDir, rootSessionId, context);
|
|
2574
|
+
return { saved: true, path, entry };
|
|
2575
|
+
} catch (error) {
|
|
2576
|
+
return { saved: false, reason: `write-failed:${errorCode(error) ?? "unknown"}` };
|
|
2577
|
+
}
|
|
2578
|
+
});
|
|
2579
|
+
}
|
|
2580
|
+
|
|
2581
|
+
private async readRootState(rootSessionId: string): Promise<ReportRootState | undefined> {
|
|
2582
|
+
return (await this.readRootStateScan(rootSessionId)).state;
|
|
2583
|
+
}
|
|
2584
|
+
|
|
2585
|
+
/**
|
|
2586
|
+
* One root state plus the first reason any part of it could not be read. The
|
|
2587
|
+
* cleanup identity inventory never treats a partial read as "nothing here".
|
|
2588
|
+
*/
|
|
2589
|
+
private async readRootStateScan(
|
|
2590
|
+
rootSessionId: string,
|
|
2591
|
+
options: { vanishedIsUncertain?: boolean } = {},
|
|
2592
|
+
): Promise<{ state?: ReportRootState; uncertainty?: string }> {
|
|
2593
|
+
const rootScan = await this.existingRootDirectoryScan(rootSessionId, options);
|
|
2594
|
+
const rootDir = rootScan.rootDir;
|
|
2595
|
+
if (!rootDir) {
|
|
2596
|
+
return rootScan.uncertainty === undefined ? {} : { uncertainty: rootScan.uncertainty };
|
|
2597
|
+
}
|
|
2598
|
+
let uncertainty = rootScan.uncertainty;
|
|
2599
|
+
const rootJson = await this.readJsonScan(
|
|
2600
|
+
join(rootDir, "root.json"),
|
|
2601
|
+
"root-metadata",
|
|
2602
|
+
(value) => parseRootMetadata(value, rootSessionId),
|
|
2603
|
+
);
|
|
2604
|
+
uncertainty ??= rootJson.uncertainty;
|
|
2605
|
+
const metadata = rootJson.value;
|
|
2606
|
+
const reportEntries: ReportEntry[] = [];
|
|
2607
|
+
const agentsDir = join(rootDir, "agents");
|
|
2608
|
+
let agentNames: string[];
|
|
2609
|
+
try {
|
|
2610
|
+
agentNames = await readdir(agentsDir);
|
|
2611
|
+
} catch (error) {
|
|
2612
|
+
if (!isNotFound(error)) {
|
|
2613
|
+
this.diagnose(`agents dir unreadable: ${errorCode(error) ?? "unknown"}`);
|
|
2614
|
+
uncertainty ??= "agents-directory-unreadable";
|
|
2615
|
+
}
|
|
2616
|
+
agentNames = [];
|
|
2617
|
+
}
|
|
2618
|
+
for (const name of agentNames.sort()) {
|
|
2619
|
+
if (!name.endsWith(".json")) continue;
|
|
2620
|
+
const scan = await this.readJsonScan(
|
|
2621
|
+
join(agentsDir, name),
|
|
2622
|
+
"report-entry",
|
|
2623
|
+
parseReportEntry,
|
|
2624
|
+
);
|
|
2625
|
+
uncertainty ??= scan.uncertainty;
|
|
2626
|
+
if (scan.value) reportEntries.push(scan.value);
|
|
2627
|
+
}
|
|
2628
|
+
const workflows: WorkflowArtifactEntry[] = [];
|
|
2629
|
+
const workflowsDir = join(rootDir, "workflows");
|
|
2630
|
+
let workflowNames: string[];
|
|
2631
|
+
try {
|
|
2632
|
+
workflowNames = await readdir(workflowsDir);
|
|
2633
|
+
} catch (error) {
|
|
2634
|
+
if (!isNotFound(error)) {
|
|
2635
|
+
this.diagnose(`workflows dir unreadable: ${errorCode(error) ?? "unknown"}`);
|
|
2636
|
+
uncertainty ??= "workflows-directory-unreadable";
|
|
2637
|
+
}
|
|
2638
|
+
workflowNames = [];
|
|
2639
|
+
}
|
|
2640
|
+
for (const name of workflowNames.sort()) {
|
|
2641
|
+
if (!name.endsWith(".json")) continue;
|
|
2642
|
+
const scan = await this.readJsonScan(
|
|
2643
|
+
join(workflowsDir, name),
|
|
2644
|
+
"workflow-entry",
|
|
2645
|
+
parseWorkflowEntry,
|
|
2646
|
+
);
|
|
2647
|
+
uncertainty ??= scan.uncertainty;
|
|
2648
|
+
if (scan.value) workflows.push(scan.value);
|
|
2649
|
+
}
|
|
2650
|
+
reportEntries.sort((a, b) => b.completedAt - a.completedAt || a.id.localeCompare(b.id));
|
|
2651
|
+
workflows.sort((a, b) => a.id.localeCompare(b.id));
|
|
2652
|
+
const scan = await this.scanLeaseFiles(rootSessionId, rootDir);
|
|
2653
|
+
uncertainty ??= scan.uncertainty;
|
|
2654
|
+
const lockRead = await this.readCleanupLockRead(rootSessionId);
|
|
2655
|
+
const state: ReportRootState = {
|
|
2656
|
+
rootSessionId,
|
|
2657
|
+
rootDir,
|
|
2658
|
+
...(metadata?.rootCwd === undefined ? {} : { rootCwd: metadata.rootCwd }),
|
|
2659
|
+
...(metadata?.rootSessionFile === undefined
|
|
2660
|
+
? {}
|
|
2661
|
+
: { rootSessionFile: metadata.rootSessionFile }),
|
|
2662
|
+
generation: metadata?.generation ?? 0,
|
|
2663
|
+
metadataPresent: metadata !== undefined,
|
|
2664
|
+
reportEntries,
|
|
2665
|
+
workflows,
|
|
2666
|
+
leases: scan.leases,
|
|
2667
|
+
cleanupLockState: lockRead.status,
|
|
2668
|
+
...(lockRead.status === "live" && lockRead.lock !== undefined
|
|
2669
|
+
? { cleanupLock: lockRead.lock }
|
|
2670
|
+
: {}),
|
|
2671
|
+
...(lockRead.reason === undefined ? {} : { cleanupLockReason: lockRead.reason }),
|
|
2672
|
+
...(scan.uncertainty === undefined ? {} : { leasesUncertain: scan.uncertainty }),
|
|
2673
|
+
};
|
|
2674
|
+
return uncertainty === undefined ? { state } : { state, uncertainty };
|
|
2675
|
+
}
|
|
2676
|
+
|
|
2677
|
+
private async enumerateRootIds(): Promise<string[]> {
|
|
2678
|
+
return (await this.enumerateRootIdsScan()).ids;
|
|
2679
|
+
}
|
|
2680
|
+
|
|
2681
|
+
/** Enumeration that reports a partial listing instead of returning "no roots". */
|
|
2682
|
+
private async enumerateRootIdsScan(): Promise<{ ids: string[]; uncertainty?: string }> {
|
|
2683
|
+
let root: string;
|
|
2684
|
+
try {
|
|
2685
|
+
root = await realpath(this.storage().reportsRoot);
|
|
2686
|
+
const info = await lstat(root);
|
|
2687
|
+
if (!info.isDirectory()) return { ids: [], uncertainty: "reports-root-not-a-directory" };
|
|
2688
|
+
} catch (error) {
|
|
2689
|
+
if (isNotFound(error)) return { ids: [] };
|
|
2690
|
+
this.diagnose(`reports root unreadable: ${errorCode(error) ?? "unknown"}`);
|
|
2691
|
+
return { ids: [], uncertainty: "reports-root-unreadable" };
|
|
2692
|
+
}
|
|
2693
|
+
let names: string[];
|
|
2694
|
+
try {
|
|
2695
|
+
names = await readdir(root);
|
|
2696
|
+
} catch (error) {
|
|
2697
|
+
this.diagnose(`reports root list failed: ${errorCode(error) ?? "unknown"}`);
|
|
2698
|
+
return { ids: [], uncertainty: "reports-root-list-failed" };
|
|
2699
|
+
}
|
|
2700
|
+
const ids: string[] = [];
|
|
2701
|
+
let uncertainty: string | undefined;
|
|
2702
|
+
for (const name of names.sort()) {
|
|
2703
|
+
const safeName = isSafePathComponent(name);
|
|
2704
|
+
// A listing basename is inspected before the safe-name filter: a name we
|
|
2705
|
+
// would never enumerate can still be a directory, junction or link that
|
|
2706
|
+
// hides a main-session identity. lstat never follows the entry itself,
|
|
2707
|
+
// and native basenames cannot contain a path separator.
|
|
2708
|
+
let info: Stats;
|
|
2709
|
+
try {
|
|
2710
|
+
info = await lstat(join(root, name));
|
|
2711
|
+
} catch (error) {
|
|
2712
|
+
if (isNotFound(error)) {
|
|
2713
|
+
// The entry was listed a moment ago: it may be a root that vanished.
|
|
2714
|
+
uncertainty ??= "root-entry-vanished";
|
|
2715
|
+
} else {
|
|
2716
|
+
this.diagnose(`root entry stat failed: ${errorCode(error) ?? "unknown"}`);
|
|
2717
|
+
uncertainty ??= "root-entry-stat-failed";
|
|
2718
|
+
}
|
|
2719
|
+
continue;
|
|
2720
|
+
}
|
|
2721
|
+
if (!safeName) {
|
|
2722
|
+
// An unsafe-named regular file cannot be a report root directory, so it
|
|
2723
|
+
// stays harmlessly ignored. Any other unsafe-named entry is a skipped
|
|
2724
|
+
// identity candidate: partial inventory, never followed.
|
|
2725
|
+
if (!info.isFile()) uncertainty ??= "root-entry-unsafe-name";
|
|
2726
|
+
continue;
|
|
2727
|
+
}
|
|
2728
|
+
if (info.isDirectory() && !info.isSymbolicLink()) ids.push(name);
|
|
2729
|
+
// Anything else (link, junction, regular file) is not a root we may
|
|
2730
|
+
// enumerate: it is skipped, but a skipped entry could hide a main
|
|
2731
|
+
// session identity, so the inventory is explicitly partial. Links are
|
|
2732
|
+
// never followed.
|
|
2733
|
+
else uncertainty ??= "root-entry-unsafe";
|
|
2734
|
+
}
|
|
2735
|
+
return uncertainty === undefined ? { ids } : { ids, uncertainty };
|
|
2736
|
+
}
|
|
2737
|
+
|
|
2738
|
+
/**
|
|
2739
|
+
* Strict global identity inventory for cleanup: complete, or an explicit
|
|
2740
|
+
* reason why a root's main-session identity may be missing.
|
|
2741
|
+
*/
|
|
2742
|
+
async scanRootIdentities(): Promise<ReportIdentityScan> {
|
|
2743
|
+
const enumeration = await this.enumerateRootIdsScan();
|
|
2744
|
+
const states: ReportRootState[] = [];
|
|
2745
|
+
let uncertainty = enumeration.uncertainty;
|
|
2746
|
+
for (const rootSessionId of enumeration.ids) {
|
|
2747
|
+
// The id came from this scan's own listing: if its directory or the base
|
|
2748
|
+
// reports root vanished before this lookup, that is partial evidence.
|
|
2749
|
+
const scan = await this.readRootStateScan(rootSessionId, { vanishedIsUncertain: true });
|
|
2750
|
+
if (scan.state) states.push(scan.state);
|
|
2751
|
+
uncertainty ??= scan.uncertainty;
|
|
2752
|
+
}
|
|
2753
|
+
return uncertainty === undefined ? { states } : { states, uncertainty };
|
|
2754
|
+
}
|
|
2755
|
+
|
|
2756
|
+
async list(scope: CleanupScope, previewRootSessionId?: string): Promise<ReportRootState[]> {
|
|
2757
|
+
if (scope === "session") {
|
|
2758
|
+
const rootSessionId = previewRootSessionId ?? this.context?.rootSessionId;
|
|
2759
|
+
if (!rootSessionId) return [];
|
|
2760
|
+
const state = await this.readRootState(rootSessionId);
|
|
2761
|
+
return state ? [state] : [];
|
|
2762
|
+
}
|
|
2763
|
+
const states: ReportRootState[] = [];
|
|
2764
|
+
for (const rootSessionId of await this.enumerateRootIds()) {
|
|
2765
|
+
const state = await this.readRootState(rootSessionId);
|
|
2766
|
+
if (state) states.push(state);
|
|
2767
|
+
}
|
|
2768
|
+
return states;
|
|
2769
|
+
}
|
|
2770
|
+
|
|
2771
|
+
/** Current persisted generation, or undefined when no metadata exists. */
|
|
2772
|
+
async getRootGeneration(rootSessionId: string): Promise<number | undefined> {
|
|
2773
|
+
const rootDir = await this.existingRootDirectory(rootSessionId);
|
|
2774
|
+
if (!rootDir) return undefined;
|
|
2775
|
+
const metadata = await this.readJson(
|
|
2776
|
+
join(rootDir, "root.json"),
|
|
2777
|
+
(value) => parseRootMetadata(value, rootSessionId),
|
|
2778
|
+
);
|
|
2779
|
+
return metadata?.generation;
|
|
2780
|
+
}
|
|
2781
|
+
|
|
2782
|
+
/**
|
|
2783
|
+
* Status-rich durable entry read for final verification. Unlike `readEntry`,
|
|
2784
|
+
* absence is only reported when it is PROVEN: an unreadable reports root, root
|
|
2785
|
+
* directory, entry file or entry metadata is `uncertain` and the caller must
|
|
2786
|
+
* refuse its captured body. `readEntry` keeps the historic best-effort
|
|
2787
|
+
* undefined contract for every non-verified state.
|
|
2788
|
+
*/
|
|
2789
|
+
async readEntryState(rootSessionId: string, agentId: string): Promise<ReportEntryState> {
|
|
2790
|
+
if (!isSafePathComponent(rootSessionId) || !isCanonicalAgentId(agentId)) {
|
|
2791
|
+
return { status: "absent" };
|
|
2792
|
+
}
|
|
2793
|
+
const rootScan = await this.existingRootDirectoryScan(rootSessionId, {
|
|
2794
|
+
strayFileIsAbsent: true,
|
|
2795
|
+
});
|
|
2796
|
+
if (rootScan.uncertainty !== undefined) {
|
|
2797
|
+
return { status: "uncertain", reason: rootScan.uncertainty };
|
|
2798
|
+
}
|
|
2799
|
+
if (rootScan.rootDir === undefined) return { status: "absent" };
|
|
2800
|
+
// Refuse to reach an entry through a link/junction: a stably relinked
|
|
2801
|
+
// ancestor or entry would otherwise be read as if it were the real path.
|
|
2802
|
+
const agentsDir = join(rootScan.rootDir, "agents");
|
|
2803
|
+
const agents = await this.lstatScan(agentsDir, "agents-directory");
|
|
2804
|
+
if (agents.status === "missing") return { status: "absent" };
|
|
2805
|
+
if (agents.status === "uncertain") return { status: "uncertain", reason: agents.reason };
|
|
2806
|
+
if (agents.info.isSymbolicLink() || !agents.info.isDirectory()) {
|
|
2807
|
+
this.diagnose(`agents path is not a plain directory: ${basename(agentsDir)}`);
|
|
2808
|
+
return { status: "uncertain", reason: "agents-directory-unsafe" };
|
|
2809
|
+
}
|
|
2810
|
+
const path = join(agentsDir, `${agentId}.json`);
|
|
2811
|
+
const before = await this.lstatScan(path, "report-entry");
|
|
2812
|
+
if (before.status === "missing") return { status: "absent" };
|
|
2813
|
+
if (before.status === "uncertain") return { status: "uncertain", reason: before.reason };
|
|
2814
|
+
if (before.info.isSymbolicLink() || !before.info.isFile()) {
|
|
2815
|
+
// A dangling link still stats as a link here, so it is refused instead of
|
|
2816
|
+
// being collapsed into "no entry".
|
|
2817
|
+
this.diagnose(`report entry is not a plain file: ${basename(path)}`);
|
|
2818
|
+
return { status: "uncertain", reason: "report-entry-unsafe" };
|
|
2819
|
+
}
|
|
2820
|
+
const scan = await this.readJsonScan(path, "report-entry", parseReportEntry);
|
|
2821
|
+
const after = await this.lstatScan(path, "report-entry");
|
|
2822
|
+
if (after.status === "missing") {
|
|
2823
|
+
return { status: "uncertain", reason: "report-entry-vanished" };
|
|
2824
|
+
}
|
|
2825
|
+
if (after.status === "uncertain") return { status: "uncertain", reason: after.reason };
|
|
2826
|
+
if (
|
|
2827
|
+
after.info.isSymbolicLink() ||
|
|
2828
|
+
!after.info.isFile() ||
|
|
2829
|
+
after.info.dev !== before.info.dev ||
|
|
2830
|
+
after.info.ino !== before.info.ino ||
|
|
2831
|
+
after.info.size !== before.info.size ||
|
|
2832
|
+
after.info.mtimeMs !== before.info.mtimeMs
|
|
2833
|
+
) {
|
|
2834
|
+
this.diagnose(`report entry changed during its read: ${basename(path)}`);
|
|
2835
|
+
return { status: "uncertain", reason: "report-entry-changed" };
|
|
2836
|
+
}
|
|
2837
|
+
// The entry stats above follow every ancestor, so replacing the agents
|
|
2838
|
+
// directory with a junction to that same directory keeps the entry's
|
|
2839
|
+
// inode/size/mtime identical. Re-stat the ancestor itself: only its own
|
|
2840
|
+
// dev/ino/type can prove the entry was read through the checked directory.
|
|
2841
|
+
// mtime/size are deliberately not compared — writes to unrelated sibling
|
|
2842
|
+
// entries legitimately change them.
|
|
2843
|
+
const agentsAfter = await this.lstatScan(agentsDir, "agents-directory");
|
|
2844
|
+
if (agentsAfter.status === "missing") {
|
|
2845
|
+
return { status: "uncertain", reason: "agents-directory-vanished" };
|
|
2846
|
+
}
|
|
2847
|
+
if (agentsAfter.status === "uncertain") {
|
|
2848
|
+
return { status: "uncertain", reason: agentsAfter.reason };
|
|
2849
|
+
}
|
|
2850
|
+
if (agentsAfter.info.isSymbolicLink() || !agentsAfter.info.isDirectory()) {
|
|
2851
|
+
this.diagnose(`agents path is not a plain directory: ${basename(agentsDir)}`);
|
|
2852
|
+
return { status: "uncertain", reason: "agents-directory-unsafe" };
|
|
2853
|
+
}
|
|
2854
|
+
if (agentsAfter.info.dev !== agents.info.dev || agentsAfter.info.ino !== agents.info.ino) {
|
|
2855
|
+
this.diagnose(`agents directory changed during its read: ${basename(agentsDir)}`);
|
|
2856
|
+
return { status: "uncertain", reason: "agents-directory-changed" };
|
|
2857
|
+
}
|
|
2858
|
+
if (scan.uncertainty !== undefined) return { status: "uncertain", reason: scan.uncertainty };
|
|
2859
|
+
if (scan.value === undefined) {
|
|
2860
|
+
// Both stats proved a plain file, so an unreadable body is not absence.
|
|
2861
|
+
return { status: "uncertain", reason: "report-entry-vanished" };
|
|
2862
|
+
}
|
|
2863
|
+
// A valid-shaped entry for another id/root is not evidence about this path.
|
|
2864
|
+
if (scan.value.id !== agentId || scan.value.rootSessionId !== rootSessionId) {
|
|
2865
|
+
this.diagnose(`report entry identity mismatch at ${basename(path)}`);
|
|
2866
|
+
return { status: "uncertain", reason: "report-entry-identity-mismatch" };
|
|
2867
|
+
}
|
|
2868
|
+
return { status: "verified", entry: scan.value, path };
|
|
2869
|
+
}
|
|
2870
|
+
|
|
2871
|
+
async readEntry(rootSessionId: string, agentId: string): Promise<ReportEntry | undefined> {
|
|
2872
|
+
const state = await this.readEntryState(rootSessionId, agentId);
|
|
2873
|
+
return state.status === "verified" ? state.entry : undefined;
|
|
2874
|
+
}
|
|
2875
|
+
|
|
2876
|
+
private async entriesById(id: string): Promise<{ rootSessionId: string; entry: ReportEntry }[]> {
|
|
2877
|
+
if (!isCanonicalAgentId(id)) return [];
|
|
2878
|
+
const found: { rootSessionId: string; entry: ReportEntry }[] = [];
|
|
2879
|
+
for (const rootSessionId of await this.enumerateRootIds()) {
|
|
2880
|
+
const rootDir = await this.existingRootDirectory(rootSessionId);
|
|
2881
|
+
if (!rootDir) continue;
|
|
2882
|
+
const entry = await this.readJson(join(rootDir, "agents", `${id}.json`), parseReportEntry);
|
|
2883
|
+
if (entry) found.push({ rootSessionId, entry });
|
|
2884
|
+
}
|
|
2885
|
+
return found;
|
|
2886
|
+
}
|
|
2887
|
+
|
|
2888
|
+
private async freshDeleted(
|
|
2889
|
+
entries: readonly { rootSessionId: string; entry: ReportEntry }[],
|
|
2890
|
+
): Promise<{ rootSessionId: string; entry: DeletedReportEntry } | undefined> {
|
|
2891
|
+
const now = this.now();
|
|
2892
|
+
for (const { rootSessionId, entry } of entries) {
|
|
2893
|
+
if (entry.state !== "deleted") continue;
|
|
2894
|
+
if (now - entry.deletedAt <= this.retentionMs()) {
|
|
2895
|
+
return { rootSessionId, entry };
|
|
2896
|
+
}
|
|
2897
|
+
}
|
|
2898
|
+
return undefined;
|
|
2899
|
+
}
|
|
2900
|
+
|
|
2901
|
+
private deletedLookup(
|
|
2902
|
+
found: { rootSessionId: string; entry: DeletedReportEntry },
|
|
2903
|
+
): ReportLookup {
|
|
2904
|
+
return {
|
|
2905
|
+
status: "deleted",
|
|
2906
|
+
entry: found.entry,
|
|
2907
|
+
rootSessionId: found.rootSessionId,
|
|
2908
|
+
deletedAt: found.entry.deletedAt,
|
|
2909
|
+
...(found.entry.deletionReason === undefined
|
|
2910
|
+
? {}
|
|
2911
|
+
: { reason: found.entry.deletionReason }),
|
|
2912
|
+
};
|
|
2913
|
+
}
|
|
2914
|
+
|
|
2915
|
+
private fullLookup(
|
|
2916
|
+
rootSessionId: string,
|
|
2917
|
+
entry: FullReportEntry,
|
|
2918
|
+
provenance: "archive" | "parent-record" | "legacy-output",
|
|
2919
|
+
): ReportLookup {
|
|
2920
|
+
return {
|
|
2921
|
+
status: "found",
|
|
2922
|
+
report: { ...entry.report, recoveredFrom: provenance },
|
|
2923
|
+
entry,
|
|
2924
|
+
rootSessionId,
|
|
2925
|
+
provenance,
|
|
2926
|
+
};
|
|
2927
|
+
}
|
|
2928
|
+
|
|
2929
|
+
/**
|
|
2930
|
+
* A lookup view for a body that is past retention but not yet stubbed on disk.
|
|
2931
|
+
* The on-disk body is untouched (no read-time deletion), yet the returned
|
|
2932
|
+
* entry cannot silently hand an expired body to a caller as current.
|
|
2933
|
+
*/
|
|
2934
|
+
private expiredLookup(
|
|
2935
|
+
rootSessionId: string,
|
|
2936
|
+
entry: FullReportEntry,
|
|
2937
|
+
expiredAt: number,
|
|
2938
|
+
reason: string,
|
|
2939
|
+
): ReportLookup {
|
|
2940
|
+
const view: ExpiredReportEntry = {
|
|
2941
|
+
version: REPORT_STORE_VERSION,
|
|
2942
|
+
id: entry.id,
|
|
2943
|
+
entryGeneration: entry.entryGeneration,
|
|
2944
|
+
createdAt: entry.createdAt,
|
|
2945
|
+
updatedAt: entry.updatedAt,
|
|
2946
|
+
completedAt: entry.completedAt,
|
|
2947
|
+
rootSessionId: entry.rootSessionId,
|
|
2948
|
+
rootCwd: entry.rootCwd,
|
|
2949
|
+
...(entry.rootSessionFile === undefined ? {} : { rootSessionFile: entry.rootSessionFile }),
|
|
2950
|
+
type: entry.type,
|
|
2951
|
+
description: entry.description,
|
|
2952
|
+
...(entry.handle === undefined ? {} : { handle: entry.handle }),
|
|
2953
|
+
...(entry.alias === undefined ? {} : { alias: entry.alias }),
|
|
2954
|
+
...(entry.parentAgentId === undefined ? {} : { parentAgentId: entry.parentAgentId }),
|
|
2955
|
+
...(entry.workflowId === undefined ? {} : { workflowId: entry.workflowId }),
|
|
2956
|
+
ownerIds: [...entry.ownerIds],
|
|
2957
|
+
...(entry.sessionFile === undefined ? {} : { sessionFile: entry.sessionFile }),
|
|
2958
|
+
...(entry.sessionId === undefined ? {} : { sessionId: entry.sessionId }),
|
|
2959
|
+
...(entry.outputFile === undefined ? {} : { outputFile: entry.outputFile }),
|
|
2960
|
+
...(entry.runGeneration === undefined ? {} : { runGeneration: entry.runGeneration }),
|
|
2961
|
+
state: "expired",
|
|
2962
|
+
expiredAt,
|
|
2963
|
+
};
|
|
2964
|
+
return { status: "expired", entry: view, rootSessionId, expiredAt, reason };
|
|
2965
|
+
}
|
|
2966
|
+
|
|
2967
|
+
async find(ref: string, parentEntries?: readonly unknown[]): Promise<ReportLookup> {
|
|
2968
|
+
const id = ref.trim();
|
|
2969
|
+
if (isCanonicalAgentId(id)) {
|
|
2970
|
+
const entries = await this.entriesById(id);
|
|
2971
|
+
const deleted = await this.freshDeleted(entries);
|
|
2972
|
+
if (deleted) return this.deletedLookup(deleted);
|
|
2973
|
+
const unowned = entries.filter(
|
|
2974
|
+
({ entry }) => isUnownedEntry(entry) && entry.state !== "deleted",
|
|
2975
|
+
);
|
|
2976
|
+
const full = unowned.filter(
|
|
2977
|
+
(candidate): candidate is { rootSessionId: string; entry: FullReportEntry } =>
|
|
2978
|
+
candidate.entry.state === "full",
|
|
2979
|
+
);
|
|
2980
|
+
const freshFull = full.filter(({ entry }) => {
|
|
2981
|
+
const completedAt = entry.report.completedAt ?? entry.completedAt;
|
|
2982
|
+
return this.now() - completedAt <= this.retentionMs();
|
|
2983
|
+
});
|
|
2984
|
+
if (freshFull.length > 1) {
|
|
2985
|
+
return {
|
|
2986
|
+
status: "ambiguous",
|
|
2987
|
+
ref: id,
|
|
2988
|
+
reason: "same exact id archived under multiple roots",
|
|
2989
|
+
candidates: freshFull.map(({ rootSessionId, entry }) => ({
|
|
2990
|
+
rootSessionId,
|
|
2991
|
+
id: entry.id,
|
|
2992
|
+
...(entry.alias === undefined ? {} : { alias: entry.alias }),
|
|
2993
|
+
})),
|
|
2994
|
+
};
|
|
2995
|
+
}
|
|
2996
|
+
if (freshFull.length === 1) {
|
|
2997
|
+
return this.fullLookup(freshFull[0].rootSessionId, freshFull[0].entry, "archive");
|
|
2998
|
+
}
|
|
2999
|
+
const expired = unowned.filter(
|
|
3000
|
+
(candidate): candidate is { rootSessionId: string; entry: ExpiredReportEntry } =>
|
|
3001
|
+
candidate.entry.state === "expired",
|
|
3002
|
+
);
|
|
3003
|
+
if (expired.length > 0) {
|
|
3004
|
+
return {
|
|
3005
|
+
status: "expired",
|
|
3006
|
+
entry: expired[0].entry,
|
|
3007
|
+
rootSessionId: expired[0].rootSessionId,
|
|
3008
|
+
expiredAt: expired[0].entry.expiredAt,
|
|
3009
|
+
reason: "report body expired after the 30-day retention window",
|
|
3010
|
+
};
|
|
3011
|
+
}
|
|
3012
|
+
if (full.length > 0 && freshFull.length === 0) {
|
|
3013
|
+
const stale = full[0].entry;
|
|
3014
|
+
return this.expiredLookup(
|
|
3015
|
+
full[0].rootSessionId,
|
|
3016
|
+
stale,
|
|
3017
|
+
stale.completedAt + this.retentionMs(),
|
|
3018
|
+
"report is past the 30-day retention window; maintenance has not run yet",
|
|
3019
|
+
);
|
|
3020
|
+
}
|
|
3021
|
+
|
|
3022
|
+
// Same agent id can be recorded more than once (running/completed then a
|
|
3023
|
+
// steered resume). The append-latest record is authoritative; an older
|
|
3024
|
+
// generation must not hide or replace the newest report.
|
|
3025
|
+
const candidates = parentRecordCandidates(parentEntries);
|
|
3026
|
+
let parent: JsonRecord | undefined;
|
|
3027
|
+
for (let index = candidates.length - 1; index >= 0; index--) {
|
|
3028
|
+
if (stringField(candidates[index], "id") === id) {
|
|
3029
|
+
parent = candidates[index];
|
|
3030
|
+
break;
|
|
3031
|
+
}
|
|
3032
|
+
}
|
|
3033
|
+
if (parent) {
|
|
3034
|
+
const snapshot = snapshotFromParentRecord(parent, this.context, "parent-record", {});
|
|
3035
|
+
if (snapshot && this.parentSnapshotFresh(snapshot)) {
|
|
3036
|
+
return {
|
|
3037
|
+
status: "found",
|
|
3038
|
+
report: snapshot,
|
|
3039
|
+
entry: this.syntheticEntry(snapshot),
|
|
3040
|
+
rootSessionId: snapshot.rootSessionId,
|
|
3041
|
+
provenance: "parent-record",
|
|
3042
|
+
};
|
|
3043
|
+
}
|
|
3044
|
+
return {
|
|
3045
|
+
status: "missing",
|
|
3046
|
+
ref: id,
|
|
3047
|
+
reason:
|
|
3048
|
+
snapshot === undefined
|
|
3049
|
+
? "parent record is not a provable top-level report"
|
|
3050
|
+
: "parent record is outside the 30-day retention window or has no completion time",
|
|
3051
|
+
};
|
|
3052
|
+
}
|
|
3053
|
+
|
|
3054
|
+
if (entries.some(({ entry }) => !isUnownedEntry(entry))) {
|
|
3055
|
+
return {
|
|
3056
|
+
status: "missing",
|
|
3057
|
+
ref: id,
|
|
3058
|
+
reason: "archived report is owned by a parent/workflow; use the owner-scoped reader",
|
|
3059
|
+
};
|
|
3060
|
+
}
|
|
3061
|
+
|
|
3062
|
+
const legacy = await this.findLegacyOutput(id);
|
|
3063
|
+
if (legacy) {
|
|
3064
|
+
return {
|
|
3065
|
+
status: "found",
|
|
3066
|
+
report: legacy.snapshot,
|
|
3067
|
+
entry: this.syntheticEntry(legacy.snapshot),
|
|
3068
|
+
rootSessionId: legacy.snapshot.rootSessionId,
|
|
3069
|
+
provenance: "legacy-output",
|
|
3070
|
+
};
|
|
3071
|
+
}
|
|
3072
|
+
return {
|
|
3073
|
+
status: "missing",
|
|
3074
|
+
ref: id,
|
|
3075
|
+
reason: "no retained, expired, deleted or provable legacy report for this exact id",
|
|
3076
|
+
};
|
|
3077
|
+
}
|
|
3078
|
+
|
|
3079
|
+
// Alias/handle resolution is deliberately root-local. A non-canonical ref is
|
|
3080
|
+
// never treated as an id prefix.
|
|
3081
|
+
const rootSessionId = this.context?.rootSessionId;
|
|
3082
|
+
if (!rootSessionId) {
|
|
3083
|
+
return { status: "missing", ref: id, reason: "alias lookup requires a bound root session" };
|
|
3084
|
+
}
|
|
3085
|
+
const root = await this.readRootState(rootSessionId);
|
|
3086
|
+
if (!root) return { status: "missing", ref: id, reason: "bound root has no reports" };
|
|
3087
|
+
const matches = root.reportEntries
|
|
3088
|
+
.filter(isUnownedEntry)
|
|
3089
|
+
.filter((entry) => entry.alias === id || entry.handle === id);
|
|
3090
|
+
if (matches.length === 0) {
|
|
3091
|
+
return { status: "missing", ref: id, reason: "no retained report with this alias in the bound root" };
|
|
3092
|
+
}
|
|
3093
|
+
const newest = matches[0];
|
|
3094
|
+
const tied = matches.filter((entry) => entry.completedAt === newest.completedAt);
|
|
3095
|
+
if (tied.length > 1) {
|
|
3096
|
+
return {
|
|
3097
|
+
status: "ambiguous",
|
|
3098
|
+
ref: id,
|
|
3099
|
+
reason: "multiple reports share the newest completion time",
|
|
3100
|
+
candidates: tied.map((entry) => ({
|
|
3101
|
+
rootSessionId,
|
|
3102
|
+
id: entry.id,
|
|
3103
|
+
...(entry.alias === undefined ? {} : { alias: entry.alias }),
|
|
3104
|
+
})),
|
|
3105
|
+
};
|
|
3106
|
+
}
|
|
3107
|
+
if (newest.state === "deleted") {
|
|
3108
|
+
return this.deletedLookup({ rootSessionId, entry: newest });
|
|
3109
|
+
}
|
|
3110
|
+
if (newest.state === "expired") {
|
|
3111
|
+
return {
|
|
3112
|
+
status: "expired",
|
|
3113
|
+
entry: newest,
|
|
3114
|
+
rootSessionId,
|
|
3115
|
+
expiredAt: newest.expiredAt,
|
|
3116
|
+
reason: "report body expired after the 30-day retention window",
|
|
3117
|
+
};
|
|
3118
|
+
}
|
|
3119
|
+
const completedAt = newest.report.completedAt ?? newest.completedAt;
|
|
3120
|
+
if (this.now() - completedAt > this.retentionMs()) {
|
|
3121
|
+
return this.expiredLookup(
|
|
3122
|
+
rootSessionId,
|
|
3123
|
+
newest,
|
|
3124
|
+
completedAt + this.retentionMs(),
|
|
3125
|
+
"report is past the 30-day retention window",
|
|
3126
|
+
);
|
|
3127
|
+
}
|
|
3128
|
+
return this.fullLookup(rootSessionId, newest, "archive");
|
|
3129
|
+
}
|
|
3130
|
+
|
|
3131
|
+
/**
|
|
3132
|
+
* Owner-scoped archived read for nested tools/workflows. The owner context is
|
|
3133
|
+
* strict: a normal parent id matches `parentAgentId` or its ancestor-chain
|
|
3134
|
+
* `ownerIds`, never a workflow row (even if the strings collide). A workflow
|
|
3135
|
+
* context matches only that workflow. Siblings, top-level and unrelated owners
|
|
3136
|
+
* stay invisible even to an exact-id request.
|
|
3137
|
+
*/
|
|
3138
|
+
async findOwned(
|
|
3139
|
+
ref: string,
|
|
3140
|
+
ownerId: string,
|
|
3141
|
+
context?: ReportOwnerContext,
|
|
3142
|
+
): Promise<ReportLookup> {
|
|
3143
|
+
const id = ref.trim();
|
|
3144
|
+
if (!isCanonicalAgentId(id)) {
|
|
3145
|
+
return { status: "missing", ref: id, reason: "owner-scoped lookup requires a canonical id" };
|
|
3146
|
+
}
|
|
3147
|
+
const kind = context?.kind ?? (ownerId.startsWith("wf_") ? "workflow" : "parent");
|
|
3148
|
+
const effectiveOwner = context?.id ?? ownerId;
|
|
3149
|
+
const entries = await this.entriesById(id);
|
|
3150
|
+
const deleted = await this.freshDeleted(entries);
|
|
3151
|
+
if (deleted) return this.deletedLookup(deleted);
|
|
3152
|
+
const owned = entries.filter(({ entry }) => {
|
|
3153
|
+
if (entry.state === "deleted") return false;
|
|
3154
|
+
if (kind === "workflow") {
|
|
3155
|
+
// Workflow owner context is the workflow id only. A normal parent row can
|
|
3156
|
+
// carry that id in its ancestor chain, so ownerIds must not widen this.
|
|
3157
|
+
return entry.workflowId === effectiveOwner;
|
|
3158
|
+
}
|
|
3159
|
+
// Parent context never reads a workflow row by id collision. Ancestors are
|
|
3160
|
+
// cleanup protection only: archived reads match the immediate parent,
|
|
3161
|
+
// exactly like the live getOwnedRecord path.
|
|
3162
|
+
if (entry.workflowId === effectiveOwner) return false;
|
|
3163
|
+
return entry.parentAgentId === effectiveOwner;
|
|
3164
|
+
});
|
|
3165
|
+
const full = owned.filter(
|
|
3166
|
+
(candidate): candidate is { rootSessionId: string; entry: FullReportEntry } =>
|
|
3167
|
+
candidate.entry.state === "full",
|
|
3168
|
+
);
|
|
3169
|
+
const freshFull = full.filter(({ entry }) => {
|
|
3170
|
+
const completedAt = entry.report.completedAt ?? entry.completedAt;
|
|
3171
|
+
return this.now() - completedAt <= this.retentionMs();
|
|
3172
|
+
});
|
|
3173
|
+
if (freshFull.length > 0) {
|
|
3174
|
+
return this.fullLookup(freshFull[0].rootSessionId, freshFull[0].entry, "archive");
|
|
3175
|
+
}
|
|
3176
|
+
if (full.length > 0) {
|
|
3177
|
+
const stale = full[0].entry;
|
|
3178
|
+
return this.expiredLookup(
|
|
3179
|
+
full[0].rootSessionId,
|
|
3180
|
+
stale,
|
|
3181
|
+
stale.completedAt + this.retentionMs(),
|
|
3182
|
+
"report is past the 30-day retention window; maintenance has not run yet",
|
|
3183
|
+
);
|
|
3184
|
+
}
|
|
3185
|
+
const expired = owned.find(
|
|
3186
|
+
(candidate): candidate is { rootSessionId: string; entry: ExpiredReportEntry } =>
|
|
3187
|
+
candidate.entry.state === "expired",
|
|
3188
|
+
);
|
|
3189
|
+
if (expired) {
|
|
3190
|
+
return {
|
|
3191
|
+
status: "expired",
|
|
3192
|
+
entry: expired.entry,
|
|
3193
|
+
rootSessionId: expired.rootSessionId,
|
|
3194
|
+
expiredAt: expired.entry.expiredAt,
|
|
3195
|
+
reason: "report body expired after the 30-day retention window",
|
|
3196
|
+
};
|
|
3197
|
+
}
|
|
3198
|
+
return {
|
|
3199
|
+
status: "missing",
|
|
3200
|
+
ref: id,
|
|
3201
|
+
reason: "no retained archived report owned by this parent/workflow",
|
|
3202
|
+
};
|
|
3203
|
+
}
|
|
3204
|
+
|
|
3205
|
+
private parentSnapshotFresh(snapshot: ReportSnapshot): boolean {
|
|
3206
|
+
const completedAt = snapshot.completedAt;
|
|
3207
|
+
if (completedAt === undefined) return false;
|
|
3208
|
+
return this.now() - completedAt <= this.retentionMs();
|
|
3209
|
+
}
|
|
3210
|
+
|
|
3211
|
+
private syntheticEntry(snapshot: ReportSnapshot): FullReportEntry {
|
|
3212
|
+
const now = this.now();
|
|
3213
|
+
return {
|
|
3214
|
+
version: REPORT_STORE_VERSION,
|
|
3215
|
+
id: snapshot.id,
|
|
3216
|
+
entryGeneration: 0,
|
|
3217
|
+
createdAt: now,
|
|
3218
|
+
updatedAt: now,
|
|
3219
|
+
completedAt: snapshot.completedAt ?? now,
|
|
3220
|
+
rootSessionId: snapshot.rootSessionId,
|
|
3221
|
+
rootCwd: snapshot.rootCwd,
|
|
3222
|
+
...(snapshot.rootSessionFile === undefined
|
|
3223
|
+
? {}
|
|
3224
|
+
: { rootSessionFile: snapshot.rootSessionFile }),
|
|
3225
|
+
type: snapshot.type,
|
|
3226
|
+
description: snapshot.description,
|
|
3227
|
+
...(snapshot.handle === undefined ? {} : { handle: snapshot.handle }),
|
|
3228
|
+
...(snapshot.alias === undefined ? {} : { alias: snapshot.alias }),
|
|
3229
|
+
ownerIds: [...snapshot.ownerIds],
|
|
3230
|
+
...(snapshot.sessionFile === undefined ? {} : { sessionFile: snapshot.sessionFile }),
|
|
3231
|
+
...(snapshot.sessionId === undefined ? {} : { sessionId: snapshot.sessionId }),
|
|
3232
|
+
...(snapshot.outputFile === undefined ? {} : { outputFile: snapshot.outputFile }),
|
|
3233
|
+
state: "full",
|
|
3234
|
+
report: snapshot,
|
|
3235
|
+
};
|
|
3236
|
+
}
|
|
3237
|
+
|
|
3238
|
+
private async findLegacyOutput(id: string): Promise<{ snapshot: ReportSnapshot } | undefined> {
|
|
3239
|
+
const candidates = await this.legacyOutputPaths(id);
|
|
3240
|
+
for (const candidate of candidates) {
|
|
3241
|
+
const snapshot = await this.verifyLegacyOutput(candidate, id);
|
|
3242
|
+
if (snapshot) return { snapshot };
|
|
3243
|
+
}
|
|
3244
|
+
return undefined;
|
|
3245
|
+
}
|
|
3246
|
+
|
|
3247
|
+
/**
|
|
3248
|
+
* Read-only legacy inventory for cleanup previews: every generated `.output`
|
|
3249
|
+
* file in the known temp layout, with a verified authoritative snapshot when
|
|
3250
|
+
* its matching parent session record proves a top-level finished report.
|
|
3251
|
+
*/
|
|
3252
|
+
async inspectLegacyOutputs(): Promise<LegacyOutputInspection[]> {
|
|
3253
|
+
const inspections: LegacyOutputInspection[] = [];
|
|
3254
|
+
for (const { path, id } of await this.allLegacyOutputCandidates()) {
|
|
3255
|
+
const snapshot = await this.verifyLegacyOutput(path, id);
|
|
3256
|
+
inspections.push({
|
|
3257
|
+
path,
|
|
3258
|
+
agentId: id,
|
|
3259
|
+
verified: snapshot !== undefined,
|
|
3260
|
+
...(snapshot === undefined
|
|
3261
|
+
? { reason: "legacy-output-unverified: no provable top-level parent record" }
|
|
3262
|
+
: { snapshot }),
|
|
3263
|
+
});
|
|
3264
|
+
}
|
|
3265
|
+
return inspections;
|
|
3266
|
+
}
|
|
3267
|
+
|
|
3268
|
+
private async legacyOutputPaths(id: string): Promise<string[]> {
|
|
3269
|
+
const candidates = await this.allLegacyOutputCandidates();
|
|
3270
|
+
return candidates.filter((candidate) => candidate.id === id).map((candidate) => candidate.path);
|
|
3271
|
+
}
|
|
3272
|
+
|
|
3273
|
+
/** Exact temp layout: `<temp>/pi-subagents-<uid>/<encoded>/<session>/tasks/<id>.output`. */
|
|
3274
|
+
private async allLegacyOutputCandidates(): Promise<{ path: string; id: string }[]> {
|
|
3275
|
+
const tempRoot = this.storage().tempRoot;
|
|
3276
|
+
let topNames: string[];
|
|
3277
|
+
try {
|
|
3278
|
+
topNames = await readdir(tempRoot);
|
|
3279
|
+
} catch (error) {
|
|
3280
|
+
if (!isNotFound(error)) this.diagnose(`legacy temp scan failed: ${errorCode(error) ?? "unknown"}`);
|
|
3281
|
+
return [];
|
|
3282
|
+
}
|
|
3283
|
+
const candidates: { path: string; id: string }[] = [];
|
|
3284
|
+
for (const top of topNames) {
|
|
3285
|
+
if (!top.startsWith("pi-subagents-")) continue;
|
|
3286
|
+
const topPath = join(tempRoot, top);
|
|
3287
|
+
let encodedNames: string[];
|
|
3288
|
+
try {
|
|
3289
|
+
if (!(await lstat(topPath)).isDirectory()) continue;
|
|
3290
|
+
encodedNames = await readdir(topPath);
|
|
3291
|
+
} catch (error) {
|
|
3292
|
+
if (!isNotFound(error)) this.diagnose(`legacy temp dir unreadable: ${errorCode(error) ?? "unknown"}`);
|
|
3293
|
+
continue;
|
|
3294
|
+
}
|
|
3295
|
+
for (const encoded of encodedNames) {
|
|
3296
|
+
const encodedPath = join(topPath, encoded);
|
|
3297
|
+
let sessionNames: string[];
|
|
3298
|
+
try {
|
|
3299
|
+
if (!(await lstat(encodedPath)).isDirectory()) continue;
|
|
3300
|
+
sessionNames = await readdir(encodedPath);
|
|
3301
|
+
} catch (error) {
|
|
3302
|
+
if (!isNotFound(error)) {
|
|
3303
|
+
this.diagnose(`legacy encoded dir unreadable: ${errorCode(error) ?? "unknown"}`);
|
|
3304
|
+
}
|
|
3305
|
+
continue;
|
|
3306
|
+
}
|
|
3307
|
+
for (const sessionId of sessionNames) {
|
|
3308
|
+
const tasksDir = join(encodedPath, sessionId, "tasks");
|
|
3309
|
+
let taskNames: string[];
|
|
3310
|
+
try {
|
|
3311
|
+
taskNames = await readdir(tasksDir);
|
|
3312
|
+
} catch (error) {
|
|
3313
|
+
if (!isNotFound(error)) {
|
|
3314
|
+
this.diagnose(`legacy tasks dir unreadable: ${errorCode(error) ?? "unknown"}`);
|
|
3315
|
+
}
|
|
3316
|
+
continue;
|
|
3317
|
+
}
|
|
3318
|
+
for (const name of taskNames.sort()) {
|
|
3319
|
+
if (!name.endsWith(".output")) continue;
|
|
3320
|
+
const id = name.slice(0, -".output".length);
|
|
3321
|
+
if (!isCanonicalAgentId(id)) continue;
|
|
3322
|
+
const path = join(tasksDir, name);
|
|
3323
|
+
try {
|
|
3324
|
+
const info = await lstat(path);
|
|
3325
|
+
if (info.isFile() && !info.isSymbolicLink()) candidates.push({ path, id });
|
|
3326
|
+
} catch (error) {
|
|
3327
|
+
if (!isNotFound(error)) {
|
|
3328
|
+
this.diagnose(`legacy output stat failed: ${errorCode(error) ?? "unknown"}`);
|
|
3329
|
+
}
|
|
3330
|
+
}
|
|
3331
|
+
}
|
|
3332
|
+
}
|
|
3333
|
+
}
|
|
3334
|
+
}
|
|
3335
|
+
return candidates.sort((a, b) => a.path.localeCompare(b.path));
|
|
3336
|
+
}
|
|
3337
|
+
|
|
3338
|
+
private async verifyLegacyOutput(path: string, id: string): Promise<ReportSnapshot | undefined> {
|
|
3339
|
+
const tempRoot = this.storage().tempRoot;
|
|
3340
|
+
const inspected = await inspectRegularFile(path, [tempRoot]);
|
|
3341
|
+
if (!inspected.ok) {
|
|
3342
|
+
this.diagnose(`legacy output skipped (${inspected.reason})`);
|
|
3343
|
+
return undefined;
|
|
3344
|
+
}
|
|
3345
|
+
let firstLine: string | undefined;
|
|
3346
|
+
try {
|
|
3347
|
+
firstLine = await readFirstLine(path);
|
|
3348
|
+
} catch (error) {
|
|
3349
|
+
this.diagnose(`legacy output unreadable: ${errorCode(error) ?? "unknown"}`);
|
|
3350
|
+
return undefined;
|
|
3351
|
+
}
|
|
3352
|
+
if (!firstLine) return undefined;
|
|
3353
|
+
let first: unknown;
|
|
3354
|
+
try {
|
|
3355
|
+
first = JSON.parse(firstLine);
|
|
3356
|
+
} catch {
|
|
3357
|
+
this.diagnose("legacy output has no parseable first line");
|
|
3358
|
+
return undefined;
|
|
3359
|
+
}
|
|
3360
|
+
if (!isRecord(first)) return undefined;
|
|
3361
|
+
if (stringField(first, "agentId") !== id) return undefined;
|
|
3362
|
+
const cwd = stringField(first, "cwd");
|
|
3363
|
+
const sessionId = basename(dirname(dirname(path)));
|
|
3364
|
+
const encodedCwd = basename(dirname(dirname(dirname(path))));
|
|
3365
|
+
if (!cwd || encodeCwd(cwd) !== encodedCwd) {
|
|
3366
|
+
this.diagnose("legacy output cwd does not match its temp directory");
|
|
3367
|
+
return undefined;
|
|
3368
|
+
}
|
|
3369
|
+
const parent = await this.findParentSessionFile(sessionId, encodedCwd);
|
|
3370
|
+
if (!parent) {
|
|
3371
|
+
this.diagnose("legacy output has no matching parent session in the bounded session roots");
|
|
3372
|
+
return undefined;
|
|
3373
|
+
}
|
|
3374
|
+
const parentParsed = await this.readSessionFile(parent.path);
|
|
3375
|
+
if (!parentParsed) return undefined;
|
|
3376
|
+
// Multiple recorded generations can share the id; the last appended record
|
|
3377
|
+
// is the newest one and is the only authoritative source considered here.
|
|
3378
|
+
let record: JsonRecord | undefined;
|
|
3379
|
+
for (const data of parentParsed.entries.map(customRecordData)) {
|
|
3380
|
+
if (data && stringField(data, "id") === id) record = data;
|
|
3381
|
+
}
|
|
3382
|
+
if (!record) {
|
|
3383
|
+
this.diagnose("legacy output has no authoritative parent subagents:record");
|
|
3384
|
+
return undefined;
|
|
3385
|
+
}
|
|
3386
|
+
const snapshot = snapshotFromParentRecord(
|
|
3387
|
+
record,
|
|
3388
|
+
this.context,
|
|
3389
|
+
"legacy-output",
|
|
3390
|
+
{
|
|
3391
|
+
rootSessionId: parentParsed.header.id,
|
|
3392
|
+
rootCwd: parentParsed.header.cwd,
|
|
3393
|
+
rootSessionFile: parent.path,
|
|
3394
|
+
},
|
|
3395
|
+
);
|
|
3396
|
+
if (!snapshot || !this.parentSnapshotFresh(snapshot)) {
|
|
3397
|
+
this.diagnose("legacy parent record is not a provable top-level terminal report");
|
|
3398
|
+
return undefined;
|
|
3399
|
+
}
|
|
3400
|
+
return {
|
|
3401
|
+
...snapshot,
|
|
3402
|
+
outputFile: path,
|
|
3403
|
+
};
|
|
3404
|
+
}
|
|
3405
|
+
|
|
3406
|
+
private async findParentSessionFile(
|
|
3407
|
+
sessionId: string,
|
|
3408
|
+
encodedCwd: string,
|
|
3409
|
+
): Promise<{ path: string; header: SessionHeader } | undefined> {
|
|
3410
|
+
for (const root of this.storage().sessionRoots) {
|
|
3411
|
+
let realRoot: string;
|
|
3412
|
+
try {
|
|
3413
|
+
realRoot = await realpath(root);
|
|
3414
|
+
} catch (error) {
|
|
3415
|
+
if (!isNotFound(error)) this.diagnose(`session root unreadable: ${errorCode(error) ?? "unknown"}`);
|
|
3416
|
+
continue;
|
|
3417
|
+
}
|
|
3418
|
+
const candidates: string[] = [];
|
|
3419
|
+
try {
|
|
3420
|
+
const names = await readdir(realRoot);
|
|
3421
|
+
for (const name of names) {
|
|
3422
|
+
const path = join(realRoot, name);
|
|
3423
|
+
const info = await lstat(path);
|
|
3424
|
+
if (info.isFile() && name.endsWith(`${sessionId}.jsonl`)) {
|
|
3425
|
+
candidates.push(path);
|
|
3426
|
+
continue;
|
|
3427
|
+
}
|
|
3428
|
+
if (!info.isDirectory() || info.isSymbolicLink()) continue;
|
|
3429
|
+
const inner = await readdir(path);
|
|
3430
|
+
for (const child of inner) {
|
|
3431
|
+
if (child.endsWith(`${sessionId}.jsonl`)) candidates.push(join(path, child));
|
|
3432
|
+
}
|
|
3433
|
+
}
|
|
3434
|
+
} catch (error) {
|
|
3435
|
+
if (!isNotFound(error)) this.diagnose(`session scan failed: ${errorCode(error) ?? "unknown"}`);
|
|
3436
|
+
continue;
|
|
3437
|
+
}
|
|
3438
|
+
for (const candidate of candidates.sort()) {
|
|
3439
|
+
const parsed = await this.readSessionFile(candidate);
|
|
3440
|
+
if (!parsed) continue;
|
|
3441
|
+
if (parsed.header.id !== sessionId) continue;
|
|
3442
|
+
if (encodeCwd(parsed.header.cwd) !== encodedCwd) continue;
|
|
3443
|
+
return { path: candidate, header: parsed.header };
|
|
3444
|
+
}
|
|
3445
|
+
}
|
|
3446
|
+
return undefined;
|
|
3447
|
+
}
|
|
3448
|
+
|
|
3449
|
+
async readSessionFile(path: string): Promise<ParsedSessionFile | undefined> {
|
|
3450
|
+
const allowed = [this.storage().tempRoot, ...this.storage().sessionRoots];
|
|
3451
|
+
const inspected = await inspectRegularFile(path, allowed);
|
|
3452
|
+
if (!inspected.ok) {
|
|
3453
|
+
this.diagnose(`session file skipped (${inspected.reason})`);
|
|
3454
|
+
return undefined;
|
|
3455
|
+
}
|
|
3456
|
+
let text: string;
|
|
3457
|
+
try {
|
|
3458
|
+
text = await readFile(path, "utf8");
|
|
3459
|
+
} catch (error) {
|
|
3460
|
+
this.diagnose(`session file unreadable: ${errorCode(error) ?? "unknown"}`);
|
|
3461
|
+
return undefined;
|
|
3462
|
+
}
|
|
3463
|
+
return parseSessionFileText(text);
|
|
3464
|
+
}
|
|
3465
|
+
|
|
3466
|
+
/**
|
|
3467
|
+
* Opt-in verbose conversation read. Existing files only; no live session is
|
|
3468
|
+
* touched and the final report above it is never affected by a missing file.
|
|
3469
|
+
*/
|
|
3470
|
+
async readConversation(report: ReportSnapshot): Promise<string | undefined> {
|
|
3471
|
+
const output = report.outputFile;
|
|
3472
|
+
if (output) {
|
|
3473
|
+
const inspected = await inspectRegularFile(output, [this.storage().tempRoot]);
|
|
3474
|
+
if (inspected.ok) {
|
|
3475
|
+
let text: string;
|
|
3476
|
+
try {
|
|
3477
|
+
text = await readFile(output, "utf8");
|
|
3478
|
+
} catch (error) {
|
|
3479
|
+
this.diagnose(`output transcript unreadable: ${errorCode(error) ?? "unknown"}`);
|
|
3480
|
+
return undefined;
|
|
3481
|
+
}
|
|
3482
|
+
const entries = text
|
|
3483
|
+
.split(/\r?\n/)
|
|
3484
|
+
.filter((line) => line.trim().length > 0)
|
|
3485
|
+
.flatMap((line) => {
|
|
3486
|
+
try {
|
|
3487
|
+
return [JSON.parse(line) as unknown];
|
|
3488
|
+
} catch {
|
|
3489
|
+
return [];
|
|
3490
|
+
}
|
|
3491
|
+
});
|
|
3492
|
+
const conversation = formatConversationLines(entries, true);
|
|
3493
|
+
if (conversation.length > 0) return conversation;
|
|
3494
|
+
}
|
|
3495
|
+
}
|
|
3496
|
+
const sessionFile = report.sessionFile;
|
|
3497
|
+
if (!sessionFile) return undefined;
|
|
3498
|
+
const parsed = await this.readSessionFile(sessionFile);
|
|
3499
|
+
if (!parsed) return undefined;
|
|
3500
|
+
const conversation = formatConversationLines(parsed.entries, false);
|
|
3501
|
+
return conversation.length > 0 ? conversation : undefined;
|
|
3502
|
+
}
|
|
3503
|
+
|
|
3504
|
+
private async maybeMaintainRootLocked(
|
|
3505
|
+
rootSessionId: string,
|
|
3506
|
+
rootDir: string,
|
|
3507
|
+
context: ReportContext,
|
|
3508
|
+
): Promise<void> {
|
|
3509
|
+
const now = this.now();
|
|
3510
|
+
const last = this.lastMaintenance.get(rootSessionId) ?? 0;
|
|
3511
|
+
if (now - last < SAVE_MAINTENANCE_INTERVAL_MS) return;
|
|
3512
|
+
const previousAttempt = this.maintenanceAttempts.get(rootSessionId);
|
|
3513
|
+
if (previousAttempt) {
|
|
3514
|
+
const exponent = Math.min(previousAttempt.failures - 1, 10);
|
|
3515
|
+
const retryDelay = Math.min(
|
|
3516
|
+
SAVE_MAINTENANCE_INTERVAL_MS,
|
|
3517
|
+
MAINTENANCE_RETRY_BASE_MS * 2 ** exponent,
|
|
3518
|
+
);
|
|
3519
|
+
if (now - previousAttempt.at < retryDelay) return;
|
|
3520
|
+
}
|
|
3521
|
+
// Attempts have their own bounded exponential backoff. A foreign lock or a
|
|
3522
|
+
// failing rewrite must not turn every save into another lock acquisition,
|
|
3523
|
+
// while a later save still retries and eventually restores retention.
|
|
3524
|
+
this.maintenanceAttempts.set(rootSessionId, {
|
|
3525
|
+
at: now,
|
|
3526
|
+
failures: (previousAttempt?.failures ?? 0) + 1,
|
|
3527
|
+
});
|
|
3528
|
+
// This runs inside the save write chain, so it must not re-enqueue. The
|
|
3529
|
+
// shared lock excludes other stores; our own chain serializes local writes.
|
|
3530
|
+
const acquired = await this.acquireMaintenanceLock(rootSessionId);
|
|
3531
|
+
if (!acquired.ok) {
|
|
3532
|
+
this.diagnose(`save maintenance skipped ${rootSessionId}: ${acquired.reason}`);
|
|
3533
|
+
return;
|
|
3534
|
+
}
|
|
3535
|
+
try {
|
|
3536
|
+
await this.expireRootLocked(rootSessionId, rootDir, context);
|
|
3537
|
+
} finally {
|
|
3538
|
+
await this.endMaintenanceLock(acquired.handle);
|
|
3539
|
+
}
|
|
3540
|
+
this.lastMaintenance.set(rootSessionId, now);
|
|
3541
|
+
this.maintenanceAttempts.delete(rootSessionId);
|
|
3542
|
+
}
|
|
3543
|
+
|
|
3544
|
+
private async expireRootLocked(
|
|
3545
|
+
rootSessionId: string,
|
|
3546
|
+
rootDir: string,
|
|
3547
|
+
context: ReportContext | undefined,
|
|
3548
|
+
): Promise<void> {
|
|
3549
|
+
const agentsDir = join(rootDir, "agents");
|
|
3550
|
+
let names: string[];
|
|
3551
|
+
try {
|
|
3552
|
+
names = await readdir(agentsDir);
|
|
3553
|
+
} catch (error) {
|
|
3554
|
+
if (!isNotFound(error)) this.diagnose(`maintenance list failed: ${errorCode(error) ?? "unknown"}`);
|
|
3555
|
+
return;
|
|
3556
|
+
}
|
|
3557
|
+
const now = this.now();
|
|
3558
|
+
let changed = false;
|
|
3559
|
+
for (const name of names.sort()) {
|
|
3560
|
+
if (!name.endsWith(".json")) continue;
|
|
3561
|
+
const path = join(agentsDir, name);
|
|
3562
|
+
const entry = await this.readJson(path, parseReportEntry);
|
|
3563
|
+
if (!entry) continue;
|
|
3564
|
+
if (entry.state === "deleted" && now - entry.deletedAt > this.retentionMs()) {
|
|
3565
|
+
// Receipt expiry also revalidates identity before unlinking.
|
|
3566
|
+
const current = await this.readJson(path, parseReportEntry);
|
|
3567
|
+
if (
|
|
3568
|
+
!current ||
|
|
3569
|
+
current.state !== "deleted" ||
|
|
3570
|
+
current.entryGeneration !== entry.entryGeneration ||
|
|
3571
|
+
current.updatedAt !== entry.updatedAt
|
|
3572
|
+
) {
|
|
3573
|
+
continue;
|
|
3574
|
+
}
|
|
3575
|
+
try {
|
|
3576
|
+
await unlink(path);
|
|
3577
|
+
changed = true;
|
|
3578
|
+
} catch (error) {
|
|
3579
|
+
if (!isNotFound(error)) {
|
|
3580
|
+
this.diagnose(`receipt expiry failed: ${errorCode(error) ?? "unknown"}`);
|
|
3581
|
+
}
|
|
3582
|
+
}
|
|
3583
|
+
continue;
|
|
3584
|
+
}
|
|
3585
|
+
if (entry.state !== "full") continue;
|
|
3586
|
+
const completedAt = entry.report.completedAt ?? entry.completedAt;
|
|
3587
|
+
if (now - completedAt <= this.retentionMs()) continue;
|
|
3588
|
+
const expired: ExpiredReportEntry = {
|
|
3589
|
+
version: REPORT_STORE_VERSION,
|
|
3590
|
+
id: entry.id,
|
|
3591
|
+
entryGeneration: entry.entryGeneration + 1,
|
|
3592
|
+
createdAt: entry.createdAt,
|
|
3593
|
+
updatedAt: now,
|
|
3594
|
+
completedAt: entry.completedAt,
|
|
3595
|
+
rootSessionId: entry.rootSessionId,
|
|
3596
|
+
rootCwd: entry.rootCwd,
|
|
3597
|
+
...(entry.rootSessionFile === undefined ? {} : { rootSessionFile: entry.rootSessionFile }),
|
|
3598
|
+
type: entry.type,
|
|
3599
|
+
description: entry.description,
|
|
3600
|
+
...(entry.handle === undefined ? {} : { handle: entry.handle }),
|
|
3601
|
+
...(entry.alias === undefined ? {} : { alias: entry.alias }),
|
|
3602
|
+
...(entry.parentAgentId === undefined ? {} : { parentAgentId: entry.parentAgentId }),
|
|
3603
|
+
...(entry.workflowId === undefined ? {} : { workflowId: entry.workflowId }),
|
|
3604
|
+
ownerIds: [...entry.ownerIds],
|
|
3605
|
+
...(entry.sessionFile === undefined ? {} : { sessionFile: entry.sessionFile }),
|
|
3606
|
+
...(entry.sessionId === undefined ? {} : { sessionId: entry.sessionId }),
|
|
3607
|
+
...(entry.outputFile === undefined ? {} : { outputFile: entry.outputFile }),
|
|
3608
|
+
...(entry.runGeneration === undefined ? {} : { runGeneration: entry.runGeneration }),
|
|
3609
|
+
state: "expired",
|
|
3610
|
+
expiredAt: completedAt + this.retentionMs(),
|
|
3611
|
+
};
|
|
3612
|
+
await this.options.maintenanceHook?.({
|
|
3613
|
+
phase: "entry-read",
|
|
3614
|
+
rootSessionId,
|
|
3615
|
+
agentId: entry.id,
|
|
3616
|
+
});
|
|
3617
|
+
// Identity revalidation: a newer generation written under the shared lock
|
|
3618
|
+
// (or a same-store save queued after us) must never be overwritten by this
|
|
3619
|
+
// older expiry stub.
|
|
3620
|
+
const current = await this.readJson(path, parseReportEntry);
|
|
3621
|
+
if (
|
|
3622
|
+
!current ||
|
|
3623
|
+
current.state !== "full" ||
|
|
3624
|
+
current.entryGeneration !== entry.entryGeneration ||
|
|
3625
|
+
current.updatedAt !== entry.updatedAt ||
|
|
3626
|
+
current.completedAt !== entry.completedAt
|
|
3627
|
+
) {
|
|
3628
|
+
continue;
|
|
3629
|
+
}
|
|
3630
|
+
try {
|
|
3631
|
+
await atomicWriteJson(path, expired, this.nonce());
|
|
3632
|
+
changed = true;
|
|
3633
|
+
} catch (error) {
|
|
3634
|
+
this.diagnose(`entry expiry failed: ${errorCode(error) ?? "unknown"}`);
|
|
3635
|
+
}
|
|
3636
|
+
}
|
|
3637
|
+
if (changed) {
|
|
3638
|
+
if (context) {
|
|
3639
|
+
await this.bumpGenerationLocked(rootDir, rootSessionId, context);
|
|
3640
|
+
} else {
|
|
3641
|
+
this.diagnose(`maintenance changed ${rootSessionId} without root metadata; generation not bumped`);
|
|
3642
|
+
}
|
|
3643
|
+
}
|
|
3644
|
+
}
|
|
3645
|
+
|
|
3646
|
+
private async maintenanceContext(
|
|
3647
|
+
rootSessionId: string,
|
|
3648
|
+
rootDir: string,
|
|
3649
|
+
): Promise<ReportContext | undefined> {
|
|
3650
|
+
const metadata = await this.readJson(
|
|
3651
|
+
join(rootDir, "root.json"),
|
|
3652
|
+
(value) => parseRootMetadata(value, rootSessionId),
|
|
3653
|
+
);
|
|
3654
|
+
if (metadata === undefined) return this.context;
|
|
3655
|
+
return {
|
|
3656
|
+
cwd: metadata.rootCwd,
|
|
3657
|
+
rootSessionId,
|
|
3658
|
+
...(metadata.rootSessionFile === undefined
|
|
3659
|
+
? {}
|
|
3660
|
+
: { rootSessionFile: metadata.rootSessionFile }),
|
|
3661
|
+
};
|
|
3662
|
+
}
|
|
3663
|
+
|
|
3664
|
+
private async maintainRoot(rootSessionId: string): Promise<void> {
|
|
3665
|
+
if (this.closed || this.closing) return;
|
|
3666
|
+
const rootDir = await this.existingRootDirectory(rootSessionId);
|
|
3667
|
+
if (!rootDir || this.closed || this.closing) return;
|
|
3668
|
+
const context = await this.maintenanceContext(rootSessionId, rootDir);
|
|
3669
|
+
const acquired = await this.acquireMaintenanceLock(rootSessionId);
|
|
3670
|
+
if (!acquired.ok) {
|
|
3671
|
+
this.diagnose(`maintenance skipped ${rootSessionId}: ${acquired.reason}`);
|
|
3672
|
+
return;
|
|
3673
|
+
}
|
|
3674
|
+
try {
|
|
3675
|
+
if (this.closed || this.closing) return;
|
|
3676
|
+
await this.options.maintenanceHook?.({ phase: "locked", rootSessionId });
|
|
3677
|
+
// Recheck after the hook: close may have stopped admission while an
|
|
3678
|
+
// explicit maintenance caller was suspended before enqueueing its write.
|
|
3679
|
+
if (this.closed || this.closing) return;
|
|
3680
|
+
await this.enqueue(rootDir, () => this.expireRootLocked(rootSessionId, rootDir, context));
|
|
3681
|
+
} finally {
|
|
3682
|
+
await this.endMaintenanceLock(acquired.handle);
|
|
3683
|
+
}
|
|
3684
|
+
}
|
|
3685
|
+
|
|
3686
|
+
private async expireRoot(rootSessionId: string): Promise<void> {
|
|
3687
|
+
await this.maintainRoot(rootSessionId);
|
|
3688
|
+
}
|
|
3689
|
+
|
|
3690
|
+
/** Startup/explicit maintenance: expire bodies and old receipts across roots. */
|
|
3691
|
+
async maintain(): Promise<void> {
|
|
3692
|
+
for (const rootSessionId of await this.enumerateRootIds()) {
|
|
3693
|
+
await this.maintainRoot(rootSessionId);
|
|
3694
|
+
}
|
|
3695
|
+
}
|
|
3696
|
+
|
|
3697
|
+
/** Foreign live/unknown leases and locks protect the whole root from cleanup. */
|
|
3698
|
+
async rootProtectionReason(rootSessionId: string): Promise<string | undefined> {
|
|
3699
|
+
const rootDir = await this.existingRootDirectory(rootSessionId);
|
|
3700
|
+
if (!rootDir) return "no-root";
|
|
3701
|
+
const lockRead = await this.readCleanupLockRead(rootSessionId);
|
|
3702
|
+
if (lockRead.status === "uncertain") return "cleanup-lock-unreadable";
|
|
3703
|
+
if (lockRead.status === "live") return "cleanup-lock";
|
|
3704
|
+
const scan = await this.scanLeaseFiles(rootSessionId, rootDir);
|
|
3705
|
+
if (scan.uncertainty !== undefined) return "lease-unreadable";
|
|
3706
|
+
for (const lease of scan.leases) {
|
|
3707
|
+
if (lease.own) continue;
|
|
3708
|
+
if (this.pidAlive(lease.pid)) return "foreign-lease";
|
|
3709
|
+
}
|
|
3710
|
+
return undefined;
|
|
3711
|
+
}
|
|
3712
|
+
|
|
3713
|
+
/**
|
|
3714
|
+
* Cleanup acquires the exclusive per-root lock FIRST, then rechecks foreign
|
|
3715
|
+
* leases. A foreign live/unknown lease makes the whole root ineligible.
|
|
3716
|
+
*/
|
|
3717
|
+
async acquireCleanupLock(
|
|
3718
|
+
rootSessionId: string,
|
|
3719
|
+
selection: CleanupSelection,
|
|
3720
|
+
options: CleanupLockOptions = {},
|
|
3721
|
+
): Promise<{ ok: true; handle: CleanupLockHandle } | { ok: false; reason: string }> {
|
|
3722
|
+
if (!isSafePathComponent(rootSessionId)) return { ok: false, reason: "invalid-root-session-id" };
|
|
3723
|
+
if (this.localCleanupLockBusy(rootSessionId)) return { ok: false, reason: "cleanup-lock-held" };
|
|
3724
|
+
this.pendingCleanupLocks.add(rootSessionId);
|
|
3725
|
+
try {
|
|
3726
|
+
return await this.acquireCleanupLockWithNonce(rootSessionId, selection, options, this.nonce());
|
|
3727
|
+
} finally {
|
|
3728
|
+
this.pendingCleanupLocks.delete(rootSessionId);
|
|
3729
|
+
}
|
|
3730
|
+
}
|
|
3731
|
+
|
|
3732
|
+
private localCleanupLockBusy(rootSessionId: string): boolean {
|
|
3733
|
+
return this.pendingCleanupLocks.has(rootSessionId)
|
|
3734
|
+
|| this.cleanupLocks.has(rootSessionId)
|
|
3735
|
+
|| this.maintenanceLocks.has(rootSessionId);
|
|
3736
|
+
}
|
|
3737
|
+
|
|
3738
|
+
/** Own-nonce exemption spans publication itself, validation and final release. */
|
|
3739
|
+
private async acquireMaintenanceLock(
|
|
3740
|
+
rootSessionId: string,
|
|
3741
|
+
): Promise<{ ok: true; handle: CleanupLockHandle } | { ok: false; reason: string }> {
|
|
3742
|
+
// Never replace an active exemption or borrow an admitted/pending manual
|
|
3743
|
+
// acquisition's nonce. Concurrent opportunistic maintenance can skip.
|
|
3744
|
+
if (this.localCleanupLockBusy(rootSessionId)) {
|
|
3745
|
+
return { ok: false, reason: "cleanup-lock-held" };
|
|
3746
|
+
}
|
|
3747
|
+
const nonce = this.nonce();
|
|
3748
|
+
this.maintenanceLocks.set(rootSessionId, nonce);
|
|
3749
|
+
let acquired = false;
|
|
3750
|
+
try {
|
|
3751
|
+
const result = await this.acquireCleanupLockWithNonce(
|
|
3752
|
+
rootSessionId, { scope: "session", agentIds: [], sessionFiles: [] }, {}, nonce,
|
|
3753
|
+
);
|
|
3754
|
+
acquired = result.ok;
|
|
3755
|
+
return result;
|
|
3756
|
+
} finally {
|
|
3757
|
+
if (!acquired && this.maintenanceLocks.get(rootSessionId) === nonce) {
|
|
3758
|
+
this.maintenanceLocks.delete(rootSessionId);
|
|
3759
|
+
}
|
|
3760
|
+
}
|
|
3761
|
+
}
|
|
3762
|
+
|
|
3763
|
+
private async acquireCleanupLockWithNonce(
|
|
3764
|
+
rootSessionId: string,
|
|
3765
|
+
selection: CleanupSelection,
|
|
3766
|
+
options: CleanupLockOptions,
|
|
3767
|
+
nonce: string,
|
|
3768
|
+
): Promise<{ ok: true; handle: CleanupLockHandle } | { ok: false; reason: string }> {
|
|
3769
|
+
if (!isSafePathComponent(rootSessionId)) return { ok: false, reason: "invalid-root-session-id" };
|
|
3770
|
+
let rootDir: string;
|
|
3771
|
+
if (options.createRoot === true) {
|
|
3772
|
+
try {
|
|
3773
|
+
rootDir = await this.ensureRootDirectory(rootSessionId);
|
|
3774
|
+
} catch (error) {
|
|
3775
|
+
return { ok: false, reason: `storage-error:${errorCode(error) ?? "unknown"}` };
|
|
3776
|
+
}
|
|
3777
|
+
} else {
|
|
3778
|
+
const existing = await this.existingRootDirectory(rootSessionId);
|
|
3779
|
+
if (!existing) return { ok: false, reason: "no-root" };
|
|
3780
|
+
rootDir = existing;
|
|
3781
|
+
}
|
|
3782
|
+
const path = this.lockPath(rootSessionId);
|
|
3783
|
+
const data: CleanupLockData = {
|
|
3784
|
+
version: REPORT_STORE_VERSION,
|
|
3785
|
+
pid: process.pid,
|
|
3786
|
+
nonce,
|
|
3787
|
+
rootSessionId,
|
|
3788
|
+
createdAt: this.now(),
|
|
3789
|
+
scope: selection.scope,
|
|
3790
|
+
agentIds: [...new Set(selection.agentIds)].sort(),
|
|
3791
|
+
sessionFiles: [...new Set(selection.sessionFiles.map((file) => resolve(file)))].sort(),
|
|
3792
|
+
};
|
|
3793
|
+
const handle: CleanupLockHandle = {
|
|
3794
|
+
rootSessionId,
|
|
3795
|
+
nonce,
|
|
3796
|
+
selection: {
|
|
3797
|
+
scope: data.scope,
|
|
3798
|
+
agentIds: data.agentIds,
|
|
3799
|
+
sessionFiles: data.sessionFiles,
|
|
3800
|
+
},
|
|
3801
|
+
acquiredAt: data.createdAt,
|
|
3802
|
+
};
|
|
3803
|
+
|
|
3804
|
+
let created = false;
|
|
3805
|
+
let lastReason = "cleanup-lock-held";
|
|
3806
|
+
for (let attempt = 0; attempt < 3 && !created; attempt++) {
|
|
3807
|
+
let published: "created" | "exists";
|
|
3808
|
+
try {
|
|
3809
|
+
published = await this.publishExclusiveJson(path, data, nonce);
|
|
3810
|
+
} catch (error) {
|
|
3811
|
+
return { ok: false, reason: `lock-create-failed:${errorCode(error) ?? "unknown"}` };
|
|
3812
|
+
}
|
|
3813
|
+
if (published === "created") {
|
|
3814
|
+
created = true;
|
|
3815
|
+
break;
|
|
3816
|
+
}
|
|
3817
|
+
const read = await this.readCleanupLockRead(rootSessionId);
|
|
3818
|
+
if (read.status === "live") return { ok: false, reason: "cleanup-lock-held" };
|
|
3819
|
+
if (read.status === "uncertain") return { ok: false, reason: "cleanup-lock-unreadable" };
|
|
3820
|
+
if (read.status === "dead") {
|
|
3821
|
+
const recovery = await withProcessRecoveryLock(pathKey(path), () =>
|
|
3822
|
+
this.recoverAndPublishLock(rootSessionId, rootDir, read, data, nonce),
|
|
3823
|
+
);
|
|
3824
|
+
if (recovery === "acquired") {
|
|
3825
|
+
created = true;
|
|
3826
|
+
break;
|
|
3827
|
+
}
|
|
3828
|
+
if (recovery === "busy") return { ok: false, reason: "cleanup-lock-recovery-busy" };
|
|
3829
|
+
if (recovery === "uncertain") return { ok: false, reason: "cleanup-lock-unreadable" };
|
|
3830
|
+
if (recovery === "create-failed") return { ok: false, reason: "lock-create-failed" };
|
|
3831
|
+
lastReason = "cleanup-lock-recovery-race";
|
|
3832
|
+
continue;
|
|
3833
|
+
}
|
|
3834
|
+
// Absent: another holder released it between publish and read; retry.
|
|
3835
|
+
lastReason = "cleanup-lock-held";
|
|
3836
|
+
}
|
|
3837
|
+
if (!created) return { ok: false, reason: lastReason };
|
|
3838
|
+
|
|
3839
|
+
const scan = await this.scanLeaseFiles(rootSessionId, rootDir);
|
|
3840
|
+
if (scan.uncertainty !== undefined) {
|
|
3841
|
+
await this.releaseCleanupLock(handle);
|
|
3842
|
+
return { ok: false, reason: "lease-unreadable" };
|
|
3843
|
+
}
|
|
3844
|
+
for (const lease of scan.leases) {
|
|
3845
|
+
if (lease.own) continue;
|
|
3846
|
+
if (this.pidAlive(lease.pid)) {
|
|
3847
|
+
await this.releaseCleanupLock(handle);
|
|
3848
|
+
return { ok: false, reason: "foreign-lease" };
|
|
3849
|
+
}
|
|
3850
|
+
}
|
|
3851
|
+
this.cleanupLocks.set(rootSessionId, handle);
|
|
3852
|
+
return { ok: true, handle };
|
|
3853
|
+
}
|
|
3854
|
+
|
|
3855
|
+
async releaseCleanupLock(handle: CleanupLockHandle): Promise<void> {
|
|
3856
|
+
const path = this.lockPath(handle.rootSessionId);
|
|
3857
|
+
try {
|
|
3858
|
+
const read = await this.readCleanupLockRead(handle.rootSessionId);
|
|
3859
|
+
if (read.status === "uncertain") {
|
|
3860
|
+
// Never unlink what we cannot prove is ours.
|
|
3861
|
+
this.diagnose("cleanup lock retained: metadata uncertain");
|
|
3862
|
+
return;
|
|
3863
|
+
}
|
|
3864
|
+
if (read.status === "absent") return;
|
|
3865
|
+
if (
|
|
3866
|
+
read.status !== "live" ||
|
|
3867
|
+
read.lock?.pid !== process.pid ||
|
|
3868
|
+
read.lock.nonce !== handle.nonce
|
|
3869
|
+
) {
|
|
3870
|
+
this.diagnose("cleanup lock not released: ownership changed");
|
|
3871
|
+
return;
|
|
3872
|
+
}
|
|
3873
|
+
try {
|
|
3874
|
+
await unlink(path);
|
|
3875
|
+
} catch (error) {
|
|
3876
|
+
if (!isNotFound(error)) {
|
|
3877
|
+
this.diagnose(`cleanup lock release failed: ${errorCode(error) ?? "unknown"}`);
|
|
3878
|
+
}
|
|
3879
|
+
}
|
|
3880
|
+
} finally {
|
|
3881
|
+
// Local ownership ends with the attempt, not with its success: a retained
|
|
3882
|
+
// file must keep failing closed through the file scan, never through a
|
|
3883
|
+
// stale local row that a later unlink would clear for us.
|
|
3884
|
+
this.forgetLocalOwnership(handle);
|
|
3885
|
+
}
|
|
3886
|
+
}
|
|
3887
|
+
|
|
3888
|
+
/**
|
|
3889
|
+
* Replace a report body with a minimal deletion receipt. Done before any
|
|
3890
|
+
* artifact unlink so a parent-transcript/legacy re-import cannot resurrect it.
|
|
3891
|
+
*/
|
|
3892
|
+
async writeDeletionReceipt(
|
|
3893
|
+
rootSessionId: string,
|
|
3894
|
+
expected: ReportEntry,
|
|
3895
|
+
request: DeletionReceiptRequest = {},
|
|
3896
|
+
): Promise<DeletionReceiptResult> {
|
|
3897
|
+
const rootDir = await this.existingRootDirectory(rootSessionId);
|
|
3898
|
+
if (!rootDir) throw new NotFoundError();
|
|
3899
|
+
return this.enqueue(rootDir, async () => {
|
|
3900
|
+
const path = join(rootDir, "agents", `${expected.id}.json`);
|
|
3901
|
+
const current = await this.readJson(path, parseReportEntry);
|
|
3902
|
+
if (!current) throw new NotFoundError();
|
|
3903
|
+
if (current.state === "deleted") {
|
|
3904
|
+
const generation = (await this.getRootGeneration(rootSessionId)) ?? 0;
|
|
3905
|
+
return { entry: current, rootGeneration: generation };
|
|
3906
|
+
}
|
|
3907
|
+
if (
|
|
3908
|
+
request.expectedEntryGeneration !== undefined &&
|
|
3909
|
+
current.entryGeneration !== request.expectedEntryGeneration
|
|
3910
|
+
) {
|
|
3911
|
+
throw new ReportUnavailableError("entry-changed");
|
|
3912
|
+
}
|
|
3913
|
+
const now = this.now();
|
|
3914
|
+
const deletedAt = request.deletedAt ?? now;
|
|
3915
|
+
const receipt: DeletedReportEntry = {
|
|
3916
|
+
version: REPORT_STORE_VERSION,
|
|
3917
|
+
id: current.id,
|
|
3918
|
+
entryGeneration: current.entryGeneration + 1,
|
|
3919
|
+
createdAt: current.createdAt,
|
|
3920
|
+
updatedAt: now,
|
|
3921
|
+
completedAt: current.completedAt,
|
|
3922
|
+
rootSessionId: current.rootSessionId,
|
|
3923
|
+
rootCwd: current.rootCwd,
|
|
3924
|
+
...(current.rootSessionFile === undefined
|
|
3925
|
+
? {}
|
|
3926
|
+
: { rootSessionFile: current.rootSessionFile }),
|
|
3927
|
+
type: current.type,
|
|
3928
|
+
description: current.description,
|
|
3929
|
+
...(current.handle === undefined ? {} : { handle: current.handle }),
|
|
3930
|
+
...(current.alias === undefined ? {} : { alias: current.alias }),
|
|
3931
|
+
...(current.parentAgentId === undefined
|
|
3932
|
+
? {}
|
|
3933
|
+
: { parentAgentId: current.parentAgentId }),
|
|
3934
|
+
...(current.workflowId === undefined ? {} : { workflowId: current.workflowId }),
|
|
3935
|
+
ownerIds: [...current.ownerIds],
|
|
3936
|
+
...(current.sessionFile === undefined ? {} : { sessionFile: current.sessionFile }),
|
|
3937
|
+
...(current.sessionId === undefined ? {} : { sessionId: current.sessionId }),
|
|
3938
|
+
...(current.outputFile === undefined ? {} : { outputFile: current.outputFile }),
|
|
3939
|
+
...(current.runGeneration === undefined
|
|
3940
|
+
? {}
|
|
3941
|
+
: { runGeneration: current.runGeneration }),
|
|
3942
|
+
state: "deleted",
|
|
3943
|
+
deletedAt,
|
|
3944
|
+
...(request.reason === undefined ? {} : { deletionReason: request.reason }),
|
|
3945
|
+
};
|
|
3946
|
+
await atomicWriteJson(path, receipt, this.nonce(), request.beforeCommit);
|
|
3947
|
+
const rootGeneration = await this.bumpGenerationLocked(
|
|
3948
|
+
rootDir,
|
|
3949
|
+
rootSessionId,
|
|
3950
|
+
{
|
|
3951
|
+
cwd: current.rootCwd,
|
|
3952
|
+
rootSessionId,
|
|
3953
|
+
...(current.rootSessionFile === undefined
|
|
3954
|
+
? {}
|
|
3955
|
+
: { rootSessionFile: current.rootSessionFile }),
|
|
3956
|
+
},
|
|
3957
|
+
);
|
|
3958
|
+
return { entry: receipt, rootGeneration };
|
|
3959
|
+
});
|
|
3960
|
+
}
|
|
3961
|
+
|
|
3962
|
+
/**
|
|
3963
|
+
* Minimal durable receipt for a verified legacy report. The main parent
|
|
3964
|
+
* conversation is never touched; only the archive ownership index is written,
|
|
3965
|
+
* and no root metadata is seeded for a legacy-only control namespace.
|
|
3966
|
+
*/
|
|
3967
|
+
async writeLegacyDeletionReceipt(
|
|
3968
|
+
snapshot: ReportSnapshot,
|
|
3969
|
+
request: { deletedAt?: number; reason?: string; beforeCommit?: () => Promise<void> } = {},
|
|
3970
|
+
): Promise<DeletionReceiptResult> {
|
|
3971
|
+
if (!isSafePathComponent(snapshot.rootSessionId) || !isCanonicalAgentId(snapshot.id)) {
|
|
3972
|
+
throw new ReportUnavailableError("invalid-legacy-receipt");
|
|
3973
|
+
}
|
|
3974
|
+
const rootSessionId = snapshot.rootSessionId;
|
|
3975
|
+
const rootDir = await this.existingRootDirectory(rootSessionId);
|
|
3976
|
+
if (!rootDir) throw new NotFoundError();
|
|
3977
|
+
return this.enqueue(rootDir, async () => {
|
|
3978
|
+
const agentsDir = join(rootDir, "agents");
|
|
3979
|
+
await mkdir(agentsDir, { recursive: true, mode: 0o700 });
|
|
3980
|
+
await chmodPrivate(agentsDir, 0o700);
|
|
3981
|
+
const path = join(agentsDir, `${snapshot.id}.json`);
|
|
3982
|
+
const existing = await this.readJson(path, parseReportEntry);
|
|
3983
|
+
if (existing?.state === "deleted") {
|
|
3984
|
+
const generation = (await this.getRootGeneration(rootSessionId)) ?? 0;
|
|
3985
|
+
return { entry: existing, rootGeneration: generation };
|
|
3986
|
+
}
|
|
3987
|
+
if (existing) throw new ReportUnavailableError("entry-present");
|
|
3988
|
+
const now = this.now();
|
|
3989
|
+
const receipt: DeletedReportEntry = {
|
|
3990
|
+
version: REPORT_STORE_VERSION,
|
|
3991
|
+
id: snapshot.id,
|
|
3992
|
+
entryGeneration: 1,
|
|
3993
|
+
createdAt: now,
|
|
3994
|
+
updatedAt: now,
|
|
3995
|
+
completedAt: snapshot.completedAt ?? now,
|
|
3996
|
+
rootSessionId,
|
|
3997
|
+
rootCwd: snapshot.rootCwd,
|
|
3998
|
+
...(snapshot.rootSessionFile === undefined
|
|
3999
|
+
? {}
|
|
4000
|
+
: { rootSessionFile: snapshot.rootSessionFile }),
|
|
4001
|
+
type: snapshot.type,
|
|
4002
|
+
description: snapshot.description,
|
|
4003
|
+
...(snapshot.handle === undefined ? {} : { handle: snapshot.handle }),
|
|
4004
|
+
...(snapshot.alias === undefined ? {} : { alias: snapshot.alias }),
|
|
4005
|
+
...(snapshot.parentAgentId === undefined ? {} : { parentAgentId: snapshot.parentAgentId }),
|
|
4006
|
+
...(snapshot.workflowId === undefined ? {} : { workflowId: snapshot.workflowId }),
|
|
4007
|
+
ownerIds: [...snapshot.ownerIds],
|
|
4008
|
+
...(snapshot.sessionFile === undefined ? {} : { sessionFile: snapshot.sessionFile }),
|
|
4009
|
+
...(snapshot.sessionId === undefined ? {} : { sessionId: snapshot.sessionId }),
|
|
4010
|
+
...(snapshot.outputFile === undefined ? {} : { outputFile: snapshot.outputFile }),
|
|
4011
|
+
...(snapshot.runGeneration === undefined
|
|
4012
|
+
? {}
|
|
4013
|
+
: { runGeneration: snapshot.runGeneration }),
|
|
4014
|
+
state: "deleted",
|
|
4015
|
+
deletedAt: request.deletedAt ?? now,
|
|
4016
|
+
...(request.reason === undefined ? {} : { deletionReason: request.reason }),
|
|
4017
|
+
};
|
|
4018
|
+
await atomicWriteJson(path, receipt, this.nonce(), request.beforeCommit);
|
|
4019
|
+
const metadata = await this.readJson(
|
|
4020
|
+
join(rootDir, "root.json"),
|
|
4021
|
+
(value) => parseRootMetadata(value, rootSessionId),
|
|
4022
|
+
);
|
|
4023
|
+
const rootGeneration =
|
|
4024
|
+
metadata === undefined
|
|
4025
|
+
? 0
|
|
4026
|
+
: await this.bumpGenerationLocked(rootDir, rootSessionId, {
|
|
4027
|
+
cwd: snapshot.rootCwd,
|
|
4028
|
+
rootSessionId,
|
|
4029
|
+
...(snapshot.rootSessionFile === undefined
|
|
4030
|
+
? {}
|
|
4031
|
+
: { rootSessionFile: snapshot.rootSessionFile }),
|
|
4032
|
+
});
|
|
4033
|
+
return { entry: receipt, rootGeneration };
|
|
4034
|
+
});
|
|
4035
|
+
}
|
|
4036
|
+
|
|
4037
|
+
/** Remove a workflow ownership entry once its generated files are gone. */
|
|
4038
|
+
async removeWorkflowRegistration(
|
|
4039
|
+
rootSessionId: string,
|
|
4040
|
+
workflowId: string,
|
|
4041
|
+
expectedUpdatedAt?: number,
|
|
4042
|
+
beforeRemove?: () => Promise<void>,
|
|
4043
|
+
): Promise<{ removed: boolean; reason?: string; rootGeneration?: number }> {
|
|
4044
|
+
if (!isSafePathComponent(rootSessionId) || !isSafePathComponent(workflowId)) {
|
|
4045
|
+
return { removed: false, reason: "invalid-workflow-id" };
|
|
4046
|
+
}
|
|
4047
|
+
const rootDir = await this.existingRootDirectory(rootSessionId);
|
|
4048
|
+
if (!rootDir) return { removed: false, reason: "no-root" };
|
|
4049
|
+
return this.enqueue(rootDir, async () => {
|
|
4050
|
+
const path = join(rootDir, "workflows", `${workflowId}.json`);
|
|
4051
|
+
const existing = await this.readJson(path, parseWorkflowEntry);
|
|
4052
|
+
if (!existing) return { removed: false, reason: "registration-missing" };
|
|
4053
|
+
if (expectedUpdatedAt !== undefined && existing.updatedAt !== expectedUpdatedAt) {
|
|
4054
|
+
return { removed: false, reason: "registration-changed" };
|
|
4055
|
+
}
|
|
4056
|
+
// Outside the unlink catch: a refusal must propagate unchanged.
|
|
4057
|
+
if (beforeRemove !== undefined) await beforeRemove();
|
|
4058
|
+
try {
|
|
4059
|
+
await unlink(path);
|
|
4060
|
+
} catch (error) {
|
|
4061
|
+
if (isNotFound(error)) return { removed: false, reason: "registration-missing" };
|
|
4062
|
+
return { removed: false, reason: `unlink-failed:${errorCode(error) ?? "unknown"}` };
|
|
4063
|
+
}
|
|
4064
|
+
const rootGeneration = await this.bumpGenerationLocked(
|
|
4065
|
+
rootDir,
|
|
4066
|
+
rootSessionId,
|
|
4067
|
+
{
|
|
4068
|
+
cwd: existing.rootCwd,
|
|
4069
|
+
rootSessionId,
|
|
4070
|
+
...(existing.rootSessionFile === undefined
|
|
4071
|
+
? {}
|
|
4072
|
+
: { rootSessionFile: existing.rootSessionFile }),
|
|
4073
|
+
},
|
|
4074
|
+
);
|
|
4075
|
+
return { removed: true, rootGeneration };
|
|
4076
|
+
});
|
|
4077
|
+
}
|
|
4078
|
+
|
|
4079
|
+
/**
|
|
4080
|
+
* Remove root metadata only when no report/workflow entry remains. The caller
|
|
4081
|
+
* holds the cleanup lock; the lock file itself is not metadata.
|
|
4082
|
+
*/
|
|
4083
|
+
async removeRootMetadata(
|
|
4084
|
+
rootSessionId: string,
|
|
4085
|
+
expectedGeneration: number,
|
|
4086
|
+
beforeRemove?: () => Promise<void>,
|
|
4087
|
+
): Promise<{ removed: boolean; reason?: string }> {
|
|
4088
|
+
const rootDir = await this.existingRootDirectory(rootSessionId);
|
|
4089
|
+
if (!rootDir) return { removed: false, reason: "no-root" };
|
|
4090
|
+
return this.enqueue(rootDir, async () => {
|
|
4091
|
+
const path = join(rootDir, "root.json");
|
|
4092
|
+
const metadata = await this.readJsonScan(path, "root-metadata", (value) =>
|
|
4093
|
+
parseRootMetadata(value, rootSessionId),
|
|
4094
|
+
);
|
|
4095
|
+
if (metadata.uncertainty !== undefined) {
|
|
4096
|
+
// Never unlink metadata that cannot be proven not to be an identity keeper.
|
|
4097
|
+
return { removed: false, reason: `root-metadata-unreadable:${metadata.uncertainty}` };
|
|
4098
|
+
}
|
|
4099
|
+
// A known main-session identity is a technical keeper: it must survive every
|
|
4100
|
+
// cleanup, including a stale/forged plan that previewed its removal.
|
|
4101
|
+
if (metadata.value?.rootSessionFile !== undefined) {
|
|
4102
|
+
return { removed: false, reason: "root-identity-keeper" };
|
|
4103
|
+
}
|
|
4104
|
+
const generation = metadata.value?.generation ?? 0;
|
|
4105
|
+
if (generation !== expectedGeneration) return { removed: false, reason: "root-generation-changed" };
|
|
4106
|
+
const nonEmpty = async (dir: string): Promise<boolean | undefined> => {
|
|
4107
|
+
try {
|
|
4108
|
+
return (await readdir(dir)).length > 0;
|
|
4109
|
+
} catch (error) {
|
|
4110
|
+
if (isNotFound(error)) return false;
|
|
4111
|
+
return undefined;
|
|
4112
|
+
}
|
|
4113
|
+
};
|
|
4114
|
+
const agents = await nonEmpty(join(rootDir, "agents"));
|
|
4115
|
+
if (agents === undefined) return { removed: false, reason: "agents-dir-unreadable" };
|
|
4116
|
+
const workflows = await nonEmpty(join(rootDir, "workflows"));
|
|
4117
|
+
if (workflows === undefined) return { removed: false, reason: "workflows-dir-unreadable" };
|
|
4118
|
+
if (agents || workflows) return { removed: false, reason: "root-not-empty" };
|
|
4119
|
+
// Outside the unlink catch: a refusal must propagate unchanged.
|
|
4120
|
+
if (beforeRemove !== undefined) await beforeRemove();
|
|
4121
|
+
try {
|
|
4122
|
+
await unlink(path);
|
|
4123
|
+
return { removed: true };
|
|
4124
|
+
} catch (error) {
|
|
4125
|
+
if (isNotFound(error)) return { removed: true };
|
|
4126
|
+
return { removed: false, reason: `unlink-failed:${errorCode(error) ?? "unknown"}` };
|
|
4127
|
+
}
|
|
4128
|
+
});
|
|
4129
|
+
}
|
|
4130
|
+
}
|