@tangle-network/agent-runtime 0.133.8 → 0.134.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/dist/{activation-CbgOt7bK.js → activation-BaxUkhEf.js} +3 -3
  2. package/dist/{activation-CbgOt7bK.js.map → activation-BaxUkhEf.js.map} +1 -1
  3. package/dist/agent.d.ts +1 -1
  4. package/dist/agent.js +2 -2
  5. package/dist/{analyst-loop-C189F6v8.js → analyst-loop-BKWqQhVI.js} +2 -2
  6. package/dist/{analyst-loop-C189F6v8.js.map → analyst-loop-BKWqQhVI.js.map} +1 -1
  7. package/dist/analyst-loop.js +1 -1
  8. package/dist/{authoring-DI2ZcORJ.js → authoring-BlbRLEOS.js} +2 -2
  9. package/dist/{authoring-DI2ZcORJ.js.map → authoring-BlbRLEOS.js.map} +1 -1
  10. package/dist/candidate-execution/index.js +4 -4
  11. package/dist/{candidate-execution-_u2HIWeX.js → candidate-execution-CJRP9CcZ.js} +4 -4
  12. package/dist/{candidate-execution-_u2HIWeX.js.map → candidate-execution-CJRP9CcZ.js.map} +1 -1
  13. package/dist/{conversation-kPowfA_A.js → conversation-CrWcNPQg.js} +4 -4
  14. package/dist/{conversation-kPowfA_A.js.map → conversation-CrWcNPQg.js.map} +1 -1
  15. package/dist/conversation.d.ts +1 -1
  16. package/dist/conversation.js +1 -1
  17. package/dist/{environment-provider-DTJA4ZiM.js → environment-provider-CwvY-Zeq.js} +2 -2
  18. package/dist/{environment-provider-DTJA4ZiM.js.map → environment-provider-CwvY-Zeq.js.map} +1 -1
  19. package/dist/{environment-provider-B-w9VYcF.d.ts → environment-provider-qDOhdE9M.d.ts} +2 -2
  20. package/dist/environment-provider.d.ts +1 -1
  21. package/dist/environment-provider.js +1 -1
  22. package/dist/{errors-DRoXIc7E.js → errors-CVIDr7GQ.js} +9 -1
  23. package/dist/errors-CVIDr7GQ.js.map +1 -0
  24. package/dist/{graph-CnLcp2Tl.js → graph-CKNenH2a.js} +4 -4
  25. package/dist/{graph-CnLcp2Tl.js.map → graph-CKNenH2a.js.map} +1 -1
  26. package/dist/{improvement-cycle-ekj_ODWY.js → improvement-cycle-CSBantKB.js} +9 -9
  27. package/dist/{improvement-cycle-ekj_ODWY.js.map → improvement-cycle-CSBantKB.js.map} +1 -1
  28. package/dist/{index-DqJa9jGF.d.ts → index-CgBJtAzI.d.ts} +2 -2
  29. package/dist/{index-CP8LBWD1.d.ts → index-Cz4qKBxm.d.ts} +4 -4
  30. package/dist/{index-Cgo-tyB8.d.ts → index-De10l_EU.d.ts} +27 -6
  31. package/dist/index.d.ts +7 -7
  32. package/dist/index.js +14 -14
  33. package/dist/intelligence.d.ts +4 -4
  34. package/dist/intelligence.js +6 -6
  35. package/dist/kernel.d.ts +6 -6
  36. package/dist/kernel.js +10 -10
  37. package/dist/{knowledge-BdJoVN9q.js → knowledge-B2C9t1Z4.js} +7 -7
  38. package/dist/{knowledge-BdJoVN9q.js.map → knowledge-B2C9t1Z4.js.map} +1 -1
  39. package/dist/knowledge.d.ts +1 -1
  40. package/dist/knowledge.js +1 -1
  41. package/dist/{loop-runner-bin-C1uQcY_O.js → loop-runner-bin-C0ymKYU7.js} +5 -5
  42. package/dist/{loop-runner-bin-C1uQcY_O.js.map → loop-runner-bin-C0ymKYU7.js.map} +1 -1
  43. package/dist/{loop-runner-bin-BX_266wJ.d.ts → loop-runner-bin-D-tgbSPx.d.ts} +3 -3
  44. package/dist/loop-runner-bin.d.ts +1 -1
  45. package/dist/loop-runner-bin.js +1 -1
  46. package/dist/{materialization-D2bdTfkK.js → materialization-BP5zspr2.js} +25 -10
  47. package/dist/materialization-BP5zspr2.js.map +1 -0
  48. package/dist/mcp/bin.js +4 -4
  49. package/dist/mcp/index.d.ts +3 -3
  50. package/dist/mcp/index.js +9 -9
  51. package/dist/mcp/memory-bin.js +1 -1
  52. package/dist/{memory-server-CblxrUKT.js → memory-server-Cdpy7Uu8.js} +3 -3
  53. package/dist/{memory-server-CblxrUKT.js.map → memory-server-Cdpy7Uu8.js.map} +1 -1
  54. package/dist/{model-policy-Bv1DU2fw.js → model-policy-UTTc9Z-A.js} +2 -2
  55. package/dist/{model-policy-Bv1DU2fw.js.map → model-policy-UTTc9Z-A.js.map} +1 -1
  56. package/dist/{openai-tools-BTznyT19.js → openai-tools-ClOkPIi0.js} +2 -2
  57. package/dist/{openai-tools-BTznyT19.js.map → openai-tools-ClOkPIi0.js.map} +1 -1
  58. package/dist/{prepare-DUbH3GD5.js → prepare-BXEtLOj9.js} +2 -2
  59. package/dist/{prepare-DUbH3GD5.js.map → prepare-BXEtLOj9.js.map} +1 -1
  60. package/dist/primeintellect/index.d.ts +1 -1
  61. package/dist/profiles.js +1 -1
  62. package/dist/{protected-model-port-DP7MS63a.js → protected-model-port-B7PAmTGi.js} +2 -2
  63. package/dist/{protected-model-port-DP7MS63a.js.map → protected-model-port-B7PAmTGi.js.map} +1 -1
  64. package/dist/{redact-BSD-nvTf.d.ts → redact-6UE6pdNi.d.ts} +3 -3
  65. package/dist/{researcher-BiWSFLi6.js → researcher-DBfKdnAz.js} +3 -3
  66. package/dist/{researcher-BiWSFLi6.js.map → researcher-DBfKdnAz.js.map} +1 -1
  67. package/dist/{runtime-Br49sl8u.js → runtime-Bisfbn3_.js} +29 -14
  68. package/dist/runtime-Bisfbn3_.js.map +1 -0
  69. package/dist/{runtime-D-26vxJt.d.ts → runtime-DlxoqEj2.d.ts} +27 -6
  70. package/dist/{snapshot-DY6VGliG.js → snapshot-BOIprwBk.js} +2 -2
  71. package/dist/{snapshot-DY6VGliG.js.map → snapshot-BOIprwBk.js.map} +1 -1
  72. package/dist/{spawn-journal-BX3-4WDm.js → spawn-journal-B856eA8e.js} +27 -11
  73. package/dist/spawn-journal-B856eA8e.js.map +1 -0
  74. package/dist/{stream-agent-turn-NFWCv1X1.d.ts → stream-agent-turn-CJog3ebs.d.ts} +2 -2
  75. package/dist/{stream-agent-turn-D8YHY0oO.js → stream-agent-turn-CdIcf-bn.js} +4 -4
  76. package/dist/{stream-agent-turn-D8YHY0oO.js.map → stream-agent-turn-CdIcf-bn.js.map} +1 -1
  77. package/dist/{structural-rollout-C4_mifPH.js → structural-rollout-DKEP5i__.js} +6 -6
  78. package/dist/{structural-rollout-C4_mifPH.js.map → structural-rollout-DKEP5i__.js.map} +1 -1
  79. package/dist/{supervise-BTwl4Cdi.js → supervise-DhghNvl6.js} +55 -37
  80. package/dist/supervise-DhghNvl6.js.map +1 -0
  81. package/dist/{supervisor-BA87pb7g.js → supervisor-CMlIOkJP.js} +65 -21
  82. package/dist/supervisor-CMlIOkJP.js.map +1 -0
  83. package/dist/testing.d.ts +2 -2
  84. package/dist/testing.js +12 -12
  85. package/dist/{tool-server-VvSK1K3X.js → tool-server-Dh-NcbHr.js} +2 -2
  86. package/dist/{tool-server-VvSK1K3X.js.map → tool-server-Dh-NcbHr.js.map} +1 -1
  87. package/dist/{types-DJ7k6vHE.d.ts → types-D4BfurNs.d.ts} +9 -2
  88. package/dist/{util-Dr--8wAL.js → util-DD8bRWPL.js} +21 -2
  89. package/dist/util-DD8bRWPL.js.map +1 -0
  90. package/dist/{workspace-archive-WEbaLREb.js → workspace-archive-B5oJu5mZ.js} +2 -2
  91. package/dist/{workspace-archive-WEbaLREb.js.map → workspace-archive-B5oJu5mZ.js.map} +1 -1
  92. package/package.json +1 -1
  93. package/dist/errors-DRoXIc7E.js.map +0 -1
  94. package/dist/materialization-D2bdTfkK.js.map +0 -1
  95. package/dist/runtime-Br49sl8u.js.map +0 -1
  96. package/dist/spawn-journal-BX3-4WDm.js.map +0 -1
  97. package/dist/supervise-BTwl4Cdi.js.map +0 -1
  98. package/dist/supervisor-BA87pb7g.js.map +0 -1
  99. package/dist/util-Dr--8wAL.js.map +0 -1
@@ -1,10 +1,10 @@
1
- import { E as SandboxClient, i as ExecCtx } from "./types-6zHo67jn.js";
2
- import { Q as UsageEvent, U as Spend, d as ExecutorFactory, gn as ExecutorProgress, ln as TraceSource, m as ExecutorRegistry } from "./types-DJ7k6vHE.js";
3
- import { i as AgentEnvironmentProvider, o as AgentEnvironmentProviderRegistry, w as ProviderExecutorOptions } from "./environment-provider-B-w9VYcF.js";
1
+ import { E as SandboxClient, i as ExecCtx, k as Validator } from "./types-6zHo67jn.js";
2
+ import { Q as UsageEvent, U as Spend, d as ExecutorFactory, gn as ExecutorProgress, ln as TraceSource, m as ExecutorRegistry } from "./types-D4BfurNs.js";
3
+ import { i as AgentEnvironmentProvider, o as AgentEnvironmentProviderRegistry, w as ProviderExecutorOptions } from "./environment-provider-qDOhdE9M.js";
4
4
  import { AgentProfile, AgentProfileMcpServer, HarnessType, ReasoningEffort } from "@tangle-network/agent-interface";
5
5
  import { WorkspacePlanReceipt } from "@tangle-network/agent-profile-materialize";
6
6
  import { ChildProcess } from "node:child_process";
7
- import { BackendType } from "@tangle-network/sandbox";
7
+ import { BackendType, SandboxEvent } from "@tangle-network/sandbox";
8
8
  //#region src/runtime/router-retry-policy.d.ts
9
9
  /** Exact retry controls accepted at `AgentProfile.model.metadata.retry`. */
10
10
  interface RouterRetryPolicy {
@@ -702,6 +702,22 @@ interface SandboxSeam {
702
702
  /** Hard cap on the composed loop's iterations. The budget pool reserves against
703
703
  * the spawn `Budget.maxIterations`; this is the leaf's own ceiling. Default 1. */
704
704
  maxIterations?: number;
705
+ /**
706
+ * OPT-IN executable score for this worker. Forwarded to the composed
707
+ * `runAgentRounds` as its `validator`, so the kernel calls `validate` while the
708
+ * iteration's box is still alive: `ValidationCtx.box` is a LIVE `SandboxInstance`
709
+ * and the check can run commands or read files in the container it is scoring.
710
+ * Every other supervised hook fires after teardown and can only read the artifact.
711
+ *
712
+ * The resulting verdict becomes the winner's verdict, which this executor already
713
+ * surfaces on its `ExecutorResult`. Absent, nothing changes: the loop runs
714
+ * unscored and the leaf falls back to its own settle verdict.
715
+ *
716
+ * Not representable with `steering` — a steerable session is a multi-turn session
717
+ * on one box, not a `runAgentRounds` composition, so the pair is rejected instead
718
+ * of silently dropping the score.
719
+ */
720
+ validator?: Validator<SandboxLeafOut>;
705
721
  /**
706
722
  * OPT-IN: run this worker as a multi-turn, STEERABLE session instead of the historical
707
723
  * single-shot `runAgentRounds` composition. Setting it gives the sandbox worker an `Executor.deliver`
@@ -909,6 +925,11 @@ interface RouterToolsSeam {
909
925
  durationMs?: number;
910
926
  }) => void;
911
927
  }
928
+ /** Parsed output of the sandbox leaf: the iteration's raw event stream. What a
929
+ * `SandboxSeam.validator` receives as its `output` argument. */
930
+ interface SandboxLeafOut {
931
+ events: SandboxEvent[];
932
+ }
912
933
  /**
913
934
  * The leaf `createWorktreeCliExecutor` as a backend-as-data factory: a supervisor-authored
914
935
  * `AgentProfile` driving claude / codex / opencode on its own worktree. `budgetExempt` like
@@ -956,5 +977,5 @@ declare function createExecutor(config: ExecutorConfig): ExecutorFactory<unknown
956
977
  */
957
978
  declare function createExecutorRegistry(): ExecutorRegistry;
958
979
  //#endregion
959
- export { removeWorktree as $, WorktreeCommandResult as A, RunLocalHarnessOptions as B, ResolvedMcpServerLaunch as C, resolveSecretEnv as D, resolveMcpServerLaunch as E, CodexTokenUsage as F, CreateWorktreeOptions as G, localHarnessExecutable as H, DEFAULT_LOCAL_HARNESS as I, GitRunner as J, DiffOptions as K, LOCAL_HARNESSES as L, WorktreeProfileMaterializationReceipt as M, CodexExecutionEvidence as N, secretEnvOfMcpServer as O, CodexExecutionPolicy as P, createWorktree as Q, LocalHarness as R, KeyProvider as S, mcpSecretEnvMetadataKey as T, parseCodexTokenUsage as U, harnessSupportsReasoningEffort as V, runLocalHarness as W, WorktreeHandle as X, RemoveWorktreeOptions as Y, captureWorktreeDiff as Z, SteerableSandboxSession as _, CliWorktreeSeam as a, ToolLoopCompactionOptions as at, InboxMessage as b, RouterSeam as c, cliWorktreeExecutor as d, RouterTransportConfig as et, createExecutor as f, SteerableSandboxArgs as g, SandboxSteeringOptions as h, CliWorktreeBridgeSeam as i, ToolLoopCompaction as it, WorktreeHarnessResult as j, WorktreeCheckRunner as k, RouterToolsSeam as l, DEFAULT_SANDBOX_STEERING_MAX_TURNS as m, BridgeSeam as n, ToolLoopCallContext as nt, ExecutorConfig as o, ToolLoopMessageRecord as ot, createExecutorRegistry as p, DiffResult as q, CliSeam as r, ToolLoopChat as rt, ProviderSeam as s, ToolLoopToolCall as st, BridgeModelCredential as t, ToolSpec as tt, SandboxSeam as u, createSteerableSandboxSession as v, envKeyProvider as w, createInbox as x, Inbox as y, LocalHarnessResult as z };
960
- //# sourceMappingURL=runtime-D-26vxJt.d.ts.map
980
+ export { createWorktree as $, WorktreeCheckRunner as A, LocalHarnessResult as B, KeyProvider as C, resolveMcpServerLaunch as D, mcpSecretEnvMetadataKey as E, CodexExecutionPolicy as F, runLocalHarness as G, harnessSupportsReasoningEffort as H, CodexTokenUsage as I, DiffResult as J, CreateWorktreeOptions as K, DEFAULT_LOCAL_HARNESS as L, WorktreeHarnessResult as M, WorktreeProfileMaterializationReceipt as N, resolveSecretEnv as O, CodexExecutionEvidence as P, captureWorktreeDiff as Q, LOCAL_HARNESSES as R, createInbox as S, envKeyProvider as T, localHarnessExecutable as U, RunLocalHarnessOptions as V, parseCodexTokenUsage as W, RemoveWorktreeOptions as X, GitRunner as Y, WorktreeHandle as Z, SteerableSandboxArgs as _, CliWorktreeSeam as a, ToolLoopCompaction as at, Inbox as b, RouterSeam as c, ToolLoopToolCall as ct, SandboxSeam as d, removeWorktree as et, cliWorktreeExecutor as f, SandboxSteeringOptions as g, DEFAULT_SANDBOX_STEERING_MAX_TURNS as h, CliWorktreeBridgeSeam as i, ToolLoopChat as it, WorktreeCommandResult as j, secretEnvOfMcpServer as k, RouterToolsSeam as l, createExecutorRegistry as m, BridgeSeam as n, ToolSpec as nt, ExecutorConfig as o, ToolLoopCompactionOptions as ot, createExecutor as p, DiffOptions as q, CliSeam as r, ToolLoopCallContext as rt, ProviderSeam as s, ToolLoopMessageRecord as st, BridgeModelCredential as t, RouterTransportConfig as tt, SandboxLeafOut as u, SteerableSandboxSession as v, ResolvedMcpServerLaunch as w, InboxMessage as x, createSteerableSandboxSession as y, LocalHarness as z };
981
+ //# sourceMappingURL=runtime-DlxoqEj2.d.ts.map
@@ -1,4 +1,4 @@
1
- import { f as ValidationError } from "./errors-DRoXIc7E.js";
1
+ import { f as ValidationError } from "./errors-CVIDr7GQ.js";
2
2
  //#region src/runtime/supervise/snapshot.ts
3
3
  /** Deeply detach and freeze untrusted data at a runtime decision boundary. The clone prevents the
4
4
  * caller from mutating it later; the freeze prevents downstream code from mutating the snapshot. */
@@ -18,4 +18,4 @@ function deepFreeze(value, seen = /* @__PURE__ */ new Set()) {
18
18
  //#endregion
19
19
  export { detachedSnapshot as t };
20
20
 
21
- //# sourceMappingURL=snapshot-DY6VGliG.js.map
21
+ //# sourceMappingURL=snapshot-BOIprwBk.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"snapshot-DY6VGliG.js","names":[],"sources":["../src/runtime/supervise/snapshot.ts"],"sourcesContent":["import { ValidationError } from '../../errors'\n\n/** Deeply detach and freeze untrusted data at a runtime decision boundary. The clone prevents the\n * caller from mutating it later; the freeze prevents downstream code from mutating the snapshot. */\nexport function detachedSnapshot<T>(value: T, context: string): T {\n try {\n return deepFreeze(structuredClone(value))\n } catch (error) {\n throw new ValidationError(`${context}: input must be structured-cloneable`, { cause: error })\n }\n}\n\nfunction deepFreeze<T>(value: T, seen = new Set<object>()): T {\n if (value === null || typeof value !== 'object' || seen.has(value)) return value\n seen.add(value)\n for (const child of Object.values(value as Record<string, unknown>)) deepFreeze(child, seen)\n return Object.freeze(value)\n}\n"],"mappings":";;;;AAIA,SAAgB,iBAAoB,OAAU,SAAoB;CAChE,IAAI;EACF,OAAO,WAAW,gBAAgB,KAAK,CAAC;CAC1C,SAAS,OAAO;EACd,MAAM,IAAI,gBAAgB,GAAG,QAAQ,uCAAuC,EAAE,OAAO,MAAM,CAAC;CAC9F;AACF;AAEA,SAAS,WAAc,OAAU,uBAAO,IAAI,IAAY,GAAM;CAC5D,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,KAAK,IAAI,KAAK,GAAG,OAAO;CAC3E,KAAK,IAAI,KAAK;CACd,KAAK,MAAM,SAAS,OAAO,OAAO,KAAgC,GAAG,WAAW,OAAO,IAAI;CAC3F,OAAO,OAAO,OAAO,KAAK;AAC5B"}
1
+ {"version":3,"file":"snapshot-BOIprwBk.js","names":[],"sources":["../src/runtime/supervise/snapshot.ts"],"sourcesContent":["import { ValidationError } from '../../errors'\n\n/** Deeply detach and freeze untrusted data at a runtime decision boundary. The clone prevents the\n * caller from mutating it later; the freeze prevents downstream code from mutating the snapshot. */\nexport function detachedSnapshot<T>(value: T, context: string): T {\n try {\n return deepFreeze(structuredClone(value))\n } catch (error) {\n throw new ValidationError(`${context}: input must be structured-cloneable`, { cause: error })\n }\n}\n\nfunction deepFreeze<T>(value: T, seen = new Set<object>()): T {\n if (value === null || typeof value !== 'object' || seen.has(value)) return value\n seen.add(value)\n for (const child of Object.values(value as Record<string, unknown>)) deepFreeze(child, seen)\n return Object.freeze(value)\n}\n"],"mappings":";;;;AAIA,SAAgB,iBAAoB,OAAU,SAAoB;CAChE,IAAI;EACF,OAAO,WAAW,gBAAgB,KAAK,CAAC;CAC1C,SAAS,OAAO;EACd,MAAM,IAAI,gBAAgB,GAAG,QAAQ,uCAAuC,EAAE,OAAO,MAAM,CAAC;CAC9F;AACF;AAEA,SAAS,WAAc,OAAU,uBAAO,IAAI,IAAY,GAAM;CAC5D,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,KAAK,IAAI,KAAK,GAAG,OAAO;CAC3E,KAAK,IAAI,KAAK;CACd,KAAK,MAAM,SAAS,OAAO,OAAO,KAAgC,GAAG,WAAW,OAAO,IAAI;CAC3F,OAAO,OAAO,OAAO,KAAK;AAC5B"}
@@ -1,6 +1,6 @@
1
- import { f as ValidationError } from "./errors-DRoXIc7E.js";
2
- import { t as detachedSnapshot } from "./snapshot-DY6VGliG.js";
3
- import { m as zeroTokenUsage, n as cloneTokenUsage, t as addTokenUsage } from "./util-Dr--8wAL.js";
1
+ import { f as ValidationError } from "./errors-CVIDr7GQ.js";
2
+ import { t as detachedSnapshot } from "./snapshot-BOIprwBk.js";
3
+ import { h as zeroTokenUsage, r as cloneTokenUsage, t as addTokenUsage } from "./util-DD8bRWPL.js";
4
4
  import { isToolSpan, toolSpansToTraceAnalysisStore } from "@tangle-network/agent-eval";
5
5
  import { createHash } from "node:crypto";
6
6
  //#region src/durable/content-address.ts
@@ -508,8 +508,9 @@ function ownedTreeRootSpawn(spawn) {
508
508
  * is intentionally not read: it proves only what Runtime requested, not what a provider served.
509
509
  *
510
510
  * Missing legacy evidence, an unfinished node, an unopened owned tree, an identity conflict, and a
511
- * paid attempt without a qualified served snapshot all return unknown. An explicit not-started arm
512
- * can be added by the owning Runtime contract later; absent legacy data remains unknown here.
511
+ * paid attempt without a qualified served snapshot all return unknown. An explicit
512
+ * `providerDispatch: "not_started"` arm is ignored for served-model identity, while absent or
513
+ * malformed legacy data remains unknown here.
513
514
  */
514
515
  function aggregateProviderModelEvidence(forest) {
515
516
  const attempts = [];
@@ -532,8 +533,10 @@ function aggregateProviderModelEvidence(forest) {
532
533
  markMissing();
533
534
  return;
534
535
  }
535
- if (raw.status === "unknown") raw.reason === "provider-model-conflict" ? markConflict() : markMissing();
536
- else if (raw.status !== "known") {
536
+ if (raw.status === "unknown") {
537
+ if (raw.reason === "provider-model-conflict") markConflict();
538
+ else if (!hasOnlyNotStartedAttempts(raw)) markMissing();
539
+ } else if (raw.status !== "known") {
537
540
  markMissing();
538
541
  return;
539
542
  }
@@ -552,6 +555,15 @@ function aggregateProviderModelEvidence(forest) {
552
555
  }
553
556
  if (rawAttempt.identityConflict === true) markConflict();
554
557
  const observations = [...rawAttempt.observations];
558
+ if (rawAttempt.providerDispatch === "not_started") {
559
+ if (observations.length > 0) markMissing();
560
+ attempts.push(Object.freeze({
561
+ observations: Object.freeze([]),
562
+ providerDispatch: "not_started",
563
+ ...rawAttempt.identityConflict === true ? { identityConflict: true } : {}
564
+ }));
565
+ continue;
566
+ }
555
567
  if (observations.length === 0) {
556
568
  markMissing();
557
569
  attempts.push(Object.freeze({
@@ -610,7 +622,7 @@ function aggregateProviderModelEvidence(forest) {
610
622
  if (evidence === void 0) markMissing();
611
623
  else append(evidence);
612
624
  } else if (event.kind === "settled" || event.kind === "cancelled") terminal(tree.root, event);
613
- if (!sawProviderEvidence || attempts.length === 0) reason ??= "provider-model-missing";
625
+ if (!sawProviderEvidence || attempts.length === 0 || observedModels.size === 0) reason ??= "provider-model-missing";
614
626
  const models = Object.freeze([...observedModels]);
615
627
  const frozenAttempts = Object.freeze(attempts);
616
628
  return Object.freeze(reason === void 0 ? {
@@ -630,8 +642,11 @@ function forestNodeKey(treeRoot, nodeId) {
630
642
  function isProviderEvidenceObject(value) {
631
643
  return typeof value === "object" && value !== null && !Array.isArray(value) && "status" in value;
632
644
  }
645
+ function hasOnlyNotStartedAttempts(evidence) {
646
+ return Array.isArray(evidence.attempts) && evidence.attempts.length > 0 && evidence.attempts.every((attempt) => isProviderAttemptEvidence(attempt) && attempt.providerDispatch === "not_started" && attempt.observations.length === 0 && attempt.identityConflict !== true);
647
+ }
633
648
  function isProviderAttemptEvidence(value) {
634
- return typeof value === "object" && value !== null && !Array.isArray(value) && Array.isArray(value.observations);
649
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Array.isArray(value.observations) && (value.providerDispatch === void 0 || value.providerDispatch === "not_started");
635
650
  }
636
651
  function servedIdentityParts(model) {
637
652
  const at = model.lastIndexOf("@");
@@ -973,7 +988,8 @@ function copyProviderModelEvidence(evidence) {
973
988
  if (evidence === void 0) return void 0;
974
989
  const attempts = Object.freeze(evidence.attempts.map((attempt) => Object.freeze({
975
990
  observations: Object.freeze([...attempt.observations]),
976
- ...attempt.identityConflict ? { identityConflict: true } : {}
991
+ ...attempt.identityConflict ? { identityConflict: true } : {},
992
+ ...attempt.providerDispatch === "not_started" ? { providerDispatch: "not_started" } : {}
977
993
  })));
978
994
  const models = Object.freeze([...evidence.models]);
979
995
  return Object.freeze(evidence.status === "unknown" ? {
@@ -1039,4 +1055,4 @@ function isNoEntError(err) {
1039
1055
  //#endregion
1040
1056
  export { contentAddress as S, WORKER_TOOL_TRACE_SCHEMA_VERSION as _, aggregateProviderModelEvidence as a, parseWorkerToolTraceArtifact as b, pendingWaits as c, prepareJsonlAppend as d, writeAllBytes as f, runtimeOwnedNestedDriverTreeRoot as g, nestedDriverTreeRoot as h, InMemorySpawnJournal as i, replaySpawnTree as l, driverRuntime as m, FileSpawnJournal as n, loadSpawnForest as o, attestNestedDriverTreeOwner as p, InMemoryResultBlobStore as r, materializeTreeView as s, FileResultBlobStore as t, parseCommittedJsonLines as u, captureWorkerTraceEvidence as v, workerTraceAnalysisStore as x, isTraceAnalysisStore as y };
1041
1057
 
1042
- //# sourceMappingURL=spawn-journal-BX3-4WDm.js.map
1058
+ //# sourceMappingURL=spawn-journal-B856eA8e.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spawn-journal-B856eA8e.js","names":["isNoEntError"],"sources":["../src/durable/content-address.ts","../src/runtime/supervise/trace-evidence.ts","../src/runtime/supervise/tree-key.ts","../src/durable/jsonl-file.ts","../src/durable/spawn-journal.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\n\n/** Stable content address shared by result and trace artifacts. */\nexport function contentAddress(artifact: unknown): string {\n const hex = createHash('sha256').update(stableStringify(artifact), 'utf-8').digest('hex')\n return `sha256:${hex}`\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`\n}\n","/**\n * Durable structured tool evidence for supervised workers.\n *\n * The executor-owned `TraceSource` is collected before teardown, snapshotted into the shared\n * content-addressed blob store, and only then referenced by a settlement. Analysis reconstructs\n * agent-eval's bounded `TraceAnalysisStore` from those exact bytes. Worker output is never accepted\n * as a substitute for tool evidence.\n *\n * @experimental\n */\n\nimport {\n isToolSpan,\n type Span,\n type ToolSpan,\n type TraceAnalysisStore,\n toolSpansToTraceAnalysisStore,\n} from '@tangle-network/agent-eval'\nimport { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\nimport type { TraceSource } from './trace-source'\nimport type { ResultBlobStore, WorkerTraceEvidence } from './types'\n\n/** Schema version for content-addressed worker tool-trace artifacts. */\nexport const WORKER_TOOL_TRACE_SCHEMA_VERSION = 1 as const\n\n/** Bytes stored under `WorkerTraceEvidence.traceRef`. */\nexport interface WorkerToolTraceArtifact {\n readonly schemaVersion: typeof WORKER_TOOL_TRACE_SCHEMA_VERSION\n readonly spans: ReadonlyArray<ToolSpan>\n}\n\n/** Structural guard for the official bounded trace-analysis read contract. */\nexport function isTraceAnalysisStore(value: unknown): value is TraceAnalysisStore {\n if (value === null || typeof value !== 'object') return false\n const store = value as Partial<Record<keyof TraceAnalysisStore, unknown>>\n return (\n typeof store.getOverview === 'function' &&\n typeof store.queryTraces === 'function' &&\n typeof store.countTraces === 'function' &&\n typeof store.viewTrace === 'function' &&\n typeof store.viewSpans === 'function' &&\n typeof store.searchTrace === 'function' &&\n typeof store.searchSpan === 'function'\n )\n}\n\n/** Collect and persist one executor's structured tool trace without changing its task outcome. */\nexport async function captureWorkerTraceEvidence(\n readSource: (() => TraceSource | undefined) | undefined,\n blobs: ResultBlobStore,\n executed: boolean,\n): Promise<WorkerTraceEvidence> {\n if (!executed) return unavailable('execution-did-not-start')\n if (readSource === undefined) return unavailable('executor-did-not-expose-trace-source')\n\n let source: TraceSource | undefined\n try {\n source = readSource()\n } catch {\n return unavailable('trace-source-unavailable')\n }\n if (source === undefined) return unavailable('trace-source-unavailable')\n\n let collected: unknown\n try {\n collected = await source.collect()\n } catch {\n return unavailable('trace-collection-failed')\n }\n if (!Array.isArray(collected) || collected.some((span) => !isToolSpanValue(span))) {\n return unavailable('invalid-tool-spans')\n }\n if (collected.length === 0) return unavailable('no-tool-spans-captured')\n\n let artifact: WorkerToolTraceArtifact\n let traceRef: string\n try {\n const snapshot = structuredClone(collected) as ToolSpan[]\n // Use agent-eval's canonical adapter as the full integrity check before the durable receipt\n // claims these spans are analyzable. `isToolSpan` only narrows the discriminated union.\n toolSpansToTraceAnalysisStore(snapshot)\n artifact = {\n schemaVersion: WORKER_TOOL_TRACE_SCHEMA_VERSION,\n spans: snapshot,\n }\n traceRef = contentAddress(artifact)\n } catch {\n return unavailable('invalid-tool-spans')\n }\n try {\n await blobs.put(traceRef, artifact)\n } catch {\n return unavailable('trace-persistence-failed')\n }\n return Object.freeze({ status: 'available', traceRef, spanCount: artifact.spans.length })\n}\n\n/** Rehydrate exact persisted spans through agent-eval's one bounded trace-analysis adapter. */\nexport async function workerTraceAnalysisStore(\n evidence: WorkerTraceEvidence,\n blobs: Pick<ResultBlobStore, 'get'>,\n): Promise<TraceAnalysisStore> {\n if (evidence.status === 'unavailable') {\n // The published adapter owns the missing-evidence error and its classification.\n return toolSpansToTraceAnalysisStore(undefined)\n }\n const raw = await blobs.get(evidence.traceRef)\n if (raw === undefined) {\n throw new ValidationError(\n `worker trace blob '${evidence.traceRef}' is missing; the settlement evidence is incomplete`,\n )\n }\n const artifact = parseWorkerToolTraceArtifact(raw, evidence.traceRef)\n if (artifact.spans.length !== evidence.spanCount) {\n throw new ValidationError(\n `worker trace blob '${evidence.traceRef}' has ${artifact.spans.length} spans but its settlement records ${evidence.spanCount}`,\n )\n }\n return toolSpansToTraceAnalysisStore(artifact.spans)\n}\n\n/** Validate a stored trace artifact before an analyst or replay trusts it. */\nexport function parseWorkerToolTraceArtifact(\n value: unknown,\n traceRef = '<unknown>',\n): WorkerToolTraceArtifact {\n if (\n value === null ||\n typeof value !== 'object' ||\n (value as { schemaVersion?: unknown }).schemaVersion !== WORKER_TOOL_TRACE_SCHEMA_VERSION ||\n !Array.isArray((value as { spans?: unknown }).spans)\n ) {\n throw new ValidationError(\n `worker trace blob '${traceRef}' is not a version-${WORKER_TOOL_TRACE_SCHEMA_VERSION} tool trace artifact`,\n )\n }\n const spans = (value as { spans: unknown[] }).spans\n if (spans.length === 0) {\n // Missing spans cannot prove a tool-free run; preserve agent-eval's explicit integrity error.\n return {\n schemaVersion: WORKER_TOOL_TRACE_SCHEMA_VERSION,\n spans: spans as ToolSpan[],\n }\n }\n if (spans.some((span) => !isToolSpanValue(span))) {\n throw new ValidationError(`worker trace blob '${traceRef}' contains a non-tool span`)\n }\n return {\n schemaVersion: WORKER_TOOL_TRACE_SCHEMA_VERSION,\n spans: spans as ToolSpan[],\n }\n}\n\nfunction unavailable(reason: Extract<WorkerTraceEvidence, { status: 'unavailable' }>['reason']) {\n return Object.freeze({ status: 'unavailable' as const, reason })\n}\n\nfunction isToolSpanValue(value: unknown): value is ToolSpan {\n try {\n return isToolSpan(value as Span)\n } catch {\n return false\n }\n}\n","import type { NodeId } from './types'\n\n/** Runtime tag used only for a child that owns another supervised scope. */\nexport const driverRuntime = 'driver' as const\n\n// Recursive ownership is an executor capability, not a Runtime string. `Runtime` is deliberately\n// open, so a caller-owned leaf may also call itself \"driver\". Keep the capability on the exact\n// Runtime-created executor object and never expose a public lookalike property that a leaf can set.\nconst nestedDriverTreeOwners = new WeakSet<object>()\n\n/** Canonical journal key for the scope owned by one nested driver node. */\nexport function nestedDriverTreeRoot(parentTreeRoot: NodeId, driverNodeId: NodeId): NodeId {\n return `${parentTreeRoot}/${driverNodeId}`\n}\n\n/** Privately mark the exact recursive executor that will create a nested journal tree. */\nexport function attestNestedDriverTreeOwner<T extends object>(owner: T): T {\n nestedDriverTreeOwners.add(owner)\n return owner\n}\n\n/** Return the canonical owned tree only for an exact privately marked recursive executor. */\nexport function runtimeOwnedNestedDriverTreeRoot(\n owner: object,\n parentTreeRoot: NodeId,\n driverNodeId: NodeId,\n): NodeId | undefined {\n return nestedDriverTreeOwners.has(owner)\n ? nestedDriverTreeRoot(parentTreeRoot, driverNodeId)\n : undefined\n}\n","import type { FileHandle } from 'node:fs/promises'\n\n/** Parse an append-only JSONL file without treating a torn final write as committed data.\n * A malformed newline-terminated or non-final record is corruption and fails loud. */\nexport function parseCommittedJsonLines<T>(text: string, source: string): T[] {\n const lines = text.split('\\n')\n const finalIndex = lines.length - 1\n const records: T[] = []\n\n for (const [index, line] of lines.entries()) {\n if (line.length === 0) continue\n try {\n records.push(JSON.parse(line) as T)\n } catch (cause) {\n const isInvalidUnterminatedTail = index === finalIndex && !text.endsWith('\\n')\n if (isInvalidUnterminatedTail) break\n throw new Error(`${source}: malformed JSONL record at line ${index + 1}`, { cause })\n }\n }\n\n return records\n}\n\n/** FileHandle.write may legally make a short write. Loop until every byte is appended. */\nexport async function writeAllBytes(\n handle: Pick<FileHandle, 'write'>,\n value: string | Uint8Array,\n): Promise<void> {\n const bytes = typeof value === 'string' ? Buffer.from(value) : Buffer.from(value)\n let offset = 0\n while (offset < bytes.byteLength) {\n const { bytesWritten } = await handle.write(bytes, offset, bytes.byteLength - offset, null)\n if (bytesWritten <= 0) {\n throw new Error(`append-only file write made no progress at byte ${offset}`)\n }\n offset += bytesWritten\n }\n}\n\n/** Prepare a recovered JSONL file for its next append. A valid unterminated final value is retained\n * and needs a separator; an invalid unterminated tail was never committed and is truncated. */\nexport async function prepareJsonlAppend(path: string): Promise<boolean> {\n const fs = await import('node:fs/promises')\n let bytes: Buffer\n try {\n bytes = await fs.readFile(path)\n } catch (error) {\n if (isNoEntError(error)) return false\n throw error\n }\n if (bytes.byteLength === 0 || bytes[bytes.byteLength - 1] === 0x0a) return false\n\n const lastNewline = bytes.lastIndexOf(0x0a)\n const tail = bytes.subarray(lastNewline + 1).toString('utf8')\n try {\n JSON.parse(tail)\n return true\n } catch {\n await fs.truncate(path, lastNewline + 1)\n return false\n }\n}\n\nfunction isNoEntError(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code: unknown }).code === 'ENOENT'\n )\n}\n","/**\n *\n * Event-sourced spawn journal for the recursive execution atom (build steps 3 + 7).\n *\n * The supervision tree is journaled as an append-only event log: every `spawned`,\n * `settled`, and `cancelled` is recorded AFTER it is observed-committed (never\n * speculative), mirroring `ConversationJournal`'s begin/append/load shape. The log\n * holds only the THIN decision record — ids, parentage, budget, the spend a decision\n * consumed, and a content-addressed `outRef`. The payloads the driver branched on\n * (the `out` artifacts) live in a separate `ResultBlobStore`, keyed by `outRef`, so\n * the journal stays small (decisions) and replay rehydrates the exact `Settled` from\n * the blob store (evidence). This is the decision/payload split the replay argument\n * rests on (B1/B2).\n *\n * Replay determinism (B2): `seq` is the monotonic cursor order `scope.next()` yielded\n * each settlement — NOT wall-clock. `replaySpawnTree` sorts strictly by `seq` before\n * touching the blob store, so the order in which rehydration `get`s resolve can never\n * reorder the replayed `Settled[]`; the result is identical regardless of blob latency.\n *\n * @stable\n */\n\nimport { detachedSnapshot } from '../runtime/supervise/snapshot'\nimport { workerTraceAnalysisStore } from '../runtime/supervise/trace-evidence'\nimport { nestedDriverTreeRoot } from '../runtime/supervise/tree-key'\nimport type {\n NodeExecutionIdentity,\n NodeId,\n NodeSnapshot,\n NodeStatus,\n ProviderModelAttemptEvidence,\n ProviderModelExecutionEvidence,\n ResultBlobStore,\n Runtime,\n Settled,\n SpawnEvent,\n SpawnJournal,\n Spend,\n TreeView,\n} from '../runtime/supervise/types'\nimport type { PendingWait } from '../runtime/supervise/wait'\nimport { addTokenUsage, cloneTokenUsage, zeroTokenUsage } from '../runtime/util'\nimport { contentAddress } from './content-address'\nimport { parseCommittedJsonLines, prepareJsonlAppend, writeAllBytes } from './jsonl-file'\n\nexport { contentAddress } from './content-address'\n\n/** One journal tree in a recursively loaded supervision forest. */\nexport interface SpawnForestTree {\n readonly root: NodeId\n /** Driver node that owns this tree; absent for the requested root tree. */\n readonly ownerNodeId?: NodeId\n /** Journal tree containing `ownerNodeId`; absent for the requested root tree. */\n readonly parentTreeRoot?: NodeId\n readonly events: ReadonlyArray<SpawnEvent>\n readonly view: TreeView\n}\n\n/** One event with the journal tree that establishes its cursor namespace. */\nexport interface SpawnForestEvent {\n readonly treeRoot: NodeId\n readonly event: SpawnEvent\n}\n\n/** One flattened node with the journal tree that owns its records. */\nexport interface SpawnForestNode extends NodeSnapshot {\n readonly treeRoot: NodeId\n}\n\n/** A spawned worker with no terminal record in a cold snapshot. Resume treats the same state as\n * in-doubt and conservatively retains its reservation. Root nodes and armed waits are excluded. */\nexport interface SpawnForestInDoubtNode {\n readonly treeRoot: NodeId\n readonly nodeId: NodeId\n readonly label: string\n readonly runtime: Runtime\n}\n\n/** A driver spawn whose owned journal tree was never begun before the process stopped. */\nexport interface SpawnForestMissingTree {\n readonly parentTreeRoot: NodeId\n readonly ownerNodeId: NodeId\n readonly root: NodeId\n}\n\n/** Complete cold-readable view of one recursive supervision run. */\nexport interface SpawnForest {\n readonly root: NodeId\n readonly trees: ReadonlyArray<SpawnForestTree>\n readonly nodes: ReadonlyArray<SpawnForestNode>\n readonly events: ReadonlyArray<SpawnForestEvent>\n readonly inDoubt: ReadonlyArray<SpawnForestInDoubtNode>\n readonly missingTrees: ReadonlyArray<SpawnForestMissingTree>\n}\n\n// ── Content addressing ──────────────────────────────────────────────────────\n\n/**\n * Mint the content-addressed `outRef` for a result artifact: `sha256:<hex>` over a\n * stable JSON encoding. Producers call this to derive the `outRef` they journal and\n * `put`; the FS/in-mem stores re-derive it on `put` to verify the supplied ref\n * matches (fail loud on a mismatch — a forged ref breaks the replay invariant).\n *\n * Stable encoding: object keys are sorted recursively so two structurally-equal\n * artifacts hash identically regardless of key insertion order.\n */\n// ── Result blob store ─────────────────────────────────────────────────────────\n\n/**\n * In-memory `ResultBlobStore`. Content-addressed: `put` verifies the supplied\n * `outRef` matches the artifact's hash so a stale/forged ref fails loud rather than\n * silently rehydrating the wrong payload. Idempotent on an identical re-put.\n *\n * @stable\n */\nexport class InMemoryResultBlobStore implements ResultBlobStore {\n private readonly blobs = new Map<string, unknown>()\n\n async put(outRef: string, artifact: unknown): Promise<void> {\n assertContentAddress(outRef, artifact)\n this.blobs.set(outRef, artifact)\n }\n\n async get(outRef: string): Promise<unknown | undefined> {\n return this.blobs.has(outRef) ? this.blobs.get(outRef) : undefined\n }\n}\n\n/**\n * FS `ResultBlobStore`. One JSON file per artifact under `dir`, named by a\n * filesystem-safe encoding of the `outRef` (`sha256:<hex>` → `sha256-<hex>.json`).\n * `put` fsyncs so a crash between writes never loses an acknowledged blob.\n *\n * @stable\n */\nexport class FileResultBlobStore implements ResultBlobStore {\n constructor(private readonly dir: string) {}\n\n async put(outRef: string, artifact: unknown): Promise<void> {\n assertContentAddress(outRef, artifact)\n const fs = await import('node:fs/promises')\n await fs.mkdir(this.dir, { recursive: true })\n const fh = await fs.open(this.blobPath(outRef), 'w')\n try {\n await fh.write(JSON.stringify(artifact))\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n\n async get(outRef: string): Promise<unknown | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.blobPath(outRef), 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n return JSON.parse(text)\n }\n\n private blobPath(outRef: string): string {\n return `${this.dir}/${outRef.replace(/:/g, '-')}.json`\n }\n}\n\nfunction assertContentAddress(outRef: string, artifact: unknown): void {\n const expected = contentAddress(artifact)\n if (outRef !== expected) {\n throw new Error(\n `blob outRef '${outRef}' does not match the artifact content hash '${expected}'; ` +\n 'a content-addressed store refuses a mismatched ref (breaks the replay invariant)',\n )\n }\n}\n\n// ── Spawn journal ──────────────────────────────────────────────────────────────\n\n/**\n * In-memory `SpawnJournal`. Appends are observed-committed only; the impl enforces\n * the corruption guards a durable replay rests on:\n * - an event before `beginTree` is a corrupted tree (fail loud),\n * - a duplicate `seq` within a tree is a corrupted cursor (fail loud) — two\n * settlements cannot share the cursor position replay orders by.\n *\n * @stable\n */\nexport class InMemorySpawnJournal implements SpawnJournal {\n private readonly trees = new Map<NodeId, { begunAt: string; events: SpawnEvent[] }>()\n\n async loadTree(root: NodeId): Promise<SpawnEvent[] | undefined> {\n const tree = this.trees.get(root)\n if (!tree) return undefined\n return tree.events.map((ev) => ({ ...ev }))\n }\n\n async beginTree(root: NodeId, at: string): Promise<void> {\n const existing = this.trees.get(root)\n if (existing) {\n if (existing.begunAt !== at) {\n throw new Error(\n `spawn tree '${root}' already begun at ${existing.begunAt}; refusing to overwrite with ${at}`,\n )\n }\n return\n }\n this.trees.set(root, { begunAt: at, events: [] })\n }\n\n async appendEvent(root: NodeId, ev: SpawnEvent): Promise<void> {\n const tree = this.trees.get(root)\n if (!tree) {\n throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`)\n }\n assertSeqUnique(root, tree.events, ev)\n tree.events.push({ ...ev })\n }\n}\n\n/**\n * JSONL on disk. One line per record: the first record is `begin`, subsequent records\n * are `event` envelopes wrapping a `SpawnEvent`. `loadTree` replays the whole file,\n * filtering by `root`, and applies the same begin-precedes-events + unique-seq\n * corruption guards as the in-memory impl. Each append fsyncs so a crash between\n * writes never loses an acknowledged event.\n *\n * @stable\n */\nexport class FileSpawnJournal implements SpawnJournal {\n private appendTail: Promise<void> = Promise.resolve()\n\n constructor(private readonly path: string) {}\n\n async loadTree(root: NodeId): Promise<SpawnEvent[] | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.path, 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n let begun = false\n const events: SpawnEvent[] = []\n for (const record of parseCommittedJsonLines<SpawnJournalRecord>(text, this.path)) {\n if (record.root !== root) continue\n if (record.kind === 'begin') {\n begun = true\n } else {\n if (!begun) {\n throw new Error(\n `spawn journal corrupted: event for tree '${root}' precedes its begin record`,\n )\n }\n assertSeqUnique(root, events, record.event)\n events.push(record.event)\n }\n }\n return begun ? events : undefined\n }\n\n async beginTree(root: NodeId, at: string): Promise<void> {\n const existing = await this.loadTreeBegin(root)\n if (existing) {\n if (existing !== at) {\n throw new Error(\n `spawn tree '${root}' already begun in ${this.path} at ${existing}; refusing to overwrite with ${at}`,\n )\n }\n return\n }\n await this.appendRecord({ kind: 'begin', root, at })\n }\n\n async appendEvent(root: NodeId, ev: SpawnEvent): Promise<void> {\n const events = await this.loadTree(root)\n if (events === undefined) {\n throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`)\n }\n assertSeqUnique(root, events, ev)\n await this.appendRecord({ kind: 'event', root, event: ev })\n }\n\n private async loadTreeBegin(root: NodeId): Promise<string | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.path, 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n for (const record of parseCommittedJsonLines<SpawnJournalRecord>(text, this.path)) {\n if (record.root === root && record.kind === 'begin') return record.at\n }\n return undefined\n }\n\n private async appendRecord(record: SpawnJournalRecord): Promise<void> {\n const append = this.appendTail.then(() => this.writeRecord(record))\n this.appendTail = append.catch(() => undefined)\n return append\n }\n\n private async writeRecord(record: SpawnJournalRecord): Promise<void> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n await fs.mkdir(path.dirname(this.path), { recursive: true })\n const needsSeparator = await prepareJsonlAppend(this.path)\n const fh = await fs.open(this.path, 'a')\n try {\n await writeAllBytes(fh, `${needsSeparator ? '\\n' : ''}${JSON.stringify(record)}\\n`)\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n}\n\n/**\n * Load every journal tree owned by one recursive supervision run and flatten its nodes/events.\n *\n * Nested driver tree keys are a Runtime implementation detail; callers should use this reader\n * instead of deriving or scanning keys themselves. The reader follows only the explicit\n * `ownedTreeRoot` written after Runtime privately attested a recursive executor; the open runtime\n * string `driver` is never treated as ownership. Legacy records without `ownedTreeRoot` are\n * intentionally treated as leaves rather than guessing or scanning convention-derived keys.\n * This preserves each tree's independent cursor namespace on flattened events.\n * A driver whose subtree was never begun is reported in `missingTrees`; any spawned non-root node\n * without a terminal record is reported in `inDoubt`, matching resume's conservative lost-work\n * interpretation.\n *\n * This is a cold/quiescent reader, not a transaction across an actively mutating file. Every value\n * returned is a detached immutable snapshot, so later journal writes or caller mutation cannot\n * change the result already observed.\n */\nexport async function loadSpawnForest(journal: SpawnJournal, root: NodeId): Promise<SpawnForest> {\n const rootEvents = await journal.loadTree(root)\n if (rootEvents === undefined) {\n throw new Error(`loadSpawnForest: no journaled tree for root '${root}'`)\n }\n\n const trees: SpawnForestTree[] = []\n const nodes: SpawnForestNode[] = []\n const events: SpawnForestEvent[] = []\n const inDoubt: SpawnForestInDoubtNode[] = []\n const missingTrees: SpawnForestMissingTree[] = []\n const visited = new Set<NodeId>()\n const queue: Array<{\n readonly root: NodeId\n readonly events: SpawnEvent[]\n readonly ownerNodeId?: NodeId\n readonly parentTreeRoot?: NodeId\n /** Parent-tree spawn that establishes the root node omitted from an owned journal tree. */\n readonly ownerSpawn?: Extract<SpawnEvent, { kind: 'spawned' }>\n }> = [{ root, events: rootEvents }]\n\n for (let cursor = 0; cursor < queue.length; cursor += 1) {\n const current = queue[cursor]!\n if (visited.has(current.root)) {\n throw new Error(`loadSpawnForest: recursive journal tree '${current.root}' was reached twice`)\n }\n visited.add(current.root)\n const stableEvents = detachedSnapshot(\n current.events,\n `loadSpawnForest tree ${JSON.stringify(current.root)}`,\n )\n const viewEvents =\n current.ownerSpawn === undefined ||\n stableEvents.some((event) => event.kind === 'spawned' && event.id === current.ownerSpawn?.id)\n ? [...stableEvents]\n : [ownedTreeRootSpawn(current.ownerSpawn), ...stableEvents]\n const view = detachedSnapshot(\n materializeTreeView(viewEvents),\n `loadSpawnForest view ${JSON.stringify(current.root)}`,\n )\n trees.push({\n root: current.root,\n ...(current.ownerNodeId === undefined ? {} : { ownerNodeId: current.ownerNodeId }),\n ...(current.parentTreeRoot === undefined ? {} : { parentTreeRoot: current.parentTreeRoot }),\n events: stableEvents,\n view,\n })\n // The owner is already a real node in its parent tree. Keep it in this tree's local view so\n // metered root events have a node, but omit the synthetic duplicate from the flattened list.\n nodes.push(\n ...view.nodes\n .filter((node) => current.ownerNodeId === undefined || node.id !== current.ownerNodeId)\n .map((node) => ({ treeRoot: current.root, ...node })),\n )\n events.push(...stableEvents.map((event) => ({ treeRoot: current.root, event })))\n\n const terminal = new Set<NodeId>()\n for (const event of stableEvents) {\n if (event.kind === 'settled' || event.kind === 'cancelled') terminal.add(event.id)\n }\n const spawns = stableEvents\n .filter(\n (event): event is Extract<SpawnEvent, { kind: 'spawned' }> => event.kind === 'spawned',\n )\n .sort((a, b) => a.seq - b.seq || a.id.localeCompare(b.id))\n for (const spawn of spawns) {\n if (spawn.parent !== undefined && !terminal.has(spawn.id)) {\n inDoubt.push({\n treeRoot: current.root,\n nodeId: spawn.id,\n label: spawn.label,\n runtime: spawn.runtime,\n })\n }\n if (spawn.ownedTreeRoot === undefined) continue\n const expectedRoot = nestedDriverTreeRoot(current.root, spawn.id)\n if (spawn.ownedTreeRoot !== expectedRoot) {\n throw new Error(\n `loadSpawnForest: node '${spawn.id}' owns non-canonical tree '${spawn.ownedTreeRoot}'; expected '${expectedRoot}'`,\n )\n }\n const nestedRoot = spawn.ownedTreeRoot\n const nestedEvents = await journal.loadTree(nestedRoot)\n if (nestedEvents === undefined) {\n missingTrees.push({\n parentTreeRoot: current.root,\n ownerNodeId: spawn.id,\n root: nestedRoot,\n })\n continue\n }\n queue.push({\n root: nestedRoot,\n events: nestedEvents,\n ownerNodeId: spawn.id,\n parentTreeRoot: current.root,\n ownerSpawn: spawn,\n })\n }\n }\n\n return detachedSnapshot(\n { root, trees, nodes, events, inDoubt, missingTrees },\n 'loadSpawnForest result',\n )\n}\n\n/** Owned journal trees record the owner's turns and descendants, but the owner's spawn belongs to\n * the parent tree. Supply a view-only parentless copy so strict materialization can fold root\n * metering without weakening its missing-spawn corruption check for ordinary event lists. */\nfunction ownedTreeRootSpawn(\n spawn: Extract<SpawnEvent, { kind: 'spawned' }>,\n): Extract<SpawnEvent, { kind: 'spawned' }> {\n const { parent: _parent, ownedTreeRoot: _ownedTreeRoot, ...root } = spawn\n return root\n}\n\n/**\n * Aggregate provider-served model evidence across one recursively owned journal forest.\n *\n * The parent tree records an owned driver's terminal summary, while that driver's own inference\n * and descendants live in its owned tree. This reducer follows the forest reader's explicit tree\n * edges and consumes each tree's metered attempts plus terminal leaf settlements exactly once.\n * A summary node is skipped because its owned tree supplies the source records. Plan materialization\n * is intentionally not read: it proves only what Runtime requested, not what a provider served.\n *\n * Missing legacy evidence, an unfinished node, an unopened owned tree, an identity conflict, and a\n * paid attempt without a qualified served snapshot all return unknown. An explicit\n * `providerDispatch: \"not_started\"` arm is ignored for served-model identity, while absent or\n * malformed legacy data remains unknown here.\n */\nexport function aggregateProviderModelEvidence(\n forest: SpawnForest,\n): ProviderModelExecutionEvidence {\n const attempts: ProviderModelAttemptEvidence[] = []\n const observedModels = new Set<string>()\n const canonicalModels = new Set<string>()\n const nodes = new Map<string, SpawnForestNode>()\n let reason: 'provider-model-missing' | 'provider-model-conflict' | undefined\n let sawProviderEvidence = false\n\n for (const node of forest.nodes) nodes.set(forestNodeKey(node.treeRoot, node.id), node)\n if (forest.missingTrees.length > 0 || forest.inDoubt.length > 0) {\n reason = 'provider-model-missing'\n }\n\n const markMissing = () => {\n reason ??= 'provider-model-missing'\n }\n const markConflict = () => {\n reason = 'provider-model-conflict'\n }\n\n const append = (raw: unknown): void => {\n sawProviderEvidence = true\n if (!isProviderEvidenceObject(raw)) {\n markMissing()\n return\n }\n if (raw.status === 'unknown') {\n if (raw.reason === 'provider-model-conflict') {\n markConflict()\n } else if (!hasOnlyNotStartedAttempts(raw)) {\n markMissing()\n }\n } else if (raw.status !== 'known') {\n markMissing()\n return\n }\n if (!Array.isArray(raw.attempts) || !Array.isArray(raw.models)) {\n markMissing()\n return\n }\n\n const declared = new Set<string>()\n for (const model of raw.models) {\n if (typeof model !== 'string' || model.length === 0) {\n markMissing()\n } else {\n declared.add(model)\n }\n }\n const observedInRecord = new Set<string>()\n for (const rawAttempt of raw.attempts) {\n if (!isProviderAttemptEvidence(rawAttempt)) {\n markMissing()\n continue\n }\n if (rawAttempt.identityConflict === true) markConflict()\n const observations = [...rawAttempt.observations]\n if (rawAttempt.providerDispatch === 'not_started') {\n if (observations.length > 0) markMissing()\n attempts.push(\n Object.freeze({\n observations: Object.freeze([]),\n providerDispatch: 'not_started' as const,\n ...(rawAttempt.identityConflict === true ? { identityConflict: true } : {}),\n }),\n )\n continue\n }\n if (observations.length === 0) {\n markMissing()\n attempts.push(\n Object.freeze({\n observations: Object.freeze([]),\n ...(rawAttempt.identityConflict === true ? { identityConflict: true } : {}),\n }),\n )\n continue\n }\n let base: string | undefined\n let snapshot: string | undefined\n for (const model of observations) {\n if (typeof model !== 'string' || model.length === 0) {\n markMissing()\n continue\n }\n observedInRecord.add(model)\n observedModels.add(model)\n const identity = servedIdentityParts(model)\n if (identity === undefined) {\n markMissing()\n continue\n }\n if (base !== undefined && base !== identity.base) markConflict()\n if (\n snapshot !== undefined &&\n identity.snapshot !== undefined &&\n snapshot !== identity.snapshot\n ) {\n markConflict()\n }\n base = identity.base\n snapshot ??= identity.snapshot\n if (identity.snapshot !== undefined) {\n canonicalModels.add(`${identity.base}@${identity.snapshot}`)\n if (canonicalModels.size > 1) markConflict()\n }\n }\n if (base === undefined || snapshot === undefined) markMissing()\n attempts.push(\n Object.freeze({\n observations: Object.freeze(observations),\n ...(rawAttempt.identityConflict === true ? { identityConflict: true } : {}),\n }),\n )\n }\n if (\n declared.size !== observedInRecord.size ||\n [...declared].some((model) => !observedInRecord.has(model))\n ) {\n markMissing()\n }\n }\n\n const terminal = (\n treeRoot: NodeId,\n event: Extract<SpawnEvent, { kind: 'settled' | 'cancelled' }>,\n ) => {\n const node = nodes.get(forestNodeKey(treeRoot, event.id))\n if (node === undefined) {\n markMissing()\n return\n }\n // This event is a parent-side summary. Its owned tree is the authoritative source and is\n // traversed above; consuming its summary here would count nested attempts twice.\n if (node.ownedTreeRoot !== undefined) return\n if (event.kind === 'cancelled') {\n markMissing()\n return\n }\n append(event.providerModel ?? node.providerModel)\n }\n\n for (const tree of forest.trees) {\n for (const event of tree.events) {\n if (event.kind === 'metered') {\n // The parent scope re-homes a driver's nested metered spend onto the driver's parent node.\n // Its owned tree carries the provider attempts; consuming this summary would both\n // double-count and treat the spend-only legacy summary as missing identity evidence.\n const summaryNode = nodes.get(forestNodeKey(tree.root, event.id))\n if (summaryNode?.ownedTreeRoot !== undefined) continue\n const evidence = (event as SpawnEvent & { providerModel?: unknown }).providerModel\n if (evidence === undefined) markMissing()\n else append(evidence)\n } else if (event.kind === 'settled' || event.kind === 'cancelled') {\n terminal(tree.root, event)\n }\n }\n }\n\n if (!sawProviderEvidence || attempts.length === 0 || observedModels.size === 0) {\n reason ??= 'provider-model-missing'\n }\n const models = Object.freeze([...observedModels])\n const frozenAttempts = Object.freeze(attempts)\n return Object.freeze(\n reason === undefined\n ? { status: 'known' as const, attempts: frozenAttempts, models }\n : { status: 'unknown' as const, attempts: frozenAttempts, models, reason },\n )\n}\n\nfunction forestNodeKey(treeRoot: NodeId, nodeId: NodeId): string {\n return `${treeRoot}\\u0000${nodeId}`\n}\n\nfunction isProviderEvidenceObject(value: unknown): value is ProviderModelExecutionEvidence {\n return typeof value === 'object' && value !== null && !Array.isArray(value) && 'status' in value\n}\n\nfunction hasOnlyNotStartedAttempts(evidence: ProviderModelExecutionEvidence): boolean {\n return (\n Array.isArray(evidence.attempts) &&\n evidence.attempts.length > 0 &&\n evidence.attempts.every(\n (attempt) =>\n isProviderAttemptEvidence(attempt) &&\n attempt.providerDispatch === 'not_started' &&\n attempt.observations.length === 0 &&\n attempt.identityConflict !== true,\n )\n )\n}\n\nfunction isProviderAttemptEvidence(value: unknown): value is ProviderModelAttemptEvidence {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n Array.isArray((value as { observations?: unknown }).observations) &&\n ((value as { providerDispatch?: unknown }).providerDispatch === undefined ||\n (value as { providerDispatch?: unknown }).providerDispatch === 'not_started')\n )\n}\n\nfunction servedIdentityParts(\n model: string,\n): { readonly base: string; readonly snapshot?: string } | undefined {\n const at = model.lastIndexOf('@')\n const rawBase = at < 0 ? model : model.slice(0, at)\n const base = rawBase.slice(rawBase.lastIndexOf('/') + 1)\n if (base.length === 0) return undefined\n const snapshot = at < 0 ? undefined : model.slice(at + 1)\n if (snapshot !== undefined && snapshot.length === 0) return undefined\n return snapshot === undefined ? { base } : { base, snapshot }\n}\n\ntype SpawnJournalRecord =\n | { kind: 'begin'; root: NodeId; at: string }\n | { kind: 'event'; root: NodeId; event: SpawnEvent }\n\n/**\n * Two `seq` namespaces share the journal: a `spawned` event's `seq` is the spawn ordinal\n * (the order children were created), and a `settled`/`cancelled` event's `seq` is the\n * monotonic CURSOR order `scope.next()` yielded that settlement (B2). The uniqueness\n * replay rests on is the cursor namespace — two settlements cannot share the position\n * replay orders by — so the guard checks only settled/cancelled events. A `spawned`\n * ordinal legitimately equals a later `settled` cursor seq and is not a collision.\n */\nfunction assertSeqUnique(root: NodeId, events: SpawnEvent[], ev: SpawnEvent): void {\n if (ev.kind === 'materialized') {\n if (events.some((event) => event.kind === 'materialized' && event.id === ev.id)) {\n throw new Error(\n `spawn journal corrupted: duplicate materialization receipt for node '${ev.id}' in tree '${root}'`,\n )\n }\n if (!events.some((event) => event.kind === 'spawned' && event.id === ev.id)) {\n throw new Error(\n `spawn journal corrupted: materialization for node '${ev.id}' precedes its spawn in tree '${root}'`,\n )\n }\n }\n if (ev.kind === 'execution-bound') {\n if (\n events.some(\n (event) =>\n event.kind === 'execution-bound' &&\n event.id === ev.id &&\n event.binding.attemptId === ev.binding.attemptId,\n )\n ) {\n throw new Error(\n `spawn journal corrupted: duplicate execution binding for node '${ev.id}' attempt '${ev.binding.attemptId}' in tree '${root}'`,\n )\n }\n if (!events.some((event) => event.kind === 'materialized' && event.id === ev.id)) {\n throw new Error(\n `spawn journal corrupted: execution binding for node '${ev.id}' precedes materialization in tree '${root}'`,\n )\n }\n }\n // `spawned` (ordinal namespace), `waiting` (the wait-ordinal namespace — it CREATES a node, it\n // does not settle one), and `metered` (informational spend, no settlement order) live outside\n // the cursor-uniqueness namespace replay relies on. `woken` IS a settlement and does not.\n if (outsideCursorNamespace(ev)) return\n if (events.some((e) => !outsideCursorNamespace(e) && e.seq === ev.seq)) {\n throw new Error(\n `spawn journal corrupted: duplicate cursor seq ${ev.seq} in tree '${root}'; ` +\n 'the cursor order replay relies on is not unique',\n )\n }\n}\n\n/** Node-CREATION and informational records — outside the cursor namespace whose uniqueness replay\n * ordering rests on. The single predicate both the guard's sides read, so a new event kind is\n * classified once. */\nfunction outsideCursorNamespace(ev: SpawnEvent): boolean {\n return (\n ev.kind === 'spawned' ||\n ev.kind === 'waiting' ||\n ev.kind === 'metered' ||\n ev.kind === 'materialized' ||\n ev.kind === 'execution-bound' ||\n ev.kind === 'edge' ||\n ev.kind === 'trace-unpropagated'\n )\n}\n\n// ── Replay executor (build step 7) ───────────────────────────────────────────────\n\n/**\n * Re-feed a journaled spawn tree in strict `seq` order, rehydrating each settled\n * child's `out` from the blob store by `outRef`, and return the `Settled[]` exactly\n * as `scope.next()` originally delivered them.\n *\n * Determinism (B2): the events are sorted by `seq` BEFORE any blob `get`, so the\n * replay order is the recorded cursor order regardless of how fast each rehydration\n * resolves. `at` (wall-clock) is never a replay input. Fail loud on a tree that was\n * never begun, a settled-done event missing its `outRef`, or a blob the store can't\n * rehydrate — a silent gap would let `act` branch on the wrong evidence.\n *\n * @stable\n */\nexport async function replaySpawnTree(\n journal: SpawnJournal,\n blobs: ResultBlobStore,\n root: NodeId,\n): Promise<Settled<unknown>[]> {\n const events = await journal.loadTree(root)\n if (events === undefined) {\n throw new Error(`replaySpawnTree: no journaled tree for root '${root}'`)\n }\n const ordered = [...events].sort((a, b) => a.seq - b.seq)\n const labels = new Map<NodeId, string>()\n const assignmentIds = new Map<NodeId, string>()\n const identities = new Map<NodeId, NodeExecutionIdentity>()\n const materializations = new Map<NodeId, NodeSnapshot['materialization']>()\n const executionBindings = new Map<\n NodeId,\n NonNullable<NodeSnapshot['executionBindings']>[number][]\n >()\n for (const ev of ordered) {\n if (ev.kind === 'spawned' || ev.kind === 'waiting') labels.set(ev.id, ev.label)\n if (ev.kind === 'spawned' && ev.assignmentId !== undefined) {\n assignmentIds.set(ev.id, ev.assignmentId)\n }\n if (ev.kind === 'spawned' && ev.identity !== undefined) {\n identities.set(ev.id, copyFrozenIdentity(ev.identity))\n }\n if (ev.kind === 'materialized') materializations.set(ev.id, ev.receipt)\n if (ev.kind === 'execution-bound') {\n const bindings = executionBindings.get(ev.id) ?? []\n bindings.push(ev.binding)\n executionBindings.set(ev.id, bindings)\n }\n }\n const handleFor = (id: NodeId, status: NodeStatus) =>\n replayHandle(id, labels.get(id) ?? id, status, {\n assignmentId: assignmentIds.get(id),\n identity: identities.get(id),\n materialization: materializations.get(id),\n executionBindings: executionBindings.get(id),\n })\n const settlementTime = (at: string): { readonly settledAt?: number } => {\n const settledAt = Date.parse(at)\n return Number.isFinite(settledAt) ? { settledAt } : {}\n }\n const settled: Settled<unknown>[] = []\n for (const ev of ordered) {\n if (ev.kind === 'spawned') continue\n if (ev.kind === 'waiting') continue // arms a wait node; `woken` is its settlement\n if (ev.kind === 'metered') continue // a spend record, not a settlement — irrelevant to replay\n if (ev.kind === 'materialized') continue // wire receipt, not a settlement\n if (ev.kind === 'execution-bound') continue // attempt transport, not a settlement\n if (ev.kind === 'edge') continue // edge-ledger observability, not a settlement\n if (ev.kind === 'trace-unpropagated') continue // severed-hop marker, not a settlement\n if (ev.kind === 'woken') {\n // A wait that was cancelled carries no outcome blob — it replays as a `down`, exactly as a\n // cancelled worker does. A fired/timed-out wait rehydrates its `WaitOutcome` and costs zero.\n if (ev.by === 'cancelled' || ev.outRef === undefined) {\n settled.push({\n kind: 'down',\n handle: handleFor(ev.id, 'cancelled'),\n reason: 'wait cancelled',\n infra: false,\n restartCount: 0,\n trace: { status: 'unavailable', reason: 'not-an-executor' },\n ...settlementTime(ev.at),\n seq: ev.seq,\n })\n continue\n }\n const outcome = await blobs.get(ev.outRef)\n if (outcome === undefined) {\n throw new Error(\n `replaySpawnTree: blob store has no wait outcome for outRef '${ev.outRef}' (node '${ev.id}', seq ${ev.seq})`,\n )\n }\n settled.push({\n kind: 'done',\n handle: handleFor(ev.id, 'done'),\n out: outcome,\n outRef: ev.outRef,\n spent: zeroSpend(),\n trace: { status: 'unavailable', reason: 'not-an-executor' },\n ...settlementTime(ev.at),\n seq: ev.seq,\n })\n continue\n }\n if (ev.kind === 'cancelled') {\n settled.push({\n kind: 'down',\n handle: handleFor(ev.id, 'cancelled'),\n reason: ev.reason,\n infra: false,\n restartCount: 0,\n trace: { status: 'unavailable', reason: 'execution-did-not-start' },\n ...settlementTime(ev.at),\n seq: ev.seq,\n })\n continue\n }\n if (ev.status === 'down') {\n const trace = traceEvidenceFor(ev)\n if (trace.status === 'available') await workerTraceAnalysisStore(trace, blobs)\n settled.push({\n kind: 'down',\n handle: handleFor(ev.id, 'failed'),\n // `reason` is written by every current scope. The verdict fallback preserves the\n // pre-field convention and the generic text keeps still-older reasonless journals usable.\n reason: ev.reason ?? ev.verdict?.notes ?? 'child down',\n infra: ev.infra === true,\n restartCount: 0,\n ...(ev.providerModel === undefined\n ? {}\n : { providerModel: copyProviderModelEvidence(ev.providerModel) }),\n trace,\n ...settlementTime(ev.at),\n seq: ev.seq,\n })\n continue\n }\n if (ev.outRef === undefined) {\n throw new Error(\n `replaySpawnTree: settled-done event for '${ev.id}' (seq ${ev.seq}) has no outRef; ` +\n 'cannot rehydrate the result the driver branched on',\n )\n }\n const out = await blobs.get(ev.outRef)\n if (out === undefined) {\n throw new Error(\n `replaySpawnTree: blob store has no artifact for outRef '${ev.outRef}' (node '${ev.id}', seq ${ev.seq})`,\n )\n }\n const trace = traceEvidenceFor(ev)\n if (trace.status === 'available') await workerTraceAnalysisStore(trace, blobs)\n settled.push({\n kind: 'done',\n handle: handleFor(ev.id, 'done'),\n out,\n outRef: ev.outRef,\n verdict: ev.verdict,\n spent: cloneJournalSpend(ev.spent),\n ...(ev.providerModel === undefined\n ? {}\n : { providerModel: copyProviderModelEvidence(ev.providerModel) }),\n trace,\n ...settlementTime(ev.at),\n seq: ev.seq,\n })\n }\n return settled\n}\n\nfunction replayHandle(\n id: NodeId,\n label: string,\n status: NodeStatus,\n evidence: {\n readonly assignmentId?: string\n readonly identity?: NodeExecutionIdentity\n readonly materialization?: NodeSnapshot['materialization']\n readonly executionBindings?: ReadonlyArray<\n NonNullable<NodeSnapshot['executionBindings']>[number]\n >\n } = {},\n) {\n return Object.freeze({\n id,\n label,\n status,\n ...(evidence.assignmentId === undefined ? {} : { assignmentId: evidence.assignmentId }),\n ...(evidence.identity === undefined ? {} : { identity: evidence.identity }),\n ...(evidence.materialization === undefined\n ? {}\n : { materialization: evidence.materialization }),\n ...(evidence.executionBindings === undefined\n ? {}\n : { executionBindings: Object.freeze([...evidence.executionBindings]) }),\n abort() {\n throw new Error(`cannot abort node '${id}': replayed handles are terminal, not live`)\n },\n })\n}\n\n/** A replayed handle must not retain mutable references into the loaded journal event. */\nfunction copyFrozenIdentity(identity: NodeExecutionIdentity): NodeExecutionIdentity {\n const correlation =\n identity.correlation === undefined ? undefined : Object.freeze({ ...identity.correlation })\n return Object.freeze({\n ...(identity.profileDigest === undefined ? {} : { profileDigest: identity.profileDigest }),\n ...(identity.taskDigest === undefined ? {} : { taskDigest: identity.taskDigest }),\n ...(identity.candidateDigest === undefined\n ? {}\n : { candidateDigest: identity.candidateDigest }),\n ...(correlation === undefined ? {} : { correlation }),\n })\n}\n\n/**\n * Materialize a recorded `TreeView` from a journaled event list for inspection. Folds\n * `spawned`/`settled`/`cancelled` into a per-node snapshot in `seq` order, then adds each\n * `metered` event's driver-inference spend onto its node in a separate additive pass so the view\n * matches the recorded cursor. It does not recover live executors or driver state after restart.\n */\nexport function materializeTreeView(events: SpawnEvent[]): TreeView {\n const nodes = new Map<NodeId, MutableSnapshot>()\n let root: NodeId | undefined\n // `spawned` (ordinal namespace) and `settled`/`cancelled` (cursor namespace) carry\n // overlapping `seq` values, so create every node before any update — process spawns in\n // ordinal order, then settlements/cancellations in cursor order. A settle/cancel for an\n // un-spawned node is a corrupted log (fail loud via requireNode).\n const spawns = events\n .filter(\n (ev): ev is Extract<SpawnEvent, { kind: 'spawned' | 'waiting' }> =>\n ev.kind === 'spawned' || ev.kind === 'waiting',\n )\n .sort((a, b) => a.seq - b.seq)\n const settlements = events\n .filter(\n (ev) =>\n ev.kind !== 'spawned' &&\n ev.kind !== 'waiting' &&\n ev.kind !== 'metered' &&\n ev.kind !== 'materialized' &&\n ev.kind !== 'execution-bound' &&\n ev.kind !== 'edge' &&\n ev.kind !== 'trace-unpropagated',\n )\n .sort((a, b) => a.seq - b.seq)\n for (const ev of spawns) {\n if (ev.kind === 'waiting') {\n // An ARMED wait reads `waiting` until a `woken` event lands. That is the whole durability\n // claim: a materialized tree from a journal whose process died mid-wait still shows the wait.\n nodes.set(ev.id, {\n id: ev.id,\n parent: ev.parent,\n label: ev.label,\n status: 'waiting',\n runtime: 'wait',\n budget: { maxIterations: 0, maxTokens: 0 },\n spent: zeroSpend(),\n })\n continue\n }\n if (ev.parent === undefined && root === undefined) root = ev.id\n nodes.set(ev.id, {\n id: ev.id,\n parent: ev.parent,\n label: ev.label,\n status: 'pending',\n runtime: ev.runtime,\n budget: ev.budget,\n ...(ev.ownedTreeRoot === undefined ? {} : { ownedTreeRoot: ev.ownedTreeRoot }),\n ...(ev.assignmentId === undefined ? {} : { assignmentId: ev.assignmentId }),\n ...(ev.identity ? { identity: ev.identity } : {}),\n spent: zeroSpend(),\n })\n }\n for (const ev of settlements) {\n if (ev.kind === 'settled') {\n const node = requireNode(nodes, ev.id)\n node.status = ev.status === 'done' ? 'done' : 'failed'\n node.spent = cloneJournalSpend(ev.spent)\n node.providerModel = copyProviderModelEvidence(ev.providerModel)\n node.outRef = ev.outRef\n node.trace = traceEvidenceFor(ev)\n const settledAt = Date.parse(ev.at)\n if (Number.isFinite(settledAt)) node.settledAt = settledAt\n } else if (ev.kind === 'woken') {\n const node = requireNode(nodes, ev.id)\n node.status = ev.by === 'cancelled' ? 'cancelled' : 'done'\n node.outRef = ev.outRef\n node.trace = { status: 'unavailable', reason: 'not-an-executor' }\n const settledAt = Date.parse(ev.at)\n if (Number.isFinite(settledAt)) node.settledAt = settledAt\n } else {\n const node = requireNode(nodes, ev.id)\n node.status = 'cancelled'\n node.trace = { status: 'unavailable', reason: 'execution-did-not-start' }\n const settledAt = Date.parse(ev.at)\n if (Number.isFinite(settledAt)) node.settledAt = settledAt\n }\n }\n // Materialization is node evidence, not a settlement. Fold it after node creation and before\n // freezing the view; exactly one receipt per node is enforced by the journal corruption guard.\n for (const ev of events) {\n if (ev.kind !== 'materialized') continue\n const node = requireNode(nodes, ev.id)\n node.materialization = ev.receipt\n node.runtime = ev.receipt.runtime\n }\n for (const ev of events) {\n if (ev.kind !== 'execution-bound') continue\n const node = requireNode(nodes, ev.id)\n node.executionBindings ??= []\n node.executionBindings.push(ev.binding)\n }\n // Driver inference: a separate pass so it accumulates ONTO the settled child-work base (no\n // dependence on metered-vs-settled seq order) without touching node status.\n for (const ev of events) {\n if (ev.kind !== 'metered') continue\n const node = requireNode(nodes, ev.id)\n node.spent = addJournalSpend(node.spent, ev.spend)\n }\n const snapshots = [...nodes.values()].map(freezeSnapshot)\n return {\n root: root ?? snapshots[0]?.id ?? '',\n nodes: snapshots,\n inFlight: snapshots.filter((n) => n.status === 'running' || n.status === 'acquiring').length,\n waiting: snapshots.filter((n) => n.status === 'waiting').length,\n }\n}\n\n/**\n * The waits a journaled tree shows as ARMED but never woken — what a resumed run re-arms with the\n * ORIGINAL absolute deadline. Reading it from the journal (rather than from any live state) is\n * what makes \"SIGKILL a waiting tree, a new process keeps waiting to the same instant\" true.\n */\nexport function pendingWaits(events: SpawnEvent[]): PendingWait[] {\n const woken = new Set<NodeId>()\n for (const ev of events) if (ev.kind === 'woken') woken.add(ev.id)\n const pending: PendingWait[] = []\n for (const ev of events) {\n if (ev.kind !== 'waiting' || woken.has(ev.id)) continue\n pending.push({\n id: ev.id,\n label: ev.label,\n spec: ev.spec,\n armedAt: ev.armedAt,\n ordinal: ev.seq,\n })\n }\n return pending.sort((a, b) => a.ordinal - b.ordinal)\n}\n\ninterface MutableSnapshot {\n id: NodeId\n parent?: NodeId\n label: string\n status: NodeStatus\n runtime: Runtime\n budget: NodeSnapshot['budget']\n ownedTreeRoot?: NodeSnapshot['ownedTreeRoot']\n assignmentId?: string\n identity?: NodeSnapshot['identity']\n materialization?: NodeSnapshot['materialization']\n executionBindings?: NonNullable<NodeSnapshot['executionBindings']>[number][]\n spent: Spend\n providerModel?: NodeSnapshot['providerModel']\n outRef?: string\n trace?: NodeSnapshot['trace']\n settledAt?: number\n}\n\nfunction zeroSpend(): Spend {\n return { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n}\n\n/** Copy a durable spend into a read model without dropping cache completeness. */\nfunction cloneJournalSpend(spend: Spend): Spend {\n return {\n iterations: spend.iterations,\n tokens: cloneTokenUsage(spend.tokens),\n ...(spend.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: spend.usd,\n ...(spend.usdKnown === false ? { usdKnown: false } : {}),\n ms: spend.ms,\n }\n}\n\n/** Copy provider evidence at the journal boundary so replay never exposes mutable event state. */\nfunction copyProviderModelEvidence(\n evidence: NodeSnapshot['providerModel'],\n): NodeSnapshot['providerModel'] {\n if (evidence === undefined) return undefined\n const attempts = Object.freeze(\n evidence.attempts.map((attempt) =>\n Object.freeze({\n observations: Object.freeze([...attempt.observations]),\n ...(attempt.identityConflict ? { identityConflict: true } : {}),\n ...(attempt.providerDispatch === 'not_started'\n ? { providerDispatch: 'not_started' as const }\n : {}),\n }),\n ),\n )\n const models = Object.freeze([...evidence.models])\n return Object.freeze(\n evidence.status === 'unknown'\n ? { status: 'unknown' as const, attempts, models, reason: evidence.reason }\n : { status: 'known' as const, attempts, models },\n )\n}\n\n/** Add a `metered` spend record onto a node's accumulated spend (per channel). */\nfunction addJournalSpend(a: Spend, b: Spend): Spend {\n return {\n iterations: a.iterations + b.iterations,\n tokens: (() => {\n const tokens = cloneTokenUsage(a.tokens)\n addTokenUsage(tokens, b.tokens)\n return tokens\n })(),\n ...(a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: a.usd + b.usd,\n ...(a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {}),\n ms: a.ms + b.ms,\n }\n}\n\nfunction requireNode(nodes: Map<NodeId, MutableSnapshot>, id: NodeId): MutableSnapshot {\n const node = nodes.get(id)\n if (!node) {\n throw new Error(`spawn journal corrupted: settle/cancel for node '${id}' with no prior spawn`)\n }\n return node\n}\n\nfunction freezeSnapshot(node: MutableSnapshot): NodeSnapshot {\n return {\n id: node.id,\n parent: node.parent,\n label: node.label,\n status: node.status,\n runtime: node.runtime,\n budget: node.budget,\n ownedTreeRoot: node.ownedTreeRoot,\n assignmentId: node.assignmentId,\n identity: node.identity,\n materialization: node.materialization,\n executionBindings:\n node.executionBindings === undefined ? undefined : Object.freeze([...node.executionBindings]),\n spent: node.spent,\n providerModel: node.providerModel,\n outRef: node.outRef,\n trace: node.trace,\n settledAt: node.settledAt,\n }\n}\n\nfunction traceEvidenceFor(\n event: Extract<SpawnEvent, { kind: 'settled' }>,\n): NonNullable<NodeSnapshot['trace']> {\n return (\n event.trace ?? {\n status: 'unavailable',\n reason: 'legacy-settlement-without-trace-evidence',\n }\n )\n}\n\nfunction isNoEntError(err: unknown): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n 'code' in err &&\n (err as { code: unknown }).code === 'ENOENT'\n )\n}\n"],"mappings":";;;;;;;AAGA,SAAgB,eAAe,UAA2B;CAExD,OAAO,UADK,WAAW,QAAQ,CAAC,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,aAAa,SAAS,EAAE,aAAa,QAAQ,EAAE,UAAU,MAAM,IAAI,CAAC;EAC1E,IAAI,EAAE,KAAK,EAAE;CACf;AACF;AAEA,SAAS,YAAY,OAAqC,IAA6B;CACrF,MAAM,OAAO,MAAM,IAAI,EAAE;CACzB,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,oDAAoD,GAAG,sBAAsB;CAE/F,OAAO;AACT;AAEA,SAAS,eAAe,MAAqC;CAC3D,OAAO;EACL,IAAI,KAAK;EACT,QAAQ,KAAK;EACb,OAAO,KAAK;EACZ,QAAQ,KAAK;EACb,SAAS,KAAK;EACd,QAAQ,KAAK;EACb,eAAe,KAAK;EACpB,cAAc,KAAK;EACnB,UAAU,KAAK;EACf,iBAAiB,KAAK;EACtB,mBACE,KAAK,sBAAsB,KAAA,IAAY,KAAA,IAAY,OAAO,OAAO,CAAC,GAAG,KAAK,iBAAiB,CAAC;EAC9F,OAAO,KAAK;EACZ,eAAe,KAAK;EACpB,QAAQ,KAAK;EACb,OAAO,KAAK;EACZ,WAAW,KAAK;CAClB;AACF;AAEA,SAAS,iBACP,OACoC;CACpC,OACE,MAAM,SAAS;EACb,QAAQ;EACR,QAAQ;CACV;AAEJ;AAEA,SAAS,aAAa,KAAuB;CAC3C,OACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACT,IAA0B,SAAS;AAExC"}
@@ -1,5 +1,5 @@
1
1
  import { J as AgentTaskStatus, Y as BackendErrorDetail, it as RuntimeStreamEvent } from "./types-6zHo67jn.js";
2
- import { d as ExecutorFactory } from "./types-DJ7k6vHE.js";
2
+ import { d as ExecutorFactory } from "./types-D4BfurNs.js";
3
3
  import { AgentProfile } from "@tangle-network/agent-interface";
4
4
  import { PromptOptions, SandboxEvent, SandboxInstance } from "@tangle-network/sandbox";
5
5
  //#region src/runtime/stream-agent-turn.d.ts
@@ -125,4 +125,4 @@ declare function streamAgentTurn(backend: AgentTurnBackend, input: AgentTurnInpu
125
125
  declare function collectAgentTurn(stream: AsyncIterable<RuntimeStreamEvent>): Promise<CollectedAgentTurn>;
126
126
  //#endregion
127
127
  export { StreamAgentTurnOptions as a, CollectedAgentTurn as i, AgentTurnInput as n, collectAgentTurn as o, AgentTurnUsage as r, streamAgentTurn as s, AgentTurnBackend as t };
128
- //# sourceMappingURL=stream-agent-turn-NFWCv1X1.d.ts.map
128
+ //# sourceMappingURL=stream-agent-turn-CJog3ebs.d.ts.map
@@ -1,7 +1,7 @@
1
- import { d as SessionMismatchError, f as ValidationError, r as BackendTransportError } from "./errors-DRoXIc7E.js";
1
+ import { d as SessionMismatchError, f as ValidationError, r as BackendTransportError } from "./errors-CVIDr7GQ.js";
2
2
  import { i as mapSandboxToolEvent, r as mapSandboxEvent, t as createSandboxToolPartState } from "./sandbox-events-vIwmuPdl.js";
3
- import { c as profileProviderModel, i as concreteModelId, o as profileBridgeWireModel } from "./model-policy-Bv1DU2fw.js";
4
- import { C as unknownMaterializationReceipt, S as unknownExecutionBindingReceipt, _ as runtimeOwnedExecutorExecutionBinding, a as authoredProfileDigest, b as runtimeOwnedPendingExecutorMaterialization, c as knownExecutionBindingReceipt, l as knownMaterializationReceipt, v as runtimeOwnedExecutorMaterialization, w as executableAgentProfileSnapshot } from "./materialization-D2bdTfkK.js";
3
+ import { c as profileProviderModel, i as concreteModelId, o as profileBridgeWireModel } from "./model-policy-UTTc9Z-A.js";
4
+ import { C as unknownExecutionBindingReceipt, T as executableAgentProfileSnapshot, a as authoredProfileDigest, c as knownExecutionBindingReceipt, l as knownMaterializationReceipt, v as runtimeOwnedExecutorExecutionBinding, w as unknownMaterializationReceipt, x as runtimeOwnedPendingExecutorMaterialization, y as runtimeOwnedExecutorMaterialization } from "./materialization-BP5zspr2.js";
5
5
  import { scoreKnowledgeReadiness } from "@tangle-network/agent-eval";
6
6
  import { canonicalCandidateDigest } from "@tangle-network/agent-interface";
7
7
  //#region src/sessions.ts
@@ -907,4 +907,4 @@ function deriveTurnSignal(callerSignal, timeoutMs) {
907
907
  //#endregion
908
908
  export { normalizeBackendStreamEvent as a, nowIso as c, createSandboxPromptBackend as i, startOrResumeRuntimeSession as l, streamAgentTurn as n, InMemoryRuntimeSessionStore as o, createIterableBackend as r, newRuntimeSession as s, collectAgentTurn as t, touchSession as u };
909
909
 
910
- //# sourceMappingURL=stream-agent-turn-D8YHY0oO.js.map
910
+ //# sourceMappingURL=stream-agent-turn-CdIcf-bn.js.map