@tangle-network/agent-provider-tangle 3.4.2 → 3.5.1

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