@tangle-network/agent-provider-tangle 3.4.2 → 3.5.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.
@@ -1,4 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { EvidenceJsonArray, evidenceJsonChunks } from "./tangle-evidence-json.js";
3
+ import { createDirectoryEvidenceWriter, createMemoryEvidenceWriter } from "./tangle-evidence-writer.js";
4
+ import { prepareNativeDirectoryEvidence, nativePayloadChunks } from "./tangle-evidence-native-files.js";
2
5
  import { AgentExactRunControlRefSchema } from "@tangle-network/agent-interface";
3
6
  import { requireNativeCaptureProof } from "./tangle-native-capture-proof.js";
4
7
  const handles = new WeakMap();
@@ -21,6 +24,27 @@ export function noteTangleSession(environment, sessionId, executionId) {
21
24
  }
22
25
  /** Export an environment through its retained Sandbox handle. */
23
26
  export async function captureTangleEnvironmentEvidence(environment, options) {
27
+ const context = evidenceContext(environment, options);
28
+ return captureTangleSandboxEvidence(context.box, context.options);
29
+ }
30
+ /** Capture to a new private directory without accumulating workspace content in memory. */
31
+ export async function captureTangleEnvironmentEvidenceToDirectory(environment, options) {
32
+ const context = evidenceContext(environment, options);
33
+ return captureTangleSandboxEvidenceToDirectory(context.box, { ...context.options, destination: options.destination });
34
+ }
35
+ /** The caller owns a successful directory; incomplete captures are removed. */
36
+ export async function captureTangleSandboxEvidenceToDirectory(box, options) {
37
+ const writer = await createDirectoryEvidenceWriter(options.destination, options.maxBytes, options.signal);
38
+ try {
39
+ const provenance = await captureSandboxEvidence(box, options, writer);
40
+ return { directory: writer.directory, provenance };
41
+ }
42
+ catch (error) {
43
+ await writer.remove();
44
+ throw error;
45
+ }
46
+ }
47
+ function evidenceContext(environment, options) {
24
48
  const state = handles.get(environment);
25
49
  if (!state || state.box.id !== environment.id)
26
50
  throw new Error("Tangle evidence requires a live provider environment handle");
@@ -41,20 +65,25 @@ export async function captureTangleEnvironmentEvidence(environment, options) {
41
65
  sessionExecutionIds[controlRef.sessionId] = [...new Set([
42
66
  ...(sessionExecutionIds[controlRef.sessionId] ?? []), controlRef.executionId,
43
67
  ])];
44
- return captureTangleSandboxEvidence(state.box, {
45
- executionId,
46
- ...(controlRef === undefined ? {} : { runtimeExecutionId: options.executionId, controlRef }),
47
- harness: options.harness,
48
- expectedSidecarImageDigest: options.expectedSidecarImageDigest,
49
- requireNativeSessionCapture: options.requireNativeSessionCapture,
50
- sandboxSessionIds: [...sessionIds],
51
- sessionExecutionIds,
52
- maxBytes: options.maxBytes,
53
- signal: options.signal,
54
- });
68
+ return { box: state.box, options: {
69
+ executionId,
70
+ ...(controlRef === undefined ? {} : { runtimeExecutionId: options.executionId, controlRef }),
71
+ harness: options.harness,
72
+ expectedSidecarImageDigest: options.expectedSidecarImageDigest,
73
+ requireNativeSessionCapture: options.requireNativeSessionCapture,
74
+ sandboxSessionIds: [...sessionIds],
75
+ sessionExecutionIds,
76
+ maxBytes: options.maxBytes,
77
+ signal: options.signal,
78
+ } };
55
79
  }
56
80
  /** Export exact Sandbox session and workspace evidence before its owning box is deleted. */
57
81
  export async function captureTangleSandboxEvidence(box, options) {
82
+ const writer = createMemoryEvidenceWriter(options.maxBytes, options.signal);
83
+ const provenance = await captureSandboxEvidence(box, options, writer);
84
+ return { files: writer.files.sort((a, b) => a.path.localeCompare(b.path)), provenance };
85
+ }
86
+ async function captureSandboxEvidence(box, options, writer) {
58
87
  if (!safeIdentifier(box.id) || !safeIdentifier(options.executionId))
59
88
  throw new Error("Tangle evidence requires exact box and execution ids");
60
89
  const controlRef = options.controlRef === undefined ? undefined : AgentExactRunControlRefSchema.parse(options.controlRef);
@@ -94,7 +123,6 @@ export async function captureTangleSandboxEvidence(box, options) {
94
123
  throw new Error("Tangle workspace usage scan is incomplete");
95
124
  if (usage.sizeBytes > options.maxBytes)
96
125
  throw new Error("Tangle workspace exceeds evidence byte limit");
97
- const files = [];
98
126
  const metadata = [];
99
127
  const seenPaths = new Set();
100
128
  const excludedPaths = [];
@@ -109,10 +137,17 @@ export async function captureTangleSandboxEvidence(box, options) {
109
137
  const flushWorkspaceFiles = async () => {
110
138
  if (!pending.length)
111
139
  return;
112
- const captured = await readWorkspaceEvidenceBatch(fs, pending, options.maxBytes - capturedBytes, options.signal);
113
- for (const file of captured) {
114
- files.push(file);
115
- capturedBytes += file.bytes.byteLength;
140
+ if (writer.download && pending.length === 1 && pending[0].size > WORKSPACE_BATCH_BYTES) {
141
+ const entry = pending[0];
142
+ await writer.download(fs, entry);
143
+ capturedBytes += entry.size;
144
+ }
145
+ else {
146
+ const captured = await readWorkspaceEvidenceBatch(fs, pending, options.maxBytes - capturedBytes, options.signal);
147
+ for (const file of captured) {
148
+ await writer.write(file);
149
+ capturedBytes += file.bytes.byteLength;
150
+ }
116
151
  }
117
152
  pending = [];
118
153
  pendingBytes = 0;
@@ -200,456 +235,463 @@ export async function captureTangleSandboxEvidence(box, options) {
200
235
  executionIds.some((executionId) => !safeIdentifier(executionId))) {
201
236
  throw new Error("Tangle evidence has invalid session execution attribution");
202
237
  }
203
- const events = [];
238
+ const counts = { events: 0, messages: 0 };
204
239
  const eventCountsByExecutionId = {};
205
- for (const executionId of executionIds) {
206
- eventCountsByExecutionId[executionId] = 0;
207
- for await (const event of session.events({ since: "0", executionId, signal: options.signal })) {
208
- options.signal?.throwIfAborted();
209
- if (events.length >= MAX_EVENTS)
210
- throw new Error("Tangle event replay limit exceeded");
211
- if (typeof event.data?.executionId === "string" && event.data.executionId !== executionId) {
212
- throw new Error("Tangle event replay returned an unrelated execution");
213
- }
214
- if (typeof event.data?.runtimeSessionId === "string" && event.data.runtimeSessionId !== id) {
215
- throw new Error("Tangle event replay returned an unrelated session");
240
+ const events = new EvidenceJsonArray(undefined, async function* () {
241
+ for (const executionId of executionIds) {
242
+ eventCountsByExecutionId[executionId] = 0;
243
+ for await (const event of session.events({ since: "0", executionId, signal: options.signal })) {
244
+ options.signal?.throwIfAborted();
245
+ if (counts.events >= MAX_EVENTS)
246
+ throw new Error("Tangle event replay limit exceeded");
247
+ if (typeof event.data?.executionId === "string" && event.data.executionId !== executionId) {
248
+ throw new Error("Tangle event replay returned an unrelated execution");
249
+ }
250
+ if (typeof event.data?.runtimeSessionId === "string" && event.data.runtimeSessionId !== id) {
251
+ throw new Error("Tangle event replay returned an unrelated session");
252
+ }
253
+ counts.events++;
254
+ eventCountsByExecutionId[executionId] += 1;
255
+ yield { executionId, event };
216
256
  }
217
- const attributed = { executionId, event };
218
- capturedBytes += Buffer.byteLength(JSON.stringify(attributed));
219
- if (capturedBytes > options.maxBytes)
220
- throw new Error("Tangle evidence exceeds byte limit");
221
- events.push(attributed);
222
- eventCountsByExecutionId[executionId] += 1;
223
257
  }
224
- }
225
- const messages = [];
226
- for (let offset = 0;; offset += 1000) {
227
- options.signal?.throwIfAborted();
228
- if (offset >= MAX_EVENTS)
229
- throw new Error("Tangle message pagination limit exceeded");
230
- const page = await session.messages({ limit: 1000, offset });
231
- if (!Array.isArray(page) || page.length > 1000)
232
- throw new Error("Tangle session message page is malformed");
233
- capturedBytes += Buffer.byteLength(JSON.stringify(page));
234
- if (capturedBytes > options.maxBytes)
235
- throw new Error("Tangle evidence exceeds byte limit");
236
- messages.push(...page);
237
- if (page.length < 1000)
238
- break;
239
- }
240
- const bytes = Buffer.from(JSON.stringify({ kind: "tangle-session-transport.v1", environmentId: box.id, sessionId: id, executionIds, status, events, messages, messageScope: "session" }));
241
- if (files.reduce((sum, file) => sum + file.bytes.byteLength, 0) + bytes.byteLength > options.maxBytes)
242
- throw new Error("Tangle evidence exceeds byte limit");
243
- capturedBytes = files.reduce((sum, file) => sum + file.bytes.byteLength, 0) + bytes.byteLength;
244
- files.push({ path: `__retention__/sessions/${id}.json`, bytes, mode: 0o600 });
245
- const rawNative = await session.rawEvidence?.();
246
- if (rawNative !== undefined && (rawNative === null || typeof rawNative !== "object")) {
247
- throw new Error("Tangle raw evidence is malformed");
248
- }
249
- const native = rawNative;
250
- const nativeStore = {
251
- scope: "session", roots: [], inventory: null, complete: false, entries: [], excludedPaths: [],
252
- };
253
- const processStreams = {
254
- complete: false, streamCount: 0, processCount: 0, terminalCount: 0,
255
- stdinBytes: 0, stdoutBytes: 0, stderrBytes: 0, protocolBytes: 0, terminals: [],
256
- sources: [],
257
- };
258
- const nativeEvents = {
259
- scope: "execution", complete: false, count: 0,
260
- };
261
- let nativeSessionId = null;
262
- let sidecarImageDigest = null;
263
- let sidecarBundleRevision = null;
264
- let nativeReason = "raw-session-capture-capability-absent";
265
- let evidenceSources = [];
266
- if (native !== undefined) {
267
- let manifestSource = native;
268
- const contentRefs = [];
269
- if (native.sessionId !== id || native.backendType !== options.harness) {
270
- throw new Error("Tangle raw evidence returned an unrelated session or profile backend");
258
+ });
259
+ const messages = new EvidenceJsonArray(undefined, async function* () {
260
+ const pageSize = 100;
261
+ for (let offset = 0;; offset += pageSize) {
262
+ options.signal?.throwIfAborted();
263
+ if (offset >= MAX_EVENTS)
264
+ throw new Error("Tangle message pagination limit exceeded");
265
+ const page = await session.messages({ limit: pageSize, offset });
266
+ if (!Array.isArray(page) || page.length > pageSize)
267
+ throw new Error("Tangle session message page is malformed");
268
+ for (const message of page) {
269
+ counts.messages++;
270
+ yield message;
271
+ }
272
+ if (page.length < pageSize)
273
+ break;
271
274
  }
272
- if (native.nativeSessionId != null && !safeIdentifier(native.nativeSessionId)) {
273
- throw new Error("Tangle raw evidence native session id is invalid");
275
+ });
276
+ await writer.writeChunks(`__retention__/sessions/${id}.json`, 0o600, evidenceJsonChunks({ kind: "tangle-session-transport.v1", environmentId: box.id, sessionId: id,
277
+ executionIds, status, events, messages, messageScope: "session" }));
278
+ capturedBytes = writer.byteLength;
279
+ const prepared = writer.directory === undefined ? undefined :
280
+ await prepareNativeDirectoryEvidence(session, options.maxBytes - capturedBytes, options.signal);
281
+ try {
282
+ const rawNative = prepared ? prepared.native : await session.rawEvidence?.();
283
+ if (rawNative !== undefined && (rawNative === null || typeof rawNative !== "object")) {
284
+ throw new Error("Tangle raw evidence is malformed");
274
285
  }
275
- nativeSessionId = native.nativeSessionId ?? null;
276
- if (native.status === "captured" || native.status === "partial") {
277
- const declaredPartial = native.status === "partial";
278
- let partial = declaredPartial;
279
- if (captureProof && (native.proofStatus !== "verified" ||
280
- native.containerId !== captureProof.containerId ||
281
- native.sidecarImageDigest !== captureProof.imageId ||
282
- native.sidecarBundleRevision !== captureProof.bundleRevision ||
283
- native.sidecarBundleChecksum !== captureProof.bundleChecksum)) {
284
- throw new Error("Tangle raw session identity differs from verified create proof");
286
+ const native = rawNative;
287
+ const retainNativeContent = async (entry, path, mode) => {
288
+ const ref = prepared?.payloads.get(entry);
289
+ if (prepared) {
290
+ if (!ref || !prepared.directory || ref.sizeBytes !== entry.sizeBytes || ref.sha256 !== entry.sha256 ||
291
+ ref.sizeBytes > options.maxBytes - writer.byteLength)
292
+ throw new Error("Tangle native payload reference is absent or inconsistent");
293
+ return writer.writeChunks(path, mode, nativePayloadChunks(prepared.directory, ref, options.signal));
285
294
  }
286
- if (!/^sha256:[0-9a-f]{64}$/.test(native.sidecarImageDigest) ||
287
- (options.expectedSidecarImageDigest !== undefined &&
288
- native.sidecarImageDigest !== options.expectedSidecarImageDigest)) {
289
- throw new Error("Tangle raw session image digest is missing or differs from deployment proof");
295
+ const bytes = exactNativeBytes(entry.contentBase64, entry.sizeBytes, entry.sha256, options.maxBytes - writer.byteLength);
296
+ await writer.write({ path, bytes, mode });
297
+ return bytes.byteLength;
298
+ };
299
+ const nativeStore = {
300
+ scope: "session", roots: [], inventory: null, complete: false, entries: [], excludedPaths: [],
301
+ };
302
+ const processStreams = {
303
+ complete: false, streamCount: 0, processCount: 0, terminalCount: 0,
304
+ stdinBytes: 0, stdoutBytes: 0, stderrBytes: 0, protocolBytes: 0, terminals: [],
305
+ sources: [],
306
+ };
307
+ const nativeEvents = {
308
+ scope: "execution", complete: false, count: 0,
309
+ };
310
+ let nativeSessionId = null;
311
+ let sidecarImageDigest = null;
312
+ let sidecarBundleRevision = null;
313
+ let nativeReason = "raw-session-capture-capability-absent";
314
+ let evidenceSources = [];
315
+ if (native !== undefined) {
316
+ let manifestSource = native;
317
+ const contentRefs = [];
318
+ if (native.sessionId !== id || native.backendType !== options.harness) {
319
+ throw new Error("Tangle raw evidence returned an unrelated session or profile backend");
290
320
  }
291
- if (!/^[0-9a-f]{40}$/.test(native.sidecarBundleRevision)) {
292
- throw new Error("Tangle raw session sidecar bundle revision is missing or invalid");
321
+ if (native.nativeSessionId != null && !safeIdentifier(native.nativeSessionId)) {
322
+ throw new Error("Tangle raw evidence native session id is invalid");
293
323
  }
294
- sidecarImageDigest = native.sidecarImageDigest;
295
- sidecarBundleRevision = native.sidecarBundleRevision;
296
- if (typeof native.completeness?.nativeStore !== "boolean" || typeof native.completeness.processIo !== "boolean" ||
297
- typeof native.completeness.events !== "boolean" || !Array.isArray(native.files) ||
298
- !Array.isArray(native.processIo) || !Array.isArray(native.events) ||
299
- !Array.isArray(native.processSources) || !Array.isArray(native.evidenceSources) ||
300
- !Array.isArray(native.excluded) || !Array.isArray(native.nativeRoots) || !native.inventory ||
301
- !Array.isArray(native.processTerminals) || typeof native.coverageComplete !== "boolean" ||
302
- !Array.isArray(native.missingReasons) || native.missingReasons.some((reason) => !safeReason(reason))) {
303
- throw new Error("Tangle raw session capture is malformed");
304
- }
305
- if ((!declaredPartial && (native.completeness.nativeStore !== true || native.completeness.processIo !== true ||
306
- native.completeness.events !== true || native.coverageComplete !== true || native.missingReasons.length > 0)) ||
307
- (declaredPartial && native.coverageComplete !== false)) {
308
- throw new Error("Tangle raw session capture is incomplete");
309
- }
310
- if (!Array.isArray(native.attempts) || native.attempts.length > MAX_ENTRIES) {
311
- throw new Error("Tangle raw session attempt inventory is missing or invalid");
312
- }
313
- const unattributedExecutions = [...new Set(native.attempts.filter(isEvidenceAttempt)
314
- .map((attempt) => attempt.executionId).filter((executionId) => !executionIds.includes(executionId)))];
315
- if (unattributedExecutions.length) {
316
- partial = true;
317
- for (const executionId of unattributedExecutions) {
318
- missing.push(`Sandbox session ${id} has an execution without retained caller attribution: ${executionId}`);
324
+ nativeSessionId = native.nativeSessionId ?? null;
325
+ if (native.status === "captured" || native.status === "partial") {
326
+ const declaredPartial = native.status === "partial";
327
+ let partial = declaredPartial;
328
+ if (captureProof && (native.proofStatus !== "verified" ||
329
+ native.containerId !== captureProof.containerId ||
330
+ native.sidecarImageDigest !== captureProof.imageId ||
331
+ native.sidecarBundleRevision !== captureProof.bundleRevision ||
332
+ native.sidecarBundleChecksum !== captureProof.bundleChecksum)) {
333
+ throw new Error("Tangle raw session identity differs from verified create proof");
319
334
  }
320
- }
321
- const sessionAttempts = readNativeAttempts(native.attempts, executionIds, partial);
322
- const sourceBindings = new Map();
323
- const sourceHomes = new Map();
324
- for (const source of native.evidenceSources) {
325
- if (!source || !safeIdentifier(source.executionId) || !safeIdentifier(source.sourceId) ||
326
- source.backendType !== options.harness || !canonicalNativeRoot(source.runtimeHome) ||
327
- !Array.isArray(source.credentialPaths) || sourceBindings.has(source.executionId) ||
328
- (sourceHomes.has(source.sourceId) && sourceHomes.get(source.sourceId) !== source.runtimeHome)) {
329
- throw new Error("Tangle raw session evidence source identity is invalid");
335
+ if (!/^sha256:[0-9a-f]{64}$/.test(native.sidecarImageDigest) ||
336
+ (options.expectedSidecarImageDigest !== undefined &&
337
+ native.sidecarImageDigest !== options.expectedSidecarImageDigest)) {
338
+ throw new Error("Tangle raw session image digest is missing or differs from deployment proof");
330
339
  }
331
- for (const path of source.credentialPaths)
332
- canonicalEntryPath(path);
333
- sourceBindings.set(source.executionId, source);
334
- sourceHomes.set(source.sourceId, source.runtimeHome);
335
- }
336
- const sourceCoverage = executionIds.every((executionId) => sourceBindings.has(executionId)) &&
337
- native.evidenceSources.every((source) => executionIds.includes(source.executionId));
338
- if (!sourceCoverage) {
339
- if (!partial)
340
- throw new Error("Tangle raw session sources do not cover the exact executions");
341
- missing.push(`Sandbox session ${id} evidence sources do not cover the exact executions`);
342
- }
343
- evidenceSources = native.evidenceSources;
344
- let processAttributionComplete = sourceCoverage;
345
- const nativeEventCoverage = nativeEventsMatch(native.events, id, executionIds, partial);
346
- attempts.push(...sessionAttempts.filter((attempt) => executionIds.includes(attempt.executionId)));
347
- if (partial)
348
- missing.push(`Sandbox session ${id} declared partial raw capture`);
349
- for (const reason of native.missingReasons)
350
- missing.push(`Sandbox session ${id}: ${reason}`);
351
- for (const attempt of sessionAttempts) {
352
- for (const reason of attempt.missingReasons) {
353
- missing.push(`Sandbox session ${id} attempt ${attempt.executionId}/${attempt.ordinal}: ${reason}`);
340
+ if (!/^[0-9a-f]{40}$/.test(native.sidecarBundleRevision)) {
341
+ throw new Error("Tangle raw session sidecar bundle revision is missing or invalid");
354
342
  }
355
- }
356
- if (!sessionAttempts.length)
357
- missing.push(`Sandbox session ${id} has no attempt inventory`);
358
- const nativeIds = new Set(sessionAttempts.flatMap((attempt) => attempt.nativeSessionIds));
359
- if (nativeSessionId !== null && !nativeIds.has(nativeSessionId)) {
360
- throw new Error("Tangle raw session identity differs from its attempt inventory");
361
- }
362
- if (native.files.length + native.processIo.length + native.processTerminals.length +
363
- native.events.length > MAX_ENTRIES) {
364
- throw new Error("Tangle raw session capture exceeds entry limit");
365
- }
366
- const roots = new Set();
367
- for (const root of native.nativeRoots) {
368
- if (!["session-home", "workspace-session"].includes(root.rootScope) || roots.has(nativeRootKey(root)) ||
369
- !canonicalNativeRoot(root.path) ||
370
- (root.sourceId !== undefined && (!safeIdentifier(root.sourceId) || !sourceHomes.has(root.sourceId) ||
371
- (root.rootScope === "session-home" && sourceHomes.get(root.sourceId) !== root.path)))) {
372
- throw new Error("Tangle raw session native root is invalid");
343
+ sidecarImageDigest = native.sidecarImageDigest;
344
+ sidecarBundleRevision = native.sidecarBundleRevision;
345
+ if (typeof native.completeness?.nativeStore !== "boolean" || typeof native.completeness.processIo !== "boolean" ||
346
+ typeof native.completeness.events !== "boolean" || !Array.isArray(native.files) ||
347
+ !Array.isArray(native.processIo) || !Array.isArray(native.events) ||
348
+ !Array.isArray(native.processSources) || !Array.isArray(native.evidenceSources) ||
349
+ !Array.isArray(native.excluded) || !Array.isArray(native.nativeRoots) || !native.inventory ||
350
+ !Array.isArray(native.processTerminals) || typeof native.coverageComplete !== "boolean" ||
351
+ !Array.isArray(native.missingReasons) || native.missingReasons.some((reason) => !safeReason(reason))) {
352
+ throw new Error("Tangle raw session capture is malformed");
373
353
  }
374
- roots.add(nativeRootKey(root));
375
- nativeStore.roots.push({ scope: root.rootScope, path: root.path,
376
- ...(root.sourceId === undefined ? {} : { sourceId: root.sourceId }) });
377
- }
378
- if (!roots.size && (!partial || native.completeness.nativeStore))
379
- throw new Error("Tangle raw session has no native root");
380
- const nativeRootCoverage = [...sourceHomes.keys()].every((sourceId) => roots.has(sourceId + "/session-home"));
381
- if (!nativeRootCoverage) {
382
- if (!partial)
383
- throw new Error("Tangle raw session has an unretained native source root");
384
- missing.push(`Sandbox session ${id} has an unretained native source root`);
385
- }
386
- const nativePaths = new Set();
387
- const included = { file: 0, directory: 0, symlink: 0 };
388
- const excluded = { file: 0, directory: 0, symlink: 0 };
389
- for (const [index, entry] of native.files.entries()) {
390
- options.signal?.throwIfAborted();
391
- const path = canonicalEntryPath(entry.path);
392
- if (!roots.has(nativeRootKey(entry)))
393
- throw new Error("Tangle raw session entry has no native root");
394
- const identity = nativeRootKey(entry) + "/" + path;
395
- if (nativePaths.has(identity))
396
- throw new Error("Tangle raw session repeats a native path");
397
- nativePaths.add(identity);
398
- if (!nativeStatMetadata(entry))
399
- throw new Error("Tangle raw session entry metadata is invalid");
400
- if (entry.kind === "file") {
401
- const content = exactNativeBytes(entry.contentBase64, entry.sizeBytes, entry.sha256, options.maxBytes - capturedBytes);
402
- if (capturedBytes + content.byteLength > options.maxBytes)
403
- throw new Error("Tangle evidence exceeds byte limit");
404
- const contentPath = "__retention__/sessions/" + id + "/native/" +
405
- (entry.sourceId === undefined ? "" : entry.sourceId + "/") + entry.rootScope + "/" + path;
406
- files.push({ path: contentPath, bytes: content, mode: entry.mode & 0o777 });
407
- contentRefs.push({ jsonPointer: `/files/${index}/contentBase64`, path: contentPath });
408
- capturedBytes += content.byteLength;
354
+ if ((!declaredPartial && (native.completeness.nativeStore !== true || native.completeness.processIo !== true ||
355
+ native.completeness.events !== true || native.coverageComplete !== true || native.missingReasons.length > 0)) ||
356
+ (declaredPartial && native.coverageComplete !== false)) {
357
+ throw new Error("Tangle raw session capture is incomplete");
409
358
  }
410
- else if (entry.kind === "directory" || entry.kind === "symlink") {
411
- if (entry.contentBase64 !== undefined || entry.sha256 !== undefined ||
412
- (entry.kind === "symlink" && (typeof entry.linkTarget !== "string" || entry.linkTarget.includes("\0")))) {
413
- throw new Error("Tangle raw session non-file entry is malformed");
359
+ if (!Array.isArray(native.attempts) || native.attempts.length > MAX_ENTRIES) {
360
+ throw new Error("Tangle raw session attempt inventory is missing or invalid");
361
+ }
362
+ const unattributedExecutions = [...new Set(native.attempts.filter(isEvidenceAttempt)
363
+ .map((attempt) => attempt.executionId).filter((executionId) => !executionIds.includes(executionId)))];
364
+ if (unattributedExecutions.length) {
365
+ partial = true;
366
+ for (const executionId of unattributedExecutions) {
367
+ missing.push(`Sandbox session ${id} has an execution without retained caller attribution: ${executionId}`);
414
368
  }
415
369
  }
416
- else {
417
- throw new Error("Tangle raw session entry kind is invalid");
370
+ const sessionAttempts = readNativeAttempts(native.attempts, executionIds, partial);
371
+ const sourceBindings = new Map();
372
+ const sourceHomes = new Map();
373
+ for (const source of native.evidenceSources) {
374
+ if (!source || !safeIdentifier(source.executionId) || !safeIdentifier(source.sourceId) ||
375
+ source.backendType !== options.harness || !canonicalNativeRoot(source.runtimeHome) ||
376
+ !Array.isArray(source.credentialPaths) || sourceBindings.has(source.executionId) ||
377
+ (sourceHomes.has(source.sourceId) && sourceHomes.get(source.sourceId) !== source.runtimeHome)) {
378
+ throw new Error("Tangle raw session evidence source identity is invalid");
379
+ }
380
+ for (const path of source.credentialPaths)
381
+ canonicalEntryPath(path);
382
+ sourceBindings.set(source.executionId, source);
383
+ sourceHomes.set(source.sourceId, source.runtimeHome);
418
384
  }
419
- included[entry.kind] += 1;
420
- nativeStore.entries.push({
421
- ...(entry.sourceId === undefined ? {} : { sourceId: entry.sourceId }),
422
- rootScope: entry.rootScope, path, kind: entry.kind, mode: entry.mode,
423
- uid: entry.uid, gid: entry.gid, mtimeMs: entry.mtimeMs, ctimeMs: entry.ctimeMs,
424
- sizeBytes: entry.sizeBytes, sha256: entry.sha256 ?? null, linkTarget: entry.linkTarget ?? null,
425
- });
426
- }
427
- for (const exclusion of native.excluded) {
428
- const path = canonicalEntryPath(exclusion.path);
429
- const identity = nativeRootKey(exclusion) + "/" + path;
430
- if (!roots.has(nativeRootKey(exclusion)) || nativePaths.has(identity) ||
431
- exclusion.reason !== "credential" || !["file", "directory", "symlink"].includes(exclusion.kind) ||
432
- !nativeStatMetadata(exclusion)) {
433
- throw new Error("Tangle raw session exclusion is invalid");
385
+ const sourceCoverage = executionIds.every((executionId) => sourceBindings.has(executionId)) &&
386
+ native.evidenceSources.every((source) => executionIds.includes(source.executionId));
387
+ if (!sourceCoverage) {
388
+ if (!partial)
389
+ throw new Error("Tangle raw session sources do not cover the exact executions");
390
+ missing.push(`Sandbox session ${id} evidence sources do not cover the exact executions`);
434
391
  }
435
- nativePaths.add(identity);
436
- excluded[exclusion.kind] += 1;
437
- nativeStore.excludedPaths.push({
438
- ...(exclusion.sourceId === undefined ? {} : { sourceId: exclusion.sourceId }),
439
- rootScope: exclusion.rootScope, path, kind: exclusion.kind, mode: exclusion.mode,
440
- uid: exclusion.uid, gid: exclusion.gid, mtimeMs: exclusion.mtimeMs, ctimeMs: exclusion.ctimeMs,
441
- sizeBytes: exclusion.sizeBytes, reason: exclusion.reason,
442
- });
443
- }
444
- const inventory = native.inventory;
445
- const counts = [
446
- inventory.reportedFiles, inventory.scannedFiles, inventory.excludedFiles,
447
- inventory.reportedDirectories, inventory.scannedDirectories, inventory.excludedDirectories,
448
- inventory.reportedSymlinks, inventory.scannedSymlinks, inventory.excludedSymlinks,
449
- ];
450
- if (counts.some((value) => !Number.isSafeInteger(value) || value < 0) ||
451
- !Number.isSafeInteger(inventory.skippedEntries) || inventory.skippedEntries < 0 ||
452
- (!partial && inventory.skippedEntries !== 0) ||
453
- inventory.reportedFiles !== included.file ||
454
- inventory.reportedDirectories !== included.directory ||
455
- inventory.reportedSymlinks !== included.symlink ||
456
- inventory.excludedFiles !== excluded.file ||
457
- inventory.excludedDirectories !== excluded.directory ||
458
- inventory.excludedSymlinks !== excluded.symlink ||
459
- inventory.scannedFiles < inventory.reportedFiles + inventory.excludedFiles ||
460
- inventory.scannedDirectories < inventory.reportedDirectories + inventory.excludedDirectories ||
461
- inventory.scannedSymlinks < inventory.reportedSymlinks + inventory.excludedSymlinks ||
462
- (!partial && (inventory.scannedFiles !== inventory.reportedFiles + inventory.excludedFiles ||
463
- inventory.scannedDirectories !== inventory.reportedDirectories + inventory.excludedDirectories ||
464
- inventory.scannedSymlinks !== inventory.reportedSymlinks + inventory.excludedSymlinks))) {
465
- throw new Error("Tangle raw session inventory does not reconcile");
466
- }
467
- nativeStore.inventory = {
468
- scannedFiles: inventory.scannedFiles,
469
- reportedFiles: inventory.reportedFiles,
470
- excludedFiles: inventory.excludedFiles,
471
- scannedDirectories: inventory.scannedDirectories,
472
- reportedDirectories: inventory.reportedDirectories,
473
- excludedDirectories: inventory.excludedDirectories,
474
- scannedSymlinks: inventory.scannedSymlinks,
475
- reportedSymlinks: inventory.reportedSymlinks,
476
- excludedSymlinks: inventory.excludedSymlinks,
477
- skippedEntries: inventory.skippedEntries,
478
- };
479
- if (native.skipped !== undefined) {
480
- if (!Array.isArray(native.skipped) || native.skipped.length !== inventory.skippedEntries ||
481
- native.skipped.some((entry) => !roots.has(nativeRootKey(entry)) || !safeReason(entry.reason))) {
482
- throw new Error("Tangle raw session skipped inventory does not reconcile");
392
+ evidenceSources = native.evidenceSources;
393
+ let processAttributionComplete = sourceCoverage;
394
+ const nativeEventCoverage = nativeEventsMatch(native.events, id, executionIds, partial);
395
+ attempts.push(...sessionAttempts.filter((attempt) => executionIds.includes(attempt.executionId)));
396
+ if (partial)
397
+ missing.push(`Sandbox session ${id} declared partial raw capture`);
398
+ for (const reason of native.missingReasons)
399
+ missing.push(`Sandbox session ${id}: ${reason}`);
400
+ for (const attempt of sessionAttempts) {
401
+ for (const reason of attempt.missingReasons) {
402
+ missing.push(`Sandbox session ${id} attempt ${attempt.executionId}/${attempt.ordinal}: ${reason}`);
403
+ }
483
404
  }
484
- for (const entry of native.skipped) {
485
- if (entry.path !== ".")
486
- canonicalEntryPath(entry.path);
405
+ if (!sessionAttempts.length)
406
+ missing.push(`Sandbox session ${id} has no attempt inventory`);
407
+ const nativeIds = new Set(sessionAttempts.flatMap((attempt) => attempt.nativeSessionIds));
408
+ if (nativeSessionId !== null && !nativeIds.has(nativeSessionId)) {
409
+ throw new Error("Tangle raw session identity differs from its attempt inventory");
487
410
  }
488
- }
489
- const ioSequences = new Map();
490
- const frameMetadata = [];
491
- for (const [index, frame] of native.processIo.entries()) {
492
- options.signal?.throwIfAborted();
493
- if (!safeIdentifier(frame.processId) || (frame.sourceId !== undefined && !safeIdentifier(frame.sourceId)) ||
494
- !Number.isSafeInteger(frame.sequence) ||
495
- frame.sequence < 0 || !Number.isFinite(Date.parse(frame.at)) ||
496
- !["stdin", "stdout", "stderr", "protocol"].includes(frame.stream)) {
497
- throw new Error("Tangle raw session process stream metadata is invalid");
411
+ if (native.files.length + native.processIo.length + native.processTerminals.length +
412
+ native.events.length > MAX_ENTRIES) {
413
+ throw new Error("Tangle raw session capture exceeds entry limit");
498
414
  }
499
- const processKey = sourceProcessKey(frame);
500
- const sequences = ioSequences.get(processKey) ?? new Set();
501
- if (sequences.has(frame.sequence))
502
- throw new Error("Tangle raw session repeats a process frame");
503
- sequences.add(frame.sequence);
504
- ioSequences.set(processKey, sequences);
505
- if (!processAttemptMatches(frame, sessionAttempts, partial)) {
506
- processAttributionComplete = false;
507
- missing.push(`Sandbox session ${id} process ${frame.processId} has no exact attempt attribution`);
415
+ const roots = new Set();
416
+ for (const root of native.nativeRoots) {
417
+ if (!["session-home", "workspace-session"].includes(root.rootScope) || roots.has(nativeRootKey(root)) ||
418
+ !canonicalNativeRoot(root.path) ||
419
+ (root.sourceId !== undefined && (!safeIdentifier(root.sourceId) || !sourceHomes.has(root.sourceId) ||
420
+ (root.rootScope === "session-home" && sourceHomes.get(root.sourceId) !== root.path)))) {
421
+ throw new Error("Tangle raw session native root is invalid");
422
+ }
423
+ roots.add(nativeRootKey(root));
424
+ nativeStore.roots.push({ scope: root.rootScope, path: root.path,
425
+ ...(root.sourceId === undefined ? {} : { sourceId: root.sourceId }) });
508
426
  }
509
- if (frame.sourceId === undefined || sourceBindings.get(frame.executionId ?? "")?.sourceId !== frame.sourceId) {
427
+ if (!roots.size && (!partial || native.completeness.nativeStore))
428
+ throw new Error("Tangle raw session has no native root");
429
+ const nativeRootCoverage = [...sourceHomes.keys()].every((sourceId) => roots.has(sourceId + "/session-home"));
430
+ if (!nativeRootCoverage) {
510
431
  if (!partial)
511
- throw new Error("Tangle raw session process has conflicting source attribution");
512
- processAttributionComplete = false;
513
- missing.push(`Sandbox session ${id} process ${frame.processId} has no exact source attribution`);
432
+ throw new Error("Tangle raw session has an unretained native source root");
433
+ missing.push(`Sandbox session ${id} has an unretained native source root`);
514
434
  }
515
- const content = exactNativeBytes(frame.contentBase64, frame.sizeBytes, frame.sha256, options.maxBytes - capturedBytes);
516
- if (capturedBytes + content.byteLength > options.maxBytes)
517
- throw new Error("Tangle evidence exceeds byte limit");
518
- const label = String(frame.sequence).padStart(16, "0");
519
- const contentPath = "__retention__/sessions/" + id + "/io/" +
520
- (frame.sourceId === undefined ? "" : frame.sourceId + "/") + frame.processId + "/" + label +
521
- "-" + frame.stream + ".bin";
522
- files.push({ path: contentPath, bytes: content, mode: 0o600 });
523
- contentRefs.push({ jsonPointer: `/processIo/${index}/contentBase64`, path: contentPath });
524
- frameMetadata.push(withoutNativeContent(frame));
525
- capturedBytes += content.byteLength;
526
- const counter = (frame.stream + "Bytes");
527
- processStreams[counter] += content.byteLength;
528
- processStreams.streamCount += 1;
529
- }
530
- const terminals = new Set();
531
- for (const terminal of native.processTerminals) {
532
- const processKey = sourceProcessKey(terminal);
533
- if (!safeIdentifier(terminal.processId) || (terminal.sourceId !== undefined && !safeIdentifier(terminal.sourceId)) ||
534
- terminals.has(processKey) ||
535
- !Number.isSafeInteger(terminal.sequence) || terminal.sequence < 0 ||
536
- !Number.isFinite(Date.parse(terminal.at)) ||
537
- !(terminal.result?.captureError === null || (partial && typeof terminal.result?.captureError === "string")) ||
538
- !(terminal.result.code === null || Number.isSafeInteger(terminal.result.code)) ||
539
- !(terminal.result.signal === null || typeof terminal.result.signal === "string") ||
540
- typeof terminal.result.timedOut !== "boolean" ||
541
- !(terminal.result.timeoutReason === null || typeof terminal.result.timeoutReason === "string") ||
542
- (terminal.result.spawnError !== undefined && typeof terminal.result.spawnError !== "string")) {
543
- throw new Error("Tangle raw session process terminal metadata is invalid");
435
+ const nativePaths = new Set();
436
+ const included = { file: 0, directory: 0, symlink: 0 };
437
+ const excluded = { file: 0, directory: 0, symlink: 0 };
438
+ for (const [index, entry] of native.files.entries()) {
439
+ options.signal?.throwIfAborted();
440
+ const path = canonicalEntryPath(entry.path);
441
+ if (!roots.has(nativeRootKey(entry)))
442
+ throw new Error("Tangle raw session entry has no native root");
443
+ const identity = nativeRootKey(entry) + "/" + path;
444
+ if (nativePaths.has(identity))
445
+ throw new Error("Tangle raw session repeats a native path");
446
+ nativePaths.add(identity);
447
+ if (!nativeStatMetadata(entry))
448
+ throw new Error("Tangle raw session entry metadata is invalid");
449
+ if (entry.kind === "file") {
450
+ const contentPath = "__retention__/sessions/" + id + "/native/" +
451
+ (entry.sourceId === undefined ? "" : entry.sourceId + "/") + entry.rootScope + "/" + path;
452
+ await retainNativeContent(entry, contentPath, entry.mode & 0o777);
453
+ contentRefs.push({ jsonPointer: `/files/${index}/contentBase64`, path: contentPath });
454
+ capturedBytes = writer.byteLength;
455
+ }
456
+ else if (entry.kind === "directory" || entry.kind === "symlink") {
457
+ if (entry.contentBase64 !== undefined || entry.sha256 !== undefined ||
458
+ (entry.kind === "symlink" && (typeof entry.linkTarget !== "string" || entry.linkTarget.includes("\0")))) {
459
+ throw new Error("Tangle raw session non-file entry is malformed");
460
+ }
461
+ }
462
+ else {
463
+ throw new Error("Tangle raw session entry kind is invalid");
464
+ }
465
+ included[entry.kind] += 1;
466
+ nativeStore.entries.push({
467
+ ...(entry.sourceId === undefined ? {} : { sourceId: entry.sourceId }),
468
+ rootScope: entry.rootScope, path, kind: entry.kind, mode: entry.mode,
469
+ uid: entry.uid, gid: entry.gid, mtimeMs: entry.mtimeMs, ctimeMs: entry.ctimeMs,
470
+ sizeBytes: entry.sizeBytes, sha256: entry.sha256 ?? null, linkTarget: entry.linkTarget ?? null,
471
+ });
544
472
  }
545
- const sequences = ioSequences.get(processKey) ?? new Set();
546
- if (!processAttemptMatches(terminal, sessionAttempts, partial)) {
547
- processAttributionComplete = false;
548
- missing.push(`Sandbox session ${id} terminal ${terminal.processId} has no exact attempt attribution`);
473
+ for (const exclusion of native.excluded) {
474
+ const path = canonicalEntryPath(exclusion.path);
475
+ const identity = nativeRootKey(exclusion) + "/" + path;
476
+ if (!roots.has(nativeRootKey(exclusion)) || nativePaths.has(identity) ||
477
+ exclusion.reason !== "credential" || !["file", "directory", "symlink"].includes(exclusion.kind) ||
478
+ !nativeStatMetadata(exclusion)) {
479
+ throw new Error("Tangle raw session exclusion is invalid");
480
+ }
481
+ nativePaths.add(identity);
482
+ excluded[exclusion.kind] += 1;
483
+ nativeStore.excludedPaths.push({
484
+ ...(exclusion.sourceId === undefined ? {} : { sourceId: exclusion.sourceId }),
485
+ rootScope: exclusion.rootScope, path, kind: exclusion.kind, mode: exclusion.mode,
486
+ uid: exclusion.uid, gid: exclusion.gid, mtimeMs: exclusion.mtimeMs, ctimeMs: exclusion.ctimeMs,
487
+ sizeBytes: exclusion.sizeBytes, reason: exclusion.reason,
488
+ });
549
489
  }
550
- if (terminal.sourceId === undefined || sourceBindings.get(terminal.executionId ?? "")?.sourceId !== terminal.sourceId) {
551
- if (!partial)
552
- throw new Error("Tangle raw session terminal has conflicting source attribution");
553
- processAttributionComplete = false;
554
- missing.push(`Sandbox session ${id} terminal ${terminal.processId} has no exact source attribution`);
490
+ const inventory = native.inventory;
491
+ const counts = [
492
+ inventory.reportedFiles, inventory.scannedFiles, inventory.excludedFiles,
493
+ inventory.reportedDirectories, inventory.scannedDirectories, inventory.excludedDirectories,
494
+ inventory.reportedSymlinks, inventory.scannedSymlinks, inventory.excludedSymlinks,
495
+ ];
496
+ if (counts.some((value) => !Number.isSafeInteger(value) || value < 0) ||
497
+ !Number.isSafeInteger(inventory.skippedEntries) || inventory.skippedEntries < 0 ||
498
+ (!partial && inventory.skippedEntries !== 0) ||
499
+ inventory.reportedFiles !== included.file ||
500
+ inventory.reportedDirectories !== included.directory ||
501
+ inventory.reportedSymlinks !== included.symlink ||
502
+ inventory.excludedFiles !== excluded.file ||
503
+ inventory.excludedDirectories !== excluded.directory ||
504
+ inventory.excludedSymlinks !== excluded.symlink ||
505
+ inventory.scannedFiles < inventory.reportedFiles + inventory.excludedFiles ||
506
+ inventory.scannedDirectories < inventory.reportedDirectories + inventory.excludedDirectories ||
507
+ inventory.scannedSymlinks < inventory.reportedSymlinks + inventory.excludedSymlinks ||
508
+ (!partial && (inventory.scannedFiles !== inventory.reportedFiles + inventory.excludedFiles ||
509
+ inventory.scannedDirectories !== inventory.reportedDirectories + inventory.excludedDirectories ||
510
+ inventory.scannedSymlinks !== inventory.reportedSymlinks + inventory.excludedSymlinks))) {
511
+ throw new Error("Tangle raw session inventory does not reconcile");
555
512
  }
556
- if (!partial && (terminal.sequence !== sequences.size ||
557
- [...sequences].some((sequence) => sequence < 0 || sequence >= terminal.sequence))) {
558
- throw new Error("Tangle raw session process sequence is incomplete");
513
+ nativeStore.inventory = {
514
+ scannedFiles: inventory.scannedFiles,
515
+ reportedFiles: inventory.reportedFiles,
516
+ excludedFiles: inventory.excludedFiles,
517
+ scannedDirectories: inventory.scannedDirectories,
518
+ reportedDirectories: inventory.reportedDirectories,
519
+ excludedDirectories: inventory.excludedDirectories,
520
+ scannedSymlinks: inventory.scannedSymlinks,
521
+ reportedSymlinks: inventory.reportedSymlinks,
522
+ excludedSymlinks: inventory.excludedSymlinks,
523
+ skippedEntries: inventory.skippedEntries,
524
+ };
525
+ if (native.skipped !== undefined) {
526
+ if (!Array.isArray(native.skipped) || native.skipped.length !== inventory.skippedEntries ||
527
+ native.skipped.some((entry) => !roots.has(nativeRootKey(entry)) || !safeReason(entry.reason))) {
528
+ throw new Error("Tangle raw session skipped inventory does not reconcile");
529
+ }
530
+ for (const entry of native.skipped) {
531
+ if (entry.path !== ".")
532
+ canonicalEntryPath(entry.path);
533
+ }
559
534
  }
560
- terminals.add(processKey);
561
- processStreams.terminals.push(terminal);
562
- }
563
- if (!partial && [...ioSequences.keys()].some((processId) => !terminals.has(processId))) {
564
- throw new Error("Tangle raw session has a process without a terminal receipt");
565
- }
566
- const observedProcesses = [...native.processIo, ...native.processTerminals];
567
- const observedAttemptProcesses = new Set(observedProcesses.map(attemptProcessKey));
568
- for (const attempt of sessionAttempts) {
569
- for (const processId of attempt.processIds) {
570
- const key = attemptProcessKey({ ...attempt, processId,
571
- sourceId: sourceBindings.get(attempt.executionId)?.sourceId });
572
- if (observedAttemptProcesses.has(key))
573
- continue;
574
- if (!partial)
575
- throw new Error("Tangle raw session attempt names an unretained attributed process");
576
- processAttributionComplete = false;
577
- missing.push(`Sandbox session ${id} attempt ${attempt.executionId}/${attempt.ordinal} names an unretained attributed process: ${processId}`);
535
+ const ioSequences = new Map();
536
+ const frameMetadata = [];
537
+ for (const [index, frame] of native.processIo.entries()) {
538
+ options.signal?.throwIfAborted();
539
+ if (!safeIdentifier(frame.processId) || (frame.sourceId !== undefined && !safeIdentifier(frame.sourceId)) ||
540
+ !Number.isSafeInteger(frame.sequence) ||
541
+ frame.sequence < 0 || !Number.isFinite(Date.parse(frame.at)) ||
542
+ !["stdin", "stdout", "stderr", "protocol"].includes(frame.stream)) {
543
+ throw new Error("Tangle raw session process stream metadata is invalid");
544
+ }
545
+ const processKey = sourceProcessKey(frame);
546
+ const sequences = ioSequences.get(processKey) ?? new Set();
547
+ if (sequences.has(frame.sequence))
548
+ throw new Error("Tangle raw session repeats a process frame");
549
+ sequences.add(frame.sequence);
550
+ ioSequences.set(processKey, sequences);
551
+ if (!processAttemptMatches(frame, sessionAttempts, partial)) {
552
+ processAttributionComplete = false;
553
+ missing.push(`Sandbox session ${id} process ${frame.processId} has no exact attempt attribution`);
554
+ }
555
+ if (frame.sourceId === undefined || sourceBindings.get(frame.executionId ?? "")?.sourceId !== frame.sourceId) {
556
+ if (!partial)
557
+ throw new Error("Tangle raw session process has conflicting source attribution");
558
+ processAttributionComplete = false;
559
+ missing.push(`Sandbox session ${id} process ${frame.processId} has no exact source attribution`);
560
+ }
561
+ const label = String(frame.sequence).padStart(16, "0");
562
+ const contentPath = "__retention__/sessions/" + id + "/io/" +
563
+ (frame.sourceId === undefined ? "" : frame.sourceId + "/") + frame.processId + "/" + label +
564
+ "-" + frame.stream + ".bin";
565
+ const contentSize = await retainNativeContent(frame, contentPath, 0o600);
566
+ contentRefs.push({ jsonPointer: `/processIo/${index}/contentBase64`, path: contentPath });
567
+ frameMetadata.push(withoutNativeContent(frame));
568
+ capturedBytes = writer.byteLength;
569
+ const counter = (frame.stream + "Bytes");
570
+ processStreams[counter] += contentSize;
571
+ processStreams.streamCount += 1;
578
572
  }
573
+ const terminals = new Set();
574
+ for (const terminal of native.processTerminals) {
575
+ const processKey = sourceProcessKey(terminal);
576
+ if (!safeIdentifier(terminal.processId) || (terminal.sourceId !== undefined && !safeIdentifier(terminal.sourceId)) ||
577
+ terminals.has(processKey) ||
578
+ !Number.isSafeInteger(terminal.sequence) || terminal.sequence < 0 ||
579
+ !Number.isFinite(Date.parse(terminal.at)) ||
580
+ !(terminal.result?.captureError === null || (partial && typeof terminal.result?.captureError === "string")) ||
581
+ !(terminal.result.code === null || Number.isSafeInteger(terminal.result.code)) ||
582
+ !(terminal.result.signal === null || typeof terminal.result.signal === "string") ||
583
+ typeof terminal.result.timedOut !== "boolean" ||
584
+ !(terminal.result.timeoutReason === null || typeof terminal.result.timeoutReason === "string") ||
585
+ (terminal.result.spawnError !== undefined && typeof terminal.result.spawnError !== "string")) {
586
+ throw new Error("Tangle raw session process terminal metadata is invalid");
587
+ }
588
+ const sequences = ioSequences.get(processKey) ?? new Set();
589
+ if (!processAttemptMatches(terminal, sessionAttempts, partial)) {
590
+ processAttributionComplete = false;
591
+ missing.push(`Sandbox session ${id} terminal ${terminal.processId} has no exact attempt attribution`);
592
+ }
593
+ if (terminal.sourceId === undefined || sourceBindings.get(terminal.executionId ?? "")?.sourceId !== terminal.sourceId) {
594
+ if (!partial)
595
+ throw new Error("Tangle raw session terminal has conflicting source attribution");
596
+ processAttributionComplete = false;
597
+ missing.push(`Sandbox session ${id} terminal ${terminal.processId} has no exact source attribution`);
598
+ }
599
+ if (!partial && (terminal.sequence !== sequences.size ||
600
+ [...sequences].some((sequence) => sequence < 0 || sequence >= terminal.sequence))) {
601
+ throw new Error("Tangle raw session process sequence is incomplete");
602
+ }
603
+ terminals.add(processKey);
604
+ processStreams.terminals.push(terminal);
605
+ }
606
+ if (!partial && [...ioSequences.keys()].some((processId) => !terminals.has(processId))) {
607
+ throw new Error("Tangle raw session has a process without a terminal receipt");
608
+ }
609
+ const observedProcesses = [...native.processIo, ...native.processTerminals];
610
+ const observedAttemptProcesses = new Set(observedProcesses.map(attemptProcessKey));
611
+ for (const attempt of sessionAttempts) {
612
+ for (const processId of attempt.processIds) {
613
+ const key = attemptProcessKey({ ...attempt, processId,
614
+ sourceId: sourceBindings.get(attempt.executionId)?.sourceId });
615
+ if (observedAttemptProcesses.has(key))
616
+ continue;
617
+ if (!partial)
618
+ throw new Error("Tangle raw session attempt names an unretained attributed process");
619
+ processAttributionComplete = false;
620
+ missing.push(`Sandbox session ${id} attempt ${attempt.executionId}/${attempt.ordinal} names an unretained attributed process: ${processId}`);
621
+ }
622
+ }
623
+ processStreams.processCount = new Set([...ioSequences.keys(), ...terminals]).size;
624
+ processStreams.terminalCount = terminals.size;
625
+ const spoolSources = new Set();
626
+ for (const [index, processSource] of native.processSources.entries()) {
627
+ if (!safeIdentifier(processSource.sourceId) || !sourceHomes.has(processSource.sourceId) ||
628
+ spoolSources.has(processSource.sourceId))
629
+ throw new Error("Tangle raw session process source identity is invalid");
630
+ spoolSources.add(processSource.sourceId);
631
+ const sourcePath = "__retention__/sessions/" + id + "/process-sources/" + processSource.sourceId + ".jsonl";
632
+ const sourceSize = await retainNativeContent(processSource, sourcePath, 0o600);
633
+ capturedBytes = writer.byteLength;
634
+ processStreams.sources.push({ sourceId: processSource.sourceId, path: sourcePath, sizeBytes: sourceSize, sha256: processSource.sha256 });
635
+ contentRefs.push({ jsonPointer: `/processSources/${index}/contentBase64`, path: sourcePath });
636
+ }
637
+ const missingSpoolSources = [...sourceHomes.keys()].filter((sourceId) => !spoolSources.has(sourceId));
638
+ if (!partial && missingSpoolSources.length > 0) {
639
+ throw new Error("Tangle raw session omits an original process source");
640
+ }
641
+ for (const sourceId of missingSpoolSources) {
642
+ missing.push(`Sandbox session ${id} has no original process source: ${sourceId}`);
643
+ }
644
+ manifestSource = {
645
+ ...native,
646
+ files: native.files.map((entry) => entry.kind === "file" ? withoutNativeContent(entry) : entry),
647
+ processIo: frameMetadata,
648
+ processSources: native.processSources.map(withoutNativeContent),
649
+ };
650
+ nativeStore.complete = sourceCoverage && nativeRootCoverage && native.completeness.nativeStore && inventory.skippedEntries === 0 &&
651
+ inventory.scannedFiles === inventory.reportedFiles + inventory.excludedFiles &&
652
+ inventory.scannedDirectories === inventory.reportedDirectories + inventory.excludedDirectories &&
653
+ inventory.scannedSymlinks === inventory.reportedSymlinks + inventory.excludedSymlinks;
654
+ processStreams.complete = missingSpoolSources.length === 0 && processAttributionComplete && native.completeness.processIo && [...ioSequences.keys()].every((processId) => terminals.has(processId)) &&
655
+ native.processTerminals.every((terminal) => {
656
+ const sequences = ioSequences.get(sourceProcessKey(terminal)) ?? new Set();
657
+ return terminal.result.captureError === null && terminal.sequence === sequences.size &&
658
+ [...sequences].every((sequence) => sequence >= 0 && sequence < terminal.sequence);
659
+ });
660
+ nativeEvents.complete = sourceCoverage && unattributedExecutions.length === 0 && native.completeness.events && nativeEventCoverage;
661
+ nativeEvents.count = native.events.length;
662
+ nativeReason = partial ? (native.missingReasons.join("; ") || "incomplete-execution-attribution") : null;
579
663
  }
580
- processStreams.processCount = new Set([...ioSequences.keys(), ...terminals]).size;
581
- processStreams.terminalCount = terminals.size;
582
- const spoolSources = new Set();
583
- for (const [index, processSource] of native.processSources.entries()) {
584
- if (!safeIdentifier(processSource.sourceId) || !sourceHomes.has(processSource.sourceId) ||
585
- spoolSources.has(processSource.sourceId))
586
- throw new Error("Tangle raw session process source identity is invalid");
587
- spoolSources.add(processSource.sourceId);
588
- const source = exactNativeBytes(processSource.contentBase64, processSource.sizeBytes, processSource.sha256, options.maxBytes - capturedBytes);
589
- const sourcePath = "__retention__/sessions/" + id + "/process-sources/" + processSource.sourceId + ".jsonl";
590
- files.push({ path: sourcePath, bytes: source, mode: 0o600 });
591
- capturedBytes += source.byteLength;
592
- processStreams.sources.push({ sourceId: processSource.sourceId, path: sourcePath, sizeBytes: source.byteLength, sha256: processSource.sha256 });
593
- contentRefs.push({ jsonPointer: `/processSources/${index}/contentBase64`, path: sourcePath });
594
- }
595
- const missingSpoolSources = [...sourceHomes.keys()].filter((sourceId) => !spoolSources.has(sourceId));
596
- if (!partial && missingSpoolSources.length > 0) {
597
- throw new Error("Tangle raw session omits an original process source");
664
+ else if (native.status === "unavailable") {
665
+ if (!safeReason(native.reason))
666
+ throw new Error("Tangle raw session unavailability reason is invalid");
667
+ nativeReason = native.reason;
598
668
  }
599
- for (const sourceId of missingSpoolSources) {
600
- missing.push(`Sandbox session ${id} has no original process source: ${sourceId}`);
669
+ else {
670
+ throw new Error("Tangle raw session capture status is invalid");
601
671
  }
602
- manifestSource = {
603
- ...native,
604
- files: native.files.map((entry) => entry.kind === "file" ? withoutNativeContent(entry) : entry),
605
- processIo: frameMetadata,
606
- processSources: native.processSources.map(withoutNativeContent),
607
- };
608
- nativeStore.complete = sourceCoverage && nativeRootCoverage && native.completeness.nativeStore && inventory.skippedEntries === 0 &&
609
- inventory.scannedFiles === inventory.reportedFiles + inventory.excludedFiles &&
610
- inventory.scannedDirectories === inventory.reportedDirectories + inventory.excludedDirectories &&
611
- inventory.scannedSymlinks === inventory.reportedSymlinks + inventory.excludedSymlinks;
612
- processStreams.complete = missingSpoolSources.length === 0 && processAttributionComplete && native.completeness.processIo && [...ioSequences.keys()].every((processId) => terminals.has(processId)) &&
613
- native.processTerminals.every((terminal) => {
614
- const sequences = ioSequences.get(sourceProcessKey(terminal)) ?? new Set();
615
- return terminal.result.captureError === null && terminal.sequence === sequences.size &&
616
- [...sequences].every((sequence) => sequence >= 0 && sequence < terminal.sequence);
617
- });
618
- nativeEvents.complete = sourceCoverage && unattributedExecutions.length === 0 && native.completeness.events && nativeEventCoverage;
619
- nativeEvents.count = native.events.length;
620
- nativeReason = partial ? (native.missingReasons.join("; ") || "incomplete-execution-attribution") : null;
621
- }
622
- else if (native.status === "unavailable") {
623
- if (!safeReason(native.reason))
624
- throw new Error("Tangle raw session unavailability reason is invalid");
625
- nativeReason = native.reason;
672
+ await writer.writeChunks("__retention__/sessions/" + id + "/raw-manifest.json", 0o600, evidenceJsonChunks({ kind: "tangle-native-session-evidence.v1", source: manifestSource,
673
+ contentEncoding: "base64", contentRefs }));
674
+ capturedBytes = writer.byteLength;
626
675
  }
627
- else {
628
- throw new Error("Tangle raw session capture status is invalid");
676
+ sessions.push({
677
+ id, executionId: artifactExecutionId, executionIds: [...executionIds], eventCountsByExecutionId,
678
+ backendType: options.harness, sidecarImageDigest, sidecarBundleRevision,
679
+ transportEvents: executionIds.every((executionId) => eventCountsByExecutionId[executionId] > 0) ? "complete" : "unavailable",
680
+ eventCount: counts.events, messageCount: counts.messages, messageScope: "session",
681
+ nativeSessionId, nativeReason, nativeStore, processStreams, nativeEvents,
682
+ evidenceSources,
683
+ });
684
+ for (const executionId of executionIds) {
685
+ if (!eventCountsByExecutionId[executionId]) {
686
+ missing.push("Sandbox session " + id + " returned no events for execution " + executionId);
687
+ }
629
688
  }
630
- const manifest = Buffer.from(JSON.stringify({
631
- kind: "tangle-native-session-evidence.v1", source: manifestSource, contentEncoding: "base64", contentRefs,
632
- }));
633
- if (capturedBytes + manifest.byteLength > options.maxBytes)
634
- throw new Error("Tangle evidence exceeds byte limit");
635
- files.push({ path: "__retention__/sessions/" + id + "/raw-manifest.json", bytes: manifest, mode: 0o600 });
636
- capturedBytes += manifest.byteLength;
637
- }
638
- sessions.push({
639
- id, executionId: artifactExecutionId, executionIds: [...executionIds], eventCountsByExecutionId,
640
- backendType: options.harness, sidecarImageDigest, sidecarBundleRevision,
641
- transportEvents: executionIds.every((executionId) => eventCountsByExecutionId[executionId] > 0) ? "complete" : "unavailable",
642
- eventCount: events.length, messageCount: messages.length, messageScope: "session",
643
- nativeSessionId, nativeReason, nativeStore, processStreams, nativeEvents,
644
- evidenceSources,
645
- });
646
- for (const executionId of executionIds) {
647
- if (!eventCountsByExecutionId[executionId]) {
648
- missing.push("Sandbox session " + id + " returned no events for execution " + executionId);
689
+ if (!nativeStore.complete || !processStreams.complete || !nativeEvents.complete) {
690
+ missing.push("Raw native session capture for Sandbox session " + id + " is unavailable: " + nativeReason);
649
691
  }
650
692
  }
651
- if (!nativeStore.complete || !processStreams.complete || !nativeEvents.complete) {
652
- missing.push("Raw native session capture for Sandbox session " + id + " is unavailable: " + nativeReason);
693
+ finally {
694
+ await prepared?.remove();
653
695
  }
654
696
  }
655
697
  const provenance = {
@@ -671,8 +713,8 @@ export async function captureTangleSandboxEvidence(box, options) {
671
713
  const provenanceBytes = Buffer.from(JSON.stringify({ kind: "tangle-evidence-provenance.v1", ...provenance }));
672
714
  if (capturedBytes + provenanceBytes.byteLength > options.maxBytes)
673
715
  throw new Error("Tangle evidence exceeds byte limit");
674
- files.push({ path: "__retention__/provenance.json", bytes: provenanceBytes, mode: 0o600 });
675
- return { files: files.sort((a, b) => a.path.localeCompare(b.path)), provenance };
716
+ await writer.write({ path: "__retention__/provenance.json", bytes: provenanceBytes, mode: 0o600 });
717
+ return provenance;
676
718
  }
677
719
  /** Match every response to exactly one request before accepting any file bytes. */
678
720
  async function readWorkspaceEvidenceBatch(fs, entries, maxBytes, signal) {
@@ -845,7 +887,8 @@ function nativeEventsMatch(events, sessionId, executionIds, partial) {
845
887
  if (event === null || typeof event !== "object")
846
888
  throw new Error("Tangle raw session event buffer is malformed");
847
889
  const entry = event;
848
- if (entry.metadata === null || typeof entry.metadata !== "object" || !Array.isArray(entry.frames)) {
890
+ if (entry.metadata === null || typeof entry.metadata !== "object" ||
891
+ !(Array.isArray(entry.frames) || entry.frames instanceof EvidenceJsonArray)) {
849
892
  throw new Error("Tangle raw session event buffer is malformed");
850
893
  }
851
894
  const metadata = entry.metadata;
@@ -853,7 +896,8 @@ function nativeEventsMatch(events, sessionId, executionIds, partial) {
853
896
  !safeIdentifier(metadata.executionId) || (!partial && !executionIds.includes(metadata.executionId)) || seen.has(metadata.executionId)) {
854
897
  throw new Error("Tangle raw session event buffer has unrelated or duplicate execution identity");
855
898
  }
856
- if (!Number.isSafeInteger(metadata.eventCount) || Number(metadata.eventCount) < 0 || metadata.eventCount !== entry.frames.length) {
899
+ const frameCount = entry.frames instanceof EvidenceJsonArray ? entry.frames.count : entry.frames.length;
900
+ if (!Number.isSafeInteger(metadata.eventCount) || Number(metadata.eventCount) < 0 || metadata.eventCount !== frameCount) {
857
901
  if (!partial)
858
902
  throw new Error("Tangle raw session event buffer count is inconsistent");
859
903
  countsComplete = false;