@tangle-network/agent-provider-tangle 1.9.2 → 2.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.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @tangle-network/agent-provider-tangle
2
2
 
3
3
  Wraps `@tangle-network/sandbox` as an `AgentEnvironmentProvider`.
4
- The peer range is `>=0.39.0 <1.0.0`, and this package is developed and tested against 0.39.0.
4
+ The Sandbox peer range is `>=0.58.4 <1.0.0`.
5
5
  The floor includes runtime MCP attachment transport and preservation across per-turn model credential overrides.
6
6
 
7
7
  Runtime MCP bindings travel through `CreateAgentEnvironmentInput.runtimeAttachments` to Sandbox's `backend.runtimeAttachments`.
@@ -469,6 +469,24 @@ Both functions return private binary files and provenance for the workspace, nat
469
469
  The caller must store those bytes in private durable custody before deleting the box.
470
470
  Credential exclusions remain listed with path, type, owner IDs, timestamps, mode, size, and reason.
471
471
  Each process stream has exact frame order and a terminal receipt.
472
+ The attempt inventory binds each Sidecar execution and retry to provider sessions, observed native sessions, and recorded processes.
473
+ Each session has one `raw-manifest.json` in its private archive.
474
+ Each execution binds to its original HOME through `evidenceSources`.
475
+ Native files and process streams use that source ID in their archive paths.
476
+ Rotations keep earlier HOMEs until durable capture permits session deletion.
477
+ Every readable process spool keeps its exact original bytes in `processSources`.
478
+ It preserves all response metadata, including unknown fields, attempts, event buffers, terminal results, exclusions, and skipped paths.
479
+ Known `contentBase64` fields become JSON pointers in `contentRefs`.
480
+ Each pointer names the archive file whose verified bytes reconstruct that field.
481
+ Binary bytes are stored once.
482
+ An unavailable response also keeps its original metadata.
483
+ Sidecar execution IDs join `sessions[].executionIds`; the outer execution ID names the Runtime node.
484
+ Partial capture retains the readable native files, process frames, and events in the same archive.
485
+ Its missing reasons prevent a complete receipt and keep the source available for recovery.
486
+ An unknown attempt outcome or native session identity remains explicit.
487
+ Reconnecting uses the execution ID from the validated durable control reference.
488
+ Earlier executions without retained caller attribution stay in the raw manifest with explicit gaps.
489
+ The caller's attempt projection includes only its known execution IDs.
472
490
  The capture records the running sidecar image digest and the served Sidecar bundle revision.
473
491
  The image digest can be compared with the pre-create proof only when that proof identifies the actual placement image.
474
492
  An incomplete inventory, missing stream, unrelated backend, or mismatched digest does not produce complete evidence.
@@ -23,5 +23,5 @@ type ExactExecutionEventStream = (options: {
23
23
  * environment observation reads it, because Sandbox reports usage per
24
24
  * execution result and never for the environment.
25
25
  */
26
- export declare function sandboxSessionAsAgentSession(session: SandboxSessionLike, controlRef: AgentRunControlRef | undefined, provider: string, environmentId: string, dispatch: ((input: AgentTurnInput) => Promise<AgentSessionRef>) | undefined, exactExecutionEvents: ExactExecutionEventStream | undefined, retainedControl: boolean, interactionResponses: boolean, usageLog?: ExecutionUsageLog, nativeContinuation?: boolean): AgentSession;
26
+ export declare function sandboxSessionAsAgentSession(session: SandboxSessionLike, controlRef: AgentRunControlRef | undefined, provider: string, environmentId: string, dispatch: ((input: AgentTurnInput) => Promise<AgentSessionRef>) | undefined, exactExecutionEvents: ExactExecutionEventStream | undefined, retainedControl: boolean, interactionResponses: boolean, usageLog?: ExecutionUsageLog, nativeContinuation?: boolean, onExecution?: (executionId: string) => void): AgentSession;
27
27
  export {};
@@ -24,14 +24,16 @@ import { hasReplayPayload, interruptExecutionAfterAbort, sessionPromptRequestDig
24
24
  * environment observation reads it, because Sandbox reports usage per
25
25
  * execution result and never for the environment.
26
26
  */
27
- export function sandboxSessionAsAgentSession(session, controlRef, provider, environmentId, dispatch, exactExecutionEvents, retainedControl, interactionResponses, usageLog, nativeContinuation = false) {
27
+ export function sandboxSessionAsAgentSession(session, controlRef, provider, environmentId, dispatch, exactExecutionEvents, retainedControl, interactionResponses, usageLog, nativeContinuation = false, onExecution) {
28
28
  const measured = (executionId, result) => {
29
29
  usageLog?.record(executionId, result.usage);
30
30
  return result;
31
31
  };
32
- let activeControlRef = controlRef
33
- ? resolveRetainedSessionControlRef(controlRef, session.id, provider, environmentId)
34
- : undefined;
32
+ let activeControlRef = controlRef === undefined
33
+ ? undefined
34
+ : resolveRetainedSessionControlRef(controlRef, session.id, provider, environmentId);
35
+ if (activeControlRef !== undefined)
36
+ onExecution?.(activeControlRef.executionId);
35
37
  let promptInFlight = false;
36
38
  const respondToInteraction = interactionResponses && typeof session.respondToInteraction === "function"
37
39
  ? tangleInteractionResponder({
@@ -356,6 +358,7 @@ export function sandboxSessionAsAgentSession(session, controlRef, provider, envi
356
358
  // The admission receipt is the durability boundary. Store it before
357
359
  // waiting for the result so an aborted caller can reconnect later.
358
360
  activeControlRef = nextControlRef;
361
+ onExecution?.(nextControlRef.executionId);
359
362
  const result = await awaitWithSignal(session.result({
360
363
  executionId: nextControlRef.executionId,
361
364
  ...(input.signal ? { signal: input.signal } : {}),
@@ -429,12 +432,15 @@ export function sandboxSessionAsAgentSession(session, controlRef, provider, envi
429
432
  executionId,
430
433
  controlRef: targetControlRef,
431
434
  };
435
+ const prompt = promptFromTurnInput(input);
436
+ const promptOptions = promptOptionsFromTurnInput(promptInput, {
437
+ provider,
438
+ environmentId,
439
+ sessionId: session.id,
440
+ });
441
+ onExecution?.(executionId);
432
442
  try {
433
- const result = await awaitWithSignal(session.prompt(promptFromTurnInput(input), promptOptionsFromTurnInput(promptInput, {
434
- provider,
435
- environmentId,
436
- sessionId: session.id,
437
- })), input.signal);
443
+ const result = await awaitWithSignal(session.prompt(prompt, promptOptions), input.signal);
438
444
  input.signal?.throwIfAborted();
439
445
  const resultRecord = validatedSandboxPromptResult(result);
440
446
  if (resultRecord.executionId !== executionId) {
@@ -2,7 +2,6 @@ import { AgentTurnInputSchema, deepFreeze } from "@tangle-network/agent-interfac
2
2
  import { AgentEnvironmentCapabilitiesSchema } from "@tangle-network/agent-interface/environment-provider";
3
3
  import { environmentEventFromSandboxEvent } from "./tangle-events.js";
4
4
  import { executionIdFromTurnInput, promptFromTurnInput, promptOptionsFromTurnInput, } from "./tangle-prompt.js";
5
- import { resolveRetainedSessionControlRef } from "./tangle-session-control.js";
6
5
  import { creationFromSandboxCreateReceipt, placementInfoFromLoopPlacement, statusFromUnknown, } from "./tangle-environment-values.js";
7
6
  import { execResultFromSandboxExecResult } from "./tangle-result-values.js";
8
7
  import { capabilitiesForSandbox, frozenCapabilityDocument, sandboxCapabilitySupport, } from "./tangle-capabilities.js";
@@ -175,7 +174,6 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
175
174
  ? {
176
175
  session(id, options) {
177
176
  boundedIdentifier(id, "Tangle session id");
178
- noteTangleSession(environment, id);
179
177
  assertOptionKeys(options, ["controlRef", "signal"], "Tangle session");
180
178
  options?.signal?.throwIfAborted();
181
179
  const session = box.session?.(id, options?.signal ? { signal: options.signal } : undefined);
@@ -186,7 +184,7 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
186
184
  if (session.id !== id) {
187
185
  throw new Error("sandbox session(id) returned an unrelated session");
188
186
  }
189
- const agentSession = sandboxSessionAsAgentSession(session, resolveRetainedSessionControlRef(options?.controlRef, id, providerName, environmentId), providerName, environmentId, dispatch, exactExecutionEvents, retainedControl, interactionResponses, usageLog, capabilities.nativeContinuation !== undefined);
187
+ const agentSession = sandboxSessionAsAgentSession(session, options?.controlRef, providerName, environmentId, dispatch, exactExecutionEvents, retainedControl, interactionResponses, usageLog, capabilities.nativeContinuation !== undefined, (executionId) => noteTangleSession(environment, id, executionId));
190
188
  // sessions.continue was granted from the probe session and the
191
189
  // deployment document together; this backstop holds every
192
190
  // concrete session to that grant, so a client whose sessions
@@ -1,9 +1,10 @@
1
1
  import type { AgentProfile, HarnessType } from "@tangle-network/agent-interface";
2
2
  import type { AgentEnvironment } from "@tangle-network/agent-interface/environment-provider";
3
- import type { NativeCaptureProofLike, SandboxClientLike, SandboxInstanceLike } from "./tangle-types.js";
3
+ import type { NativeCaptureProofLike, SandboxClientLike, SandboxInstanceLike, TangleEvidenceAttemptLike, TangleEvidenceSourceLike } from "./tangle-types.js";
4
4
  export interface TangleEvidenceCapabilities {
5
5
  readonly workspaceCaptureV1: true;
6
6
  readonly nativeSessionCaptureV1: boolean;
7
+ readonly nativeSessionCaptureVersion: 2;
7
8
  readonly nativeSessionCaptureHarnesses: readonly HarnessType[];
8
9
  readonly sidecarImageDigest: string;
9
10
  }
@@ -69,6 +70,7 @@ export interface TangleEnvironmentEvidence {
69
70
  reportedDirectories: number;
70
71
  complete: true;
71
72
  };
73
+ attempts: TangleEvidenceAttemptLike[];
72
74
  sessions: Array<{
73
75
  id: string;
74
76
  executionId: string;
@@ -83,11 +85,13 @@ export interface TangleEnvironmentEvidence {
83
85
  messageScope: "session";
84
86
  nativeSessionId: string | null;
85
87
  nativeReason: string | null;
88
+ evidenceSources: TangleEvidenceSourceLike[];
86
89
  nativeStore: {
87
90
  scope: "session";
88
91
  roots: Array<{
89
92
  scope: "session-home" | "workspace-session";
90
93
  path: string;
94
+ sourceId?: string;
91
95
  }>;
92
96
  inventory: {
93
97
  scannedFiles: number;
@@ -99,10 +103,11 @@ export interface TangleEnvironmentEvidence {
99
103
  scannedSymlinks: number;
100
104
  reportedSymlinks: number;
101
105
  excludedSymlinks: number;
102
- skippedEntries: 0;
106
+ skippedEntries: number;
103
107
  } | null;
104
108
  complete: boolean;
105
109
  entries: Array<{
110
+ sourceId?: string;
106
111
  rootScope: "session-home" | "workspace-session";
107
112
  path: string;
108
113
  kind: "file" | "directory" | "symlink";
@@ -116,6 +121,7 @@ export interface TangleEnvironmentEvidence {
116
121
  linkTarget: string | null;
117
122
  }>;
118
123
  excludedPaths: Array<{
124
+ sourceId?: string;
119
125
  rootScope: "session-home" | "workspace-session";
120
126
  path: string;
121
127
  kind: "file" | "directory" | "symlink";
@@ -137,8 +143,17 @@ export interface TangleEnvironmentEvidence {
137
143
  stdoutBytes: number;
138
144
  stderrBytes: number;
139
145
  protocolBytes: number;
146
+ sources: Array<{
147
+ sourceId: string;
148
+ path: string;
149
+ sizeBytes: number;
150
+ sha256: string;
151
+ }>;
140
152
  terminals: Array<{
141
153
  processId: string;
154
+ executionId?: string;
155
+ ordinal?: number;
156
+ providerSessionId?: string;
142
157
  sequence: number;
143
158
  at: string;
144
159
  result: {
@@ -146,12 +161,13 @@ export interface TangleEnvironmentEvidence {
146
161
  signal: string | null;
147
162
  timedOut: boolean;
148
163
  timeoutReason: string | null;
149
- captureError: null;
164
+ captureError: string | null;
150
165
  spawnError?: string;
151
166
  };
152
167
  }>;
153
168
  };
154
169
  nativeEvents: {
170
+ scope: "execution";
155
171
  complete: boolean;
156
172
  count: number;
157
173
  };
@@ -12,12 +12,14 @@ export async function readTangleEvidenceCapabilities(client) {
12
12
  throw new Error("Tangle deployment has no pre-create evidence capability query");
13
13
  const document = await client.evidenceCapabilities();
14
14
  if (document?.workspaceCaptureV1 !== true || typeof document.nativeSessionCaptureV1 !== "boolean" ||
15
+ document.nativeSessionCaptureVersion !== 2 ||
15
16
  !/^sha256:[0-9a-f]{64}$/.test(document.sidecarImageDigest ?? "")) {
16
17
  throw new Error("Tangle deployment has not proven complete workspace and native session capture for next-create placement");
17
18
  }
18
19
  const verified = Object.freeze({
19
20
  workspaceCaptureV1: true,
20
21
  nativeSessionCaptureV1: document.nativeSessionCaptureV1,
22
+ nativeSessionCaptureVersion: 2,
21
23
  nativeSessionCaptureHarnesses: nativeCaptureHarnesses(document.nativeSessionCaptureHarnesses),
22
24
  sidecarImageDigest: document.sidecarImageDigest,
23
25
  });
@@ -183,6 +185,7 @@ export async function captureTangleSandboxEvidence(box, options) {
183
185
  }
184
186
  const sessionIds = new Set(options.sandboxSessionIds);
185
187
  const sessions = [];
188
+ const attempts = [];
186
189
  const missing = [];
187
190
  if (sessionIds.size === 0)
188
191
  missing.push("No exact Sandbox session id was attributed to this execution");
@@ -255,23 +258,29 @@ export async function captureTangleSandboxEvidence(box, options) {
255
258
  const processStreams = {
256
259
  complete: false, streamCount: 0, processCount: 0, terminalCount: 0,
257
260
  stdinBytes: 0, stdoutBytes: 0, stderrBytes: 0, protocolBytes: 0, terminals: [],
261
+ sources: [],
258
262
  };
259
263
  const nativeEvents = {
260
- complete: false, count: 0,
264
+ scope: "execution", complete: false, count: 0,
261
265
  };
262
266
  let nativeSessionId = null;
263
267
  let sidecarImageDigest = null;
264
268
  let sidecarBundleRevision = null;
265
269
  let nativeReason = "raw-session-capture-capability-absent";
270
+ let evidenceSources = [];
266
271
  if (native !== undefined) {
272
+ let manifestSource = native;
273
+ const contentRefs = [];
267
274
  if (native.sessionId !== id || native.backendType !== options.harness) {
268
275
  throw new Error("Tangle raw evidence returned an unrelated session or profile backend");
269
276
  }
270
- if (native.nativeSessionId !== undefined && !safeIdentifier(native.nativeSessionId)) {
277
+ if (native.nativeSessionId != null && !safeIdentifier(native.nativeSessionId)) {
271
278
  throw new Error("Tangle raw evidence native session id is invalid");
272
279
  }
273
280
  nativeSessionId = native.nativeSessionId ?? null;
274
- if (native.status === "captured") {
281
+ if (native.status === "captured" || native.status === "partial") {
282
+ const declaredPartial = native.status === "partial";
283
+ let partial = declaredPartial;
275
284
  if (captureProof && (native.proofStatus !== "verified" ||
276
285
  native.containerId !== captureProof.containerId ||
277
286
  native.sidecarImageDigest !== captureProof.imageId ||
@@ -289,37 +298,105 @@ export async function captureTangleSandboxEvidence(box, options) {
289
298
  }
290
299
  sidecarImageDigest = native.sidecarImageDigest;
291
300
  sidecarBundleRevision = native.sidecarBundleRevision;
292
- if (native.completeness?.nativeStore !== true || native.completeness.processIo !== true ||
293
- native.completeness.events !== true || !Array.isArray(native.files) ||
301
+ if (typeof native.completeness?.nativeStore !== "boolean" || typeof native.completeness.processIo !== "boolean" ||
302
+ typeof native.completeness.events !== "boolean" || !Array.isArray(native.files) ||
294
303
  !Array.isArray(native.processIo) || !Array.isArray(native.events) ||
304
+ !Array.isArray(native.processSources) || !Array.isArray(native.evidenceSources) ||
295
305
  !Array.isArray(native.excluded) || !Array.isArray(native.nativeRoots) || !native.inventory ||
296
- !Array.isArray(native.processTerminals) || native.coverageComplete !== true) {
306
+ !Array.isArray(native.processTerminals) || typeof native.coverageComplete !== "boolean" ||
307
+ !Array.isArray(native.missingReasons) || native.missingReasons.some((reason) => !safeReason(reason))) {
308
+ throw new Error("Tangle raw session capture is malformed");
309
+ }
310
+ if ((!declaredPartial && (native.completeness.nativeStore !== true || native.completeness.processIo !== true ||
311
+ native.completeness.events !== true || native.coverageComplete !== true || native.missingReasons.length > 0)) ||
312
+ (declaredPartial && native.coverageComplete !== false)) {
297
313
  throw new Error("Tangle raw session capture is incomplete");
298
314
  }
315
+ if (!Array.isArray(native.attempts) || native.attempts.length > MAX_ENTRIES) {
316
+ throw new Error("Tangle raw session attempt inventory is missing or invalid");
317
+ }
318
+ const unattributedExecutions = [...new Set(native.attempts.filter(isEvidenceAttempt)
319
+ .map((attempt) => attempt.executionId).filter((executionId) => !executionIds.includes(executionId)))];
320
+ if (unattributedExecutions.length) {
321
+ partial = true;
322
+ for (const executionId of unattributedExecutions) {
323
+ missing.push(`Sandbox session ${id} has an execution without retained caller attribution: ${executionId}`);
324
+ }
325
+ }
326
+ const sessionAttempts = readNativeAttempts(native.attempts, executionIds, partial);
327
+ const sourceBindings = new Map();
328
+ const sourceHomes = new Map();
329
+ for (const source of native.evidenceSources) {
330
+ if (!source || !safeIdentifier(source.executionId) || !safeIdentifier(source.sourceId) ||
331
+ source.backendType !== options.harness || !canonicalNativeRoot(source.runtimeHome) ||
332
+ !Array.isArray(source.credentialPaths) || sourceBindings.has(source.executionId) ||
333
+ (sourceHomes.has(source.sourceId) && sourceHomes.get(source.sourceId) !== source.runtimeHome)) {
334
+ throw new Error("Tangle raw session evidence source identity is invalid");
335
+ }
336
+ for (const path of source.credentialPaths)
337
+ canonicalEntryPath(path);
338
+ sourceBindings.set(source.executionId, source);
339
+ sourceHomes.set(source.sourceId, source.runtimeHome);
340
+ }
341
+ const sourceCoverage = executionIds.every((executionId) => sourceBindings.has(executionId)) &&
342
+ native.evidenceSources.every((source) => executionIds.includes(source.executionId));
343
+ if (!sourceCoverage) {
344
+ if (!partial)
345
+ throw new Error("Tangle raw session sources do not cover the exact executions");
346
+ missing.push(`Sandbox session ${id} evidence sources do not cover the exact executions`);
347
+ }
348
+ evidenceSources = native.evidenceSources;
349
+ let processAttributionComplete = sourceCoverage;
350
+ const nativeEventCoverage = nativeEventsMatch(native.events, id, executionIds, partial);
351
+ attempts.push(...sessionAttempts.filter((attempt) => executionIds.includes(attempt.executionId)));
352
+ if (partial)
353
+ missing.push(`Sandbox session ${id} declared partial raw capture`);
354
+ for (const reason of native.missingReasons)
355
+ missing.push(`Sandbox session ${id}: ${reason}`);
356
+ for (const attempt of sessionAttempts) {
357
+ for (const reason of attempt.missingReasons) {
358
+ missing.push(`Sandbox session ${id} attempt ${attempt.executionId}/${attempt.ordinal}: ${reason}`);
359
+ }
360
+ }
361
+ if (!sessionAttempts.length)
362
+ missing.push(`Sandbox session ${id} has no attempt inventory`);
363
+ const nativeIds = new Set(sessionAttempts.flatMap((attempt) => attempt.nativeSessionIds));
364
+ if (nativeSessionId !== null && !nativeIds.has(nativeSessionId)) {
365
+ throw new Error("Tangle raw session identity differs from its attempt inventory");
366
+ }
299
367
  if (native.files.length + native.processIo.length + native.processTerminals.length +
300
368
  native.events.length > MAX_ENTRIES) {
301
369
  throw new Error("Tangle raw session capture exceeds entry limit");
302
370
  }
303
371
  const roots = new Set();
304
372
  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)) {
373
+ if (!["session-home", "workspace-session"].includes(root.rootScope) || roots.has(nativeRootKey(root)) ||
374
+ !canonicalNativeRoot(root.path) ||
375
+ (root.sourceId !== undefined && (!safeIdentifier(root.sourceId) || !sourceHomes.has(root.sourceId) ||
376
+ (root.rootScope === "session-home" && sourceHomes.get(root.sourceId) !== root.path)))) {
307
377
  throw new Error("Tangle raw session native root is invalid");
308
378
  }
309
- roots.add(root.rootScope);
310
- nativeStore.roots.push({ scope: root.rootScope, path: root.path });
379
+ roots.add(nativeRootKey(root));
380
+ nativeStore.roots.push({ scope: root.rootScope, path: root.path,
381
+ ...(root.sourceId === undefined ? {} : { sourceId: root.sourceId }) });
311
382
  }
312
- if (!roots.size)
383
+ if (!roots.size && (!partial || native.completeness.nativeStore))
313
384
  throw new Error("Tangle raw session has no native root");
385
+ const nativeRootCoverage = [...sourceHomes.keys()].every((sourceId) => roots.has(sourceId + "/session-home"));
386
+ if (!nativeRootCoverage) {
387
+ if (!partial)
388
+ throw new Error("Tangle raw session has an unretained native source root");
389
+ missing.push(`Sandbox session ${id} has an unretained native source root`);
390
+ }
314
391
  const nativePaths = new Set();
315
392
  const included = { file: 0, directory: 0, symlink: 0 };
316
393
  const excluded = { file: 0, directory: 0, symlink: 0 };
317
- for (const entry of native.files) {
394
+ for (const [index, entry] of native.files.entries()) {
318
395
  options.signal?.throwIfAborted();
319
396
  const path = canonicalEntryPath(entry.path);
320
- if (!roots.has(entry.rootScope))
397
+ if (!roots.has(nativeRootKey(entry)))
321
398
  throw new Error("Tangle raw session entry has no native root");
322
- const identity = entry.rootScope + "/" + path;
399
+ const identity = nativeRootKey(entry) + "/" + path;
323
400
  if (nativePaths.has(identity))
324
401
  throw new Error("Tangle raw session repeats a native path");
325
402
  nativePaths.add(identity);
@@ -329,7 +406,10 @@ export async function captureTangleSandboxEvidence(box, options) {
329
406
  const content = exactNativeBytes(entry.contentBase64, entry.sizeBytes, entry.sha256, options.maxBytes - capturedBytes);
330
407
  if (capturedBytes + content.byteLength > options.maxBytes)
331
408
  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 });
409
+ const contentPath = "__retention__/sessions/" + id + "/native/" +
410
+ (entry.sourceId === undefined ? "" : entry.sourceId + "/") + entry.rootScope + "/" + path;
411
+ files.push({ path: contentPath, bytes: content, mode: entry.mode & 0o777 });
412
+ contentRefs.push({ jsonPointer: `/files/${index}/contentBase64`, path: contentPath });
333
413
  capturedBytes += content.byteLength;
334
414
  }
335
415
  else if (entry.kind === "directory" || entry.kind === "symlink") {
@@ -343,6 +423,7 @@ export async function captureTangleSandboxEvidence(box, options) {
343
423
  }
344
424
  included[entry.kind] += 1;
345
425
  nativeStore.entries.push({
426
+ ...(entry.sourceId === undefined ? {} : { sourceId: entry.sourceId }),
346
427
  rootScope: entry.rootScope, path, kind: entry.kind, mode: entry.mode,
347
428
  uid: entry.uid, gid: entry.gid, mtimeMs: entry.mtimeMs, ctimeMs: entry.ctimeMs,
348
429
  sizeBytes: entry.sizeBytes, sha256: entry.sha256 ?? null, linkTarget: entry.linkTarget ?? null,
@@ -350,8 +431,8 @@ export async function captureTangleSandboxEvidence(box, options) {
350
431
  }
351
432
  for (const exclusion of native.excluded) {
352
433
  const path = canonicalEntryPath(exclusion.path);
353
- const identity = exclusion.rootScope + "/" + path;
354
- if (!roots.has(exclusion.rootScope) || nativePaths.has(identity) ||
434
+ const identity = nativeRootKey(exclusion) + "/" + path;
435
+ if (!roots.has(nativeRootKey(exclusion)) || nativePaths.has(identity) ||
355
436
  exclusion.reason !== "credential" || !["file", "directory", "symlink"].includes(exclusion.kind) ||
356
437
  !nativeStatMetadata(exclusion)) {
357
438
  throw new Error("Tangle raw session exclusion is invalid");
@@ -359,6 +440,7 @@ export async function captureTangleSandboxEvidence(box, options) {
359
440
  nativePaths.add(identity);
360
441
  excluded[exclusion.kind] += 1;
361
442
  nativeStore.excludedPaths.push({
443
+ ...(exclusion.sourceId === undefined ? {} : { sourceId: exclusion.sourceId }),
362
444
  rootScope: exclusion.rootScope, path, kind: exclusion.kind, mode: exclusion.mode,
363
445
  uid: exclusion.uid, gid: exclusion.gid, mtimeMs: exclusion.mtimeMs, ctimeMs: exclusion.ctimeMs,
364
446
  sizeBytes: exclusion.sizeBytes, reason: exclusion.reason,
@@ -371,16 +453,20 @@ export async function captureTangleSandboxEvidence(box, options) {
371
453
  inventory.reportedSymlinks, inventory.scannedSymlinks, inventory.excludedSymlinks,
372
454
  ];
373
455
  if (counts.some((value) => !Number.isSafeInteger(value) || value < 0) ||
374
- inventory.skippedEntries !== 0 ||
456
+ !Number.isSafeInteger(inventory.skippedEntries) || inventory.skippedEntries < 0 ||
457
+ (!partial && inventory.skippedEntries !== 0) ||
375
458
  inventory.reportedFiles !== included.file ||
376
459
  inventory.reportedDirectories !== included.directory ||
377
460
  inventory.reportedSymlinks !== included.symlink ||
378
461
  inventory.excludedFiles !== excluded.file ||
379
462
  inventory.excludedDirectories !== excluded.directory ||
380
463
  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) {
464
+ inventory.scannedFiles < inventory.reportedFiles + inventory.excludedFiles ||
465
+ inventory.scannedDirectories < inventory.reportedDirectories + inventory.excludedDirectories ||
466
+ inventory.scannedSymlinks < inventory.reportedSymlinks + inventory.excludedSymlinks ||
467
+ (!partial && (inventory.scannedFiles !== inventory.reportedFiles + inventory.excludedFiles ||
468
+ inventory.scannedDirectories !== inventory.reportedDirectories + inventory.excludedDirectories ||
469
+ inventory.scannedSymlinks !== inventory.reportedSymlinks + inventory.excludedSymlinks))) {
384
470
  throw new Error("Tangle raw session inventory does not reconcile");
385
471
  }
386
472
  nativeStore.inventory = {
@@ -393,33 +479,54 @@ export async function captureTangleSandboxEvidence(box, options) {
393
479
  scannedSymlinks: inventory.scannedSymlinks,
394
480
  reportedSymlinks: inventory.reportedSymlinks,
395
481
  excludedSymlinks: inventory.excludedSymlinks,
396
- skippedEntries: 0,
482
+ skippedEntries: inventory.skippedEntries,
397
483
  };
484
+ if (native.skipped !== undefined) {
485
+ if (!Array.isArray(native.skipped) || native.skipped.length !== inventory.skippedEntries ||
486
+ native.skipped.some((entry) => !roots.has(nativeRootKey(entry)) || !safeReason(entry.reason))) {
487
+ throw new Error("Tangle raw session skipped inventory does not reconcile");
488
+ }
489
+ for (const entry of native.skipped) {
490
+ if (entry.path !== ".")
491
+ canonicalEntryPath(entry.path);
492
+ }
493
+ }
398
494
  const ioSequences = new Map();
399
495
  const frameMetadata = [];
400
- for (const frame of native.processIo) {
496
+ for (const [index, frame] of native.processIo.entries()) {
401
497
  options.signal?.throwIfAborted();
402
- if (!safeIdentifier(frame.processId) || !Number.isSafeInteger(frame.sequence) ||
498
+ if (!safeIdentifier(frame.processId) || (frame.sourceId !== undefined && !safeIdentifier(frame.sourceId)) ||
499
+ !Number.isSafeInteger(frame.sequence) ||
403
500
  frame.sequence < 0 || !Number.isFinite(Date.parse(frame.at)) ||
404
501
  !["stdin", "stdout", "stderr", "protocol"].includes(frame.stream)) {
405
502
  throw new Error("Tangle raw session process stream metadata is invalid");
406
503
  }
407
- const sequences = ioSequences.get(frame.processId) ?? new Set();
504
+ const processKey = sourceProcessKey(frame);
505
+ const sequences = ioSequences.get(processKey) ?? new Set();
408
506
  if (sequences.has(frame.sequence))
409
507
  throw new Error("Tangle raw session repeats a process frame");
410
508
  sequences.add(frame.sequence);
411
- ioSequences.set(frame.processId, sequences);
509
+ ioSequences.set(processKey, sequences);
510
+ if (!processAttemptMatches(frame, sessionAttempts, partial)) {
511
+ processAttributionComplete = false;
512
+ missing.push(`Sandbox session ${id} process ${frame.processId} has no exact attempt attribution`);
513
+ }
514
+ if (frame.sourceId === undefined || sourceBindings.get(frame.executionId ?? "")?.sourceId !== frame.sourceId) {
515
+ if (!partial)
516
+ throw new Error("Tangle raw session process has conflicting source attribution");
517
+ processAttributionComplete = false;
518
+ missing.push(`Sandbox session ${id} process ${frame.processId} has no exact source attribution`);
519
+ }
412
520
  const content = exactNativeBytes(frame.contentBase64, frame.sizeBytes, frame.sha256, options.maxBytes - capturedBytes);
413
521
  if (capturedBytes + content.byteLength > options.maxBytes)
414
522
  throw new Error("Tangle evidence exceeds byte limit");
415
523
  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
- });
524
+ const contentPath = "__retention__/sessions/" + id + "/io/" +
525
+ (frame.sourceId === undefined ? "" : frame.sourceId + "/") + frame.processId + "/" + label +
526
+ "-" + frame.stream + ".bin";
527
+ files.push({ path: contentPath, bytes: content, mode: 0o600 });
528
+ contentRefs.push({ jsonPointer: `/processIo/${index}/contentBase64`, path: contentPath });
529
+ frameMetadata.push(withoutNativeContent(frame));
423
530
  capturedBytes += content.byteLength;
424
531
  const counter = (frame.stream + "Bytes");
425
532
  processStreams[counter] += content.byteLength;
@@ -427,10 +534,12 @@ export async function captureTangleSandboxEvidence(box, options) {
427
534
  }
428
535
  const terminals = new Set();
429
536
  for (const terminal of native.processTerminals) {
430
- if (!safeIdentifier(terminal.processId) || terminals.has(terminal.processId) ||
537
+ const processKey = sourceProcessKey(terminal);
538
+ if (!safeIdentifier(terminal.processId) || (terminal.sourceId !== undefined && !safeIdentifier(terminal.sourceId)) ||
539
+ terminals.has(processKey) ||
431
540
  !Number.isSafeInteger(terminal.sequence) || terminal.sequence < 0 ||
432
541
  !Number.isFinite(Date.parse(terminal.at)) ||
433
- terminal.result?.captureError !== null ||
542
+ !(terminal.result?.captureError === null || (partial && typeof terminal.result?.captureError === "string")) ||
434
543
  !(terminal.result.code === null || Number.isSafeInteger(terminal.result.code)) ||
435
544
  !(terminal.result.signal === null || typeof terminal.result.signal === "string") ||
436
545
  typeof terminal.result.timedOut !== "boolean" ||
@@ -438,47 +547,98 @@ export async function captureTangleSandboxEvidence(box, options) {
438
547
  (terminal.result.spawnError !== undefined && typeof terminal.result.spawnError !== "string")) {
439
548
  throw new Error("Tangle raw session process terminal metadata is invalid");
440
549
  }
441
- const sequences = ioSequences.get(terminal.processId) ?? new Set();
442
- if (terminal.sequence !== sequences.size ||
443
- [...sequences].some((sequence) => sequence < 0 || sequence >= terminal.sequence)) {
550
+ const sequences = ioSequences.get(processKey) ?? new Set();
551
+ if (!processAttemptMatches(terminal, sessionAttempts, partial)) {
552
+ processAttributionComplete = false;
553
+ missing.push(`Sandbox session ${id} terminal ${terminal.processId} has no exact attempt attribution`);
554
+ }
555
+ if (terminal.sourceId === undefined || sourceBindings.get(terminal.executionId ?? "")?.sourceId !== terminal.sourceId) {
556
+ if (!partial)
557
+ throw new Error("Tangle raw session terminal has conflicting source attribution");
558
+ processAttributionComplete = false;
559
+ missing.push(`Sandbox session ${id} terminal ${terminal.processId} has no exact source attribution`);
560
+ }
561
+ if (!partial && (terminal.sequence !== sequences.size ||
562
+ [...sequences].some((sequence) => sequence < 0 || sequence >= terminal.sequence))) {
444
563
  throw new Error("Tangle raw session process sequence is incomplete");
445
564
  }
446
- terminals.add(terminal.processId);
565
+ terminals.add(processKey);
447
566
  processStreams.terminals.push(terminal);
448
567
  }
449
- if ([...ioSequences.keys()].some((processId) => !terminals.has(processId))) {
568
+ if (!partial && [...ioSequences.keys()].some((processId) => !terminals.has(processId))) {
450
569
  throw new Error("Tangle raw session has a process without a terminal receipt");
451
570
  }
452
- processStreams.processCount = terminals.size;
571
+ const observedProcesses = [...native.processIo, ...native.processTerminals];
572
+ const observedAttemptProcesses = new Set(observedProcesses.map(attemptProcessKey));
573
+ for (const attempt of sessionAttempts) {
574
+ for (const processId of attempt.processIds) {
575
+ const key = attemptProcessKey({ ...attempt, processId,
576
+ sourceId: sourceBindings.get(attempt.executionId)?.sourceId });
577
+ if (observedAttemptProcesses.has(key))
578
+ continue;
579
+ if (!partial)
580
+ throw new Error("Tangle raw session attempt names an unretained attributed process");
581
+ processAttributionComplete = false;
582
+ missing.push(`Sandbox session ${id} attempt ${attempt.executionId}/${attempt.ordinal} names an unretained attributed process: ${processId}`);
583
+ }
584
+ }
585
+ processStreams.processCount = new Set([...ioSequences.keys(), ...terminals]).size;
453
586
  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;
587
+ const spoolSources = new Set();
588
+ for (const [index, processSource] of native.processSources.entries()) {
589
+ if (!safeIdentifier(processSource.sourceId) || !sourceHomes.has(processSource.sourceId) ||
590
+ spoolSources.has(processSource.sourceId))
591
+ throw new Error("Tangle raw session process source identity is invalid");
592
+ spoolSources.add(processSource.sourceId);
593
+ const source = exactNativeBytes(processSource.contentBase64, processSource.sizeBytes, processSource.sha256, options.maxBytes - capturedBytes);
594
+ const sourcePath = "__retention__/sessions/" + id + "/process-sources/" + processSource.sourceId + ".jsonl";
595
+ files.push({ path: sourcePath, bytes: source, mode: 0o600 });
596
+ capturedBytes += source.byteLength;
597
+ processStreams.sources.push({ sourceId: processSource.sourceId, path: sourcePath, sizeBytes: source.byteLength, sha256: processSource.sha256 });
598
+ contentRefs.push({ jsonPointer: `/processSources/${index}/contentBase64`, path: sourcePath });
599
+ }
600
+ const missingSpoolSources = [...sourceHomes.keys()].filter((sourceId) => !spoolSources.has(sourceId));
601
+ if (!partial && missingSpoolSources.length > 0) {
602
+ throw new Error("Tangle raw session omits an original process source");
603
+ }
604
+ for (const sourceId of missingSpoolSources) {
605
+ missing.push(`Sandbox session ${id} has no original process source: ${sourceId}`);
606
+ }
607
+ manifestSource = {
608
+ ...native,
609
+ files: native.files.map((entry) => entry.kind === "file" ? withoutNativeContent(entry) : entry),
610
+ processIo: frameMetadata,
611
+ processSources: native.processSources.map(withoutNativeContent),
612
+ };
613
+ nativeStore.complete = sourceCoverage && nativeRootCoverage && native.completeness.nativeStore && inventory.skippedEntries === 0 &&
614
+ inventory.scannedFiles === inventory.reportedFiles + inventory.excludedFiles &&
615
+ inventory.scannedDirectories === inventory.reportedDirectories + inventory.excludedDirectories &&
616
+ inventory.scannedSymlinks === inventory.reportedSymlinks + inventory.excludedSymlinks;
617
+ processStreams.complete = missingSpoolSources.length === 0 && processAttributionComplete && native.completeness.processIo && [...ioSequences.keys()].every((processId) => terminals.has(processId)) &&
618
+ native.processTerminals.every((terminal) => {
619
+ const sequences = ioSequences.get(sourceProcessKey(terminal)) ?? new Set();
620
+ return terminal.result.captureError === null && terminal.sequence === sequences.size &&
621
+ [...sequences].every((sequence) => sequence >= 0 && sequence < terminal.sequence);
622
+ });
623
+ nativeEvents.complete = sourceCoverage && unattributedExecutions.length === 0 && native.completeness.events && nativeEventCoverage;
474
624
  nativeEvents.count = native.events.length;
475
- nativeReason = null;
625
+ nativeReason = partial ? (native.missingReasons.join("; ") || "incomplete-execution-attribution") : null;
476
626
  }
477
- else {
478
- if (!safeIdentifier(native.reason))
627
+ else if (native.status === "unavailable") {
628
+ if (!safeReason(native.reason))
479
629
  throw new Error("Tangle raw session unavailability reason is invalid");
480
630
  nativeReason = native.reason;
481
631
  }
632
+ else {
633
+ throw new Error("Tangle raw session capture status is invalid");
634
+ }
635
+ const manifest = Buffer.from(JSON.stringify({
636
+ kind: "tangle-native-session-evidence.v1", source: manifestSource, contentEncoding: "base64", contentRefs,
637
+ }));
638
+ if (capturedBytes + manifest.byteLength > options.maxBytes)
639
+ throw new Error("Tangle evidence exceeds byte limit");
640
+ files.push({ path: "__retention__/sessions/" + id + "/raw-manifest.json", bytes: manifest, mode: 0o600 });
641
+ capturedBytes += manifest.byteLength;
482
642
  }
483
643
  sessions.push({
484
644
  id, executionId: options.executionId, executionIds: [...executionIds], eventCountsByExecutionId,
@@ -486,6 +646,7 @@ export async function captureTangleSandboxEvidence(box, options) {
486
646
  transportEvents: executionIds.every((executionId) => eventCountsByExecutionId[executionId] > 0) ? "complete" : "unavailable",
487
647
  eventCount: events.length, messageCount: messages.length, messageScope: "session",
488
648
  nativeSessionId, nativeReason, nativeStore, processStreams, nativeEvents,
649
+ evidenceSources,
489
650
  });
490
651
  for (const executionId of executionIds) {
491
652
  if (!eventCountsByExecutionId[executionId]) {
@@ -507,6 +668,7 @@ export async function captureTangleSandboxEvidence(box, options) {
507
668
  entries: metadata.sort((a, b) => a.path.localeCompare(b.path)),
508
669
  excludedPaths,
509
670
  workspace: { scannedFiles, scannedDirectories, reportedFiles: usage.fileCount, reportedDirectories: usage.directoryCount, complete: true },
671
+ attempts,
510
672
  sessions,
511
673
  missing,
512
674
  };
@@ -516,8 +678,113 @@ export async function captureTangleSandboxEvidence(box, options) {
516
678
  files.push({ path: "__retention__/provenance.json", bytes: provenanceBytes, mode: 0o600 });
517
679
  return { files: files.sort((a, b) => a.path.localeCompare(b.path)), provenance };
518
680
  }
681
+ /** Keep every source field; store validated binary content once in the archive. */
682
+ function withoutNativeContent(source) {
683
+ const metadata = { ...source };
684
+ delete metadata.contentBase64;
685
+ return metadata;
686
+ }
519
687
  function safeIdentifier(value) {
520
- return /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value);
688
+ return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value);
689
+ }
690
+ function safeReason(value) {
691
+ return typeof value === "string" && value.length > 0 && value.length <= 1024 && !/[\u0000-\u001f\u007f]/.test(value);
692
+ }
693
+ function nativeRootKey(value) {
694
+ return `${value.sourceId ?? ""}/${value.rootScope}`;
695
+ }
696
+ function sourceProcessKey(value) {
697
+ return `${value.sourceId ?? ""}/${value.processId}`;
698
+ }
699
+ function attemptProcessKey(value) {
700
+ return `${sourceProcessKey(value)}/${value.executionId ?? ""}/${value.ordinal ?? ""}/${value.providerSessionId ?? ""}`;
701
+ }
702
+ /** Source roots are metadata; archive entry paths remain relative. */
703
+ function canonicalNativeRoot(value) {
704
+ if (typeof value !== "string" || value.includes("\\") || value.includes("\0"))
705
+ return false;
706
+ if (value === ".")
707
+ return true;
708
+ const parts = (value.startsWith("/") ? value.slice(1) : value).split("/");
709
+ return parts.every((part) => part.length > 0 && part !== "." && part !== "..");
710
+ }
711
+ function readNativeAttempts(value, executionIds, partial) {
712
+ if (!Array.isArray(value) || value.length > MAX_ENTRIES || (!partial && value.length === 0)) {
713
+ throw new Error("Tangle raw session attempt inventory is missing or invalid");
714
+ }
715
+ const ordinals = new Map();
716
+ const attempts = [];
717
+ for (const entry of value) {
718
+ if (!isEvidenceAttempt(entry) || (!partial && !executionIds.includes(entry.executionId))) {
719
+ throw new Error("Tangle raw session attempt has invalid identity or an unrelated execution");
720
+ }
721
+ const seen = ordinals.get(entry.executionId) ?? new Set();
722
+ if (seen.has(entry.ordinal))
723
+ throw new Error("Tangle raw session repeats an attempt ordinal");
724
+ seen.add(entry.ordinal);
725
+ ordinals.set(entry.executionId, seen);
726
+ if (!partial && (!entry.nativeSessionIds.length ||
727
+ entry.outcome === "unknown" || entry.missingReasons.length > 0)) {
728
+ throw new Error("Tangle raw session attempt coverage is incomplete");
729
+ }
730
+ attempts.push({ ...entry, nativeSessionIds: [...entry.nativeSessionIds], processIds: [...entry.processIds], missingReasons: [...entry.missingReasons] });
731
+ }
732
+ if (!partial && executionIds.some((id) => {
733
+ const seen = ordinals.get(id);
734
+ return !seen || Array.from({ length: seen.size }, (_, i) => i + 1).some((ordinal) => !seen.has(ordinal));
735
+ })) {
736
+ throw new Error("Tangle raw session attempt inventory does not cover every execution and retry");
737
+ }
738
+ return attempts;
739
+ }
740
+ function isEvidenceAttempt(value) {
741
+ if (value === null || typeof value !== "object")
742
+ return false;
743
+ const entry = value;
744
+ const identifiers = (candidate) => Array.isArray(candidate) &&
745
+ candidate.every((id) => typeof id === "string" && safeIdentifier(id)) && new Set(candidate).size === candidate.length;
746
+ return typeof entry.executionId === "string" && safeIdentifier(entry.executionId) &&
747
+ Number.isSafeInteger(entry.ordinal) && Number(entry.ordinal) > 0 &&
748
+ typeof entry.providerSessionId === "string" && safeIdentifier(entry.providerSessionId) &&
749
+ identifiers(entry.nativeSessionIds) && identifiers(entry.processIds) &&
750
+ typeof entry.outcome === "string" && ["succeeded", "failed", "cancelled", "unknown"].includes(entry.outcome) &&
751
+ identifiers(entry.missingReasons);
752
+ }
753
+ function processAttemptMatches(value, attempts, partial) {
754
+ const owners = attempts.filter((attempt) => attempt.processIds.includes(value.processId) &&
755
+ attempt.executionId === value.executionId && attempt.ordinal === value.ordinal &&
756
+ attempt.providerSessionId === value.providerSessionId);
757
+ const exact = owners.length === 1;
758
+ if (!exact && !partial)
759
+ throw new Error("Tangle raw session process has missing or conflicting attempt attribution");
760
+ return exact;
761
+ }
762
+ function nativeEventsMatch(events, sessionId, executionIds, partial) {
763
+ const seen = new Set();
764
+ let countsComplete = true;
765
+ for (const event of events) {
766
+ if (event === null || typeof event !== "object")
767
+ throw new Error("Tangle raw session event buffer is malformed");
768
+ const entry = event;
769
+ if (entry.metadata === null || typeof entry.metadata !== "object" || !Array.isArray(entry.frames)) {
770
+ throw new Error("Tangle raw session event buffer is malformed");
771
+ }
772
+ const metadata = entry.metadata;
773
+ if (metadata.sessionId !== sessionId || typeof metadata.executionId !== "string" ||
774
+ !safeIdentifier(metadata.executionId) || (!partial && !executionIds.includes(metadata.executionId)) || seen.has(metadata.executionId)) {
775
+ throw new Error("Tangle raw session event buffer has unrelated or duplicate execution identity");
776
+ }
777
+ if (!Number.isSafeInteger(metadata.eventCount) || Number(metadata.eventCount) < 0 || metadata.eventCount !== entry.frames.length) {
778
+ if (!partial)
779
+ throw new Error("Tangle raw session event buffer count is inconsistent");
780
+ countsComplete = false;
781
+ }
782
+ seen.add(metadata.executionId);
783
+ }
784
+ const complete = countsComplete && executionIds.every((executionId) => seen.has(executionId));
785
+ if (!complete && !partial)
786
+ throw new Error("Tangle raw session event buffers do not cover every execution");
787
+ return complete;
521
788
  }
522
789
  function canonicalEntryPath(value) {
523
790
  if (!value || value.startsWith("/") || value.includes("\\") || value.includes("\0"))
@@ -40,6 +40,9 @@ export async function requireNativeCaptureCapability(client, harness) {
40
40
  throw new Error("Tangle deployment has not proven native session capture for next-create placement");
41
41
  }
42
42
  const document = await client.evidenceCapabilities();
43
+ if (document.nativeSessionCaptureVersion !== 2) {
44
+ throw new Error("Tangle deployment has not proven native session capture protocol 2 for next-create placement");
45
+ }
43
46
  if (harness === undefined) {
44
47
  if (document.nativeSessionCaptureV1 !== true) {
45
48
  throw new Error("Tangle deployment has not proven native session capture for unprofiled next-create placement");
@@ -26,6 +26,7 @@ export interface SandboxClientLike {
26
26
  /** Deployment-scoped evidence guarantees for a new sandbox on this client. */
27
27
  evidenceCapabilities?(): Promise<{
28
28
  nativeSessionCaptureV1?: boolean;
29
+ nativeSessionCaptureVersion?: number;
29
30
  nativeSessionCaptureHarnesses?: readonly HarnessType[];
30
31
  workspaceCaptureV1?: boolean;
31
32
  sidecarImageDigest?: string;
@@ -554,22 +555,42 @@ export interface SandboxInstanceLike {
554
555
  attestationNonce?: string;
555
556
  }): Promise<SandboxTeeAttestationResponseLike>;
556
557
  }
558
+ /** Exact observed attempts within one Sidecar execution. */
559
+ export interface TangleEvidenceAttemptLike {
560
+ executionId: string;
561
+ ordinal: number;
562
+ providerSessionId: string;
563
+ nativeSessionIds: string[];
564
+ processIds: string[];
565
+ outcome: "succeeded" | "failed" | "cancelled" | "unknown";
566
+ missingReasons: string[];
567
+ }
568
+ export interface TangleEvidenceSourceLike {
569
+ executionId: string;
570
+ sourceId: string;
571
+ backendType: string;
572
+ runtimeHome: string;
573
+ credentialPaths: string[];
574
+ }
557
575
  export type TangleRawEvidenceLike = {
558
- status: "captured";
576
+ status: "captured" | "partial";
559
577
  sessionId: string;
560
578
  backendType: string;
561
- nativeSessionId?: string;
579
+ nativeSessionId?: string | null;
562
580
  proofStatus?: "verified" | "unverified";
563
581
  containerId?: string;
564
582
  sidecarImageDigest: string;
565
583
  sidecarBundleRevision: string;
566
584
  sidecarBundleChecksum?: string;
585
+ evidenceSources: TangleEvidenceSourceLike[];
567
586
  nativeRoots: Array<{
568
587
  rootScope: "session-home" | "workspace-session";
569
588
  path: string;
589
+ sourceId?: string;
570
590
  }>;
571
591
  inventory: Record<string, number>;
572
592
  files: Array<{
593
+ sourceId?: string;
573
594
  rootScope: "session-home" | "workspace-session";
574
595
  path: string;
575
596
  kind: "file" | "directory" | "symlink";
@@ -584,7 +605,11 @@ export type TangleRawEvidenceLike = {
584
605
  linkTarget?: string;
585
606
  }>;
586
607
  processIo: Array<{
608
+ sourceId?: string;
587
609
  processId: string;
610
+ executionId?: string;
611
+ ordinal?: number;
612
+ providerSessionId?: string;
588
613
  sequence: number;
589
614
  at: string;
590
615
  stream: "stdin" | "stdout" | "stderr" | "protocol";
@@ -593,8 +618,19 @@ export type TangleRawEvidenceLike = {
593
618
  contentBase64: string;
594
619
  metadata?: unknown;
595
620
  }>;
621
+ /** Exact original spool for every readable source. */
622
+ processSources: Array<{
623
+ sourceId: string;
624
+ contentBase64: string;
625
+ sizeBytes: number;
626
+ sha256: string;
627
+ }>;
596
628
  processTerminals: Array<{
629
+ sourceId?: string;
597
630
  processId: string;
631
+ executionId?: string;
632
+ ordinal?: number;
633
+ providerSessionId?: string;
598
634
  sequence: number;
599
635
  at: string;
600
636
  result: {
@@ -602,12 +638,13 @@ export type TangleRawEvidenceLike = {
602
638
  signal: string | null;
603
639
  timedOut: boolean;
604
640
  timeoutReason: string | null;
605
- captureError: null;
641
+ captureError: string | null;
606
642
  spawnError?: string;
607
643
  };
608
644
  }>;
609
645
  events: unknown[];
610
646
  excluded: Array<{
647
+ sourceId?: string;
611
648
  rootScope: "session-home" | "workspace-session";
612
649
  path: string;
613
650
  kind: "file" | "directory" | "symlink";
@@ -619,12 +656,20 @@ export type TangleRawEvidenceLike = {
619
656
  sizeBytes: number;
620
657
  reason: "credential";
621
658
  }>;
659
+ attempts: TangleEvidenceAttemptLike[];
660
+ skipped?: Array<{
661
+ rootScope: "session-home" | "workspace-session";
662
+ path: string;
663
+ reason: string;
664
+ sourceId?: string;
665
+ }>;
622
666
  completeness: {
623
- nativeStore: true;
624
- processIo: true;
625
- events: true;
667
+ nativeStore: boolean;
668
+ processIo: boolean;
669
+ events: boolean;
626
670
  };
627
- coverageComplete: true;
671
+ coverageComplete: boolean;
672
+ missingReasons: string[];
628
673
  } | {
629
674
  status: "unavailable";
630
675
  sessionId: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-provider-tangle",
3
- "version": "1.9.2",
3
+ "version": "2.0.0",
4
4
  "description": "AgentEnvironmentProvider adapter for Tangle sandboxes",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -106,7 +106,7 @@
106
106
  "@tangle-network/agent-interface": "^2.15.0"
107
107
  },
108
108
  "peerDependencies": {
109
- "@tangle-network/sandbox": ">=0.58.0 <1.0.0"
109
+ "@tangle-network/sandbox": ">=0.58.4 <1.0.0"
110
110
  },
111
111
  "peerDependenciesMeta": {
112
112
  "@tangle-network/sandbox": {
@@ -115,8 +115,8 @@
115
115
  },
116
116
  "devDependencies": {
117
117
  "@tangle-network/agent-provider-testkit": "0.10.0",
118
- "@tangle-network/agent-runtime": "0.282.2",
119
- "@tangle-network/sandbox": "0.58.0",
118
+ "@tangle-network/agent-runtime": "0.286.0",
119
+ "@tangle-network/sandbox": "0.58.4",
120
120
  "@types/node": "26.6.3",
121
121
  "typescript": "7.0.2",
122
122
  "vitest": "5.0.2"