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