@tangle-network/agent-runtime 0.338.0 → 0.340.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.
Files changed (144) hide show
  1. package/dist/{activation-kbkAuSmY.js → activation-D2PVljaw.js} +5 -18
  2. package/dist/{activation-kbkAuSmY.js.map → activation-D2PVljaw.js.map} +1 -1
  3. package/dist/{activation-CsbNax2X.d.ts → activation-DGDl4wwI.d.ts} +4 -24
  4. package/dist/agent.d.ts +4 -18
  5. package/dist/agent.js +3 -21
  6. package/dist/agent.js.map +1 -1
  7. package/dist/analyst-loop.d.ts +2 -2
  8. package/dist/{bundle-DM60AI2B.js → bundle-DNUq-OPW.js} +2 -2
  9. package/dist/{bundle-DM60AI2B.js.map → bundle-DNUq-OPW.js.map} +1 -1
  10. package/dist/candidate-execution/index.d.ts +4 -101
  11. package/dist/candidate-execution/index.js +10 -395
  12. package/dist/candidate-execution/index.js.map +1 -1
  13. package/dist/{delegate-Se1YZKMb.js → delegate-CtJIS-tp.js} +2 -2
  14. package/dist/{delegate-Se1YZKMb.js.map → delegate-CtJIS-tp.js.map} +1 -1
  15. package/dist/{driver-control-acknowledgers-T2a1Ouay.js → driver-control-acknowledgers-MTrs8HAF.js} +15 -11
  16. package/dist/driver-control-acknowledgers-MTrs8HAF.js.map +1 -0
  17. package/dist/{durable-file-B_eJr6Mb.js → durable-file-gNI9ILAn.js} +1 -3
  18. package/dist/durable-file-gNI9ILAn.js.map +1 -0
  19. package/dist/durable.d.ts +3 -35
  20. package/dist/durable.js +10 -10
  21. package/dist/durable.js.map +1 -1
  22. package/dist/{graph-CY0wH838.js → graph-DfWqp_1e.js} +4 -4
  23. package/dist/graph-DfWqp_1e.js.map +1 -0
  24. package/dist/{graph-registry-By0tUj4S.js → graph-registry-BnO64cn8.js} +3 -3
  25. package/dist/{graph-registry-By0tUj4S.js.map → graph-registry-BnO64cn8.js.map} +1 -1
  26. package/dist/{improve-CWGBT13K.js → improve-CKRVQqzt.js} +8 -35
  27. package/dist/improve-CKRVQqzt.js.map +1 -0
  28. package/dist/{improvement-adapter-D5gwwoXQ.d.ts → improvement-adapter-sIthWkcN.d.ts} +3 -21
  29. package/dist/index.d.ts +10 -215
  30. package/dist/index.js +91 -302
  31. package/dist/index.js.map +1 -1
  32. package/dist/intelligence.d.ts +11 -143
  33. package/dist/intelligence.js +7 -81
  34. package/dist/intelligence.js.map +1 -1
  35. package/dist/{jsonl-file-DBv31uPi.js → jsonl-file-C9Kde_0Z.js} +2 -2
  36. package/dist/{jsonl-file-DBv31uPi.js.map → jsonl-file-C9Kde_0Z.js.map} +1 -1
  37. package/dist/kernel.d.ts +4 -3
  38. package/dist/kernel.js +12 -14
  39. package/dist/loop-runner-C4EWEcXf.d.ts +32 -0
  40. package/dist/loop-runner-DNWbTcVm.js +59 -0
  41. package/dist/loop-runner-DNWbTcVm.js.map +1 -0
  42. package/dist/loop-runner-bin.d.ts +32 -2
  43. package/dist/loop-runner-bin.js +93 -1
  44. package/dist/loop-runner-bin.js.map +1 -0
  45. package/dist/mcp/bin.js +3 -3
  46. package/dist/mcp/index.d.ts +99 -418
  47. package/dist/mcp/index.js +121 -203
  48. package/dist/mcp/index.js.map +1 -1
  49. package/dist/mcp/memory-bin.js +231 -1
  50. package/dist/mcp/memory-bin.js.map +1 -1
  51. package/dist/model-policy-CyCUwHed.js.map +1 -1
  52. package/dist/placement.d.ts +2 -33
  53. package/dist/placement.js +1 -35
  54. package/dist/placement.js.map +1 -1
  55. package/dist/platform.d.ts +188 -1
  56. package/dist/platform.js +129 -1
  57. package/dist/platform.js.map +1 -1
  58. package/dist/{prepare-Bt0IouPq.js → prepare-FzJoS68l.js} +8 -160
  59. package/dist/prepare-FzJoS68l.js.map +1 -0
  60. package/dist/{profile-Do-5xO_D.js → profile-DToH0XEs.js} +2 -2
  61. package/dist/profile-DToH0XEs.js.map +1 -0
  62. package/dist/profile-materialization-bPm0gGLO.d.ts +49 -0
  63. package/dist/profiles.d.ts +2 -2
  64. package/dist/profiles.js +3 -40
  65. package/dist/profiles.js.map +1 -1
  66. package/dist/{protected-model-port-DGxQ8_YM.d.ts → protected-model-port-DVVh-hEk.d.ts} +3 -33
  67. package/dist/protected-redaction-DFCeo4vg.js.map +1 -1
  68. package/dist/{provision-supervisor-0jMufp4h.js → provision-supervisor-DqvWXmAE.js} +6 -6
  69. package/dist/{provision-supervisor-0jMufp4h.js.map → provision-supervisor-DqvWXmAE.js.map} +1 -1
  70. package/dist/{run-cancellation-BoW5Sg9Y.js → run-cancellation-C9oL62sW.js} +3 -7
  71. package/dist/{run-cancellation-BoW5Sg9Y.js.map → run-cancellation-C9oL62sW.js.map} +1 -1
  72. package/dist/{runtime-D37zRSs7.js → runtime-C55Zgo1R.js} +2531 -2889
  73. package/dist/runtime-C55Zgo1R.js.map +1 -0
  74. package/dist/{runtime-hooks-Bj6wJHlH.d.ts → runtime-hooks-nsqxSUFL.d.ts} +2 -6
  75. package/dist/{sandbox-profile-compat-xSoVtdWw.js → sandbox-profile-compat-DRr3JwDx.js} +2 -4
  76. package/dist/sandbox-profile-compat-DRr3JwDx.js.map +1 -0
  77. package/dist/{search-executor-DmgUm5p7.js → search-executor-ChOlRBgg.js} +3 -3
  78. package/dist/search-executor-ChOlRBgg.js.map +1 -0
  79. package/dist/{server-DQHJszfk.js → server-DkVBSN_S.js} +362 -67
  80. package/dist/server-DkVBSN_S.js.map +1 -0
  81. package/dist/{structural-rollout-DAvIE8mw.js → structural-rollout-C1LEk_zq.js} +80 -80
  82. package/dist/structural-rollout-C1LEk_zq.js.map +1 -0
  83. package/dist/{substrate-B0TYNrXn.js → substrate-CGDFTSRh.js} +2 -9
  84. package/dist/substrate-CGDFTSRh.js.map +1 -0
  85. package/dist/{supervise-WuPAwfPh.js → supervise-CaUAxZZP.js} +92 -75
  86. package/dist/supervise-CaUAxZZP.js.map +1 -0
  87. package/dist/{supervisor-CPG1I9UN.js → supervisor-VXuN2OHT.js} +205 -319
  88. package/dist/supervisor-VXuN2OHT.js.map +1 -0
  89. package/dist/testing.d.ts +2 -2
  90. package/dist/testing.js +13 -13
  91. package/dist/testing.js.map +1 -1
  92. package/dist/tool-loop.d.ts +1 -1
  93. package/dist/{tool-server-Dqer2M4_.js → tool-server-XV4aJwoQ.js} +2 -2
  94. package/dist/tool-server-XV4aJwoQ.js.map +1 -0
  95. package/dist/top-snapshot-CbZE1JsU.js +502 -0
  96. package/dist/top-snapshot-CbZE1JsU.js.map +1 -0
  97. package/dist/tui/bin.js +711 -1
  98. package/dist/tui/bin.js.map +1 -1
  99. package/dist/tui/index.d.ts +2 -70
  100. package/dist/tui/index.js +3 -3
  101. package/dist/{types-zWfqDjeL.d.ts → types-Cwrea-bU.d.ts} +2 -17
  102. package/dist/{types-CrNWif8-.d.ts → types-DZ6L0Bv3.d.ts} +765 -2152
  103. package/dist/workspace-store/index.d.ts +1 -107
  104. package/dist/workspace-store/index.js +1 -415
  105. package/dist/workspace-store/index.js.map +1 -1
  106. package/dist/{workspace-streams-BZZds1Fw.d.ts → workspace-streams-BiS4ABah.d.ts} +3 -18
  107. package/package.json +1 -1
  108. package/skills/agent-graphs/references/authoring.md +3 -2
  109. package/dist/coder-yhVWbdWc.js +0 -40
  110. package/dist/coder-yhVWbdWc.js.map +0 -1
  111. package/dist/delegation-status-CF4D0NZ_.js +0 -358
  112. package/dist/delegation-status-CF4D0NZ_.js.map +0 -1
  113. package/dist/driver-control-acknowledgers-T2a1Ouay.js.map +0 -1
  114. package/dist/durable-file-B_eJr6Mb.js.map +0 -1
  115. package/dist/graph-CY0wH838.js.map +0 -1
  116. package/dist/improve-CWGBT13K.js.map +0 -1
  117. package/dist/integrations-6xttbPi9.d.ts +0 -190
  118. package/dist/integrations-dFi-ALk7.js +0 -132
  119. package/dist/integrations-dFi-ALk7.js.map +0 -1
  120. package/dist/kb-gate-C8z2juK8.d.ts +0 -80
  121. package/dist/kb-gate-DpaSwXVx.js +0 -80
  122. package/dist/kb-gate-DpaSwXVx.js.map +0 -1
  123. package/dist/loop-runner-bin-CFnrAHpl.d.ts +0 -164
  124. package/dist/loop-runner-bin-CdPlhy9g.js +0 -246
  125. package/dist/loop-runner-bin-CdPlhy9g.js.map +0 -1
  126. package/dist/memory-server-DXQ8IxGR.js +0 -234
  127. package/dist/memory-server-DXQ8IxGR.js.map +0 -1
  128. package/dist/openai-tools-DoQ32vpe.js +0 -44
  129. package/dist/openai-tools-DoQ32vpe.js.map +0 -1
  130. package/dist/openai-tools-zh2I_uD7.d.ts +0 -24
  131. package/dist/prepare-Bt0IouPq.js.map +0 -1
  132. package/dist/profile-Do-5xO_D.js.map +0 -1
  133. package/dist/profile-materialization-BnoEf1co.d.ts +0 -96
  134. package/dist/runtime-D37zRSs7.js.map +0 -1
  135. package/dist/sandbox-profile-compat-xSoVtdWw.js.map +0 -1
  136. package/dist/search-executor-DmgUm5p7.js.map +0 -1
  137. package/dist/server-DQHJszfk.js.map +0 -1
  138. package/dist/structural-rollout-DAvIE8mw.js.map +0 -1
  139. package/dist/substrate-B0TYNrXn.js.map +0 -1
  140. package/dist/supervise-WuPAwfPh.js.map +0 -1
  141. package/dist/supervisor-CPG1I9UN.js.map +0 -1
  142. package/dist/tool-server-Dqer2M4_.js.map +0 -1
  143. package/dist/top-app-C55Wa7uy.js +0 -1214
  144. package/dist/top-app-C55Wa7uy.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"driver-control-acknowledgers-MTrs8HAF.js","names":[],"sources":["../src/mcp/tools/spawn-resource-paths.ts","../src/runtime/supervise/coordination-log.ts","../src/runtime/supervise/run-context.ts","../src/mcp/tools/coordination-events.ts","../src/runtime/supervise/event-bus.ts","../src/mcp/tools/coordination-analysts.ts","../src/mcp/tools/coordination-json.ts","../src/mcp/tools/coordination-analysis.ts","../src/mcp/tools/coordination-input.ts","../src/mcp/tools/coordination-worker-argument.ts","../src/mcp/tools/coordination-analyst-tools.ts","../src/mcp/tools/coordination-tool-timeout.ts","../src/mcp/tools/coordination-audit-tools.ts","../src/mcp/tools/coordination-completion-refusal.ts","../src/mcp/tools/coordination-down-messages.ts","../src/mcp/tools/coordination-event-projection.ts","../src/mcp/tools/coordination-budget.ts","../src/mcp/tools/coordination-graph-tools.ts","../src/mcp/tools/coordination-journal-reader.ts","../src/mcp/tools/coordination-manager-reentry.ts","../src/mcp/tools/coordination-runtime-spawn.ts","../src/mcp/tools/coordination-map-routing.ts","../src/mcp/tools/coordination-question-ledger.ts","../src/mcp/tools/coordination-messages.ts","../src/mcp/tools/coordination-questions.ts","../src/mcp/tools/coordination-question-tools.ts","../src/mcp/tools/coordination-route-routing.ts","../src/mcp/tools/coordination-settlement-drain.ts","../src/mcp/tools/coordination-budget-override.ts","../src/mcp/tools/coordination-model-attribution.ts","../src/mcp/tools/coordination-spawn-admission.ts","../src/runtime/supervise/detector-monitor.ts","../src/mcp/tools/coordination-worker-observation.ts","../src/mcp/tools/coordination-worker-settlement.ts","../src/mcp/tools/coordination-profile-schema.ts","../src/mcp/tools/worker-output.ts","../src/mcp/tools/coordination-worker-tools.ts","../src/mcp/tools/coordination-manager.ts","../src/runtime/supervise/driver-control-acknowledgers.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport { type FileHandle, open, realpath, stat } from 'node:fs/promises'\nimport { isAbsolute, relative, resolve, sep } from 'node:path'\nimport { isRecord } from '../../record-value'\n\n/**\n * Inline resources a manager hands a child by PATH instead of by content.\n *\n * The canonical profile schema knows two resource kinds, `inline` (a content string) and `github`.\n * A manager that wants a child to receive a data file therefore had one way to do it: emit the\n * bytes inside its own `spawn` tool call. That is a transcription by a language model, and it does\n * not survive size. Measured 2026-09-12 (discovery-lab `mech-interp-foundations-glm2-b-20260912b`):\n * a 29,144-character base64 payload on the manager's disk reached three children as 15,928\n * characters with 11 substitutions, and a fourth child received the literal placeholder the\n * manager meant to replace. Seven blind-check attempts across two runs delivered no data.\n *\n * `{ kind: 'inline', name, path }` lets the coordination server be the transport: it reads the\n * file from the manager's workspace, fills `content`, and the profile that reaches the schema,\n * the journal, and the provider is an ordinary inline resource. Nothing downstream changes; the\n * model's output stops carrying the bytes.\n *\n * Where the bytes come from is a {@link SpawnResourceReader}, and there are two:\n * - a HOST DIRECTORY, for a manager whose driver runs on this host (a loopback bridge with a\n * `cwd`), read through the descriptor-identity checks below;\n * - the manager's OWN EXECUTION ENVIRONMENT, for a manager inside a provider sandbox, read\n * through the environment's `read()`. The coordination server cannot see a sandbox filesystem,\n * but the provider that created the sandbox can, and it is already in hand.\n *\n * The second reader exists because the first one's absence was not a refusal a manager could\n * work around. Measured 2026-09-17 (discovery-lab `mech-interp-foundations-sandbox-a-20260917h`):\n * a sandbox-rooted director, refused by path, fell back to emitting its files as content and got\n * 5 characters wrong in 24,008, destroying 3 of 7 files including its instrument and both\n * drivers. At that rate 20 KB of mounts all arrive intact about 2% of the time, and gzip makes it\n * worse by turning one wrong character into total loss. Four consecutive runs in that lane lost\n * their research children to this. There is no encoding that fixes a transcription channel; the\n * only fix is a channel with no model in it.\n *\n * Fail-closed rules, each with the reason a manager needs to fix its call:\n * - no reader available → refused (neither a host directory nor an environment with `read`)\n * - absolute path or `..` escape → refused by both readers; a symlink that resolves outside the\n * root → refused by the host reader (the environment reader delegates containment to the\n * provider, which serves only the sandbox's own workspace)\n * - not a regular file → refused\n * - over {@link SPAWN_RESOURCE_PATH_MAX_BYTES} → refused naming the bound\n * - bytes that are not valid UTF-8 → refused; `content` is a string, so binary data is encoded\n * (base64) by the manager first, exactly as it would be for a content resource\n */\nexport const SPAWN_RESOURCE_PATH_MAX_BYTES = 4 * 1024 * 1024\n\n/** One successful read: the bytes as a string plus the identity the journal records. */\nexport interface SpawnResourceBytes {\n readonly content: string\n readonly byteLength: number\n readonly sha256: string\n}\n\nexport type SpawnResourceRead =\n | ({ readonly ok: true } & SpawnResourceBytes)\n | { readonly ok: false; readonly reason: string }\n\n/**\n * Where a by-path resource's bytes come from. `describe` names the source in a refusal so a\n * manager reading \"path X does not exist under the workspace root\" and \"path X: sandbox read\n * failed\" can tell which filesystem was consulted.\n */\nexport interface SpawnResourceReader {\n readonly describe: string\n read(path: string): Promise<SpawnResourceRead>\n}\n\n/** The host-directory reader: a manager whose workspace is a directory this process can open. */\nexport function hostDirectoryReader(root: string): SpawnResourceReader {\n return {\n describe: `workspace root ${root}`,\n read: (requested) => readUnderRoot(root, requested),\n }\n}\n\n/**\n * The environment reader: a manager running inside a provider environment whose `read()` serves\n * its own workspace. The provider owns containment — it will not serve a path outside the box —\n * but the relative-path and `..` rules are enforced here too, so the refusal names the rule the\n * manager broke rather than whatever the provider says about an escape it declined.\n *\n * `read()` returns a string, so an environment cannot hand back bytes that are not UTF-8; the\n * provider has already decoded. The size bound is checked on what arrives.\n */\nexport function environmentReader(environment: {\n readonly id: string\n read(path: string): Promise<string>\n}): SpawnResourceReader {\n return {\n describe: `environment ${environment.id}`,\n async read(requested) {\n if (requested.length === 0) return { ok: false, reason: 'path is empty' }\n if (isAbsolute(requested)) {\n return {\n ok: false,\n reason: `path must be relative to the manager's workspace, not absolute (${requested})`,\n }\n }\n if (requested.split(/[\\\\/]/u).includes('..')) {\n return { ok: false, reason: `path ${requested} leaves the manager's workspace` }\n }\n let content: string\n try {\n content = await environment.read(requested)\n } catch (error) {\n return {\n ok: false,\n reason: `path ${requested}: ${describe(error)} (read from environment ${environment.id})`,\n }\n }\n const bytes = Buffer.from(content, 'utf8')\n if (bytes.length > SPAWN_RESOURCE_PATH_MAX_BYTES) {\n return {\n ok: false,\n reason: `path ${requested} is ${bytes.length} bytes; an inline resource is at most ${SPAWN_RESOURCE_PATH_MAX_BYTES} bytes`,\n }\n }\n return {\n ok: true,\n content,\n byteLength: bytes.length,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n }\n },\n }\n}\n\nexport interface ResolvedSpawnResourcePath {\n /** The `resources` location, e.g. `files[0].resource` or `skills[2]`. */\n readonly at: string\n /** The path as the manager wrote it. */\n readonly path: string\n readonly byteLength: number\n readonly sha256: string\n}\n\nexport type ResolveSpawnResourcePathsResult =\n | {\n readonly ok: true\n readonly profile: unknown\n readonly resolved: readonly ResolvedSpawnResourcePath[]\n }\n | { readonly ok: false; readonly at: string; readonly reason: string }\n\ninterface PathInlineRef {\n readonly kind: 'inline'\n readonly name: string\n readonly path: string\n}\n\n/** An inline ref that names a path and carries no content. Anything else is left untouched so the\n * canonical schema keeps its verdict on it. */\nfunction pathInlineRef(value: unknown): PathInlineRef | undefined {\n if (!isRecord(value)) return undefined\n if (value.kind !== 'inline' || value.content !== undefined) return undefined\n if (typeof value.path !== 'string' || typeof value.name !== 'string') return undefined\n return { kind: 'inline', name: value.name, path: value.path }\n}\n\nasync function readUnderRoot(root: string, requested: string): Promise<SpawnResourceRead> {\n if (requested.length === 0) return { ok: false, reason: 'path is empty' }\n if (isAbsolute(requested)) {\n return {\n ok: false,\n reason: `path must be relative to the workspace root, not absolute (${requested})`,\n }\n }\n const rootReal = await realpath(root).catch(() => undefined)\n if (rootReal === undefined) return { ok: false, reason: `workspace root ${root} does not exist` }\n const candidate = resolve(rootReal, requested)\n if (!inside(rootReal, candidate)) {\n return { ok: false, reason: `path ${requested} leaves the workspace root` }\n }\n // Open first, then judge the OPENED file. A containment check on a path alone can be raced: the\n // manager's workspace is live (a background process of its own can rename a directory and put a\n // symlink in its place between the check and the read), so the descriptor's identity is what the\n // verdict is about. The in-root real path must name the same inode the descriptor holds, and the\n // bytes are read from the descriptor, never from the path.\n let handle: FileHandle\n try {\n handle = await open(candidate, 'r')\n } catch (error) {\n return { ok: false, reason: `path ${requested}: ${describe(error)}` }\n }\n try {\n const info = await handle.stat()\n if (!info.isFile()) return { ok: false, reason: `path ${requested} is not a regular file` }\n const real = await realpath(candidate).catch(() => undefined)\n if (real === undefined || !inside(rootReal, real)) {\n return { ok: false, reason: `path ${requested} resolves outside the workspace root` }\n }\n const named = await stat(real).catch(() => undefined)\n if (named === undefined || named.dev !== info.dev || named.ino !== info.ino) {\n return {\n ok: false,\n reason: `path ${requested} changed while it was being read; retry the spawn`,\n }\n }\n if (info.size > SPAWN_RESOURCE_PATH_MAX_BYTES) {\n return {\n ok: false,\n reason: `path ${requested} is ${info.size} bytes; an inline resource is at most ${SPAWN_RESOURCE_PATH_MAX_BYTES} bytes`,\n }\n }\n const bytes = await handle.readFile()\n if (bytes.length > SPAWN_RESOURCE_PATH_MAX_BYTES) {\n return {\n ok: false,\n reason: `path ${requested} is ${bytes.length} bytes; an inline resource is at most ${SPAWN_RESOURCE_PATH_MAX_BYTES} bytes`,\n }\n }\n const content = bytes.toString('utf8')\n if (!Buffer.from(content, 'utf8').equals(bytes)) {\n return {\n ok: false,\n reason: `path ${requested} is not valid UTF-8; encode binary data (base64) before handing it to a child`,\n }\n }\n return {\n ok: true,\n content,\n byteLength: bytes.length,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n }\n } catch (error) {\n return { ok: false, reason: `path ${requested}: ${describe(error)}` }\n } finally {\n await handle.close().catch(() => undefined)\n }\n}\n\n/** `target` is `rootReal` itself or strictly below it; both must already be absolute. */\nfunction inside(rootReal: string, target: string): boolean {\n const rel = relative(rootReal, target)\n return rel !== '' && !rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel)\n}\n\nfunction describe(error: unknown): string {\n const code = (error as { code?: unknown } | null)?.code\n if (code === 'ENOENT') return 'does not exist under the workspace root'\n if (code === 'EACCES' || code === 'EPERM') return 'is not readable by the runtime process'\n if (code === 'EISDIR') return 'is not a regular file'\n return error instanceof Error ? error.message : String(error)\n}\n\n/**\n * Replace every `{ kind: 'inline', name, path }` under `profile.resources` with the inline\n * resource its bytes make. Returns the profile unchanged (same reference) when nothing names a\n * path, so callers pay nothing on the common case.\n *\n * `source` is a host directory (a string, kept for the existing call sites), a\n * {@link SpawnResourceReader}, or `undefined` when the manager has neither — in which case a path\n * is refused with the reason and what to do instead.\n */\nexport async function resolveSpawnResourcePaths(\n profile: unknown,\n source: string | SpawnResourceReader | undefined,\n): Promise<ResolveSpawnResourcePathsResult> {\n if (!isRecord(profile) || !isRecord(profile.resources)) return { ok: true, profile, resolved: [] }\n const reader = typeof source === 'string' ? hostDirectoryReader(source) : source\n const resources = profile.resources\n const resolved: ResolvedSpawnResourcePath[] = []\n let touched = false\n const next: Record<string, unknown> = { ...resources }\n\n const substitute = async (\n at: string,\n ref: PathInlineRef,\n ): Promise<{ kind: 'inline'; name: string; content: string } | { error: string }> => {\n if (reader === undefined) {\n return {\n // Keep \"no workspace root\": discovery-lab's failure catalog and its director prompts match\n // that phrase, and a reworded refusal would silently stop being recognised downstream.\n error:\n 'this manager has no workspace root the coordination server may read (no host directory and no environment with read), so a resource by path cannot be resolved; pass content, or a github resource',\n }\n }\n const read = await reader.read(ref.path)\n if (!read.ok) return { error: read.reason }\n resolved.push({ at, path: ref.path, byteLength: read.byteLength, sha256: read.sha256 })\n touched = true\n return { kind: 'inline', name: ref.name, content: read.content }\n }\n\n for (const list of ['tools', 'skills', 'agents'] as const) {\n const entries = resources[list]\n if (!Array.isArray(entries)) continue\n const out: unknown[] = []\n for (const [index, entry] of entries.entries()) {\n const ref = pathInlineRef(entry)\n if (ref === undefined) {\n out.push(entry)\n continue\n }\n const at = `${list}[${index}]`\n const replaced = await substitute(at, ref)\n if ('error' in replaced) return { ok: false, at, reason: replaced.error }\n out.push(replaced)\n }\n next[list] = out\n }\n if (Array.isArray(resources.files)) {\n const out: unknown[] = []\n for (const [index, mount] of resources.files.entries()) {\n const ref = isRecord(mount) ? pathInlineRef(mount.resource) : undefined\n if (ref === undefined || !isRecord(mount)) {\n out.push(mount)\n continue\n }\n const at = `files[${index}].resource`\n const replaced = await substitute(at, ref)\n if ('error' in replaced) return { ok: false, at, reason: replaced.error }\n out.push({ ...mount, resource: replaced })\n }\n next.files = out\n }\n const instructions = pathInlineRef(resources.instructions)\n if (instructions !== undefined) {\n const replaced = await substitute('instructions', instructions)\n if ('error' in replaced) return { ok: false, at: 'instructions', reason: replaced.error }\n next.instructions = replaced\n }\n if (!touched) return { ok: true, profile, resolved: [] }\n return { ok: true, profile: { ...profile, resources: next }, resolved }\n}\n","/**\n * Durable side-log for coordination evidence the spawn journal does not own: questions, analyst\n * findings, answer decisions, authorized continuation receipts, delivery-attempt markers, and\n * delivery outcomes. A durable run\n * (`supervise({ runDir })`) appends them as they publish and loads them on resume, so a restarted\n * coordinator retains the exact evidence produced by prior processes.\n *\n * Answer down-events also fold status on load: a question answered before the crash reloads as\n * `answered`, not as a re-blocking `open`. Settled events are skipped (the spawn journal is their\n * ledger). A receipt followed by an attempt but no outcome proves the process died in the delivery\n * window; that outcome remains unknown and no prior instruction is auto-delivered.\n *\n * JSONL, one fsynced record per event, keyed by `runId` — several runs may share one log file\n * exactly as they share one spawn-journal file.\n *\n * @experimental\n */\n\nimport { appendCommittedJsonLine, readCommittedJsonLines } from '../../durable/jsonl-file'\nimport type {\n AnalystFindingEvent,\n DefinedAnalystRecord,\n} from '../../mcp/tools/coordination-analysts'\nimport type { CoordinationEvent } from '../../mcp/tools/coordination-events'\nimport type { ContinuationInstruction } from '../../mcp/tools/coordination-messages'\nimport type {\n QuestionEscalationRecord,\n QuestionRecord,\n} from '../../mcp/tools/coordination-questions'\nimport type { BusRecord } from './event-bus'\nimport type { PeerMailEvent } from './peer-mail'\n\n/** Stable identity of the supervisor that owns one coordination stream. High-level supervision\n * derives it from the exact root/child execution identity plus its parent assignment. */\nexport type CoordinationOwnerId = string\n\n/** Durable delivery evidence retained in commit order. An attempt without a later event carrying\n * the same `receiptId` has an unknown outcome after a crash and is never replayed. */\nexport type CoordinationDeliveryEvidence = Extract<\n CoordinationEvent,\n { readonly type: 'delivery-attempt' | 'steer' | 'answer' }\n>\n\n/** Coordination evidence loaded from prior processes of one durable supervised run. */\nexport interface PriorCoordination {\n /** The owner filter used for this replay. Omitted only for the compatibility all-owner read. */\n readonly ownerId?: CoordinationOwnerId\n /** Every question the prior process raised, with answer-status folded in, raise order. */\n readonly questions: ReadonlyArray<QuestionRecord>\n /** Every analyst finding the prior process published, publish order. */\n readonly findings: ReadonlyArray<AnalystFindingEvent>\n /** Every `ask_parent` escalation the prior process made, raise order. An undelivered one names a\n * question the run raised that nothing above it received — retained so a resuming operator sees\n * it, never auto-redelivered. */\n readonly escalations: ReadonlyArray<QuestionEscalationRecord>\n /** Every lens the prior process DEFINED at run time, definition order. The exact authored bytes\n * and their digest, so an invented lens can be re-registered and any finding it produced can be\n * traced to the words that produced it. Re-registration is the owner's decision, never automatic:\n * the registry may have changed between processes. */\n readonly analystDefinitions: ReadonlyArray<DefinedAnalystRecord>\n /** Every authorized continuation, in commit order. These are evidence, never replayed to a new\n * worker automatically. */\n readonly continuations: ReadonlyArray<ContinuationInstruction>\n /** Delivery intent and result records in commit order, linked to receipts by `receiptId`. */\n readonly deliveryEvidence: ReadonlyArray<CoordinationDeliveryEvidence>\n /** Every peer-mail attempt the prior process made, delivered and refused alike, in commit order.\n * Evidence of what siblings told each other; never replayed into a new worker's inbox. */\n readonly mail: ReadonlyArray<PeerMailEvent>\n /** Exact source-bus stamps in durable append order. Bus `seq` restarts with each process; append\n * order remains the cross-process replay order. */\n readonly records: ReadonlyArray<BusRecord<CoordinationEvent>>\n}\n\n/** The durable coordination side-log seam. `append` records one bus event (kinds it does not\n * persist are ignored); `load` replays a run's prior records folded into `PriorCoordination`. */\nexport interface CoordinationLog {\n append(\n runId: string,\n record: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void>\n load(runId: string, ownerId?: CoordinationOwnerId): Promise<PriorCoordination>\n}\n\ntype CoordinationLogRecord = {\n readonly runId: string\n readonly ownerId?: CoordinationOwnerId\n readonly seq: number\n readonly at: number\n readonly priority: number\n readonly event: CoordinationEvent\n}\n\ntype LegacyCoordinationLogRecord = {\n readonly runId: string\n readonly ownerId?: CoordinationOwnerId\n readonly at: string\n readonly event: CoordinationEvent\n}\n\n/** Persist prior context plus exact continuation authorization, attempt, and result evidence.\n * Settlements have their own journal. */\nfunction persisted(event: CoordinationEvent): boolean {\n return event.type !== 'settled'\n}\n\n/** FS-backed `CoordinationLog`: append-only JSONL, fsynced per record. */\nexport class FileCoordinationLog implements CoordinationLog {\n private appendTail: Promise<void> = Promise.resolve()\n\n constructor(private readonly path: string) {}\n\n async append(\n runId: string,\n record: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void> {\n if (!persisted(record.event)) return\n const append = this.appendTail.then(() => this.appendRecord(runId, record, ownerId))\n this.appendTail = append.catch(() => undefined)\n return append\n }\n\n private async appendRecord(\n runId: string,\n busRecord: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void> {\n const fs = await import('node:fs/promises')\n const { dirname } = await import('node:path')\n await fs.mkdir(dirname(this.path), { recursive: true })\n const record: CoordinationLogRecord = {\n runId,\n ...(ownerId !== undefined ? { ownerId } : {}),\n ...busRecord,\n }\n await appendCommittedJsonLine(this.path, record)\n }\n\n async load(runId: string, ownerId?: CoordinationOwnerId): Promise<PriorCoordination> {\n return foldCoordinationRecords(\n readCommittedJsonLines<CoordinationLogRecord | LegacyCoordinationLogRecord>(this.path, {\n allowMissing: true,\n }),\n runId,\n ownerId,\n )\n }\n}\n\n/** @internal Shared replay semantics for file and SQL coordination evidence. */\nexport async function foldCoordinationRecords(\n source:\n | Iterable<CoordinationLogRecord | LegacyCoordinationLogRecord>\n | AsyncIterable<CoordinationLogRecord | LegacyCoordinationLogRecord>,\n runId: string,\n ownerId?: CoordinationOwnerId,\n): Promise<PriorCoordination> {\n const byId = new Map<string, QuestionRecord>()\n const findings: AnalystFindingEvent[] = []\n const escalations: QuestionEscalationRecord[] = []\n const analystDefinitions: DefinedAnalystRecord[] = []\n const continuations: ContinuationInstruction[] = []\n const deliveryEvidence: CoordinationDeliveryEvidence[] = []\n const mail: PeerMailEvent[] = []\n const records: BusRecord<CoordinationEvent>[] = []\n let legacySeq = 0\n for await (const stored of source) {\n if (stored.runId !== runId) continue\n // Omitting ownerId preserves the historical all-run read for direct consumers. Runtime always\n // supplies one, so root and nested supervisors never receive one another's evidence.\n if (ownerId !== undefined && stored.ownerId !== ownerId) continue\n const record: BusRecord<CoordinationEvent> =\n 'seq' in stored\n ? {\n seq: stored.seq,\n at: stored.at,\n priority: stored.priority,\n event: stored.event,\n }\n : {\n seq: legacySeq++,\n at: Date.parse(stored.at),\n priority: 0,\n event: stored.event,\n }\n records.push(record)\n const ev = record.event\n if (ev.type === 'delivery-attempt' || ev.type === 'steer' || ev.type === 'answer') {\n deliveryEvidence.push(ev)\n }\n if (ev.type === 'question') {\n byId.set(ev.question.id, ev.question)\n } else if (ev.type === 'finding') {\n findings.push(ev.finding)\n } else if (ev.type === 'answer') {\n // Only accepted delivery resolves a blocking question. Authorization and an attempted\n // refusal remain evidence, but cannot turn \"worker never received the answer\" into answered\n // state on replay. `by` is not on the wire; prior-run is the honest attribution.\n const prior = byId.get(ev.questionId)\n if (prior && ev.down.delivered) {\n byId.set(ev.questionId, {\n ...prior,\n status: 'answered',\n decision: { kind: 'answer', answer: ev.down.instruction, by: 'prior-run' },\n })\n }\n } else if (ev.type === 'instruction') {\n continuations.push(ev.instruction)\n } else if (ev.type === 'mail') {\n mail.push(ev.mail)\n } else if (ev.type === 'escalation') {\n escalations.push(ev.escalation)\n } else if (ev.type === 'analyst-defined') {\n analystDefinitions.push(ev.analyst)\n }\n }\n return {\n ...(ownerId !== undefined ? { ownerId } : {}),\n questions: [...byId.values()],\n findings,\n escalations,\n analystDefinitions,\n continuations,\n deliveryEvidence,\n mail,\n records,\n }\n}\n","/**\n *\n * `createInMemoryRunContext` — the one-call bundle of the in-memory stores a\n * `createSupervisor().run(root, task, opts)` needs: a fresh `InMemorySpawnJournal`\n * (the event-sourced spawn log), a fresh `InMemoryResultBlobStore` (the\n * content-addressed `outRef` payload store the driver's `observe`/`finalize` reads\n * settled outputs through), and a fresh `createExecutorRegistry()` (the open\n * `AgentSpec → Executor` resolver).\n *\n * It exists to kill the boilerplate every offline/local supervised run repeats by\n * hand — three constructors threaded into `SupervisorOpts` — and to single-source the\n * ONE wiring invariant that is easy to get wrong: when the root is the recursive\n * `driverAgent` LLM-driver brain AND it may spawn nested managed children, the registry MUST be\n * wrapped with `withDriverExecutor` so a child constructed by `driverChild` resolves to the\n * nested-scope executor — and that SAME blob\n * store MUST be the one passed to `driverAgent({ blobs })`, or the driver\n * reads from a different store than the scope writes to. Pass `{ withDriver: true }`\n * and reuse the returned `blobs` for both.\n *\n * The spread shape matches `SupervisorOpts` exactly, so the call site reads:\n * const run = createInMemoryRunContext()\n * await createSupervisor().run(root, task, { budget, runId, ...run })\n *\n * @experimental\n */\n\nimport { InMemoryResultBlobStore, InMemorySpawnJournal } from '../../durable/in-memory-spawn-stores'\nimport { FileSpawnJournal } from '../../durable/spawn-journal/journal-store'\nimport { FileResultBlobStore } from '../../durable/spawn-journal/result-blob-store'\nimport { type CoordinationLog, FileCoordinationLog } from './coordination-log'\nimport { withDriverExecutor } from './driver-executor'\nimport { createExecutorRegistry } from './runtime'\nimport type { ExecutorRegistry, ResultBlobStore, SpawnJournal } from './types'\n\n/** Options for a supervised run context. */\nexport interface InMemoryRunContextOptions {\n /**\n * Wrap the executor registry with `withDriverExecutor` so a child constructed by `driverChild`\n * resolves to the recursive driver-executor (agents driving agents\n * over a nested `Scope` on the same conserved pool). Leave `false` for a flat tree of\n * leaf workers. Default `false`.\n */\n readonly withDriver?: boolean\n}\n\n/**\n * The bundle of stores a supervised run needs, shaped to spread into `SupervisorOpts`.\n * The fields are exactly `SupervisorOpts`' `journal` / `blobs` / `executors`.\n */\nexport interface InMemoryRunContext {\n /** SQL contexts bind all stores and ownership to this durable run identity. */\n readonly runId?: string\n readonly namespace?: string\n readonly durability?: 'sql'\n /** Present only on an unacquired context. An acquired context cannot reacquire itself. */\n readonly acquire?: (signal?: AbortSignal) => Promise<RunContextLease>\n readonly journal: SpawnJournal\n readonly blobs: ResultBlobStore\n readonly executors: ExecutorRegistry\n /**\n * Present (and `true`) only on a DURABLE context (`createFileRunContext`), so spreading the\n * context into `SupervisorOpts` also opts the run into resume-first. An in-memory context\n * leaves it undefined: there is never a prior tree to resume, and the default stays fresh-run.\n */\n readonly resume?: boolean\n /**\n * Present only on a DURABLE context: the coordination side-log stores questions, analyst\n * findings, answer decisions, and authorized continuation receipts that the spawn journal does\n * not own. `supervise({ runDir })` appends them as they publish and loads them on resume.\n * Continuation receipts are evidence and are never auto-delivered to a replacement worker.\n * In-memory contexts have none: nothing outlives the process.\n */\n readonly coordinationLog?: CoordinationLog\n}\n\n/** The stores a supervised run needs, in-memory or file-backed. `InMemoryRunContext` is the\n * historical name for the same shape. */\nexport type RunContext = InMemoryRunContext\n\n/** An immutable capability for one run ownership generation. */\nexport interface RunContextLease {\n readonly context: RunContext\n readonly signal: AbortSignal\n release(): Promise<void>\n}\n\n/** Hold a run context's ownership (when it has any) across the whole run, releasing after. */\nexport async function withRunContext<T>(\n context: RunContext,\n signal: AbortSignal | undefined,\n run: (context: RunContext, signal: AbortSignal | undefined) => Promise<T>,\n): Promise<T> {\n if (context.acquire === undefined) return run(context, signal)\n const lease = await context.acquire(signal)\n try {\n const result = await run(\n lease.context,\n signal === undefined ? lease.signal : AbortSignal.any([signal, lease.signal]),\n )\n lease.signal.throwIfAborted()\n return result\n } finally {\n await lease.release()\n }\n}\n\n/**\n * Build a fresh in-memory run context. Every call returns NEW stores (no shared global\n * state between runs), so two runs never cross-contaminate their journals/blobs.\n */\nexport function createInMemoryRunContext(opts: InMemoryRunContextOptions = {}): InMemoryRunContext {\n const base = createExecutorRegistry()\n return {\n journal: new InMemorySpawnJournal(),\n blobs: new InMemoryResultBlobStore(),\n executors: opts.withDriver ? withDriverExecutor(base) : base,\n }\n}\n\n/**\n * Build a DURABLE run context: the spawn journal and the result blobs are file-backed (fsynced\n * per append/write) under `dir`, and the context carries `resume: true` so spreading it into\n * `SupervisorOpts` makes the supervisor `loadTree`-first. A run that dies mid-flight therefore\n * resumes when it is re-run with the SAME `runId` and the SAME `dir`: the committed children come\n * back on `Scope.resume` (rehydrated by `replaySpawnTree`) instead of being re-executed.\n *\n * Layout: `${dir}/spawn-journal.jsonl` (one JSONL record per event), `${dir}/blobs/` (one\n * content-addressed JSON file per settled result), and `${dir}/coordination-log.jsonl`\n * (questions, findings, answer decisions, and authorized continuation receipts retained as\n * evidence). The directory is created on first write.\n *\n * Opt-in by construction — `createInMemoryRunContext()` is unchanged and stays the default, so no\n * existing consumer writes to disk or resumes unless it asks for this.\n */\nexport function createFileRunContext(\n dir: string,\n opts: InMemoryRunContextOptions = {},\n): RunContext {\n const base = createExecutorRegistry()\n return {\n journal: new FileSpawnJournal(`${dir}/spawn-journal.jsonl`),\n blobs: new FileResultBlobStore(`${dir}/blobs`),\n executors: opts.withDriver ? withDriverExecutor(base) : base,\n resume: true,\n coordinationLog: new FileCoordinationLog(`${dir}/coordination-log.jsonl`),\n }\n}\n","import type { WatchTraceOptions } from '../../runtime/supervise/detector-monitor'\nimport type { BusRecord } from '../../runtime/supervise/event-bus'\nimport type { PeerMailEvent } from '../../runtime/supervise/peer-mail'\nimport type {\n AnalystAssignmentRecord,\n AnalystFindingEvent,\n DefinedAnalystRecord,\n} from './coordination-analysts'\nimport type { SettledWorker } from './coordination-contracts'\nimport type { MapTraversalEvent } from './coordination-map-contracts'\nimport type {\n ContinuationInstruction,\n DownMessageDeliveryAttempt,\n DownMessageEvent,\n} from './coordination-messages'\nimport type { QuestionEscalationRecord, QuestionRecord } from './coordination-questions'\nimport type { RouteFlowEvent } from './coordination-route-contracts'\n\n/** Every message on the one typed pipe. UP (child→parent): question / settled / finding — queued for\n * the driver to `pull`. An `instruction` is the pre-delivery authorization receipt and is retained\n * as evidence. DOWN (parent→child): steer / answer — record-only (history + subscribers), routed\n * to the child inbox. SIDEWAYS (child→sibling): mail — also record-only, and deliberately NOT\n * queued, so peer traffic audits through the parent without flooding the inbox it pulls from.\n * Receipts are never auto-delivered on restart. New kinds are additive. */\nexport type CoordinationEvent =\n | { readonly type: 'question'; readonly question: QuestionRecord }\n | { readonly type: 'settled'; readonly worker: SettledWorker }\n | { readonly type: 'finding'; readonly finding: AnalystFindingEvent }\n /** A direct manager result that passed its injected completion check. Record-only: the caller\n * already received the tool response, and a restarted manager restores this exact accepted\n * result instead of running the check or its harness again. */\n | { readonly type: 'submission'; readonly result: unknown }\n | {\n readonly type: 'steer'\n readonly down: DownMessageEvent\n /** Present when this steer DELIVERED an analyst's routed findings (an analyzes-edge\n * traversal), naming the lens — absent on an ordinary driver-authored steer. */\n readonly analyst?: string\n }\n | { readonly type: 'answer'; readonly down: DownMessageEvent; readonly questionId: string }\n | { readonly type: 'instruction'; readonly instruction: ContinuationInstruction }\n | { readonly type: 'delivery-attempt'; readonly attempt: DownMessageDeliveryAttempt }\n | { readonly type: 'mail'; readonly mail: PeerMailEvent }\n /** A question left this manager through `ask_parent`, and what became of it. Record-only: the\n * asker already holds the outcome, and an escalation is evidence for the operator, not an item\n * in the inbox the manager pulls from. */\n | { readonly type: 'escalation'; readonly escalation: QuestionEscalationRecord }\n /** A manager DEFINED a trace analyst (`define_analyst`). Record-only: the manager already has the\n * result in its tool return, so queueing it would put its own action in its own inbox. It is the\n * run artifact that makes an invented lens reproducible — the exact bytes, their digest, and the\n * owner the durable log stamps beside them. */\n | { readonly type: 'analyst-defined'; readonly analyst: DefinedAnalystRecord }\n /** Persisted before a native analyst can spend; restored by assignment id after restart. */\n | { readonly type: 'analyst-assignment'; readonly assignment: AnalystAssignmentRecord }\n /** The manager processed events a wake delivered to it. Record-only, and separate from\n * delivery on purpose: an event delivered to a turn that then FAILED stays unacknowledged, and\n * the manager's next re-entry names it again instead of losing it with the dead turn. */\n | { readonly type: 'acknowledgement'; readonly acknowledgement: EventAcknowledgement }\n /** A tool call that outlived its response fence settled. Queued: the manager's next wake\n * carries it, so the caller never re-calls to collect it. */\n | { readonly type: 'tool-outcome'; readonly outcome: ToolOutcomeEvent }\n /** This manager's lead (its parent manager, or the operator for a root) sent it a steer or an\n * answer. Queued: a manager's harness has no live inbox between turns, so the message is the\n * input of its next wake instead of a refused delivery. */\n | { readonly type: 'lead-message'; readonly message: LeadMessage }\n /** One step of a map route. Record-only, except an expansion that was refused and a join that\n * could not run: those are queued, because no settlement will wake the manager for them. */\n | { readonly type: 'map'; readonly map: MapTraversalEvent }\n /** One flow step (see [RouteFlowEvent](https://github.com/tangle-network/agent-runtime/blob/main/src/mcp/tools/coordination-route-contracts.ts)). Record-only: the settle that caused it already\n * woke the manager, and a flow manager makes no decision of its own. */\n | { readonly type: 'route'; readonly route: RouteFlowEvent }\n\n/** One acknowledgement record: which delivered events are now processed, and on whose word. */\nexport interface EventAcknowledgement {\n /** Bus `seq` of each acknowledged event, in this process's sequence space. Empty for the\n * recipient's receipt on a steer or answer, which `messageId` names instead. */\n readonly seqs: ReadonlyArray<number>\n /** `manager`: legacy rows from a manager that named them. `turn-completed`: the\n * driver turn that received them ended normally. `result-accepted`: a submission passed the\n * completion check after they were delivered. `consumed`: the recipient's provider accepted a\n * model input carrying the steer or answer `messageId`. `failed`: the recipient stopped without\n * reading it, for `reason`. */\n readonly by: 'manager' | 'turn-completed' | 'result-accepted' | 'consumed' | 'failed'\n /** The 1-based driver attempt that received them, when the manager has driver attempts. */\n readonly attempt?: number\n /** `consumed` / `failed`: the `receiptId` of the steer or answer this row answers. */\n readonly messageId?: string\n /** `consumed`: the recipient attempt whose accepted input carried the message. */\n readonly attemptId?: string\n /** `failed`: why the recipient never read the message. */\n readonly reason?: string\n}\n\n/** What a manager's coordinator knows about its run, read when the manager is entered again.\n * Every field comes from the coordinator's own records, never from the manager's environment. */\nexport interface ManagerReentryState {\n /** Rows in this manager's journal (`read_journal`) right now. */\n readonly journalRows: number\n /** The highest `nextRow` a `read_journal` call has returned, 0 when the manager never read it. */\n readonly journalReadTo: number\n /** Workers still running. */\n readonly live: ReadonlyArray<{\n readonly id: string\n readonly label: string\n readonly status: string\n }>\n /** Workers that settled, with whether their settlement reached the manager in a wake. */\n readonly settled: ReadonlyArray<{\n readonly id: string\n readonly status: 'done' | 'down'\n readonly valid?: boolean\n readonly delivered: boolean\n }>\n /** Events queued for the next wake and not yet delivered, including settlements the coordinator\n * holds but has not queued yet. */\n readonly waiting: ReadonlyArray<{ readonly type: string; readonly worker?: string }>\n /** Events delivered to a turn that did not complete, and not acknowledged since. */\n readonly unacknowledged: ReadonlyArray<{\n readonly seq: number\n readonly type: string\n readonly worker?: string\n readonly attempt?: number\n /** The event as its wake showed it. A turn that failed may never have read it: a steer named\n * only by its sequence number reaches no prompt. */\n readonly event: Record<string, unknown>\n }>\n /** The last refused `submit_result`, with the refusal the manager was given. */\n readonly lastRejection?: { readonly at: number; readonly reason: string }\n}\n\n/** Online-detector wiring for spawned workers (`CoordinationToolsOptions.watchWorkers`). */\nexport interface WorkerWatchOptions {\n /** Detector panel; omit for the default stuck-loop + error-streak pair. */\n readonly detectors?: WatchTraceOptions['detectors']\n /** Raise at most this many findings per worker, so one pathological worker cannot flood the\n * driver's inbox with the same signal every span. Default 3; `<= 0` = unlimited. */\n readonly maxFindingsPerWorker?: number\n}\n\n/** What a manager waits for, from `awaitWake`. */\nexport interface AwaitWakeInput {\n /** The driver attempt the wake will start: its deliveries are acknowledged when that turn\n * completes, and named again on re-entry when it fails. Omit for the current attempt. */\n readonly attempt?: number\n readonly signal: AbortSignal\n /** Wake with no event after this long, so a waiting manager can reconsider. */\n readonly heartbeatMs: number\n /** The wake starts a model turn: a heartbeat that finds every live worker progressing is\n * re-armed instead of returned. A caller that uses the heartbeat as a poll bound omits it. */\n readonly quietWhileProgressing?: boolean\n /** After the first event, wait this long for more and deliver them together. */\n readonly debounceMs: number\n /** Epoch ms of a deadline warning: wake once then, with or without an event. */\n readonly deadlineAt?: number\n /** Something outside the bus that also ends the wait, such as a delivery to the manager's own\n * inbox. */\n readonly alsoWakeOn?: Promise<unknown>\n}\n\n/** One wake of a manager that ended its turn with work open. */\nexport interface ManagerWake {\n /** `events`: something reached the inbox. `heartbeat`: the heartbeat elapsed with nothing new.\n * `deadline`: the deadline warning came due. */\n readonly reason: 'events' | 'heartbeat' | 'deadline'\n /** Everything that reached the inbox since the last turn, in bus order. */\n readonly events: ReadonlyArray<Record<string, unknown> & { readonly eventSeq: number }>\n /** Workers still running. */\n readonly live: ReadonlyArray<Record<string, unknown>>\n /** How many more workers can start now; `null` when uncapped. */\n readonly freeSlots: number | null\n /** How long the manager waited, with no model turn, before this wake. */\n readonly idleMs: number\n /** Heartbeats that elapsed with every live worker still progressing, and woke no turn. */\n readonly quietHeartbeats?: number\n}\n\n/** A steer or an answer this manager received from its lead. */\nexport interface LeadMessage {\n /** The sender's message id, when it named one; its receipt is answered under this id. */\n readonly messageId?: string\n readonly kind: 'steer' | 'answer'\n readonly text: string\n readonly questionId?: string\n /** The lead asked for the message to interrupt; it is delivered at the next wake either way. */\n readonly interrupt: boolean\n}\n\n/** A tool call that outlived its response fence, and its outcome once it settled. */\nexport interface ToolOutcomeEvent {\n /** The receipt the caller was given when the fence elapsed. */\n readonly receipt: string\n readonly tool: string\n readonly ok: boolean\n /** The tool's result, when it succeeded. */\n readonly value?: unknown\n /** The tool's error message, when it failed. */\n readonly error?: string\n readonly elapsedMs: number\n}\n\n// ── The manager's own journal, read back ────────────────────────────────────────\n//\n// `history()` is the ordered log of every coordination event this manager published — its spawns,\n// its settles, the questions it raised and decided, the steers it authorized, the findings its\n// analysts returned. It was reachable only from the HOST process, so a manager could observe every\n// child and never re-read its own record; a driver that had already tried an approach had no way to\n// see that it had. `read_journal` is that log made agent-readable, under three fences.\n//\n// BOUNDED. A long run's history is far larger than any context window, so the read is paged by an\n// explicit cursor and capped by both a record count and a byte budget. A single oversize record is\n// replaced by a marker rather than dropped, so the cursor always advances past it.\n//\n// REDACTED. The log carries model-authored instruction text and worker output that may quote a\n// credential. Every returned event is passed through a redactor before it leaves; the default is\n// the runtime's own {@link Redactor}.\n//\n// SUBTREE-SCOPED BY CONSTRUCTION, not by a check. Each manager node builds its OWN toolbox over its\n// OWN bus, so `history()` holds that manager's events and no other's. The tool takes no node,\n// worker, run or owner argument, so there is no name a child could pass to reach its parent's log.\n\n/** Default and maximum bounds for one {@link CoordinationTools} journal read. The defaults are\n * sized for a driver turn (a page a model can read and still have room to act on); the maxima\n * bound what a single tool result may cost even when the caller asks for everything. */\nexport const JOURNAL_READ_BOUNDS = Object.freeze({\n defaultLimit: 50,\n maxLimit: 500,\n defaultMaxBytes: 16_384,\n maxMaxBytes: 262_144,\n})\n\n/** Every `CoordinationEvent` kind `read_journal` can return — the tool advertises this list in its\n * JSON Schema AND filters on it, so the schema cannot promise a kind the filter drops. */\nexport const journalEventKinds = [\n 'question',\n 'settled',\n 'finding',\n 'submission',\n 'steer',\n 'answer',\n 'instruction',\n 'delivery-attempt',\n 'mail',\n 'escalation',\n 'analyst-defined',\n 'analyst-assignment',\n 'acknowledgement',\n 'tool-outcome',\n 'lead-message',\n 'map',\n 'route',\n] as const satisfies ReadonlyArray<CoordinationEvent['type']>\n\nexport type JournalEventKind = (typeof journalEventKinds)[number]\n\n/** `satisfies` above proves every listed name IS an event kind; this proves the list is COMPLETE.\n * Without it a new `CoordinationEvent` member compiles fine while `read_journal` returns it when\n * `kinds` is omitted and refuses it as unknown when `kinds` names it — a filter that hides a row\n * the unfiltered read shows. Adding a member without adding it here is now a compile error. */\nexport type JournalKindsAreExhaustive = CoordinationEvent['type'] extends JournalEventKind\n ? true\n : ['a CoordinationEvent kind is missing from journalEventKinds', CoordinationEvent['type']]\n\n/** The assertion itself. Exported so it cannot be pruned as unused, and typed so an uncovered kind\n * fails to compile HERE, naming the missing member, rather than at some later call site. */\nexport const journalKindsAreExhaustive: JournalKindsAreExhaustive = true\n\n/** One journal row: its position, the bus stamp, and the REDACTED event.\n *\n * `row` is the CURSOR, not `seq`. A bus `seq` restarts at 0 in every process of a durable run, so\n * a seq cursor silently re-reads after a restart; `row` counts from the first record of the run,\n * across processes. `seq` stays on the row as the in-process ordering stamp the audit trail uses.\n *\n * `event` is a bare `{ type }` with `oversize` set when the record alone exceeded the read's byte\n * budget — the row still carries its position, so a caller paging by `nextRow` advances past it. */\nexport interface JournalEntry {\n readonly row: number\n readonly seq: number\n readonly at: number\n readonly priority: number\n /** True for a row written by a PRIOR process of this durable run, replayed from the coordination\n * log rather than from the live bus. */\n readonly prior?: true\n readonly event: unknown\n /** Present only on a record too large for the byte budget: what was skipped, and how big it is. */\n readonly oversize?: { readonly type: string; readonly bytes: number }\n}\n\n/** What `read_journal` returns: the page, the cursor to resume from, and the exact bounds that\n * produced it. `remaining` counts matching records this page did not reach, so a caller knows\n * whether to page again without guessing. */\nexport interface JournalPage {\n readonly entries: ReadonlyArray<JournalEntry>\n /** Pass as the next call's `sinceRow`. Equals `sinceRow` when the page is empty. */\n readonly nextRow: number\n readonly remaining: number\n /** True when a bound applied — the row limit, the byte budget, or a row elided as oversize. False\n * ONLY when this page carried every remaining matching row in full. */\n readonly truncated: boolean\n readonly bounds: {\n readonly sinceRow: number\n readonly limit: number\n readonly maxBytes: number\n /** Bytes the returned rows occupy, measured on the ASSEMBLED rows (stamp included), which is\n * what the caller receives. It stays within `maxBytes` in every case but one: a page whose\n * FIRST row is oversize emits the marker anyway, because returning nothing would leave the\n * cursor unable to advance past that record forever. */\n readonly usedBytes: number\n }\n /** How many rows of this journal were written by PRIOR processes of the run. 0 for a fresh run. */\n readonly priorRows: number\n}\n\n/** The reserved coordination verb names — the complete set `createCoordinationTools` can emit\n * (the analyst pair is conditional but still reserved). A driver's extra WORK tools must not\n * collide with any of these, or it could no longer coordinate; callers validate eagerly against\n * this set so the conflict fails loud at construction, not buried in a swallowed `act()` throw.\n *\n * Every name here must also stay clear of the tools a coding harness publishes NATIVELY\n * (`harnessNativeToolNames`, `mcp/harness-native-tools`). A harness prefixes an MCP tool with its\n * server name, so the two never collide on the wire — but a driver reads a BARE word out of a\n * prompt, and a bare word that the harness also publishes resolves to the harness's own tool.\n * The spawn verb is `spawn_worker` for that reason: the runtime's vocabulary for the spawned\n * thing is a worker (`workerId`, `workerSlots`, the per-worker budget), and no known harness\n * publishes that name. `tests/kernel/harness-native-tools.test.ts` holds the set clear. */\nexport const coordinationVerbNames = [\n 'spawn_worker',\n 'cancel_worker',\n 'observe_agent',\n 'steer_agent',\n 'list_questions',\n 'answer_question',\n 'ask_parent',\n 'submit_result',\n 'stop',\n 'report_blocked',\n 'read_continuation',\n 'read_journal',\n 'list_analysts',\n 'run_analyst',\n 'define_analyst',\n 'run_graph',\n] as const\n\n/**\n * The `CoordinationEvent` kinds that wake a waiting manager. The queue carries the UP-leg only:\n * `steer` / `answer` / `instruction` / `delivery-attempt` are recorded `queue: false` (history and\n * subscribers, never delivered back), and `mail` is delivered to its addressee's inbox. A\n * `question` on this bus is the manager's own `ask_parent`, already escalated: it never wakes the\n * asker, whose answer arrives as a `lead-message`.\n */\nexport const wakeEventKinds = [\n 'settled',\n 'finding',\n 'tool-outcome',\n 'lead-message',\n 'map',\n] as const satisfies ReadonlyArray<CoordinationEvent['type']>\n\nexport interface Delivery {\n readonly record: BusRecord<CoordinationEvent>\n readonly attempt: number | undefined\n acknowledged: boolean\n}\n","/**\n *\n * The child→parent message bus: the ONE pipe carrying every message a worker, sub-driver, or\n * analyst sends up to the driver — settled outputs, questions, and trace-analyst findings. It\n * unifies channels that were ad-hoc before (the settled-worker cursor, the ask-parent question\n * channel, and analyst results) into a single typed primitive with two lanes:\n *\n * - PASS-THROUGH (`subscribe`): every published event reaches subscribers immediately — the\n * express lane for online steering and live observation (a UI, a hook, the parent's box).\n * - STANDBY (`pull`): events also queue so the driver consumes them on its own cadence. The queue\n * is PRIORITY-ordered: a higher-`priority` event (a blocking question) is bumped ahead of\n * queued settles/findings so the driver sees it first; ties resolve FIFO by publish order.\n *\n * Observability is first-class (A++): every event is stamped with a monotonic `seq` and wall-clock\n * `at`, the full ordered `history()` is retained as current-process audit evidence, and `stats()`\n * exposes published/pulled counts by kind. Subscribers receive the stamped record, not a bare event.\n *\n * The interface is transport-agnostic on purpose. Same box → this in-process queue. Cross box →\n * the SAME publish/pull/subscribe surface backed by a durable mailbox on the parent's box (children\n * POST events with at-least-once retry; payloads are blob refs so the event stays small). Consumers\n * depend only on this interface, so distribution is a transport swap, never an architecture change.\n *\n * @experimental\n */\n\n/** Every bus event is a discriminated union member keyed by `type`. */\nexport interface BusEvent {\n readonly type: string\n}\n\n/** A published event stamped for ordering and observability. `seq` is the monotonic publish index;\n * `priority` drives pull order (higher = bumped ahead); `at` is the wall-clock publish time (ms). */\nexport interface BusRecord<E extends BusEvent> {\n readonly seq: number\n readonly at: number\n readonly priority: number\n readonly event: E\n}\n\nexport interface PublishOptions {\n /** Higher = pulled ahead of lower-priority queued events (default 0). A blocking question sets\n * this so it bumps to the front of the driver's inbox. */\n readonly priority?: number\n /** Whether the event enters the pull queue (default true). Set `false` for record-only events —\n * the parent→child down-leg (steer / answer / resume): they belong in `history()` and reach\n * `subscribe` observers, but the parent must never `pull` its own outbound message back. */\n readonly queue?: boolean\n}\n\nexport interface BusStats {\n readonly published: number\n readonly pulled: number\n /** Count published per event `type`. */\n readonly byKind: Readonly<Record<string, number>>\n}\n\n/** The child→parent coordination bus surface: publish, priority-ordered pull, pass-through subscribe, history, and stats.\n * @experimental In-process only — the durable cross-process mailbox this interface is designed\n * to admit is not implemented (docs/agent-managed-compute/README.md). */\nexport interface EventBus<E extends BusEvent> {\n /** Stamp the event, await every subscriber in order, then make it pull-visible. A subscriber\n * failure leaves the event invisible and retrying the SAME event object reuses the exact stamp.\n * This lets an awaited product observer commit its record before a supervisor can consume it. */\n publish(event: E, opts?: PublishOptions): Promise<BusRecord<E>>\n /** Remove and return the highest-priority QUEUED event whose type is in `kinds` (any if omitted),\n * ties broken FIFO by `seq`; `undefined` when nothing matches. */\n pull(kinds?: ReadonlyArray<E['type']>): E | undefined\n /** {@link EventBus.pull}, returning the stamped record, so a consumer can later acknowledge the\n * exact event it received by `seq`. */\n pullRecord(kinds?: ReadonlyArray<E['type']>): BusRecord<E> | undefined\n /** The queued, not-yet-pulled records in publish order (filtered by `kinds` when given), as a\n * copy: reading it never changes what `pull` returns next. */\n queued(kinds?: ReadonlyArray<E['type']>): ReadonlyArray<BusRecord<E>>\n /** Register a pass-through handler; it receives the stamped record of every event published after\n * registration. Returns an unsubscribe fn. */\n subscribe(handler: (record: BusRecord<E>) => void | Promise<void>): () => void\n /** Register a handler called once an event has entered the pull queue, after every subscriber\n * acknowledged it — the moment a waiting consumer can pull it. Returns an unsubscribe fn. */\n onQueued(handler: (record: BusRecord<E>) => void): () => void\n /** Count of queued, not-yet-pulled events (filtered by `kinds` when given). */\n pending(kinds?: ReadonlyArray<E['type']>): number\n /** The full ordered log of every event published in this process (audit evidence, not replay). */\n history(): ReadonlyArray<BusRecord<E>>\n /** Throughput counters for observability dashboards. */\n stats(): BusStats\n}\n\n/** Create the child→parent coordination bus: one typed pipe for settled outputs, questions, and analyst findings, with a priority-ordered pull queue and a pass-through subscribe lane.\n * @experimental In-process queue; durability is a transport swap that does not exist yet. */\nexport function createEventBus<E extends BusEvent>(now: () => number = Date.now): EventBus<E> {\n const queue: BusRecord<E>[] = []\n const log: BusRecord<E>[] = []\n const subscribers: Array<(record: BusRecord<E>) => void | Promise<void>> = []\n const queuedHandlers: Array<(record: BusRecord<E>) => void> = []\n const byKind: Record<string, number> = {}\n // A failed publication is staged, not published. Coordination retains and retries the same event\n // object, so the exact BusRecord survives a lost acknowledgement and downstream idempotency keys\n // do not change between attempts.\n const staged = new WeakMap<object, BusRecord<E>>()\n let seq = 0\n let published = 0\n let pulled = 0\n\n const matches = (r: BusRecord<E>, kinds?: ReadonlyArray<E['type']>) =>\n !kinds || kinds.includes(r.event.type)\n\n // Index of the highest-priority matching record; ties resolve to the earliest `seq` (the queue is\n // maintained in publish order, so the first scan hit at the max priority is the oldest).\n const bestIndex = (kinds?: ReadonlyArray<E['type']>): number => {\n let best = -1\n let bestPriority = Number.NEGATIVE_INFINITY\n for (let i = 0; i < queue.length; i++) {\n const r = queue[i]\n if (!r || !matches(r, kinds)) continue\n if (r.priority > bestPriority) {\n best = i\n bestPriority = r.priority\n }\n }\n return best\n }\n\n const pullRecord = (kinds?: ReadonlyArray<E['type']>): BusRecord<E> | undefined => {\n const i = bestIndex(kinds)\n if (i < 0) return undefined\n pulled++\n return queue.splice(i, 1)[0]\n }\n\n return {\n async publish(event, opts) {\n const record =\n staged.get(event) ??\n ({ seq: seq++, at: now(), priority: opts?.priority ?? 0, event } satisfies BusRecord<E>)\n staged.set(event, record)\n // Sequential, not Promise.all: transaction observers must see causal order. Nothing enters\n // the pull queue or successful history until all observers acknowledge the record.\n for (const handler of subscribers) await handler(record)\n staged.delete(event)\n // Record-only events (the down-leg) skip the pull queue but still hit the log + subscribers.\n if (opts?.queue !== false) queue.push(record)\n log.push(record)\n published += 1\n byKind[event.type] = (byKind[event.type] ?? 0) + 1\n if (opts?.queue !== false) for (const handler of [...queuedHandlers]) handler(record)\n return record\n },\n pull(kinds) {\n return pullRecord(kinds)?.event\n },\n pullRecord,\n queued(kinds) {\n return queue.filter((r) => matches(r, kinds))\n },\n subscribe(handler) {\n subscribers.push(handler)\n return () => {\n const i = subscribers.indexOf(handler)\n if (i >= 0) subscribers.splice(i, 1)\n }\n },\n onQueued(handler) {\n queuedHandlers.push(handler)\n return () => {\n const i = queuedHandlers.indexOf(handler)\n if (i >= 0) queuedHandlers.splice(i, 1)\n }\n },\n pending(kinds) {\n return kinds ? queue.filter((r) => matches(r, kinds)).length : queue.length\n },\n history() {\n return log\n },\n stats() {\n return { published, pulled, byKind: { ...byKind } }\n },\n }\n}\n","import type { AnalystFinding, TraceAnalysisStore } from '@tangle-network/agent-eval'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { Spend, WorkerTraceEvidence } from '../../runtime'\n\n/**\n * What one analyst lens may return.\n *\n * Two shapes, because two real producers exist and neither can be dropped. An eval-registry lens\n * returns validated `AnalystFinding`s — the schema every upstream consumer already reads. An\n * authored lens like `failuresAnalyst` returns a written brief for the driver and has no findings\n * to validate against. The union names both, so the boundary can no longer silently accept an\n * unvalidated shape (#630) while the authored lens keeps working.\n */\nexport type AnalystLensOutput = ReadonlyArray<AnalystFinding> | { readonly summary: string }\n\n/** One lens on the menu `list_analysts` shows and `run_analyst` resolves. */\nexport interface AnalystKind {\n readonly id: string\n readonly description: string\n readonly area: string\n}\n\n/**\n * The trace-tool sets a DEFINED analyst may ask for — the exact group names agent-eval's\n * `buildTraceToolsForGroup` accepts, restated here so the `define_analyst` JSON Schema can\n * enumerate them for the model that writes one. Named, not free-form, because the group is the\n * lens's cost ceiling: `all` grants seven trace tools, `discovery` grants three and no deep reads.\n * A name eval does not know throws at registration, which is where the two lists are held together.\n */\nexport const analystToolGroupNames = [\n 'all',\n 'discovery',\n 'discoveryAndRead',\n 'discoveryAndSearch',\n 'targeted',\n 'singleTrace',\n] as const\n\nexport type AnalystToolGroupName = (typeof analystToolGroupNames)[number]\n\n/** Bounds on the recursive investigation a defined analyst may run. Each field is optional and is\n * clamped to `ANALYST_DEFINITION_BOUNDS`; omitted fields take the engine's own default. */\nexport interface AuthoredAnalystLimits {\n readonly maxIterations?: number\n readonly maxLlmCalls?: number\n readonly maxToolCalls?: number\n readonly maxOutputChars?: number\n}\n\n/**\n * A trace analyst a MANAGER authored at run time: the research question, the policy for answering\n * it, the trace tools it may use, and the model seat it asks for. Data only.\n *\n * DATA, NEVER CODE, is the whole safety argument. `TraceAnalystDefinition` (agent-eval) also\n * carries `prepareContext` and `postProcess` FUNCTIONS; those are host-authored and are deliberately\n * absent here, because accepting a function from a tool argument would mean executing model-written\n * code inside the coordination handler — the one thing every other verb in this file refuses. What a\n * manager can author is exactly what a prompt can say.\n *\n * The model seat is PROPOSED, not granted: {@link AnalystRegistry.register} resolves `model` to an\n * engine and may refuse it, the same way `preflightSpawn` refuses a worker's model route.\n */\nexport interface AuthoredAnalystDefinition {\n /** Stable lens id. Lowercase, digits and hyphens; it becomes the `kind` passed to `run_analyst`\n * and the `analyst_id` on every finding, so it is the attribution key. */\n readonly id: string\n /** One line naming what this lens looks for — what `list_analysts` shows the next manager. */\n readonly description: string\n /** The finding area this lens reports under (e.g. `coordination`, `tool-use`, `cost`). */\n readonly area: string\n /** The research question, in the manager's own words. */\n readonly question: string\n /** How to answer it: evidence rules, what counts as a finding, what to refuse to infer. */\n readonly instructions: string\n readonly toolGroup: AnalystToolGroupName\n /** The model seat the lens should run on. Omit to take the run's default analyst engine. */\n readonly model?: string\n readonly limits?: AuthoredAnalystLimits\n /** Minimum distinct evidence citations per finding. Default 1. */\n readonly minimumEvidenceCitations?: number\n}\n\n/** Every bound `define_analyst` enforces before a definition reaches a registry.\n *\n * MOTIVE, stated as numbers, because a fence whose motive cannot be stated is over-engineering:\n * a defined lens spends real model calls from the run's own account on every settle it is routed\n * over, and its `instructions` are re-sent on every one of them. So the two fields that multiply\n * — `instructions` bytes and `maxLlmCalls` — are the ones with hard ceilings, and the ceilings are\n * twice agent-eval's own defaults (`maxIterations` 12, `maxLlmCalls` 8, `maxToolCalls` 48,\n * `maxOutputChars` 10_000): enough headroom for a deeper question than the shipped lenses ask,\n * not enough for one definition to become the dominant cost of a run. */\nexport const ANALYST_DEFINITION_BOUNDS = Object.freeze({\n idPattern: /^[a-z0-9][a-z0-9-]{1,63}$/,\n maxDescriptionChars: 300,\n maxAreaChars: 64,\n maxQuestionChars: 1_000,\n maxInstructionsChars: 20_000,\n maxModelChars: 128,\n maxIterations: 24,\n maxLlmCalls: 16,\n maxToolCalls: 96,\n maxOutputChars: 20_000,\n maxEvidenceCitations: 10,\n /** Lenses ONE manager may define, counting those it defined in a PRIOR process of a durable run.\n * This bounds MENU GROWTH, not spend: a definition costs nothing until `run_analyst` is called,\n * so the failure it stops is a manager that keeps re-authoring a lens instead of running one —\n * each definition adds a line every later `list_analysts` re-reads. Eight is more than the five\n * calibrated lenses agent-eval ships. Per-run analyst SPEND is bounded by the conserved pool the\n * engine draws from, not here. */\n maxDefinitionsPerManager: 8,\n})\n\n/** What the coordination layer records when a definition is admitted: the exact accepted bytes, the\n * kind the registry returned, and a digest over the definition so a finding can be traced back to\n * the words that produced it. */\nexport interface DefinedAnalystRecord {\n readonly definition: AuthoredAnalystDefinition\n readonly kind: AnalystKind\n /** Canonical digest of `definition` — the reproducibility key. */\n readonly digest: string\n readonly definedAt: number\n}\n\n/** What the coordination layer hands one registry lens run. */\nexport interface AnalystRunContext {\n /**\n * Charge the model spend this lens run made to the run's conserved pool — the pool an agent\n * analyst reserves from. A registry whose lens calls a model calls this with the spend it\n * measured; unknown tokens or dollars stay explicitly unknown. The spend is journaled as\n * Runtime-owned accounting. Under a dollar ceiling an unknown dollar cost closes the pool's\n * dollar admission, as an agent analyst's unknown cost does, and the lens keeps its findings.\n */\n readonly charge: (spend: Spend) => Promise<void>\n}\n\nexport interface AnalystRegistry {\n readonly kinds: ReadonlyArray<AnalystKind>\n /** Run one lens. THROWING is the failure channel: it is published as `{ analystRunFailed }`. */\n readonly run: (\n kindId: string,\n trace: TraceAnalysisStore,\n context?: AnalystRunContext,\n ) => Promise<AnalystLensOutput>\n /**\n * OPT-IN: admit a MANAGER-AUTHORED lens while the run is in flight, so a driver can change the\n * questions asked of its own children's traces instead of picking from a menu fixed before the\n * run started. Present = `define_analyst` is mounted; absent = the menu is fixed (the status quo).\n *\n * The coordination layer validates and bounds the definition first (see\n * `ANALYST_DEFINITION_BOUNDS`) and refuses a duplicate id, so an implementation receives\n * only well-formed, in-bounds definitions. It returns the {@link AnalystKind} the lens is now\n * reachable as; `run_analyst` must resolve that id immediately afterwards. THROWING is the\n * refusal channel — an unavailable model seat, a policy that forbids authored lenses — and the\n * message reaches the manager as the tool result's `reason`, so it can re-author.\n */\n readonly register?: (definition: AuthoredAnalystDefinition) => Promise<AnalystKind> | AnalystKind\n}\n\n/** A trace-analyst result re-entered as a message on the bus (the `finding` event kind). */\nexport interface AnalystFindingEvent {\n readonly fromWorker: string\n readonly analyst: string\n /** Native analyst execution that produced this review, when this is an agent route. */\n readonly analystWorkerId?: string\n readonly assignmentId?: string\n /** The analyst's result. ABSENT when the analyst returned `undefined` (no findings); any other\n * value is canonicalized to finite RFC 8785 JSON at publish (`canonicalFindingEvent`), so\n * digesting subscribers (the coordination-event id) never throw on analyst-shaped data. */\n readonly findings?: unknown\n}\n\n/** Producer-side cleanliness for the `finding` event. The findings payload is arbitrary analyst\n * output, the digest a subscriber computes (RFC 8785) throws on ANY `undefined` value — nested\n * included — and a throwing subscriber leaves the event invisible to EVERY subscriber. The\n * producer, not the digest, owns keeping the event canonical: an `undefined` payload is stripped\n * to key-absence, everything else is JSON round-tripped (nested `undefined` object values drop,\n * `undefined` array slots become `null`), and a payload JSON cannot represent at all (cycle,\n * BigInt, bare function) becomes a record OF that fact — degraded findings beat a vanished\n * event. */\nexport function canonicalFindingEvent(finding: AnalystFindingEvent): AnalystFindingEvent {\n if (finding.findings === undefined) {\n const { findings: _absent, ...present } = finding\n return present\n }\n try {\n // JSON.stringify returns undefined (not a string) for a bare function/symbol payload;\n // JSON.parse then throws, landing in the same non-canonical fallback as cycles and BigInt.\n return { ...finding, findings: JSON.parse(JSON.stringify(finding.findings)) as unknown }\n } catch (error) {\n return {\n ...finding,\n findings: { nonCanonicalFindings: error instanceof Error ? error.message : String(error) },\n }\n }\n}\n\n/**\n * One analyst-on-settle ROUTE: which lens runs (`kind`), over WHICH settled workers (`over`),\n * delivered to WHOM (`to`), wrapped in WHAT standing instruction (`directive`). The generalized\n * form of the bare-string entry — a string `k` is exactly `{ kind: k }`: every settle feeds the\n * lens and the findings go to the driver via the bus. This is the analyzes-edge of an agent\n * graph expressed at the coordination layer; the finding is ALWAYS also published on the bus\n * (the audit trail), routing adds delivery, never replaces the record.\n */\nexport interface AnalyzeOnSettleRoute {\n /** Analyze this manager's final output and settled-child references before it closes.\n * Requires an agent route; omitted means each eligible worker settlement. */\n readonly at?: 'worker' | 'manager-end'\n /** Worker outcomes admitted to this route. Defaults to done; down includes failed attempts. */\n readonly statuses?: ReadonlyArray<'done' | 'down'>\n /** The analyst id: a lens id resolved against the `analysts` registry, or — when `agent` is\n * present — the AGENT analyst's stable identity carried on its finding/steer events (it need\n * not exist in any registry). */\n readonly kind: string\n /**\n * Make this analyst a tool-equipped AGENT instead of a registry lens: on each matching settle\n * the runtime spawns this profile as a WORKER through the SAME spawn machinery a driver spawn\n * uses (`Scope.spawn` + the run's `makeWorkerAgent` seam) — so its spend reserves from the\n * conserved pool, its node is journaled and traced like any worker, and a node-pinning seam\n * sees the spawn context marker (`WorkerSpawnContext.analyst`). Its task is `directive` plus\n * the settled worker's tool-trace evidence; its settle OUTPUT is the findings, published as a\n * `finding` event (same canonicalization) and delivered per `to` exactly like registry-analyst\n * findings. A settle that failed publishes `{ analystRunFailed }`; a spawn the pool or fences\n * refuse publishes `{ analystSpawnRefused }` — observable, never a silent drop. An agent\n * analyst's settlement never enters the settled-worker ledger, never feeds the finalizer, and\n * never re-fires the analyst-on-settle hook (no analyst-on-analyst cascade by construction).\n */\n readonly agent?: AgentProfile\n /** Deliver the findings to this live worker, named by its PROFILE NAME (the stable node\n * identity a graph pins) or its spawn label. Omit = the driver (bus only). Delivery goes\n * through the same authorization + steer machinery a driver-authored steer uses and is\n * recorded as a `steer` event carrying `analyst`, so a routed delivery is observable and a\n * failed one (`delivered: false`) is a recorded outcome, never a silent drop. */\n readonly to?: string\n /** Standing instruction wrapped around the findings on a routed delivery — what the recipient\n * should DO with the analysis. For an AGENT analyst (`agent` set) it is instead the analysis\n * directive handed to the agent as its task; the routed delivery then carries the bare\n * findings, because the directive was already consumed upstream. Omit = the bare findings\n * JSON (and, for an agent analyst, a task of evidence only). */\n readonly directive?: string\n /** Restrict which settled workers feed this lens, by profile name or spawn label. Omit =\n * every settled `done` worker. */\n readonly over?: ReadonlyArray<string>\n}\n\n/** Exact analyst assignment recorded before execution. The existing spawn journal retains the\n * profile and task bytes; these digests bind the review to those bytes and its source evidence. */\nexport interface AnalystAssignmentRecord {\n readonly assignmentId: string\n readonly kind: string\n readonly sourceWorker: string\n /** Complete retained source envelope behind the analyst task's bounded excerpt. */\n readonly sourceEvidenceRef?: string\n readonly sourceTrace: WorkerTraceEvidence\n readonly sourceOutRef?: string\n readonly profileDigest: string\n readonly taskDigest: string\n readonly directive?: string\n readonly to?: string\n}\n\n/** One rejected field of an authored analyst definition: which field, and what is wrong with it. */\ninterface AnalystDefinitionIssue {\n readonly path: string\n readonly message: string\n}\n\n/**\n * Validate and BOUND one `define_analyst` argument.\n *\n * Every reason is collected, never short-circuited: a manager re-authoring from a partial list of\n * complaints spends a turn per complaint. Numeric limits are CLAMPED rather than rejected — asking\n * for 200 tool calls is a mis-estimate, not a malformed definition, and the accepted value is\n * returned so the manager reads the ceiling it actually got.\n */\nexport function parseAuthoredAnalystDefinition(\n raw: unknown,\n): { definition: AuthoredAnalystDefinition } | { issues: ReadonlyArray<AnalystDefinitionIssue> } {\n const issues: AnalystDefinitionIssue[] = []\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n return { issues: [{ path: 'definition', message: 'must be an object' }] }\n }\n const o = raw as Record<string, unknown>\n const bounds = ANALYST_DEFINITION_BOUNDS\n\n const text = (field: string, max: number): string => {\n const value = o[field]\n if (typeof value !== 'string' || value.trim().length === 0) {\n issues.push({ path: field, message: 'is required and must be a non-empty string' })\n return ''\n }\n const trimmed = value.trim()\n if (trimmed.length > max) {\n issues.push({\n path: field,\n message: `must be at most ${max} characters (received ${trimmed.length})`,\n })\n return ''\n }\n return trimmed\n }\n\n const id = text('id', 64)\n if (id.length > 0 && !bounds.idPattern.test(id)) {\n issues.push({\n path: 'id',\n message:\n 'must be 2-64 characters of lowercase letters, digits and hyphens, starting with a letter or digit',\n })\n }\n const description = text('description', bounds.maxDescriptionChars)\n const area = text('area', bounds.maxAreaChars)\n const question = text('question', bounds.maxQuestionChars)\n const instructions = text('instructions', bounds.maxInstructionsChars)\n\n const toolGroup = o.toolGroup\n if (!(analystToolGroupNames as ReadonlyArray<unknown>).includes(toolGroup)) {\n issues.push({\n path: 'toolGroup',\n message: `must be one of ${analystToolGroupNames.join(', ')}`,\n })\n }\n\n let model: string | undefined\n if (o.model !== undefined) {\n if (typeof o.model !== 'string' || o.model.trim().length === 0) {\n issues.push({ path: 'model', message: 'must be a non-empty string when present' })\n } else if (o.model.length > bounds.maxModelChars) {\n issues.push({ path: 'model', message: `must be at most ${bounds.maxModelChars} characters` })\n } else {\n model = o.model.trim()\n }\n }\n\n const clampedLimit = (\n field: keyof AuthoredAnalystLimits,\n max: number,\n source: Record<string, unknown>,\n ): number | undefined => {\n const value = source[field]\n if (value === undefined) return undefined\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) {\n issues.push({ path: `limits.${field}`, message: 'must be a positive integer' })\n return undefined\n }\n return Math.min(value, max)\n }\n let limits: AuthoredAnalystLimits | undefined\n if (o.limits !== undefined) {\n if (!o.limits || typeof o.limits !== 'object' || Array.isArray(o.limits)) {\n issues.push({ path: 'limits', message: 'must be an object' })\n } else {\n const source = o.limits as Record<string, unknown>\n const knownLimits = new Set([\n 'maxIterations',\n 'maxLlmCalls',\n 'maxToolCalls',\n 'maxOutputChars',\n ])\n for (const key of Object.keys(source)) {\n if (!knownLimits.has(key)) {\n issues.push({\n path: `limits.${key}`,\n message: `is not an investigation limit (accepted: ${[...knownLimits].join(', ')})`,\n })\n }\n }\n const maxIterations = clampedLimit('maxIterations', bounds.maxIterations, source)\n const maxLlmCalls = clampedLimit('maxLlmCalls', bounds.maxLlmCalls, source)\n const maxToolCalls = clampedLimit('maxToolCalls', bounds.maxToolCalls, source)\n const maxOutputChars = clampedLimit('maxOutputChars', bounds.maxOutputChars, source)\n const present = {\n ...(maxIterations === undefined ? {} : { maxIterations }),\n ...(maxLlmCalls === undefined ? {} : { maxLlmCalls }),\n ...(maxToolCalls === undefined ? {} : { maxToolCalls }),\n ...(maxOutputChars === undefined ? {} : { maxOutputChars }),\n }\n if (Object.keys(present).length > 0) limits = present\n }\n }\n\n let minimumEvidenceCitations: number | undefined\n if (o.minimumEvidenceCitations !== undefined) {\n const value = o.minimumEvidenceCitations\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) {\n issues.push({ path: 'minimumEvidenceCitations', message: 'must be a positive integer' })\n } else {\n minimumEvidenceCitations = Math.min(value, bounds.maxEvidenceCitations)\n }\n }\n\n // A field this contract does not name is refused rather than dropped: a manager that passed\n // `prepareContext` must learn the lens will not run its code, not silently get a lens without it.\n const known = new Set([\n 'id',\n 'description',\n 'area',\n 'question',\n 'instructions',\n 'toolGroup',\n 'model',\n 'limits',\n 'minimumEvidenceCitations',\n ])\n for (const key of Object.keys(o)) {\n if (!known.has(key)) {\n issues.push({\n path: key,\n message: `is not part of an authored analyst definition (accepted: ${[...known].join(', ')})`,\n })\n }\n }\n\n if (issues.length > 0) return { issues }\n return {\n definition: Object.freeze({\n id,\n description,\n area,\n question,\n instructions,\n toolGroup: toolGroup as AnalystToolGroupName,\n ...(model === undefined ? {} : { model }),\n ...(limits === undefined ? {} : { limits: Object.freeze(limits) }),\n ...(minimumEvidenceCitations === undefined ? {} : { minimumEvidenceCitations }),\n }),\n }\n}\n\n/** Normalize the two spellings of an analyst-on-settle entry to the route form. */\nexport function normalizeAnalyzeOnSettle(\n entry: string | AnalyzeOnSettleRoute,\n): AnalyzeOnSettleRoute {\n const route = typeof entry === 'string' ? { kind: entry } : entry\n if (route.at !== undefined && route.at !== 'worker' && route.at !== 'manager-end') {\n throw new TypeError('analyzeOnSettle.at must be worker or manager-end')\n }\n if (route.at === 'manager-end' && route.agent === undefined) {\n throw new TypeError('manager-end analysis requires an agent profile')\n }\n if (\n route.statuses !== undefined &&\n (!Array.isArray(route.statuses) ||\n route.statuses.length === 0 ||\n route.statuses.some((status) => status !== 'done' && status !== 'down'))\n ) {\n throw new TypeError('analyzeOnSettle.statuses must contain done or down')\n }\n return route\n}\n\nexport interface AnalystRunInFlight {\n readonly route: Pick<AnalyzeOnSettleRoute, 'kind' | 'to'>\n readonly sourceWorker: string\n readonly assignmentId: string\n}\n","/** Stringify a findings payload for a routed delivery; never throws (a cyclic payload degrades to\n * its String form rather than killing the settle path). */\nexport function safeJsonText(value: unknown): string {\n if (typeof value === 'string') return value\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport {\n type AgentProfile,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport { contentAddress } from '../../durable/content-address'\nimport type { Settled } from '../../runtime'\nimport type { EventBus } from '../../runtime/supervise/event-bus'\nimport type { InboxReceipt } from '../../runtime/supervise/inbox'\nimport { meterRuntimeOwnedAccounting } from '../../runtime/supervise/scope'\nimport { detachedFrozen } from '../../runtime/supervise/snapshot'\nimport { parseWorkerToolTraceArtifact } from '../../runtime/supervise/trace-evidence'\nimport {\n ANALYST_DEFINITION_BOUNDS,\n type AnalystAssignmentRecord,\n type AnalystKind,\n type AnalystLensOutput,\n type AnalystRunContext,\n type AnalystRunInFlight,\n type AnalyzeOnSettleRoute,\n canonicalFindingEvent,\n type DefinedAnalystRecord,\n normalizeAnalyzeOnSettle,\n parseAuthoredAnalystDefinition,\n} from './coordination-analysts'\nimport type {\n CoordinationTools,\n CoordinationToolsOptions,\n SettledWorker,\n WorkerSpawnContext,\n} from './coordination-contracts'\nimport type { createDownMessages } from './coordination-down-messages'\nimport type { CoordinationEvent } from './coordination-events'\nimport { safeJsonText } from './coordination-json'\nimport type { ContinuationInstruction } from './coordination-messages'\n\nexport function createCoordinationAnalysis({\n leadReceipts,\n opts,\n ledger,\n bus,\n profileNameByWorker,\n watchWorker,\n liveWorkerIdNamed,\n messages,\n ready,\n ensureDrain,\n}: {\n readonly leadReceipts: Map<string, (receipt: InboxReceipt) => void>\n readonly opts: CoordinationToolsOptions\n readonly ledger: ReadonlyArray<SettledWorker>\n readonly bus: EventBus<CoordinationEvent>\n readonly profileNameByWorker: Map<string, string>\n readonly watchWorker: (id: string) => void\n readonly liveWorkerIdNamed: (destination: string) => string | undefined\n readonly messages: () => ReturnType<typeof createDownMessages>\n readonly ready: () => Promise<void>\n readonly ensureDrain: () => Promise<boolean>\n}) {\n const analysisRoutes = (opts.analyzeOnSettle ?? []).map(normalizeAnalyzeOnSettle)\n let finishingAnalysis = false\n const analystAssignments = new Map<string, AnalystAssignmentRecord>()\n for (const record of opts.priorJournal ?? []) {\n if (record.event.type !== 'analyst-assignment') continue\n const assignment = record.event.assignment\n const prior = analystAssignments.get(assignment.assignmentId)\n if (prior && canonicalCandidateDigest(prior) !== canonicalCandidateDigest(assignment)) {\n throw new Error(`coordination: conflicting analyst assignment '${assignment.assignmentId}'`)\n }\n analystAssignments.set(assignment.assignmentId, detachedFrozen(assignment))\n }\n const analystRuns = new Map<string, AnalystRunInFlight>()\n const flushedAnalystRuns = new Set<string>()\n let analystRunOrdinal = 0\n for (const assignment of analystAssignments.values()) {\n const ordinal = Number(/:o(\\d+)$/.exec(assignment.assignmentId)?.[1])\n if (!Number.isSafeInteger(ordinal) || ordinal < 0 || ordinal === Number.MAX_SAFE_INTEGER) {\n throw new Error(`coordination: invalid analyst assignment '${assignment.assignmentId}'`)\n }\n analystRunOrdinal = Math.max(analystRunOrdinal, ordinal + 1)\n }\n for (const node of [...(opts.scope.resume?.view.nodes ?? []), ...opts.scope.view.nodes]) {\n if (node.parent !== opts.scope.view.root || !node.assignmentId?.startsWith('analyst:')) continue\n const assignment = analystAssignments.get(node.assignmentId)\n if (!assignment) {\n throw new Error(\n `coordination: analyst assignment '${node.assignmentId}' has no durable source record; refusing to treat its review as a worker result`,\n )\n }\n if (\n node.identity &&\n (node.identity.profileDigest !== assignment.profileDigest ||\n node.identity.taskDigest !== assignment.taskDigest)\n ) {\n throw new Error(\n `coordination: analyst assignment '${node.assignmentId}' conflicts with its journaled execution identity`,\n )\n }\n analystRuns.set(node.id, {\n route: {\n kind: assignment.kind,\n ...(assignment.to === undefined ? {} : { to: assignment.to }),\n },\n sourceWorker: assignment.sourceWorker,\n assignmentId: assignment.assignmentId,\n })\n }\n const analystRunFinding = (\n run: AnalystRunInFlight,\n settled: Settled<unknown>,\n ): CoordinationEvent =>\n detachedFrozen<CoordinationEvent>({\n type: 'finding',\n finding: canonicalFindingEvent({\n fromWorker: run.sourceWorker,\n analyst: run.route.kind,\n analystWorkerId: settled.handle.id,\n assignmentId: run.assignmentId,\n findings: settled.kind === 'done' ? settled.out : { analystRunFailed: settled.reason },\n }),\n })\n\n /**\n * Spawn one analyst-AGENT run over a settled worker's evidence, through the SAME spawn\n * machinery a driver spawn uses (`scope.spawn` + `makeWorkerAgent`): the analyst's spend\n * reserves from the conserved pool, its node is journaled/traced like any worker, and a\n * node-pinning seam sees `context.analyst`. Its task is the route directive plus the settled\n * worker's persisted tool-trace spans. A refused spawn publishes a finding RECORDING the\n * refusal — observable, never silent — and must never take down the settlement path.\n */\n const spawnAnalystRun = async (\n route: AnalyzeOnSettleRoute,\n worker: SettledWorker,\n ): Promise<void> => {\n let spansText = ''\n let spanCount = 0\n if (worker.trace.status === 'available') {\n try {\n const raw = await opts.blobs.get(worker.trace.traceRef)\n const artifact = parseWorkerToolTraceArtifact(raw, worker.trace.traceRef)\n spanCount = artifact.spans.length\n spansText = safeJsonText(artifact.spans)\n } catch {\n spansText = '' // degraded evidence is stated below, never a thrown settle path\n }\n }\n let output: unknown = null\n let outputError: string | undefined\n if (worker.outRef !== undefined) {\n try {\n output = await opts.blobs.get(worker.outRef)\n } catch (error) {\n outputError = error instanceof Error ? error.message : String(error)\n }\n }\n if (worker.outRef !== undefined && output === undefined && outputError === undefined) {\n outputError = 'referenced output blob unavailable'\n }\n const sourceEvidence = JSON.parse(\n safeJsonText({\n worker,\n output: output ?? null,\n ...(outputError ? { outputError } : {}),\n ...(route.at === 'manager-end'\n ? {\n managerCheckpoint: {\n managerId: opts.scope.view.root,\n nodes: opts.scope.view.nodes\n .filter((node) => !node.assignmentId?.startsWith('analyst:'))\n .map((node) => ({\n id: node.id,\n parent: node.parent,\n assignmentId: node.assignmentId,\n status: node.status,\n })),\n settled: ledger.map(({ resumed: _resumed, ...row }) => row),\n },\n }\n : {}),\n }),\n ) as unknown\n const sourceEvidenceRef = contentAddress(sourceEvidence)\n await opts.blobs.put(sourceEvidenceRef, sourceEvidence)\n const excerpt = (text: string, limit: number) => ({\n text: text.slice(0, limit),\n totalChars: text.length,\n omittedChars: Math.max(0, text.length - limit),\n })\n const task = [\n ...(route.directive === undefined || route.directive.length === 0 ? [] : [route.directive]),\n `Complete source envelope: ${sourceEvidenceRef}. Source output: ${worker.outRef ?? '(unavailable)'}.`,\n 'When your profile grants observe_agent, fetch authorized source refs with {outRef}, following outputPage.nextOffset to read all pages. Without that tool or before fetching all pages, coverage is excerpt-only: leave claims requiring omitted evidence unassessed.',\n `Bounded source excerpt (omitted evidence is not inspected): ${safeJsonText(excerpt(safeJsonText(sourceEvidence), 12000))}`,\n `Source tool trace: ${safeJsonText(worker.trace)} (${spanCount} spans).`,\n spansText.length === 0 ? '(no tool spans available)' : safeJsonText(excerpt(spansText, 8000)),\n ].join('\\n\\n')\n // Reuse an exact durable assignment after a coordinator restart or repeated finalization.\n // A changed checkpoint is a different investigation and retains its own identity.\n const taskDigest = canonicalCandidateDigest(task)\n if (\n route.at === 'manager-end' &&\n [...analystAssignments.values()].some(\n (assignment) =>\n assignment.sourceWorker === worker.id &&\n assignment.kind === route.kind &&\n assignment.taskDigest === taskDigest &&\n assignment.profileDigest === canonicalAgentProfileDigest(route.agent as AgentProfile),\n )\n )\n return\n const assignmentId = `analyst:${route.kind}:o${analystRunOrdinal++}`\n const label = `analyst:${route.kind}`\n const assignment: AnalystAssignmentRecord = detachedFrozen({\n assignmentId,\n kind: route.kind,\n sourceWorker: worker.id,\n sourceTrace: worker.trace,\n sourceEvidenceRef,\n ...(worker.outRef === undefined ? {} : { sourceOutRef: worker.outRef }),\n profileDigest: canonicalAgentProfileDigest(route.agent as AgentProfile),\n taskDigest,\n ...(route.directive === undefined ? {} : { directive: route.directive }),\n ...(route.to === undefined ? {} : { to: route.to }),\n })\n // Persist before spawn: a crash after admission must not leave an unclassified child.\n await bus.publish({ type: 'analyst-assignment', assignment }, { queue: false })\n analystAssignments.set(assignmentId, assignment)\n const context: WorkerSpawnContext = Object.freeze({\n assignmentId,\n parentNodeId: opts.scope.view.root,\n budget: opts.perWorker,\n task,\n label,\n analyst: route.kind,\n sourceEvidenceRefs: Object.freeze([\n sourceEvidenceRef,\n ...(worker.outRef === undefined ? [] : [worker.outRef]),\n ...(worker.trace.status === 'available' ? [worker.trace.traceRef] : []),\n ]),\n // An analyst run is always a brand-new session over settled evidence — never a resume.\n continuity: 'fresh' as const,\n })\n let refusal: string | undefined\n let spawnedId: string | undefined\n try {\n const res = opts.scope.spawn(\n () => opts.makeWorkerAgent(route.agent as AgentProfile, context),\n task,\n { budget: opts.perWorker, label, assignmentId },\n )\n if (res.ok) spawnedId = res.handle.id\n else refusal = String(res.reason)\n } catch (cause) {\n refusal = cause instanceof Error ? cause.message : String(cause)\n }\n if (spawnedId === undefined) {\n await bus.publish({\n type: 'finding',\n finding: canonicalFindingEvent({\n fromWorker: worker.id,\n analyst: route.kind,\n findings: { analystSpawnRefused: refusal ?? 'unknown' },\n }),\n })\n return\n }\n analystRuns.set(spawnedId, { route, sourceWorker: worker.id, assignmentId })\n if (route.agent?.name) profileNameByWorker.set(spawnedId, route.agent.name)\n watchWorker(spawnedId)\n }\n\n /**\n * Deliver one routed analyst finding to its destination worker through the SAME authorized\n * steer machinery a driver steer uses, so the delivery is recorded (`steer` event carrying\n * `analyst`) and its outcome is a fact. No live destination ⇒ a record-only failed steer —\n * observable, never a silent drop. A throw here must not kill the settle path: failures are\n * recorded on the bus (a `steer` with `delivered: false`) before being swallowed, with ONE\n * narrow exception — a bus that refuses the `delivery-attempt` record itself leaves only the\n * `instruction` receipt (an attempt with no outcome = explicitly unknown, per\n * recordDeliveryAttempt's own contract).\n */\n const deliverRoutedFinding = async (\n route: AnalyzeOnSettleRoute,\n findings: AnalystLensOutput | unknown,\n ): Promise<void> => {\n const destination = route.to as string\n const text =\n route.directive === undefined || route.directive.length === 0\n ? safeJsonText(findings)\n : `${route.directive}\\n\\n${safeJsonText(findings)}`\n const targetId = liveWorkerIdNamed(destination)\n if (targetId === undefined) {\n await bus.publish(\n {\n type: 'steer',\n down: detachedFrozen({\n receiptId: randomUUID(),\n toWorker: destination,\n instruction: text,\n instructionDigest: canonicalCandidateDigest(text),\n delivered: false,\n outcome: 'unknown-worker' as const,\n }),\n analyst: route.kind,\n },\n { queue: false },\n )\n return\n }\n let instruction: ContinuationInstruction\n try {\n instruction = messages().authorizeInstruction('steer', targetId, text, false)\n await messages().recordInstruction(instruction)\n } catch (cause) {\n // NOTHING reached the bus for this failure (an authorization refusal, a target without\n // durable identity, a durable subscriber rejecting the instruction record) — record the\n // failed delivery now, in the same `steer` shape a failed attempt publishes, so a routed\n // finding is observable on EVERY failure path, never a silent drop.\n try {\n await messages().sendDown(\n 'steer',\n detachedFrozen({\n receiptId: randomUUID(),\n toWorker: targetId,\n instruction: text,\n instructionDigest: canonicalCandidateDigest(text),\n delivered: false,\n outcome: 'runtime-error' as const,\n error: cause instanceof Error ? cause.message : String(cause),\n }),\n route.kind,\n )\n } catch {\n // The bus itself refused the failure record — there is nothing left to record ON, and a\n // routed finding must never take down the settlement path.\n }\n return\n }\n try {\n await messages().attemptDelivery(\n instruction,\n { steer: instruction.instruction, interrupt: false },\n {\n analyst: route.kind,\n },\n )\n } catch {\n // `attemptDelivery` publishes the failed `steer` (delivered:false + outcome) BEFORE\n // rethrowing, so the failure is already on the bus — except when the bus refused the\n // `delivery-attempt` record itself, where only the `instruction` receipt lands (see the\n // docstring). A routed finding must never take down the settlement path.\n }\n }\n\n // A registry lens spends from the same conserved pool an agent analyst reserves from. Its spend\n // is Runtime-owned accounting on this manager's node: journaled as `metered`, never an owner turn.\n // The lens already ran, so an unknown dollar cost closes dollar admission rather than being\n // refused: a refusal would replace the findings it paid for with `analystRunFailed`.\n const analystRunContext = (kind: string, sourceWorker: string): AnalystRunContext => ({\n charge: (spend) =>\n meterRuntimeOwnedAccounting(\n opts.scope,\n spend,\n { role: 'analyst', analyst: kind, sourceWorker },\n { alreadySpent: true },\n ),\n })\n\n // ── define_analyst ────────────────────────────────────────────────────────────\n //\n // A manager writes a lens; this layer bounds it, refuses a name already taken, hands it to the\n // registry, journals what was admitted, and adds it to the menu. Refusals are tool RESULTS with a\n // named cause, the same vocabulary `spawn_worker` uses, because a manager that cannot read WHY a\n // definition was refused re-submits the same one.\n const definedAnalysts: DefinedAnalystRecord[] = [...(opts.priorAnalystDefinitions ?? [])]\n const analystMenu = (): ReadonlyArray<AnalystKind> => [\n ...(opts.analysts?.kinds ?? []),\n ...definedAnalysts.map((record) => record.kind),\n ]\n const maxDefinedAnalysts =\n opts.maxDefinedAnalysts ?? ANALYST_DEFINITION_BOUNDS.maxDefinitionsPerManager\n const defineAnalyst = async (raw: unknown): Promise<unknown> => {\n const register = opts.analysts?.register\n if (register === undefined) {\n return {\n error: 'authoring-unavailable' as const,\n reason: \"this run's analyst registry admits no authored lens\",\n }\n }\n if (maxDefinedAnalysts > 0 && definedAnalysts.length >= maxDefinedAnalysts) {\n return {\n error: 'max-defined-analysts' as const,\n reason: `you have defined ${definedAnalysts.length} lenses, the cap for this manager; run the ones you have instead of defining more`,\n defined: definedAnalysts.map((record) => record.kind.id),\n }\n }\n const parsed = parseAuthoredAnalystDefinition(raw)\n if ('issues' in parsed) {\n return {\n error: 'invalid-definition' as const,\n reason: parsed.issues.map((issue) => `${issue.path} ${issue.message}`).join('; '),\n issues: parsed.issues,\n }\n }\n const { definition } = parsed\n const taken = analystMenu().find((kind) => kind.id === definition.id)\n if (taken !== undefined) {\n return {\n error: 'duplicate-analyst' as const,\n reason: `the lens id ${JSON.stringify(definition.id)} is already on the menu (${taken.description}); choose a different id or run the existing lens`,\n }\n }\n let kind: AnalystKind\n try {\n kind = await register(definition)\n } catch (error) {\n // The registry is the authority on the model seat and on whether an authored lens is allowed\n // at all. Its message is the manager's re-authoring instruction, so it is passed through.\n return {\n error: 'register-refused' as const,\n reason: error instanceof Error ? error.message : String(error),\n }\n }\n const record: DefinedAnalystRecord = Object.freeze({\n definition,\n kind: Object.freeze({ id: kind.id, description: kind.description, area: kind.area }),\n digest: canonicalCandidateDigest(definition),\n definedAt: Date.now(),\n })\n definedAnalysts.push(record)\n // Record-only: the manager already holds this result, and its own action does not belong in the\n // inbox it pulls from. The event is the durable artifact — the log stamps the owner beside it.\n await bus.publish({ type: 'analyst-defined', analyst: record }, { queue: false })\n return { analyst: record.kind, digest: record.digest, defined: definedAnalysts.length }\n }\n let managerAnalysis: Promise<void> | undefined\n const finishAnalysis: CoordinationTools['finishAnalysis'] = (input) => {\n // This manager takes no further turn: a queued lead message no turn acknowledged is unread.\n for (const [messageId, receipt] of leadReceipts) {\n try {\n receipt({\n status: 'failed',\n messageId,\n cause: 'closed',\n reason: 'the manager finished before a turn read the message',\n })\n } catch {\n // A sender's receipt handler cannot change how this manager ended.\n }\n }\n leadReceipts.clear()\n\n if (managerAnalysis) return managerAnalysis\n managerAnalysis = (async () => {\n const routes = analysisRoutes.filter(\n (route) =>\n route.at === 'manager-end' && (route.statuses ?? ['done', 'down']).includes(input.status),\n )\n if (routes.length === 0) return\n finishingAnalysis = true\n await ready()\n const outRef = input.output === undefined ? undefined : contentAddress(input.output)\n if (outRef !== undefined) await opts.blobs.put(outRef, input.output)\n const worker: SettledWorker = detachedFrozen({\n id: opts.scope.view.root,\n status: input.status,\n trace: { status: 'unavailable', reason: 'trace-source-unavailable' },\n ...(outRef === undefined ? {} : { outRef }),\n ...(input.reason === undefined ? {} : { reason: input.reason }),\n })\n for (const route of routes) await spawnAnalystRun(route, worker)\n // The original Scope bounds every review, including deadline and cancellation.\n // Existing research settlements can arrive first; they are retained without spawning\n // more reviews. Analyst output never enters the candidate ledger.\n while (analystRuns.size > 0) {\n if (!(await ensureDrain())) break\n }\n })().catch(async (error: unknown) => {\n const detail = error instanceof Error ? error.message : String(error)\n try {\n await bus.publish({\n type: 'finding',\n finding: canonicalFindingEvent({\n fromWorker: opts.scope.view.root,\n analyst: 'manager-end',\n findings: { analystRunFailed: detail },\n }),\n })\n } catch (recordError) {\n // A failed evidence store cannot certify its own receipt. Preserve the research\n // outcome and surface the unavailable analysis record to the controller log.\n console.error('Runtime terminal analysis evidence unavailable', {\n managerId: opts.scope.view.root,\n analysisError: detail,\n recordError: recordError instanceof Error ? recordError.message : String(recordError),\n })\n }\n })\n return managerAnalysis\n }\n\n return {\n analysisRoutes,\n analystRuns,\n flushedAnalystRuns,\n analystRunFinding,\n spawnAnalystRun,\n deliverRoutedFinding,\n analystRunContext,\n finishAnalysis,\n definedAnalysts,\n analystMenu,\n defineAnalyst,\n isFinishing: () => finishingAnalysis,\n }\n}\n","import type { ContinuityMode } from './coordination-messages'\nimport type { Question, QuestionUrgency } from './coordination-questions'\n\nexport // Urgency → bus priority: a blocking question is bumped ahead of queued settles/findings so the\n// driver sees it FIRST when it drains the inbox (and pass-through already delivered it the instant\n// it was raised). Non-blocking messages share priority 0 and resolve FIFO.\nconst urgencyPriority = (u: QuestionUrgency): number =>\n u === 'blocks-run' ? 20 : u === 'blocks-step' ? 10 : 0\n\nexport const str = (v: unknown, field: string): string => {\n if (typeof v !== 'string' || v.length === 0)\n throw new Error(`coordination tools: \"${field}\" must be a non-empty string`)\n return v\n}\n\nexport const obj = (raw: unknown): Record<string, unknown> => {\n if (!raw || typeof raw !== 'object')\n throw new Error('coordination tools: arguments must be an object')\n return raw as Record<string, unknown>\n}\n\nexport const level = (v: unknown): Question['level'] => {\n if (v === 'worker' || v === 'driver' || v === 'loop') return v\n throw new Error('coordination tools: \"level\" must be worker, driver, or loop')\n}\n\nexport const urgency = (v: unknown): Question['urgency'] => {\n if (v === 'continue-without' || v === 'blocks-step' || v === 'blocks-run') return v\n throw new Error(\n 'coordination tools: \"urgency\" must be continue-without, blocks-step, or blocks-run',\n )\n}\n\nexport const parseContinuity = (v: unknown): ContinuityMode | undefined => {\n if (v === undefined) return undefined\n if (v === 'fresh' || v === 'resume') return v\n throw new Error('coordination tools: \"continuity\" must be \"fresh\" or \"resume\"')\n}\n","export const idArg = {\n type: 'string',\n description: 'The workerId returned by spawn_worker.',\n} as const\n","import type { TraceAnalysisStore } from '@tangle-network/agent-eval'\nimport { isLiveNodeStatus } from '../../runtime/supervise/node-status'\nimport { workerTraceAnalysisStore } from '../../runtime/supervise/trace-evidence'\nimport type { McpToolDescriptor } from '../server'\nimport type { createCoordinationAnalysis } from './coordination-analysis'\nimport { ANALYST_DEFINITION_BOUNDS, analystToolGroupNames } from './coordination-analysts'\nimport type { CoordinationToolsOptions, SettledWorker } from './coordination-contracts'\nimport { obj, str } from './coordination-input'\nimport type { createSpawnAdmission } from './coordination-spawn-admission'\nimport { idArg } from './coordination-worker-argument'\nexport function mountAnalystsTools({\n opts,\n tools,\n ledger,\n nodeForWorker,\n analystMenu,\n analystRunContext,\n defineAnalyst,\n}: {\n readonly opts: CoordinationToolsOptions\n readonly tools: McpToolDescriptor[]\n readonly ledger: ReadonlyArray<SettledWorker>\n readonly nodeForWorker: ReturnType<typeof createSpawnAdmission>['nodeForWorker']\n readonly analystMenu: ReturnType<typeof createCoordinationAnalysis>['analystMenu']\n readonly analystRunContext: ReturnType<typeof createCoordinationAnalysis>['analystRunContext']\n readonly defineAnalyst: ReturnType<typeof createCoordinationAnalysis>['defineAnalyst']\n}): void {\n if (opts.analysts) {\n tools.push({\n name: 'list_analysts',\n description:\n 'List trace-analyst lenses available to run over a settled worker — the ones this run was ' +\n 'given plus any you defined with define_analyst.',\n inputSchema: { type: 'object', properties: {} },\n handler: () => Promise.resolve({ analysts: analystMenu() }),\n })\n tools.push({\n name: 'run_analyst',\n description: 'Apply an analyst lens to a settled worker trace.',\n inputSchema: {\n type: 'object',\n properties: {\n kind: { type: 'string', description: 'The analyst kind id.' },\n workerId: idArg,\n },\n required: ['kind', 'workerId'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const id = str(a.workerId, 'workerId')\n const node = nodeForWorker(id)\n if (!node)\n return {\n error: 'unknown-worker' as const,\n reason: `no worker of this manager has the id ${JSON.stringify(id)}; spawn_worker returns the ids you may analyze`,\n }\n if (isLiveNodeStatus(node.status)) {\n return {\n error: 'worker-not-settled' as const,\n reason: `worker ${JSON.stringify(id)} has not settled, so it has no trace to analyze yet — end your turn until it settles, then run the lens`,\n }\n }\n const trace =\n ledger.find((worker) => worker.id === id)?.trace ??\n node.trace ??\n ({\n status: 'unavailable',\n reason: 'legacy-settlement-without-trace-evidence',\n } as const)\n let store: TraceAnalysisStore\n try {\n store = await workerTraceAnalysisStore(trace, opts.blobs)\n } catch (error) {\n return {\n error: 'trace-unreadable' as const,\n reason: `the settled worker's trace evidence could not be read: ${error instanceof Error ? error.message : String(error)}`,\n trace,\n }\n }\n // The registry a run installs is SHARED by every manager in the tree, and a lens one\n // manager defined is registered in it. Without this fence a sibling could run a lens it was\n // never shown, spending the run's account on another manager's authored instructions. The\n // menu is the grant: a kind not on it is refused here, before the registry is asked.\n const kind = str(a.kind, 'kind')\n if (!analystMenu().some((entry) => entry.id === kind)) {\n return {\n error: 'unknown-analyst' as const,\n reason: `no lens named ${JSON.stringify(kind)} is on this manager's menu; call list_analysts to see what you may run`,\n }\n }\n return { findings: await opts.analysts?.run(kind, store, analystRunContext(kind, id)) }\n },\n })\n if (opts.analysts.register) {\n tools.push({\n name: 'define_analyst',\n description: [\n 'Define a NEW trace-analyst lens for this run, then run it with run_analyst like any',\n 'other. You write the research question, the policy for answering it, which trace tools',\n 'it may use, and the model seat — data only, never code. The definition is journaled, so',\n 'the lens you invented is reproducible and attributed to you.',\n ].join(' '),\n inputSchema: {\n type: 'object',\n properties: {\n id: {\n type: 'string',\n description:\n 'Stable lens id: lowercase letters, digits and hyphens, 2-64 characters. It is the `kind` you pass to run_analyst and the analyst_id on every finding.',\n },\n description: {\n type: 'string',\n description: `One line naming what this lens looks for. At most ${ANALYST_DEFINITION_BOUNDS.maxDescriptionChars} characters.`,\n },\n area: {\n type: 'string',\n description:\n 'The finding area this lens reports under, e.g. coordination, tool-use, cost.',\n },\n question: {\n type: 'string',\n description: `The research question, in your own words. At most ${ANALYST_DEFINITION_BOUNDS.maxQuestionChars} characters.`,\n },\n instructions: {\n type: 'string',\n description: `How to answer it: evidence rules, what counts as a finding, what to refuse to infer. At most ${ANALYST_DEFINITION_BOUNDS.maxInstructionsChars} characters.`,\n },\n toolGroup: {\n type: 'string',\n enum: [...analystToolGroupNames],\n description:\n 'Smallest trace-tool set that can answer the question. discovery = overview/query/count only; discoveryAndRead adds deep reads; discoveryAndSearch adds regex; targeted and singleTrace narrow further; all grants every trace tool.',\n },\n model: {\n type: 'string',\n description:\n 'The model seat this lens should run on. Omit for the run default. It is a request: registration may refuse a seat this run cannot serve.',\n },\n limits: {\n type: 'object',\n properties: {\n maxIterations: {\n type: 'integer',\n minimum: 1,\n maximum: ANALYST_DEFINITION_BOUNDS.maxIterations,\n },\n maxLlmCalls: {\n type: 'integer',\n minimum: 1,\n maximum: ANALYST_DEFINITION_BOUNDS.maxLlmCalls,\n },\n maxToolCalls: {\n type: 'integer',\n minimum: 1,\n maximum: ANALYST_DEFINITION_BOUNDS.maxToolCalls,\n },\n maxOutputChars: {\n type: 'integer',\n minimum: 1,\n maximum: ANALYST_DEFINITION_BOUNDS.maxOutputChars,\n },\n },\n additionalProperties: false,\n description:\n 'Investigation ceilings. Values above the maximum are clamped, not refused.',\n },\n minimumEvidenceCitations: {\n type: 'integer',\n minimum: 1,\n maximum: ANALYST_DEFINITION_BOUNDS.maxEvidenceCitations,\n description: 'Distinct evidence citations required per finding. Default 1.',\n },\n },\n required: ['id', 'description', 'area', 'question', 'instructions', 'toolGroup'],\n additionalProperties: false,\n },\n handler: async (raw) => defineAnalyst(raw),\n })\n }\n }\n}\n","export async function runWithin<T>(work: Promise<T>, ms: number, message: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(message)), ms)\n if (typeof timer?.unref === 'function') timer.unref()\n })\n try {\n return await Promise.race([work, timeout])\n } finally {\n if (timer) clearTimeout(timer)\n }\n}\n","import type { McpToolDescriptor } from '../server'\nimport type { BlockedToolReport, CoordinationToolsOptions } from './coordination-contracts'\nimport type { JournalPage } from './coordination-events'\nimport { JOURNAL_READ_BOUNDS, journalEventKinds } from './coordination-events'\nimport { obj, str } from './coordination-input'\nimport { runWithin } from './coordination-tool-timeout'\nexport function createAuditTools({\n opts,\n tools,\n blockedReports,\n readJournal,\n}: {\n readonly opts: CoordinationToolsOptions\n readonly tools: () => ReadonlyArray<McpToolDescriptor>\n readonly blockedReports: BlockedToolReport[]\n readonly readJournal: (raw: unknown, trackOwnRead?: boolean) => JournalPage\n}): McpToolDescriptor[] {\n return [\n {\n name: 'report_blocked',\n description: [\n 'Report that a tool you need keeps failing.',\n 'Name the tool, the arguments you called it with, and the error you saw.',\n 'The coordinator calls that tool again, with those arguments, under your identity.',\n 'When the call succeeds you are not blocked: the reply carries its result, and you continue.',\n 'When it fails again, the record keeps both errors and the run goes on: work around the tool,',\n 'or end your turn and be woken later. A blocked tool never ends the run; turns in a row',\n 'that end without progress make Runtime wait longer before each next turn.',\n 'submit_result, stop and report_blocked cannot be probed.',\n ].join(' '),\n inputSchema: {\n type: 'object',\n properties: {\n tool: { type: 'string', description: 'The tool that failed, as you called it.' },\n arguments: {\n type: 'object',\n description: 'The arguments you called it with. Omit for none.',\n },\n error: { type: 'string', description: 'The error the tool returned to you.' },\n },\n required: ['tool', 'error'],\n additionalProperties: false,\n },\n handler: async (raw) => {\n const a = obj(raw)\n const named = str(a.tool, 'tool')\n const reported = str(a.error, 'error')\n // A harness names an MCP tool with its server alias in front; the probe wants the bare name.\n const bare = named.replace(/^mcp__.+?__/u, '').replace(/^.*?coordination_+/u, '')\n if (unprobeableVerbs.has(bare)) {\n return {\n blocked: false,\n error: 'unprobeable' as const,\n reason: `${bare} changes the run, so the coordinator does not call it for you`,\n }\n }\n const target = opts.resolveProbeTool?.(bare) ?? tools().find((tool) => tool.name === bare)\n if (target === undefined) {\n return {\n blocked: false,\n error: 'unknown-tool' as const,\n reason: `no tool named ${JSON.stringify(bare)} is served to you, so there is nothing to probe; call the tools you were given`,\n }\n }\n const args =\n a.arguments === undefined\n ? {}\n : typeof a.arguments === 'object' && a.arguments !== null && !Array.isArray(a.arguments)\n ? a.arguments\n : undefined\n if (args === undefined) {\n return {\n blocked: false,\n error: 'invalid-arguments' as const,\n reason: '\"arguments\" must be an object',\n }\n }\n let probe:\n | { readonly ok: true; readonly result: unknown }\n | { readonly ok: false; readonly error: string }\n try {\n probe = {\n ok: true,\n result: await runWithin(\n target.handler(structuredClone(args)),\n REPORT_BLOCKED_PROBE_MS,\n `the probe of ${bare} did not answer within ${REPORT_BLOCKED_PROBE_MS}ms`,\n ),\n }\n } catch (error) {\n probe = { ok: false, error: error instanceof Error ? error.message : String(error) }\n }\n if (probe.ok) {\n return {\n blocked: false,\n probe: { tool: bare, ok: true, result: probe.result },\n guidance:\n 'The call worked when the coordinator made it under your identity, so the tool is ' +\n 'not blocked. Use this result and continue the objective.',\n }\n }\n blockedReports.push(\n Object.freeze({\n tool: bare,\n reported,\n probed: probe.error,\n at: new Date().toISOString(),\n }),\n )\n return {\n blocked: true,\n probe: { tool: bare, ok: false, error: probe.error },\n guidance:\n 'The call failed when the coordinator made it too, and the record keeps both errors. ' +\n 'The run does not end on a blocked tool. Continue with the work that does not need it, ' +\n 'or end your turn: you will be woken, and the tool may work then. Turns in a row that ' +\n 'end without progress make Runtime wait longer before each next turn.',\n }\n },\n },\n {\n name: 'read_journal',\n description: [\n 'Re-read YOUR OWN coordination journal: every spawn you made, every worker that settled,',\n 'every question raised or decided, every steer you authorized, and every analyst finding —',\n 'oldest first, on this node only, including what you did before a restart. Read it before',\n 'deciding what to do next, so you can see what you already tried. Bounded: page with the',\n 'returned `nextRow`, and check `truncated` before concluding you have read everything.',\n ].join(' '),\n inputSchema: {\n type: 'object',\n properties: {\n sinceRow: {\n type: 'integer',\n minimum: 0,\n description:\n 'First journal row to return (inclusive, 0 = the first record of the run). Pass the previous call’s `nextRow` to continue.',\n },\n kinds: {\n type: 'array',\n items: { type: 'string', enum: [...journalEventKinds] },\n description: 'Return only these event kinds. Omit for every kind.',\n },\n // No `maximum` here on purpose: the handler CLAMPS an over-large ask and reports the bound\n // it applied in `bounds`. Declaring a maximum too would make a validating transport reject\n // the same call the handler is designed to accept and narrow.\n limit: {\n type: 'integer',\n minimum: 1,\n description: `Maximum rows to return. Default ${JOURNAL_READ_BOUNDS.defaultLimit}; anything above ${JOURNAL_READ_BOUNDS.maxLimit} is clamped to it.`,\n },\n maxBytes: {\n type: 'integer',\n minimum: 1,\n description: `Byte budget for the returned rows. Default ${JOURNAL_READ_BOUNDS.defaultMaxBytes}; anything above ${JOURNAL_READ_BOUNDS.maxMaxBytes} is clamped to it.`,\n },\n },\n additionalProperties: false,\n },\n // async so an argument the manager got wrong surfaces as a REJECTED tool call the transport\n // reports back to it, never as a synchronous throw through the server's dispatch.\n handler: async (raw) => readJournal(raw),\n },\n ]\n}\n\nconst unprobeableVerbs: ReadonlySet<string> = new Set(['submit_result', 'stop', 'report_blocked'])\n\nconst REPORT_BLOCKED_PROBE_MS = 60_000\n","import type { CheckVerdict, DeliverableSpec } from '../../runtime/supervise/completion-gate'\nimport { failedItems, NOTE_FAILURE_LINES } from '../../runtime/supervise/continuation'\n/**\n * The refusal a failed check reading returns to `submit_result`: the verdict as a located fact,\n * the FAIL lines unless the check's tests must stay hidden, and how many times the manager has\n * read the check.\n */\nexport function refusalText(\n verdict: CheckVerdict,\n deliverable: DeliverableSpec<unknown>,\n read: number,\n): string {\n const total = Object.keys(verdict.items ?? {}).length\n const failed = failedItems(verdict).length\n const score =\n verdict.composite === undefined\n ? ''\n : ` (composite ${verdict.composite}${verdict.threshold === undefined ? '' : `, passes at ${verdict.threshold}`})`\n const head =\n total > 0\n ? `The outside check failed: ${failed} of ${total} items fail${score}. Check read ${read}.`\n : `The outside check failed${score}. Check read ${read}.`\n if (deliverable.feedback === 'pass-only') return head\n const lines = verdict.failures ?? []\n if (lines.length === 0) {\n return deliverable.describe ? `${head} Expected: ${deliverable.describe}` : head\n }\n const shown = lines.slice(0, NOTE_FAILURE_LINES)\n return [\n head,\n ...shown,\n ...(lines.length > shown.length ? [`${lines.length - shown.length} more failure lines.`] : []),\n ].join('\\n')\n}\n","import { randomUUID } from 'node:crypto'\nimport { canonicalCandidateDigest } from '@tangle-network/agent-interface'\nimport type { EventBus } from '../../runtime/supervise/event-bus'\nimport { INBOX_RECEIPT_KEY, type InboxReceipt } from '../../runtime/supervise/inbox'\nimport { isLiveNodeStatus } from '../../runtime/supervise/node-status'\nimport { detachedFrozen } from '../../runtime/supervise/snapshot'\nimport type { CoordinationToolsOptions } from './coordination-contracts'\nimport type { CoordinationEvent, EventAcknowledgement } from './coordination-events'\nimport { str } from './coordination-input'\nimport type {\n ContinuationInstruction,\n DownMessageDeliveryAttempt,\n DownMessageDeliveryOutcome,\n DownMessageEvent,\n} from './coordination-messages'\n\nexport function createDownMessages({\n opts,\n bus,\n lifetime,\n}: {\n readonly opts: CoordinationToolsOptions\n readonly bus: EventBus<CoordinationEvent>\n readonly lifetime: AbortSignal | undefined\n}) {\n // The down-leg: record a parent→child message on the bus for the audit trail (history +\n // subscribers) WITHOUT enqueuing it — the parent must never pull its own outbound message back.\n // Overloaded so the `answer` kind REQUIRES a questionId (no silent `?? ''` fallback to mask a bug).\n function sendDown(type: 'steer', down: DownMessageEvent, analyst?: string): Promise<void>\n function sendDown(type: 'answer', down: DownMessageEvent, questionId: string): Promise<void>\n async function sendDown(\n type: 'steer' | 'answer',\n down: DownMessageEvent,\n questionIdOrAnalyst?: string,\n ): Promise<void> {\n await bus.publish(\n type === 'answer'\n ? { type, down, questionId: str(questionIdOrAnalyst, 'questionId') }\n : questionIdOrAnalyst !== undefined\n ? { type, down, analyst: questionIdOrAnalyst }\n : { type, down },\n { queue: false },\n )\n }\n\n const authorizeInstruction = (\n kind: 'steer' | 'answer',\n workerId: string,\n instruction: string,\n interrupt: boolean,\n questionId?: string,\n ): ContinuationInstruction => {\n const workerIdentity = opts.scope.view.nodes.find((node) => node.id === workerId)?.identity\n let authorizedInstruction = instruction\n if (opts.authorizeDownMessage) {\n if (workerIdentity === undefined) {\n throw new Error(\n `coordination tools: cannot authorize ${kind} for worker ${JSON.stringify(workerId)} without durable identity`,\n )\n }\n const decision = detachedFrozen(\n opts.authorizeDownMessage(\n detachedFrozen({\n kind,\n workerId,\n workerIdentity,\n instruction,\n interrupt,\n ...(questionId !== undefined ? { questionId } : {}),\n }),\n ),\n )\n if (\n typeof decision !== 'object' ||\n decision === null ||\n Array.isArray(decision) ||\n typeof decision.instruction !== 'string' ||\n decision.instruction.length === 0\n ) {\n throw new Error('coordination tools: authorizeDownMessage must return an instruction')\n }\n authorizedInstruction = decision.instruction\n }\n return detachedFrozen({\n receiptId: randomUUID(),\n kind,\n toWorker: workerId,\n instruction: authorizedInstruction,\n instructionDigest: canonicalCandidateDigest(authorizedInstruction),\n ...(workerIdentity !== undefined ? { workerIdentity } : {}),\n interrupt,\n ...(questionId !== undefined ? { questionId } : {}),\n })\n }\n\n /** Publish before `scope.send`: an awaited durable subscriber therefore commits the exact bytes\n * before the worker can observe them. */\n const recordInstruction = async (instruction: ContinuationInstruction): Promise<void> => {\n await bus.publish({ type: 'instruction', instruction }, { queue: false })\n }\n\n /** Commit delivery intent after the authorization receipt and before `Scope.send`. An attempt with\n * no matching outcome after a crash is explicitly unknown and must never be replayed. */\n const recordDeliveryAttempt = async (\n instruction: ContinuationInstruction,\n ): Promise<DownMessageDeliveryAttempt> => {\n const attempt = detachedFrozen({\n receiptId: instruction.receiptId,\n kind: instruction.kind,\n toWorker: instruction.toWorker,\n instructionDigest: instruction.instructionDigest,\n interrupt: instruction.interrupt,\n ...(instruction.questionId !== undefined ? { questionId: instruction.questionId } : {}),\n })\n await bus.publish({ type: 'delivery-attempt', attempt }, { queue: false })\n return attempt\n }\n\n const deliveryOutcome = (workerId: string, delivered: boolean): DownMessageDeliveryOutcome => {\n if (delivered) return 'delivered'\n if (opts.scope.signal.aborted) return 'scope-stopped'\n const node = opts.scope.view.nodes.find((candidate) => candidate.id === workerId)\n if (!node) return 'unknown-worker'\n if (!isLiveNodeStatus(node.status)) return 'already-settled'\n return 'runtime-has-no-inbox'\n }\n\n const recordReceipt = (receipt: InboxReceipt): void => {\n bus\n .publish(\n {\n type: 'acknowledgement',\n acknowledgement: detachedFrozen<EventAcknowledgement>({\n seqs: [],\n by: receipt.status,\n messageId: receipt.messageId,\n ...(receipt.status === 'consumed'\n ? { attemptId: receipt.attemptId }\n : { reason: receipt.reason }),\n }),\n },\n { queue: false },\n )\n .catch(() => undefined)\n }\n\n const attemptDelivery = async (\n instruction: ContinuationInstruction,\n message: Record<string, unknown>,\n origin?: { readonly analyst?: string },\n ): Promise<DownMessageEvent> => {\n await recordDeliveryAttempt(instruction)\n let delivered = false\n let outcome: DownMessageDeliveryOutcome\n let error: string | undefined\n try {\n if (lifetime?.aborted) {\n outcome = 'scope-stopped'\n } else {\n delivered = opts.scope.send(instruction.toWorker, {\n ...message,\n messageId: instruction.receiptId,\n [INBOX_RECEIPT_KEY]: recordReceipt,\n })\n outcome = deliveryOutcome(instruction.toWorker, delivered)\n }\n } catch (cause) {\n outcome = 'runtime-error'\n error = cause instanceof Error ? cause.message : String(cause)\n }\n const down = detachedFrozen({\n receiptId: instruction.receiptId,\n toWorker: instruction.toWorker,\n instruction: instruction.instruction,\n instructionDigest: instruction.instructionDigest,\n delivered,\n outcome,\n ...(error !== undefined ? { error } : {}),\n })\n if (instruction.kind === 'answer') {\n await sendDown('answer', down, str(instruction.questionId, 'questionId'))\n } else {\n await sendDown('steer', down, origin?.analyst)\n }\n if (error !== undefined) throw new Error(`coordination tools: delivery failed: ${error}`)\n return down\n }\n\n const steerWorker = async (\n workerId: string,\n instruction: string,\n options: { readonly interrupt?: boolean } = {},\n ): Promise<DownMessageEvent> => {\n const interrupt = options.interrupt === true\n const authorized = authorizeInstruction('steer', workerId, instruction, interrupt)\n await recordInstruction(authorized)\n return await attemptDelivery(authorized, {\n steer: authorized.instruction,\n interrupt,\n })\n }\n\n return { sendDown, authorizeInstruction, recordInstruction, attemptDelivery, steerWorker }\n}\n","import type { CoordinationEvent } from './coordination-events'\n\nexport const eventWorker = (event: CoordinationEvent): string | undefined =>\n event.type === 'settled'\n ? event.worker.id\n : event.type === 'finding'\n ? event.finding.fromWorker\n : event.type === 'question'\n ? event.question.from\n : event.type === 'map'\n ? event.map.sourceWorker\n : undefined\n\nexport // Consumer projection: the wire shape the driver sees for a pulled bus event.\nconst projectEvent = (ev: CoordinationEvent): Record<string, unknown> => {\n if (ev.type === 'settled') {\n const { id, status, ...evidence } = ev.worker\n return {\n type: 'settled',\n settled: id,\n status,\n ...evidence,\n ...(status === 'done' && evidence.valid === undefined ? { assessment: 'unassessed' } : {}),\n ...(evidence.outRef === undefined\n ? {}\n : {\n outputRead: { tool: 'observe_agent', arguments: { workerId: id } },\n }),\n }\n }\n if (ev.type === 'question') return { type: 'question', question: ev.question }\n if (ev.type === 'finding') return { type: 'finding', ...ev.finding }\n if (ev.type === 'submission') return { type: 'submission', result: ev.result }\n if (ev.type === 'answer') return { type: 'answer', ...ev.down, questionId: ev.questionId }\n if (ev.type === 'instruction') return { type: 'instruction', ...ev.instruction }\n if (ev.type === 'delivery-attempt') return { type: 'delivery-attempt', ...ev.attempt }\n // Peer mail is sideways and record-only, so the driver never pulls it either. Projected\n // explicitly rather than through the `down` fallback below: a member with no `down` property\n // spread through that fallback would yield a bare `{ type }` and drop the whole payload.\n if (ev.type === 'mail') return { type: 'mail', ...ev.mail }\n // Record-only like mail, and with no `down` leg, so it is projected explicitly.\n if (ev.type === 'escalation') return { type: 'escalation', ...ev.escalation }\n // A definition is record-only for the same reason, and carries no `down` leg either.\n if (ev.type === 'analyst-defined') return { type: 'analyst-defined', ...ev.analyst }\n if (ev.type === 'analyst-assignment') return { type: 'analyst-assignment', ...ev.assignment }\n // Record-only as well: the manager already holds what it acknowledged.\n if (ev.type === 'acknowledgement') return { type: 'acknowledgement', ...ev.acknowledgement }\n if (ev.type === 'tool-outcome') return { type: 'tool-outcome', ...ev.outcome }\n if (ev.type === 'lead-message') return { type: 'lead-message', ...ev.message }\n if (ev.type === 'map') return { type: 'map', ...ev.map }\n if (ev.type === 'route') return { type: 'route', ...ev.route }\n // Down-leg `steer` is record-only (never queued), so the driver never pulls it; project\n // defensively for completeness.\n return { type: ev.type, ...ev.down }\n}\n","import type { BudgetViolation, SpawnRejection } from '../../runtime'\nimport type { ReservationShortfall } from '../../runtime/supervise/budget'\nimport type { SpawnRefusalCause } from './coordination-contracts'\n\n/** Each channel spent beyond its budget, as spent of budget: `tokens 235,857 of 42,000` or\n * `deadline 3,857 s of 2,400 s`. */\nexport function budgetOverspendText(violation: BudgetViolation): string {\n const count = (value: number) => value.toLocaleString('en-US')\n return violation.overspent\n .map((entry) =>\n entry.channel === 'deadline'\n ? `deadline ${count(Math.round(entry.spent / 1000))} s of ${count(Math.round(entry.reserved / 1000))} s`\n : `${entry.channel} ${count(entry.spent)} of ${count(entry.reserved)}`,\n )\n .join('; ')\n}\n\n/** What a manager can do with a keyed worker its budget stopped. */\nexport const BUDGET_STOP_NEXT =\n 'spawn_worker with the same key and a larger budget continues this session where it stopped; ' +\n 'cancel_worker releases it'\n\n/** Every cause at zero — a pre-flight publishes its whole ledger from the first read. */\nexport function emptyPreflightCounts(): Record<SpawnRefusalCause, number> {\n return { 'model-route': 0, 'bridge-full': 0, 'unmountable-tool': 0, 'unprovisionable-profile': 0 }\n}\n\n/** The optional per-spawn budget `spawn_worker` and `run_graph` take. */\nexport const spawnBudgetArg = {\n type: 'object',\n description:\n 'Optional per-spawn budget that merges over the per-worker default (per field). ' +\n 'Only set the ceilings this sub-task needs raised; the conserved pool still fences.',\n properties: {\n maxIterations: { type: 'number', minimum: 0 },\n maxTokens: { type: 'number', minimum: 0 },\n maxUsd: { type: 'number', minimum: 0 },\n deadlineMs: { type: 'number', minimum: 0 },\n resources: {\n type: 'object',\n additionalProperties: {\n type: 'object',\n properties: {\n unit: { type: 'string', minLength: 1 },\n limit: { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER },\n },\n required: ['unit', 'limit'],\n },\n },\n },\n}\n\nfunction budgetField(channel: ReservationShortfall['channel']): string {\n return channel.startsWith('resource:')\n ? `resources.${channel.slice('resource:'.length)}.limit`\n : BUDGET_FIELD[channel as 'tokens' | 'iterations' | 'usd']\n}\n\n/** One clause per short channel. Iterations can be requested at exactly `free`: a driver's own\n * turns charge none. Tokens and dollars cannot: the driver's next turn is metered from the same\n * pool before its retry reaches admission, so the clause says to leave room. */\nfunction shortfallClause(shortfall: ReservationShortfall): string {\n const { channel, requested, free } = shortfall\n const field = budgetField(channel)\n if (shortfall.closedByUnknownSpend === true) {\n return `${channel} is closed: work with unmeasured ${channel} usage ran under the run's enforced limit, so this run admits no further spawn at any budget`\n }\n const asked = `this spawn asked for budget.${field} ${requested}`\n const held = shortfall.held ?? 0\n const most = free + held\n if (most === 0) {\n return `${channel} has nothing free and none held by your running workers (${asked})`\n }\n // A spawn of at most free + held is admitted and waits for the running workers to return it.\n const room =\n held > 0\n ? `${free} free now and ${held} held by your running workers, which a spawn waits for`\n : `${free} free${channel === 'iterations' || channel.startsWith('resource:') ? '' : ' right now'}`\n if (channel === 'iterations' || channel.startsWith('resource:')) {\n return `${channel} has ${room} (${asked}); budget.${field} at most ${most} fits`\n }\n return `${channel} has ${room} (${asked}); your own turns draw ${channel} from this same pool before a retry is admitted, so ask for well under ${most}`\n}\n\n/**\n * The reason text `spawn_worker` returns for a refused spawn. Every rejection kind names its own\n * cause: a live-worker cap, a depth limit, or a key collision is not an empty budget, and telling a\n * driver \"no allocation left\" for those sends it after the wrong fix. A `budget-exhausted` refusal\n * names every channel that did not fit and the amounts, so the driver can size its next request.\n */\nexport function spawnRefusalReason(\n reason: SpawnRejection,\n shortfalls: readonly ReservationShortfall[] | undefined,\n pinned: {\n readonly usdUnbudgeted: string\n readonly inDoubt: string\n readonly scopeSettled: string\n },\n): string {\n switch (reason) {\n case 'usd-unbudgeted':\n return pinned.usdUnbudgeted\n case 'in-doubt':\n return pinned.inDoubt\n case 'scope-settled':\n return pinned.scopeSettled\n case 'scope-aborted':\n return 'this run stopped admitting work (it was cancelled, passed its deadline, or too many children went down); no further worker can start'\n case 'depth-exceeded':\n return \"this spawn would exceed the run's maxDepth; a worker at the deepest level cannot start children of its own\"\n case 'duplicate-key':\n return 'a worker under this key is still live; wait for it to settle, or use a different key for different work'\n case 'key-conflict':\n return \"this key is already recorded for a different profile or task in this run's journal; use a new key for different work\"\n case 'invalid-identity':\n return 'a keyed spawn needs a complete execution identity to journal, and this profile and task did not produce one; spawn again without a key'\n case 'budget-exhausted': {\n if (shortfalls === undefined || shortfalls.length === 0) {\n return \"the conserved pool refused this spawn (budget-exhausted): the run's remaining budget cannot cover this worker's budget\"\n }\n if (shortfalls.some((shortfall) => shortfall.closedByUnknownSpend === true)) {\n const closed = shortfalls.find((shortfall) => shortfall.closedByUnknownSpend === true)!\n return `the run pool refused this spawn: ${shortfallClause(closed)}; the caller must re-run with a measurable or larger root budget`\n }\n return `the run pool refused this spawn: ${shortfalls.map(shortfallClause).join('; ')}; or ask the caller for a larger root budget`\n }\n }\n}\n\nconst BUDGET_FIELD: Readonly<Record<'tokens' | 'iterations' | 'usd', string>> = {\n tokens: 'maxTokens',\n iterations: 'maxIterations',\n usd: 'maxUsd',\n}\n","import { detachedFrozen } from '../../runtime/supervise/snapshot'\nimport type { McpToolDescriptor } from '../server'\nimport { spawnBudgetArg } from './coordination-budget'\nimport type { CoordinationToolsOptions, SpawnAdmission } from './coordination-contracts'\nimport { obj, str } from './coordination-input'\nexport function mountGraphsTools({\n opts,\n tools,\n admitSpawn,\n}: {\n readonly opts: CoordinationToolsOptions\n readonly tools: McpToolDescriptor[]\n readonly admitSpawn: (input: SpawnAdmission) => Promise<unknown>\n}): void {\n if (opts.graphs) {\n const graphs = opts.graphs\n tools.push({\n name: 'run_graph',\n description:\n 'Run an agent graph as ONE subtask instead of one worker: a fixed topology whose nodes are ' +\n 'profiles and whose edges carry directives, driven by its root node. Pass `graph` ' +\n \"({ nodes: [{ id, profile }], edges: [{ kind: 'delegates', from, to, directive: \" +\n \"'delegates/worker-brief/v1' }] }, where each profile.name equals its node id and the \" +\n 'root node grants agent_runtime_coordination_spawn_worker) or `graphDigest` (a graph ' +\n \"stored in this run's graph registry). `deliverable` is what the graph must deliver; it \" +\n \"becomes the root node's task. The subtask reserves `budget` (merged over the per-worker \" +\n 'default, as for spawn_worker) from your conserved pool, and the whole graph spends only ' +\n 'that. Every node runs its own pinned profile, and a node settles on its own ' +\n 'submit_result: the run keeps its checks and graders, which judge your result and are ' +\n 'never graph nodes. Returns a workerId as spawn_worker does; end your turn and ' +\n 'you are woken when the graph settles. Its output is { deliverable, edges }: the root ' +\n \"node's result and the edge ledger (every traversal, also recorded in the run journal).\",\n inputSchema: {\n type: 'object',\n properties: {\n graph: {\n type: 'object',\n description:\n 'The graph as data: { nodes: [{ id, profile }], edges: [...] }. Delegates edges ' +\n 'run from the root to each worker node; an optional analyzes edge ' +\n \"({ kind: 'analyzes', analyst, over, to, directive }) names an analyst node. With \" +\n \"entry ([{ node, task }]) it is a flow graph of routes edges ({ kind: 'routes', from, \" +\n 'to, directive, when? }), where Runtime starts the entries and decides every spawn.',\n additionalProperties: true,\n },\n graphDigest: {\n type: 'string',\n description: \"A stored graph's digest in this run's graph registry, instead of graph.\",\n },\n deliverable: {\n type: 'string',\n description: \"What the graph must deliver. It becomes the root node's task.\",\n },\n budget: spawnBudgetArg,\n label: { type: 'string', description: 'Optional trace label.' },\n key: {\n type: 'string',\n description:\n 'Optional semantic name for this subtask. The same key never runs twice, as for ' +\n 'spawn_worker: a completed key returns its committed result.',\n },\n },\n required: ['deliverable'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const deliverable = typeof a.deliverable === 'string' ? a.deliverable.trim() : ''\n if (deliverable.length === 0) {\n return {\n error: 'invalid-graph' as const,\n reason: 'deliverable must be a non-empty string: what the graph must deliver',\n }\n }\n if ((a.graph === undefined) === (a.graphDigest === undefined)) {\n return {\n error: 'invalid-graph' as const,\n reason: 'pass exactly one of graph (the graph as data) or graphDigest (a stored graph)',\n }\n }\n if (a.graphDigest !== undefined && typeof a.graphDigest !== 'string') {\n return { error: 'invalid-graph' as const, reason: 'graphDigest must be a string' }\n }\n const key = a.key === undefined ? undefined : str(a.key, 'key')\n const prepared = await graphs.prepare(\n typeof a.graphDigest === 'string' ? { graphDigest: a.graphDigest } : { graph: a.graph },\n )\n if (!prepared.ok) return { error: 'invalid-graph' as const, reason: prepared.reason }\n const profile = detachedFrozen(prepared.profile)\n return admitSpawn({\n profile,\n args: a,\n task: deliverable,\n key,\n // A graph root starts fresh: its continuity is its nodes' edges, inside the graph.\n continuity: { continuity: 'fresh' },\n successorOf: undefined,\n // A graph root is canonical already; this manager's resolver still judges it.\n preflightProfile: () =>\n opts.resolveSpawnProfile ? detachedFrozen(opts.resolveSpawnProfile(profile)) : profile,\n resourcesFromPath: [],\n defaultLabel: `graph:${prepared.root}`,\n accepted: { graph: { root: prepared.root, nodes: prepared.nodes } },\n })\n },\n })\n }\n}\n","import { resolveRedactor } from '../../redact'\nimport type { BusRecord, EventBus } from '../../runtime/supervise/event-bus'\nimport { detachedFrozen } from '../../runtime/supervise/snapshot'\nimport type { CoordinationToolsOptions } from './coordination-contracts'\nimport {\n type CoordinationEvent,\n JOURNAL_READ_BOUNDS,\n type JournalEntry,\n type JournalEventKind,\n type JournalPage,\n journalEventKinds,\n} from './coordination-events'\nimport { obj } from './coordination-input'\nimport { safeJsonText } from './coordination-json'\n\nexport function createJournalReader({\n opts,\n bus,\n}: {\n readonly opts: CoordinationToolsOptions\n readonly bus: EventBus<CoordinationEvent>\n}) {\n let journalReadTo = 0\n\n // ── read_journal ──────────────────────────────────────────────────────────────\n //\n // Reads `bus.history()`, which is this manager's own log and nothing else. Bounds are clamped,\n // never rejected: a model that asks for 10_000 rows gets `maxLimit` rows and reads the exact\n // bound it was given back in `bounds`, which is more useful than an error it has to re-plan\n // around. A kind it cannot name IS an error, because silently dropping an unknown filter would\n // answer a different question than the one asked.\n const redactJournalEvent = resolveRedactor(opts.redactJournal)\n const clampBound = (raw: unknown, field: string, fallback: number, max: number): number => {\n if (raw === undefined) return fallback\n if (typeof raw !== 'number' || !Number.isInteger(raw))\n throw new Error(`coordination tools: \"${field}\" must be an integer`)\n return Math.min(Math.max(raw, 1), max)\n }\n const journalKinds = (raw: unknown): ReadonlySet<JournalEventKind> | undefined => {\n if (raw === undefined) return undefined\n if (!Array.isArray(raw))\n throw new Error('coordination tools: \"kinds\" must be an array of event kinds')\n for (const kind of raw) {\n if (!(journalEventKinds as ReadonlyArray<unknown>).includes(kind))\n throw new Error(\n `coordination tools: \"kinds\" accepts ${journalEventKinds.join(', ')}; received ${JSON.stringify(kind)}`,\n )\n }\n return new Set(raw as ReadonlyArray<JournalEventKind>)\n }\n // DETACHED, then redacted, in that order and unconditionally. Detaching must not depend on which\n // redactor was configured: `redact: false` or a pass-through domain hook would otherwise hand the\n // manager live references into `bus.history()`, and in code mode a model-written program holds\n // that result and can write through it into the run's own audit log. A redactor that throws\n // yields a marker for that row alone — the manager still learns an event of that kind happened.\n const redactedRow = (record: BusRecord<CoordinationEvent>): unknown => {\n try {\n return redactJournalEvent(detachedFrozen(record.event))\n } catch (error) {\n return {\n type: record.event.type,\n redactionFailed: error instanceof Error ? error.message : String(error),\n }\n }\n }\n // Prior-process rows first, then this process's bus. `row` indexes THIS concatenation, so the\n // cursor is stable across a restart even though the bus `seq` space restarts with it.\n const priorJournal = opts.priorJournal ?? []\n const journalRows = (): ReadonlyArray<\n JournalEntry & { readonly record: BusRecord<CoordinationEvent> }\n > => {\n const rows: Array<JournalEntry & { readonly record: BusRecord<CoordinationEvent> }> = []\n let row = 0\n for (const record of priorJournal) {\n rows.push({\n row: row++,\n seq: record.seq,\n at: record.at,\n priority: record.priority,\n prior: true,\n event: undefined,\n record,\n })\n }\n for (const record of bus.history()) {\n rows.push({\n row: row++,\n seq: record.seq,\n at: record.at,\n priority: record.priority,\n event: undefined,\n record,\n })\n }\n return rows\n }\n const readJournal = (raw: unknown, trackOwnRead = true): JournalPage => {\n const a = raw === undefined ? {} : obj(raw)\n const sinceRow =\n a.sinceRow === undefined\n ? 0\n : typeof a.sinceRow === 'number' && Number.isInteger(a.sinceRow) && a.sinceRow >= 0\n ? a.sinceRow\n : (() => {\n throw new Error('coordination tools: \"sinceRow\" must be a non-negative integer')\n })()\n const limit = clampBound(\n a.limit,\n 'limit',\n JOURNAL_READ_BOUNDS.defaultLimit,\n JOURNAL_READ_BOUNDS.maxLimit,\n )\n const maxBytes = clampBound(\n a.maxBytes,\n 'maxBytes',\n JOURNAL_READ_BOUNDS.defaultMaxBytes,\n JOURNAL_READ_BOUNDS.maxMaxBytes,\n )\n const kinds = journalKinds(a.kinds)\n const matching = journalRows().filter(\n (candidate) =>\n candidate.row >= sinceRow && (!kinds || kinds.has(candidate.record.event.type)),\n )\n\n const entries: JournalEntry[] = []\n // Seeded with the array's own two brackets, and each later row adds its separating comma, so\n // `usedBytes` equals the byte length of the `entries` array the caller receives — not a sum\n // that ignores the envelope and overshoots the budget by a few bytes on a full page.\n const envelopeBytes = 2\n let usedBytes = envelopeBytes\n let index = 0\n // A bound APPLIED, which is not the same as \"records were left over\": an oversize row is\n // consumed and still elided, so a caller keying completeness off `truncated` must see it.\n let bounded = false\n for (; index < matching.length; index++) {\n if (entries.length >= limit) {\n bounded = true\n break\n }\n const candidate = matching[index] as (typeof matching)[number]\n const { record, event: _placeholder, ...stamp } = candidate\n const row: JournalEntry = { ...stamp, event: redactedRow(record) }\n // Measured on the ASSEMBLED row, because the stamp is part of what the caller receives; the\n // event alone under-counts by ~50 bytes a row and a full page then overshoots the budget.\n const bytes = Buffer.byteLength(safeJsonText(row), 'utf8') + (entries.length === 0 ? 0 : 1)\n if (usedBytes + bytes > maxBytes) {\n bounded = true\n // A row that cannot fit ANY budget would stall the cursor forever, so the first row of a\n // page is always emitted — as a marker when it is too big to render.\n if (entries.length > 0) break\n const marker: JournalEntry = {\n ...stamp,\n event: { type: record.event.type },\n oversize: { type: record.event.type, bytes },\n }\n entries.push(marker)\n usedBytes += Buffer.byteLength(safeJsonText(marker), 'utf8')\n // The marker is only ever the FIRST row of a page, so it never adds a separator.\n index++\n break\n }\n entries.push(row)\n usedBytes += bytes\n }\n const last = entries[entries.length - 1]\n const nextRow = last === undefined ? sinceRow : last.row + 1\n if (trackOwnRead) journalReadTo = Math.max(journalReadTo, nextRow)\n return {\n entries,\n nextRow,\n remaining: matching.length - index,\n truncated: bounded,\n bounds: { sinceRow, limit, maxBytes, usedBytes },\n priorRows: priorJournal.length,\n }\n }\n\n return { readJournal, priorJournal, redactJournalEvent, readTo: () => journalReadTo }\n}\n","import type { Scope } from '../../runtime'\nimport type { BusRecord, EventBus } from '../../runtime/supervise/event-bus'\nimport { isLiveNodeStatus } from '../../runtime/supervise/node-status'\nimport { detachedFrozen } from '../../runtime/supervise/snapshot'\nimport type { CoordinationToolsOptions, SettledWorker } from './coordination-contracts'\nimport { eventWorker, projectEvent } from './coordination-event-projection'\nimport type { CoordinationEvent, Delivery, ManagerReentryState } from './coordination-events'\nimport type { createJournalReader } from './coordination-journal-reader'\nimport type { createWorkerObservation } from './coordination-worker-observation'\n\nexport function managerReentryState({\n opts,\n ledger,\n deliveries,\n priorJournal,\n bus,\n journal,\n openWork,\n driverAttempt,\n lastRejection,\n}: {\n readonly opts: CoordinationToolsOptions\n readonly ledger: ReadonlyArray<SettledWorker>\n readonly deliveries: ReadonlyArray<Delivery>\n readonly priorJournal: ReadonlyArray<BusRecord<CoordinationEvent>>\n readonly bus: EventBus<CoordinationEvent>\n readonly journal: ReturnType<typeof createJournalReader>\n readonly openWork: ReturnType<typeof createWorkerObservation>['openWork']\n readonly driverAttempt: number | undefined\n readonly lastRejection: { readonly at: number; readonly reason: string } | undefined\n}): ManagerReentryState {\n const { unqueued, queued } = openWork()\n const deliveredSettled = new Set(\n deliveries.flatMap((delivery) =>\n delivery.record.event.type === 'settled' ? [delivery.record.event.worker.id] : [],\n ),\n )\n return detachedFrozen<ManagerReentryState>({\n journalRows: priorJournal.length + bus.history().length,\n journalReadTo: journal.readTo(),\n live: ((opts.scope as Partial<Scope<unknown>>).view?.nodes ?? [])\n .filter((node) => isLiveNodeStatus(node.status))\n .map((node) => ({ id: node.id, label: node.label, status: node.status })),\n settled: [\n ...ledger.map((worker) => ({\n id: worker.id,\n status: worker.status,\n ...(worker.status === 'done' && worker.valid !== undefined ? { valid: worker.valid } : {}),\n delivered: deliveredSettled.has(worker.id),\n })),\n ...unqueued.map((node) => ({\n id: node.id,\n status: node.status === 'done' ? ('done' as const) : ('down' as const),\n delivered: false,\n })),\n ],\n waiting: [\n ...queued.map((record) => ({\n type: record.event.type,\n ...(eventWorker(record.event) === undefined ? {} : { worker: eventWorker(record.event) }),\n })),\n ...unqueued.map((node) => ({ type: 'settled', worker: node.id })),\n ],\n // The current attempt's own deliveries are its wake's events, which its input already\n // shows; only an earlier attempt's unacknowledged deliveries are unread.\n unacknowledged: deliveries\n .filter((delivery) => !delivery.acknowledged && delivery.attempt !== driverAttempt)\n .map((delivery) => ({\n seq: delivery.record.seq,\n type: delivery.record.event.type,\n ...(eventWorker(delivery.record.event) === undefined\n ? {}\n : { worker: eventWorker(delivery.record.event) }),\n ...(delivery.attempt === undefined ? {} : { attempt: delivery.attempt }),\n event: { ...projectEvent(delivery.record.event), eventSeq: delivery.record.seq },\n })),\n ...(lastRejection === undefined ? {} : { lastRejection }),\n })\n}\n","import { errMessage } from '../../runtime/supervise/error-message'\nimport type { SpawnAdmission } from './coordination-contracts'\n\n/** What a keyed runtime spawn (a flow's entry or route, a map's item or join) became. */\nexport type RuntimeSpawnOutcome =\n /** `committed`: the key's done settlement is already on disk, so nothing ran and the caller\n * settles that result itself; no settlement drain will ever carry it. */\n | { readonly workerId: string; readonly committed: boolean }\n /** The key and its one replacement both have a prior worker started without a terminal receipt. */\n | { readonly inDoubt: true }\n | { readonly refused: string }\n\n/**\n * Admit one keyed runtime spawn. A key whose prior worker is in doubt (started in a dead process\n * with no terminal receipt) is re-admitted once under `<key>#2`, the replacement key the\n * `spawn_worker` contract names; a replacement that is in doubt too is reported, never retried.\n */\nexport async function admitRuntimeSpawn(\n admitSpawn: (input: SpawnAdmission) => Promise<unknown>,\n input: SpawnAdmission & { readonly key: string },\n): Promise<RuntimeSpawnOutcome> {\n for (const key of [input.key, `${input.key}#2`]) {\n let response: unknown\n try {\n response = await admitSpawn({ ...input, key })\n } catch (error) {\n return { refused: errMessage(error) }\n }\n const started = response as Partial<\n Record<'workerId' | 'resumed' | 'error' | 'reason', unknown>\n >\n if (typeof started.workerId === 'string') {\n return { workerId: started.workerId, committed: started.resumed === 'completed' }\n }\n if (started.error !== 'in-doubt') {\n return { refused: typeof started.reason === 'string' ? started.reason : 'spawn refused' }\n }\n }\n return { inDoubt: true }\n}\n","import type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { Scope, Settled } from '../../runtime'\nimport { errMessage } from '../../runtime/supervise/error-message'\nimport type { EventBus } from '../../runtime/supervise/event-bus'\nimport { detachedFrozen } from '../../runtime/supervise/snapshot'\nimport type {\n CoordinationToolsOptions,\n SettledWorker,\n SpawnAdmission,\n} from './coordination-contracts'\nimport type { CoordinationEvent } from './coordination-events'\nimport { safeJsonText } from './coordination-json'\nimport type { MapOnSettleRoute, MapTraversalEvent } from './coordination-map-contracts'\nimport { admitRuntimeSpawn } from './coordination-runtime-spawn'\n\nexport function createMapRouting({\n opts,\n bus,\n admitSpawn,\n nodeOf,\n settleCommitted,\n endInDoubt,\n}: {\n readonly opts: CoordinationToolsOptions\n readonly bus: EventBus<CoordinationEvent>\n readonly admitSpawn: (input: SpawnAdmission) => Promise<unknown>\n /** The node a worker of this manager runs, by profile name. */\n readonly nodeOf: (workerId: string) => string | undefined\n /** Run a committed spawn's journaled settle through the live settle path. */\n readonly settleCommitted: (workerId: string, node: string) => Promise<void>\n /** End a flow whose map spawn is in doubt twice, at the node and source worker named. */\n readonly endInDoubt: (node: string, source: string) => Promise<void>\n}) {\n // ── Map routes: fan-out over a run-time list, then one join ──\n // A map's items and its join are runtime spawns, like analyst runs: each takes the admission a\n // `spawn_worker` call takes, so the pool, the pre-flight and the pinning authority judge it, and\n // no manager turn is spent starting it.\n const mapRoutes = opts.mapOnSettle ?? []\n interface MapExpansion {\n readonly route: MapOnSettleRoute\n readonly sourceWorker: string\n /** The source node's 1-based done-settle count: its spawns' keys are\n * `map:<edge>#<expansion>:<index>` and `map:<edge>#<expansion>:join`. */\n readonly expansion: number\n readonly items: ReadonlyArray<unknown>\n readonly settlements: Array<WorkerSettlement | undefined>\n /** The next index to start. */\n next: number\n inFlight: number\n /** Set by a failed item under all-or-refuse: no further item starts. */\n stopped: boolean\n finished: boolean\n }\n const mapMembers = new Map<\n string,\n {\n readonly expansion: MapExpansion\n readonly role: 'item' | 'join'\n readonly index?: number\n readonly bytes: number\n }\n >()\n const textBytes = (value: unknown): number => Buffer.byteLength(safeJsonText(value), 'utf8')\n const publishMap = async (event: MapTraversalEvent, wake = false): Promise<void> => {\n const record = detachedFrozen<CoordinationEvent>({ type: 'map', map: event })\n if (wake) await bus.publish(record)\n else await bus.publish(record, { queue: false })\n }\n // The run's worker-slot bound, or undefined when only the pool bounds concurrency.\n const workerSlotBound = (): number | undefined => {\n const capacity = (opts.scope as Partial<Scope<unknown>>).workerCapacity\n if (capacity === undefined || capacity.freeSlots === null) return undefined\n return capacity.working + capacity.freeSlots\n }\n // A started spawn is a map member until it settles. A committed one (its key's done settlement\n // is on disk from a prior process) settles at once through the live settle path, so a restarted\n // manager re-expanding a map runs only the items with no done settlement, then the join once.\n // A spawn in doubt twice is refused, and ends a flow.\n const startMapSpawn = async (\n expansion: MapExpansion,\n role: 'item' | 'join',\n profile: AgentProfile,\n task: unknown,\n index: number | undefined,\n ): Promise<{ readonly workerId: string } | { readonly refused: string }> => {\n const { route } = expansion\n const name =\n typeof profile.name === 'string' && profile.name.length > 0 ? profile.name : 'worker'\n const spawned = await admitRuntimeSpawn(admitSpawn, {\n profile,\n args: {\n label: index === undefined ? name : `${name}#${index}`,\n ...(role === 'item' && route.itemBudget !== undefined ? { budget: route.itemBudget } : {}),\n },\n task,\n key: `map:${route.edge}#${expansion.expansion}:${index ?? 'join'}`,\n continuity: { continuity: 'fresh' },\n successorOf: undefined,\n preflightProfile: () =>\n opts.resolveSpawnProfile ? detachedFrozen(opts.resolveSpawnProfile(profile)) : profile,\n resourcesFromPath: [],\n defaultLabel: name,\n map: Object.freeze({ edge: route.edge, role, ...(index === undefined ? {} : { index }) }),\n })\n if ('inDoubt' in spawned) {\n await endInDoubt(name, expansion.sourceWorker)\n return { refused: `in-doubt:${name}` }\n }\n if ('refused' in spawned) return spawned\n mapMembers.set(spawned.workerId, {\n expansion,\n role,\n ...(index === undefined ? {} : { index }),\n bytes: textBytes(task),\n })\n if (role === 'item') expansion.inFlight += 1\n if (spawned.committed) await settleCommitted(spawned.workerId, name)\n return { workerId: spawned.workerId }\n }\n // A graph item starts the way `run_graph` starts a graph: the run prepares the same root profile.\n const mapItemProfile = async (\n route: MapOnSettleRoute,\n ): Promise<{ readonly profile: AgentProfile } | { readonly refused: string }> => {\n if ('profile' in route.item) return { profile: route.item.profile }\n if (!opts.graphs) {\n return { refused: 'a graph item starts through run_graph, which this manager does not serve' }\n }\n const prepared = await opts.graphs.prepare({ graph: route.item.graph })\n return prepared.ok\n ? { profile: detachedFrozen(prepared.profile) }\n : { refused: prepared.reason }\n }\n const startMapItem = async (expansion: MapExpansion, index: number): Promise<void> => {\n const { route } = expansion\n const resolved = await mapItemProfile(route)\n const started =\n 'refused' in resolved\n ? resolved\n : await startMapSpawn(expansion, 'item', resolved.profile, expansion.items[index], index)\n if ('workerId' in started) return\n const reason = `item spawn refused: ${started.refused}`\n expansion.settlements[index] = { outcome: 'unpropagated', reason }\n if (route.onItemFailure === 'all-or-refuse') expansion.stopped = true\n await publishMap({\n edge: route.edge,\n phase: 'item',\n outcome: 'unpropagated',\n sourceWorker: expansion.sourceWorker,\n index,\n bytes: 0,\n reason,\n })\n }\n // Start items until the concurrency cap is reached, the list is exhausted, or all-or-refuse\n // stopped the map; once nothing is in flight, the map finishes.\n const pumpMap = async (expansion: MapExpansion): Promise<void> => {\n const { route, items } = expansion\n while (\n !expansion.stopped &&\n expansion.inFlight < route.concurrency &&\n expansion.next < items.length\n ) {\n const index = expansion.next\n expansion.next += 1\n await startMapItem(expansion, index)\n }\n if (expansion.inFlight === 0) await finishMap(expansion)\n }\n // Every item settled or was never started: record the unstarted ones, then start the join with\n // the ordered results, or refuse it. `closed` names why a manager that already stopped does not\n // run the join; nobody would read it.\n const finishMap = async (expansion: MapExpansion, closed?: string): Promise<void> => {\n if (expansion.finished) return\n expansion.finished = true\n const { route, items, sourceWorker } = expansion\n for (let index = expansion.next; index < items.length; index += 1) {\n const reason = closed ?? 'not started: all-or-refuse stopped this map after an item failed'\n expansion.settlements[index] = { outcome: 'unpropagated', reason }\n await publishMap({\n edge: route.edge,\n phase: 'item',\n outcome: 'unpropagated',\n sourceWorker,\n index,\n bytes: 0,\n reason,\n })\n }\n expansion.next = items.length\n const results: Array<{ index: number; item: unknown; result: unknown }> = []\n const failures: Array<{ index: number; item: unknown; outcome: string; reason: string }> = []\n items.forEach((item, index) => {\n const settlement = expansion.settlements[index]\n if (settlement?.outcome === 'delivered') {\n results.push({ index, item, result: settlement.result })\n } else {\n failures.push({\n index,\n item,\n outcome: settlement?.outcome ?? 'unpropagated',\n reason: settlement?.reason ?? 'never settled',\n })\n }\n })\n const refusal =\n closed ??\n (route.onItemFailure === 'all-or-refuse' && failures.length > 0\n ? `all-or-refuse: ${failures.length} of ${items.length} items did not deliver (${failures\n .map((failure) => `#${failure.index} ${failure.outcome}: ${failure.reason}`)\n .join('; ')}); the join did not run`\n : undefined)\n if (refusal !== undefined) {\n // No settlement follows a refused join, so this event is what wakes the manager.\n await publishMap(\n {\n edge: route.edge,\n phase: 'join',\n outcome: 'unpropagated',\n sourceWorker,\n bytes: 0,\n reason: refusal,\n },\n closed === undefined,\n )\n return\n }\n const task = { map: route.edge, source: sourceWorker, items: items.length, results, failures }\n const started = await startMapSpawn(expansion, 'join', route.join, task, undefined)\n if ('refused' in started) {\n await publishMap(\n {\n edge: route.edge,\n phase: 'join',\n outcome: 'unpropagated',\n sourceWorker,\n bytes: 0,\n reason: `join spawn refused: ${started.refused}`,\n },\n true,\n )\n }\n // A started join is recorded when it settles; its outcome is not known before.\n }\n // A map item or join settled. `advance` is false once the manager stopped: no further item or\n // join starts, and what never started is recorded as such.\n const settleMapMember = async (\n settled: Settled<unknown>,\n worker: SettledWorker,\n advance: boolean,\n ): Promise<void> => {\n const member = mapMembers.get(worker.id)\n if (member === undefined) return\n mapMembers.delete(worker.id)\n const { expansion, role, index, bytes } = member\n const settlement = workerSettlement(settled, worker)\n await publishMap({\n edge: expansion.route.edge,\n phase: role,\n outcome: settlement.outcome,\n sourceWorker: expansion.sourceWorker,\n ...(index === undefined ? {} : { index }),\n workerId: worker.id,\n bytes,\n ...(settlement.reason === undefined ? {} : { reason: settlement.reason }),\n })\n if (role === 'join' || index === undefined) return\n expansion.inFlight -= 1\n expansion.settlements[index] = settlement\n if (settlement.outcome !== 'delivered' && expansion.route.onItemFailure === 'all-or-refuse') {\n expansion.stopped = true\n }\n if (advance) await pumpMap(expansion)\n else if (expansion.inFlight === 0) {\n await finishMap(expansion, 'not started: the manager stopped before this map finished')\n }\n }\n // The expansion number of a source's done settle. A settle a prior process committed keeps the\n // number it had there (its rank among the resumed done settles of that node), so a replay\n // re-derives the keys that process journaled. A new settle counts on past every prior settle and\n // every journaled expansion: a root-driven graph replays no prior settle, and its driver may\n // label a worker other than by its node.\n const liveExpansions = new Map<string, number>()\n const expansionOf = (source: string, workerId: string): number => {\n const resume = opts.scope.resume\n const labels = new Map(resume?.view.nodes.map((node) => [node.id, node.label]) ?? [])\n const prior = (resume?.settled ?? [])\n .filter((s) => s.kind === 'done' && labels.get(s.handle.id) === source)\n .map((s) => s.handle.id)\n const rank = prior.indexOf(workerId)\n if (rank >= 0) return rank + 1\n let journaled = 0\n for (const route of mapRoutes) {\n if (route.from !== source) continue\n const prefix = `key:map:${route.edge}#`\n for (const node of resume?.view.nodes ?? []) {\n if (!node.assignmentId?.startsWith(prefix)) continue\n const n = Number.parseInt(node.assignmentId.slice(prefix.length), 10)\n if (Number.isSafeInteger(n)) journaled = Math.max(journaled, n)\n }\n }\n const live = (liveExpansions.get(source) ?? 0) + 1\n liveExpansions.set(source, live)\n return Math.max(prior.length, journaled) + live\n }\n // A source settled `done`: expand every map that names it.\n const expandMaps = async (settled: Settled<unknown>, worker: SettledWorker): Promise<void> => {\n if (settled.kind !== 'done' || mapRoutes.length === 0) return\n const name = nodeOf(worker.id)\n if (name === undefined || !mapRoutes.some((route) => route.from === name)) return\n const expansion = expansionOf(name, worker.id)\n for (const route of mapRoutes) {\n if (route.from !== name) continue\n const refuse = (reason: string): Promise<void> =>\n publishMap(\n {\n edge: route.edge,\n phase: 'expand',\n outcome: 'unpropagated',\n sourceWorker: worker.id,\n bytes: 0,\n reason,\n },\n true,\n )\n const selected = resolveJsonPointer(settled.out, route.pointer)\n if (!selected.found) {\n await refuse(\n `pointer ${JSON.stringify(route.pointer)} does not resolve in the source result: ${selected.reason}; no item ran`,\n )\n continue\n }\n const items = selected.value\n if (!Array.isArray(items)) {\n await refuse(\n `pointer ${JSON.stringify(route.pointer)} resolves to ${items === null ? 'null' : typeof items}, not an array; no item ran`,\n )\n continue\n }\n if (items.length > route.maxItems) {\n await refuse(\n `max-items-exceeded: the list holds ${items.length} items and this map admits at most ${route.maxItems}; no item ran`,\n )\n continue\n }\n const slots = workerSlotBound()\n if (slots !== undefined && route.concurrency > slots) {\n await refuse(\n `concurrency-unsatisfiable: concurrency ${route.concurrency} exceeds this run's ${slots} worker slots, so the cap could never be honored; no item ran`,\n )\n continue\n }\n await publishMap({\n edge: route.edge,\n phase: 'expand',\n outcome: items.length === 0 ? 'empty' : 'delivered',\n sourceWorker: worker.id,\n bytes: textBytes(items),\n items: items.length,\n ...(items.length === 0\n ? { reason: 'the list is empty; the join runs with no results' }\n : {}),\n })\n await pumpMap({\n route,\n sourceWorker: worker.id,\n expansion,\n items: detachedFrozen(items),\n settlements: [],\n next: 0,\n inFlight: 0,\n stopped: false,\n finished: false,\n })\n }\n }\n // Map steps run on the settlement path, which must never be taken down by them.\n const runMapStep = async (step: () => Promise<void>, worker: SettledWorker): Promise<void> => {\n try {\n await step()\n } catch (error) {\n console.error('Runtime map step failed', {\n managerId: opts.scope.view.root,\n worker: worker.id,\n error: errMessage(error),\n })\n }\n }\n\n return {\n isItem: (workerId: string) => mapMembers.get(workerId)?.role === 'item',\n settleMapMember,\n expandMaps,\n runMapStep,\n }\n}\n\n/** What one settle delivered. A settle is usable (`delivered`) when it settled `done`, its\n * deliverable check did not reject it, and its result is defined; maps and routes both read\n * results through this one rule. */\ninterface WorkerSettlement {\n readonly outcome: 'delivered' | 'empty' | 'failed' | 'unpropagated'\n readonly result?: unknown\n readonly reason?: string\n}\n\nexport function workerSettlement(\n settled: Settled<unknown>,\n worker: SettledWorker,\n): WorkerSettlement {\n if (settled.kind !== 'done' || worker.status !== 'done') {\n return { outcome: 'failed', reason: worker.status === 'down' ? worker.reason : 'down' }\n }\n if (worker.valid === false) {\n return { outcome: 'failed', reason: 'its deliverable check rejected the result' }\n }\n if (settled.out === undefined) return { outcome: 'empty', reason: 'it settled with no result' }\n return { outcome: 'delivered', result: settled.out }\n}\n\n/** Resolve an RFC 6901 JSON pointer (`''` is the whole document). */\nexport function resolveJsonPointer(\n document: unknown,\n pointer: string,\n):\n | { readonly found: true; readonly value: unknown }\n | { readonly found: false; readonly reason: string } {\n if (pointer === '') return { found: true, value: document }\n if (!pointer.startsWith('/')) {\n return { found: false, reason: 'a JSON pointer is empty or starts with \"/\"' }\n }\n let value = document\n for (const raw of pointer.slice(1).split('/')) {\n const token = raw.replaceAll('~1', '/').replaceAll('~0', '~')\n if (Array.isArray(value)) {\n if (!/^(0|[1-9]\\d*)$/.test(token) || Number(token) >= value.length) {\n return {\n found: false,\n reason: `no index ${JSON.stringify(token)} in an array of ${value.length}`,\n }\n }\n value = value[Number(token)]\n } else if (typeof value === 'object' && value !== null && Object.hasOwn(value, token)) {\n value = (value as Record<string, unknown>)[token]\n } else {\n return { found: false, reason: `no member ${JSON.stringify(token)}` }\n }\n }\n return { found: true, value }\n}\n","import type { EventBus } from '../../runtime/supervise/event-bus'\nimport type { CoordinationToolsOptions } from './coordination-contracts'\nimport type { CoordinationEvent } from './coordination-events'\nimport { level, str, urgency, urgencyPriority } from './coordination-input'\nimport type {\n Question,\n QuestionDecision,\n QuestionEscalationOutcome,\n QuestionEscalationRecord,\n QuestionInput,\n QuestionRecord,\n} from './coordination-questions'\n\nexport function createQuestionLedger({\n opts,\n bus,\n}: {\n readonly opts: CoordinationToolsOptions\n readonly bus: EventBus<CoordinationEvent>\n}) {\n let questionSeq = 0\n const questions: QuestionRecord[] = [...(opts.priorQuestions ?? [])]\n const questionPolicy = opts.questionPolicy ?? 'auto'\n\n const nextQuestionId = (from: string): string => {\n for (;;) {\n const id = `${from}:q${questionSeq++}`\n if (!questions.some((question) => question.id === id)) return id\n }\n }\n const normalizeQuestion = (q: QuestionInput, fallbackFrom: string): Question => {\n const from = str(q.from ?? fallbackFrom, 'from')\n return {\n id: typeof q.id === 'string' && q.id.length > 0 ? q.id : nextQuestionId(from),\n from,\n level: level(q.level),\n question: str(q.question, 'question'),\n reason: str(q.reason, 'reason'),\n ...(q.options ? { options: q.options } : {}),\n urgency: urgency(q.urgency),\n }\n }\n const addQuestion = (\n raw: QuestionInput,\n fallbackFrom: string,\n decision?: QuestionDecision,\n ): { question: QuestionRecord; added: boolean } => {\n const q = normalizeQuestion(raw, fallbackFrom)\n const existing = questions.find((x) => x.id === q.id)\n if (existing) return { question: existing, added: false }\n const effectiveDecision =\n decision ??\n (questionPolicy === 'bubble'\n ? ({\n kind: 'escalate',\n to: 'parent',\n reason: 'question policy bubbled to parent',\n } as const)\n : undefined)\n const status: QuestionRecord['status'] =\n effectiveDecision?.kind === 'answer'\n ? 'answered'\n : effectiveDecision?.kind === 'defer'\n ? 'deferred'\n : effectiveDecision?.kind === 'escalate'\n ? 'escalated'\n : 'open'\n const record: QuestionRecord = {\n ...q,\n status,\n openedAt: Date.now(),\n ...(effectiveDecision ? { decision: effectiveDecision } : {}),\n }\n questions.push(record)\n return { question: record, added: true }\n }\n const emitNewQuestion = async (record: {\n question: QuestionRecord\n added: boolean\n }): Promise<QuestionRecord> => {\n if (record.added)\n await bus.publish(\n { type: 'question', question: record.question },\n { priority: urgencyPriority(record.question.urgency) },\n )\n return record.question\n }\n /** The refusal every `answer_question` path returns for an id this manager has no question for.\n * A THROW here reaches the manager as a transport error with no vocabulary it can act on, and\n * this is the verb the `no-parent` guidance tells it to use — so it names the condition. */\n const unknownQuestion = (questionId: string) => ({\n error: 'unknown-question' as const,\n reason: `this manager has no question with the id ${JSON.stringify(questionId)}; call list_questions for the ids you may decide`,\n })\n const decideQuestion = (questionId: string, decision: QuestionDecision): QuestionRecord => {\n const idx = questions.findIndex((q) => q.id === questionId)\n if (idx < 0) throw new Error(`unknown questionId ${JSON.stringify(questionId)}`)\n const prior = questions[idx] as QuestionRecord\n const status: QuestionRecord['status'] =\n decision.kind === 'answer' ? 'answered' : decision.kind === 'defer' ? 'deferred' : 'escalated'\n const next: QuestionRecord = { ...prior, status, decision }\n questions[idx] = next\n return next\n }\n // ── ask_parent, and the honest answer when nothing is above ───────────────────\n //\n // A manager that escalates a BLOCKING question and reads a bare receipt waits for an answer. When\n // no parent inbox exists, that wait never ends, and a fail-closed stop policy then refuses every\n // `stop` for the rest of the run — the question is counted as unresolved forever. So the outcome\n // is stated, every time: `queued-for-parent` when something took the question, `no-parent` when\n // nothing did, and in the second case the manager is told it is the last decider.\n const escalations: QuestionEscalationRecord[] = [...(opts.priorEscalations ?? [])]\n const escalate = async (question: QuestionRecord): Promise<QuestionEscalationRecord> => {\n let outcome: QuestionEscalationOutcome\n if (opts.escalateQuestion === undefined) {\n outcome = {\n delivered: false,\n reason:\n 'this manager has no parent inbox in this run, so nothing above it can receive the question',\n }\n } else {\n try {\n outcome = await opts.escalateQuestion(question)\n } catch (error) {\n // A broken parent channel is an UNDELIVERED escalation, never a delivered one: reading a\n // throw as success is exactly the silent wait this verb exists to remove.\n outcome = {\n delivered: false,\n reason: `the parent channel refused the question: ${error instanceof Error ? error.message : String(error)}`,\n }\n }\n }\n const record: QuestionEscalationRecord = Object.freeze({\n questionId: question.id,\n from: question.from,\n urgency: question.urgency,\n delivered: outcome.delivered,\n ...(outcome.delivered ? { to: outcome.to } : { reason: outcome.reason }),\n at: Date.now(),\n })\n escalations.push(record)\n await bus.publish({ type: 'escalation', escalation: record }, { queue: false })\n return record\n }\n\n const blockingQuestionsForStop = (): QuestionRecord[] => {\n if (questionPolicy === 'auto' || questionPolicy === 'bubble') return []\n return questions.filter((q) => {\n const blocking = q.urgency === 'blocks-step' || q.urgency === 'blocks-run'\n if (!blocking) return false\n if (questionPolicy === 'mustDecide') return q.status === 'open'\n return q.status !== 'answered' && q.status !== 'deferred'\n })\n }\n\n return {\n questions,\n addQuestion,\n emitNewQuestion,\n unknownQuestion,\n decideQuestion,\n escalations,\n escalate,\n blockingQuestionsForStop,\n }\n}\n","import type { NodeExecutionIdentity } from '../../runtime'\n\n/**\n * Why one parent→child delivery did not land, in the words the MANAGER needs.\n *\n * `DownMessageDeliveryOutcome` is the machine code; this is the sentence beside it. A code alone\n * left the manager to guess whether to retry, spawn, or give up — `already-settled` and\n * `scope-stopped` look alike and need opposite moves. Every refusal a coordination verb returns\n * carries a sentence like these, because the manager cannot see the state that produced it.\n */\nexport const downMessageRefusalReasons: Readonly<Record<DownMessageDeliveryOutcome, string>> =\n Object.freeze({\n delivered: 'the message reached the worker',\n 'unknown-worker':\n 'no worker of this manager has that id — check observe_agent for the live ids',\n 'already-settled':\n 'that worker already settled, so nothing can reach it — spawn a fresh worker for the follow-up work',\n 'runtime-has-no-inbox':\n 'that worker runs on an executor with no inbox, so it can never receive a message — re-spawn it on a steerable executor if it must be corrected mid-run',\n 'scope-stopped': 'this manager’s scope has stopped, so no further message may be sent from it',\n 'runtime-error':\n 'the executor threw while accepting the message; the worker may or may not have received it',\n })\n\n/** How a spawn CONTINUES a node's prior work: `'fresh'` starts a brand-new session (the default,\n * and the only pre-continuity behavior); `'resume'` re-attaches to the node's most recent\n * SETTLED worker — a NEW live worker is spawned whose spawn context carries the prior worker's\n * identity ({@link WorkerResumeContext}), and the executor seam owns the actual session\n * re-attachment. */\nexport type ContinuityMode = 'fresh' | 'resume'\n\n/** The resume lineage a `'resume'` spawn hands the executor seam\n * ({@link WorkerSpawnContext.resume}). The kernel owns identity, ordering, ledger truth, and\n * spend continuity (the resumed worker reserves from the same conserved pool); the seam owns the\n * re-attachment itself — e.g. mapping `ofWorker` to a backend session id. */\nexport interface WorkerResumeContext {\n /** The prior SETTLED worker whose session the new worker continues. */\n readonly ofWorker: string\n /** 1-based position of the NEW worker in the node's continuity chain: a node spawned once and\n * resumed once hands the resumed worker `sequence: 2`. */\n readonly sequence: number\n}\n\n/** The exact result of one parent→child delivery attempt. */\nexport type DownMessageDeliveryOutcome =\n | 'delivered'\n | 'unknown-worker'\n | 'already-settled'\n | 'runtime-has-no-inbox'\n | 'scope-stopped'\n | 'runtime-error'\n\n/** A durable marker written after authorization and immediately before Runtime calls `Scope.send`.\n * If a process dies with this marker but no matching outcome, delivery is unknown and is never\n * replayed automatically. */\nexport interface DownMessageDeliveryAttempt {\n readonly receiptId: string\n readonly kind: 'steer' | 'answer'\n readonly toWorker: string\n readonly instructionDigest: string\n readonly interrupt: boolean\n readonly questionId?: string\n}\n\n/** A parent→child delivery result (the down-leg): recorded for observability, never pulled back by\n * the parent. `receiptId` and `instructionDigest` link it to the pre-delivery authorization receipt\n * and attempt marker. */\nexport interface DownMessageEvent {\n readonly receiptId: string\n readonly toWorker: string\n readonly instruction: string\n readonly instructionDigest: string\n readonly delivered: boolean\n readonly outcome: DownMessageDeliveryOutcome\n readonly error?: string\n}\n\n/** Durable authorization receipt written before a continuation reaches a worker. */\nexport interface ContinuationInstruction {\n readonly receiptId: string\n readonly kind: 'steer' | 'answer'\n readonly toWorker: string\n readonly instruction: string\n readonly instructionDigest: string\n readonly workerIdentity?: NodeExecutionIdentity\n readonly interrupt: boolean\n readonly questionId?: string\n}\n\n/** Detached continuation bytes and exact worker identity presented to product authorization before\n * Runtime records or delivers a steer/answer. */\nexport interface DownMessageAuthorizationInput {\n readonly kind: 'steer' | 'answer'\n readonly workerId: string\n readonly workerIdentity: NodeExecutionIdentity\n readonly instruction: string\n readonly interrupt: boolean\n readonly questionId?: string\n}\n\n/** Product-authorized continuation bytes. Returning a narrowed instruction replaces the proposed\n * bytes; throwing refuses delivery. */\nexport interface AuthorizedDownMessage {\n readonly instruction: string\n}\n\n/** Product decision over an exact continuation before it is durably recorded or delivered. */\nexport type AuthorizeDownMessage = (input: DownMessageAuthorizationInput) => AuthorizedDownMessage\n","export type QuestionLevel = 'worker' | 'driver' | 'loop'\n\nexport type QuestionUrgency = 'continue-without' | 'blocks-step' | 'blocks-run'\n\nexport interface QuestionOption {\n readonly label: string\n readonly tradeoff: string\n}\n\nexport interface Question {\n readonly id: string\n readonly from: string\n readonly level: QuestionLevel\n readonly question: string\n readonly reason: string\n readonly urgency: QuestionUrgency\n readonly options?: ReadonlyArray<QuestionOption>\n}\n\n/** Where a question this driver cannot answer goes next. `answer_question` accepts these and\n * nothing else, so the decision type states them and nothing else. */\nexport const questionEscalationTargets = ['parent', 'user'] as const\n\nexport type QuestionEscalationTarget = (typeof questionEscalationTargets)[number]\n\nexport const isQuestionEscalationTarget = (value: unknown): value is QuestionEscalationTarget =>\n (questionEscalationTargets as ReadonlyArray<unknown>).includes(value)\n\nexport type QuestionDecision =\n | { readonly kind: 'answer'; readonly answer: string; readonly by: string }\n | { readonly kind: 'defer'; readonly reason: string }\n | {\n readonly kind: 'escalate'\n readonly to: QuestionEscalationTarget\n readonly reason: string\n }\n\nexport interface QuestionRecord extends Question {\n readonly status: 'open' | 'answered' | 'deferred' | 'escalated'\n readonly decision?: QuestionDecision\n readonly openedAt: number\n}\n\nexport type QuestionInput = Omit<Question, 'id'> & { readonly id?: string }\n\nexport type QuestionPolicy = 'auto' | 'mustDecide' | 'bubble' | 'failClosed'\n\n/** The result of handing a question this manager cannot answer to whatever is above it. */\nexport type QuestionEscalationOutcome =\n | { readonly delivered: true; readonly to: string }\n | { readonly delivered: false; readonly reason: string }\n\n/**\n * Where a question leaves this manager when `ask_parent` is called.\n *\n * Absent means NO INBOX IS CONFIGURED above this manager: `ask_parent` then answers `no-parent`\n * instead of appearing to succeed. That distinction is the whole point of the seam — a manager that\n * escalates a blocking question and reads a bare receipt BLOCKS on an answer nothing is routing to\n * it, and a fail-closed stop policy then refuses to let it finish.\n *\n * `no-parent` is not \"the question vanished\". It is still published on the bus and journaled, so an\n * external answerer watching the run — the coordination MCP's own `answer_question`, an operator\n * console, a product observer on `onCoordinationEvent` — can still decide it. What `no-parent` says\n * is that the RUNTIME will carry it nowhere by itself, so the manager must not sit and wait.\n *\n * An implementation returns `{ delivered: true, to }` naming who holds the question now, or\n * `{ delivered: false, reason }`. A THROW is also a refusal: its message becomes the reason, so a\n * broken parent channel reads as an undelivered escalation, never as a delivered one.\n */\nexport type EscalateQuestion = (\n question: QuestionRecord,\n) => Promise<QuestionEscalationOutcome> | QuestionEscalationOutcome\n\n/**\n * A manager's intake for an `ask_parent` question raised by a worker it spawned that manages work\n * of its own. `assignmentId` is the assignment the parent gave that worker. The question joins the\n * parent's questions under that worker's id, so the parent's next wake carries it and\n * `answer_question` delivers the answer back down to the asker.\n */\nexport type ChildQuestionInbox = (\n assignmentId: string,\n question: QuestionRecord,\n) => Promise<QuestionEscalationOutcome>\n\n/** The operator-facing artifact written for every `ask_parent`: which question left, whether\n * anything received it, and — when nothing did — that the manager itself is now the last decider.\n * Journaled record-only, so the run's durable coordination log holds every question that was\n * raised and went unheard. */\nexport interface QuestionEscalationRecord {\n readonly questionId: string\n readonly from: string\n readonly urgency: QuestionUrgency\n readonly delivered: boolean\n /** Who holds the question now. Absent when nothing received it. */\n readonly to?: string\n /** Why it was not delivered. Absent on a delivered escalation. */\n readonly reason?: string\n readonly at: number\n}\n","import type { McpToolDescriptor } from '../server'\nimport type { createDownMessages } from './coordination-down-messages'\nimport { level, obj, str, urgency } from './coordination-input'\nimport { downMessageRefusalReasons } from './coordination-messages'\nimport type { createQuestionLedger } from './coordination-question-ledger'\nimport { isQuestionEscalationTarget, questionEscalationTargets } from './coordination-questions'\nexport function createQuestionTools({\n questionLedger,\n messages,\n}: {\n readonly questionLedger: ReturnType<typeof createQuestionLedger>\n readonly messages: ReturnType<typeof createDownMessages>\n}): McpToolDescriptor[] {\n return [\n {\n name: 'list_questions',\n description:\n 'List questions raised by workers, drivers, or analysts. Blocking stop behavior follows questionPolicy.',\n inputSchema: { type: 'object', properties: {} },\n handler: () => Promise.resolve({ questions: questionLedger.questions }),\n },\n {\n name: 'answer_question',\n description: 'Record an answer, deferral, or escalation for a loop question.',\n inputSchema: {\n type: 'object',\n properties: {\n questionId: { type: 'string' },\n answer: { type: 'string' },\n by: { type: 'string', description: 'Node id or \"user\".' },\n deferReason: { type: 'string' },\n escalateTo: { type: 'string', enum: questionEscalationTargets },\n escalateReason: { type: 'string' },\n },\n required: ['questionId'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const questionId = str(a.questionId, 'questionId')\n if (typeof a.answer === 'string' && a.answer.length > 0) {\n const answer = a.answer\n const pendingQuestion = questionLedger.questions.find(\n (question) => question.id === questionId,\n )\n if (pendingQuestion === undefined) return questionLedger.unknownQuestion(questionId)\n // Route the answer DOWN to the worker that asked, unparking it, and record the down-leg.\n // A blocking question parked the worker, so deliver forcefully — it should resume on the\n // answer immediately, not wait for its next step boundary.\n const interrupt =\n pendingQuestion.urgency === 'blocks-run' || pendingQuestion.urgency === 'blocks-step'\n const authorized = messages.authorizeInstruction(\n 'answer',\n pendingQuestion.from,\n answer,\n interrupt,\n questionId,\n )\n await messages.recordInstruction(authorized)\n const delivery = await messages.attemptDelivery(authorized, {\n answer: authorized.instruction,\n questionId,\n interrupt,\n })\n // Authorization is evidence of allowed bytes, not proof the blocked worker received them.\n // Resolve the question only after the durable delivery outcome says the live inbox accepted\n // the answer. A refusal stays open both in this process and after replay.\n const question = delivery.delivered\n ? questionLedger.decideQuestion(questionId, {\n kind: 'answer',\n answer: authorized.instruction,\n by: typeof a.by === 'string' && a.by.length > 0 ? a.by : 'user',\n })\n : pendingQuestion\n // Surface `delivered` like steer_agent — the caller must see whether the answer actually\n // reached a live worker (false when it already settled or has no inbox).\n return {\n question,\n delivered: delivery.delivered,\n ...(delivery.delivered\n ? {}\n : {\n outcome: delivery.outcome,\n reason: downMessageRefusalReasons[delivery.outcome],\n }),\n }\n }\n if (typeof a.deferReason === 'string' && a.deferReason.length > 0) {\n if (!questionLedger.questions.some((question) => question.id === questionId))\n return Promise.resolve(questionLedger.unknownQuestion(questionId))\n return Promise.resolve({\n question: questionLedger.decideQuestion(questionId, {\n kind: 'defer',\n reason: a.deferReason,\n }),\n })\n }\n if (typeof a.escalateTo === 'string' && a.escalateTo.length > 0) {\n if (!isQuestionEscalationTarget(a.escalateTo)) {\n return Promise.resolve({\n error: 'invalid-escalation-target' as const,\n reason: `escalateTo must be one of ${questionEscalationTargets.join(', ')}; received ${JSON.stringify(a.escalateTo)}`,\n })\n }\n if (!questionLedger.questions.some((question) => question.id === questionId))\n return Promise.resolve(questionLedger.unknownQuestion(questionId))\n const escalateReason =\n typeof a.escalateReason === 'string' && a.escalateReason.length > 0\n ? a.escalateReason\n : 'driver escalated'\n const decided = questionLedger.decideQuestion(questionId, {\n kind: 'escalate',\n to: a.escalateTo,\n reason: escalateReason,\n })\n // THE SAME PATH `ask_parent` TAKES, for the same reason. Marking a question 'escalated'\n // and stopping there is exactly the silent wait this change removes: under `failClosed`\n // an escalated question still blocks `stop`, so a manager that escalates to a parent that\n // is not configured would never finish and would never be told why. `escalateTo: 'user'`\n // addresses the operator, who reads the run record, so only the 'parent' target crosses\n // the runtime seam.\n if (a.escalateTo !== 'parent') return Promise.resolve({ question: decided })\n return questionLedger.escalate(decided).then((escalation) => ({\n question: decided,\n escalated: escalation.delivered,\n outcome: escalation.delivered ? ('queued-for-parent' as const) : ('no-parent' as const),\n reason: escalation.delivered\n ? `the question is held by ${escalation.to}`\n : escalation.reason,\n ...(escalation.delivered\n ? {}\n : {\n guidance:\n 'No inbox above this manager is configured to receive it, so nothing will route an answer back to you. The question stays on the run record for anyone watching. Do not BLOCK on it: answer_question it yourself, or answer_question with deferReason to record that it stays open.',\n }),\n }))\n }\n return Promise.resolve({\n error: 'no-decision' as const,\n reason:\n 'a decision is required: pass `answer` to answer the question, `deferReason` to record that it stays open, or `escalateTo` to hand it further up',\n })\n },\n },\n {\n name: 'ask_parent',\n description: 'Raise a question to the parent driver/Pi/user when this driver cannot decide.',\n inputSchema: {\n type: 'object',\n properties: {\n from: { type: 'string' },\n level: { type: 'string', enum: ['worker', 'driver', 'loop'] },\n question: { type: 'string' },\n reason: { type: 'string' },\n urgency: { type: 'string', enum: ['continue-without', 'blocks-step', 'blocks-run'] },\n },\n required: ['from', 'level', 'question', 'reason', 'urgency'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const from = str(a.from, 'from')\n const q = await questionLedger.emitNewQuestion(\n questionLedger.addQuestion(\n {\n from,\n level: level(a.level),\n question: str(a.question, 'question'),\n reason: str(a.reason, 'reason'),\n urgency: urgency(a.urgency),\n },\n from,\n { kind: 'escalate', to: 'parent', reason: 'asked parent' },\n ),\n )\n const escalation = await questionLedger.escalate(q)\n return {\n question: q,\n escalated: escalation.delivered,\n outcome: escalation.delivered ? ('queued-for-parent' as const) : ('no-parent' as const),\n reason: escalation.delivered\n ? `the question is held by ${escalation.to}`\n : escalation.reason,\n ...(escalation.delivered\n ? {}\n : {\n // The artifact is journaled either way; this line is the manager's instruction, and\n // it is the difference between deciding and waiting forever.\n guidance:\n 'Nobody above this manager received the question. It is journaled for the operator, and YOU are the last decider: answer_question it yourself, or answer_question with deferReason to record that it stays open. Do not wait for an answer.',\n }),\n }\n },\n },\n ]\n}\n","import type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { Settled } from '../../runtime'\nimport { errMessage } from '../../runtime/supervise/error-message'\nimport type { EventBus } from '../../runtime/supervise/event-bus'\nimport { detachedFrozen } from '../../runtime/supervise/snapshot'\nimport type {\n CoordinationToolsOptions,\n ResolvedContinuity,\n SettledWorker,\n SpawnAdmission,\n} from './coordination-contracts'\nimport type { CoordinationEvent } from './coordination-events'\nimport { safeJsonText } from './coordination-json'\nimport { resolveJsonPointer, workerSettlement } from './coordination-map-routing'\nimport type { ContinuityMode } from './coordination-messages'\nimport type {\n GateDecision,\n RouteFlowEvent,\n RouteMatch,\n RouteOnSettleEdge,\n RouteSpawnMarker,\n RouteWhen,\n} from './coordination-route-contracts'\nimport { admitRuntimeSpawn, type RuntimeSpawnOutcome } from './coordination-runtime-spawn'\n\n/**\n * The flow scheduler of one manager: entry and route spawns are runtime spawns, like map items.\n * It has two call sites. `start` spawns every entry when the manager's coordination opens, before\n * the manager's first turn, so a manager that makes no tool call still has open work. `route` runs\n * on each settle beside the map expansion and fires at most one edge leaving the settled node; that\n * edge may start several nodes at once (a fork), or wait for several sources (a join). An edge into\n * a gate awaits `decideGate`, and the decision `{ choice, by }` is routed as the gate's result.\n *\n * Every spawn is keyed, so a restarted manager replays the flow from its spawn journal by walking\n * it again from its entries: a key whose done settlement is on disk comes back committed, and its\n * result takes the live settle path at once through `settleCommitted` (routes, maps, gates); an\n * in-doubt key is re-admitted once under `<key>#2`, and a second in-doubt ends the flow as\n * `in-doubt:<node>`. The walk re-derives every key a prior process used, because each one counts\n * traversals and settles that the replay repeats in the same order.\n */\nexport function createRouteRouting({\n opts,\n bus,\n admitSpawn,\n resolveContinuity,\n nodeOf,\n settleCommitted,\n stop,\n}: {\n readonly opts: CoordinationToolsOptions\n readonly bus: EventBus<CoordinationEvent>\n readonly admitSpawn: (input: SpawnAdmission) => Promise<unknown>\n readonly resolveContinuity: (\n requested: ContinuityMode | undefined,\n profileName: string | undefined,\n key: string | undefined,\n ) => ResolvedContinuity\n /** The node a worker of this manager runs, by profile name. */\n readonly nodeOf: (workerId: string) => string | undefined\n /** Run a committed spawn's journaled settle through the live settle path. */\n readonly settleCommitted: (workerId: string, node: string) => Promise<void>\n /** End the manager: the flow spawns nothing more and the manager takes no further turn. */\n readonly stop: (reason: string) => void\n}) {\n const flow = opts.routeFlow\n const flowNodes = new Set(flow?.nodes ?? [])\n const terminals = new Set(flow?.terminals ?? [])\n const gates = new Map((flow?.gates ?? []).map((gate) => [gate.id, gate]))\n // How many times the run reached each gate: the `visit` a decision is asked and journaled under.\n const visits = new Map<string, number>()\n const routesFrom = new Map<string, RouteOnSettleEdge[]>()\n for (const edge of flow?.routes ?? []) {\n for (const from of edge.from) routesFrom.set(from, [...(routesFrom.get(from) ?? []), edge])\n }\n // The latest usable result of every flow node: what a match and a task's evidence read.\n const latest = new Map<string, unknown>()\n // Fired traversals per edge: what the cap judges and what each route spawn's key counts.\n const fired = new Map<string, number>()\n // Per join edge, the members that settled usably since it last fired.\n const joined = new Map<string, Set<string>>()\n // Flow workers still running, by node: a route into one of them is refused as `target-live`.\n const live = new Map<string, Set<string>>()\n // The latest settled worker of each flow node, live or replayed from the journal: the\n // predecessor a routes edge names when it spawns that node again.\n const settledWorker = new Map<string, string>()\n const setLive = (node: string, workerId: string): void => {\n live.set(node, (live.get(node) ?? new Set()).add(workerId))\n }\n let ended = false\n let started: Promise<void> | undefined\n\n const textBytes = (value: unknown): number => Buffer.byteLength(safeJsonText(value), 'utf8')\n const publish = (event: RouteFlowEvent): Promise<void> =>\n bus\n .publish(detachedFrozen<CoordinationEvent>({ type: 'route', route: event }), { queue: false })\n .then(() => undefined)\n const end = async (event: RouteFlowEvent, reason: string): Promise<void> => {\n ended = true\n await publish(event)\n stop(reason)\n }\n\n const spawnNode = async (\n marker: RouteSpawnMarker,\n profile: AgentProfile,\n task: unknown,\n key: string,\n continuity: Exclude<ResolvedContinuity, { readonly error: string }>,\n ): Promise<RuntimeSpawnOutcome> => {\n const spawned = await admitRuntimeSpawn(admitSpawn, {\n profile,\n args: { label: marker.node },\n task,\n key,\n continuity,\n // A back edge re-spawns a node that already settled in this flow; the new worker succeeds it.\n successorOf: settledWorker.get(marker.node),\n preflightProfile: () =>\n opts.resolveSpawnProfile ? detachedFrozen(opts.resolveSpawnProfile(profile)) : profile,\n resourcesFromPath: [],\n defaultLabel: marker.node,\n route: Object.freeze({ ...marker }),\n })\n // A committed spawn is no running worker: a later route into its node is not `target-live`.\n if ('workerId' in spawned && !spawned.committed) setLive(marker.node, spawned.workerId)\n return spawned\n }\n // A spawn whose key is in doubt twice: the flow cannot tell whether that step is still running,\n // so it ends. A manager with no flow (a map of a root-driven graph) records the refusal only.\n const endInDoubt = async (node: string, source: string): Promise<void> => {\n if (flow === undefined || ended) return\n await end(\n { kind: 'stopped', at: node, workerId: source, reason: `in-doubt:${node}` },\n `flow in-doubt:${node}`,\n )\n }\n const refusal = (spawned: RuntimeSpawnOutcome): string =>\n 'refused' in spawned ? spawned.refused : 'in-doubt'\n\n // Every entry at once, each with its own task, under its own key. Committed entries settle once\n // every entry is spawned, the order in which their live settles would arrive at the earliest.\n const start = (): Promise<void> => {\n started ??= (async () => {\n const committed: Array<{ readonly workerId: string; readonly node: string }> = []\n for (const entry of flow?.entries ?? []) {\n const spawned = await spawnNode(\n { edge: entry.edge, node: entry.node },\n entry.profile,\n entry.task,\n entry.key,\n { continuity: 'fresh' },\n )\n if ('inDoubt' in spawned) {\n await endInDoubt(entry.node, 'entry')\n return\n }\n if ('workerId' in spawned && spawned.committed) {\n committed.push({ workerId: spawned.workerId, node: entry.node })\n }\n await publish({\n kind: 'traversal',\n edge: entry.edge,\n from: 'entry',\n to: entry.node,\n outcome: 'workerId' in spawned ? 'delivered' : 'unpropagated',\n continuity: 'fresh',\n bytes: 'workerId' in spawned ? textBytes(entry.task) : 0,\n ...('workerId' in spawned\n ? { workerId: spawned.workerId }\n : { reason: `entry spawn refused: ${refusal(spawned)}` }),\n })\n }\n for (const step of committed) {\n if (ended) return\n await settleCommitted(step.workerId, step.node)\n }\n })()\n return started\n }\n\n const matches = (match: RouteMatch, from: string): boolean => {\n const node = match.node ?? from\n if (!latest.has(node)) return false\n const selected = resolveJsonPointer(latest.get(node), match.pointer)\n if ('exists' in match) return selected.found === match.exists\n if (!selected.found) return false\n if ('equals' in match) return selected.value === match.equals\n return match.in.some((value) => value === selected.value)\n }\n const holds = (when: RouteWhen | undefined, from: string): boolean =>\n when === undefined ||\n ('all' in when ? when.all.every((match) => matches(match, from)) : matches(when, from))\n\n const targetName = (to: RouteOnSettleEdge['to']): string =>\n 'nodes' in to\n ? to.nodes.map((target) => target.node).join('+')\n : 'gate' in to\n ? to.gate\n : 'stop' in to\n ? `stop:${to.stop}`\n : `finish:${to.finish}`\n\n // A node's settle names its worker; a gate's decision names `gate:<id>#<visit>`.\n const fire = async (\n edge: RouteOnSettleEdge,\n node: string,\n source: string,\n result: unknown,\n ): Promise<void> => {\n const traversal = (fired.get(edge.edge) ?? 0) + 1\n fired.set(edge.edge, traversal)\n const from = edge.from.join('+')\n const row = { kind: 'traversal' as const, edge: edge.edge, from, sourceWorker: source }\n if ('stop' in edge.to) {\n await publish({\n ...row,\n to: `stop:${edge.to.stop}`,\n outcome: 'delivered',\n continuity: 'fresh',\n bytes: textBytes(result),\n })\n await end(\n { kind: 'stopped', edge: edge.edge, at: node, workerId: source, reason: edge.to.stop },\n `route ${edge.edge}: ${edge.to.stop}`,\n )\n return\n }\n if ('finish' in edge.to) {\n await publish({\n ...row,\n to: `finish:${edge.to.finish}`,\n outcome: 'delivered',\n continuity: 'fresh',\n bytes: textBytes(result),\n })\n await publish({ kind: 'output', node, workerId: source, result, edge: edge.edge })\n return\n }\n // The members of a join ride its evidence beside the nodes the edge lists.\n const evidence: Record<string, unknown> = {}\n for (const id of [...(edge.from.length > 1 ? edge.from : []), ...edge.evidence]) {\n if (latest.has(id)) evidence[id] = latest.get(id)\n }\n if ('gate' in edge.to) {\n const reached = { [node]: result, ...evidence }\n await publish({\n ...row,\n to: edge.to.gate,\n outcome: 'delivered',\n continuity: 'fresh',\n bytes: textBytes(reached),\n })\n await decide(edge.to.gate, reached)\n return\n }\n // Converging branches use a join: a second spawn of a running node would race the first.\n const busy = edge.to.nodes.find((target) => (live.get(target.node)?.size ?? 0) > 0)\n if (busy !== undefined) {\n await end(\n {\n kind: 'unrouted',\n reason: 'target-live',\n node,\n workerId: source,\n detail: `${edge.edge} fired into '${busy.node}', which still has a running worker`,\n result,\n },\n `flow: ${edge.edge} fired into live node '${busy.node}'`,\n )\n return\n }\n // A join's task names every member in declared order, never the member that happened to\n // settle last: a resume replays members in another order and must derive the same task.\n const task =\n edge.from.length > 1\n ? { from: { nodes: edge.from }, evidence }\n : { from: { node, result }, evidence }\n const fork = edge.to.nodes.length > 1\n const committed: Array<{ readonly workerId: string; readonly node: string }> = []\n for (const target of edge.to.nodes) {\n // A resume edge re-attaches to the target's latest settled session; a target that never\n // settled starts fresh, as a delegates edge's declared resume does.\n const resolved =\n edge.continuity === 'resume'\n ? resolveContinuity('resume', target.node, undefined)\n : { continuity: 'fresh' as const }\n const continuity =\n 'error' in resolved && resolved.error === 'resume-no-prior'\n ? { continuity: 'fresh' as const }\n : resolved\n const spawned =\n 'error' in continuity\n ? { refused: `${continuity.error}: ${continuity.hint}` }\n : await spawnNode(\n { edge: edge.edge, node: target.node },\n target.profile,\n task,\n fork\n ? `route:${edge.edge}#${traversal}:${target.node}`\n : `route:${edge.edge}#${traversal}`,\n continuity,\n )\n if ('inDoubt' in spawned) {\n await endInDoubt(target.node, source)\n return\n }\n if ('workerId' in spawned && spawned.committed) {\n committed.push({ workerId: spawned.workerId, node: target.node })\n }\n await publish({\n ...row,\n to: target.node,\n outcome: 'workerId' in spawned ? 'delivered' : 'unpropagated',\n continuity: 'continuity' in continuity ? continuity.continuity : edge.continuity,\n bytes: 'workerId' in spawned ? textBytes(task) : 0,\n ...('workerId' in spawned\n ? { workerId: spawned.workerId }\n : { reason: `route spawn refused: ${refusal(spawned)}` }),\n })\n }\n // A committed target settles after every target of a fork is spawned, as live settles would.\n for (const step of committed) {\n if (ended) return\n await settleCommitted(step.workerId, step.node)\n }\n }\n\n const routeSettle = async (settled: Settled<unknown>, worker: SettledWorker): Promise<void> => {\n if (ended) return\n const node = nodeOf(worker.id)\n if (node === undefined || !flowNodes.has(node)) return\n live.get(node)?.delete(worker.id)\n settledWorker.set(node, worker.id)\n const settlement = workerSettlement(settled, worker)\n if (worker.status === 'down' || settled.kind !== 'done') {\n const reason = `down: ${settlement.reason ?? 'down'}`\n await end({ kind: 'stopped', at: node, workerId: worker.id, reason }, `flow ${reason}`)\n return\n }\n const edges = routesFrom.get(node) ?? []\n if (settlement.outcome !== 'delivered') {\n // A terminal's unusable settle is simply not output. Anywhere else the flow cannot go on, so\n // it ends exactly as a down settle does: no edge, and the run is `all-children-down`.\n if (edges.length === 0) return\n const reason = `unusable: ${settlement.reason ?? 'no usable result'}`\n await end({ kind: 'stopped', at: node, workerId: worker.id, reason }, `flow ${reason}`)\n return\n }\n const result = settlement.result\n latest.set(node, result)\n if (terminals.has(node)) {\n await publish({ kind: 'output', node, workerId: worker.id, result })\n return\n }\n await select(node, worker.id, result)\n }\n\n // Fire the first edge leaving `node` whose `when` holds over its latest result.\n const select = async (node: string, source: string, result: unknown): Promise<void> => {\n const edges = routesFrom.get(node) ?? []\n for (const edge of edges) {\n if (!holds(edge.when, node)) continue\n if (edge.from.length > 1) {\n // A join is the only edge leaving its members: it fires once each has settled since it\n // last fired, and until then this settle simply waits.\n const settled = (joined.get(edge.edge) ?? new Set<string>()).add(node)\n joined.set(edge.edge, settled)\n if (settled.size < edge.from.length) return\n joined.delete(edge.edge)\n }\n if ((fired.get(edge.edge) ?? 0) >= edge.maxTraversals) {\n await publish({\n kind: 'traversal',\n edge: edge.edge,\n from: edge.from.join('+'),\n to: targetName(edge.to),\n outcome: 'unpropagated',\n continuity: edge.continuity,\n bytes: 0,\n reason: `traversal-cap-exhausted (max ${edge.maxTraversals})`,\n sourceWorker: source,\n })\n continue\n }\n await fire(edge, node, source, result)\n return\n }\n // A node left only by maps edges is routed by its maps; one with routes edges must match one.\n if (edges.length === 0) return\n await end(\n {\n kind: 'unrouted',\n reason: 'unrouted',\n node,\n workerId: source,\n detail: `no routes edge leaving '${node}' matched its result`,\n result,\n },\n `flow: no routes edge leaving '${node}' matched`,\n )\n }\n\n // Ask the caller for one gate visit while the process holds the run, then route the decision as\n // the gate's result. The wait counts against the run's deadline: an undecided gate at the\n // deadline ends the flow as a timed-out node does, and an aborted run records nothing.\n const decide = async (id: string, evidence: Record<string, unknown>): Promise<void> => {\n const gate = gates.get(id)\n if (gate === undefined || opts.decideGate === undefined) {\n throw new Error(`gate '${id}' has no decideGate to ask`)\n }\n const visit = (visits.get(id) ?? 0) + 1\n visits.set(id, visit)\n const source = `gate:${id}#${visit}`\n const asked = opts.decideGate({\n gate: id,\n visit,\n question: gate.question,\n choices: gate.choices,\n evidence,\n })\n const answer = await untilDeadline(asked)\n if (ended || answer === 'aborted') return\n if (answer === 'deadline') {\n const reason = `deadline: gate '${id}' visit ${visit} was not decided`\n await end({ kind: 'stopped', at: id, workerId: source, reason }, `flow ${reason}`)\n return\n }\n const decision = gateDecision(answer, gate.choices)\n if (typeof decision === 'string') {\n throw new Error(`decideGate answered gate '${id}' visit ${visit} with ${decision}`)\n }\n const replayed = answer.replayed === true ? { replayed: true } : {}\n await publish({\n kind: 'traversal',\n edge: `gate:${id}`,\n from: id,\n to: decision.kind === 'choose' ? `choice:${decision.choice}` : `stop:${decision.reason}`,\n outcome: 'delivered',\n continuity: 'fresh',\n bytes: textBytes(decision),\n gate:\n decision.kind === 'choose'\n ? { by: decision.by, choice: decision.choice, ...replayed }\n : { by: decision.by, stop: decision.reason, ...replayed },\n })\n if (decision.kind === 'stop') {\n await end(\n { kind: 'stopped', edge: `gate:${id}`, at: id, workerId: source, reason: decision.reason },\n `gate ${id}: ${decision.reason}`,\n )\n return\n }\n const result = { choice: decision.choice, by: decision.by }\n latest.set(id, result)\n await select(id, source, result)\n }\n\n // A gate wait ends with the run: its abort signal, or its absolute deadline when it has one.\n const untilDeadline = <T>(asked: Promise<T>): Promise<T | 'aborted' | 'deadline'> => {\n const signal = opts.scope.signal\n if (signal.aborted) return Promise.resolve('aborted')\n const deadlineMs = opts.scope.budget.deadlineMs\n return new Promise((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined\n const onAbort = (): void => settle(() => resolve('aborted'))\n const settle = (done: () => void): void => {\n clearTimeout(timer)\n signal.removeEventListener('abort', onAbort)\n done()\n }\n if (deadlineMs > 0) {\n const left = Math.max(0, deadlineMs - Date.now())\n timer = setTimeout(() => settle(() => resolve('deadline')), left)\n }\n signal.addEventListener('abort', onAbort, { once: true })\n asked.then(\n (value) => settle(() => resolve(value)),\n (error: unknown) => settle(() => reject(error)),\n )\n })\n }\n\n // Route steps run on the settlement path, which they must never take down; a step that throws\n // ends the flow loudly instead of leaving the manager waiting on a spawn that never happens.\n const route = async (settled: Settled<unknown>, worker: SettledWorker): Promise<void> => {\n try {\n await routeSettle(settled, worker)\n } catch (error) {\n if (ended) return\n await end(\n {\n kind: 'stopped',\n at: nodeOf(worker.id) ?? worker.id,\n workerId: worker.id,\n reason: `route-step-failed: ${errMessage(error)}`,\n },\n `flow route step failed: ${errMessage(error)}`,\n )\n }\n }\n\n return { start, route, endInDoubt }\n}\n\n/** The caller's decision, checked against the gate's choices, or why it is not one. */\nfunction gateDecision(answer: unknown, choices: ReadonlyArray<string>): GateDecision | string {\n const value = answer as Partial<{ kind: unknown; choice: unknown; reason: unknown; by: unknown }>\n const shown = safeJsonText(answer)\n if (typeof value !== 'object' || value === null || typeof value.by !== 'string' || !value.by) {\n return `${shown} — a decision names who decided in a non-empty by`\n }\n if (value.kind === 'choose' && typeof value.choice === 'string') {\n if (choices.includes(value.choice)) {\n return { kind: 'choose', choice: value.choice, by: value.by }\n }\n return `${shown} — choice is not one of ${choices.join(', ')}`\n }\n if (value.kind === 'stop' && typeof value.reason === 'string' && value.reason.length > 0) {\n return { kind: 'stop', reason: value.reason, by: value.by }\n }\n return `${shown} — expected { kind: 'choose', choice, by } or { kind: 'stop', reason, by }`\n}\n","import type { TraceAnalysisStore } from '@tangle-network/agent-eval'\nimport type { Settled } from '../../runtime'\nimport { errMessage } from '../../runtime/supervise/error-message'\nimport type { EventBus } from '../../runtime/supervise/event-bus'\nimport { detachedFrozen } from '../../runtime/supervise/snapshot'\nimport { workerTraceAnalysisStore } from '../../runtime/supervise/trace-evidence'\nimport type { createCoordinationAnalysis } from './coordination-analysis'\nimport { type AnalystRunInFlight, canonicalFindingEvent } from './coordination-analysts'\nimport type { CoordinationToolsOptions, SettledWorker } from './coordination-contracts'\nimport type { CoordinationEvent } from './coordination-events'\nimport type { createMapRouting } from './coordination-map-routing'\nimport type { createRouteRouting } from './coordination-route-routing'\n\nexport function createSettlementDrain({\n opts,\n ledger,\n unwatchWorker,\n bus,\n analysis,\n maps,\n routes,\n workerRouteNames,\n projectSettled,\n}: {\n readonly opts: CoordinationToolsOptions\n readonly ledger: SettledWorker[]\n readonly unwatchWorker: (id: string) => void\n readonly bus: EventBus<CoordinationEvent>\n readonly analysis: ReturnType<typeof createCoordinationAnalysis>\n readonly maps: ReturnType<typeof createMapRouting>\n readonly routes: ReturnType<typeof createRouteRouting>\n readonly workerRouteNames: (workerId: string) => Set<string>\n readonly projectSettled: (settled: Settled<unknown>, resumed?: boolean) => SettledWorker\n}) {\n // Workers whose settle already ran the settle hooks below, live or committed: each runs them once.\n const hooked = new Set<string>()\n const commitSettled = (w: SettledWorker): void => {\n ledger.push(w)\n // A settled worker's trace source is finished; drop the online subscription with it.\n unwatchWorker(w.id)\n }\n\n // `Scope.next()` is once-only, while an awaited observer may commit and lose its acknowledgement.\n // Retain the exact event until publication succeeds so the next await retries rather than losing\n // the settlement between the spawn journal and the product transaction. `analystRun` marks a\n // settlement that IS an analyst-agent's findings (see `analysis.analystRuns`), whose event is a `finding`.\n let pendingSettlement:\n | {\n readonly settled: Settled<unknown>\n readonly worker: SettledWorker\n readonly event: CoordinationEvent\n readonly analyze: boolean\n readonly analystRun?: AnalystRunInFlight\n }\n | undefined\n\n // Settlements being published with their analysis right now. The settled event is queued first\n // and the analysis it triggers follows, so a wake waits for both.\n let flushing = 0\n const flushPendingSettlement = async (): Promise<boolean> => {\n flushing += 1\n try {\n return await flushPendingSettlementOnce()\n } finally {\n flushing -= 1\n }\n }\n const flushPendingSettlementOnce = async (): Promise<boolean> => {\n const pending = pendingSettlement\n if (!pending) return false\n // A map item's settlement is recorded but not queued: the manager is woken by the map's join,\n // or by the event that says the join could not run.\n if (maps.isItem(pending.worker.id)) {\n await bus.publish(pending.event, { queue: false })\n } else {\n await bus.publish(pending.event)\n }\n // An analyst-AGENT settlement IS its finding (just published): it never enters the settled\n // ledger or the finalizer, and it re-fires no analyst hook. Its routed delivery goes through\n // the exact machinery a registry-analyst finding uses — with no wrap directive, because the\n // route's directive was already consumed as the analyst's task.\n if (pending.analystRun) {\n analysis.analystRuns.delete(pending.worker.id)\n analysis.flushedAnalystRuns.add(pending.worker.id)\n unwatchWorker(pending.worker.id)\n pendingSettlement = undefined\n const { route } = pending.analystRun\n if (route.to !== undefined && pending.event.type === 'finding') {\n await analysis.deliverRoutedFinding(\n { kind: route.kind, to: route.to },\n pending.event.finding.findings,\n )\n }\n return true\n }\n commitSettled(pending.worker)\n pendingSettlement = undefined\n hooked.add(pending.worker.id)\n const advance = pending.analyze && !analysis.isFinishing()\n await maps.runMapStep(\n () => maps.settleMapMember(pending.settled, pending.worker, advance),\n pending.worker,\n )\n if (pending.analyze && !analysis.isFinishing() && analysis.analysisRoutes.length) {\n const sourceNames = workerRouteNames(pending.worker.id)\n const applicable = analysis.analysisRoutes.filter(\n (route) =>\n route.at !== 'manager-end' &&\n (route.statuses ?? ['done']).includes(pending.worker.status) &&\n (route.over === undefined || route.over.some((name) => sourceNames.has(name))),\n )\n // Registry lenses run in-process over the trace store; agent analysts spawn as workers.\n const lensRoutes = applicable.filter((route) => route.agent === undefined)\n const agentRoutes = applicable.filter((route) => route.agent !== undefined)\n if (lensRoutes.length > 0 && opts.analysts && pending.worker.trace.status === 'available') {\n // A lens that throws, or a trace it cannot read, is a FAILED analyst run, published as\n // `{ analystRunFailed }` exactly like a failed agent analyst. Before this, the throw left\n // the drain that carried the settlement, so the driver waited on a finding that never\n // landed and every later lens and agent route on this settlement was skipped.\n let trace: TraceAnalysisStore | undefined\n let traceFailure: unknown\n try {\n trace = await workerTraceAnalysisStore(pending.worker.trace, opts.blobs)\n } catch (error) {\n traceFailure = error\n }\n for (const route of lensRoutes) {\n let findings: unknown\n try {\n if (trace === undefined) throw traceFailure\n findings = await opts.analysts.run(\n route.kind,\n trace,\n analysis.analystRunContext(route.kind, pending.worker.id),\n )\n } catch (error) {\n findings = { analystRunFailed: errMessage(error) }\n }\n // The finding ALWAYS lands on the bus — the audit trail and the driver's pullable copy —\n // whether or not the route also delivers it to a named worker.\n await bus.publish({\n type: 'finding',\n finding: canonicalFindingEvent({\n fromWorker: pending.worker.id,\n analyst: route.kind,\n findings,\n }),\n })\n if (route.to !== undefined) await analysis.deliverRoutedFinding(route, findings)\n }\n }\n for (const route of agentRoutes) await analysis.spawnAnalystRun(route, pending.worker)\n }\n if (advance) {\n await maps.runMapStep(() => maps.expandMaps(pending.settled, pending.worker), pending.worker)\n await routes.route(pending.settled, pending.worker)\n }\n return true\n }\n\n // A keyed runtime spawn that came back committed: its done settlement is on disk from a prior\n // process, already in the ledger, and no cursor will ever yield it. Its result takes the steps a\n // live settle takes after the ledger: the map member, the maps it expands and its routes. Its\n // analysis already ran in the process that settled it.\n const settleCommitted = async (workerId: string): Promise<void> => {\n if (hooked.has(workerId)) return\n const settled = opts.scope.resume?.settled.find((s) => s.handle.id === workerId)\n if (settled === undefined) {\n throw new Error(`committed worker ${workerId} has no settlement in the resumed journal`)\n }\n hooked.add(workerId)\n const worker = projectSettled(settled, true)\n const advance = !analysis.isFinishing()\n await maps.runMapStep(() => maps.settleMapMember(settled, worker, advance), worker)\n if (!advance) return\n await maps.runMapStep(() => maps.expandMaps(settled, worker), worker)\n await routes.route(settled, worker)\n }\n\n const prepareSettlement = (\n settled: Settled<unknown>,\n analyze: boolean,\n ): NonNullable<typeof pendingSettlement> => {\n const worker = projectSettled(settled)\n const run = analysis.analystRuns.get(settled.handle.id)\n return run\n ? {\n settled,\n worker,\n event: analysis.analystRunFinding(run, settled),\n analyze: false,\n analystRun: run,\n }\n : {\n settled,\n worker,\n event: detachedFrozen<CoordinationEvent>({ type: 'settled', worker }),\n analyze,\n }\n }\n\n // Producer: drain exactly one settlement from the scope cursor onto the bus (a `settled` event),\n // then fire the analyst-on-settle hook — auto-run each configured lens over the worker's trace and\n // publish its result as a `finding`. Returns false when the cursor is idle (no live workers). The\n // cursor is a once-per-child source, so a settlement is produced at most once.\n // `next` blocks on a live worker; `nextResolved` takes only a child that already settled.\n const drainSettlement = async (source: 'next' | 'nextResolved' = 'next'): Promise<boolean> => {\n if (!pendingSettlement) {\n const settled = await (source === 'next' ? opts.scope.next() : opts.scope.nextResolved())\n if (!settled) return false\n pendingSettlement = prepareSettlement(settled, true)\n }\n return flushPendingSettlement()\n }\n\n // Post-loop drain: every ALREADY-settled, unpulled child enters the ledger + audit trail. No\n // analyst-on-settle here — the driver has stopped, so a finding has no reader and an analyst\n // spawn would spend real compute for nothing. An analyst-agent run ALREADY in flight is not a\n // new spawn: its settlement still becomes its finding (the audit trail must not lose paid-for\n // findings), though a routed delivery will usually record `delivered:false` this late.\n const drainResolved = async (): Promise<number> => {\n let drained = 0\n for (;;) {\n if (!pendingSettlement) {\n const settled = await opts.scope.nextResolved()\n if (!settled) return drained\n pendingSettlement = prepareSettlement(settled, false)\n }\n await flushPendingSettlement()\n drained += 1\n }\n }\n\n return {\n drainSettlement,\n drainResolved,\n settleCommitted,\n isFlushing: () => flushing > 0,\n isBusy: () => pendingSettlement !== undefined || flushing > 0,\n }\n}\n","import type { Budget } from '../../runtime'\nimport { assertValidBudget } from '../../runtime/supervise/spend-validation'\n\nexport // Parse a per-spawn `budget` override and merge it over the per-worker default (per field).\n// Fails loud on a non-object or a non-finite numeric field — a malformed budget must never\n// silently fall back to the default and run a sub-task on a ceiling nobody chose.\nconst mergeBudget = (base: Budget, raw: unknown): Budget => {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw))\n throw new Error('coordination tools: \"budget\" must be an object')\n const o = raw as Record<string, unknown>\n const field = (name: keyof Budget): number | undefined => {\n const v = o[name]\n if (v === undefined) return undefined\n if (typeof v !== 'number' || !Number.isFinite(v))\n throw new Error(`coordination tools: \"budget.${name}\" must be a finite number`)\n return v\n }\n const maxIterations = field('maxIterations')\n const maxTokens = field('maxTokens')\n const maxUsd = field('maxUsd')\n const deadlineMs = field('deadlineMs')\n const rawResources = o.resources\n if (\n rawResources !== undefined &&\n (!rawResources || typeof rawResources !== 'object' || Array.isArray(rawResources))\n ) {\n throw new Error('coordination tools: \"budget.resources\" must be a resource map')\n }\n const resources =\n rawResources === undefined ? base.resources : { ...base.resources, ...rawResources }\n const merged: Budget = {\n ...(resources === undefined\n ? {}\n : { resources: resources as NonNullable<Budget['resources']> }),\n maxIterations: maxIterations ?? base.maxIterations,\n maxTokens: maxTokens ?? base.maxTokens,\n ...((maxUsd ?? base.maxUsd) === undefined ? {} : { maxUsd: maxUsd ?? base.maxUsd }),\n ...((deadlineMs ?? base.deadlineMs) === undefined\n ? {}\n : { deadlineMs: deadlineMs ?? base.deadlineMs }),\n }\n assertValidBudget(merged, 'coordination tools: budget')\n return merged\n}\n","import type { SpawnModelSubstitution } from '../../runtime'\n/**\n * The substitution and the sentence a manager reads beside it. A manager that reports which model\n * did the work must read `modelSubstitution.ran`, never the model it asked for.\n */\nexport function modelSubstitutionReport(substitution: SpawnModelSubstitution): {\n readonly modelSubstitution: SpawnModelSubstitution\n readonly modelWarning: string\n} {\n return {\n modelSubstitution: substitution,\n modelWarning: `spawn authorization ran this worker on ${substitution.ran}, not the ${substitution.requested} you authored; attribute its work to ${substitution.ran}`,\n }\n}\n","import type { Handle, Settled } from '../../runtime'\nimport { isLiveNodeStatus } from '../../runtime/supervise/node-status'\nimport type { PeerMailbox } from '../../runtime/supervise/peer-mail'\nimport { detachedFrozen } from '../../runtime/supervise/snapshot'\nimport { emptyPreflightCounts, spawnRefusalReason } from './coordination-budget'\nimport { mergeBudget } from './coordination-budget-override'\nimport type {\n CoordinationToolsOptions,\n ResolvedContinuity,\n SettledWorker,\n SpawnAdmission,\n WorkerSpawnContext,\n} from './coordination-contracts'\nimport type { ContinuityMode } from './coordination-messages'\nimport { modelSubstitutionReport } from './coordination-model-attribution'\n\nexport function createSpawnAdmission({\n opts,\n ledger,\n liveWorkerCount,\n freeWorkerSlots,\n queuedWorkerCount,\n watchWorker,\n peerMail,\n projectSettled,\n}: {\n readonly opts: CoordinationToolsOptions\n readonly ledger: ReadonlyArray<SettledWorker>\n readonly liveWorkerCount: () => number\n readonly freeWorkerSlots: () => number | null\n readonly queuedWorkerCount: () => number\n readonly watchWorker: (id: string) => void\n readonly peerMail: () => PeerMailbox | undefined\n readonly projectSettled: (settled: Settled<unknown>, resumed?: boolean) => SettledWorker\n}) {\n // Worker id → the AUTHORED profile name it was spawned from. The stable identity an\n // `AnalyzeOnSettleRoute` names (`to`/`over`): labels are the driver's free-text choice, while\n // the profile name is what a graph pins a node by. Recorded at spawn, dropped never (a settled\n // source can still be matched by `over` after it is gone).\n const profileNameByWorker = new Map<string, string>()\n // Assignment id → the worker spawned under it, which a child manager's question names.\n const workerByAssignment = new Map<string, string>()\n // Worker id → the live child Handle from its spawn. `Handle.abort` is the ONLY per-child abort\n // (its controller cascades to that child's subtree and no sibling), and the scope does not\n // re-expose it, so `abortWorker` must keep the handle from the spawn that minted it. Entries\n // are never deleted (liveness is re-checked against the view at abort time); the map is\n // bounded by the run's spawn count, like `profileNameByWorker`.\n const liveHandles = new Map<string, Handle<unknown>>()\n // `Scope` advances its node/cursor ordinals on resume, but assignment identity belongs to this\n // manager. Seed it independently from durable evidence so a restarted manager never calls new\n // work `ordinal:0` when a prior process already used that assignment. Use the maximum rather\n // than the number of rows: journals can contain gaps, keyed assignments, and legacy/custom ids.\n let unkeyedAssignmentOrdinal = nextUnkeyedAssignmentOrdinal(opts.scope)\n const preflightCounts = emptyPreflightCounts()\n\n const nodeForWorker = (id: string) =>\n opts.scope.view.nodes.find((node) => node.id === id) ??\n opts.scope.resume?.view.nodes.find((node) => node.id === id)\n\n // The names an analyst route may know a worker by: its authored profile name (the stable node\n // identity) and its spawn label (the driver's free-text choice).\n // A named profile is the worker's route identity. The label is the driver's free text and\n // defaults to the profile name, or 'worker' for an unnamed profile, so matching it for a named\n // profile would make a route over a node named 'worker' cover every unlabelled worker. It names\n // only a worker without a profile name.\n const workerRouteNames = (workerId: string): Set<string> => {\n const profileName = profileNameByWorker.get(workerId)\n if (profileName !== undefined) return new Set([profileName])\n const label = nodeForWorker(workerId)?.label\n return new Set(label === undefined ? [] : [label])\n }\n\n /** The LIVE worker a route destination names, by profile name first, label second. */\n const liveWorkerIdNamed = (destination: string): string | undefined => {\n const live = opts.scope.view.nodes.filter((node) => isLiveNodeStatus(node.status))\n return (\n live.find((node) => profileNameByWorker.get(node.id) === destination)?.id ??\n live.find((node) => node.label === destination)?.id\n )\n }\n\n // ── Continuity: how a spawn continues a node's prior work ──\n // Node identity is the PROFILE NAME only (never the label): resume re-attaches to a specific\n // prior session, and the label is the driver's free-text choice. All three reads are\n // process-local by construction — `profileNameByWorker` records only this process's spawns —\n // which is the documented resume boundary (a prior process's workers are not resume targets).\n const liveWorkerForNode = (name: string): string | undefined =>\n opts.scope.view.nodes.find(\n (node) => isLiveNodeStatus(node.status) && profileNameByWorker.get(node.id) === name,\n )?.id\n const latestSettledWorkerForNode = (name: string): string | undefined => {\n for (let i = ledger.length - 1; i >= 0; i -= 1) {\n const worker = ledger[i] as SettledWorker\n if (profileNameByWorker.get(worker.id) === name) return worker.id\n }\n return undefined\n }\n const nodeSpawnCount = (name: string): number => {\n let count = 0\n for (const profileName of profileNameByWorker.values()) if (profileName === name) count += 1\n return count\n }\n /**\n * Resolve the EFFECTIVE continuity of one spawn: the per-call request wins, else the profile\n * name's declared default, else `'fresh'`. Every refusal is loud and actionable:\n * - an EXPLICIT `'resume'` with no settled prior worker refuses (`resume-no-prior`) — the\n * DECLARED default degrades to `'fresh'` instead, so a resume edge's first traversal is\n * simply the first spawn;\n * - resume while a prior worker of the node is still LIVE refuses (`resume-while-live`) —\n * that is what steer is for, and the error says so;\n * - resume under a semantic `key` refuses (`resume-with-key`) — a key makes an assignment\n * run-once, resume explicitly runs the node again.\n */\n const resolveContinuity = (\n requested: ContinuityMode | undefined,\n profileName: string | undefined,\n key: string | undefined,\n ): ResolvedContinuity => {\n const declared =\n profileName === undefined ? 'fresh' : (opts.continuityByProfile?.[profileName] ?? 'fresh')\n const wantsResume = requested === 'resume' || (requested === undefined && declared === 'resume')\n if (!wantsResume) return { continuity: 'fresh' }\n if (profileName === undefined || profileName.length === 0) {\n return {\n error: 'resume-unnamed-profile',\n hint:\n 'Resume targets a node by profile.name — the stable node identity — and this profile ' +\n 'has none. Name the profile, or spawn fresh.',\n }\n }\n if (key !== undefined) {\n return {\n error: 'resume-with-key',\n hint:\n 'A semantic key makes an assignment run-once (a completed key returns its committed ' +\n 'result instead of running again); resume explicitly runs the node AGAIN. Drop the ' +\n 'key to resume, or keep the key and spawn fresh.',\n }\n }\n const live = liveWorkerForNode(profileName)\n if (live !== undefined) {\n return {\n error: 'resume-while-live',\n hint:\n `Worker '${live}' on node '${profileName}' is still LIVE — resume re-attaches to a ` +\n 'SETTLED session. To redirect the live worker, use steer_agent (that is the ' +\n \"live-worker channel); to run a parallel sibling instead, pass continuity: 'fresh'.\",\n }\n }\n const prior = latestSettledWorkerForNode(profileName)\n if (prior === undefined) {\n // The DECLARED default asked for resume-when-possible; with nothing to resume this is the\n // node's effective first spawn. Only an explicit per-call demand fails loud here.\n if (requested === undefined) return { continuity: 'fresh' }\n return {\n error: 'resume-no-prior',\n hint:\n `Node '${profileName}' has no settled prior worker in this process to resume — ` +\n 'resume continues a FINISHED session. Spawn the node fresh first (omit continuity or ' +\n \"pass 'fresh').\",\n }\n }\n return {\n continuity: 'resume',\n resume: { ofWorker: prior, sequence: nodeSpawnCount(profileName) + 1 },\n }\n }\n const admitSpawn = async (input: SpawnAdmission): Promise<unknown> => {\n const { profile, key, continuity, successorOf } = input\n const a = input.args\n const task = detachedFrozen(input.task)\n const label = typeof a.label === 'string' ? a.label : input.defaultLabel\n // The ONE pre-journal point that may ask the backend a question: everything below —\n // assignment, budget reservation, `Scope.spawn` — is synchronous and commits state.\n if (opts.preflightSpawn) {\n // The gate judges the profile that will RUN, which the caller resolved.\n const refusal = await opts.preflightSpawn(input.preflightProfile(), {\n label,\n ...(key !== undefined ? { key } : {}),\n task,\n })\n if (refusal) {\n preflightCounts[refusal.cause] += 1\n return {\n error: 'preflight-refused' as const,\n reason: `the spawn pre-flight refused this profile (${refusal.cause}): ${refusal.detail}`,\n cause: refusal.cause,\n detail: refusal.detail,\n live: liveWorkerCount(),\n freeSlots: freeWorkerSlots(),\n }\n }\n }\n const budget = Object.freeze(\n a.budget === undefined ? opts.perWorker : mergeBudget(opts.perWorker, a.budget),\n )\n const assignmentId = key !== undefined ? `key:${key}` : `ordinal:${unkeyedAssignmentOrdinal++}`\n // Minted BEFORE the worker exists, because the agent factory runs inside `scope.spawn` and\n // the node id is not known until after it. The capability is bound to the concrete worker\n // below, and sends nothing until then.\n const peerMailUrl = peerMail()?.mintCapability(assignmentId)\n const context: WorkerSpawnContext = Object.freeze({\n assignmentId,\n parentNodeId: opts.scope.view.root,\n budget,\n task,\n label,\n ...(key !== undefined ? { key } : {}),\n continuity: continuity.continuity,\n ...(continuity.continuity === 'resume' ? { resume: continuity.resume } : {}),\n ...(successorOf !== undefined ? { successorOf } : {}),\n ...(peerMailUrl !== undefined ? { peerMailUrl } : {}),\n ...(input.map !== undefined ? { map: input.map } : {}),\n ...(input.route !== undefined ? { route: input.route } : {}),\n })\n const res = opts.scope.spawn(() => opts.makeWorkerAgent(profile, context), task, {\n budget,\n label,\n assignmentId,\n ...(key !== undefined ? { key } : {}),\n ...(successorOf !== undefined ? { successorOf } : {}),\n // A re-spawned key that names a budget asks for more: a result that ended over its budget,\n // with its environment still held, continues in the same session.\n ...(key !== undefined && a.budget !== undefined ? { continueHeld: true } : {}),\n })\n // A keyed spawn that resolved to committed work: NOTHING ran — return the finished result\n // (it is already in the settled ledger, seeded from the resumed scope or recorded when the\n // cursor yielded it), so the driver folds it in without waiting for a wake.\n if (res.ok && res.prior?.state === 'completed') {\n const s = res.prior.settled\n const { id, status, resumed: _resumed, ...evidence } = projectSettled(s)\n return Promise.resolve({\n workerId: id,\n resumed: 'completed' as const,\n status,\n ...evidence,\n ...(evidence.outRef === undefined\n ? {}\n : {\n outputRead: { tool: 'observe_agent', arguments: { workerId: id } },\n }),\n live: liveWorkerCount(),\n freeSlots: freeWorkerSlots(),\n })\n }\n if (res.ok) {\n watchWorker(res.handle.id)\n liveHandles.set(res.handle.id, res.handle)\n // The capability becomes a sender only now, when there is a concrete worker to speak as.\n peerMail()?.bindCapability(assignmentId, res.handle.id)\n if (typeof profile.name === 'string' && profile.name.length > 0) {\n profileNameByWorker.set(res.handle.id, profile.name)\n }\n workerByAssignment.set(assignmentId, res.handle.id)\n }\n // A `completed` key returned above, so any prior still attached here is a real re-run:\n // `retried` means the prior attempt reached a terminal down receipt.\n const priorHistory =\n res.ok && res.prior !== undefined && res.prior.state !== 'completed'\n ? {\n resumed: res.prior.state,\n priorWorkerId: res.prior.priorId,\n ...(res.prior.state === 'retried' ? { priorReason: res.prior.reason } : {}),\n }\n : {}\n // Report the REMAINING capacity alongside the spawn, so one tool call tells the driver\n // both \"it started\" and \"you can still open N more\" — the feedback that lets it fill\n // slots instead of opening one worker per turn. `null` = uncapped. A fresh spawn under a\n // key with a failed prior attempt carries that history (`resumed`/`priorWorkerId`), so a\n // re-run is always explicit. An in-doubt prior is refused above and never duplicated.\n return Promise.resolve(\n res.ok\n ? {\n workerId: res.handle.id,\n assignmentId: res.handle.assignmentId ?? assignmentId,\n ...(res.handle.identity === undefined ? {} : { identity: res.handle.identity }),\n ...(res.handle.modelSubstitution === undefined\n ? {}\n : modelSubstitutionReport(res.handle.modelSubstitution)),\n ...(res.handle.materialization === undefined\n ? {}\n : { materialization: res.handle.materialization }),\n ...(res.handle.executionBindings === undefined\n ? {}\n : { executionBindings: res.handle.executionBindings }),\n // The EFFECTIVE continuity of this spawn, with the resume lineage when it\n // re-attached — so the driver's transcript states how the node continued.\n continuity: continuity.continuity,\n ...(continuity.continuity === 'resume' ? { resume: continuity.resume } : {}),\n ...(successorOf !== undefined ? { successorOf } : {}),\n status: res.handle.status,\n live: liveWorkerCount(),\n queued: queuedWorkerCount(),\n freeSlots: freeWorkerSlots(),\n ...priorHistory,\n // The receipt for every resource the server read by path: the manager can check\n // the sha256 against its own file instead of trusting that the bytes arrived.\n ...(input.resourcesFromPath.length === 0\n ? {}\n : { resourcesFromPath: input.resourcesFromPath }),\n ...input.accepted,\n }\n : {\n error: res.reason,\n // `usd-unbudgeted` is the one rejection no retry can clear, so it says so: without\n // that, a driver reads \"budget\" and walks its request down until it gives up.\n // A refusal a driver can ACT on: each kind says what happened and what to do next.\n reason: spawnRefusalReason(res.reason, res.shortfalls, {\n usdUnbudgeted:\n \"this run's root budget declares no maxUsd, so a child budget naming maxUsd can never be admitted at any amount — spawn with a budget that omits maxUsd\",\n inDoubt:\n 'this key has a prior worker recorded as started without a terminal receipt; no replacement was started because that remote worker may still be running — inspect or recover the exact prior execution before retrying',\n // Nothing is exhausted and nothing was cancelled: this run's driver already\n // finished and the supervisor is joining. A caller that reaches here is working\n // past the end of its own request; the honest report is that the stage never\n // started, not that it failed.\n scopeSettled:\n 'this run has already reached its join barrier — its driver returned and the supervisor is settling, so no further worker can be started, joined, or paid for; record this stage as not started',\n }),\n ...(res.shortfalls === undefined ? {} : { shortfalls: res.shortfalls }),\n ...(res.reason === 'usd-unbudgeted'\n ? {\n hint:\n \"This run's root budget declares no maxUsd, so a child budget naming maxUsd \" +\n 'can never be admitted — at any amount. Retrying with a smaller maxUsd will ' +\n 'fail identically. Spawn with a budget that omits maxUsd, or ask the caller ' +\n 'to give the run a root maxUsd.',\n }\n : res.reason === 'in-doubt'\n ? {\n hint: 'Do not retry this key. Use the recorded prior worker identity to inspect or recover that exact execution. A terminal receipt or explicit recovery is required before replacement work can start.',\n }\n : {}),\n live: liveWorkerCount(),\n freeSlots: freeWorkerSlots(),\n },\n )\n }\n\n // Per-child abort by stable reference. Resolution order matches the steer destination rule\n // (profile name before label) with the exact workerId first; only LIVE workers resolve, so an\n // already-settled or unknown reference returns `undefined` instead of a false \"aborted\".\n const abortWorker = (\n ref: string,\n reason?: string,\n ): { readonly id: string; readonly label: string } | undefined => {\n const live = opts.scope.view.nodes.filter((node) => isLiveNodeStatus(node.status))\n const target =\n live.find((node) => node.id === ref) ??\n live.find((node) => profileNameByWorker.get(node.id) === ref) ??\n live.find((node) => node.label === ref)\n if (target === undefined) return undefined\n const handle = liveHandles.get(target.id)\n if (handle === undefined) return undefined\n handle.abort(reason)\n return { id: target.id, label: target.label }\n }\n\n return {\n profileNameByWorker,\n workerByAssignment,\n preflightCounts,\n nodeForWorker,\n workerRouteNames,\n liveWorkerIdNamed,\n resolveContinuity,\n admitSpawn,\n abortWorker,\n }\n}\n\nimport type { Scope } from '../../runtime'\n\nfunction nextUnkeyedAssignmentOrdinal(scope: Scope<unknown>): number {\n let next = 0\n const views = [scope.resume?.view, scope.view]\n for (const view of views) {\n if (view === undefined) continue\n for (const node of view.nodes) {\n const match = /^ordinal:(\\d+)$/.exec(node.assignmentId ?? '')\n if (match === null) continue\n const ordinal = Number(match[1])\n if (!Number.isSafeInteger(ordinal)) {\n throw new Error(\n `coordination: durable assignment id '${node.assignmentId}' exceeds the safe ordinal range`,\n )\n }\n next = Math.max(next, ordinal + 1)\n }\n }\n if (!Number.isSafeInteger(next)) {\n throw new Error('coordination: durable assignment ordinal space is exhausted')\n }\n return next\n}\n","/**\n *\n * The ONLINE analyst: watch a `TraceSource` and fold each tool span through agent-eval's published\n * streaming detector kernel (`repeatedActionDetector`/`errorStreakDetector` — the SAME kernel the\n * control loop folds), firing `onSignal` the moment a worker loops or error-storms. Substrate-\n * agnostic: it consumes spans from any source (owned router/bridge loop OR a sandbox box session),\n * never the raw tool seam. Detection logic + the failure taxonomy live in agent-eval; not reimplemented.\n *\n * @experimental\n */\n\nimport {\n argHash,\n type DetectorSignal,\n errorStreakDetector,\n observeAll,\n repeatedActionDetector,\n type StreamingDetector,\n type ToolSpan,\n} from '@tangle-network/agent-eval'\nimport type { TraceSource } from './trace-source'\n\nexport interface WatchTraceOptions {\n /** The detectors to run online. Defaults to a stuck-loop + error-streak panel. */\n readonly detectors?: ReadonlyArray<StreamingDetector>\n /** Fired for each signal a detector raises — the seam that raises a `finding` on the bus. */\n readonly onSignal?: (signal: DetectorSignal, span: ToolSpan) => void | Promise<void>\n}\n\n/** The default online panel for a tool-call pipe: a worker repeating the same call, or hammering\n * consecutive errors. (No-progress needs a domain progress-probe, so it is opt-in, not default.)\n *\n * Coverage note: `repeated-action` works for EVERY harness (it needs only tool name + args, which\n * every adapter provides). `error-streak` needs per-call status — opencode carries it inline\n * (`state.status`, VALIDATED live), but claude-code/codex tool-call parts do NOT (their errors live\n * in separate result blocks not yet decoded), so error-streak is silent for those until result-block\n * decoding is added + live-validated. It is in the panel because it is correct where status exists. */\nexport function defaultToolDetectors(): StreamingDetector[] {\n return [repeatedActionDetector({ maxRepeated: 3 }), errorStreakDetector({ maxErrors: 3 })]\n}\n\n/** Subscribe to a `TraceSource` and run the streaming detectors over its live spans. Returns an\n * unsubscribe. A defensive `argHash` failure (circular args) never throws out of the side-channel. */\nexport function watchTrace(source: TraceSource, opts: WatchTraceOptions = {}): () => void {\n const detectors = opts.detectors ?? defaultToolDetectors()\n return source.onSpan((span) => {\n let fingerprint: string\n try {\n // Same fingerprint scheme as agent-eval's batch stuck-loop view: tool name + hashed args.\n fingerprint = `${span.toolName}|${argHash(span.args)}`\n } catch {\n fingerprint = `${span.toolName}|<unhashable>`\n }\n const signals = observeAll(detectors, {\n actionFingerprint: fingerprint,\n ...(span.status ? { status: span.status } : {}),\n label: span.toolName,\n })\n for (const s of signals) void opts.onSignal?.(s, span)\n })\n}\n","import type { Scope } from '../../runtime'\nimport { watchTrace } from '../../runtime/supervise/detector-monitor'\nimport type { EventBus } from '../../runtime/supervise/event-bus'\nimport { isLiveNodeStatus } from '../../runtime/supervise/node-status'\nimport type { WorkerProgress } from '../../runtime/supervise/progress'\nimport { canonicalFindingEvent } from './coordination-analysts'\nimport type { CoordinationToolsOptions, SettledWorker } from './coordination-contracts'\nimport { eventWorker } from './coordination-event-projection'\nimport type { CoordinationEvent } from './coordination-events'\nimport { modelSubstitutionReport } from './coordination-model-attribution'\n\nexport function createWorkerObservation({\n opts,\n ledger,\n flushedAnalystRuns,\n bus,\n deadlineNoticeDelivered,\n leadPublishing,\n}: {\n readonly opts: CoordinationToolsOptions\n readonly ledger: ReadonlyArray<SettledWorker>\n readonly flushedAnalystRuns: ReadonlySet<string>\n readonly bus: EventBus<CoordinationEvent>\n readonly deadlineNoticeDelivered: () => boolean\n readonly leadPublishing: () => number\n}) {\n // This manager's own children that have not settled, and those of them still waiting for a\n // worker slot. The slot allocator is shared by the whole tree, so its reading is read live.\n const liveWorkerCount = (): number =>\n opts.scope.view.nodes.filter((n) => isLiveNodeStatus(n.status)).length\n const queuedWorkerCount = (): number =>\n opts.scope.view.nodes.filter((n) => n.status === 'queued').length\n\n // A snapshot of every still-in-flight worker — the liveness signal a wake\n // returns when its wait elapses, so the supervisor can tell \"worker still running, keep waiting\"\n // apart from \"nothing is happening\" (the distinction it lost when the unbounded await erred out).\n const projectNodeEvidence = (\n node: Scope<unknown>['view']['nodes'][number],\n resumed = false,\n ): Record<string, unknown> => ({\n id: node.id,\n status: node.status,\n ...(node.assignmentId === undefined ? {} : { assignmentId: node.assignmentId }),\n ...(node.identity === undefined ? {} : { identity: node.identity }),\n ...(node.modelSubstitution === undefined\n ? {}\n : modelSubstitutionReport(node.modelSubstitution)),\n ...(node.materialization === undefined ? {} : { materialization: node.materialization }),\n ...(node.executionBindings === undefined ? {} : { executionBindings: node.executionBindings }),\n spent: node.spent,\n ...(node.settledAt === undefined ? {} : { settledAt: node.settledAt }),\n ...(node.outRef === undefined ? {} : { outRef: node.outRef }),\n ...(node.trace === undefined ? {} : { trace: node.trace }),\n ...(resumed ? { resumed: true } : {}),\n })\n\n const liveSnapshot = (): Array<Record<string, unknown>> =>\n opts.scope.view.nodes\n .filter((n) => isLiveNodeStatus(n.status))\n .map((n) => projectNodeEvidence(n))\n\n // ── closure ──────────────────────────────────────────────────────────────────\n //\n // A manager may not close its run while work it commissioned is unread: a worker still running,\n // a settlement or finding queued for the next wake, or a settlement the coordinator holds and\n // has not queued yet. Measured in Autopsy C (2026-09-03): a root stopped 15 to 45 s after its\n // children returned without reading them, and the verification it had commissioned sat\n // unclaimed. The refusal names the open work so the manager can go and read it.\n const openWork = () => {\n const received = new Set(ledger.map((worker) => worker.id))\n // A hand-built scope may expose no view at all; it then has no children to wait for.\n const nodes = (opts.scope as Partial<Scope<unknown>>).view?.nodes ?? []\n const running = nodes.filter((node) => isLiveNodeStatus(node.status))\n const unqueued = nodes.filter(\n (node) =>\n !isLiveNodeStatus(node.status) &&\n !received.has(node.id) &&\n !flushedAnalystRuns.has(node.id),\n )\n // Questions have their own closure rule (`questionPolicy`), so only results count here.\n // A steer the manager has not read is as unread as a result. The outcome of its own earlier tool\n // call is not work it commissioned, so it never refuses a submission.\n const queued = bus.queued(['settled', 'finding', 'lead-message', 'map'])\n return { running, unqueued, queued }\n }\n const openWorkRefusal = (verb: 'submit_result' | 'stop'): Record<string, unknown> | undefined => {\n if (deadlineNoticeDelivered()) return undefined\n const { running, unqueued, queued } = openWork()\n if (\n running.length === 0 &&\n unqueued.length === 0 &&\n queued.length === 0 &&\n leadPublishing() === 0\n )\n return undefined\n const parts: string[] = []\n if (running.length > 0)\n parts.push(\n `${running.length} worker${running.length === 1 ? ' is' : 's are'} still running (${running.map((node) => node.id).join(', ')})`,\n )\n const waiting = unqueued.length + queued.length\n if (waiting > 0)\n parts.push(`${waiting} event${waiting === 1 ? ' is' : 's are'} waiting for you`)\n if (leadPublishing() > 0)\n parts.push(\n `${leadPublishing()} lead message${leadPublishing() === 1 ? ' is' : 's are'} still being published`,\n )\n return {\n error: 'open-work' as const,\n reason:\n `${parts.join(' and ')}. End your turn to wait: you will be woken with each result. Read each settled ` +\n `worker's output, and then call ${verb} again. Nothing was ${verb === 'stop' ? 'stopped' : 'checked'}.`,\n running: running.map((node) => ({ id: node.id, label: node.label, status: node.status })),\n waiting: [\n ...queued.map((record) => ({\n type: record.event.type,\n ...(eventWorker(record.event) === undefined ? {} : { worker: eventWorker(record.event) }),\n })),\n ...unqueued.map((node) => ({ type: 'settled', worker: node.id })),\n ],\n }\n }\n\n // How many more workers could start working RIGHT NOW, or `null` when no bound is set (the\n // conserved pool is then the only fence, so there is no finite slot count). A spawn past the\n // bound is queued rather than refused; this reading tells the driver whether a new worker starts\n // at once or waits behind the queue. Policy (whether to spawn) stays with the driver.\n const freeWorkerSlots = (): number | null =>\n (opts.scope as Partial<Scope<unknown>>).workerCapacity?.freeSlots ?? null\n\n // The LIVE read of one worker. Guarded because `createCoordinationTools` is bound to a `Scope`\n // it did not construct — an older or hand-rolled scope may not implement `progress` at all, and\n // an observation must degrade to \"no progress available\", never throw at the driver.\n const readProgress = (id: string): WorkerProgress | undefined => {\n const scope = opts.scope as Partial<Scope<unknown>>\n if (typeof scope.progress !== 'function') return undefined\n try {\n return scope.progress(\n id,\n opts.stallAfterMs !== undefined ? { stallAfterMs: opts.stallAfterMs } : {},\n )\n } catch {\n return undefined\n }\n }\n\n // ONLINE detection: subscribe the streaming detector panel to a freshly-spawned worker's live\n // tool trace, and turn each signal into a `finding` the driver receives in its next wake. The\n // unsubscribe fires on the worker's settle (its trace source is dead from then on) and the\n // per-worker cap stops one looping worker from flooding the bus.\n const watchers = new Map<string, () => void>()\n const watchWorker = (id: string): void => {\n const watch = opts.watchWorkers\n if (!watch) return\n const scope = opts.scope as Partial<Scope<unknown>>\n if (typeof scope.traceSource !== 'function') return\n let source: ReturnType<NonNullable<Scope<unknown>['traceSource']>>\n try {\n source = scope.traceSource(id)\n } catch {\n return\n }\n if (!source) return\n const cap = watch.maxFindingsPerWorker ?? 3\n let raised = 0\n const unsub = watchTrace(source, {\n ...(watch.detectors ? { detectors: watch.detectors } : {}),\n onSignal: async (signal, span) => {\n if (cap > 0 && raised >= cap) return\n raised += 1\n await bus.publish({\n type: 'finding',\n // canonicalFindingEvent: `span.toolName` is optional — an undefined value anywhere in\n // the payload would throw in the digesting subscriber and vanish the event.\n finding: canonicalFindingEvent({\n fromWorker: id,\n analyst: `online:${signal.detector}`,\n findings: {\n detector: signal.detector,\n severity: signal.severity,\n reason: signal.reason,\n streak: signal.streak,\n ...(signal.failureClass ? { failureClass: signal.failureClass } : {}),\n toolName: span.toolName,\n at: span.endedAt,\n progress: readProgress(id),\n },\n }),\n })\n },\n })\n watchers.set(id, unsub)\n }\n const unwatchWorker = (id: string): void => {\n const unsub = watchers.get(id)\n if (!unsub) return\n watchers.delete(id)\n try {\n unsub()\n } catch {\n // an unsubscribe that throws must never break the settle path\n }\n }\n\n return {\n liveWorkerCount,\n queuedWorkerCount,\n projectNodeEvidence,\n liveSnapshot,\n openWork,\n openWorkRefusal,\n freeWorkerSlots,\n readProgress,\n watchWorker,\n unwatchWorker,\n }\n}\n","import type { Settled } from '../../runtime'\nimport { settlementFailureCause } from '../../runtime/failure-cause'\nimport { detachedFrozen } from '../../runtime/supervise/snapshot'\nimport { BUDGET_STOP_NEXT, budgetOverspendText } from './coordination-budget'\nimport type { CoordinationToolsOptions, SettledWorker } from './coordination-contracts'\nimport { modelSubstitutionReport } from './coordination-model-attribution'\nimport type { createSpawnAdmission } from './coordination-spawn-admission'\n\nexport function createWorkerSettlement({\n opts,\n nodeForWorker,\n}: {\n readonly opts: CoordinationToolsOptions\n readonly nodeForWorker: ReturnType<typeof createSpawnAdmission>['nodeForWorker']\n}) {\n // Outputs of descendants this manager learned by content address from a team summary.\n const descendantOutRefs = new Set<string>(opts.sourceEvidenceRefs ?? [])\n const projectSettled = (settled: Settled<unknown>, resumed = false): SettledWorker => {\n const node = nodeForWorker(settled.handle.id)\n const assignmentId = settled.handle.assignmentId ?? node?.assignmentId\n const identity = settled.handle.identity ?? node?.identity\n const modelSubstitution = settled.handle.modelSubstitution ?? node?.modelSubstitution\n const materialization = settled.handle.materialization ?? node?.materialization\n const executionBindings = settled.handle.executionBindings ?? node?.executionBindings\n const settledAt = settled.settledAt ?? node?.settledAt\n const trace =\n settled.trace ??\n node?.trace ??\n ({\n status: 'unavailable',\n reason: 'legacy-settlement-without-trace-evidence',\n } as const)\n const common = {\n id: settled.handle.id,\n ...(assignmentId === undefined ? {} : { assignmentId }),\n ...(identity === undefined ? {} : { identity }),\n ...(modelSubstitution === undefined ? {} : modelSubstitutionReport(modelSubstitution)),\n ...(materialization === undefined ? {} : { materialization }),\n ...(executionBindings === undefined ? {} : { executionBindings }),\n ...(settledAt === undefined ? {} : { settledAt }),\n ...(settled.budgetViolation === undefined\n ? {}\n : {\n budgetViolation: settled.budgetViolation,\n budgetStop: budgetOverspendText(settled.budgetViolation),\n ...(assignmentId?.startsWith('key:') === true\n ? { budgetStopNext: BUDGET_STOP_NEXT }\n : {}),\n }),\n trace,\n ...(settled.subtree === undefined ? {} : { subtree: settled.subtree }),\n ...(resumed ? { resumed: true as const } : {}),\n }\n // A result a manager was told about by digest is one it may read; no other digest is.\n for (const result of settled.subtree?.results ?? []) {\n if (result.outRef !== undefined) descendantOutRefs.add(result.outRef)\n }\n return detachedFrozen<SettledWorker>(\n settled.kind === 'done'\n ? {\n ...common,\n status: 'done',\n spent: settled.spent,\n ...(settled.verdict?.score === undefined ? {} : { score: settled.verdict.score }),\n ...(settled.verdict?.valid === undefined ? {} : { valid: settled.verdict.valid }),\n outRef: settled.outRef,\n }\n : {\n ...common,\n status: 'down',\n ...(settled.outRef === undefined ? {} : { outRef: settled.outRef }),\n ...(node?.spent === undefined ? {} : { spent: node.spent }),\n reason: settled.reason,\n failure: settlementFailureCause(settled),\n },\n )\n }\n\n return { descendantOutRefs, projectSettled }\n}\n","import { agentProfileSchema } from '@tangle-network/agent-interface'\nimport { registry } from 'zod'\nimport { detachedFrozen } from '../../runtime/supervise/snapshot'\nimport type { SuperviseProfileEntry } from './coordination-contracts'\n\n/**\n * Strip zod's object-KEY CODEC artifact from a derived JSON Schema, at every depth.\n *\n * `z.record(z.string(), …)` converts to `propertyNames: { type: 'string', pattern:\n * '^u(?:[0-9a-f]{4})*$' }` — a marker of the lossy key round-trip, not a constraint anything\n * enforces: `agentProfileSchema.safeParse({ name: 'r', tools: { bash: true, Read: false } })`\n * succeeds with those plain keys. Published verbatim it reads to a model as \"every key must be a\n * run of hex quads\", and the model either emits hex-encoded garbage keys or drops the field —\n * on `tools`, `permissions`, `metadata`, `mcp`, `mcp.*.env`, and `model.metadata`, which is most\n * of what a parent actually configures.\n *\n * Every `propertyNames` in the canonical profile schema is this artifact (25 of 25 at Interface\n * 0.40), and the canonical schema constrains no key by pattern, so dropping the keyword outright\n * loses nothing real and cannot be defeated by zod changing the encoding's exact regex.\n *\n * Rebuilds rather than mutates: the canonical conversion output must stay untouched for callers\n * that compare against it.\n */\nconst stripKeyCodecArtifacts = (node: unknown): unknown => {\n if (Array.isArray(node)) return node.map(stripKeyCodecArtifacts)\n if (!node || typeof node !== 'object') return node\n return Object.fromEntries(\n Object.entries(node as Record<string, unknown>)\n .filter(([key]) => key !== 'propertyNames')\n .map(([key, value]) => [key, stripKeyCodecArtifacts(value)]),\n )\n}\n\n/** One field of the published child-profile shape: the canonical field it mirrors, the one-line\n * description a model can act on (what it is, what a child typically sets), and — for the two\n * fields whose canonical sub-tree dwarfs the rest of the tool surface — the BRIEF schema published\n * in place of that sub-tree. */\ninterface PublishedProfileField {\n readonly name: string\n readonly description: string\n readonly brief?: Record<string, unknown>\n}\n\n/** The canonical profile fields a spawning parent actually sets on a child, in the order a reader\n * needs them, each with the description published alongside it. Everything else stays legal to\n * pass — see {@link deriveSpawnProfileArg}.\n *\n * Why these eleven, with the measured numbers (serialized JSON bytes, Interface 0.40). The\n * canonical `properties` map is 10629 bytes, against 2424 bytes for every argument of every other\n * coordination tool COMBINED — publishing it whole makes one parameter four times the rest of the\n * surface a driver re-reads each turn. Of the seven omitted fields (tags, connections, subagents,\n * hooks, modes, confidential, extensions) none is something a parent hands a worker; `permissions`\n * (321 bytes) IS, so it is published — a child that must not touch the network or the filesystem\n * is fenced there and nowhere else. `mcp` (2663 bytes) and `resources` (3122 bytes) are the two a\n * parent is least likely to author inline and were together 85% of the published cost, so they\n * carry a brief shape plus a description naming the full form instead of the canonical sub-tree. */\nconst spawnProfileFields: readonly PublishedProfileField[] = [\n {\n name: 'name',\n description:\n 'Short identifier for this child, e.g. \"researcher\" or \"patch-writer\". A child normally ' +\n 'sets it to its role; it shows up in traces and worker labels.',\n },\n {\n name: 'description',\n description:\n 'One line saying what this child is for. Read by humans and by a parent listing its workers.',\n },\n {\n name: 'version',\n description:\n 'Optional version string for this profile, so two revisions of the same role are ' +\n 'distinguishable in evidence. A child usually omits it.',\n },\n {\n name: 'harness',\n description:\n 'Which coding backend runs the child. Omit to inherit the run default; set it only when ' +\n 'this child needs a specific backend (e.g. a long refactor on \"claude-code\").',\n },\n {\n name: 'model',\n description:\n 'Model routing: `default` model id, optional `small` for cheap sub-calls, `provider`, and ' +\n '`reasoningEffort`. A child typically sets `default` and `reasoningEffort` — raise effort ' +\n 'for a hard reasoning task, lower it for bulk mechanical work.',\n },\n {\n name: 'prompt',\n description:\n \"The child's standing instructions: `systemPrompt` (who it is and how it works) and \" +\n '`instructions` (durable rules). This is the role; the separate `task` argument carries ' +\n 'what to do right now. A child with no systemPrompt has no role — always set one.',\n },\n {\n name: 'tools',\n description:\n 'Per-tool on/off map keyed by tool name, e.g. `{ \"bash\": true, \"webfetch\": false }`. Omit ' +\n \"to inherit the backend's default tool set; set it to narrow a child to the tools its task \" +\n 'needs. Keys are plain tool names.',\n },\n {\n name: 'permissions',\n description:\n 'Per-tool permission decisions: each tool name maps to \"allow\", \"deny\", or \"ask\", or to a ' +\n 'nested map of finer-grained rules. This is where a parent fences a child it does not fully ' +\n 'trust — a read-only child denies write and network tools here, not in `tools`.',\n },\n {\n name: 'mcp',\n description:\n 'MCP tool servers to mount for the child, keyed by server name. Brief form: each value is ' +\n 'either `{ transport: \"stdio\", command, args?, env?, cwd? }` or ' +\n '`{ transport: \"sse\" | \"http\", url, headers? }`. A child normally sets this only when it ' +\n 'needs a tool server the task requires; the canonical AgentProfile schema carries the full ' +\n 'form (secret-ref values for env/headers, per-server metadata) and governs validation.',\n brief: { type: 'object', additionalProperties: { type: 'object' } },\n },\n {\n name: 'resources',\n description:\n 'Files, tools, skills, and agents materialized into the child workspace before it starts. ' +\n 'Brief form: `{ files?, tools?, skills?, agents? }`, each an array whose entries are ' +\n '`{ kind: \"inline\", name, content }`, `{ kind: \"inline\", name, path }`, or ' +\n '`{ kind: \"github\", repository?, path, ref? }` ' +\n '(`files` entries wrap that as `{ path, resource, executable? }`). An inline `path` is ' +\n 'relative to YOUR workspace and is read by the runtime, so use it for any file over a few ' +\n 'hundred bytes: content you retype in this call arrives truncated and altered, a path ' +\n 'arrives byte-exact and the result reports its sha256. A child typically gets ' +\n '`files` for seed inputs and `skills` for a procedure it must follow; the canonical ' +\n 'AgentProfile schema carries the full form and governs validation.',\n brief: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'object' } },\n tools: { type: 'array', items: { type: 'object' } },\n skills: { type: 'array', items: { type: 'object' } },\n agents: { type: 'array', items: { type: 'object' } },\n },\n additionalProperties: true,\n },\n },\n {\n name: 'metadata',\n description:\n 'Free-form key/value bag carried with the profile (plain string keys). Use it for run ' +\n 'bookkeeping a reader will want later; it does not change how the child executes.',\n },\n]\n\n/**\n * Build the published shape of `spawn_worker`'s `profile` argument from the canonical\n * `agentProfileSchema` conversion's `properties` map, so it cannot drift from the profile the\n * runtime materializes.\n *\n * DEGRADES, never throws. A canonical field that is absent — renamed or removed upstream — is\n * simply omitted from the published shape, and a canonical schema that is no longer an object\n * publishes no properties at all. This function is reached from a statically-imported module, so a\n * throw here bricks `import '@tangle-network/agent-runtime/kernel'` for every consumer over an\n * upstream rename that costs them, at worst, one advisory field. The drift itself is still caught\n * loudly — as a test assertion in `tests/kernel/coordination.test.ts`, in CI, where it is our\n * problem rather than at a consumer's import, where it is theirs.\n *\n * Permissive on purpose: `additionalProperties: true` with no `required` list, so every canonical\n * field this shape omits stays legal to pass. This tool layer performs no profile validation.\n *\n * @internal exported for the drift and degradation tests; not part of the package's public API.\n */\nfunction deriveSpawnProfileArg(\n canonicalProperties: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n const published: Array<[string, unknown]> = []\n for (const field of spawnProfileFields) {\n const canonical = canonicalProperties?.[field.name]\n if (canonical === undefined) continue\n const shape = field.brief ?? (stripKeyCodecArtifacts(canonical) as Record<string, unknown>)\n published.push([field.name, { ...shape, description: field.description }])\n }\n return {\n type: 'object',\n description:\n 'The child agent profile to run — this is the shape the DEFAULT worker seam accepts; a run ' +\n 'wired with a custom makeWorkerAgent may accept a different one. The properties below are ' +\n 'derived from the canonical AgentProfile schema and reduced to what a spawning parent sets ' +\n '(`mcp` and `resources` in a brief form); every other canonical field — tags, connections, ' +\n 'subagents, hooks, modes, confidential, extensions — may still be passed. This tool does ' +\n 'not validate the profile: the canonical AgentProfile schema governs validation downstream.',\n properties: Object.fromEntries(published),\n additionalProperties: true,\n }\n}\n\nlet spawnProfileArgCache: Record<string, unknown> | undefined\n\n/** The published `profile` shape, computed on FIRST tool-definition access and memoized — not at\n * module load. The conversion walks the whole canonical profile tree, and the strip walk rebuilds\n * it: 3.5ms on the first `createCoordinationTools`, 0.017ms on every later one (measured, Interface\n * 0.40, node 24). `src/runtime/index.ts` imports this module statically, so paying that at import\n * taxes every consumer of the kernel entrypoint — including the ones that never build a\n * coordination toolbox. The memo keeps it at once per process for the ones that do.\n *\n * Conversion choices. `io: 'input'` is the CALLER's view — pre-default, pre-transform — which is\n * what a spawning parent may pass, not what the runtime ends up holding. `unrepresentable: 'any'`\n * keeps the conversion total: the canonical schema contains transforms with no JSON Schema form,\n * and zod's default is to throw on them, which would leave the tool with no published shape. */\nexport function spawnProfileArg(): Record<string, unknown> {\n if (!spawnProfileArgCache) {\n const canonical = agentProfileSchema.toJSONSchema({\n // Runtime's API metadata contains ids and output schemas. Derive this input shape\n // without that shared registry so import order cannot replace properties with a ref.\n metadata: registry(),\n io: 'input',\n target: 'draft-07',\n unrepresentable: 'any',\n })\n // Deep-frozen because ONE memoized object is handed to every coordination toolbox in the\n // process: an unfrozen shared schema lets one consumer's mutation corrupt every later one.\n spawnProfileArgCache = detachedFrozen(deriveSpawnProfileArg(canonical.properties))\n }\n return spawnProfileArgCache\n}\n\n/** `spawn_worker`'s `profile` argument when the run has a profiles table: one of the table's names,\n * listed with each entry's description and whether a sealed verdict promoted it, or a profile the\n * manager authors. Without a table the argument is the authored shape alone, byte for byte. */\nexport function spawnProfileArgWithTable(\n profiles: ReadonlyMap<string, SuperviseProfileEntry>,\n): Record<string, unknown> {\n const menu = [...profiles].map(([name, entry]) => {\n const description =\n typeof entry.profile.description === 'string' && entry.profile.description.length > 0\n ? ` — ${entry.profile.description}`\n : ''\n const status = entry.promotion\n ? `promoted by sealed play ${JSON.stringify(entry.promotion.experiment.spec.id)}`\n : 'exploratory'\n return `- '${name}'${description} (${status})`\n })\n return {\n anyOf: [\n {\n type: 'string',\n enum: [...profiles.keys()],\n description:\n \"The name of a profile in this run's profiles table. The runtime runs that exact \" +\n 'profile, so do not retype it; other profile fields cannot be added to a name. ' +\n 'Promoted entries beat their control in a sealed comparison; exploratory ones have no ' +\n `verdict yet.\\n${menu.join('\\n')}`,\n },\n spawnProfileArg(),\n ],\n }\n}\n\n/** Why `spawn_worker` cannot use this `profile` argument against the profiles table, or\n * `undefined` when it can. A name must be in the table. An authored profile must not take a table\n * name: continuity and every per-name record key on `profile.name`, so one name must mean one\n * profile. Without a table nothing is refused here, and the canonical schema answers as before. */\nexport function profileTableRefusal(\n table: ReadonlyMap<string, SuperviseProfileEntry> | undefined,\n profile: unknown,\n): string | undefined {\n if (table === undefined) return undefined\n if (typeof profile === 'string') {\n if (table.has(profile)) return undefined\n return `profile ${JSON.stringify(profile)} is not in this run's profiles table, which holds ${[\n ...table.keys(),\n ]\n .map((name) => JSON.stringify(name))\n .join(', ')}`\n }\n const name =\n typeof profile === 'object' && profile !== null\n ? (profile as { readonly name?: unknown }).name\n : undefined\n if (typeof name !== 'string' || !table.has(name)) return undefined\n return `profile.name ${JSON.stringify(name)} is a profiles-table entry: pass profile: ${JSON.stringify(name)} to run that exact profile, or give the profile you wrote another name`\n}\n","import type { ResultBlobStore } from '../../runtime/supervise/types'\n\n// JSON escaping can expand each character sixfold; this page remains below a native tool frame.\nexport const WORKER_OUTPUT_PAGE_CHARS = 16_384\n\nexport function workerOutputReadOptions(raw: Record<string, unknown>): {\n offset: number\n limit: number\n path: readonly string[]\n} {\n const offset = raw.outputOffset ?? 0\n const limit = raw.outputLimit ?? WORKER_OUTPUT_PAGE_CHARS\n const path = raw.outputPath === undefined ? [] : raw.outputPath\n if (!Array.isArray(path) || !path.every((part) => typeof part === 'string')) {\n throw new Error('observe_agent outputPath must be an array of field names')\n }\n if (typeof offset !== 'number' || !Number.isSafeInteger(offset) || offset < 0) {\n throw new Error('observe_agent outputOffset must be a nonnegative safe integer')\n }\n if (\n typeof limit !== 'number' ||\n !Number.isSafeInteger(limit) ||\n limit < 1 ||\n limit > WORKER_OUTPUT_PAGE_CHARS\n ) {\n throw new Error(\n `observe_agent outputLimit must be an integer from 1 to ${WORKER_OUTPUT_PAGE_CHARS}`,\n )\n }\n return { offset, limit, path }\n}\n\ntype EncodedWorkerOutput =\n | { readonly kind: 'missing' }\n | { readonly kind: 'page'; readonly text: string }\n | { readonly kind: 'small'; readonly output: unknown; readonly text: string }\n\ninterface WorkerOutputCacheEntry {\n readonly outRef: string\n readonly path: readonly string[]\n readonly result: Promise<EncodedWorkerOutput>\n activeReads: number\n releaseWhenIdle: boolean\n}\n\nfunction samePath(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((field, index) => field === right[index])\n}\n\nfunction selectWorkerOutput(output: unknown, path: readonly string[]): unknown {\n let selected = output\n for (const field of path) {\n if (selected === null || typeof selected !== 'object' || !Object.hasOwn(selected, field)) {\n throw new Error('observe_agent outputPath does not identify a retained field')\n }\n selected = (selected as Record<string, unknown>)[field]\n }\n return selected\n}\n\nasync function encodeWorkerOutput(\n blobs: Pick<ResultBlobStore, 'get'>,\n outRef: string,\n path: readonly string[],\n): Promise<EncodedWorkerOutput> {\n const retained = await blobs.get(outRef)\n if (retained === undefined) return { kind: 'missing' }\n const output = selectWorkerOutput(retained, path)\n const text = JSON.stringify(output)\n if (text === undefined) throw new Error('observe_agent result blob is not JSON-serializable')\n // A paged result can never return its typed value: outputLimit is capped at this page size.\n // Drop the parsed selection after encoding so a large archive does not stay live beside its text.\n return text.length > WORKER_OUTPUT_PAGE_CHARS\n ? { kind: 'page', text }\n : { kind: 'small', output, text }\n}\n\nfunction readEncodedWorkerOutput(\n encoded: EncodedWorkerOutput,\n { offset, limit }: Pick<ReturnType<typeof workerOutputReadOptions>, 'offset' | 'limit'>,\n): Record<string, unknown> {\n if (encoded.kind === 'missing') return { output: null, outputUnavailable: 'result-blob-missing' }\n const { text } = encoded\n if (offset > text.length)\n throw new Error('observe_agent outputOffset exceeds the retained output')\n if (encoded.kind === 'small' && offset === 0 && text.length <= limit) {\n return { output: encoded.output }\n }\n const end = Math.min(offset + limit, text.length)\n return {\n output: null,\n outputPage: {\n format: 'json',\n text: text.slice(offset, end),\n offset,\n nextOffset: end < text.length ? end : null,\n totalChars: text.length,\n },\n }\n}\n\ntype WorkerOutputReader = (\n outRef: string | undefined,\n options: ReturnType<typeof workerOutputReadOptions>,\n) => Promise<Record<string, unknown>>\n\n/**\n * Create a manager-scoped reader for immutable retained artifacts.\n *\n * At most one selected `outRef` + path is retained. Concurrent reads for that selection share the\n * blob read and JSON encoding; missing blobs and rejected selections are evicted after all readers\n * leave so a transient failure cannot poison later observations.\n */\nexport function createWorkerOutputReader(blobs: Pick<ResultBlobStore, 'get'>): WorkerOutputReader {\n let cached: WorkerOutputCacheEntry | undefined\n\n return async (outRef, options) => {\n if (outRef === undefined) return { output: null }\n\n let entry = cached\n if (entry === undefined || entry.outRef !== outRef || !samePath(entry.path, options.path)) {\n const path = [...options.path]\n entry = {\n outRef,\n path,\n result: encodeWorkerOutput(blobs, outRef, path),\n activeReads: 0,\n releaseWhenIdle: false,\n }\n cached = entry\n }\n\n entry.activeReads += 1\n try {\n const encoded = await entry.result\n const reply = readEncodedWorkerOutput(encoded, options)\n if (encoded.kind === 'missing') {\n entry.releaseWhenIdle = true\n } else {\n const page = reply.outputPage as { readonly nextOffset?: number | null } | undefined\n if (page === undefined || page.nextOffset === null) entry.releaseWhenIdle = true\n }\n return reply\n } catch (error) {\n entry.releaseWhenIdle = true\n throw error\n } finally {\n entry.activeReads -= 1\n if (entry.releaseWhenIdle && entry.activeReads === 0 && cached === entry) cached = undefined\n }\n }\n}\n","import { agentProfileSchema } from '@tangle-network/agent-interface'\nimport { isLiveNodeStatus } from '../../runtime/supervise/node-status'\nimport { runtimeGraphMetadataKey } from '../../runtime/supervise/provider-visible-profile'\nimport { detachedFrozen } from '../../runtime/supervise/snapshot'\nimport type { McpToolDescriptor } from '../server'\nimport { spawnBudgetArg } from './coordination-budget'\nimport type { CoordinationTools, CoordinationToolsOptions } from './coordination-contracts'\nimport { obj, parseContinuity, str } from './coordination-input'\nimport { downMessageRefusalReasons } from './coordination-messages'\nimport {\n profileTableRefusal,\n spawnProfileArg,\n spawnProfileArgWithTable,\n} from './coordination-profile-schema'\nimport type { createSpawnAdmission } from './coordination-spawn-admission'\nimport { idArg } from './coordination-worker-argument'\nimport type { createWorkerObservation } from './coordination-worker-observation'\nimport {\n type ResolveSpawnResourcePathsResult,\n resolveSpawnResourcePaths,\n} from './spawn-resource-paths'\nimport type { createWorkerOutputReader } from './worker-output'\nimport { WORKER_OUTPUT_PAGE_CHARS, workerOutputReadOptions } from './worker-output'\nexport function createWorkerTools({\n opts,\n profileTable,\n spawn,\n workers,\n descendantOutRefs,\n readWorkerOutput,\n redactJournalEvent,\n steerWorker,\n}: {\n readonly opts: CoordinationToolsOptions\n readonly profileTable: CoordinationToolsOptions['profiles']\n readonly spawn: ReturnType<typeof createSpawnAdmission>\n readonly workers: ReturnType<typeof createWorkerObservation>\n readonly descendantOutRefs: ReadonlySet<string>\n readonly redactJournalEvent: (value: unknown) => unknown\n readonly readWorkerOutput: ReturnType<typeof createWorkerOutputReader>\n readonly steerWorker: CoordinationTools['steerWorker']\n}): McpToolDescriptor[] {\n return [\n {\n name: 'spawn_worker',\n description:\n 'Start a worker the driver will drive. `profile` is the worker or another driver; ' +\n '`task` is what it should do. Reserves budget from the conserved pool and fails closed. ' +\n 'Pass an optional `budget` (per-field) to give a sub-task more or less than the default — ' +\n 'it merges over the per-worker default; the conserved pool is still the hard fence. Each ' +\n 'worker reserves its whole budget when it starts, so the pool divided by the per-worker ' +\n 'budget is how many run at once: to run a wide team at once, give each worker less. When ' +\n 'every worker slot is busy, or the pool cannot cover the budget until your running workers ' +\n 'return what they hold, the worker is admitted with `status: \"queued\"` and starts on its ' +\n 'own when a slot and its budget free — it is never refused for concurrency, so spawn all ' +\n 'the work you want done, then end your turn: you are woken with each result. A queued worker whose budget ' +\n 'never frees settles down as budget-exhausted. ' +\n 'Pass a `key` naming the assignment to make it run-once ACROSS restarts: a key that ' +\n 'already completed returns the finished result (`resumed: \"completed\"` — no work re-runs, ' +\n 'nothing is spent). A keyed worker that settled with a `budgetStop` keeps its session for ' +\n 'a while: spawn the same key with a larger `budget` and a new worker continues that same ' +\n 'session where it stopped (`resumed: \"continued\"`, `priorWorkerId`), or cancel_worker the ' +\n 'stopped worker to release it. A key whose prior attempt failed (`down`) spawns fresh and says so ' +\n '(`resumed: \"retried\"`), and a key the process died with IN FLIGHT retries under the same ' +\n 'key when the executor provably died with the process (an inline worker — the same ' +\n '`resumed: \"retried\"`, naming the interruption). A key with no terminal receipt whose ' +\n 'execution may still exist elsewhere (sandbox, CLI bridge, router) is refused ' +\n '(`error: \"in-doubt\"`) until its exact prior execution is recovered. A key still running ' +\n 'is refused (`error: \"duplicate-key\"`). ' +\n 'Returns `freeSlots`: how many MORE workers start at once (`null` = no slot bound), and ' +\n '`queued`: how many of your workers wait for a slot. Parallel workers finish the run ' +\n 'sooner than one at a time.' +\n (profileTable === undefined\n ? ''\n : \" This run has a profiles table: pass `profile` as one of the table's names to run \" +\n 'that exact profile, or write a new profile under a name the table does not hold.'),\n inputSchema: {\n type: 'object',\n properties: {\n profile:\n profileTable === undefined ? spawnProfileArg() : spawnProfileArgWithTable(profileTable),\n task: { description: 'The task the worker should perform.' },\n label: {\n type: 'string',\n description: 'Optional trace label; defaults to the profile name.',\n },\n key: {\n type: 'string',\n description:\n 'Optional semantic name for this assignment (e.g. \"summarize-ch3\"). The same key ' +\n 'never runs twice: completed keys return their committed result, even after a ' +\n 'coordinator restart.',\n },\n continuity: {\n type: 'string',\n enum: ['fresh', 'resume'],\n description:\n 'How this spawn continues the node\\'s prior work. \"fresh\" (the default) starts a ' +\n 'brand-new session. \"resume\" re-attaches to the node\\'s most recent SETTLED ' +\n 'worker: a NEW live worker is spawned whose session continues where that worker ' +\n 'stopped (the backend receives the prior workerId and the resume sequence). ' +\n 'Resume fails closed when the node has no settled prior worker ' +\n '(`error: \"resume-no-prior\"` — spawn it fresh first), while a prior worker of the ' +\n 'node is still live (`error: \"resume-while-live\"` — steer_agent is the ' +\n 'live-worker channel), and under a `key` (`error: \"resume-with-key\"` — keys are ' +\n \"run-once, resume runs again). Omit to use the run's declared default for this \" +\n 'profile name.',\n },\n successorOf: {\n type: 'string',\n description:\n 'The workerId of a SETTLED worker you spawned that this new worker replaces — for ' +\n 'example one that failed, stalled, or finished with a weak result, restarted with a ' +\n 'changed profile or task. The run record then names the predecessor on the new ' +\n 'worker. Refused for an id you did not spawn (`error: \"successor-unknown\"`) and for ' +\n 'a worker still live (`error: \"successor-live\"` — end your turn until it settles). ' +\n 'Put what the successor needs from its predecessor in `task`.',\n },\n budget: spawnBudgetArg,\n },\n required: ['profile', 'task'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const key = a.key === undefined ? undefined : str(a.key, 'key')\n // A name selects a profiles-table entry: its exact validated profile stands in for an\n // authored one, and every step below treats it the same way.\n const tableRefusal = profileTableRefusal(profileTable, a.profile)\n if (tableRefusal !== undefined) {\n return {\n error: 'invalid-profile' as const,\n reason: tableRefusal,\n issues: [{ path: 'profile', message: tableRefusal }],\n }\n }\n const tableEntry = typeof a.profile === 'string' ? profileTable?.get(a.profile) : undefined\n // A resource named by path is read here, under the manager's workspace root, so the\n // canonical schema validates the inline resource its bytes make and the journal records\n // exactly what the child received. A table entry carries its own bytes.\n const resourcePaths: ResolveSpawnResourcePathsResult =\n tableEntry === undefined\n ? await resolveSpawnResourcePaths(\n a.profile,\n opts.spawnResourceReader ?? opts.spawnResourceRoot,\n )\n : { ok: true as const, profile: tableEntry.profile, resolved: [] }\n if (!resourcePaths.ok) {\n return {\n error: 'invalid-profile' as const,\n reason: `resources.${resourcePaths.at}: ${resourcePaths.reason}`,\n issues: [{ path: `resources.${resourcePaths.at}`, message: resourcePaths.reason }],\n }\n }\n const parsedProfile = agentProfileSchema.safeParse(resourcePaths.profile)\n if (!parsedProfile.success) {\n return Promise.resolve({\n error: 'invalid-profile' as const,\n reason: `the profile you wrote is not a valid AgentProfile: ${parsedProfile.error.issues\n .map((issue) => `${issue.path.join('.') || 'profile'} ${issue.message}`)\n .join('; ')}`,\n issues: parsedProfile.error.issues.map((issue) => ({\n path: issue.path.join('.'),\n message: issue.message,\n })),\n })\n }\n // Only run_graph starts a graph: the topology a graph root carries is Runtime's to write,\n // so a profile that carries one would start a graph without the run_graph grant.\n if (parsedProfile.data.metadata?.[runtimeGraphMetadataKey] !== undefined) {\n const reason = `metadata.${runtimeGraphMetadataKey} is written by Runtime for the root of a run_graph subtask; call run_graph to run a graph`\n return {\n error: 'invalid-profile' as const,\n reason,\n issues: [{ path: `metadata.${runtimeGraphMetadataKey}`, message: reason }],\n }\n }\n const profile = detachedFrozen(\n opts.composeSpawnProfile\n ? agentProfileSchema.parse(opts.composeSpawnProfile(parsedProfile.data))\n : parsedProfile.data,\n )\n // Continuity resolves BEFORE any assignment is minted or budget reserved, so a refused\n // resume touches nothing — same fail-closed discipline as the fences above.\n const continuity = spawn.resolveContinuity(parseContinuity(a.continuity), profile.name, key)\n if ('error' in continuity) {\n return Promise.resolve({\n // `reason` is the contract every refusal carries; `hint` is retained under its old name\n // for readers that already key on it, and both are the same sentence by construction so\n // they cannot drift.\n error: continuity.error,\n reason: continuity.hint,\n hint: continuity.hint,\n live: workers.liveWorkerCount(),\n freeSlots: workers.freeWorkerSlots(),\n })\n }\n // A successor names a settled worker of this manager, so the relation the journal records\n // is true: never an unknown id, and never a worker still running beside its replacement.\n const successorOf =\n a.successorOf === undefined ? undefined : str(a.successorOf, 'successorOf')\n if (successorOf !== undefined) {\n const predecessor = spawn.nodeForWorker(successorOf)\n if (predecessor === undefined || predecessor.parent !== opts.scope.view.root) {\n return {\n error: 'successor-unknown' as const,\n reason: `'${successorOf}' is not a worker this manager spawned — successorOf takes a workerId from one of your own spawn_worker results`,\n live: workers.liveWorkerCount(),\n freeSlots: workers.freeWorkerSlots(),\n }\n }\n if (isLiveNodeStatus(predecessor.status)) {\n return {\n error: 'successor-live' as const,\n reason: `worker '${successorOf}' has not settled — end your turn until it does, then spawn its successor (steer_agent redirects a live worker instead)`,\n live: workers.liveWorkerCount(),\n freeSlots: workers.freeWorkerSlots(),\n }\n }\n }\n return spawn.admitSpawn({\n profile,\n args: a,\n task: a.task,\n key,\n continuity,\n successorOf,\n // The gate judges the profile that will RUN. A pinning layer resolves the authored stub\n // to its canonical profile here, so the backend is asked about the real model and tools.\n preflightProfile: () =>\n opts.resolveSpawnProfile ? detachedFrozen(opts.resolveSpawnProfile(profile)) : profile,\n resourcesFromPath: resourcePaths.resolved,\n // magnetar-rust-20261018b's 13 workers were all labelled 'worker', so no view showed a role.\n defaultLabel:\n typeof profile.name === 'string' && profile.name.length > 0 ? profile.name : 'worker',\n })\n },\n },\n {\n name: 'observe_agent',\n description:\n 'Inspect a worker WHILE IT RUNS, not only after it finishes: status, spend so far, and ' +\n '`progress` — how long since it last did anything (`idleMs`), whether that counts as ' +\n 'stalled, how many turns it has taken, the last tools/files it touched ' +\n '(`recentActivity`), what its executor CHANGED about the profile you gave it ' +\n '(`derived` — an MCP config it materialized, an extension it had to add), whether a ' +\n 'steer can even reach it (`steerable`), and how many ' +\n 'steers it has not yet read (`pendingMessages`). For a worker that leads its own team, ' +\n '`progress.team` counts the agents below it (working, queued, done, down) and its idle ' +\n 'clock reads the newest activity anywhere in that team, so a lead whose workers are busy ' +\n 'is not stalled. A queued worker waits for a worker slot and is never stalled. ' +\n 'A worker whose executor has FINISHED ' +\n 'but whose settlement you have not yet drained reports `settlementPending` with its ' +\n 'terminal kind; its `status` still reads running until your next wake ' +\n 'delivers it, so end your turn rather than observing again. The settled output ' +\n 'artifact is returned once drained. Select a field with `outputPath`, for example [\"content\"] ' +\n 'to read a provider result without its event history. Omit it to read the complete artifact. ' +\n 'Large outputs return a bounded JSON `outputPage`; ' +\n 'repeat with `outputOffset: outputPage.nextOffset` until it is null, concatenate page text, ' +\n 'then parse the JSON. Offsets and limits count UTF-16 characters. The full artifact stays ' +\n 'retained; an outRef is a content address, not a workspace path. Use this BEFORE steer_agent: a steer is only worth ' +\n 'sending when the progress says the worker is on the wrong path or has stopped making any.',\n inputSchema: {\n type: 'object',\n properties: {\n events: {\n type: 'boolean',\n description: 'Read bounded live output for an owned descendant.',\n },\n tree: {\n type: 'boolean',\n description: \"Read this manager's complete owned tree without reading state files.\",\n },\n eventCursor: {\n type: 'object',\n properties: {\n epoch: { type: 'string', minLength: 1 },\n next: { type: 'integer', minimum: 0 },\n },\n required: ['epoch', 'next'],\n additionalProperties: false,\n },\n\n workerId: idArg,\n outRef: {\n type: 'string',\n description:\n 'Instead of workerId: the content address of a result listed in a settled ' +\n \"worker's `subtree.results` or authorized for your analyst assignment, to read it in full.\",\n },\n outputPath: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Own field names from the artifact root; array indices use strings. Default: the complete artifact.',\n },\n outputOffset: {\n type: 'integer',\n minimum: 0,\n description: 'Start at this retained JSON character offset; default 0.',\n },\n outputLimit: {\n type: 'integer',\n minimum: 1,\n maximum: WORKER_OUTPUT_PAGE_CHARS,\n description: `Maximum JSON characters per page; default ${WORKER_OUTPUT_PAGE_CHARS}.`,\n },\n },\n },\n handler: async (raw) => {\n const args = obj(raw)\n if (args.tree === true) {\n const tree = opts.scope.observeTree?.() ?? opts.scope.view\n return redactJournalEvent({\n tree: {\n root: tree.root,\n inFlight: tree.inFlight,\n nodes: tree.nodes.map((node) => ({\n id: node.id,\n parent: node.parent,\n label: node.label,\n status: node.status,\n runtime: node.runtime,\n spawnedAt: node.spawnedAt,\n settledAt: node.settledAt,\n })),\n },\n })\n }\n const eventCursor =\n args.eventCursor === undefined\n ? undefined\n : (() => {\n const cursor = obj(args.eventCursor)\n if (\n typeof cursor.epoch !== 'string' ||\n cursor.epoch.length === 0 ||\n !Number.isSafeInteger(cursor.next) ||\n Number(cursor.next) < 0\n )\n throw new Error('eventCursor must name an epoch and a non-negative safe integer')\n return { epoch: cursor.epoch, next: Number(cursor.next) }\n })()\n if (args.events === true) {\n const id = str(args.workerId, 'workerId')\n const node = (opts.scope.observeTree?.() ?? opts.scope.view).nodes.find(\n (candidate) => candidate.id === id,\n )\n if (!node) return { error: 'unknown-worker' as const }\n return redactJournalEvent({\n id: node.id,\n parent: node.parent,\n label: node.label,\n status: node.status,\n runtime: node.runtime,\n events: opts.scope.observeEvents?.(id, eventCursor) ?? {\n status: 'unavailable',\n reason: 'not-captured',\n },\n })\n }\n const outputRead = workerOutputReadOptions(args)\n if (args.outRef !== undefined && args.workerId === undefined) {\n const outRef = str(args.outRef, 'outRef')\n if (!descendantOutRefs.has(outRef)) {\n return {\n error: 'unknown-result' as const,\n reason:\n 'this outRef was not authorized as assignment evidence or listed in a subtree summary; pass an authorized source ref, a subtree.results outRef, or observe your own worker by workerId',\n }\n }\n return { outRef, ...(await readWorkerOutput(outRef, outputRead)) }\n }\n const id = str(args.workerId, 'workerId')\n const node = opts.scope.view.nodes.find((n) => n.id === id)\n if (!node) {\n // A worker from a PRIOR process of this run: not in the live nursery, but its committed\n // record is on the resumed view — observable like any settled worker, marked `resumed`.\n const resumed = opts.scope.resume?.view.nodes.find((n) => n.id === id)\n if (!resumed)\n return {\n error: 'unknown-worker' as const,\n reason: `no worker of this manager has the id ${JSON.stringify(id)}; spawn_worker returns the ids you may observe`,\n }\n return {\n ...workers.projectNodeEvidence(resumed, true),\n outRef: resumed.outRef ?? null,\n ...(await readWorkerOutput(resumed.outRef, outputRead)),\n progress: null,\n }\n }\n const progress = workers.readProgress(id)\n // Finished-but-undrained is the one state a polling manager cannot otherwise see: the\n // executor is gone, the settlement sits in the inbox, and `status` still says running.\n // Say so in the fields the manager reads, and point at the call that resolves it.\n const pending = node.settlementPending\n return {\n ...workers.projectNodeEvidence(node),\n events: opts.scope.observeEvents?.(node.id, eventCursor) ?? {\n status: 'unavailable',\n reason: 'not-captured',\n },\n outRef: node.outRef ?? null,\n ...(await readWorkerOutput(node.outRef, outputRead)),\n progress: progress ?? null,\n ...(pending\n ? {\n settlementPending: pending,\n hint: `this worker has finished (${pending.kind}); its settlement is queued for your next wake — end your turn to receive it, observing again will not change this`,\n }\n : {}),\n }\n },\n },\n {\n name: 'steer_agent',\n description:\n 'Send a message DOWN to a still-LIVE worker (parent→child): a new instruction, a course ' +\n 'correction, or a continuation. The worker reads it at its next step boundary — and before ' +\n 'it may settle, so it cannot finish while a message it never read is pending. A worker that ' +\n 'already settled is gone (returns delivered:false) — spawn a fresh one instead.',\n inputSchema: {\n type: 'object',\n properties: {\n workerId: idArg,\n instruction: { type: 'string', description: 'What the worker should do next.' },\n interrupt: {\n type: 'boolean',\n description:\n 'true = forceful: abort the worker’s in-flight inference so it re-plans on the NEXT ' +\n 'turn (a tool already mid-execution finishes first; only the owned tool-loop honors this). ' +\n 'false/omitted = queued: it flushes at the next step boundary (and before it may settle).',\n },\n },\n required: ['workerId', 'instruction'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const workerId = str(a.workerId, 'workerId')\n const instruction = str(a.instruction, 'instruction')\n const delivery = await steerWorker(workerId, instruction, {\n interrupt: a.interrupt === true,\n })\n if (delivery.delivered) {\n return { delivered: true, progress: workers.readProgress(workerId) ?? null }\n }\n return {\n delivered: false,\n outcome: delivery.outcome,\n reason: downMessageRefusalReasons[delivery.outcome],\n progress: workers.readProgress(workerId) ?? null,\n }\n },\n },\n {\n name: 'cancel_worker',\n description:\n 'Cancel one of YOUR live workers — running, or queued for a worker slot — and every worker ' +\n 'it leads. Its unspent budget returns to your pool when it settles, so this is how you ' +\n 'take back what a stalled or no-longer-needed worker holds (for example when spawn_worker ' +\n 'is refused budget-exhausted while workers you no longer need hold the budget). The ' +\n 'cancelled worker still settles `down`, delivered in your next wake with what it spent. ' +\n 'For a worker that settled with a `budgetStop` and still holds its session, this releases ' +\n 'that session instead (`released: true`). ' +\n 'Refused (`error: \"not-live\"`) for a worker that already settled or is not yours.',\n inputSchema: {\n type: 'object',\n properties: {\n workerId: idArg,\n reason: {\n type: 'string',\n description: 'Why it is cancelled; recorded on its settlement.',\n },\n },\n required: ['workerId'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const workerId = str(a.workerId, 'workerId')\n const why = a.reason === undefined ? 'cancelled by its manager' : str(a.reason, 'reason')\n // Exact ids only: a label or profile name could name a sibling the manager did not mean.\n const own = opts.scope.view.nodes.some(\n (node) => node.id === workerId && isLiveNodeStatus(node.status),\n )\n const cancelled = own ? spawn.abortWorker(workerId, why) : undefined\n if (\n cancelled === undefined &&\n opts.scope.view.nodes.some(\n (node) => node.id === workerId && node.parent === opts.scope.view.root,\n ) &&\n (await opts.scope.releaseHeld?.(workerId, 'cancel-worker')) === true\n ) {\n return {\n released: true,\n workerId,\n live: workers.liveWorkerCount(),\n queued: workers.queuedWorkerCount(),\n }\n }\n if (cancelled === undefined) {\n return {\n error: 'not-live' as const,\n reason: `'${workerId}' is not a live worker you spawned; only your own running or queued workers can be cancelled`,\n live: workers.liveWorkerCount(),\n queued: workers.queuedWorkerCount(),\n }\n }\n return {\n cancelled: true,\n workerId: cancelled.id,\n label: cancelled.label,\n live: workers.liveWorkerCount(),\n queued: workers.queuedWorkerCount(),\n }\n },\n },\n ]\n}\n","import type { Scope } from '../../runtime'\nimport { CheckUnavailableError, type CheckVerdict } from '../../runtime/supervise/completion-gate'\nimport { type CheckRead, checkVerdictOf } from '../../runtime/supervise/continuation'\nimport { type BusRecord, createEventBus } from '../../runtime/supervise/event-bus'\nimport { INBOX_RECEIPT_KEY, type InboxReceipt } from '../../runtime/supervise/inbox'\nimport { isLiveNodeStatus } from '../../runtime/supervise/node-status'\nimport { createPeerMailbox, type PeerMailbox } from '../../runtime/supervise/peer-mail'\nimport { detachedFrozen } from '../../runtime/supervise/snapshot'\nimport type { McpToolDescriptor } from '../server'\nimport { createCoordinationAnalysis } from './coordination-analysis'\nimport { mountAnalystsTools } from './coordination-analyst-tools'\nimport { canonicalFindingEvent } from './coordination-analysts'\nimport { createAuditTools } from './coordination-audit-tools'\nimport { refusalText } from './coordination-completion-refusal'\nimport type {\n BlockedToolReport,\n CoordinationTools,\n CoordinationToolsOptions,\n SettledWorker,\n} from './coordination-contracts'\nimport { createDownMessages } from './coordination-down-messages'\nimport { projectEvent } from './coordination-event-projection'\nimport type { Delivery } from './coordination-events'\nimport {\n type AwaitWakeInput,\n type CoordinationEvent,\n type EventAcknowledgement,\n type ManagerWake,\n type ToolOutcomeEvent,\n wakeEventKinds,\n} from './coordination-events'\nimport { mountGraphsTools } from './coordination-graph-tools'\nimport { obj, str } from './coordination-input'\nimport { createJournalReader } from './coordination-journal-reader'\nimport { managerReentryState } from './coordination-manager-reentry'\nimport { createMapRouting } from './coordination-map-routing'\nimport { createQuestionLedger } from './coordination-question-ledger'\nimport { createQuestionTools } from './coordination-question-tools'\nimport { createRouteRouting } from './coordination-route-routing'\nimport { createSettlementDrain } from './coordination-settlement-drain'\nimport { createSpawnAdmission } from './coordination-spawn-admission'\nimport { createWorkerObservation } from './coordination-worker-observation'\nimport { createWorkerSettlement } from './coordination-worker-settlement'\nimport { createWorkerTools } from './coordination-worker-tools'\nimport { createWorkerOutputReader } from './worker-output'\n\n/** Build the driver's MCP tools over a live scope. */\nexport function createCoordinationTools(opts: CoordinationToolsOptions): CoordinationTools {\n return createCoordinationToolsForManager(opts)\n}\n\n/** Internal manager binding; its lifetime fences delivery without cancelling the worker scope. */\nexport function createCoordinationToolsForManager(\n opts: CoordinationToolsOptions,\n lifetime?: AbortSignal,\n): CoordinationTools {\n // The one child→parent pipe. Keep the event-first callback and also pass its exact stamp, so a\n // durable subscriber retains causal sequence, original timestamp, and priority.\n const bus = createEventBus<CoordinationEvent>()\n const questionLedger = createQuestionLedger({ opts, bus })\n const { questions, addQuestion, emitNewQuestion, escalations, blockingQuestionsForStop } =\n questionLedger\n\n const deliverable = opts.deliverable\n const profileTable =\n opts.profiles !== undefined && opts.profiles.size > 0 ? opts.profiles : undefined\n // The manager owns one bounded reader so adjacent/concurrent pages share the immutable\n // content-addressed selection without allowing a caller-supplied blob reference to bypass the\n // worker lookup below.\n const readWorkerOutput = createWorkerOutputReader(opts.blobs)\n // An accepted direct result is a terminal fact, not an in-process callback. A durable observer\n // appends the `submission` record before the tool responds, so a fresh manager can restore it\n // after a crash in the response-to-driver window.\n const priorSubmission =\n deliverable === undefined\n ? undefined\n : opts.priorJournal?.find(\n (\n record,\n ): record is BusRecord<Extract<CoordinationEvent, { readonly type: 'submission' }>> =>\n record.event.type === 'submission',\n )\n let stopped = priorSubmission !== undefined\n let reason: string | undefined = priorSubmission === undefined ? undefined : 'result-accepted'\n let stopNotified = false\n let submitted: { readonly result: unknown } | undefined =\n priorSubmission === undefined\n ? undefined\n : detachedFrozen({ result: priorSubmission.event.result })\n let submissionInFlight: Promise<void> | undefined\n // Every `report_blocked` whose probe failed too.\n const blockedReports: BlockedToolReport[] = []\n\n const ledger: SettledWorker[] = []\n\n const notifyStop = (): void => {\n if (stopNotified) return\n stopNotified = true\n opts.onStop?.(reason)\n }\n const spawnAdmission = createSpawnAdmission({\n opts,\n ledger,\n liveWorkerCount: () => liveWorkerCount(),\n freeWorkerSlots: () => freeWorkerSlots(),\n queuedWorkerCount: () => queuedWorkerCount(),\n watchWorker: (id) => watchWorker(id),\n peerMail: () => peerMail,\n projectSettled: (settled, resumed) => projectSettled(settled, resumed),\n })\n const {\n profileNameByWorker,\n workerByAssignment,\n preflightCounts,\n nodeForWorker,\n workerRouteNames,\n liveWorkerIdNamed,\n resolveContinuity,\n admitSpawn,\n abortWorker,\n } = spawnAdmission\n const { descendantOutRefs, projectSettled } = createWorkerSettlement({ opts, nodeForWorker })\n\n const leadReceipts = new Map<string, (receipt: InboxReceipt) => void>()\n const analysis = createCoordinationAnalysis({\n leadReceipts,\n opts,\n ledger,\n bus,\n profileNameByWorker,\n watchWorker: (id) => watchWorker(id),\n liveWorkerIdNamed,\n messages: () => messages,\n ready: () => ready(),\n ensureDrain: () => ensureDrain(),\n })\n const {\n analystRuns,\n flushedAnalystRuns,\n analystRunFinding,\n analystRunContext,\n finishAnalysis,\n definedAnalysts,\n analystMenu,\n defineAnalyst,\n } = analysis\n\n // Replayed reviews remain findings. They cannot enter the completion pool or recursively\n // trigger another analyst, even when the resumed configuration changes its analyst routes.\n const resumedWorkers: SettledWorker[] = []\n const resumedFindings: CoordinationEvent[] = []\n for (const s of opts.scope.resume?.settled ?? []) {\n const analyst = analystRuns.get(s.handle.id)\n if (analyst) {\n resumedFindings.push(analystRunFinding(analyst, s))\n analystRuns.delete(s.handle.id)\n flushedAnalystRuns.add(s.handle.id)\n continue\n }\n const worker = projectSettled(s, true)\n resumedWorkers.push(worker)\n ledger.push(worker)\n }\n if (opts.onEvent) {\n const cb = opts.onEvent\n bus.subscribe((rec) => cb(rec.event, rec))\n }\n // A settlement can be durable in the spawn journal while the process dies before the product\n // observer acknowledges it. Opted-in high-level callers replay those events at least once. Keep\n // each frozen event object across an in-process retry so EventBus reuses its exact BusRecord.\n const resumeEvents = opts.replaySettlements\n ? [\n ...resumedWorkers.map((worker) =>\n detachedFrozen<CoordinationEvent>({ type: 'settled', worker }),\n ),\n ...resumedFindings,\n ]\n : []\n let resumeEventIndex = 0\n let readyInFlight: Promise<void> | undefined\n // The flow start hook: a flow's entries are spawned once, when the coordination opens and\n // before the manager's first turn, after any replayed settlements are published.\n const ready = async (): Promise<void> => {\n await replayResumeEvents()\n if (opts.routeFlow !== undefined) await routes.start()\n }\n const replayResumeEvents = (): Promise<void> => {\n if (resumeEventIndex >= resumeEvents.length) return Promise.resolve()\n if (readyInFlight) return readyInFlight\n readyInFlight = (async () => {\n while (resumeEventIndex < resumeEvents.length) {\n const event = resumeEvents[resumeEventIndex]\n if (!event) break\n await bus.publish(event)\n resumeEventIndex += 1\n }\n })().finally(() => {\n readyInFlight = undefined\n })\n return readyInFlight\n }\n const deliveries: Delivery[] = []\n // Tool calls that outlived their response fence, by receipt. Each is open work: its outcome\n // reaches the manager as a `tool-outcome` event on the next wake.\n const openReceipts = new Map<string, { readonly tool: string; readonly startedAt: number }>()\n let receiptSeq = 0\n // Lead messages accepted and still being published. The sender is told `delivered` the moment the\n // message is accepted, so a manager that ends its turn then must still count it as open work.\n let leadPublishing = 0\n // Set once a wake has told this manager the deadline is near. From then on open work does not\n // refuse its `submit_result` or `stop`: the notice asks for the best result now, and the workers\n // still running are torn down when the manager settles.\n let deadlineNoticeDelivered = false\n let driverAttempt: number | undefined\n const journal = createJournalReader({ opts, bus })\n const { readJournal, priorJournal } = journal\n\n let lastRejection: { readonly at: number; readonly reason: string } | undefined\n const checkReads: CheckRead[] = []\n const recordCheckRead = (read: {\n readonly source: CheckRead['source']\n readonly verdict?: CheckVerdict\n readonly unavailable?: string\n }): CheckRead => {\n const entry = detachedFrozen<CheckRead>({\n read: checkReads.length + 1,\n attempt: driverAttempt ?? 1,\n at: Date.now(),\n source: read.source,\n ...(read.verdict === undefined ? {} : { verdict: read.verdict }),\n ...(read.unavailable === undefined ? {} : { unavailable: read.unavailable }),\n })\n checkReads.push(entry)\n return entry\n }\n const acknowledge = async (\n targets: ReadonlyArray<Delivery>,\n by: EventAcknowledgement['by'],\n ): Promise<number[]> => {\n const fresh = targets.filter((delivery) => !delivery.acknowledged)\n if (fresh.length === 0) return []\n // A lead's steer or answer was read by the turn that processed it: answer its sender.\n for (const delivery of fresh) {\n const event = delivery.record.event\n const messageId = event.type === 'lead-message' ? event.message.messageId : undefined\n const receipt = messageId === undefined ? undefined : leadReceipts.get(messageId)\n if (messageId === undefined || receipt === undefined) continue\n leadReceipts.delete(messageId)\n try {\n receipt({\n status: 'consumed',\n messageId,\n attemptId: `${opts.scope.view.root}#attempt-${delivery.attempt ?? driverAttempt ?? 1}`,\n })\n } catch {\n // A sender's receipt handler cannot change what this manager processed.\n }\n }\n const seqs = fresh.map((delivery) => delivery.record.seq)\n await bus.publish(\n {\n type: 'acknowledgement',\n acknowledgement: detachedFrozen<EventAcknowledgement>({\n seqs,\n by,\n ...(driverAttempt === undefined ? {} : { attempt: driverAttempt }),\n }),\n },\n { queue: false },\n )\n for (const delivery of fresh) delivery.acknowledged = true\n return seqs\n }\n\n // Committed runtime spawns of a prior process, by node. They stay out of `profileNameByWorker`,\n // so they are never resume targets, but their replayed settles route and expand as live ones do.\n const committedNodes = new Map<string, string>()\n const nodeOf = (id: string) => profileNameByWorker.get(id) ?? committedNodes.get(id)\n const settleCommitted = (id: string, node: string): Promise<void> => {\n committedNodes.set(id, node)\n return settlements.settleCommitted(id)\n }\n const maps = createMapRouting({\n opts,\n bus,\n admitSpawn: (input) => admitSpawn(input),\n nodeOf,\n settleCommitted,\n endInDoubt: (node, source) => routes.endInDoubt(node, source),\n })\n const routes = createRouteRouting({\n opts,\n bus,\n admitSpawn: (input) => admitSpawn(input),\n resolveContinuity,\n nodeOf,\n settleCommitted,\n stop: (why) => {\n stopped = true\n reason = why\n notifyStop()\n },\n })\n const settlements = createSettlementDrain({\n opts,\n ledger,\n unwatchWorker: (id) => unwatchWorker(id),\n bus,\n analysis,\n maps,\n routes,\n workerRouteNames,\n projectSettled,\n })\n const { drainSettlement, drainResolved } = settlements\n const messages = createDownMessages({ opts, bus, lifetime })\n const { steerWorker } = messages\n\n // The sibling channel, when this run enabled it. Publishing is record-only (`queue: false`) for\n // the same reason a steer is: the parent audits and can stop a thread, but peer traffic must not\n // enter the queue a wake delivers — a busy channel would otherwise bury the settlements and\n // questions a wake exists to deliver.\n const peerMail: PeerMailbox | undefined = opts.peerMail\n ? createPeerMailbox({\n scope: opts.scope,\n publish: (mail) =>\n bus.publish({ type: 'mail', mail }, { queue: false }).then(() => undefined),\n ...(opts.peerMail.limits ? { limits: opts.peerMail.limits } : {}),\n })\n : undefined\n // magnetar-rust-20261017c dropped 8 escalations from nested leads with 'no parent inbox': no path\n // carried a child manager's question to the manager that spawned it.\n opts.onChildQuestionInbox?.(async (assignmentId, asked) => {\n const workerId = workerByAssignment.get(assignmentId)\n if (workerId === undefined || nodeForWorker(workerId) === undefined) {\n return {\n delivered: false,\n reason: `the parent manager has no worker for assignment ${JSON.stringify(assignmentId)}`,\n }\n }\n const record = await emitNewQuestion(\n addQuestion(\n {\n from: workerId,\n level: asked.level,\n question: asked.question,\n reason: asked.reason,\n ...(asked.options ? { options: asked.options } : {}),\n urgency: asked.urgency,\n },\n workerId,\n ),\n )\n return { delivered: true, to: `parent manager question ${record.id}` }\n })\n const workers = createWorkerObservation({\n opts,\n ledger,\n flushedAnalystRuns,\n bus,\n deadlineNoticeDelivered: () => deadlineNoticeDelivered,\n leadPublishing: () => leadPublishing,\n })\n const {\n liveWorkerCount,\n queuedWorkerCount,\n liveSnapshot,\n openWork,\n openWorkRefusal,\n freeWorkerSlots,\n readProgress,\n watchWorker,\n unwatchWorker,\n } = workers\n\n // The blocking `scope.next()` (via `drainSettlement`) waits on a LIVE worker for its whole run.\n // Keep at most ONE such drain in flight, so a wake that ends on its heartbeat never starts a\n // second block, and the one drain still delivers the settlement (exactly-once via the scope\n // cursor) whenever it lands.\n let inFlightDrain: Promise<boolean> | null = null\n const ensureDrain = (): Promise<boolean> => {\n if (!inFlightDrain)\n inFlightDrain = drainSettlement().finally(() => {\n inFlightDrain = null\n })\n return inFlightDrain\n }\n\n // ── waiting ─────────────────────────────────────────────────────────────────────\n //\n // A manager with nothing to do ends its turn, and Runtime waits for it. Measured 2026-10-05 on\n // two Discovery roots: when the manager did the waiting through a bounded poll, 18 of 88 model\n // turns did nothing but wait, each re-reading the whole cached context. The wait below spends\n // no model turn: it blocks on the bus, and its result becomes the input of the next turn.\n const settledWithoutDrain = async (): Promise<void> => {\n // Move children that already settled onto the bus. Only when no blocking drain holds the\n // cursor: that drain publishes whatever it takes itself.\n if (inFlightDrain) return\n inFlightDrain = (async () => {\n let drained = false\n while (await drainSettlement('nextResolved')) drained = true\n return drained\n })().finally(() => {\n inFlightDrain = null\n })\n await inFlightDrain\n }\n const hasOpenWork = (): boolean => {\n const { running, unqueued, queued } = openWork()\n return (\n running.length > 0 ||\n unqueued.length > 0 ||\n queued.length > 0 ||\n bus.pending(wakeEventKinds) > 0 ||\n openReceipts.size > 0 ||\n leadPublishing > 0 ||\n // A settlement taken from the cursor and still being published, with its analysis.\n settlements.isBusy()\n )\n }\n // Every live worker reports progress and none is stalled; unknown progress counts as stalled.\n const liveWorkersProgressing = (): boolean => {\n const running = openWork().running\n return running.length > 0 && running.every((node) => readProgress(node.id)?.stalled === false)\n }\n // A question one of this manager's workers raised wakes it: a child manager still working would\n // otherwise wait for the heartbeat, or for that child to settle and so never need the answer.\n // The manager's own ask_parent is recorded on the same bus and wakes nothing.\n const isWorkerQuestion = (event: CoordinationEvent): boolean =>\n event.type === 'question' && nodeForWorker(event.question.from) !== undefined\n const workerQuestionPending = (): boolean =>\n bus.queued(['question']).some((record) => isWorkerQuestion(record.event))\n const awaitWake = async (input: AwaitWakeInput): Promise<ManagerWake | undefined> => {\n const startedAt = Date.now()\n let quietHeartbeats = 0\n await ready()\n await settledWithoutDrain()\n if (!hasOpenWork() || input.signal.aborted) return undefined\n let heartbeatAt = startedAt + Math.max(0, input.heartbeatMs)\n const deadlineAt = input.deadlineAt ?? Number.POSITIVE_INFINITY\n let wakeAt = Math.min(heartbeatAt, deadlineAt)\n let unsubscribe: (() => void) | undefined\n let timer: ReturnType<typeof setTimeout> | undefined\n let onAbort: (() => void) | undefined\n let outsideWake = false\n try {\n const queuedEvent = new Promise<void>((resolve) => {\n // Once the record is pull-visible: a subscriber runs before the record is queued.\n unsubscribe = bus.onQueued((record) => {\n if (\n (wakeEventKinds as ReadonlyArray<string>).includes(record.event.type) ||\n isWorkerQuestion(record.event)\n )\n resolve()\n })\n })\n let elapsed: Promise<void> = Promise.resolve()\n const armTimer = (): void => {\n if (timer) clearTimeout(timer)\n elapsed = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, Math.max(0, wakeAt - Date.now()))\n // Held: a manager waiting for its workers is live work, and must keep its process up.\n })\n }\n armTimer()\n const aborted = new Promise<void>((resolve) => {\n onAbort = () => resolve()\n input.signal.addEventListener('abort', onAbort, { once: true })\n })\n const outside = (input.alsoWakeOn ?? new Promise<never>(() => undefined)).then(() => {\n outsideWake = true\n })\n // Set once the cursor reports no child it can wait on, so a node it does not drain cannot\n // turn this loop into a spin.\n let cursorIdle = false\n for (;;) {\n while (\n bus.pending(wakeEventKinds) === 0 &&\n !workerQuestionPending() &&\n !outsideWake &&\n !input.signal.aborted &&\n Date.now() < wakeAt\n ) {\n const running = !cursorIdle && openWork().running.length > 0\n // A live worker can only reach the bus through the blocking drain. With none live, the\n // open work is a question or a tool outcome, which publishes itself.\n const drained = running ? ensureDrain() : new Promise<boolean>(() => undefined)\n const done = await Promise.race([\n drained.then((value) => (value ? 'drained' : 'idle')),\n queuedEvent.then(() => 'queued' as const),\n elapsed.then(() => 'elapsed' as const),\n aborted.then(() => 'aborted' as const),\n outside.then(() => 'outside' as const),\n ])\n if (done === 'idle') {\n cursorIdle = true\n if (!hasOpenWork()) break\n }\n }\n // A heartbeat with nothing new costs no model turn while every live worker is still making\n // progress: Runtime re-arms it and keeps waiting. magnetar-rust-20261018b spent 58 of its\n // root's 79 turns, about 37% of root spend, on 15-minute wakes that changed nothing. A\n // stalled worker, no live worker, or the deadline still wakes the manager.\n if (\n input.quietWhileProgressing === true &&\n input.heartbeatMs > 0 &&\n bus.pending(wakeEventKinds) === 0 &&\n !workerQuestionPending() &&\n !outsideWake &&\n !input.signal.aborted &&\n Date.now() >= heartbeatAt &&\n Date.now() < deadlineAt &&\n liveWorkersProgressing()\n ) {\n quietHeartbeats += 1\n heartbeatAt = Date.now() + input.heartbeatMs\n wakeAt = Math.min(heartbeatAt, deadlineAt)\n armTimer()\n continue\n }\n break\n }\n if (input.signal.aborted) return undefined\n // A settlement queued mid-flush still has its analysis to publish: let that bounded flush\n // finish, so the settlement and the finding it triggers ride one wake.\n if (settlements.isFlushing() && inFlightDrain !== null) await inFlightDrain.catch(() => false)\n // Coalesce: whatever else lands within the debounce rides the same wake. Only while other\n // workers still run: with none, nothing else is coming.\n if (\n bus.pending(wakeEventKinds) > 0 &&\n input.debounceMs > 0 &&\n openWork().running.length > 0\n ) {\n await Promise.race([\n new Promise<void>((resolve) => {\n setTimeout(resolve, input.debounceMs)\n }),\n aborted,\n ])\n if (input.signal.aborted) return undefined\n await settledWithoutDrain()\n }\n } finally {\n unsubscribe?.()\n if (timer) clearTimeout(timer)\n if (onAbort) input.signal.removeEventListener('abort', onAbort)\n }\n const events: Array<Record<string, unknown> & { readonly eventSeq: number }> = []\n const pulledKinds: ReadonlyArray<CoordinationEvent['type']> = workerQuestionPending()\n ? [...wakeEventKinds, 'question']\n : wakeEventKinds\n for (let next = bus.pullRecord(pulledKinds); next; next = bus.pullRecord(pulledKinds)) {\n deliveries.push({\n record: next,\n attempt: input.attempt ?? driverAttempt,\n acknowledged: false,\n })\n events.push({ ...projectEvent(next.event), eventSeq: next.seq })\n }\n if (events.length === 0 && !outsideWake && !hasOpenWork()) return undefined\n const reason =\n events.length > 0 || outsideWake\n ? 'events'\n : Date.now() >= deadlineAt\n ? 'deadline'\n : 'heartbeat'\n if (reason === 'deadline') deadlineNoticeDelivered = true\n return detachedFrozen<ManagerWake>({\n reason,\n events,\n live: liveSnapshot(),\n freeSlots: freeWorkerSlots(),\n idleMs: Date.now() - startedAt,\n ...(quietHeartbeats === 0 ? {} : { quietHeartbeats }),\n })\n }\n\n const tools: McpToolDescriptor[] = [\n ...createWorkerTools({\n opts: opts,\n profileTable: profileTable,\n spawn: spawnAdmission,\n workers: workers,\n descendantOutRefs: descendantOutRefs,\n readWorkerOutput: readWorkerOutput,\n redactJournalEvent: journal.redactJournalEvent,\n steerWorker: steerWorker,\n }),\n\n ...createQuestionTools({ questionLedger: questionLedger, messages: messages }),\n\n ...(deliverable\n ? [\n {\n name: 'submit_result',\n description: [\n 'Submit the complete result to the injected independent check.',\n 'The first passing result is retained; stop work when accepted.',\n ...(deliverable.describe ? [`Expected result: ${deliverable.describe}`] : []),\n ].join(' '),\n inputSchema: {\n type: 'object',\n properties: {\n result: {\n description: 'The complete result in the form requested by the task.',\n },\n },\n required: ['result'],\n additionalProperties: false,\n },\n handler: async (raw: unknown) => {\n if (submitted) {\n return {\n accepted: true,\n retained: 'earlier-passing-result',\n stop: true,\n }\n }\n const a = obj(raw)\n if (!Object.hasOwn(a, 'result')) {\n throw new Error('submit_result: \"result\" is required')\n }\n const open = openWorkRefusal('submit_result')\n if (open !== undefined) {\n lastRejection = { at: Date.now(), reason: String(open.reason) }\n return { accepted: false, stop: false, ...open }\n }\n\n // Copy once at intake so the value checked below is the exact value retained after\n // acceptance, even when this handler is called directly rather than through JSON-RPC.\n const result = structuredClone(a.result)\n // A check that COULD NOT RUN and a check that FAILED are both \"not delivered\" —\n // fail-closed is unchanged — but they need opposite moves from the manager. A check\n // that could not run is not a verdict, and the refusal says so.\n let verdict: CheckVerdict | undefined\n let fault: { readonly unavailable: boolean; readonly message: string } | undefined\n try {\n verdict = checkVerdictOf(await deliverable.check(result))\n } catch (error) {\n fault = {\n unavailable: error instanceof CheckUnavailableError,\n message: error instanceof Error ? error.message : String(error),\n }\n }\n const read = recordCheckRead({\n source: 'submit',\n ...(verdict === undefined ? {} : { verdict }),\n ...(fault === undefined ? {} : { unavailable: fault.message }),\n })\n if (verdict === undefined || !verdict.pass) {\n const refusal =\n verdict !== undefined\n ? refusalText(verdict, deliverable, read.read)\n : fault?.unavailable === true\n ? `the check could not run, so this result was not judged (check read ${read.read}): ${fault.message}`\n : `the independent check THREW, so nothing was accepted (check read ${read.read}): ${fault?.message}. This is a fault in the check, not necessarily in your result — report it rather than resubmitting unchanged`\n lastRejection = { at: Date.now(), reason: refusal }\n return {\n accepted: false,\n stop: false,\n reason: refusal,\n checkRead: read.read,\n }\n }\n // Two remote callers may submit concurrently. Whichever passing check completes\n // first owns the retained result; a later completion must never overwrite it.\n if (submitted) {\n return {\n accepted: true,\n retained: 'earlier-passing-result',\n stop: true,\n }\n }\n\n // Persist before acknowledging. The first caller that reaches this point owns the\n // result while the append is in flight; a concurrent caller waits for the same\n // durable fact instead of appending a second passing result.\n if (submissionInFlight) {\n await submissionInFlight\n return {\n accepted: true,\n retained: 'earlier-passing-result',\n stop: true,\n }\n }\n const acceptedSubmission = detachedFrozen({ result })\n const commit = bus\n .publish(\n { type: 'submission', result: acceptedSubmission.result },\n { queue: false },\n )\n .then(() => {\n submitted = acceptedSubmission\n stopped = true\n reason = 'result-accepted'\n notifyStop()\n })\n submissionInFlight = commit\n try {\n await commit\n } finally {\n if (submissionInFlight === commit) submissionInFlight = undefined\n }\n // An accepted result is the manager's processing of everything it had received.\n await acknowledge(deliveries, 'result-accepted')\n return { accepted: true, retained: 'this-result', stop: true }\n },\n } satisfies McpToolDescriptor,\n ]\n : []),\n\n // A manager with a check ends only when the check passes or when a bound ends the run.\n // Measured before this rule (2026-09-24): 389 of 650\n // lead directors could call `stop`, which ended the run with no check and no second chance.\n ...(deliverable\n ? []\n : [\n {\n name: 'stop',\n description: 'Declare the run complete.',\n inputSchema: {\n type: 'object',\n properties: { reason: { type: 'string', description: 'Why you are stopping.' } },\n },\n handler: (raw) => {\n const blocking = blockingQuestionsForStop()\n if (blocking.length) {\n // Name the exit as well as the block. A question this manager escalated to nobody\n // (`no-parent`) will never be answered from above, so \"wait for an answer\" is not a\n // strategy — the manager is the last decider and must answer or defer it itself.\n const unheard = blocking.filter((question) =>\n escalations.some(\n (record) => record.questionId === question.id && record.delivered === false,\n ),\n )\n return Promise.resolve({\n stopped: false,\n error: 'unresolved-blocking-questions' as const,\n reason:\n `${blocking.length} blocking question${blocking.length === 1 ? '' : 's'} ${blocking.length === 1 ? 'is' : 'are'} still undecided` +\n (unheard.length > 0\n ? `, and ${unheard.length} of them reached no parent — nothing above this manager will answer ${unheard.length === 1 ? 'it' : 'them'}. Decide ${unheard.length === 1 ? 'it' : 'them'} with answer_question (answer, or deferReason to record that it stays open) and stop again.`\n : '. Decide each with answer_question (answer, deferReason, or escalateTo) and stop again.'),\n questions: blocking,\n ...(unheard.length > 0 ? { unheardQuestionIds: unheard.map((q) => q.id) } : {}),\n })\n }\n const open = openWorkRefusal('stop')\n if (open !== undefined) return Promise.resolve({ stopped: false, ...open })\n stopped = true\n const r = obj(raw).reason\n reason = typeof r === 'string' ? r : undefined\n notifyStop()\n return Promise.resolve({ stopped: true })\n },\n } satisfies McpToolDescriptor,\n ]),\n\n ...(opts.readContinuation\n ? [\n {\n name: 'read_continuation',\n description: [\n \"Read a continuation note in full: the note, every line of the check's verdict, and\",\n \"the question panel's answers. Omit continuation for the latest.\",\n ].join(' '),\n inputSchema: {\n type: 'object',\n properties: {\n continuation: {\n type: 'integer',\n minimum: 1,\n description: 'Which continuation, 1-based. Omit for the latest.',\n },\n },\n additionalProperties: false,\n },\n handler: async (raw: unknown) => {\n const value = obj(raw).continuation\n if (value !== undefined && (!Number.isInteger(value) || (value as number) < 1)) {\n throw new Error('read_continuation: \"continuation\" must be an integer >= 1')\n }\n return opts.readContinuation?.(value as number | undefined)\n },\n } satisfies McpToolDescriptor,\n ]\n : []),\n ...createAuditTools({\n opts: opts,\n tools: () => tools,\n blockedReports: blockedReports,\n readJournal: readJournal,\n }),\n ]\n\n if (opts.peerAudit) {\n for (const tool of tools) {\n if (tool.name !== 'observe_agent' && tool.name !== 'read_journal') continue\n const ownHandler = tool.handler\n const name = tool.name\n const schema = tool.inputSchema as { properties?: Record<string, unknown> }\n schema.properties = {\n ...schema.properties,\n peerId: {\n type: 'string',\n description:\n \"Read a peer root's own record, using its workerId from read_mail.peers. Read-only; omit for your own tree.\",\n },\n }\n tool.handler = async (raw) => {\n const args = obj(raw)\n if (args.peerId === undefined) return ownHandler(raw)\n const peerId = str(args.peerId, 'peerId')\n const { peerId: _peerId, ...readArgs } = args\n return opts.peerAudit?.read(peerId, name, readArgs)\n }\n }\n // A peer read must not claim that this manager has consumed its own journal.\n opts.peerAudit.register(\n opts.scope.view.root,\n tools.map((tool) =>\n tool.name === 'read_journal'\n ? { ...tool, handler: async (raw) => readJournal(raw, false) }\n : tool,\n ),\n )\n }\n mountGraphsTools({ opts, tools, admitSpawn })\n mountAnalystsTools({\n opts,\n tools,\n ledger,\n nodeForWorker,\n analystMenu,\n analystRunContext,\n defineAnalyst,\n })\n\n return {\n tools,\n ready,\n history: () => bus.history(),\n raiseFinding: (finding) =>\n bus\n .publish({ type: 'finding', finding: canonicalFindingEvent(finding) })\n .then(() => undefined),\n steerWorker,\n stats: () =>\n opts.preflightSpawn === undefined\n ? bus.stats()\n : { ...bus.stats(), preflight: { ...preflightCounts } },\n isStopped: () => stopped,\n stopReason: () => reason,\n submittedResult: () => submitted,\n settled: () => ledger,\n questions: () => questions,\n escalations: () => escalations,\n definedAnalysts: () => definedAnalysts,\n drainResolved,\n finishAnalysis,\n abortWorker,\n beginDriverAttempt: (attempt) => {\n driverAttempt = attempt\n },\n endDriverAttempt: async (outcome) => {\n const attempt = driverAttempt\n if (outcome === 'completed') {\n await acknowledge(\n deliveries.filter((delivery) => delivery.attempt === attempt),\n 'turn-completed',\n )\n }\n },\n hasOpenWork,\n awaitWake,\n awaitSettlement: async (workerIds, signal) => {\n const wanted = new Set(workerIds)\n const settledIds = () => ledger.filter((worker) => wanted.has(worker.id)).map((w) => w.id)\n await ready()\n for (;;) {\n await settledWithoutDrain()\n const hit = settledIds()\n if (hit.length > 0) return hit\n signal?.throwIfAborted()\n const live = ((opts.scope as Partial<Scope<unknown>>).view?.nodes ?? []).some(\n (node) => wanted.has(node.id) && isLiveNodeStatus(node.status),\n )\n if (!live) return []\n const drained = await (signal === undefined\n ? ensureDrain()\n : Promise.race([\n ensureDrain(),\n new Promise<never>((_resolve, reject) => {\n signal.addEventListener('abort', () => reject(signal.reason), { once: true })\n }),\n ]))\n if (!drained && settledIds().length === 0) return []\n }\n },\n receiveLeadMessage: (message) => {\n const parsed = leadMessageOf(message)\n if (parsed === undefined) return false\n const receipt = (message as Record<string, unknown>)[INBOX_RECEIPT_KEY]\n if (parsed.messageId !== undefined && typeof receipt === 'function') {\n leadReceipts.set(parsed.messageId, receipt as (receipt: InboxReceipt) => void)\n }\n leadPublishing += 1\n bus\n .publish({ type: 'lead-message', message: parsed })\n .catch((error: unknown) => {\n console.error('Runtime could not queue a lead message for its manager', {\n manager: opts.scope.view.root,\n error: error instanceof Error ? error.message : String(error),\n })\n })\n .finally(() => {\n leadPublishing -= 1\n })\n return true\n },\n openToolReceipt: (tool) => {\n receiptSeq += 1\n const receipt = `${tool}#${receiptSeq}`\n openReceipts.set(receipt, { tool, startedAt: Date.now() })\n return receipt\n },\n settleToolReceipt: async (receipt, outcome) => {\n const open = openReceipts.get(receipt)\n if (open === undefined) return\n openReceipts.delete(receipt)\n await bus.publish({\n type: 'tool-outcome',\n outcome: detachedFrozen<ToolOutcomeEvent>({\n receipt,\n tool: open.tool,\n ...(outcome.ok\n ? { ok: true, value: outcome.value }\n : {\n ok: false,\n error:\n outcome.error instanceof Error ? outcome.error.message : String(outcome.error),\n }),\n elapsedMs: Date.now() - open.startedAt,\n }),\n })\n },\n reentryState: () =>\n managerReentryState({\n opts,\n ledger,\n deliveries,\n priorJournal,\n bus,\n journal,\n openWork,\n driverAttempt,\n lastRejection,\n }),\n blocked: () => [...blockedReports],\n checkReads: () => checkReads,\n recordCheckRead,\n ...(peerMail ? { peerMail } : {}),\n }\n}\n\nimport type { LeadMessage } from './coordination-events'\n\nfunction leadMessageOf(message: unknown): LeadMessage | undefined {\n if (message === null || typeof message !== 'object') return undefined\n const m = message as Record<string, unknown>\n const interrupt = m.interrupt === true\n const id =\n typeof m.messageId === 'string' && m.messageId.length > 0 ? { messageId: m.messageId } : {}\n if (typeof m.steer === 'string') return { ...id, kind: 'steer', text: m.steer, interrupt }\n if (typeof m.answer === 'string') {\n return {\n ...id,\n kind: 'answer',\n text: m.answer,\n ...(typeof m.questionId === 'string' ? { questionId: m.questionId } : {}),\n interrupt,\n }\n }\n return undefined\n}\n","import { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { SettledWorker } from '../../mcp/tools/coordination-contracts'\nimport type { DownMessageEvent } from '../../mcp/tools/coordination-messages'\nimport type { InboxReceipt } from './inbox'\nimport { isTerminalNodeStatus } from './node-status'\nimport type { RunCancelRequest } from './run-cancellation'\nimport {\n applyRunCancellation,\n type RunCancellation,\n readRunCancellation,\n readRunCancelRequest,\n writeRunCancellation,\n} from './run-cancellation'\nimport {\n claimWorkerSteerDelivery,\n readWorkerCancellation,\n readWorkerCancelRequests,\n readWorkerSteerAcknowledgement,\n readWorkerSteerRequests,\n type WorkerCancellation,\n type WorkerCancelRequest,\n type WorkerSteerAcknowledgement,\n type WorkerSteerRequest,\n writeWorkerCancellation,\n writeWorkerSteerAcknowledgement,\n} from './run-layout'\nimport type { Scope } from './types'\n\n/** The journal file `createFileRunContext` writes inside the run directory. The acknowledger\n * reads it as EVIDENCE for the terminated-descendants set — the nested trees of a cancelled\n * lead journal their terminal records there before the lead settles into this scope. */\nconst SPAWN_JOURNAL_FILE = 'spawn-journal.jsonl'\n\ninterface CancelAcknowledgerDeps {\n readonly dir: string\n readonly coord: {\n settled(): ReadonlyArray<SettledWorker>\n abortWorker(\n ref: string,\n reason?: string,\n ): { readonly id: string; readonly label: string } | undefined\n }\n readonly scope: Scope<unknown>\n readonly now: () => number\n /** This manager's own node id (`scope.view.root`) — the parent every owned node id hangs off. */\n readonly ownerId: string\n /** `'run'` also owns label/profile-name references (the tree root's role); `'subtree'` owns\n * exact direct-child node ids only. See `DriverAgentOptions.controlScope`. */\n readonly controlScope: 'run' | 'subtree'\n /** Abort the WHOLE run through the one cascade controller it already has. Present only on the\n * `'run'`-scoped manager, and only when the caller wired a root control; without it a\n * run-scoped cancel request is not this manager's to apply. */\n readonly abortRun?: (reason: string, request?: RunCancelRequest) => void\n}\n\n/** An operator steer handed to the run root's inbox. The root answers `receipt` once: when a model\n * turn consumes the steer, or when the root stops without reading it. */\nexport interface RootSteer {\n readonly steer: string\n readonly interrupt: boolean\n readonly messageId: string\n readonly receipt: (receipt: InboxReceipt) => void\n}\n\ninterface SteerAcknowledgerDeps {\n /** Present only on the run root; nested managers must not claim their parent's child steer. */\n readonly deliverRoot?: (message: RootSteer) => boolean\n /** Root delivery is not claimable until the current harness invocation exposes its inbox. */\n readonly deliverRootReady?: () => boolean\n readonly dir: string\n readonly coord: {\n steerWorker(\n workerId: string,\n instruction: string,\n options?: { readonly interrupt?: boolean },\n ): Promise<DownMessageEvent>\n }\n readonly now: () => number\n readonly ownerId: string\n /** Stops admission between requests when an external manager's lifetime ends. */\n readonly signal?: AbortSignal\n}\n\n/**\n * Apply externally admitted steers once through the owning manager's control path.\n *\n * The `unknown` acknowledgement lands before authorization or delivery. A crash after that write\n * can lose this steer, but a restarted manager never delivers it again. This is the same\n * at-most-once crash boundary as coordination instruction receipts: no duplicate instruction is\n * safer than replaying a mutation whose first delivery may already have succeeded.\n */\nexport function createSteerAcknowledger(deps: SteerAcknowledgerDeps): {\n pass(phase: 'turn' | 'final'): Promise<void>\n} {\n const iso = () => new Date(deps.now()).toISOString()\n // Root steers this process queued and the root has not yet answered, by operation id.\n const awaiting = new Map<string, WorkerSteerRequest>()\n const answerRoot = (request: WorkerSteerRequest, receipt: InboxReceipt): void => {\n if (!awaiting.delete(request.operationId)) return\n writeWorkerSteerAcknowledgement(deps.dir, {\n ...base(request),\n ...(receipt.status === 'consumed'\n ? {\n effect: 'delivered',\n detail: `the root consumed the steer in ${receipt.attemptId}`,\n }\n : {\n effect: 'not_live',\n detail: `the root did not consume the steer: ${receipt.reason}`,\n }),\n observedAt: iso(),\n })\n }\n\n const base = (\n request: WorkerSteerRequest,\n ): Omit<WorkerSteerAcknowledgement, 'effect' | 'observedAt' | 'detail'> => ({\n schemaVersion: 1,\n operationId: request.operationId,\n requestDigest: request.requestDigest,\n worker: request.worker,\n requestedAt: request.at,\n })\n\n return {\n async pass(phase): Promise<void> {\n for (const request of readWorkerSteerRequests(deps.dir)) {\n if (phase === 'turn' && deps.signal?.aborted) return\n const rootRequest = request.worker === deps.ownerId && deps.deliverRoot !== undefined\n if (!rootRequest && !isDirectChildNodeId(deps, request.worker)) continue\n const queued = awaiting.get(request.operationId)\n if (phase === 'final' && queued !== undefined) {\n answerRoot(queued, {\n status: 'failed',\n messageId: request.operationId,\n cause: 'closed',\n reason: 'the run ended before a root turn read it',\n })\n continue\n }\n if (readWorkerSteerAcknowledgement(deps.dir, request.operationId) !== undefined) continue\n if (phase === 'final') {\n writeWorkerSteerAcknowledgement(deps.dir, {\n ...base(request),\n effect: 'not_live',\n observedAt: iso(),\n detail: 'run ended before the steer was applied',\n })\n continue\n }\n if (rootRequest && deps.deliverRootReady !== undefined && !deps.deliverRootReady()) {\n continue\n }\n const claimed = claimWorkerSteerDelivery(deps.dir, {\n ...base(request),\n effect: 'unknown',\n observedAt: iso(),\n detail: 'delivery admitted; outcome not yet known',\n })\n if (!claimed) continue\n try {\n let outcome: Pick<DownMessageEvent, 'delivered' | 'outcome'>\n if (rootRequest) {\n awaiting.set(request.operationId, request)\n const delivered = deps.deliverRoot!({\n steer: request.message,\n interrupt: request.interrupt,\n messageId: request.operationId,\n receipt: (receipt) => answerRoot(request, receipt),\n })\n if (!delivered) awaiting.delete(request.operationId)\n outcome = { delivered, outcome: delivered ? 'delivered' : 'runtime-has-no-inbox' }\n } else {\n outcome = await deps.coord.steerWorker(request.worker, request.message, {\n interrupt: request.interrupt,\n })\n }\n // A queued root steer stays `unknown` until the root answers its receipt.\n if (rootRequest && outcome.delivered) {\n if (awaiting.has(request.operationId)) {\n writeWorkerSteerAcknowledgement(deps.dir, {\n ...base(request),\n effect: 'unknown',\n observedAt: iso(),\n detail: 'queued in the root inbox; no root turn has consumed it yet',\n })\n }\n continue\n }\n const effect: WorkerSteerAcknowledgement['effect'] = outcome.delivered\n ? 'delivered'\n : outcome.outcome === 'runtime-has-no-inbox'\n ? 'unsupported'\n : outcome.outcome === 'unknown-worker' ||\n outcome.outcome === 'already-settled' ||\n outcome.outcome === 'scope-stopped'\n ? 'not_live'\n : 'unknown'\n writeWorkerSteerAcknowledgement(deps.dir, {\n ...base(request),\n effect,\n observedAt: iso(),\n detail: rootRequest\n ? 'the root exposes no accepting inbox at delivery time'\n : steerAcknowledgementDetail(outcome),\n })\n } catch (error) {\n void error\n awaiting.delete(request.operationId)\n writeWorkerSteerAcknowledgement(deps.dir, {\n ...base(request),\n effect: 'unknown',\n observedAt: iso(),\n detail: 'delivery outcome is unknown after a runtime error',\n })\n }\n }\n },\n }\n}\n\n/**\n * The OPERATOR-facing sentence for a steer outcome, written into the durable acknowledgement file.\n *\n * Deliberately separate from `downMessageRefusalReasons`, which is the MANAGER-facing sentence: one\n * says what happened for someone reading the run afterwards, the other tells a model what to do\n * next, and merging them would make one audience read the other's copy. They must nonetheless cover\n * the SAME outcomes, so `tests/kernel/refusal-reasons.test.ts` holds both maps total over\n * `DownMessageDeliveryOutcome` — a new code cannot land in only one.\n */\nfunction steerAcknowledgementDetail(outcome: Pick<DownMessageEvent, 'outcome'>): string {\n switch (outcome.outcome) {\n case 'delivered':\n return 'the owning manager delivered the steer to the exact live worker'\n case 'runtime-has-no-inbox':\n return 'the exact worker does not expose a steer inbox'\n case 'unknown-worker':\n return 'the owning manager does not know the exact worker'\n case 'already-settled':\n return 'the exact worker settled before delivery'\n case 'scope-stopped':\n return 'the owning manager stopped before delivery'\n case 'runtime-error':\n return 'delivery outcome is unknown after a runtime error'\n }\n}\n\n/**\n * The worker-cancel ACKNOWLEDGER — the runtime-side half of `run-layout`'s `cancelWorker`\n * contract. Router managers check between turns; native managers observe throughout their invocation.\n * Every manager with a `controlDir` mounts one;\n * OWNERSHIP keeps them from colliding: a request naming a node id is owned by the manager whose\n * own id is that node's parent, and a label/profile-name reference is owned by the `'run'`-scoped\n * (root) manager only — so exactly one acknowledger can ever apply one operation.\n *\n * Two-phase, honestly reported: `cancel_requested` is written the moment a live worker's abort is\n * issued (through the per-child abort chain the scope already owns, so siblings are untouched);\n * `cancelled` is written only when that worker's settlement is DELIVERED on the settle path with\n * a terminal `down`, and then the record names every subtree node id proven terminated. A worker\n * that already settled — or that settles `done` despite the abort — records `not_live`; a\n * reference matching nothing this manager owns stays pending (`cancelWorker` reports it\n * `unknown`). No path reports success for a missing worker.\n *\n * Expiry is run end, not a clock: `finish()` (after the final post-drain pass) writes `not_live`\n * for every owned request never applied and `unknown` for an issued abort whose settle the run\n * ended too soon to observe. A pending request can therefore never outlive its run and abort a\n * future spawn that happens to reuse a label.\n *\n * Idempotency is a lookup, in-process and across processes: an operation with a durable\n * acknowledgement is returned as-is and never re-applied.\n */\nexport function createCancelAcknowledger(deps: CancelAcknowledgerDeps): {\n /** `'turn'` = a live manager control pass (the only phase that APPLIES a request); `'final'` = the\n * post-drain pass, which only reconciles records the run already wrote. */\n pass(phase: 'turn' | 'final'): void\n finish(): void\n} {\n const tracked = new Map<string, WorkerCancellation>()\n // The run-scoped operation this manager has already applied, so its abort is issued once.\n let runTracked: RunCancellation | undefined\n // The abort-issue instant per operation (the `observedAt` written on its `cancel_requested`\n // record) — the terminated-set window survives the record moving to `cancelled`.\n const abortIssuedAt = new Map<string, string>()\n const iso = () => new Date(deps.now()).toISOString()\n\n const write = (record: WorkerCancellation): void => {\n writeWorkerCancellation(deps.dir, record)\n tracked.set(record.operationId, record)\n }\n\n /** Whether this acknowledger owns `ref`. A node id deeper in this subtree belongs to the nested\n * manager that parents it; anything that is not a node id under this manager is a\n * label/profile-name reference, owned by the `'run'`-scoped manager alone. */\n const owned = (ref: string): boolean => {\n if (isDirectChildNodeId(deps, ref)) return true\n if (deps.controlScope !== 'run') return false\n return !ref.startsWith(`${deps.ownerId}:`) && ref !== deps.ownerId\n }\n\n // Terminal knowledge of one node, visible only once its settlement was DELIVERED (the ledger\n // row, or the view status `finalizeSettlement` stamps on the pull). 'down' = it died.\n const deliveredTerminal = (id: string): 'down' | 'done' | undefined => {\n const row = deps.coord.settled().find((w) => w.id === id)\n if (row !== undefined) return row.status\n const node = deps.scope.view.nodes.find((n) => n.id === id)\n if (node === undefined) return undefined\n if (node.status === 'done') return 'done'\n if (node.status === 'failed' || node.status === 'cancelled') return 'down'\n return undefined\n }\n\n const apply = (request: WorkerCancelRequest): void => {\n const aborted = deps.coord.abortWorker(request.worker, request.reason ?? 'cancel requested')\n const base = {\n operationId: request.operationId,\n worker: request.worker,\n requestedAt: request.at,\n observedAt: iso(),\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n }\n if (aborted !== undefined) {\n abortIssuedAt.set(request.operationId, base.observedAt)\n write({\n ...base,\n effect: 'cancel_requested',\n workerId: aborted.id,\n detail: `abort issued to live worker '${aborted.label}' (${aborted.id}); termination not yet proven`,\n terminated: [],\n })\n return\n }\n // Not live. A reference that matches a node whose settlement was already delivered is\n // answered `not_live`; a reference matching nothing stays pending — never a success either\n // way, and a worker that appears later can still be cancelled by a later pass.\n const settledNode = deps.scope.view.nodes.find(\n (n) =>\n (n.id === request.worker || n.label === request.worker) && isTerminalNodeStatus(n.status),\n )\n const goneId = settledNode?.id ?? deps.coord.settled().find((w) => w.id === request.worker)?.id\n if (goneId !== undefined) {\n write({\n ...base,\n effect: 'not_live',\n workerId: goneId,\n detail: `worker '${goneId}' had already settled before this operation was applied`,\n terminated: [],\n })\n }\n }\n\n /** The proven-terminated set for one record: the worker plus every subtree id with a terminal\n * journal record at/after the abort was issued. Union with what the record already names, so\n * the set only ever grows (a late teardown journal adds; nothing removes). */\n const provenTerminated = (record: WorkerCancellation, workerId: string): string[] => {\n const since = abortIssuedAt.get(record.operationId) ?? record.observedAt\n const ids = new Set<string>([\n ...record.terminated,\n workerId,\n ...terminatedDescendants(deps.dir, workerId, since),\n ])\n return [...ids].sort()\n }\n\n const reconcile = (record: WorkerCancellation): void => {\n const workerId = record.workerId\n if (workerId === undefined) return\n const terminal = deliveredTerminal(workerId)\n if (terminal === undefined) return\n if (terminal === 'down') {\n write({\n ...record,\n effect: 'cancelled',\n observedAt: iso(),\n terminated: provenTerminated(record, workerId),\n detail: `worker '${workerId}' reached a terminal down state on the settle path`,\n })\n return\n }\n // The worker finished `done` despite the abort request — its result stands, so this\n // operation terminated nothing and must not read as a successful cancellation.\n write({\n ...record,\n effect: 'not_live',\n observedAt: iso(),\n terminated: [],\n detail: `worker '${workerId}' settled done despite the abort request; nothing was terminated`,\n })\n }\n\n /** Re-scan a `cancelled` record while the manager still turns: a descendant whose teardown\n * journals after the lead's settle joins the set on a later pass instead of being lost. Only\n * a grown set is re-written; the window needs the in-process abort instant, so a record a\n * PRIOR process closed stays as that process proved it. */\n const regrow = (record: WorkerCancellation): void => {\n const workerId = record.workerId\n if (workerId === undefined || !abortIssuedAt.has(record.operationId)) return\n const terminated = provenTerminated(record, workerId)\n if (terminated.length > record.terminated.length) {\n write({ ...record, observedAt: iso(), terminated })\n }\n }\n\n /**\n * The RUN-scoped request: seen once, `cancel_requested` written the moment the run's cascading\n * abort is issued through the one controller the run already has. The `supervise()` settle path\n * records what the run then actually did — this manager cannot observe its own tree's terminal\n * state from inside `act`.\n *\n * Applied only at a TURN boundary, never on the final post-drain pass: by then the driver has\n * finished and drained, so a root abort could only void work that is already delivered. A\n * request that arrives that late expires in `finish()` instead — it terminated nothing.\n */\n const passRun = (): void => {\n if (deps.controlScope !== 'run' || deps.abortRun === undefined) return\n if (runTracked !== undefined) return\n runTracked = applyRunCancellation(deps.dir, deps.abortRun, iso)\n }\n\n const pass = (phase: 'turn' | 'final'): void => {\n if (phase === 'turn') passRun()\n for (const request of readWorkerCancelRequests(deps.dir)) {\n if (!owned(request.worker)) continue\n let record = tracked.get(request.operationId)\n if (record === undefined) {\n // Cross-process idempotency: an acknowledgement a prior process wrote wins over\n // re-applying the operation.\n record = readWorkerCancellation(deps.dir, request.operationId)\n if (record !== undefined) tracked.set(request.operationId, record)\n }\n if (record === undefined) {\n if (phase === 'turn') apply(request)\n continue\n }\n if (record.effect === 'cancel_requested') reconcile(record)\n else if (record.effect === 'cancelled') regrow(record)\n }\n }\n\n return {\n pass,\n finish(): void {\n const runRequest =\n deps.controlScope === 'run' && deps.abortRun !== undefined\n ? readRunCancelRequest(deps.dir)\n : undefined\n if (\n runRequest !== undefined &&\n readRunCancellation(deps.dir, runRequest.operationId) === undefined\n ) {\n // The request landed after the last turn boundary. The run is over, so it terminated\n // nothing — recording it here keeps a reader from seeing an operation that never resolves.\n writeRunCancellation(deps.dir, {\n operationId: runRequest.operationId,\n effect: 'not_live',\n requestedAt: runRequest.at,\n observedAt: iso(),\n ...(runRequest.reason === undefined ? {} : { reason: runRequest.reason }),\n ...(runRequest.operator === undefined ? {} : { operator: runRequest.operator }),\n detail: 'run ended before the request was applied',\n })\n }\n for (const request of readWorkerCancelRequests(deps.dir)) {\n if (!owned(request.worker)) continue\n const record =\n tracked.get(request.operationId) ?? readWorkerCancellation(deps.dir, request.operationId)\n if (record === undefined) {\n // Never applied and the run is over: the request expires as `not_live` so it cannot\n // linger and abort a future spawn that matches by label — and never reads as success.\n write({\n operationId: request.operationId,\n worker: request.worker,\n effect: 'not_live',\n requestedAt: request.at,\n observedAt: iso(),\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n detail: 'run ended before the request was applied',\n terminated: [],\n })\n continue\n }\n if (record.effect === 'cancel_requested') {\n // The abort went out but act is returning before the settle path could prove the\n // termination. `unknown` is the honest terminal: not in progress, never a success.\n write({\n ...record,\n effect: 'unknown',\n observedAt: iso(),\n detail: 'abort issued; run ended before termination was observed',\n })\n }\n }\n },\n }\n}\n\n/**\n * Subtree node ids with a terminal `down`/`cancelled` journal record at or after `sinceIso` —\n * the abort-issue instant (the acknowledger's own `observedAt` on the `cancel_requested` record,\n * runtime clock), never the client's `requestedAt` — read from the durable spawn journal beside\n * the run layout. The set is proven at acknowledgement time and is approximate about post-abort\n * causation: a descendant that died of its OWN cause after the abort was issued is\n * indistinguishable from the cascade and may be included; one whose teardown journals late joins\n * on a later acknowledger pass; a teardown journal still absent when the run ends is absent from\n * the set. Ids are hierarchical (`parent:sN`), so `${nodeId}:` prefixes exactly the subtree.\n * Tolerant of a missing or partially-written journal: evidence that cannot be read names fewer\n * nodes, never wrong ones.\n */\nfunction terminatedDescendants(dir: string, nodeId: string, sinceIso: string): string[] {\n let raw: string\n try {\n raw = readFileSync(join(dir, SPAWN_JOURNAL_FILE), 'utf8')\n } catch {\n return []\n }\n const prefix = `${nodeId}:`\n const ids = new Set<string>()\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n let parsed: { kind?: unknown; event?: Record<string, unknown> }\n try {\n parsed = JSON.parse(trimmed) as { kind?: unknown; event?: Record<string, unknown> }\n } catch {\n continue\n }\n if (parsed.kind !== 'event' || parsed.event === undefined) continue\n const event = parsed.event\n const died = (event.kind === 'settled' && event.status === 'down') || event.kind === 'cancelled'\n if (!died) continue\n if (typeof event.id !== 'string' || !event.id.startsWith(prefix)) continue\n if (typeof event.at !== 'string' || event.at < sinceIso) continue\n ids.add(event.id)\n }\n return [...ids].sort()\n}\n\n/** A direct child has exactly one generated spawn segment below its owner. */\nfunction isDirectChildNodeId(owner: { readonly ownerId: string }, ref: string): boolean {\n return ref.startsWith(`${owner.ownerId}:s`) && /^s\\d+$/.test(ref.slice(owner.ownerId.length + 1))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAa,gCAAgC,IAAI,OAAO;;AAwBxD,SAAgB,oBAAoB,MAAmC;CACrE,OAAO;EACL,UAAU,kBAAkB;EAC5B,OAAO,cAAc,cAAc,MAAM,SAAS;CACpD;AACF;;;;;;;;;;AAWA,SAAgB,kBAAkB,aAGV;CACtB,OAAO;EACL,UAAU,eAAe,YAAY;EACrC,MAAM,KAAK,WAAW;GACpB,IAAI,UAAU,WAAW,GAAG,OAAO;IAAE,IAAI;IAAO,QAAQ;GAAgB;GACxE,IAAI,WAAW,SAAS,GACtB,OAAO;IACL,IAA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