@tangle-network/agent-provider-tangle 1.9.2 → 3.0.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,45 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
- import { parseBackendType } from "@tangle-network/sandbox";
3
- import { nativeCaptureHarnesses, requireNativeCaptureProof } from "./tangle-native-capture-proof.js";
2
+ import { requireNativeCaptureProof } from "./tangle-native-capture-proof.js";
4
3
  const handles = new WeakMap();
5
4
  const blockedNames = new Set([".ssh", ".config", ".claude", ".codex", ".opencode", ".env", ".env.local", ".npmrc", ".sidecar"]);
6
5
  const MAX_ENTRIES = 100_000;
7
6
  const MAX_EVENTS = 100_000;
8
- const verifiedCapabilities = new WeakSet();
9
- /** Read a deployment guarantee once, before Runtime starts creating environments. */
10
- export async function readTangleEvidenceCapabilities(client) {
11
- if (typeof client.evidenceCapabilities !== "function")
12
- throw new Error("Tangle deployment has no pre-create evidence capability query");
13
- const document = await client.evidenceCapabilities();
14
- if (document?.workspaceCaptureV1 !== true || typeof document.nativeSessionCaptureV1 !== "boolean" ||
15
- !/^sha256:[0-9a-f]{64}$/.test(document.sidecarImageDigest ?? "")) {
16
- throw new Error("Tangle deployment has not proven complete workspace and native session capture for next-create placement");
17
- }
18
- const verified = Object.freeze({
19
- workspaceCaptureV1: true,
20
- nativeSessionCaptureV1: document.nativeSessionCaptureV1,
21
- nativeSessionCaptureHarnesses: nativeCaptureHarnesses(document.nativeSessionCaptureHarnesses),
22
- sidecarImageDigest: document.sidecarImageDigest,
23
- });
24
- verifiedCapabilities.add(verified);
25
- return verified;
26
- }
27
- /** Require the exact profile harness in the deployment's verified admission list. */
28
- export function assertTangleEvidenceProfileCapability(document, profile) {
29
- if (!verifiedCapabilities.has(document))
30
- throw new Error("Tangle evidence capability was not read from the deployment");
31
- if (!profile.harness)
32
- throw new Error("Tangle complete native session capture requires an exact profile harness");
33
- parseBackendType(profile.harness);
34
- if (!document.nativeSessionCaptureHarnesses.includes(profile.harness)) {
35
- throw new Error(`Tangle deployment has not proven native session capture for harness ${JSON.stringify(profile.harness)}`);
36
- }
37
- }
38
- /** Refuse unsupported or unproven native trace retention before Sandbox create. */
39
- export async function assertTangleEvidenceCapability(client, profile) {
40
- const document = await readTangleEvidenceCapabilities(client);
41
- assertTangleEvidenceProfileCapability(document, profile);
42
- }
43
7
  export function bindTangleEvidenceEnvironment(environment, box) {
44
8
  handles.set(environment, { box, sessions: new Map() });
45
9
  }
@@ -183,6 +147,7 @@ export async function captureTangleSandboxEvidence(box, options) {
183
147
  }
184
148
  const sessionIds = new Set(options.sandboxSessionIds);
185
149
  const sessions = [];
150
+ const attempts = [];
186
151
  const missing = [];
187
152
  if (sessionIds.size === 0)
188
153
  missing.push("No exact Sandbox session id was attributed to this execution");
@@ -255,23 +220,29 @@ export async function captureTangleSandboxEvidence(box, options) {
255
220
  const processStreams = {
256
221
  complete: false, streamCount: 0, processCount: 0, terminalCount: 0,
257
222
  stdinBytes: 0, stdoutBytes: 0, stderrBytes: 0, protocolBytes: 0, terminals: [],
223
+ sources: [],
258
224
  };
259
225
  const nativeEvents = {
260
- complete: false, count: 0,
226
+ scope: "execution", complete: false, count: 0,
261
227
  };
262
228
  let nativeSessionId = null;
263
229
  let sidecarImageDigest = null;
264
230
  let sidecarBundleRevision = null;
265
231
  let nativeReason = "raw-session-capture-capability-absent";
232
+ let evidenceSources = [];
266
233
  if (native !== undefined) {
234
+ let manifestSource = native;
235
+ const contentRefs = [];
267
236
  if (native.sessionId !== id || native.backendType !== options.harness) {
268
237
  throw new Error("Tangle raw evidence returned an unrelated session or profile backend");
269
238
  }
270
- if (native.nativeSessionId !== undefined && !safeIdentifier(native.nativeSessionId)) {
239
+ if (native.nativeSessionId != null && !safeIdentifier(native.nativeSessionId)) {
271
240
  throw new Error("Tangle raw evidence native session id is invalid");
272
241
  }
273
242
  nativeSessionId = native.nativeSessionId ?? null;
274
- if (native.status === "captured") {
243
+ if (native.status === "captured" || native.status === "partial") {
244
+ const declaredPartial = native.status === "partial";
245
+ let partial = declaredPartial;
275
246
  if (captureProof && (native.proofStatus !== "verified" ||
276
247
  native.containerId !== captureProof.containerId ||
277
248
  native.sidecarImageDigest !== captureProof.imageId ||
@@ -289,37 +260,105 @@ export async function captureTangleSandboxEvidence(box, options) {
289
260
  }
290
261
  sidecarImageDigest = native.sidecarImageDigest;
291
262
  sidecarBundleRevision = native.sidecarBundleRevision;
292
- if (native.completeness?.nativeStore !== true || native.completeness.processIo !== true ||
293
- native.completeness.events !== true || !Array.isArray(native.files) ||
263
+ if (typeof native.completeness?.nativeStore !== "boolean" || typeof native.completeness.processIo !== "boolean" ||
264
+ typeof native.completeness.events !== "boolean" || !Array.isArray(native.files) ||
294
265
  !Array.isArray(native.processIo) || !Array.isArray(native.events) ||
266
+ !Array.isArray(native.processSources) || !Array.isArray(native.evidenceSources) ||
295
267
  !Array.isArray(native.excluded) || !Array.isArray(native.nativeRoots) || !native.inventory ||
296
- !Array.isArray(native.processTerminals) || native.coverageComplete !== true) {
268
+ !Array.isArray(native.processTerminals) || typeof native.coverageComplete !== "boolean" ||
269
+ !Array.isArray(native.missingReasons) || native.missingReasons.some((reason) => !safeReason(reason))) {
270
+ throw new Error("Tangle raw session capture is malformed");
271
+ }
272
+ if ((!declaredPartial && (native.completeness.nativeStore !== true || native.completeness.processIo !== true ||
273
+ native.completeness.events !== true || native.coverageComplete !== true || native.missingReasons.length > 0)) ||
274
+ (declaredPartial && native.coverageComplete !== false)) {
297
275
  throw new Error("Tangle raw session capture is incomplete");
298
276
  }
277
+ if (!Array.isArray(native.attempts) || native.attempts.length > MAX_ENTRIES) {
278
+ throw new Error("Tangle raw session attempt inventory is missing or invalid");
279
+ }
280
+ const unattributedExecutions = [...new Set(native.attempts.filter(isEvidenceAttempt)
281
+ .map((attempt) => attempt.executionId).filter((executionId) => !executionIds.includes(executionId)))];
282
+ if (unattributedExecutions.length) {
283
+ partial = true;
284
+ for (const executionId of unattributedExecutions) {
285
+ missing.push(`Sandbox session ${id} has an execution without retained caller attribution: ${executionId}`);
286
+ }
287
+ }
288
+ const sessionAttempts = readNativeAttempts(native.attempts, executionIds, partial);
289
+ const sourceBindings = new Map();
290
+ const sourceHomes = new Map();
291
+ for (const source of native.evidenceSources) {
292
+ if (!source || !safeIdentifier(source.executionId) || !safeIdentifier(source.sourceId) ||
293
+ source.backendType !== options.harness || !canonicalNativeRoot(source.runtimeHome) ||
294
+ !Array.isArray(source.credentialPaths) || sourceBindings.has(source.executionId) ||
295
+ (sourceHomes.has(source.sourceId) && sourceHomes.get(source.sourceId) !== source.runtimeHome)) {
296
+ throw new Error("Tangle raw session evidence source identity is invalid");
297
+ }
298
+ for (const path of source.credentialPaths)
299
+ canonicalEntryPath(path);
300
+ sourceBindings.set(source.executionId, source);
301
+ sourceHomes.set(source.sourceId, source.runtimeHome);
302
+ }
303
+ const sourceCoverage = executionIds.every((executionId) => sourceBindings.has(executionId)) &&
304
+ native.evidenceSources.every((source) => executionIds.includes(source.executionId));
305
+ if (!sourceCoverage) {
306
+ if (!partial)
307
+ throw new Error("Tangle raw session sources do not cover the exact executions");
308
+ missing.push(`Sandbox session ${id} evidence sources do not cover the exact executions`);
309
+ }
310
+ evidenceSources = native.evidenceSources;
311
+ let processAttributionComplete = sourceCoverage;
312
+ const nativeEventCoverage = nativeEventsMatch(native.events, id, executionIds, partial);
313
+ attempts.push(...sessionAttempts.filter((attempt) => executionIds.includes(attempt.executionId)));
314
+ if (partial)
315
+ missing.push(`Sandbox session ${id} declared partial raw capture`);
316
+ for (const reason of native.missingReasons)
317
+ missing.push(`Sandbox session ${id}: ${reason}`);
318
+ for (const attempt of sessionAttempts) {
319
+ for (const reason of attempt.missingReasons) {
320
+ missing.push(`Sandbox session ${id} attempt ${attempt.executionId}/${attempt.ordinal}: ${reason}`);
321
+ }
322
+ }
323
+ if (!sessionAttempts.length)
324
+ missing.push(`Sandbox session ${id} has no attempt inventory`);
325
+ const nativeIds = new Set(sessionAttempts.flatMap((attempt) => attempt.nativeSessionIds));
326
+ if (nativeSessionId !== null && !nativeIds.has(nativeSessionId)) {
327
+ throw new Error("Tangle raw session identity differs from its attempt inventory");
328
+ }
299
329
  if (native.files.length + native.processIo.length + native.processTerminals.length +
300
330
  native.events.length > MAX_ENTRIES) {
301
331
  throw new Error("Tangle raw session capture exceeds entry limit");
302
332
  }
303
333
  const roots = new Set();
304
334
  for (const root of native.nativeRoots) {
305
- if (!["session-home", "workspace-session"].includes(root.rootScope) || roots.has(root.rootScope) ||
306
- (root.path !== "." && canonicalEntryPath(root.path) !== root.path)) {
335
+ if (!["session-home", "workspace-session"].includes(root.rootScope) || roots.has(nativeRootKey(root)) ||
336
+ !canonicalNativeRoot(root.path) ||
337
+ (root.sourceId !== undefined && (!safeIdentifier(root.sourceId) || !sourceHomes.has(root.sourceId) ||
338
+ (root.rootScope === "session-home" && sourceHomes.get(root.sourceId) !== root.path)))) {
307
339
  throw new Error("Tangle raw session native root is invalid");
308
340
  }
309
- roots.add(root.rootScope);
310
- nativeStore.roots.push({ scope: root.rootScope, path: root.path });
341
+ roots.add(nativeRootKey(root));
342
+ nativeStore.roots.push({ scope: root.rootScope, path: root.path,
343
+ ...(root.sourceId === undefined ? {} : { sourceId: root.sourceId }) });
311
344
  }
312
- if (!roots.size)
345
+ if (!roots.size && (!partial || native.completeness.nativeStore))
313
346
  throw new Error("Tangle raw session has no native root");
347
+ const nativeRootCoverage = [...sourceHomes.keys()].every((sourceId) => roots.has(sourceId + "/session-home"));
348
+ if (!nativeRootCoverage) {
349
+ if (!partial)
350
+ throw new Error("Tangle raw session has an unretained native source root");
351
+ missing.push(`Sandbox session ${id} has an unretained native source root`);
352
+ }
314
353
  const nativePaths = new Set();
315
354
  const included = { file: 0, directory: 0, symlink: 0 };
316
355
  const excluded = { file: 0, directory: 0, symlink: 0 };
317
- for (const entry of native.files) {
356
+ for (const [index, entry] of native.files.entries()) {
318
357
  options.signal?.throwIfAborted();
319
358
  const path = canonicalEntryPath(entry.path);
320
- if (!roots.has(entry.rootScope))
359
+ if (!roots.has(nativeRootKey(entry)))
321
360
  throw new Error("Tangle raw session entry has no native root");
322
- const identity = entry.rootScope + "/" + path;
361
+ const identity = nativeRootKey(entry) + "/" + path;
323
362
  if (nativePaths.has(identity))
324
363
  throw new Error("Tangle raw session repeats a native path");
325
364
  nativePaths.add(identity);
@@ -329,7 +368,10 @@ export async function captureTangleSandboxEvidence(box, options) {
329
368
  const content = exactNativeBytes(entry.contentBase64, entry.sizeBytes, entry.sha256, options.maxBytes - capturedBytes);
330
369
  if (capturedBytes + content.byteLength > options.maxBytes)
331
370
  throw new Error("Tangle evidence exceeds byte limit");
332
- files.push({ path: "__retention__/sessions/" + id + "/native/" + entry.rootScope + "/" + path, bytes: content, mode: entry.mode & 0o777 });
371
+ const contentPath = "__retention__/sessions/" + id + "/native/" +
372
+ (entry.sourceId === undefined ? "" : entry.sourceId + "/") + entry.rootScope + "/" + path;
373
+ files.push({ path: contentPath, bytes: content, mode: entry.mode & 0o777 });
374
+ contentRefs.push({ jsonPointer: `/files/${index}/contentBase64`, path: contentPath });
333
375
  capturedBytes += content.byteLength;
334
376
  }
335
377
  else if (entry.kind === "directory" || entry.kind === "symlink") {
@@ -343,6 +385,7 @@ export async function captureTangleSandboxEvidence(box, options) {
343
385
  }
344
386
  included[entry.kind] += 1;
345
387
  nativeStore.entries.push({
388
+ ...(entry.sourceId === undefined ? {} : { sourceId: entry.sourceId }),
346
389
  rootScope: entry.rootScope, path, kind: entry.kind, mode: entry.mode,
347
390
  uid: entry.uid, gid: entry.gid, mtimeMs: entry.mtimeMs, ctimeMs: entry.ctimeMs,
348
391
  sizeBytes: entry.sizeBytes, sha256: entry.sha256 ?? null, linkTarget: entry.linkTarget ?? null,
@@ -350,8 +393,8 @@ export async function captureTangleSandboxEvidence(box, options) {
350
393
  }
351
394
  for (const exclusion of native.excluded) {
352
395
  const path = canonicalEntryPath(exclusion.path);
353
- const identity = exclusion.rootScope + "/" + path;
354
- if (!roots.has(exclusion.rootScope) || nativePaths.has(identity) ||
396
+ const identity = nativeRootKey(exclusion) + "/" + path;
397
+ if (!roots.has(nativeRootKey(exclusion)) || nativePaths.has(identity) ||
355
398
  exclusion.reason !== "credential" || !["file", "directory", "symlink"].includes(exclusion.kind) ||
356
399
  !nativeStatMetadata(exclusion)) {
357
400
  throw new Error("Tangle raw session exclusion is invalid");
@@ -359,6 +402,7 @@ export async function captureTangleSandboxEvidence(box, options) {
359
402
  nativePaths.add(identity);
360
403
  excluded[exclusion.kind] += 1;
361
404
  nativeStore.excludedPaths.push({
405
+ ...(exclusion.sourceId === undefined ? {} : { sourceId: exclusion.sourceId }),
362
406
  rootScope: exclusion.rootScope, path, kind: exclusion.kind, mode: exclusion.mode,
363
407
  uid: exclusion.uid, gid: exclusion.gid, mtimeMs: exclusion.mtimeMs, ctimeMs: exclusion.ctimeMs,
364
408
  sizeBytes: exclusion.sizeBytes, reason: exclusion.reason,
@@ -371,16 +415,20 @@ export async function captureTangleSandboxEvidence(box, options) {
371
415
  inventory.reportedSymlinks, inventory.scannedSymlinks, inventory.excludedSymlinks,
372
416
  ];
373
417
  if (counts.some((value) => !Number.isSafeInteger(value) || value < 0) ||
374
- inventory.skippedEntries !== 0 ||
418
+ !Number.isSafeInteger(inventory.skippedEntries) || inventory.skippedEntries < 0 ||
419
+ (!partial && inventory.skippedEntries !== 0) ||
375
420
  inventory.reportedFiles !== included.file ||
376
421
  inventory.reportedDirectories !== included.directory ||
377
422
  inventory.reportedSymlinks !== included.symlink ||
378
423
  inventory.excludedFiles !== excluded.file ||
379
424
  inventory.excludedDirectories !== excluded.directory ||
380
425
  inventory.excludedSymlinks !== excluded.symlink ||
381
- inventory.scannedFiles !== inventory.reportedFiles + inventory.excludedFiles ||
382
- inventory.scannedDirectories !== inventory.reportedDirectories + inventory.excludedDirectories ||
383
- inventory.scannedSymlinks !== inventory.reportedSymlinks + inventory.excludedSymlinks) {
426
+ inventory.scannedFiles < inventory.reportedFiles + inventory.excludedFiles ||
427
+ inventory.scannedDirectories < inventory.reportedDirectories + inventory.excludedDirectories ||
428
+ inventory.scannedSymlinks < inventory.reportedSymlinks + inventory.excludedSymlinks ||
429
+ (!partial && (inventory.scannedFiles !== inventory.reportedFiles + inventory.excludedFiles ||
430
+ inventory.scannedDirectories !== inventory.reportedDirectories + inventory.excludedDirectories ||
431
+ inventory.scannedSymlinks !== inventory.reportedSymlinks + inventory.excludedSymlinks))) {
384
432
  throw new Error("Tangle raw session inventory does not reconcile");
385
433
  }
386
434
  nativeStore.inventory = {
@@ -393,33 +441,54 @@ export async function captureTangleSandboxEvidence(box, options) {
393
441
  scannedSymlinks: inventory.scannedSymlinks,
394
442
  reportedSymlinks: inventory.reportedSymlinks,
395
443
  excludedSymlinks: inventory.excludedSymlinks,
396
- skippedEntries: 0,
444
+ skippedEntries: inventory.skippedEntries,
397
445
  };
446
+ if (native.skipped !== undefined) {
447
+ if (!Array.isArray(native.skipped) || native.skipped.length !== inventory.skippedEntries ||
448
+ native.skipped.some((entry) => !roots.has(nativeRootKey(entry)) || !safeReason(entry.reason))) {
449
+ throw new Error("Tangle raw session skipped inventory does not reconcile");
450
+ }
451
+ for (const entry of native.skipped) {
452
+ if (entry.path !== ".")
453
+ canonicalEntryPath(entry.path);
454
+ }
455
+ }
398
456
  const ioSequences = new Map();
399
457
  const frameMetadata = [];
400
- for (const frame of native.processIo) {
458
+ for (const [index, frame] of native.processIo.entries()) {
401
459
  options.signal?.throwIfAborted();
402
- if (!safeIdentifier(frame.processId) || !Number.isSafeInteger(frame.sequence) ||
460
+ if (!safeIdentifier(frame.processId) || (frame.sourceId !== undefined && !safeIdentifier(frame.sourceId)) ||
461
+ !Number.isSafeInteger(frame.sequence) ||
403
462
  frame.sequence < 0 || !Number.isFinite(Date.parse(frame.at)) ||
404
463
  !["stdin", "stdout", "stderr", "protocol"].includes(frame.stream)) {
405
464
  throw new Error("Tangle raw session process stream metadata is invalid");
406
465
  }
407
- const sequences = ioSequences.get(frame.processId) ?? new Set();
466
+ const processKey = sourceProcessKey(frame);
467
+ const sequences = ioSequences.get(processKey) ?? new Set();
408
468
  if (sequences.has(frame.sequence))
409
469
  throw new Error("Tangle raw session repeats a process frame");
410
470
  sequences.add(frame.sequence);
411
- ioSequences.set(frame.processId, sequences);
471
+ ioSequences.set(processKey, sequences);
472
+ if (!processAttemptMatches(frame, sessionAttempts, partial)) {
473
+ processAttributionComplete = false;
474
+ missing.push(`Sandbox session ${id} process ${frame.processId} has no exact attempt attribution`);
475
+ }
476
+ if (frame.sourceId === undefined || sourceBindings.get(frame.executionId ?? "")?.sourceId !== frame.sourceId) {
477
+ if (!partial)
478
+ throw new Error("Tangle raw session process has conflicting source attribution");
479
+ processAttributionComplete = false;
480
+ missing.push(`Sandbox session ${id} process ${frame.processId} has no exact source attribution`);
481
+ }
412
482
  const content = exactNativeBytes(frame.contentBase64, frame.sizeBytes, frame.sha256, options.maxBytes - capturedBytes);
413
483
  if (capturedBytes + content.byteLength > options.maxBytes)
414
484
  throw new Error("Tangle evidence exceeds byte limit");
415
485
  const label = String(frame.sequence).padStart(16, "0");
416
- files.push({ path: "__retention__/sessions/" + id + "/io/" + frame.processId + "/" + label +
417
- "-" + frame.stream + ".bin", bytes: content, mode: 0o600 });
418
- frameMetadata.push({
419
- processId: frame.processId, sequence: frame.sequence, at: frame.at, stream: frame.stream,
420
- sizeBytes: frame.sizeBytes, sha256: frame.sha256,
421
- ...(frame.metadata === undefined ? {} : { metadata: frame.metadata }),
422
- });
486
+ const contentPath = "__retention__/sessions/" + id + "/io/" +
487
+ (frame.sourceId === undefined ? "" : frame.sourceId + "/") + frame.processId + "/" + label +
488
+ "-" + frame.stream + ".bin";
489
+ files.push({ path: contentPath, bytes: content, mode: 0o600 });
490
+ contentRefs.push({ jsonPointer: `/processIo/${index}/contentBase64`, path: contentPath });
491
+ frameMetadata.push(withoutNativeContent(frame));
423
492
  capturedBytes += content.byteLength;
424
493
  const counter = (frame.stream + "Bytes");
425
494
  processStreams[counter] += content.byteLength;
@@ -427,10 +496,12 @@ export async function captureTangleSandboxEvidence(box, options) {
427
496
  }
428
497
  const terminals = new Set();
429
498
  for (const terminal of native.processTerminals) {
430
- if (!safeIdentifier(terminal.processId) || terminals.has(terminal.processId) ||
499
+ const processKey = sourceProcessKey(terminal);
500
+ if (!safeIdentifier(terminal.processId) || (terminal.sourceId !== undefined && !safeIdentifier(terminal.sourceId)) ||
501
+ terminals.has(processKey) ||
431
502
  !Number.isSafeInteger(terminal.sequence) || terminal.sequence < 0 ||
432
503
  !Number.isFinite(Date.parse(terminal.at)) ||
433
- terminal.result?.captureError !== null ||
504
+ !(terminal.result?.captureError === null || (partial && typeof terminal.result?.captureError === "string")) ||
434
505
  !(terminal.result.code === null || Number.isSafeInteger(terminal.result.code)) ||
435
506
  !(terminal.result.signal === null || typeof terminal.result.signal === "string") ||
436
507
  typeof terminal.result.timedOut !== "boolean" ||
@@ -438,47 +509,98 @@ export async function captureTangleSandboxEvidence(box, options) {
438
509
  (terminal.result.spawnError !== undefined && typeof terminal.result.spawnError !== "string")) {
439
510
  throw new Error("Tangle raw session process terminal metadata is invalid");
440
511
  }
441
- const sequences = ioSequences.get(terminal.processId) ?? new Set();
442
- if (terminal.sequence !== sequences.size ||
443
- [...sequences].some((sequence) => sequence < 0 || sequence >= terminal.sequence)) {
512
+ const sequences = ioSequences.get(processKey) ?? new Set();
513
+ if (!processAttemptMatches(terminal, sessionAttempts, partial)) {
514
+ processAttributionComplete = false;
515
+ missing.push(`Sandbox session ${id} terminal ${terminal.processId} has no exact attempt attribution`);
516
+ }
517
+ if (terminal.sourceId === undefined || sourceBindings.get(terminal.executionId ?? "")?.sourceId !== terminal.sourceId) {
518
+ if (!partial)
519
+ throw new Error("Tangle raw session terminal has conflicting source attribution");
520
+ processAttributionComplete = false;
521
+ missing.push(`Sandbox session ${id} terminal ${terminal.processId} has no exact source attribution`);
522
+ }
523
+ if (!partial && (terminal.sequence !== sequences.size ||
524
+ [...sequences].some((sequence) => sequence < 0 || sequence >= terminal.sequence))) {
444
525
  throw new Error("Tangle raw session process sequence is incomplete");
445
526
  }
446
- terminals.add(terminal.processId);
527
+ terminals.add(processKey);
447
528
  processStreams.terminals.push(terminal);
448
529
  }
449
- if ([...ioSequences.keys()].some((processId) => !terminals.has(processId))) {
530
+ if (!partial && [...ioSequences.keys()].some((processId) => !terminals.has(processId))) {
450
531
  throw new Error("Tangle raw session has a process without a terminal receipt");
451
532
  }
452
- processStreams.processCount = terminals.size;
533
+ const observedProcesses = [...native.processIo, ...native.processTerminals];
534
+ const observedAttemptProcesses = new Set(observedProcesses.map(attemptProcessKey));
535
+ for (const attempt of sessionAttempts) {
536
+ for (const processId of attempt.processIds) {
537
+ const key = attemptProcessKey({ ...attempt, processId,
538
+ sourceId: sourceBindings.get(attempt.executionId)?.sourceId });
539
+ if (observedAttemptProcesses.has(key))
540
+ continue;
541
+ if (!partial)
542
+ throw new Error("Tangle raw session attempt names an unretained attributed process");
543
+ processAttributionComplete = false;
544
+ missing.push(`Sandbox session ${id} attempt ${attempt.executionId}/${attempt.ordinal} names an unretained attributed process: ${processId}`);
545
+ }
546
+ }
547
+ processStreams.processCount = new Set([...ioSequences.keys(), ...terminals]).size;
453
548
  processStreams.terminalCount = terminals.size;
454
- const processManifest = Buffer.from(JSON.stringify({
455
- kind: "tangle-native-process-streams.v1", sessionId: id,
456
- frames: frameMetadata, terminals: native.processTerminals,
457
- }));
458
- if (capturedBytes + processManifest.byteLength > options.maxBytes)
459
- throw new Error("Tangle evidence exceeds byte limit");
460
- files.push({ path: "__retention__/sessions/" + id + "/process-manifest.json",
461
- bytes: processManifest, mode: 0o600 });
462
- capturedBytes += processManifest.byteLength;
463
- const nativeEventBytes = Buffer.from(JSON.stringify({
464
- kind: "tangle-native-session-events.v1", sessionId: id, backendType: native.backendType,
465
- nativeSessionId, events: native.events,
466
- }));
467
- if (capturedBytes + nativeEventBytes.byteLength > options.maxBytes)
468
- throw new Error("Tangle evidence exceeds byte limit");
469
- files.push({ path: "__retention__/sessions/" + id + "/native-events.json", bytes: nativeEventBytes, mode: 0o600 });
470
- capturedBytes += nativeEventBytes.byteLength;
471
- nativeStore.complete = true;
472
- processStreams.complete = true;
473
- nativeEvents.complete = true;
549
+ const spoolSources = new Set();
550
+ for (const [index, processSource] of native.processSources.entries()) {
551
+ if (!safeIdentifier(processSource.sourceId) || !sourceHomes.has(processSource.sourceId) ||
552
+ spoolSources.has(processSource.sourceId))
553
+ throw new Error("Tangle raw session process source identity is invalid");
554
+ spoolSources.add(processSource.sourceId);
555
+ const source = exactNativeBytes(processSource.contentBase64, processSource.sizeBytes, processSource.sha256, options.maxBytes - capturedBytes);
556
+ const sourcePath = "__retention__/sessions/" + id + "/process-sources/" + processSource.sourceId + ".jsonl";
557
+ files.push({ path: sourcePath, bytes: source, mode: 0o600 });
558
+ capturedBytes += source.byteLength;
559
+ processStreams.sources.push({ sourceId: processSource.sourceId, path: sourcePath, sizeBytes: source.byteLength, sha256: processSource.sha256 });
560
+ contentRefs.push({ jsonPointer: `/processSources/${index}/contentBase64`, path: sourcePath });
561
+ }
562
+ const missingSpoolSources = [...sourceHomes.keys()].filter((sourceId) => !spoolSources.has(sourceId));
563
+ if (!partial && missingSpoolSources.length > 0) {
564
+ throw new Error("Tangle raw session omits an original process source");
565
+ }
566
+ for (const sourceId of missingSpoolSources) {
567
+ missing.push(`Sandbox session ${id} has no original process source: ${sourceId}`);
568
+ }
569
+ manifestSource = {
570
+ ...native,
571
+ files: native.files.map((entry) => entry.kind === "file" ? withoutNativeContent(entry) : entry),
572
+ processIo: frameMetadata,
573
+ processSources: native.processSources.map(withoutNativeContent),
574
+ };
575
+ nativeStore.complete = sourceCoverage && nativeRootCoverage && native.completeness.nativeStore && inventory.skippedEntries === 0 &&
576
+ inventory.scannedFiles === inventory.reportedFiles + inventory.excludedFiles &&
577
+ inventory.scannedDirectories === inventory.reportedDirectories + inventory.excludedDirectories &&
578
+ inventory.scannedSymlinks === inventory.reportedSymlinks + inventory.excludedSymlinks;
579
+ processStreams.complete = missingSpoolSources.length === 0 && processAttributionComplete && native.completeness.processIo && [...ioSequences.keys()].every((processId) => terminals.has(processId)) &&
580
+ native.processTerminals.every((terminal) => {
581
+ const sequences = ioSequences.get(sourceProcessKey(terminal)) ?? new Set();
582
+ return terminal.result.captureError === null && terminal.sequence === sequences.size &&
583
+ [...sequences].every((sequence) => sequence >= 0 && sequence < terminal.sequence);
584
+ });
585
+ nativeEvents.complete = sourceCoverage && unattributedExecutions.length === 0 && native.completeness.events && nativeEventCoverage;
474
586
  nativeEvents.count = native.events.length;
475
- nativeReason = null;
587
+ nativeReason = partial ? (native.missingReasons.join("; ") || "incomplete-execution-attribution") : null;
476
588
  }
477
- else {
478
- if (!safeIdentifier(native.reason))
589
+ else if (native.status === "unavailable") {
590
+ if (!safeReason(native.reason))
479
591
  throw new Error("Tangle raw session unavailability reason is invalid");
480
592
  nativeReason = native.reason;
481
593
  }
594
+ else {
595
+ throw new Error("Tangle raw session capture status is invalid");
596
+ }
597
+ const manifest = Buffer.from(JSON.stringify({
598
+ kind: "tangle-native-session-evidence.v1", source: manifestSource, contentEncoding: "base64", contentRefs,
599
+ }));
600
+ if (capturedBytes + manifest.byteLength > options.maxBytes)
601
+ throw new Error("Tangle evidence exceeds byte limit");
602
+ files.push({ path: "__retention__/sessions/" + id + "/raw-manifest.json", bytes: manifest, mode: 0o600 });
603
+ capturedBytes += manifest.byteLength;
482
604
  }
483
605
  sessions.push({
484
606
  id, executionId: options.executionId, executionIds: [...executionIds], eventCountsByExecutionId,
@@ -486,6 +608,7 @@ export async function captureTangleSandboxEvidence(box, options) {
486
608
  transportEvents: executionIds.every((executionId) => eventCountsByExecutionId[executionId] > 0) ? "complete" : "unavailable",
487
609
  eventCount: events.length, messageCount: messages.length, messageScope: "session",
488
610
  nativeSessionId, nativeReason, nativeStore, processStreams, nativeEvents,
611
+ evidenceSources,
489
612
  });
490
613
  for (const executionId of executionIds) {
491
614
  if (!eventCountsByExecutionId[executionId]) {
@@ -507,6 +630,7 @@ export async function captureTangleSandboxEvidence(box, options) {
507
630
  entries: metadata.sort((a, b) => a.path.localeCompare(b.path)),
508
631
  excludedPaths,
509
632
  workspace: { scannedFiles, scannedDirectories, reportedFiles: usage.fileCount, reportedDirectories: usage.directoryCount, complete: true },
633
+ attempts,
510
634
  sessions,
511
635
  missing,
512
636
  };
@@ -516,8 +640,113 @@ export async function captureTangleSandboxEvidence(box, options) {
516
640
  files.push({ path: "__retention__/provenance.json", bytes: provenanceBytes, mode: 0o600 });
517
641
  return { files: files.sort((a, b) => a.path.localeCompare(b.path)), provenance };
518
642
  }
643
+ /** Keep every source field; store validated binary content once in the archive. */
644
+ function withoutNativeContent(source) {
645
+ const metadata = { ...source };
646
+ delete metadata.contentBase64;
647
+ return metadata;
648
+ }
519
649
  function safeIdentifier(value) {
520
- return /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value);
650
+ return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value);
651
+ }
652
+ function safeReason(value) {
653
+ return typeof value === "string" && value.length > 0 && value.length <= 1024 && !/[\u0000-\u001f\u007f]/.test(value);
654
+ }
655
+ function nativeRootKey(value) {
656
+ return `${value.sourceId ?? ""}/${value.rootScope}`;
657
+ }
658
+ function sourceProcessKey(value) {
659
+ return `${value.sourceId ?? ""}/${value.processId}`;
660
+ }
661
+ function attemptProcessKey(value) {
662
+ return `${sourceProcessKey(value)}/${value.executionId ?? ""}/${value.ordinal ?? ""}/${value.providerSessionId ?? ""}`;
663
+ }
664
+ /** Source roots are metadata; archive entry paths remain relative. */
665
+ function canonicalNativeRoot(value) {
666
+ if (typeof value !== "string" || value.includes("\\") || value.includes("\0"))
667
+ return false;
668
+ if (value === ".")
669
+ return true;
670
+ const parts = (value.startsWith("/") ? value.slice(1) : value).split("/");
671
+ return parts.every((part) => part.length > 0 && part !== "." && part !== "..");
672
+ }
673
+ function readNativeAttempts(value, executionIds, partial) {
674
+ if (!Array.isArray(value) || value.length > MAX_ENTRIES || (!partial && value.length === 0)) {
675
+ throw new Error("Tangle raw session attempt inventory is missing or invalid");
676
+ }
677
+ const ordinals = new Map();
678
+ const attempts = [];
679
+ for (const entry of value) {
680
+ if (!isEvidenceAttempt(entry) || (!partial && !executionIds.includes(entry.executionId))) {
681
+ throw new Error("Tangle raw session attempt has invalid identity or an unrelated execution");
682
+ }
683
+ const seen = ordinals.get(entry.executionId) ?? new Set();
684
+ if (seen.has(entry.ordinal))
685
+ throw new Error("Tangle raw session repeats an attempt ordinal");
686
+ seen.add(entry.ordinal);
687
+ ordinals.set(entry.executionId, seen);
688
+ if (!partial && (!entry.nativeSessionIds.length ||
689
+ entry.outcome === "unknown" || entry.missingReasons.length > 0)) {
690
+ throw new Error("Tangle raw session attempt coverage is incomplete");
691
+ }
692
+ attempts.push({ ...entry, nativeSessionIds: [...entry.nativeSessionIds], processIds: [...entry.processIds], missingReasons: [...entry.missingReasons] });
693
+ }
694
+ if (!partial && executionIds.some((id) => {
695
+ const seen = ordinals.get(id);
696
+ return !seen || Array.from({ length: seen.size }, (_, i) => i + 1).some((ordinal) => !seen.has(ordinal));
697
+ })) {
698
+ throw new Error("Tangle raw session attempt inventory does not cover every execution and retry");
699
+ }
700
+ return attempts;
701
+ }
702
+ function isEvidenceAttempt(value) {
703
+ if (value === null || typeof value !== "object")
704
+ return false;
705
+ const entry = value;
706
+ const identifiers = (candidate) => Array.isArray(candidate) &&
707
+ candidate.every((id) => typeof id === "string" && safeIdentifier(id)) && new Set(candidate).size === candidate.length;
708
+ return typeof entry.executionId === "string" && safeIdentifier(entry.executionId) &&
709
+ Number.isSafeInteger(entry.ordinal) && Number(entry.ordinal) > 0 &&
710
+ typeof entry.providerSessionId === "string" && safeIdentifier(entry.providerSessionId) &&
711
+ identifiers(entry.nativeSessionIds) && identifiers(entry.processIds) &&
712
+ typeof entry.outcome === "string" && ["succeeded", "failed", "cancelled", "unknown"].includes(entry.outcome) &&
713
+ identifiers(entry.missingReasons);
714
+ }
715
+ function processAttemptMatches(value, attempts, partial) {
716
+ const owners = attempts.filter((attempt) => attempt.processIds.includes(value.processId) &&
717
+ attempt.executionId === value.executionId && attempt.ordinal === value.ordinal &&
718
+ attempt.providerSessionId === value.providerSessionId);
719
+ const exact = owners.length === 1;
720
+ if (!exact && !partial)
721
+ throw new Error("Tangle raw session process has missing or conflicting attempt attribution");
722
+ return exact;
723
+ }
724
+ function nativeEventsMatch(events, sessionId, executionIds, partial) {
725
+ const seen = new Set();
726
+ let countsComplete = true;
727
+ for (const event of events) {
728
+ if (event === null || typeof event !== "object")
729
+ throw new Error("Tangle raw session event buffer is malformed");
730
+ const entry = event;
731
+ if (entry.metadata === null || typeof entry.metadata !== "object" || !Array.isArray(entry.frames)) {
732
+ throw new Error("Tangle raw session event buffer is malformed");
733
+ }
734
+ const metadata = entry.metadata;
735
+ if (metadata.sessionId !== sessionId || typeof metadata.executionId !== "string" ||
736
+ !safeIdentifier(metadata.executionId) || (!partial && !executionIds.includes(metadata.executionId)) || seen.has(metadata.executionId)) {
737
+ throw new Error("Tangle raw session event buffer has unrelated or duplicate execution identity");
738
+ }
739
+ if (!Number.isSafeInteger(metadata.eventCount) || Number(metadata.eventCount) < 0 || metadata.eventCount !== entry.frames.length) {
740
+ if (!partial)
741
+ throw new Error("Tangle raw session event buffer count is inconsistent");
742
+ countsComplete = false;
743
+ }
744
+ seen.add(metadata.executionId);
745
+ }
746
+ const complete = countsComplete && executionIds.every((executionId) => seen.has(executionId));
747
+ if (!complete && !partial)
748
+ throw new Error("Tangle raw session event buffers do not cover every execution");
749
+ return complete;
521
750
  }
522
751
  function canonicalEntryPath(value) {
523
752
  if (!value || value.startsWith("/") || value.includes("\\") || value.includes("\0"))
@@ -1,9 +1,10 @@
1
1
  import { type HarnessType } from "@tangle-network/agent-interface";
2
- import type { NativeCaptureProofLike, SandboxClientLike, SandboxInstanceLike } from "./tangle-types.js";
2
+ import type { NativeCaptureProofLike, SandboxInstanceLike, SandboxRuntimeCapabilityDocument } from "./tangle-types.js";
3
3
  /** Require a current host proof; a create must also prove its receipt names that same container. */
4
4
  export declare function requireNativeCaptureProof(box: SandboxInstanceLike, create?: boolean): NativeCaptureProofLike;
5
5
  /** Parse the deployment's explicit per-harness admission without inferring from a global flag. */
6
6
  export declare function nativeCaptureHarnesses(raw: unknown): readonly HarnessType[];
7
- /** Refuse an unsupported deployment before creating a billable sandbox.
8
- * Unprofiled exact-process and checkpoint restores retain the stricter universal guarantee. */
9
- export declare function requireNativeCaptureCapability(client: SandboxClientLike, harness?: string): Promise<void>;
7
+ /** Require the selected container's native protocol and exact agent backend before dispatch. */
8
+ export declare function requireNativeCaptureCapability(box: SandboxInstanceLike, harness: string): Promise<SandboxRuntimeCapabilityDocument>;
9
+ /** Validate each newly dispatched backend against this container's measured document. */
10
+ export declare function assertNativeCaptureHarness(document: SandboxRuntimeCapabilityDocument, harness: string | undefined): void;