@tangle-network/agent-runtime 0.344.0 → 0.349.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 (82) hide show
  1. package/dist/{activation-C5rFWXGj.js → activation-tNGW73Y9.js} +4 -4
  2. package/dist/{activation-C5rFWXGj.js.map → activation-tNGW73Y9.js.map} +1 -1
  3. package/dist/{activation-CGtGr0qu.d.ts → activation-wBipBkCf.d.ts} +2 -2
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +3 -3
  6. package/dist/{bundle-DKQtOO9d.js → bundle-1xaJEgjq.js} +2 -2
  7. package/dist/{bundle-DKQtOO9d.js.map → bundle-1xaJEgjq.js.map} +1 -1
  8. package/dist/candidate-execution/index.js +4 -4
  9. package/dist/{coordination-manager-T98ZbsEt.js → coordination-manager-B2Z_MmL9.js} +22 -19
  10. package/dist/coordination-manager-B2Z_MmL9.js.map +1 -0
  11. package/dist/{delegate-CjdtLf1v.js → delegate-Dr-63jFl.js} +2 -2
  12. package/dist/{delegate-CjdtLf1v.js.map → delegate-Dr-63jFl.js.map} +1 -1
  13. package/dist/durable.d.ts +7 -2
  14. package/dist/durable.js +129 -117
  15. package/dist/durable.js.map +1 -1
  16. package/dist/{graph-kgzTaNMA.js → graph-DPejYB3C.js} +6 -5
  17. package/dist/graph-DPejYB3C.js.map +1 -0
  18. package/dist/{improve-DevAd83a.js → improve-DwSahPi1.js} +7 -7
  19. package/dist/{improve-DevAd83a.js.map → improve-DwSahPi1.js.map} +1 -1
  20. package/dist/index.d.ts +3 -3
  21. package/dist/index.js +9 -9
  22. package/dist/intelligence.d.ts +2 -2
  23. package/dist/intelligence.js +6 -6
  24. package/dist/kernel.d.ts +2 -2
  25. package/dist/kernel.js +11 -11
  26. package/dist/{loop-runner-DsVqEv8O.d.ts → loop-runner-C6pGq-2l.d.ts} +2 -2
  27. package/dist/{loop-runner-BM509Zmp.js → loop-runner-CP6MfO1b.js} +2 -2
  28. package/dist/{loop-runner-BM509Zmp.js.map → loop-runner-CP6MfO1b.js.map} +1 -1
  29. package/dist/loop-runner-bin.d.ts +1 -1
  30. package/dist/loop-runner-bin.js +1 -1
  31. package/dist/mcp/bin.js +3 -3
  32. package/dist/mcp/index.d.ts +1 -1
  33. package/dist/mcp/index.js +6 -6
  34. package/dist/mcp/index.js.map +1 -1
  35. package/dist/model-policy-CyCUwHed.js.map +1 -1
  36. package/dist/{prepare-TEEHSJwq.js → prepare-B9wWffjO.js} +3 -3
  37. package/dist/{prepare-TEEHSJwq.js.map → prepare-B9wWffjO.js.map} +1 -1
  38. package/dist/{profile-6OLpbjvV.js → profile-JLJd2wFG.js} +2 -2
  39. package/dist/{profile-6OLpbjvV.js.map → profile-JLJd2wFG.js.map} +1 -1
  40. package/dist/profiles.d.ts +1 -1
  41. package/dist/{provision-supervisor-CysVhSqV.js → provision-supervisor-C4v2vqDo.js} +6 -6
  42. package/dist/{provision-supervisor-CysVhSqV.js.map → provision-supervisor-C4v2vqDo.js.map} +1 -1
  43. package/dist/{durable-file-DLcrzrjL.js → record-events-D93DkpAx.js} +100 -3
  44. package/dist/record-events-D93DkpAx.js.map +1 -0
  45. package/dist/{run-cancellation-CEDiqfhC.js → run-cancellation-CzFhQGMa.js} +11 -9
  46. package/dist/run-cancellation-CzFhQGMa.js.map +1 -0
  47. package/dist/{runtime-B_93oWEv.js → runtime-CsvGCQpl.js} +448 -55
  48. package/dist/runtime-CsvGCQpl.js.map +1 -0
  49. package/dist/{sandbox-profile-compat-_fEtHPCj.js → sandbox-profile-compat-DtuJWFrM.js} +2 -2
  50. package/dist/sandbox-profile-compat-DtuJWFrM.js.map +1 -0
  51. package/dist/{search-executor-t05_9Wwk.js → search-executor-CCb82Umc.js} +5 -5
  52. package/dist/search-executor-CCb82Umc.js.map +1 -0
  53. package/dist/{server-DjrVWzH2.js → server-CKPwZU-I.js} +4 -4
  54. package/dist/{server-DjrVWzH2.js.map → server-CKPwZU-I.js.map} +1 -1
  55. package/dist/{structural-rollout-CpJknIaL.js → structural-rollout-DylC_fwU.js} +3 -3
  56. package/dist/{structural-rollout-CpJknIaL.js.map → structural-rollout-DylC_fwU.js.map} +1 -1
  57. package/dist/{supervise-BuVVC7Bl.js → supervise-BGfm2GlY.js} +293 -87
  58. package/dist/supervise-BGfm2GlY.js.map +1 -0
  59. package/dist/{supervisor-D3M9ab1v.js → supervisor-wS9Ehz_x.js} +454 -187
  60. package/dist/supervisor-wS9Ehz_x.js.map +1 -0
  61. package/dist/testing.d.ts +2 -2
  62. package/dist/testing.js +13 -13
  63. package/dist/{top-snapshot-BGYI6G6K.js → top-snapshot-CflmaDgk.js} +6 -4
  64. package/dist/top-snapshot-CflmaDgk.js.map +1 -0
  65. package/dist/tui/bin.js +2 -2
  66. package/dist/tui/index.d.ts +1 -1
  67. package/dist/tui/index.js +2 -2
  68. package/dist/{types-DztCeYd6.d.ts → types-C8BGOCBn.d.ts} +286 -34
  69. package/package.json +11 -11
  70. package/skills/agent-graphs/SKILL.md +40 -2
  71. package/skills/graph-designer/SKILL.md +6 -0
  72. package/skills/profile-authoring/SKILL.md +1 -1
  73. package/dist/coordination-manager-T98ZbsEt.js.map +0 -1
  74. package/dist/durable-file-DLcrzrjL.js.map +0 -1
  75. package/dist/graph-kgzTaNMA.js.map +0 -1
  76. package/dist/run-cancellation-CEDiqfhC.js.map +0 -1
  77. package/dist/runtime-B_93oWEv.js.map +0 -1
  78. package/dist/sandbox-profile-compat-_fEtHPCj.js.map +0 -1
  79. package/dist/search-executor-t05_9Wwk.js.map +0 -1
  80. package/dist/supervise-BuVVC7Bl.js.map +0 -1
  81. package/dist/supervisor-D3M9ab1v.js.map +0 -1
  82. package/dist/top-snapshot-BGYI6G6K.js.map +0 -1
@@ -1,11 +1,11 @@
1
- import { c as __exportAll, n as assertNoSymlinkDescendant, o as writeAtomicDurableFile, s as sha256 } from "./durable-file-DLcrzrjL.js";
2
- import { $ as beginScopeRetainedOwnerDrive, $n as upstreamUnavailableSignal, A as coordinationProfileToolPrefix, An as createInbox, Ar as bridgeStopSignalKey, B as meterRuntimeOwnedProviderAttempt, Bi as assertValidBudget, Br as fullProfileMaterialization, Bt as toolResultText, Ci as cappedDoublingMs, Ct as captureReusableExecutorConfig, D as restoreScopeOwnerAcceptedExecution, Dr as runAbortable, E as recordScopeOwnerMaterialization, Ei as unavailableResumeAt, Er as linkAbort, F as deriveNodeExecutionIdentity, G as scopeRetainedOwnerResourceReader, Gn as isTerminalNodeStatus, H as recordScopeOwnerDriverAttempt, Hn as createActivityLog, Hr as promptControlProfileMaterialization, Ht as routerBrain, Ii as meterUsageEvent, Ir as assertProfileMaterialization, It as codeModeArguments, J as abandonScopeRetainedOwnerInvocation, Jn as abandonablePending, Jr as worktreeCliProfileMaterialization, Kn as DriverAttemptsExhaustedError, Kr as sandboxProfileMaterialization, Li as newUsageTotals, Ln as isPeerMailEnvelope, Lt as codeModeModelOutput, M as runtimeGraphMetadataKey, Mi as contentAddress, Ni as executorFailure, O as scopeOwnerExecutorNodeContext, P as assertRecursiveReservationPolicy, Pi as errMessage, Pn as PEER_MAIL_WIRE_KEY, Q as scopeRetainedOwnerResult, Qn as undispatchedCredentialExit, Rr as controlProfileMaterialization, Rt as createCodeModeTools, Si as retainedExecutorSeamKey, St as bindReusableExecutorExecutionId, T as noteScopeOwnerPlannedExecution, Ti as unavailablePauseMs, Tr as RunCancellationReason, Tt as snapshotExecutorConfig, U as recordScopeOwnerPause, Ur as promptModelProfileMaterialization, V as recordScopeOwnerBarrenPause, Vr as profileMaterializationAxes$1, Vt as createRouterTranscript, W as prepareScopeRetainedOwnerSeatSwitch, Wn as isLiveNodeStatus, Wr as renderUnsupported, Wt as resolveAgentEnvironmentProvider, X as prepareScopeRetainedOwnerTask, Xn as classifyDriverFailure, Xr as attestRuntimeOwnedScopeOwner, Y as consumeScopeRetainedOwnerResult, Yn as causedByPartialFailure, Z as scopeRetainedOwnerPriorSpend, Zn as summarizeDriverAttempts, Zr as authoredAgentIdentity, _r as bridgeModelRouteRefusal, _t as readCommittedJsonLines, a as runFinalizer, ai as recordRuntimeOwnedDriveHarnessProviderEvidence, ar as CheckUnavailableError, at as bindScopeRetainedOwnerProvider, bi as RetainedExecutionPendingError, bn as generateSpanId, c as driverChild, ci as runtimeOwnedExecutorMaterialization, di as runtimeOwnedScopeOwnerRuntime, dn as WORKER_TRACE_PROPAGATION, dr as bestComposite, ei as inheritRuntimeOwnedExecutorAttestation, er as SeatChain, et as scopeRetainedOwnerTurnEnded, fr as checkVerdictOf, gr as bridgeAdmissionRefusal, gt as readCommittedJsonFile, h as parseWorkerToolTraceArtifact, ht as prepareJsonlAppend, i as bestDelivered, ii as providerAttemptEvidence, in as readHarnessTranscript, it as bindScopeRetainedOwnerEnvironmentId, j as providerVisibleProfile, ji as detachedSnapshot, k as coordinationMcpAlias, kn as INBOX_RECEIPT_KEY, kr as bridgeRuntimeAttachmentsKey, l as driverExecutorFactory, li as runtimeOwnedExecutorProviderEvidence, lr as CONTINUATIONS_DIR, mt as isNoEntError, n as createSupervisor, nr as authoredSeatStages, nt as scopeRetainedOwnerRestorePoint, o as runTree, oi as runtimeOwnedDriveHarnessProviderEvidence, or as gateOnDeliverable, ot as scopeRetainedOwnerContext, pr as createContinuationKeeper, qn as HarnessTurnFailedError, qr as unsupportedProfileDimensions, rn as persistHarnessTranscript, rr as seatExecutionProfile, rt as noteScopeRetainedOwnerCoordination, s as createRootHandle, si as runtimeOwnedExecutorExecutionBinding, st as scopeRetainedOwnerJournalRoot, tr as SeatChainExhaustedError, tt as reconcileScopeRetainedOwnerEnvironment, u as isDriverSpec, ui as runtimeOwnedPendingExecutorMaterialization, ur as admitContinuationPolicy, vn as createOtelExporter, vt as upsertCommittedJsonLine, w as beginScopeOwnerAttempt, wi as jitteredMs, wn as toOtelAttributes, wt as createExecutor, xi as registerRetainedExecutorPreparation, yt as withJsonlFileLock, z as meterRuntimeOwnedAccounting, zi as spendFromUsageTotals, zr as defineProfileMaterializationContract } from "./supervisor-D3M9ab1v.js";
1
+ import { c as captureRunWriteContext, l as fenceRunWrite, m as __exportAll, p as sha256, r as assertNoSymlinkDescendant, s as writeAtomicDurableFile } from "./record-events-D93DkpAx.js";
2
+ import { $n as HarnessTurnFailedError, $r as sandboxProfileMaterialization, A as beginScopeOwnerAttempt, Ai as cappedDoublingMs, An as toOtelAttributes, At as createExecutor, B as assertRecursiveReservationPolicy, Bi as executorFailure, Bn as PEER_MAIL_WIRE_KEY, Cr as bridgeAdmissionRefusal, Ct as readCommittedJsonLines, Di as RetainedExecutionPendingError, En as generateSpanId, F as coordinationMcpAlias, Fn as INBOX_RECEIPT_KEY, G as meterRuntimeOwnedAccounting, Gr as controlProfileMaterialization, Ht as codeModeArguments, I as coordinationProfileToolPrefix, In as createInbox, Ir as bridgeRuntimeAttachmentsKey, J as recordScopeOwnerDriverAttempt, Jn as createActivityLog, Jr as profileMaterializationAxes$1, Jt as routerBrain, K as meterRuntimeOwnedProviderAttempt, Ki as spendFromUsageTotals, Kr as defineProfileMaterializationContract, Kt as toolResultText, L as providerVisibleProfile, Lr as bridgeStopSignalKey, M as recordScopeOwnerMaterialization, Mi as unavailablePauseMs, Mr as RunCancellationReason, N as restoreScopeOwnerAcceptedExecution, Ni as unavailableResumeAt, Nr as linkAbort, Oi as registerRetainedExecutorPreparation, Ot as bindReusableExecutorExecutionId, P as scopeOwnerExecutorNodeContext, Pr as runAbortable, Qn as DriverAttemptsExhaustedError, R as runtimeGraphMetadataKey, Ri as detachedSnapshot, St as readCommittedJsonFile, Tt as withJsonlFileLock, Ui as meterUsageEvent, Un as isPeerMailEnvelope, Ur as assertProfileMaterialization, Ut as codeModeModelOutput, V as deriveNodeExecutionIdentity, Vi as errMessage, Wi as newUsageTotals, Wt as createCodeModeTools, X as prepareScopeRetainedOwnerSeatSwitch, Xn as isLiveNodeStatus, Xr as promptModelProfileMaterialization, Xt as resolveAgentEnvironmentProvider, Y as recordScopeOwnerPause, Yr as promptControlProfileMaterialization, Z as scopeRetainedOwnerResourceReader, Zn as isTerminalNodeStatus, Zr as renderUnsupported, _i as runtimeOwnedPendingExecutorMaterialization, _n as WORKER_TRACE_PROPAGATION, _r as admitContinuationPolicy, a as assertRunParking, ar as upstreamUnavailableSignal, at as beginScopeRetainedOwnerDrive, br as createContinuationKeeper, bt as isNoEntError, c as sleepScopeWait, cr as authoredSeatStages, ct as scopeRetainedOwnerRestorePoint, d as runFinalizer, di as providerAttemptEvidence, dr as CheckUnavailableError, dt as bindScopeRetainedOwnerProvider, ei as unsupportedProfileDimensions, er as abandonablePending, et as abandonScopeRetainedOwnerInvocation, f as runTree, fi as recordRuntimeOwnedDriveHarnessProviderEvidence, fr as gateFactoryOnDeliverable, ft as scopeRetainedOwnerContext, g as isDriverSpec, gi as runtimeOwnedExecutorProviderEvidence, gr as CONTINUATIONS_DIR, h as driverExecutorFactory, hi as runtimeOwnedExecutorMaterialization, i as RunParkedError, ii as authoredAgentIdentity, ir as undispatchedCredentialExit, it as scopeRetainedOwnerResult, j as noteScopeOwnerPlannedExecution, ji as jitteredMs, jt as snapshotExecutorConfig, ki as retainedExecutorSeamKey, kt as captureReusableExecutorConfig, l as withRunParking, ln as persistHarnessTranscript, lr as seatExecutionProfile, lt as noteScopeRetainedOwnerCoordination, m as driverChild, mi as runtimeOwnedExecutorExecutionBinding, n as createSupervisor, nr as classifyDriverFailure, nt as prepareScopeRetainedOwnerTask, o as bindScopeParkingDrain, or as SeatChain, ot as scopeRetainedOwnerTurnEnded, p as createRootHandle, pi as runtimeOwnedDriveHarnessProviderEvidence, pt as scopeRetainedOwnerJournalRoot, q as recordScopeOwnerBarrenPause, qi as assertValidBudget, qr as fullProfileMaterialization, qt as createRouterTranscript, ri as attestRuntimeOwnedScopeOwner, rr as summarizeDriverAttempts, rt as scopeRetainedOwnerPriorSpend, si as inheritRuntimeOwnedExecutorAttestation, sr as SeatChainExhaustedError, st as reconcileScopeRetainedOwnerEnvironment, ti as worktreeCliProfileMaterialization, tr as causedByPartialFailure, tt as consumeScopeRetainedOwnerResult, u as bestDelivered, un as readHarnessTranscript, ut as bindScopeRetainedOwnerEnvironmentId, vi as runtimeOwnedScopeOwnerRuntime, vr as bestComposite, wn as createOtelExporter, wr as bridgeModelRouteRefusal, wt as upsertCommittedJsonLine, x as parseWorkerToolTraceArtifact, xt as prepareJsonlAppend, yr as checkVerdictOf, zi as contentAddress } from "./supervisor-wS9Ehz_x.js";
3
3
  import { f as RuntimeRunStateError, i as ConfigError, m as ValidationError } from "./errors-DodWX-cb.js";
4
- import { Et as isDeadlineAbortReason, K as chargedTokens, Ot as teardownExecutor, W as addSpend, X as errorMessage, _t as withBudgetResources, dt as withTimeout, et as isAsyncIterable, ft as zeroSpend, gt as resourceTelemetry, kt as teardownSurfaces, mt as addResourceSpend, nt as promptCacheTokenClasses, ot as sleep, ut as unmeteredSpend, xt as DEFAULT_SUCCESSFUL_SHUTDOWN_MS } from "./sandbox-profile-compat-_fEtHPCj.js";
4
+ import { Et as isDeadlineAbortReason, K as chargedTokens, Ot as teardownExecutor, W as addSpend, X as errorMessage, _t as withBudgetResources, dt as withTimeout, et as isAsyncIterable, ft as zeroSpend, gt as resourceTelemetry, kt as teardownSurfaces, mt as addResourceSpend, nt as promptCacheTokenClasses, ot as sleep, ut as unmeteredSpend, xt as DEFAULT_SUCCESSFUL_SHUTDOWN_MS } from "./sandbox-profile-compat-DtuJWFrM.js";
5
5
  import { _ as agentHarness, a as concreteProfileModel, c as profileModelExecutionSettings, l as profileProviderModel, n as assertModelAllowed, o as enforceTokenLimits, r as assertProfileModelsAllowed, s as profileBridgeWireModel, t as assertExecutableAgentProfile, v as harnessRunsAgent } from "./model-policy-CyCUwHed.js";
6
6
  import { t as composeRuntimeHooks } from "./runtime-hooks-tXpAarhW.js";
7
- import { c as budgetOverspendText, d as safeJsonText, f as createFileRunContext, l as normalizeAnalyzeOnSettle, m as withRunContext, n as createCoordinationToolsForManager, o as createCancelAcknowledger, p as createInMemoryRunContext, s as createSteerAcknowledger, t as createCoordinationTools, u as coordinationVerbNames } from "./coordination-manager-T98ZbsEt.js";
8
- import { c as writeRunCancellation, i as readRunCancellation, r as readRunCancelRequest, s as watchRunCancellation, t as applyRunCancellation } from "./run-cancellation-CEDiqfhC.js";
7
+ import { c as budgetOverspendText, d as safeJsonText, f as createFileRunContext, l as normalizeAnalyzeOnSettle, m as withRunContext, n as createCoordinationToolsForManager, o as createCancelAcknowledger, p as createInMemoryRunContext, s as createSteerAcknowledger, t as createCoordinationTools, u as coordinationVerbNames } from "./coordination-manager-B2Z_MmL9.js";
8
+ import { c as writeRunCancellation, i as readRunCancellation, r as readRunCancelRequest, s as watchRunCancellation, t as applyRunCancellation } from "./run-cancellation-CzFhQGMa.js";
9
9
  import { n as createStdioToolServer, t as PROTOCOL_VERSION } from "./tool-server-XV4aJwoQ.js";
10
10
  import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, canonicalCandidateJson, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
11
11
  import { toolSpansToTraceAnalysisStore } from "@tangle-network/agent-eval";
@@ -169,6 +169,7 @@ const superviseOptionKeySet = /* @__PURE__ */ new Set([
169
169
  "rootHandle",
170
170
  "router",
171
171
  "runDir",
172
+ "parking",
172
173
  "resume",
173
174
  "segment",
174
175
  "runContext",
@@ -755,7 +756,7 @@ function truncate(value) {
755
756
  /**
756
757
  * The root manager's own provider stream, retained where Runtime owns it.
757
758
  *
758
- * Measured motive (agent-runtime#1233, 2026-09-15): a CHILD's full event stream — reasoning, text,
759
+ * Measured motive (agent-runtime#1233): a CHILD's full event stream — reasoning, text,
759
760
  * and tool parts, 28k to 76k reasoning characters per child — is retained in the blob its
760
761
  * `settled` record names as `outRef`. The ROOT's stream reached nobody: `driveHarnessFromBackend`
761
762
  * drained the root executor for accounting and discarded every `progress` event, and on a
@@ -772,7 +773,7 @@ function truncate(value) {
772
773
  *
773
774
  * Durability boundary: each line is written synchronously to an `O_APPEND` descriptor before the
774
775
  * next event is drained, and the file is fsynced at every drive-attempt boundary and at close, not
775
- * per line. Measured 2026-09-15 on this host's APFS: an fsync per line cost 7.1 ms per event over
776
+ * per line. An fsync per line cost 7.1 ms per event over
776
777
  * 1,000 events and 8.1 ms over 5,000 (~80 s for a root emitting ten thousand text deltas, all of
777
778
  * it serialized inside the drain loop that also meters the budget); an async `FileHandle.write`
778
779
  * still cost 0.9 to 1.1 ms per line in the thread pool the children's journal writes share; a
@@ -790,6 +791,7 @@ const ROOT_STREAM_FILE = "root-stream.jsonl";
790
791
  /** Create the writer for `<runDir>/root-stream.jsonl`. Nothing touches disk until the first
791
792
  * `beginAttempt`, so a run whose root never drives leaves no file and no receipt. */
792
793
  function createRootStreamSink(runDir, now) {
794
+ const withClaim = captureRunWriteContext();
793
795
  const dir = resolve(runDir);
794
796
  const path = resolve(dir, ROOT_STREAM_FILE);
795
797
  let fd;
@@ -803,63 +805,79 @@ function createRootStreamSink(runDir, now) {
803
805
  const needsSeparator = await prepareJsonlAppend(path);
804
806
  seq = 0;
805
807
  for await (const _record of readCommittedJsonLines(path, { allowMissing: true })) seq += 1;
806
- fd = openSync(path, constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | (typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0), 384);
807
- if (needsSeparator) writeLine(fd, "");
808
+ fd = fenceRunWrite(() => {
809
+ const writer = openSync(path, constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | (typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0), 384);
810
+ try {
811
+ if (needsSeparator) writeLine(writer, "");
812
+ return writer;
813
+ } catch (error) {
814
+ closeSync(writer);
815
+ throw error;
816
+ }
817
+ });
808
818
  };
809
819
  return {
810
820
  async beginAttempt() {
811
- if (closed) throw new Error("root stream: beginAttempt after close");
812
- attempt += 1;
813
- if (fd !== void 0) fsyncSync(fd);
814
- await openOnce();
821
+ return withClaim(async () => {
822
+ if (closed) throw new Error("root stream: beginAttempt after close");
823
+ attempt += 1;
824
+ const writer = fd;
825
+ if (writer !== void 0) fenceRunWrite(() => fsyncSync(writer));
826
+ await openOnce();
827
+ });
815
828
  },
816
829
  append(event) {
817
- if (closed) throw new Error("root stream: append after close");
818
- if (fd === void 0) throw new Error("root stream: append before beginAttempt");
819
- const at = new Date(now()).toISOString();
820
- const record = {
821
- seq: seq + 1,
822
- at,
823
- attempt,
824
- event
825
- };
826
- let line;
827
- try {
828
- line = JSON.stringify(record);
829
- } catch (error) {
830
- line = JSON.stringify({
830
+ return withClaim(() => fenceRunWrite(() => {
831
+ if (closed) throw new Error("root stream: append after close");
832
+ if (fd === void 0) throw new Error("root stream: append before beginAttempt");
833
+ const at = new Date(now()).toISOString();
834
+ const record = {
835
+ seq: seq + 1,
836
+ at,
837
+ attempt,
838
+ event
839
+ };
840
+ let line;
841
+ try {
842
+ line = JSON.stringify(record);
843
+ } catch (error) {
844
+ line = JSON.stringify({
845
+ seq: seq + 1,
846
+ at,
847
+ attempt,
848
+ dropped: {
849
+ kind: event.kind,
850
+ reason: errorMessage(error)
851
+ }
852
+ });
853
+ }
854
+ if (line === void 0) line = JSON.stringify({
831
855
  seq: seq + 1,
832
856
  at,
833
857
  attempt,
834
858
  dropped: {
835
859
  kind: event.kind,
836
- reason: errorMessage(error)
860
+ reason: "event serialized to nothing"
837
861
  }
838
862
  });
839
- }
840
- if (line === void 0) line = JSON.stringify({
841
- seq: seq + 1,
842
- at,
843
- attempt,
844
- dropped: {
845
- kind: event.kind,
846
- reason: "event serialized to nothing"
847
- }
848
- });
849
- writeLine(fd, line);
850
- seq += 1;
863
+ writeLine(fd, line);
864
+ seq += 1;
865
+ }));
851
866
  },
852
867
  async close() {
853
- if (closed) throw new Error("root stream: closed twice");
854
- closed = true;
855
- if (fd === void 0) return void 0;
856
- try {
857
- fsyncSync(fd);
858
- } finally {
859
- closeSync(fd);
860
- fd = void 0;
861
- }
862
- return readRootStreamReceipt(dir);
868
+ return withClaim(async () => {
869
+ if (closed) throw new Error("root stream: closed twice");
870
+ closed = true;
871
+ const writer = fd;
872
+ if (writer === void 0) return void 0;
873
+ try {
874
+ fenceRunWrite(() => fsyncSync(writer));
875
+ } finally {
876
+ closeSync(writer);
877
+ fd = void 0;
878
+ }
879
+ return readRootStreamReceipt(dir);
880
+ });
863
881
  }
864
882
  };
865
883
  }
@@ -3689,12 +3707,12 @@ function driverInitialMessages(opts, system, task, scope) {
3689
3707
  * that assigned the task. The run's own check judges the run's result, never a child's narrower
3690
3708
  * assignment. Held to the run's check, a child's submission is refused for as long as the run's
3691
3709
  * is: every node of test-canary-graph-tools-20261017a, and the `delay` child of
3692
- * test-retained-root-wake-20261018b (2026-10-18: "Expected: the canary runs to its deadline"), was
3710
+ * test-retained-root-wake-20261018b ("Expected: the canary runs to its deadline"), was
3693
3711
  * refused at submit_result, never settled, and its manager was never woken with it.
3694
3712
  *
3695
3713
  * It is the one check a harness manager may hold without a continuation policy: it accepts every
3696
3714
  * submission, so there is nothing to send the child back for. test-canary-graph-tools-20261018c and
3697
- * -d (2026-10-18) had every harness-run graph lead refused at spawn until this exemption.
3715
+ * -d had every harness-run graph lead refused at spawn until this exemption.
3698
3716
  */
3699
3717
  const ownSubmissionDeliverable = Object.freeze({
3700
3718
  describe: "the result your task asks for; it goes to the manager that assigned the task, and the run's own check judges that manager's result",
@@ -4895,7 +4913,19 @@ function observeWorkerControls(options) {
4895
4913
  }
4896
4914
  if (failure) throw failure.error;
4897
4915
  };
4898
- return { close: () => closing ??= finish() };
4916
+ return {
4917
+ async pass() {
4918
+ if (!active) return;
4919
+ try {
4920
+ cancellations?.pass("boundary");
4921
+ await steers?.pass("boundary");
4922
+ } catch (error) {
4923
+ fail(error);
4924
+ }
4925
+ if (failure) throw failure.error;
4926
+ },
4927
+ close: () => closing ??= finish()
4928
+ };
4899
4929
  }
4900
4930
  //#endregion
4901
4931
  //#region src/runtime/supervise/supervisor-manager-session.ts
@@ -5101,7 +5131,7 @@ const SAME_PARTIAL_FAILURE_LIMIT = 2;
5101
5131
  /**
5102
5132
  * Why an aborted run stopped: `deadline` when the root's or the node's own deadline cut it, else
5103
5133
  * `aborted`. Read before any failure classification, which calls every failure after an abort
5104
- * terminal: measured 2026-10-21, 61 of 62 runs that ended `terminal-error` were a deadline that cut
5134
+ * terminal: 61 of 62 runs that ended `terminal-error` were a deadline that cut
5105
5135
  * a turn.
5106
5136
  */
5107
5137
  function abortStop(signal) {
@@ -5642,7 +5672,7 @@ var DriverRetryLoop = class {
5642
5672
  *
5643
5673
  * WHAT COUNTS AS PROGRESS was got wrong first. Reading metered spend, settled children and an
5644
5674
  * accepted submission measured the filesystem and the meter, never the goal: across 1,422 settled
5645
- * discovery-lab runs (2026-09-01) it retried the runs that produced NOTHING 629 of 827 times
5675
+ * discovery-lab runs it retried the runs that produced NOTHING 629 of 827 times
5646
5676
  * (76.1%) and the runs that HAD left an artifact 21 of 399 times (5.3%). So when the caller
5647
5677
  * declares a completion check, spend and settlements alone are NOT progress while it is unmet; only
5648
5678
  * a delivery (an accepted submission, a child that passed the check, the contract turning met, or a
@@ -5660,7 +5690,7 @@ var DriverRetryLoop = class {
5660
5690
  * `barren-pause` row per pause for an operator alarm, and re-enters. A barren streak never ends the
5661
5691
  * run: the check, the deadline, the budget and cancellation do. Progress resets the streak and the
5662
5692
  * backoff. There is no count cap and no caller veto (the old prompt-owned loop logged 896 of 1,011
5663
- * rounds with no progress). Measured 2026-10-21 on magnetar-rust-20261021a: the barren bound
5693
+ * rounds with no progress). The barren bound
5664
5694
  * settled a 48-hour run `no-winner` after 14.3 hours, while its last two turns updated its pages
5665
5695
  * and waited on its own 2^20 prove.
5666
5696
  *
@@ -5683,7 +5713,7 @@ var DriverRetryLoop = class {
5683
5713
  * created and then failed its setup (Sandbox's `PartialFailureError`): it meets the same failure on
5684
5714
  * every re-entry, so a second identical attempt with no progress stops with `repeated-failure`
5685
5715
  * (`SAME_PARTIAL_FAILURE_LIMIT`). A failure that spent tokens without delivering keeps the bounds.
5686
- * Measured 2026-10-04 on Discovery run research-nqs-20261003system2: a Platform restart answered
5716
+ * A Platform restart answered
5687
5717
  * `HTTP 502 ... Platform key verification unavailable` from 03:04:34 to 03:09:41Z, and the
5688
5718
  * coordinator's twelve attempts ran out at 03:07:12Z with no token spent.
5689
5719
  *
@@ -5701,8 +5731,7 @@ var DriverRetryLoop = class {
5701
5731
  * still spent pauses again with its own row, and the steer stays queued until a turn reads it.
5702
5732
  * After the pause the per-window counters start over and the driver is re-entered: after
5703
5733
  * a failure as `driver-failure` with `pausedMs`, after an admission or continuation refusal as the
5704
- * re-entry it was about to use. Drew, 2026-10-21: "why do these runs keep failing early its
5705
- * unacceptable!" Measured 2026-10-21 over 259 runs since 10-14: 8 of the 10 stops settled runs that
5734
+ * re-entry it was about to use. Runs must not fail early: over 259 runs, 8 of the 10 stops settled runs that
5706
5735
  * nobody solved or stopped, including 17 roots whose harness never streamed.
5707
5736
  */
5708
5737
  function assertContinuationPolicy(continuation) {
@@ -5741,6 +5770,7 @@ async function runDriverWithRetry(run) {
5741
5770
  try {
5742
5771
  await run.drive(attempt, loop.reentry);
5743
5772
  } catch (error) {
5773
+ if (error instanceof RunParkedError) throw error;
5744
5774
  await loop.afterFailure(error, attempt, before, startedAt);
5745
5775
  continue;
5746
5776
  }
@@ -5811,7 +5841,7 @@ function composeReentryTask(input) {
5811
5841
  }
5812
5842
  /**
5813
5843
  * Why the driver is back, in one clause. The failure's own text stays in the attempt records and
5814
- * never reaches the driver: measured 2026-09-11, a continuation told the details of a provider
5844
+ * never reaches the driver: a continuation told the details of a provider
5815
5845
  * failure spent two of its first four children probing the infrastructure, while its peer, told
5816
5846
  * only what to continue, spent all forty-five on the research.
5817
5847
  */
@@ -6063,6 +6093,9 @@ async function driveManagerTurns(inputs) {
6063
6093
  reported: false
6064
6094
  };
6065
6095
  const { mcp } = session;
6096
+ bindScopeParkingDrain(scope, async () => {
6097
+ await mcp.drainResolved();
6098
+ }, () => !session.controls.hasOpenWork({ includeSettled: false }) && session.state.nextTurnInbox.pendingAuthority() === 0);
6066
6099
  const keeper = session.state.keeper;
6067
6100
  const reenteredWorkers = scope.resume?.reentered;
6068
6101
  const reentered = reenteredWorkers === void 0 ? void 0 : {
@@ -6073,14 +6106,26 @@ async function driveManagerTurns(inputs) {
6073
6106
  modelEvents: () => loop.modelEvents
6074
6107
  };
6075
6108
  let driverFailed = true;
6109
+ let parked = false;
6076
6110
  try {
6077
6111
  await runDriverWithRetry({
6078
6112
  ...reentered === void 0 ? {} : { reentered },
6079
- drive: (attempt, reentry) => driveManagerTurn(loop, attempt, reentry),
6113
+ drive: async (attempt, reentry) => {
6114
+ let handedOff = false;
6115
+ try {
6116
+ await driveManagerTurn(loop, attempt, reentry);
6117
+ } catch (error) {
6118
+ handedOff = error instanceof RunParkedError && error.runId === scope.view.root;
6119
+ throw error;
6120
+ } finally {
6121
+ if (!handedOff) await loop.controlPass?.();
6122
+ }
6123
+ },
6080
6124
  progress: () => readManagerProgress(loop),
6081
6125
  budget: () => scope.budget,
6082
6126
  signal: scope.signal,
6083
6127
  stopSignal: session.state.stopController.signal,
6128
+ sleep: (ms, signal) => sleepScopeWait(scope, ms, signal, "paused-root"),
6084
6129
  ...rootStopPause(config, session),
6085
6130
  resolvePending: (failure, failures) => abandonScopeRetainedOwnerInvocation(scope, failure, failures),
6086
6131
  wait: {
@@ -6098,9 +6143,14 @@ async function driveManagerTurns(inputs) {
6098
6143
  onBarrenPause: (pause) => recordScopeOwnerBarrenPause(loop.session.state.scope, pause)
6099
6144
  });
6100
6145
  driverFailed = false;
6146
+ } catch (error) {
6147
+ parked = error instanceof RunParkedError && error.runId === scope.view.root;
6148
+ throw error;
6101
6149
  } finally {
6102
- await driveHarness.closeSeatSegment?.(scope.signal.aborted ? "cancelled" : driverFailed ? "failed" : "completed");
6103
- if (!loop.reported) reportManagerLoop(loop);
6150
+ if (!parked) {
6151
+ await driveHarness.closeSeatSegment?.(scope.signal.aborted ? "cancelled" : driverFailed ? "failed" : "completed");
6152
+ if (!loop.reported) reportManagerLoop(loop);
6153
+ }
6104
6154
  }
6105
6155
  return loop.candidate;
6106
6156
  }
@@ -6474,9 +6524,11 @@ async function actExternalManager(config, task, scope) {
6474
6524
  contractDeclared,
6475
6525
  finalize,
6476
6526
  coordinationTools,
6477
- providerProfile
6527
+ providerProfile,
6528
+ controlPass: () => controlObserver?.pass() ?? Promise.resolve()
6478
6529
  }));
6479
6530
  } catch (error) {
6531
+ if (error instanceof RunParkedError && error.runId === scope.view.root) throw error;
6480
6532
  await mcp.finishAnalysis({
6481
6533
  status: "down",
6482
6534
  reason: errorMessage(error)
@@ -7111,7 +7163,7 @@ async function providerAcceptsCoordinationAttachments(backend) {
7111
7163
  * A manager waits between turns, and a wake can come much later than five minutes after its last
7112
7164
  * turn. Claude Code 2.1.289 writes its prompt cache with a five-minute lifetime unless this variable
7113
7165
  * is set; a wake after the cache expired re-writes the manager's whole context, about 140K tokens
7114
- * per turn on a Discovery root measured 2026-10-05. That root ran on a subscription and already
7166
+ * per turn on a Discovery root. That root ran on a subscription and already
7115
7167
  * wrote one-hour entries; the variable makes the hour hold for every claude-code manager, whatever
7116
7168
  * its credential. A value the caller set wins.
7117
7169
  */
@@ -7163,7 +7215,7 @@ function workerFromBackend(backend, deliverable, seams) {
7163
7215
  const boundSessionId = boundBackend.backend === "bridge" ? boundBackend.sessionId : void 0;
7164
7216
  const peerMailAttachment = peerMailRuntimeAttachment(profile, capturedBackend, spawnContext);
7165
7217
  if (spawnContext?.peerMailUrl && boundBackend.backend === "provider" && Object.hasOwn(boundBackend.defaults?.runtimeAttachments?.mcp ?? {}, "agent-runtime-peer-mail")) throw new ValidationError("workerFromBackend: provider defaults contain the reserved peer-mail attachment alias");
7166
- const baseFactory = createExecutor(spawnContext?.peerMailUrl && boundBackend.backend === "provider" ? {
7218
+ const rawFactory = createExecutor(spawnContext?.peerMailUrl && boundBackend.backend === "provider" ? {
7167
7219
  ...boundBackend,
7168
7220
  steering: boundBackend.steering ?? {},
7169
7221
  defaults: {
@@ -7180,6 +7232,7 @@ function workerFromBackend(backend, deliverable, seams) {
7180
7232
  }
7181
7233
  }
7182
7234
  } : boundBackend);
7235
+ const baseFactory = deliverable ? gateFactoryOnDeliverable(rawFactory, deliverable) : rawFactory;
7183
7236
  const executorFactory = (spec, ctx) => {
7184
7237
  if (boundSessionId !== void 0 && ctx.node?.nodeId !== void 0) bridgeSessionByWorker.set(ctx.node.nodeId, boundSessionId);
7185
7238
  const extraSeams = seams?.();
@@ -7191,11 +7244,10 @@ function workerFromBackend(backend, deliverable, seams) {
7191
7244
  ...peerMailAttachment
7192
7245
  } }
7193
7246
  };
7194
- const built = baseFactory(spec, seamsForChild === ctx.seams ? ctx : {
7247
+ return baseFactory(spec, seamsForChild === ctx.seams ? ctx : {
7195
7248
  ...ctx,
7196
7249
  seams: seamsForChild
7197
7250
  });
7198
- return deliverable ? gateOnDeliverable(built, deliverable) : built;
7199
7251
  };
7200
7252
  return {
7201
7253
  name,
@@ -7362,6 +7414,7 @@ function admitSpawn(env, seat, authoredProfile, spawnContext, recovering) {
7362
7414
  */
7363
7415
  var graph_registry_exports = /* @__PURE__ */ __exportAll({
7364
7416
  digestOfGraph: () => digestOfGraph,
7417
+ graphCorpusSummary: () => graphCorpusSummary,
7365
7418
  graphDigest: () => graphDigest,
7366
7419
  graphFromStored: () => graphFromStored,
7367
7420
  graphRegistry: () => graphRegistry,
@@ -7371,6 +7424,7 @@ var graph_registry_exports = /* @__PURE__ */ __exportAll({
7371
7424
  lookupGraph: () => lookupGraph,
7372
7425
  pickBestGraph: () => pickBestGraph,
7373
7426
  recordGraphRun: () => recordGraphRun,
7427
+ recordStoredGraphRun: () => recordStoredGraphRun,
7374
7428
  storedGraphDigests: () => storedGraphDigests,
7375
7429
  taskShapeDigest: () => taskShapeDigest
7376
7430
  });
@@ -7415,10 +7469,26 @@ function storeGraph(graph) {
7415
7469
  function assertRecord(record) {
7416
7470
  if (typeof record.graphDigest !== "string" || record.graphDigest.length === 0) throw new ValidationError("graph-registry: record.graphDigest is required");
7417
7471
  if (typeof record.taskDigest !== "string" || record.taskDigest.length === 0) throw new ValidationError("graph-registry: record.taskDigest is required");
7418
- if (record.outcome.kind !== "delivered" && record.outcome.kind !== "no-winner") throw new ValidationError("graph-registry: record.outcome.kind must be 'delivered' | 'no-winner'");
7472
+ if (!Number.isFinite(Date.parse(record.startedAt))) throw new ValidationError("graph-registry: record.startedAt must be a timestamp");
7473
+ if (![
7474
+ "delivered",
7475
+ "no-winner",
7476
+ "unknown",
7477
+ "running"
7478
+ ].includes(record.outcome.kind)) throw new ValidationError("graph-registry: invalid record.outcome.kind");
7479
+ if ((record.outcome.kind === "delivered" || record.outcome.kind === "no-winner") && (!record.finishedAt || !Number.isFinite(Date.parse(record.finishedAt)))) throw new ValidationError("graph-registry: terminal outcomes require record.finishedAt");
7480
+ if ((record.outcome.kind === "unknown" || record.outcome.kind === "running") && !record.outcome.reason) throw new ValidationError("graph-registry: incomplete outcomes require a reason");
7481
+ if (record.source && (!record.source.kind || !record.source.id)) throw new ValidationError("graph-registry: source.kind and source.id are required");
7482
+ if (record.finishedAt && (!Number.isFinite(Date.parse(record.finishedAt)) || Date.parse(record.finishedAt) < Date.parse(record.startedAt))) throw new ValidationError("graph-registry: finishedAt precedes startedAt or is invalid");
7483
+ for (const [channel, value] of Object.entries(record.cost)) if (value !== void 0 && (typeof value !== "number" || !Number.isFinite(value) || value < 0)) throw new ValidationError(`graph-registry: invalid cost.${channel}`);
7419
7484
  }
7420
7485
  function recordKey(record) {
7421
7486
  assertRecord(record);
7487
+ if (record.source) return JSON.stringify([
7488
+ "source",
7489
+ record.source.kind,
7490
+ record.source.id
7491
+ ]);
7422
7492
  return JSON.stringify([
7423
7493
  record.taskDigest,
7424
7494
  record.graphDigest,
@@ -7435,13 +7505,58 @@ function graphRegistry(root) {
7435
7505
  * Idempotent per (taskDigest, graphDigest, startedAt): a replayed append with
7436
7506
  * the same key replaces the prior row rather than duplicating it. */
7437
7507
  async function recordGraphRun(reg, graph, record) {
7508
+ return recordStoredGraphRun(reg, storeGraph(graph), record);
7509
+ }
7510
+ /** Store an executable graph or an observed external topology in the same registry.
7511
+ * Imported observations retain their source identity and never authorize replay.
7512
+ * A reader refreshing facts can preserve independently joined labels; an explicit
7513
+ * correction leaves preserveLabels unset and replaces the record. */
7514
+ async function recordStoredGraphRun(reg, stored, record, options = {}) {
7438
7515
  assertRecord(record);
7439
- const stored = storeGraph(graph);
7516
+ if (stored.observed && !record.source) throw new ValidationError("graph-registry: observed graphs require a source run identity");
7517
+ if (!stored.observed && !record.finishedAt) throw new ValidationError("graph-registry: native graph runs require a completion timestamp");
7518
+ if ((!stored.observed || record.traversals !== void 0) && (!Number.isSafeInteger(record.traversals) || record.traversals < 0)) throw new ValidationError("graph-registry: native graphs require metered traversals; observed counts must be non-negative integers");
7519
+ const { digest, ...content } = stored;
7520
+ if (graphDigest(content) !== digest) throw new ValidationError("graph-registry: stored graph content does not match its digest");
7440
7521
  if (stored.digest !== record.graphDigest) throw new ValidationError(`graph-registry: record.graphDigest ${record.graphDigest} does not match the supplied graph (${stored.digest}) — record the graph that actually ran`);
7441
7522
  await mkdir(join(reg.root, GRAPHS_DIR), { recursive: true });
7442
7523
  return withJsonlFileLock(join(reg.root, RECORDS_FILE), async (canonicalPath) => {
7443
- writeAtomicDurableFile(join(reg.root, GRAPHS_DIR, `${stored.digest}.json`), JSON.stringify(stored), { preserveMode: true });
7444
- await upsertCommittedJsonLine(canonicalPath, record, recordKey);
7524
+ let persisted = record;
7525
+ if (options.preserveLabels && record.source) {
7526
+ const prior = (await readCommittedJsonFile(canonicalPath)).find((row) => row.source?.kind === record.source.kind && row.source.id === record.source.id);
7527
+ if (prior) {
7528
+ const taskType = record.taskType ?? prior.taskType;
7529
+ const priorTerminal = prior.outcome.kind === "delivered" || prior.outcome.kind === "no-winner";
7530
+ const incomingUnassessed = record.outcome.kind === "unknown" || record.outcome.kind === "running";
7531
+ if (priorTerminal && incomingUnassessed && prior.startedAt !== record.startedAt) throw new ValidationError("graph-registry: preserving labels requires the same task start and source identity");
7532
+ const evidence = [...prior.evidence ?? [], ...record.evidence ?? []];
7533
+ persisted = {
7534
+ ...record,
7535
+ ...taskType ? { taskType } : {},
7536
+ ...record.unknowns ? { unknowns: record.unknowns.filter((reason) => !(taskType && reason === "task type not explicitly labeled")) } : {},
7537
+ ...evidence.length ? { evidence: [...new Map(evidence.map((entry) => [canonicalJson$1(entry), entry])).values()] } : {},
7538
+ ...priorTerminal && incomingUnassessed ? {
7539
+ outcome: prior.outcome,
7540
+ finishedAt: prior.finishedAt,
7541
+ cost: {
7542
+ ...record.cost,
7543
+ ...prior.cost.ms === void 0 ? {} : { ms: prior.cost.ms },
7544
+ ...prior.cost.mergeMs === void 0 ? {} : { mergeMs: prior.cost.mergeMs }
7545
+ }
7546
+ } : {}
7547
+ };
7548
+ }
7549
+ }
7550
+ assertRecord(persisted);
7551
+ const revisionPath = join(reg.root, GRAPHS_DIR, `${stored.digest}.json`);
7552
+ try {
7553
+ const { digest: existingDigest, ...existing } = JSON.parse(await readFile(revisionPath, "utf8"));
7554
+ if (existingDigest !== stored.digest || graphDigest(existing) !== stored.digest) throw new ValidationError("graph-registry: stored graph revision is immutable but its content differs");
7555
+ } catch (error) {
7556
+ if (!isNoEntError(error)) throw error;
7557
+ writeAtomicDurableFile(revisionPath, JSON.stringify(stored), { preserveMode: true });
7558
+ }
7559
+ await upsertCommittedJsonLine(canonicalPath, persisted, recordKey);
7445
7560
  return stored;
7446
7561
  });
7447
7562
  }
@@ -7449,13 +7564,87 @@ async function recordGraphRun(reg, graph, record) {
7449
7564
  async function listGraphRuns(reg) {
7450
7565
  return readCommittedJsonFile(join(reg.root, RECORDS_FILE));
7451
7566
  }
7452
- /** Records for one task shape, newest last. */
7453
- async function graphRunsFor(reg, taskDigest) {
7454
- return (await listGraphRuns(reg)).filter((row) => row.taskDigest === taskDigest);
7567
+ function observedTopology(record) {
7568
+ return record.topologyDigest ?? (record.source ? "unknown" : record.graphDigest);
7569
+ }
7570
+ /** Records for one task shape or deterministic label query, newest last. */
7571
+ async function graphRunsFor(reg, query = {}) {
7572
+ const filters = typeof query === "string" ? { taskDigest: query } : query;
7573
+ return (await listGraphRuns(reg)).filter((row) => (filters.taskDigest === void 0 || row.taskDigest === filters.taskDigest) && (filters.taskType === void 0 || (row.taskType ?? "unknown") === filters.taskType) && (filters.topologyDigest === void 0 || observedTopology(row) === filters.topologyDigest) && (filters.sourceKind === void 0 || (row.source?.kind ?? "native") === filters.sourceKind));
7574
+ }
7575
+ function medianKnown(values) {
7576
+ const known = values.filter((value) => value !== void 0 && Number.isFinite(value) && value >= 0).sort((a, b) => a - b);
7577
+ const middle = Math.floor(known.length / 2);
7578
+ return {
7579
+ count: known.length,
7580
+ median: known.length === 0 ? null : known.length % 2 ? known[middle] : (known[middle - 1] + known[middle]) / 2
7581
+ };
7582
+ }
7583
+ function observedGraphSummary(records) {
7584
+ const groups = /* @__PURE__ */ new Map();
7585
+ for (const record of records) {
7586
+ const key = JSON.stringify([record.taskType ?? "unknown", observedTopology(record)]);
7587
+ const rows = groups.get(key);
7588
+ if (rows) rows.push(record);
7589
+ else groups.set(key, [record]);
7590
+ }
7591
+ const summaries = [...groups.values()].map((runs) => {
7592
+ const assessed = runs.filter((run) => run.outcome.kind === "delivered" || run.outcome.kind === "no-winner");
7593
+ const delivered = assessed.filter((run) => run.outcome.kind === "delivered");
7594
+ const wall = medianKnown(assessed.map((run) => run.cost.ms));
7595
+ const merge = medianKnown(delivered.filter((run) => run.evidence?.some((entry) => entry.kind === "pr-merged")).map((run) => run.cost.mergeMs));
7596
+ const tokens = medianKnown(assessed.map((run) => run.cost.tokens));
7597
+ const human = medianKnown(assessed.map((run) => run.cost.humanMessages));
7598
+ return {
7599
+ taskType: runs[0].taskType ?? "unknown",
7600
+ topologyDigest: observedTopology(runs[0]),
7601
+ delivered: delivered.length,
7602
+ assessed: assessed.length,
7603
+ unknown: runs.length - assessed.length,
7604
+ deliveredRate: assessed.length ? delivered.length / assessed.length : null,
7605
+ medianWallMs: wall.median,
7606
+ wallMsCount: wall.count,
7607
+ medianMergeMs: merge.median,
7608
+ mergeMsCount: merge.count,
7609
+ medianTokens: tokens.median,
7610
+ tokenCount: tokens.count,
7611
+ medianHumanMessages: human.median,
7612
+ humanMessageCount: human.count,
7613
+ runs
7614
+ };
7615
+ });
7616
+ summaries.sort((a, b) => {
7617
+ const delivered = (b.deliveredRate ?? -1) - (a.deliveredRate ?? -1);
7618
+ if (delivered) return delivered;
7619
+ for (const key of [
7620
+ "medianWallMs",
7621
+ "medianTokens",
7622
+ "medianHumanMessages"
7623
+ ]) {
7624
+ if (a[key] === b[key]) continue;
7625
+ if (a[key] === null) return 1;
7626
+ if (b[key] === null) return -1;
7627
+ return a[key] - b[key];
7628
+ }
7629
+ return a.taskType.localeCompare(b.taskType) || a.topologyDigest.localeCompare(b.topologyDigest);
7630
+ });
7631
+ return {
7632
+ recordCount: records.length,
7633
+ groups: summaries
7634
+ };
7635
+ }
7636
+ /** Query and rank the same registry records using the opt-in observational
7637
+ * policy: delivery rate, wall time, tokens, then human messages; unknowns last. */
7638
+ async function graphCorpusSummary(reg, query = {}) {
7639
+ return observedGraphSummary(await graphRunsFor(reg, query));
7455
7640
  }
7456
7641
  /** The documented heuristic: delivered beats failed; among delivered, cheaper
7457
7642
  * (tokens, then iterations) wins; ties go to the most recent. */
7458
- function pickBestGraph(records) {
7643
+ function pickBestGraph(records, options = {}) {
7644
+ if (options.policy === "observed") {
7645
+ const group = observedGraphSummary(records).groups[0];
7646
+ return group && pickBestGraph(group.runs);
7647
+ }
7459
7648
  const delivered = records.filter((row) => row.outcome.kind === "delivered");
7460
7649
  if (delivered.length === 0) return void 0;
7461
7650
  const better = (a, b) => {
@@ -7481,7 +7670,17 @@ async function loadGraph(reg, digest) {
7481
7670
  * author a new one — with the reason stated either way (the decision is data). */
7482
7671
  async function lookupGraph(reg, taskDigest) {
7483
7672
  const records = await graphRunsFor(reg, taskDigest);
7484
- const best = pickBestGraph(records);
7673
+ const candidates = [];
7674
+ const loaded = /* @__PURE__ */ new Map();
7675
+ for (const record of records) {
7676
+ if (!loaded.has(record.graphDigest)) loaded.set(record.graphDigest, await loadGraph(reg, record.graphDigest));
7677
+ if (!loaded.get(record.graphDigest)?.observed) candidates.push(record);
7678
+ }
7679
+ if (records.length && !candidates.length) return {
7680
+ kind: "author",
7681
+ reason: "only observed topologies are available; author an executable graph"
7682
+ };
7683
+ const best = pickBestGraph(candidates);
7485
7684
  if (best) {
7486
7685
  const graph = await loadGraph(reg, best.graphDigest);
7487
7686
  if (graph) return {
@@ -7502,6 +7701,7 @@ async function lookupGraph(reg, taskDigest) {
7502
7701
  /** Rehydrate a stored graph into a runnable one. The check comes from the
7503
7702
  * CALLER's environment (oracles are environment, never stored). */
7504
7703
  function graphFromStored(stored, check) {
7704
+ if (stored.observed) throw new ValidationError("graphFromStored: observed topology cannot be replayed");
7505
7705
  return {
7506
7706
  nodes: stored.nodes,
7507
7707
  edges: stored.edges,
@@ -7666,7 +7866,7 @@ function registerRecovery(env, makeRecursiveWorker) {
7666
7866
  const { options } = env.setup;
7667
7867
  if (options.makeLeafAgent !== void 0 || options.backend?.backend !== "provider" || options.backend.steering) return;
7668
7868
  const factory = registerRetainedExecutorPreparation(createExecutor(options.backend), ({ spawned, profile, task }) => {
7669
- if (!spawned.ownedTreeRoot || !spawned.parent || !spawned.assignmentId || !spawned.identity) return void 0;
7869
+ if (!spawned.parent || !spawned.assignmentId || !spawned.identity) return void 0;
7670
7870
  const execution = {
7671
7871
  ...spawned.identity.candidateDigest ? { candidateDigest: spawned.identity.candidateDigest } : {},
7672
7872
  ...spawned.identity.correlation ? { correlation: spawned.identity.correlation } : {}
@@ -7680,10 +7880,11 @@ function registerRecovery(env, makeRecursiveWorker) {
7680
7880
  ...spawned.key === void 0 ? {} : { key: spawned.key },
7681
7881
  execution
7682
7882
  }, true).executorSpec;
7683
- if (!spec || !isDriverSpec(spec)) return void 0;
7684
- return {
7883
+ if (!spec) return void 0;
7884
+ const factory = isDriverSpec(spec) ? driverExecutorFactory : spec.executorFactory;
7885
+ return factory === void 0 ? void 0 : {
7685
7886
  spec,
7686
- factory: driverExecutorFactory
7887
+ factory
7687
7888
  };
7688
7889
  });
7689
7890
  env.recoveryFactories.set(makeRecursiveWorker, factory);
@@ -7700,7 +7901,7 @@ function registerRecovery(env, makeRecursiveWorker) {
7700
7901
  * bridgeExecutor: bridge stream error: host-executor: acquire timeout after 60000ms
7701
7902
  * (in_flight=4/4, queued=1)
7702
7903
  *
7703
- * Measured 2026-08-22 on discovery-lab cells oscnp s2/s3: two live cells held 2 leads and up to 8
7904
+ * Two live cells held 2 leads and up to 8
7704
7905
  * workers on one bridge whose host executor caps live harness children at 4. A worker spawn that
7705
7906
  * queued past the bridge's single 60 s acquire deadline died there, and the run lost that worker
7706
7907
  * permanently even though a slot freed seconds later. The bridge retries nothing.
@@ -7849,6 +8050,8 @@ function retryPreSpawnRefusals(inner, policy, hooks = {}) {
7849
8050
  ...inner.progress ? { progress: () => inner.progress?.() } : {},
7850
8051
  ...inner.traceSource ? { traceSource: () => inner.traceSource?.() } : {},
7851
8052
  ...inner.metered ? { metered: () => inner.metered?.() } : {},
8053
+ ...inner.accounting ? { accounting: () => inner.accounting?.() } : {},
8054
+ ...inner.resultAccepted ? { resultAccepted: () => inner.resultAccepted?.() === true } : {},
7852
8055
  ...inner.harnessTranscript ? { harnessTranscript: () => inner.harnessTranscript?.() } : {},
7853
8056
  ...inner.harnessTranscriptSettled ? { harnessTranscriptSettled: () => inner.harnessTranscriptSettled?.() ?? Promise.resolve() } : {},
7854
8057
  ...inner.interactive === void 0 ? {} : { interactive: () => interactiveOf(inner) },
@@ -7857,6 +8060,7 @@ function retryPreSpawnRefusals(inner, policy, hooks = {}) {
7857
8060
  const restart = () => inner.execute(task, signal);
7858
8061
  return isAsyncIterable(first) ? retryStream(first, restart, signal) : retryOneShot(first, restart, signal);
7859
8062
  },
8063
+ ...inner.recover ? { recover: (task, signal) => inner.recover(task, signal) } : {},
7860
8064
  teardown: (grace) => inner.teardown(grace),
7861
8065
  ...teardownSurfaces(inner),
7862
8066
  resultArtifact: () => inner.resultArtifact()
@@ -8681,7 +8885,8 @@ var ManagerDriveSession = class {
8681
8885
  }
8682
8886
  /** The next seat the chain grants, waiting out every pause the chain is exhausted until. */
8683
8887
  async nextSeat(seatChain, scope, seatSelection, seatJournalRoot, usageLimit, now) {
8684
- let afterRecheck = false;
8888
+ const paused = [...await seatSelection.journal.loadTree(seatJournalRoot) ?? []].reverse().find((event) => event.id === scope.view.root && (event.kind === "seat-paused" || event.kind === "seat-segment" && event.phase === "started"));
8889
+ let afterRecheck = paused?.kind === "seat-paused" && Date.parse(paused.resumeAt) <= now();
8685
8890
  for (;;) try {
8686
8891
  const seat = await seatChain.next(usageLimit && !afterRecheck, afterRecheck);
8687
8892
  this.activeSeat = seat;
@@ -8697,7 +8902,7 @@ var ManagerDriveSession = class {
8697
8902
  at: new Date(now()).toISOString()
8698
8903
  });
8699
8904
  await seatSelection.onPause(scope.view.root, error.resumeAt, "paused");
8700
- await sleep(Math.max(1e3, Date.parse(error.resumeAt) - now()), scope.signal, false);
8905
+ await sleepScopeWait(scope, Math.max(1e3, Date.parse(error.resumeAt) - now()), scope.signal, "seat-wait");
8701
8906
  afterRecheck = true;
8702
8907
  }
8703
8908
  }
@@ -9517,7 +9722,7 @@ async function startSupervisedRun(run) {
9517
9722
  cancellation?.close();
9518
9723
  throw error;
9519
9724
  }
9520
- const result = supervisor.run(agent, canonicalTask, rootRunOptions(run, runDir, hooks, recorder));
9725
+ const result = withRunParking(options.parking, runDir, runId, setup.journal, setup.now, options.signal === void 0 ? run.durableCancellation.signal : AbortSignal.any([options.signal, run.durableCancellation.signal]), () => supervisor.run(agent, canonicalTask, rootRunOptions(run, runDir, hooks, recorder)));
9521
9726
  const settle = () => settleSupervisedRun(run, result, cancellation);
9522
9727
  if (!recorder) return settle();
9523
9728
  try {
@@ -9725,6 +9930,7 @@ function superviseWithTestBrain(profile, task, opts) {
9725
9930
  return superviseWithContext(profile, task, runtimeOptions, brain);
9726
9931
  }
9727
9932
  function superviseWithContext(profile, task, opts, brain) {
9933
+ assertRunParking(opts.parking, opts.runDir !== void 0);
9728
9934
  if (opts.driverRetry?.pauseRootStops === true && opts.driverRetry.enabled === false) throw new ValidationError("supervise: driverRetry.pauseRootStops pauses where a retry would stop; it cannot be combined with driverRetry.enabled: false");
9729
9935
  if (opts.runContext?.acquire === void 0) return superviseInternal(profile, task, opts, brain);
9730
9936
  const options = captureSuperviseOptions(opts);
@@ -9737,6 +9943,6 @@ function superviseWithContext(profile, task, opts, brain) {
9737
9943
  }, brain));
9738
9944
  }
9739
9945
  //#endregion
9740
- export { noProgressFor as $, runBrainLoop as A, graphRootProfile as B, workerFromBackend as C, composeReentryTask as D, UNPROVEN_CONTINUITY as E, flowRootProfile as F, dumbContinuationFailPrompt as G, analyzesFindingsReportPrompt as H, journaledGateDecider as I, kernelPromptRegistry as J, dumbContinuationPassPrompt as K, routeFlowOf as L, createGraphOverlay as M, GraphRouteError as N, serveCoordinationMcp as O, createFlowRun as P, anyOf as Q, validateFlowGraph as R, taskShapeDigest as S, supervisorAgentWithTestBrain as T, createPromptRegistry as U, validateGraphTopology as V, delegatesWorkerBriefPrompt as W, promptHandle as X, naiveContinuationPrompt as Y, allWorkersStalled as Z, loadGraph as _, superviseRootProfile as a, renderAnytimeTable as at, recordGraphRun as b, retryPreSpawnRefusals as c, createSupervisorSpanRecorder as ct, graphDigest as d, plateau as et, graphFromStored as f, listGraphRuns as g, graph_registry_exports as h, profileGuidanceComposer as i, plateauLength as it, runtimeFlowBrain as j, driverAgent as k, withWorkerSpawnRetry as l, graphRunsFor as m, superviseFleetCapabilities as n, areaUnderCurve as nt, isPreSpawnExecutorFailure as o, readRootStream as ot, graphRegistry as p, formatPromptHandle as q, superviseWithTestBrain as r, bestSoFar as rt, resolveWorkerSpawnRetry as s, readRootStreamReceipt as st, supervise as t, anytimeReport as tt, digestOfGraph as u, lookupGraph as v, supervisorAgent as w, storedGraphDigests as x, pickBestGraph as y, defaultEdgeTraversalCap as z };
9946
+ export { allWorkersStalled as $, serveCoordinationMcp as A, validateFlowGraph as B, storedGraphDigests as C, supervisorAgentWithTestBrain as D, supervisorAgent as E, GraphRouteError as F, createPromptRegistry as G, graphRootProfile as H, createFlowRun as I, dumbContinuationPassPrompt as J, delegatesWorkerBriefPrompt as K, flowRootProfile as L, runBrainLoop as M, runtimeFlowBrain as N, UNPROVEN_CONTINUITY as O, createGraphOverlay as P, promptHandle as Q, journaledGateDecider as R, recordStoredGraphRun as S, workerFromBackend as T, validateGraphTopology as U, defaultEdgeTraversalCap as V, analyzesFindingsReportPrompt as W, kernelPromptRegistry as X, formatPromptHandle as Y, naiveContinuationPrompt as Z, listGraphRuns as _, superviseRootProfile as a, bestSoFar as at, pickBestGraph as b, retryPreSpawnRefusals as c, readRootStream as ct, graphCorpusSummary as d, anyOf as et, graphDigest as f, graph_registry_exports as g, graphRunsFor as h, profileGuidanceComposer as i, areaUnderCurve as it, driverAgent as j, composeReentryTask as k, withWorkerSpawnRetry as l, readRootStreamReceipt as lt, graphRegistry as m, superviseFleetCapabilities as n, plateau as nt, isPreSpawnExecutorFailure as o, plateauLength as ot, graphFromStored as p, dumbContinuationFailPrompt as q, superviseWithTestBrain as r, anytimeReport as rt, resolveWorkerSpawnRetry as s, renderAnytimeTable as st, supervise as t, noProgressFor as tt, digestOfGraph as u, createSupervisorSpanRecorder as ut, loadGraph as v, taskShapeDigest as w, recordGraphRun as x, lookupGraph as y, routeFlowOf as z };
9741
9947
 
9742
- //# sourceMappingURL=supervise-BuVVC7Bl.js.map
9948
+ //# sourceMappingURL=supervise-BGfm2GlY.js.map