@wezzard/mcp-relay 0.0.0-stage → 0.14.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.
@@ -0,0 +1,68 @@
1
+ export interface CommandOutput {
2
+ exit?: number | null;
3
+ signal?: string | null;
4
+ timedOut?: boolean;
5
+ stdout?: string;
6
+ stderr?: string;
7
+ }
8
+ /** Evidence about a step that the trajectory does not carry as fields. */
9
+ export interface StepDetail {
10
+ /** When the step started: the action start, or the diagnostic request. */
11
+ at?: string;
12
+ beforeAt?: string;
13
+ afterAt?: string;
14
+ /** The guest command, exactly as requested. */
15
+ argv?: string[];
16
+ output?: CommandOutput;
17
+ }
18
+ export interface ReviewPageStep {
19
+ id: string;
20
+ title: string;
21
+ execution: string;
22
+ state: string;
23
+ inputMode: string;
24
+ because?: string;
25
+ expected?: string;
26
+ observed?: string;
27
+ snapshots?: {
28
+ before?: string;
29
+ after?: string;
30
+ groupId?: string;
31
+ declaredAfterIntervalMs?: number;
32
+ };
33
+ }
34
+ /** A plain-words reason for a verdict that is not complete or passed, with the steps it concerns and what the reader can do. */
35
+ export interface Reason {
36
+ text: string;
37
+ stepIds: string[];
38
+ action?: string;
39
+ }
40
+ /** A package's review data: JSON, with the details keyed by step id. */
41
+ export interface ReviewData {
42
+ packageId: string;
43
+ sessionId: string;
44
+ taskId: string;
45
+ completeness: string;
46
+ execution: string;
47
+ findings: string[];
48
+ /** Why each verdict is not complete or passed, and the relay's own defects, which change no verdict. */
49
+ reasons: {
50
+ snapshots: Reason[];
51
+ execution: Reason[];
52
+ defects?: Reason[];
53
+ };
54
+ steps: ReviewPageStep[];
55
+ details: Record<string, StepDetail>;
56
+ /** Declared extractions, by package path. */
57
+ outputs: {
58
+ path: string;
59
+ bytes: number;
60
+ }[];
61
+ /** The package's own files, by package path: its seal, its opening note, and an earlier relay's derived files. */
62
+ files: {
63
+ path: string;
64
+ bytes: number;
65
+ }[];
66
+ }
67
+ /** The steps, verdicts and reasons of the package in `dir`, with each step's snapshots as package paths. */
68
+ export declare const reviewData: (dir: string) => Promise<ReviewData>;
@@ -0,0 +1,404 @@
1
+ import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+
7
+ // node_modules/@wezzard/relay-driver-host-sdk/dist/src/evidence-package.js
8
+ var init_evidence_package = __esm({
9
+ "node_modules/@wezzard/relay-driver-host-sdk/dist/src/evidence-package.js"() {
10
+ }
11
+ });
12
+
13
+ // src/package.ts
14
+ import { createHash } from "node:crypto";
15
+ import { lstat, readFile, readdir, mkdir, writeFile, rm } from "node:fs/promises";
16
+ import { dirname, join, resolve, parse } from "node:path";
17
+
18
+ // node_modules/@wezzard/relay-driver-host-sdk/dist/src/index.js
19
+ init_evidence_package();
20
+
21
+ // src/package.ts
22
+ var hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
23
+ function object(value, label) {
24
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`invalid ${label}`);
25
+ return value;
26
+ }
27
+ function text(value, label) {
28
+ if (typeof value !== "string" || !value.trim()) throw new Error(`invalid ${label}`);
29
+ return value;
30
+ }
31
+ function relativePath(value) {
32
+ const path = text(value, "package path");
33
+ if (path.includes("\\") || /[\x00-\x1f:#?]/.test(path) || path.split("/").some((p) => !p || p === "." || p === "..")) {
34
+ throw new Error(`unsafe package path: ${path}`);
35
+ }
36
+ return path;
37
+ }
38
+ async function rootPath(rootDir) {
39
+ const root = resolve(rootDir);
40
+ let current = parse(root).root;
41
+ for (const part of root.slice(current.length).split("/").filter(Boolean)) {
42
+ current = join(current, part);
43
+ const info = await lstat(current);
44
+ if (info.isSymbolicLink() || !info.isDirectory()) throw new Error(`unsafe package directory: ${current}`);
45
+ }
46
+ return root;
47
+ }
48
+ async function filesUnder(root, prefix = "") {
49
+ const result = [];
50
+ for (const entry of await readdir(join(root, prefix), { withFileTypes: true })) {
51
+ const path = relativePath(prefix ? `${prefix}/${entry.name}` : entry.name);
52
+ const info = await lstat(join(root, path));
53
+ if (info.isSymbolicLink()) throw new Error(`symlink in package: ${path}`);
54
+ if (info.isDirectory()) result.push(...await filesUnder(root, path));
55
+ else if (info.isFile() && info.nlink === 1) result.push(path);
56
+ else throw new Error(`non-regular or hard-linked package artifact: ${path}`);
57
+ }
58
+ return result.sort();
59
+ }
60
+ async function readJson(root, path) {
61
+ return object(JSON.parse(await readFile(join(root, relativePath(path)), "utf8")), path);
62
+ }
63
+ function snapshotPath(sessionId, sn) {
64
+ const name = relativePath(sn.fileName);
65
+ if (name.includes("/")) throw new Error("snapshot fileName must be a basename");
66
+ return relativePath(`state/snapshots/${relativePath(sessionId)}/${name}`);
67
+ }
68
+ function sameRef(ref, sn) {
69
+ return ref.sha256 === sn.sha256 && ref.bytes === sn.bytes && ref.role === sn.role && ref.capturedAt === sn.capturedAt && ref.declaredAfterIntervalMs === sn.declaredAfterIntervalMs;
70
+ }
71
+ function outcomeOf(completion, refused) {
72
+ if (refused) return "refused";
73
+ if (!completion) return "incomplete";
74
+ if (completion.state === "uncertain" || !completion.toolOutcome) return "uncertain";
75
+ const outcome = object(completion.toolOutcome, "tool outcome");
76
+ if (outcome.kind === "failure") return "failed";
77
+ if (outcome.kind !== "success") return "uncertain";
78
+ const value = outcome.value;
79
+ if (value && typeof value === "object") {
80
+ if (value.timedOut || value.outputRefused || value.signal || value.exitStatus?.signal) return "failed";
81
+ for (const code of [value.code, value.exitCode, value.exitStatus?.code]) {
82
+ if (typeof code === "number" && code !== 0) return "failed";
83
+ if (code === null) return "uncertain";
84
+ }
85
+ }
86
+ return "completed";
87
+ }
88
+ function receiptOutcome(receipt) {
89
+ const outcome = receipt.outcome;
90
+ if (outcome?.kind === "refused") return "refused";
91
+ if (outcome?.kind !== "completed") return "uncertain";
92
+ const exit = outcome.exitStatus;
93
+ if (typeof exit?.code === "number" && exit.code !== 0 || exit?.signal) return "failed";
94
+ return Number.isSafeInteger(exit?.code) && exit.code === 0 && exit.signal === null ? "completed" : "uncertain";
95
+ }
96
+ function reconcileOutcome(original, receipts) {
97
+ const outcomes = [original, ...receipts.map(receiptOutcome)];
98
+ if (outcomes.includes("refused")) return "refused";
99
+ if (outcomes.includes("failed")) return "failed";
100
+ return original === "completed" && outcomes.includes("uncertain") ? "uncertain" : original;
101
+ }
102
+ async function analyze(root, options, files) {
103
+ text(options.packageId, "packageId");
104
+ text(options.sessionId, "sessionId");
105
+ text(options.taskId, "taskId");
106
+ relativePath(options.sessionId);
107
+ const journalPath = "state/journal/events.jsonl";
108
+ if (!files.includes(journalPath)) throw new Error("missing original state/journal/events.jsonl");
109
+ const events = (await readFile(join(root, journalPath), "utf8")).split("\n").filter((l) => l.trim()).map((l, i) => object(JSON.parse(l), `journal line ${i + 1}`));
110
+ const starts = /* @__PURE__ */ new Map(), completions = /* @__PURE__ */ new Map(), refusals = /* @__PURE__ */ new Map();
111
+ const actionRecords = /* @__PURE__ */ new Map();
112
+ const findings = [];
113
+ for (const event of events) {
114
+ if (event.sessionId !== void 0 && event.sessionId !== options.sessionId) throw new Error("journal session identity mismatch");
115
+ for (const [kind, map] of [["action-start", starts], ["action-completion", completions], ["action-refusal", refusals]]) {
116
+ if (event.kind !== kind) continue;
117
+ const id = text(event.actionId, "actionId");
118
+ if (map.has(id)) throw new Error(`duplicate ${kind}: ${id}`);
119
+ map.set(id, event);
120
+ }
121
+ }
122
+ for (const path of files.filter((p) => /^state\/records\/actions?\/[^/]+\.json$/.test(p))) {
123
+ const record = await readJson(root, path), id = text(record.actionId, "action record id");
124
+ if (record.sessionId !== options.sessionId || actionRecords.has(id)) throw new Error(`invalid action record identity: ${id}`);
125
+ actionRecords.set(id, record);
126
+ const start = starts.get(id), completion = completions.get(id);
127
+ if (start && record.attemptId !== start.attemptId) throw new Error(`action attempt mismatch: ${id}`);
128
+ if (completion && record.toolOutcome !== void 0 && JSON.stringify(record.toolOutcome) !== JSON.stringify(completion.toolOutcome)) throw new Error(`action outcome disagrees with journal: ${id}`);
129
+ if (!starts.has(id) && !refusals.has(id)) findings.push(`action ${id} has no retained start or refusal`);
130
+ }
131
+ for (const id of completions.keys()) if (!starts.has(id)) throw new Error(`completion references unknown action ${id}`);
132
+ const snapshots = [], byPath = /* @__PURE__ */ new Map();
133
+ for (const event of events.filter((e) => e.kind === "snapshot-captured")) {
134
+ const id = text(event.actionId, "snapshot actionId"), start = starts.get(id);
135
+ if (!start) throw new Error(`snapshot references unknown action ${id}`);
136
+ if (events.indexOf(event) <= events.indexOf(start) || completions.has(id) && events.indexOf(event) >= events.indexOf(completions.get(id))) throw new Error(`snapshot outside action interval: ${id}`);
137
+ const sn = object(event.snapshot, "captured snapshot"), path = snapshotPath(options.sessionId, sn);
138
+ if (byPath.has(path)) throw new Error(`duplicate snapshot capture: ${path}`);
139
+ if (sn.role !== "before" && sn.role !== "after") throw new Error(`invalid snapshot role: ${path}`);
140
+ if (!/^[a-f0-9]{64}$/.test(sn.sha256) || !Number.isSafeInteger(sn.bytes) || sn.bytes < 0) throw new Error(`invalid capture integrity: ${path}`);
141
+ if (!Number.isFinite(Date.parse(text(sn.capturedAt, "capture timestamp")))) throw new Error(`invalid capture timestamp: ${path}`);
142
+ if (sn.role === "after" && (typeof sn.declaredAfterIntervalMs !== "number" || !Number.isFinite(sn.declaredAfterIntervalMs) || sn.declaredAfterIntervalMs < 0)) throw new Error(`invalid declared after interval: ${path}`);
143
+ const plan = start.snapshotPlan;
144
+ if (!plan || (event.group ?? void 0) !== plan.group?.groupId) throw new Error(`snapshot group/plan mismatch: ${id}`);
145
+ if (event.attemptId !== start.attemptId) throw new Error(`snapshot attempt mismatch: ${id}`);
146
+ if (sn.role === "before" && !plan.capturesBefore || sn.role === "after" && (!plan.capturesAfter || plan.capturesAfter.afterIntervalMs !== sn.declaredAfterIntervalMs)) throw new Error(`snapshot contradicts declared plan: ${id}`);
147
+ if (!files.includes(path)) throw new Error(`missing captured original: ${path}`);
148
+ const bytes = await readFile(join(root, path));
149
+ if (bytes.length !== sn.bytes || hash(bytes) !== sn.sha256) throw new Error(`capture integrity mismatch: ${path}`);
150
+ const artifact = {
151
+ path,
152
+ sha256: sn.sha256,
153
+ bytes: sn.bytes,
154
+ actionId: id,
155
+ role: sn.role,
156
+ capturedAt: sn.capturedAt,
157
+ provenance: "dispatch-captured",
158
+ ...event.group ? { groupId: text(event.group, "groupId") } : {},
159
+ ...sn.declaredAfterIntervalMs !== void 0 ? { declaredAfterIntervalMs: sn.declaredAfterIntervalMs } : {}
160
+ };
161
+ snapshots.push(artifact);
162
+ byPath.set(path, artifact);
163
+ }
164
+ for (const path of files.filter((p) => p.startsWith("state/snapshots/") && !p.endsWith(".part"))) {
165
+ if (!byPath.has(path)) throw new Error(`snapshot original has no captured journal record: ${path}`);
166
+ }
167
+ for (const record of [...actionRecords.values(), ...events.filter((e) => e.kind === "snapshot-evidence")]) {
168
+ const id = text(record.actionId, "snapshot reference actionId"), start = starts.get(id);
169
+ if (record.snapshots === void 0) continue;
170
+ if (!start || !Array.isArray(record.snapshots)) throw new Error(`invalid snapshot references for ${id}`);
171
+ if ((record.groupId ?? void 0) !== start.snapshotPlan?.group?.groupId || record.snapshotRole !== start.snapshotPlan?.role) throw new Error(`action group reference mismatch: ${id}`);
172
+ const cited = /* @__PURE__ */ new Set();
173
+ for (const raw of record.snapshots) {
174
+ const ref = object(raw, "snapshot reference"), path = snapshotPath(options.sessionId, ref), sn = byPath.get(path);
175
+ if (!sn || sn.actionId !== id || !sameRef(ref, sn) || cited.has(path)) throw new Error(`invalid action snapshot reference: ${id} -> ${path}`);
176
+ cited.add(path);
177
+ }
178
+ for (const sn of snapshots.filter((s) => s.actionId === id)) if (!cited.has(sn.path)) findings.push(`action ${id} is missing reverse snapshot reference ${sn.path}`);
179
+ }
180
+ const groups = /* @__PURE__ */ new Map();
181
+ for (const start of starts.values()) {
182
+ const plan = start.snapshotPlan;
183
+ if (plan?.group) {
184
+ const id = text(plan.group.groupId, "group identity");
185
+ groups.set(id, [...groups.get(id) ?? [], start]);
186
+ }
187
+ }
188
+ const incompleteGroups = /* @__PURE__ */ new Set();
189
+ for (const [id, members] of groups) {
190
+ const pair = snapshots.filter((s) => s.groupId === id);
191
+ const roles = members.map((m) => m.snapshotPlan.role);
192
+ const invalid = roles[0] !== "first" || roles.at(-1) !== "last" || roles.slice(1, -1).some((r) => r !== "member") || members.length < 2 || new Set(members.map((m) => m.attemptId)).size !== 1;
193
+ const allStarts = [...starts.values()];
194
+ const positions = members.map((m) => allStarts.indexOf(m));
195
+ if (invalid || positions.some((p, i) => i > 0 && p !== positions[i - 1] + 1) || pair.length !== 2 || !pair.some((s) => s.role === "before") || !pair.some((s) => s.role === "after")) {
196
+ incompleteGroups.add(id);
197
+ findings.push(`coalescing group ${id} lacks a complete consecutive first/member/last causal pair`);
198
+ }
199
+ if (pair.filter((s) => s.role === "before").length > 1 || pair.filter((s) => s.role === "after").length > 1) throw new Error(`duplicate group snapshot role: ${id}`);
200
+ }
201
+ const hostRecords = events.filter((e) => e.kind === "annotation" && e.annotationType === "routing-decision");
202
+ for (const path of files.filter((p) => p.startsWith("host/") && /\.jsonl?$/.test(p))) {
203
+ const raw = await readFile(join(root, path), "utf8");
204
+ for (const value of path.endsWith(".jsonl") ? raw.split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l)) : [JSON.parse(raw)]) {
205
+ if (value && typeof value === "object") hostRecords.push(value);
206
+ }
207
+ }
208
+ const receipts = [];
209
+ const retainReceipt = (raw, envelope) => {
210
+ const receipt = object(raw, "execution receipt");
211
+ for (const key of ["executionId", "actionId", "sessionId"]) {
212
+ if (receipt[key] !== void 0) text(receipt[key], `receipt ${key}`);
213
+ if (envelope?.[key] !== void 0 && receipt[key] !== void 0 && envelope[key] !== receipt[key]) throw new Error(`receipt ${key} identity mismatch`);
214
+ }
215
+ if (receipt.sessionId !== void 0 && receipt.sessionId !== options.sessionId) throw new Error("receipt session identity mismatch");
216
+ const executionId = receipt.executionId ?? envelope?.executionId;
217
+ const actionId = receipt.actionId ?? envelope?.actionId;
218
+ if (executionId === void 0 && actionId === void 0) throw new Error("receipt lacks execution/action identity");
219
+ receipts.push({ ...receipt, executionId, actionId });
220
+ };
221
+ for (const event of events.filter((e) => e.kind === "execution-completion")) retainReceipt(event.response, event);
222
+ for (const path of files.filter((p) => /^(?:host\/(?:receipts|receiver-receipts)|state\/receiver\/receipts)\/[^/]+\.json$/.test(p) || /^host\/diagnostics\/[^/]+\.receipt\.json$/.test(p))) retainReceipt(await readJson(root, path));
223
+ const routingRecords = hostRecords.filter((h) => h.because !== void 0 || h.request?.because !== void 0 || h.step !== void 0 || h.request?.step !== void 0);
224
+ const steps = [], used = /* @__PURE__ */ new Set(), details = /* @__PURE__ */ new Map(), stepsByExecution = /* @__PURE__ */ new Map();
225
+ const commandOutput = (value, exitStatus) => {
226
+ if (!value) return void 0;
227
+ const exit = exitStatus ?? value.outcome?.exitStatus ?? value.exitStatus;
228
+ const stdout = typeof value.stdout === "string" ? value.stdout : typeof value.output === "string" ? value.output : void 0;
229
+ const stderr = typeof value.stderr === "string" ? value.stderr : void 0;
230
+ if (exit === void 0 && stdout === void 0 && stderr === void 0) return void 0;
231
+ return { ...exit ? { exit: exit.code ?? null, signal: exit.signal ?? null } : {}, ...typeof value.timedOut === "boolean" ? { timedOut: value.timedOut } : {}, stdout, stderr };
232
+ };
233
+ for (const id of /* @__PURE__ */ new Set([...starts.keys(), ...refusals.keys(), ...actionRecords.keys()])) {
234
+ const start = starts.get(id), record = actionRecords.get(id), refusal = refusals.get(id);
235
+ const source = start ?? refusal ?? record;
236
+ if (receipts.some((r) => r.evidenceMode === "diagnostic" && r.executionId === (source.executionId ?? record?.executionId))) continue;
237
+ const plan = start?.snapshotPlan, groupId = plan?.group?.groupId;
238
+ const pair = snapshots.filter((s) => groupId ? s.groupId === groupId : s.actionId === id);
239
+ if (pair.filter((s) => s.role === "before").length > 1 || pair.filter((s) => s.role === "after").length > 1) throw new Error(`duplicate action snapshot role: ${id}`);
240
+ const before = pair.find((s) => s.role === "before"), after = pair.find((s) => s.role === "after");
241
+ if (before && after && (snapshots.indexOf(before) >= snapshots.indexOf(after) || Date.parse(before.capturedAt) > Date.parse(after.capturedAt))) throw new Error(`reversed causal pair: ${id}`);
242
+ const runId = source.executionId ?? record?.executionId;
243
+ const uncaptured = !!start && !plan && events.some((e) => e.kind === "execution-start" && e.executionId === runId && e.capture === false);
244
+ const missingPair = !!start && !uncaptured && (!plan || !before || !after || groupId && incompleteGroups.has(groupId));
245
+ if (missingPair) findings.push(`action ${id} lacks its declared causal pair`);
246
+ if (start && !record) findings.push(`action ${id} has no materialized action record`);
247
+ if (pair.length && (!record?.snapshots || !events.some((e) => e.kind === "snapshot-evidence" && e.actionId === id))) findings.push(`action ${id} lacks durable reverse snapshot references`);
248
+ let execution2 = outcomeOf(completions.get(id), !!refusal || record?.state === "refused");
249
+ if (execution2 === "completed" && (missingPair || !record || record.state !== "recorded")) execution2 = "uncertain";
250
+ const rawId = source.stepId ?? record?.stepId ?? id;
251
+ let stepId = text(rawId, "step id");
252
+ if (used.has(stepId)) stepId = `${stepId}@${id}`;
253
+ if (used.has(stepId)) throw new Error(`duplicate review step id: ${stepId}`);
254
+ used.add(stepId);
255
+ const executionId = source.executionId ?? record?.executionId;
256
+ const exactHost = routingRecords.find((h) => h.actionId === id || executionId && (h.executionId === executionId || h.request?.executionId === executionId));
257
+ const fallback = routingRecords.filter((h) => source.stepId && (h.stepId === source.stepId || h.step?.id === source.stepId || h.request?.step?.id === source.stepId));
258
+ const fallbackIdentities = new Set(fallback.map((h) => h.executionId ?? h.request?.executionId ?? h.actionId ?? h));
259
+ const candidate = fallbackIdentities.size === 1 ? fallback[0] : void 0;
260
+ const host = exactHost ?? (candidate && (!candidate.actionId || candidate.actionId === id) && (!executionId || !(candidate.executionId ?? candidate.request?.executionId) || (candidate.executionId ?? candidate.request?.executionId) === executionId) ? candidate : void 0);
261
+ const because = source.because ?? host?.because ?? host?.request?.because;
262
+ const actionReceipts = receipts.filter((r) => (r.actionId === id || executionId && r.executionId === executionId) && (r.actionId === void 0 || r.actionId === id) && (r.executionId === void 0 || executionId === void 0 || r.executionId === executionId));
263
+ execution2 = reconcileOutcome(execution2, actionReceipts);
264
+ const completion = completions.get(id);
265
+ const argv = events.find((e) => e.kind === "execution-start" && executionId && e.executionId === executionId && Array.isArray(e.argv))?.argv;
266
+ details.set(stepId, {
267
+ at: source.writtenAt ?? before?.capturedAt,
268
+ beforeAt: before?.capturedAt,
269
+ afterAt: after?.capturedAt,
270
+ ...argv?.every((w) => typeof w === "string") ? { argv } : {},
271
+ output: commandOutput(actionReceipts.find((r) => commandOutput(r)) ?? completion?.toolOutcome?.value)
272
+ });
273
+ const originalObserved = refusal?.diagnostic ?? completion?.diagnostic ?? (completion?.toolOutcome ? JSON.stringify(completion.toolOutcome) : void 0);
274
+ const observed = actionReceipts.length ? `Authoritative receipt outcomes: ${JSON.stringify(actionReceipts.map((r) => ({ executionId: r.executionId, actionId: r.actionId, execution: receiptOutcome(r), outcome: r.outcome })))}
275
+ Original subprocess/action evidence (not an authoritative input-success verdict): ${JSON.stringify({ refusal: refusal?.diagnostic, state: completion?.state, diagnostic: completion?.diagnostic, toolOutcome: completion?.toolOutcome })}` : originalObserved;
276
+ if (executionId) stepsByExecution.set(executionId, [...stepsByExecution.get(executionId) ?? [], stepId]);
277
+ steps.push({
278
+ id: stepId,
279
+ actionId: id,
280
+ inputMode: source.inputMode ?? record?.inputMode ?? "unknown",
281
+ attemptId: source.attemptId ?? "unknown-attempt",
282
+ title: source.title ?? record?.title ?? id,
283
+ execution: execution2,
284
+ state: record?.state ?? source.state ?? "unknown",
285
+ expected: host?.step?.expected ?? host?.request?.step?.expected,
286
+ observed,
287
+ ...typeof because === "string" ? { because } : {},
288
+ ...pair.length ? { snapshots: { before: before?.path, after: after?.path, groupId, declaredAfterIntervalMs: after?.declaredAfterIntervalMs } } : {}
289
+ });
290
+ }
291
+ const diagnostics = /* @__PURE__ */ new Map();
292
+ for (const receipt of receipts.filter((r) => r.evidenceMode === "diagnostic")) diagnostics.set(text(receipt.executionId, "diagnostic execution id"), receipt);
293
+ for (const [executionId, receipt] of diagnostics) {
294
+ const request = hostRecords.find((h) => h.executionId === executionId && (h.diagnostic === true || h.evidenceMode === "diagnostic") && h.argv);
295
+ const stepId = `diagnostic-${executionId}`;
296
+ if (used.has(stepId)) throw new Error(`duplicate diagnostic review step: ${stepId}`);
297
+ used.add(stepId);
298
+ details.set(stepId, {
299
+ at: typeof request?.at === "string" ? request.at : void 0,
300
+ ...Array.isArray(request?.argv) && request.argv.every((w) => typeof w === "string") ? { argv: request.argv } : {},
301
+ output: commandOutput(receipt)
302
+ });
303
+ stepsByExecution.set(executionId, [...stepsByExecution.get(executionId) ?? [], stepId]);
304
+ steps.push({
305
+ id: stepId,
306
+ actionId: executionId,
307
+ inputMode: "diagnostic",
308
+ attemptId: request?.attemptId ?? executionId,
309
+ title: request?.step?.title ?? "Diagnostic command",
310
+ execution: receiptOutcome(receipt),
311
+ state: "diagnostic",
312
+ because: request?.because,
313
+ expected: request?.step?.expected,
314
+ observed: `No screenshot evidence. ${JSON.stringify({ outcome: receipt.outcome, ...receipt.output !== void 0 ? { output: receipt.output } : { stdout: receipt.stdout, stderr: receipt.stderr }, timeoutMs: receipt.timeoutMs })}`
315
+ });
316
+ }
317
+ if (events.some((e) => ["evidence-failure", "capture-status", "resource-stop"].includes(e.kind) && ["incomplete", "uncertain"].includes(e.state))) findings.push("journal records incomplete evidence or a resource stop");
318
+ if (files.some((p) => p.startsWith("state/snapshots/") && p.endsWith(".part"))) findings.push("unfinished snapshot originals retained");
319
+ for (const request of hostRecords.filter((h) => typeof h.because === "string" && typeof h.executionId === "string" && !diagnostics.has(h.executionId))) {
320
+ if (![...starts.values()].some((s) => s.executionId === request.executionId) && !events.some((e) => e.kind === "execution-completion" && e.executionId === request.executionId) && !receipts.some((r) => r.executionId === request.executionId && r.outcome?.kind === "refused")) {
321
+ findings.push(`request ${request.executionId} has no retained guest execution`);
322
+ }
323
+ }
324
+ const bearing = (finding) => /^action \S+ (has no retained start or refusal|is missing reverse snapshot reference |has no materialized action record|lacks durable reverse snapshot references)/.test(finding) ? "defects" : /^request \S+ has no retained guest execution$/.test(finding) ? "execution" : "snapshots";
325
+ const explained = (key) => findings.filter((f) => bearing(f) === key).map((finding) => explainFinding(finding, steps, stepsByExecution));
326
+ const snapshotReasons = explained("snapshots"), unexecuted = explained("execution"), defectReasons = explained("defects");
327
+ const completeness = snapshotReasons.length ? "incomplete" : "complete";
328
+ const receiptFailed = receipts.some((r) => ["refused", "failed"].includes(receiptOutcome(r)));
329
+ const receiptUncertain = receipts.some((r) => receiptOutcome(r) === "uncertain");
330
+ const execution = receiptFailed || steps.some((s) => s.execution === "failed" || s.execution === "refused") ? "failed" : receiptUncertain || !steps.length || unexecuted.length || steps.some((s) => s.execution !== "completed") ? "uncertain" : "passed";
331
+ if (receiptFailed) findings.push("retained execution receipt reports refusal or failure");
332
+ if (receiptUncertain) findings.push("retained execution receipt reports uncertainty");
333
+ const failedSteps = steps.filter((s) => s.execution === "failed" || s.execution === "refused").map((s) => s.id);
334
+ const unsettled = steps.filter((s) => !["completed", "failed", "refused"].includes(s.execution)).map((s) => s.id);
335
+ const receiptSteps = (outcomes) => [...new Set(receipts.filter((r) => outcomes.includes(receiptOutcome(r))).flatMap((r) => [...stepsByExecution.get(r.executionId) ?? [], ...steps.filter((s) => s.actionId === r.actionId).map((s) => s.id)]))];
336
+ const rerun = "Look for its effect in the next step's before snapshot, or run the task again.";
337
+ const executionReasons = execution === "passed" ? [] : [
338
+ ...failedSteps.length ? [{ text: "The guest refused or failed these steps.", stepIds: failedSteps, action: "Open each step to read what the guest reported, correct the cause, and run the task again." }] : [],
339
+ ...receiptFailed ? [{ text: "A retained receipt reports that the guest refused or failed an execution.", stepIds: receiptSteps(["refused", "failed"]), action: "Open the step to read the receipt, correct the cause, and run the task again." }] : [],
340
+ ...execution === "uncertain" && receiptUncertain ? [{ text: "A retained receipt cannot confirm whether the guest ran an execution, for example because the connection was lost.", stepIds: receiptSteps(["uncertain"]), action: rerun }] : [],
341
+ ...execution === "uncertain" && !steps.length ? [{ text: "The package holds no steps, so there is nothing whose execution could be confirmed.", stepIds: [], action: "Run the task again; this run recorded nothing." }] : [],
342
+ ...execution === "uncertain" ? unexecuted : [],
343
+ ...execution === "uncertain" && unsettled.length ? [{ text: "The relay cannot confirm these steps' outcomes: they reported none, or they lack the snapshots that would show it.", stepIds: unsettled, action: "Look for each step's effect in the next step's before snapshot, or run the task again." }] : []
344
+ ];
345
+ const outputs = [];
346
+ for (const path of files.filter((p) => p.startsWith("extractions/")).sort()) outputs.push({ path, bytes: (await lstat(join(root, path))).size });
347
+ return { snapshots, steps, incompleteGroups, findings, completeness, execution, details, outputs, reasons: { snapshots: snapshotReasons, execution: executionReasons, defects: defectReasons } };
348
+ }
349
+ function explainFinding(finding, steps, byExecution) {
350
+ const ofAction = (id) => steps.filter((s) => s.actionId === id).map((s) => s.id);
351
+ const ofExecution = (id) => byExecution.get(id) ?? [];
352
+ const checkStep = "Check the step another way, by its output or the next step's before snapshot, or run the task again.";
353
+ const checkRun = "Check the steps around it by their output, or run the task again.";
354
+ const report = "Nothing in this review depends on it. Report it as an mcp-relay issue, with this package.";
355
+ const rules = [
356
+ [/^request (\S+) has no retained guest execution$/, (m) => ({
357
+ stepIds: ofExecution(m[1]),
358
+ text: "The relay sent a request that the guest's event journal never recorded starting or finishing, so whether it ran is unknown.",
359
+ action: "Look for its effect in the next step's before snapshot, or run the task again."
360
+ })],
361
+ [/^action (\S+) lacks its declared causal pair$/, (m) => ({ stepIds: ofAction(m[1]), text: "This action's before or after snapshot is missing.", action: checkStep })],
362
+ [/^coalescing group (\S+) lacks a complete consecutive first\/member\/last causal pair$/, (m) => ({
363
+ stepIds: steps.filter((s) => s.snapshots?.groupId === m[1]).map((s) => s.id),
364
+ text: "These steps share one before and after pair of snapshots, and that pair is incomplete.",
365
+ action: checkStep
366
+ })],
367
+ [/^journal records incomplete evidence or a resource stop$/, () => ({ stepIds: [], text: "The guest's event journal records that evidence capture was incomplete, or that a resource limit stopped it.", action: checkRun })],
368
+ [/^unfinished snapshot originals retained$/, () => ({ stepIds: [], text: "Some snapshots were still being written when the package was assembled.", action: checkRun })],
369
+ [/^action (\S+) has no retained start or refusal$/, (m) => ({ stepIds: ofAction(m[1]), text: "The package holds this action's record, but no record that the guest started or refused it.", action: report })],
370
+ [/^action (\S+) is missing reverse snapshot reference (.+)$/, (m) => ({ stepIds: ofAction(m[1]), text: `The snapshot ${m[2]} was taken for this action, but the action's record does not refer back to it.`, action: report })],
371
+ [/^action (\S+) has no materialized action record$/, (m) => ({ stepIds: ofAction(m[1]), text: "This action started, but its action record was never written.", action: report })],
372
+ [/^action (\S+) lacks durable reverse snapshot references$/, (m) => ({ stepIds: ofAction(m[1]), text: "This action's snapshots exist, but the guest's event journal does not tie them to it.", action: report })]
373
+ ];
374
+ for (const [pattern, explain] of rules) {
375
+ const m = pattern.exec(finding);
376
+ if (m) return explain(m);
377
+ }
378
+ return { stepIds: [], text: finding.replace(/^./, (c) => c.toUpperCase()) };
379
+ }
380
+ var listedFiles = ["manifest.json", "OPENING.txt", "summary.json", "trajectory.json", "walkthrough.json"];
381
+ async function reviewData(rootDir) {
382
+ const root = await rootPath(rootDir), m = await readJson(root, "manifest.json"), files = await filesUnder(root);
383
+ const options = { packageId: text(m.packageId, "package id"), sessionId: text(m.sessionId, "session id"), taskId: text(m.taskId, "task id") };
384
+ const a = await analyze(root, options, files);
385
+ const listed = [];
386
+ for (const path of listedFiles.filter((p) => files.includes(p))) listed.push({ path, bytes: (await lstat(join(root, path))).size });
387
+ return {
388
+ ...options,
389
+ completeness: a.completeness,
390
+ execution: a.execution,
391
+ findings: a.findings,
392
+ reasons: a.reasons,
393
+ steps: a.steps,
394
+ details: Object.fromEntries(a.details),
395
+ outputs: a.outputs,
396
+ files: listed
397
+ };
398
+ }
399
+
400
+ // src/review-data.ts
401
+ var reviewData2 = reviewData;
402
+ export {
403
+ reviewData2 as reviewData
404
+ };