maka-agent 0.2.0-dev.22.20260905 → 0.2.0-dev.24.20260907

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 (194) hide show
  1. package/dist/acp/maka-acp-agent.js +2 -1
  2. package/dist/acp/session-configuration.js +143 -0
  3. package/dist/acp/session-registry.js +90 -4
  4. package/dist/cli-core.js +2 -0
  5. package/dist/pi-transcript.js +5 -12
  6. package/dist/pi-tui-runner.js +74 -4
  7. package/dist/runtime-host-cli-context.js +167 -78
  8. package/dist/runtime-host-cli-installation.js +8 -2
  9. package/dist/runtime-host-cli.js +31 -1
  10. package/dist/runtime-host-handoff-surface.js +81 -0
  11. package/dist/runtime-host-installed-update-bootstrap.js +13 -0
  12. package/dist/runtime-host-installed-update-coordinator.js +33 -0
  13. package/dist/runtime-host-lifecycle-transaction.js +9 -1
  14. package/dist/runtime-host-local-handoff.js +37 -4
  15. package/dist/runtime-host-local-managed-activation.js +84 -0
  16. package/dist/runtime-host-local-source-retirement.js +18 -2
  17. package/dist/runtime-host-managed-lifecycle-manager.js +1 -0
  18. package/dist/runtime-host-operator-retirement.js +50 -0
  19. package/dist/runtime-host-service-manager.js +3 -0
  20. package/dist/runtime-host-session-driver.js +4 -25
  21. package/dist/runtime-host-session-update.js +62 -0
  22. package/dist/runtime-host-tui-command.js +38 -73
  23. package/dist/runtime-host-tui-context.js +1 -0
  24. package/dist/runtime-host-tui-owner.js +226 -0
  25. package/dist/tui-copy-catalog.js +140 -3
  26. package/dist/tui-host-owner-copy.js +24 -0
  27. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  28. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  29. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  30. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  31. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  32. package/node_modules/@maka/core/dist/bot-events.js +18 -63
  33. package/node_modules/@maka/core/dist/canonical-runtime-event.js +3 -1
  34. package/node_modules/@maka/core/dist/model-call-attempt.js +0 -82
  35. package/node_modules/@maka/core/dist/model-call-usage-projection.js +0 -186
  36. package/node_modules/@maka/core/dist/model-failure.js +40 -0
  37. package/node_modules/@maka/core/dist/model-metadata.generated.js +4 -4
  38. package/node_modules/@maka/core/dist/model-metadata.js +3 -3
  39. package/node_modules/@maka/core/dist/model-web-search.js +5 -4
  40. package/node_modules/@maka/core/dist/provider-registry.js +45 -4
  41. package/node_modules/@maka/core/dist/record-schema.js +22 -2
  42. package/node_modules/@maka/core/dist/redaction.js +41 -58
  43. package/node_modules/@maka/core/dist/runtime-boundary.js +31 -11
  44. package/node_modules/@maka/core/dist/runtime-event.js +37 -6
  45. package/node_modules/@maka/core/dist/runtime-handoff.js +98 -0
  46. package/node_modules/@maka/core/dist/runtime-invocation.js +1 -1
  47. package/node_modules/@maka/core/dist/runtime-logical-execution.js +112 -0
  48. package/node_modules/@maka/core/dist/session-trace.js +5 -1
  49. package/node_modules/@maka/core/dist/session.js +54 -52
  50. package/node_modules/@maka/core/dist/slash-command-catalog.js +2 -0
  51. package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +20 -0
  52. package/node_modules/@maka/core/dist/usage-ledger-merge.js +7 -9
  53. package/node_modules/@maka/core/dist/usage-record-schema.js +26 -35
  54. package/node_modules/@maka/core/dist/workhub-creation-intent.js +34 -20
  55. package/node_modules/@maka/core/package.json +4 -0
  56. package/node_modules/@maka/eval/harbor/egress-proxy/entrypoint.sh +2 -1
  57. package/node_modules/@maka/mcp/dist/index.js +131 -1
  58. package/node_modules/@maka/runtime/dist/agent-run.js +272 -105
  59. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +13 -5
  60. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +109 -34
  61. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +155 -134
  62. package/node_modules/@maka/runtime/dist/bots/base-adapter.js +17 -0
  63. package/node_modules/@maka/runtime/dist/bots/bot-test.js +38 -22
  64. package/node_modules/@maka/runtime/dist/bots/dingtalk-bridge.js +7 -5
  65. package/node_modules/@maka/runtime/dist/bots/discord-bridge.js +4 -4
  66. package/node_modules/@maka/runtime/dist/bots/feishu-bridge.js +4 -5
  67. package/node_modules/@maka/runtime/dist/bots/qq-bridge.js +6 -4
  68. package/node_modules/@maka/runtime/dist/bots/slack-bridge.js +3 -4
  69. package/node_modules/@maka/runtime/dist/bots/telegram-bridge.js +4 -5
  70. package/node_modules/@maka/runtime/dist/bots/wechat-bridge.js +17 -19
  71. package/node_modules/@maka/runtime/dist/bots/wecom-bridge.js +5 -6
  72. package/node_modules/@maka/runtime/dist/bots/ws-bridge-base.js +2 -3
  73. package/node_modules/@maka/runtime/dist/context-budget.js +14 -9
  74. package/node_modules/@maka/runtime/dist/conversation-copy.js +5 -4
  75. package/node_modules/@maka/runtime/dist/goal-continuation.js +36 -4
  76. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +18 -9
  77. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +30 -22
  78. package/node_modules/@maka/runtime/dist/history-compaction.js +29 -4
  79. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +106 -0
  80. package/node_modules/@maka/runtime/dist/message-authority.js +9 -0
  81. package/node_modules/@maka/runtime/dist/model-adapter.js +19 -98
  82. package/node_modules/@maka/runtime/dist/model-factory.js +19 -81
  83. package/node_modules/@maka/runtime/dist/model-fetcher.js +7 -0
  84. package/node_modules/@maka/runtime/dist/model-runtime.js +85 -111
  85. package/node_modules/@maka/runtime/dist/native-web-search-tool.js +2 -1
  86. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +2 -2
  87. package/node_modules/@maka/runtime/dist/opencode-session-header.js +4 -2
  88. package/node_modules/@maka/runtime/dist/provider-error-classification.js +84 -123
  89. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +68 -108
  90. package/node_modules/@maka/runtime/dist/run-handoff-gate.js +97 -0
  91. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +82 -54
  92. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +117 -159
  93. package/node_modules/@maka/runtime/dist/runtime-kernel.js +150 -112
  94. package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +160 -79
  95. package/node_modules/@maka/runtime/dist/runtime-read-model.js +30 -89
  96. package/node_modules/@maka/runtime/dist/runtime-resume.js +80 -4
  97. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +5 -0
  98. package/node_modules/@maka/runtime/dist/session-manager.js +171 -288
  99. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +0 -27
  100. package/node_modules/@maka/runtime/dist/session-trace-projection.js +3 -30
  101. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +3 -4
  102. package/node_modules/@maka/runtime/dist/test-connection.js +16 -16
  103. package/node_modules/@maka/runtime/dist/tool-result-archive-encoding.js +38 -0
  104. package/node_modules/@maka/runtime/dist/tool-runtime.js +3 -61
  105. package/node_modules/@maka/runtime/package.json +1 -0
  106. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +35 -0
  107. package/node_modules/@maka/runtime-host/dist/candidate-entry.js +4 -1
  108. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +9 -1
  109. package/node_modules/@maka/runtime-host/dist/client/connection.js +3 -0
  110. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +156 -0
  111. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +273 -0
  112. package/node_modules/@maka/runtime-host/dist/client/host-retirement.js +26 -5
  113. package/node_modules/@maka/runtime-host/dist/client/index.js +3 -1
  114. package/node_modules/@maka/runtime-host/dist/client/launcher.js +3 -0
  115. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +13 -0
  116. package/node_modules/@maka/runtime-host/dist/client/registered-host-termination.js +0 -59
  117. package/node_modules/@maka/runtime-host/dist/client/remote-compatibility-error.js +2 -0
  118. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +27 -5
  119. package/node_modules/@maka/runtime-host/dist/operator/index.js +2 -1
  120. package/node_modules/@maka/runtime-host/dist/operator/retirement-cancellation.js +20 -0
  121. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +28 -16
  122. package/node_modules/@maka/runtime-host/dist/protocol/external-session.js +4 -0
  123. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +29 -12
  124. package/node_modules/@maka/runtime-host/dist/protocol/index.js +37 -1
  125. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +2 -0
  126. package/node_modules/@maka/runtime-host/dist/protocol/session-collaboration.js +28 -1
  127. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +40 -20
  128. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +0 -5
  129. package/node_modules/@maka/runtime-host/dist/protocol/session-turns.js +29 -58
  130. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +11 -1
  131. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +33 -0
  132. package/node_modules/@maka/runtime-host/dist/server/access-authority.js +26 -1
  133. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +6 -1
  134. package/node_modules/@maka/runtime-host/dist/server/canonical-turn-snapshot.js +19 -4
  135. package/node_modules/@maka/runtime-host/dist/server/canonical-usage-reader.js +24 -11
  136. package/node_modules/@maka/runtime-host/dist/server/connection-session.js +7 -6
  137. package/node_modules/@maka/runtime-host/dist/server/daily-review-coordinator.js +7 -4
  138. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +168 -28
  139. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +5 -5
  140. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +3 -2
  141. package/node_modules/@maka/runtime-host/dist/server/external-session-coordinator.js +6 -3
  142. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +40 -1
  143. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +108 -23
  144. package/node_modules/@maka/runtime-host/dist/server/host-residency-registry.js +13 -7
  145. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-admission-registry.js +3 -1
  146. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +124 -62
  147. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +85 -8
  148. package/node_modules/@maka/runtime-host/dist/server/root-admission-owner.js +7 -0
  149. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +344 -71
  150. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +37 -2
  151. package/node_modules/@maka/runtime-host/dist/server/serial-outbound-writer.js +45 -3
  152. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +201 -12
  153. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +87 -25
  154. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +8 -55
  155. package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +1 -16
  156. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +0 -1
  157. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +460 -70
  158. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +1 -1
  159. package/node_modules/@maka/runtime-host/dist/server/storage-maintenance.js +109 -0
  160. package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +4 -11
  161. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +44 -15
  162. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +6 -2
  163. package/node_modules/@maka/storage/dist/agent-run-store.js +44 -0
  164. package/node_modules/@maka/storage/dist/artifact-store.js +21 -10
  165. package/node_modules/@maka/storage/dist/artifact-stores.js +1 -1
  166. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +0 -4
  167. package/node_modules/@maka/storage/dist/codex-session-adapter.js +0 -2
  168. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +325 -0
  169. package/node_modules/@maka/storage/dist/conversation-operational-state.js +4 -0
  170. package/node_modules/@maka/storage/dist/execution-stores.js +11 -7
  171. package/node_modules/@maka/storage/dist/file-session-repository.js +1012 -0
  172. package/node_modules/@maka/storage/dist/model-call-ledger.js +199 -32
  173. package/node_modules/@maka/storage/dist/model-call-usage-sql.js +136 -0
  174. package/node_modules/@maka/storage/dist/opencode-session-adapter.js +0 -4
  175. package/node_modules/@maka/storage/dist/operational-state-backup.js +9 -5
  176. package/node_modules/@maka/storage/dist/operational-state-store-public.js +1 -1
  177. package/node_modules/@maka/storage/dist/operational-state-store.js +5 -3
  178. package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
  179. package/node_modules/@maka/storage/dist/runtime-transcript-query.js +308 -0
  180. package/node_modules/@maka/storage/dist/session-bundle-policy.js +24 -4
  181. package/node_modules/@maka/storage/dist/session-message-projection.js +15 -0
  182. package/node_modules/@maka/storage/dist/session-repository.js +767 -0
  183. package/node_modules/@maka/storage/dist/session-store.js +25 -99
  184. package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +10 -3
  185. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +24 -8
  186. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +17 -1
  187. package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +44 -1
  188. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +129 -25
  189. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +109 -892
  190. package/node_modules/@maka/storage/dist/sqlite-usage-schema.js +200 -20
  191. package/node_modules/@maka/storage/dist/tool-result-archive-evidence.js +111 -0
  192. package/node_modules/@maka/storage/dist/usage-stores.js +6 -2
  193. package/node_modules/@maka/storage/package.json +2 -0
  194. package/package.json +1 -1
@@ -35,12 +35,14 @@ import { DEFAULT_TOOL_MODE } from '@maka/core/tool-mode';
35
35
  import { PLAN_USER_ABANDON_REASON, PLAN_USER_CANCEL_REASON, PlanConflictError, } from '@maka/core/plan';
36
36
  import { DEFAULT_SESSION_NAME } from '@maka/core/session-name';
37
37
  import { DEEP_RESEARCH_SESSION_LABEL, isDeepResearchSession } from '@maka/core/deep-research';
38
- import { SUBAGENT_SESSION_RUNTIME_SCHEMA_VERSION, SUBAGENT_SESSION_SPAWN_SCHEMA_VERSION, childSessionsForParent, deriveTurnRecords, subagentSessionRuntimeSummary, } from '@maka/core/session';
38
+ import { SUBAGENT_SESSION_RUNTIME_SCHEMA_VERSION, SUBAGENT_SESSION_SPAWN_SCHEMA_VERSION, childSessionsForParent, subagentSessionRuntimeSummary, } from '@maka/core/session';
39
39
  import { decodeAgentGraphIntentClaim } from '@maka/core/agent-graph-control';
40
40
  import { executionBoundaryContains } from '@maka/core/sandbox-boundary';
41
41
  import { failureClassFromCompleteStopReason } from '@maka/core/events';
42
42
  import { isActiveShellRunStatus } from '@maka/core/shell-run';
43
43
  import { isTerminalRuntimeEvent } from '@maka/core/runtime-event';
44
+ import { runtimeHandoffPause } from '@maka/core/runtime-handoff';
45
+ import { readLogicalRuntimeExecutionForRun } from '@maka/core/runtime-logical-execution';
44
46
  import { buildInvocationOpenedEvent, isSessionInlineInvocation, runtimeInvocationOutcome, } from '@maka/core/runtime-invocation';
45
47
  import { isArtifactChildResultOutput } from '@maka/core/artifacts';
46
48
  import { invocationMatchesClaimTarget } from '@maka/core/runtime-boundary';
@@ -49,7 +51,7 @@ import { AGENT_GRAPH_OPERATOR_PROVISION_SCHEMA_VERSION } from '@maka/core/agent-
49
51
  import { runtimeInvocationFailureClass, } from './runtime-event-read-model.js';
50
52
  import { RuntimeReadModel, RuntimeReadModelError, } from './runtime-read-model.js';
51
53
  import { inspectAgentRunReadModel } from './agent-run-inspect.js';
52
- import { RuntimeLedgerRepair } from './runtime-ledger-repair.js';
54
+ import { isTranscriptLedgerInvocation, RuntimeLedgerRepair } from './runtime-ledger-repair.js';
53
55
  import { buildRecoveredTerminalRuntimeEvent, classifyTerminalRuntimeLedger, commitTerminalRunWithRuntimeFact, terminalRunStatusFromRuntimeEvent, } from './terminal-run-commit.js';
54
56
  import { readLatestContextDiagnostics } from './context-diagnostics.js';
55
57
  import { attributeSandboxBoundaryRestartClosure, classifyAgentRunRecovery, } from './agent-run-recovery.js';
@@ -59,7 +61,7 @@ import { RuntimeInteractionInvariantError, } from './interaction-authority.js';
59
61
  import { RuntimeKernel, SessionQuiescentMutationBusyError, } from './runtime-kernel.js';
60
62
  import { fingerprintAgentGraphRunnableIntent } from './stream-graph-admission.js';
61
63
  import { projectAgentGraphRecords } from './stream-graph-projection.js';
62
- import { buildStatusPatch, buildTurnStateMessage, turnHasRetainedOutput as messagesHaveRetainedOutput, } from './session-projection-helpers.js';
64
+ import { buildStatusPatch } from './session-projection-helpers.js';
63
65
  import { assertAgentDefinitionRunnable, buildToolsForAgentDefinition, listBuiltinAgentDefinitions, requireBuiltinAgentDefinition, requireBuiltinAgentDefinitionByProfile, AGENT_WORKSPACE_WORKTREE, } from './agent-catalog.js';
64
66
  import { stableHash } from './request-shape.js';
65
67
  import { RuntimeContinuationPlanner, } from './runtime-resume.js';
@@ -153,10 +155,7 @@ export class SessionManager {
153
155
  if (deps.runStore && deps.runtimeEventStore) {
154
156
  this.runtimeLedgerRepair = new RuntimeLedgerRepair({
155
157
  runtimeEventStore: deps.runtimeEventStore,
156
- readMessages: (sessionId) => deps.store.readMessages(sessionId),
157
- appendMessage: (sessionId, message) => deps.store.appendMessage(sessionId, message),
158
- newId: deps.newId,
159
- now: deps.now,
158
+ readMessagesAfter: (sessionId, request) => deps.store.readMessagesAfter(sessionId, request),
160
159
  });
161
160
  }
162
161
  this.runtimeKernel = deps.runtimeKernel ?? new RuntimeKernel({ ...deps });
@@ -539,9 +538,6 @@ export class SessionManager {
539
538
  const interrupted = (await listSessionsForRecovery(this.deps.store, policy)).filter((session) => !session.isArchived);
540
539
  const recovered = new Set();
541
540
  for (const session of interrupted) {
542
- if (this.runtimeLedgerRepair) {
543
- await recoverOr(policy, () => this.runtimeLedgerRepair.repairSteeringMessagesOnce(session.id), 0);
544
- }
545
541
  if (this.runtimeKernel.hasActiveRuns(session.id))
546
542
  continue;
547
543
  // Fail-closed: a request whose live owner died can never be answered, so
@@ -561,39 +557,15 @@ export class SessionManager {
561
557
  }), undefined);
562
558
  }
563
559
  }
564
- if (this.deps.planStore) {
565
- const planRecovery = await recoverOr(policy, () => this.deps.planStore.interruptActiveExecution(session.id, 'runtime_recovery'), null);
566
- if (planRecovery)
567
- recovered.add(session.id);
568
- }
569
560
  if (this.deps.shellRuns) {
570
561
  const recoveredShellRuns = await recoverOr(policy, () => this.deps.shellRuns.recoverOrphanedSession(session.id), 0);
571
562
  if (recoveredShellRuns > 0)
572
563
  recovered.add(session.id);
573
564
  }
574
- let messages = [];
575
- let messagesReadable = true;
576
- try {
577
- messages =
578
- policy.kind === 'strict'
579
- ? await policy.stores.sessionStore.readMessagesForRecovery(session.id)
580
- : await this.deps.store.readMessages(session.id);
581
- }
582
- catch (error) {
583
- if (policy.kind === 'strict')
584
- throw error;
585
- messagesReadable = false;
586
- }
587
- if (session.revisionState === 'preparing' && messagesReadable) {
588
- if (hasRevisionUserMessage(messages)) {
589
- await recoverOr(policy, () => this.commitRevisionVersion(session.id), undefined);
590
- }
591
- else {
592
- await recoverOr(policy, () => this.remove(session.id), undefined);
593
- recovered.add(session.id);
594
- continue;
595
- }
596
- }
565
+ // A revision copy still `preparing` is settled by the Host's revision
566
+ // coordinator, which reads the admission ledger and runs before this
567
+ // recovery. Deciding it a second time here — off a transcript scan, and
568
+ // ending in `remove()` — could only ever contradict it.
597
569
  let continuationClaimRecovered = false;
598
570
  const continuationAuthority = runtimeContinuationAuthority(this.deps.runtimeEventStore);
599
571
  if (this.deps.runStore && continuationAuthority) {
@@ -612,6 +584,24 @@ export class SessionManager {
612
584
  if (continuationClaimRecovered)
613
585
  recovered.add(session.id);
614
586
  }
587
+ if (this.deps.planStore) {
588
+ const preservesHandoff = await recoverOr(policy, async () => {
589
+ if (!continuationAuthority)
590
+ return false;
591
+ const latest = latestInvocation((await this.listInvocations(session.id)).filter((run) => isSessionInlineInvocation(run.opening)));
592
+ if (!latest)
593
+ return false;
594
+ // Only the current logical execution may preserve a session-owned Plan.
595
+ // Read after claim repair: an abandoned successor now has a real failure.
596
+ return Boolean((await readLogicalRuntimeExecutionForRun(continuationAuthority, latest))
597
+ ?.pendingHandoff);
598
+ }, false);
599
+ if (!preservesHandoff) {
600
+ const planRecovery = await recoverOr(policy, () => this.deps.planStore.interruptActiveExecution(session.id, 'runtime_recovery'), null);
601
+ if (planRecovery)
602
+ recovered.add(session.id);
603
+ }
604
+ }
615
605
  if (this.deps.runStore) {
616
606
  const runRecovery = await recoverOr(policy, () => this.recoverAgentRunsFromLedger(session.id, policy), undefined);
617
607
  if (runRecovery?.hasLedger) {
@@ -619,44 +609,23 @@ export class SessionManager {
619
609
  await recoverOr(policy, () => this.updateStatus(session.id, 'active'), undefined);
620
610
  recovered.add(session.id);
621
611
  }
622
- else if (!messagesReadable &&
623
- (session.status === 'running' || session.status === 'waiting_for_user')) {
624
- await recoverOr(policy, () => this.updateStatus(session.id, 'active'), undefined);
625
- recovered.add(session.id);
626
- }
627
612
  continue;
628
613
  }
629
614
  }
630
- if (!messagesReadable) {
631
- if (session.status === 'running' || session.status === 'waiting_for_user') {
632
- // Recovery may run in BACKGROUND startup (#456): re-check for a
633
- // run the user started while this session's recovery was in
634
- // flight, so we never stomp a live run's status.
635
- if (this.runtimeKernel.hasActiveRuns(session.id))
636
- continue;
637
- await recoverOr(policy, () => this.updateStatus(session.id, 'active'), undefined);
638
- recovered.add(session.id);
639
- }
640
- continue;
641
- }
642
- const recoveries = interruptedTurnRecoveries(messages);
643
- if (recoveries.length === 0)
644
- continue;
645
- for (const recovery of recoveries) {
646
- await recoverOr(policy, () => this.appendTurnState(session.id, recovery.turnId, 'failed', recovery.lineage, {
647
- errorClass: recovery.errorClass,
648
- }), undefined);
649
- }
615
+ // No ledger and nothing to recover from it. A Session whose turns were
616
+ // interrupted before this process started is settled by the transcript
617
+ // importer, which converts a turn that never recorded how it ended into
618
+ // the failed terminal fact it actually was — this recovery has no second
619
+ // transcript to read that from.
650
620
  if (session.status === 'running' || session.status === 'waiting_for_user') {
651
- // Same double-check as above: a message sent mid-recovery owns
652
- // the session status now (its own transitions will settle it).
653
- if (this.runtimeKernel.hasActiveRuns(session.id)) {
654
- recovered.add(session.id);
621
+ // Recovery may run in BACKGROUND startup (#456): re-check for a run the
622
+ // user started while this session's recovery was in flight, so we never
623
+ // stomp a live run's status.
624
+ if (this.runtimeKernel.hasActiveRuns(session.id))
655
625
  continue;
656
- }
657
626
  await recoverOr(policy, () => this.updateStatus(session.id, 'active'), undefined);
627
+ recovered.add(session.id);
658
628
  }
659
- recovered.add(session.id);
660
629
  }
661
630
  return [...recovered];
662
631
  }
@@ -717,15 +686,6 @@ export class SessionManager {
717
686
  });
718
687
  const next = await this.deps.store.readHeader(sessionId);
719
688
  this.runtimeKernel.updateCachedHeader(sessionId, next);
720
- await this.deps.store
721
- .appendMessage(sessionId, {
722
- type: 'system_note',
723
- id: this.deps.newId(),
724
- ts: this.deps.now(),
725
- kind: 'mode_change',
726
- data: { from: previous.permissionMode, to: mode },
727
- })
728
- .catch(() => undefined);
729
689
  return headerToSummary(next);
730
690
  }
731
691
  async setExecutionBoundaryKind(sessionId, kind) {
@@ -886,13 +846,6 @@ export class SessionManager {
886
846
  const next = await this.deps.store.updateHeader(sessionId, {
887
847
  collaborationMode: mode,
888
848
  });
889
- await this.deps.store.appendMessage(sessionId, {
890
- type: 'system_note',
891
- id: this.deps.newId(),
892
- ts: this.deps.now(),
893
- kind: 'mode_change',
894
- data: { dimension: 'collaboration', from, to: mode },
895
- });
896
849
  this.runtimeKernel.updateCachedHeader(sessionId, next);
897
850
  await this.runtimeKernel.disposeBackend(sessionId);
898
851
  return headerToSummary(next);
@@ -909,13 +862,6 @@ export class SessionManager {
909
862
  throw new Error('Cannot change orchestration mode while a tool call awaits confirmation.');
910
863
  }
911
864
  const next = await this.deps.store.updateHeader(sessionId, { orchestrationMode: mode });
912
- await this.deps.store.appendMessage(sessionId, {
913
- type: 'system_note',
914
- id: this.deps.newId(),
915
- ts: this.deps.now(),
916
- kind: 'mode_change',
917
- data: { dimension: 'orchestration', from, to: mode },
918
- });
919
865
  this.runtimeKernel.updateCachedHeader(sessionId, next);
920
866
  return headerToSummary(next);
921
867
  }
@@ -950,7 +896,7 @@ export class SessionManager {
950
896
  if (!replay)
951
897
  await this.runtimeKernel.disposeBackend(sessionId);
952
898
  const result = await this.requirePlanStore().abandonProposal(input);
953
- await this.finalizePlanAbandonment(sessionId, operationId, replay);
899
+ await this.finalizePlanAbandonment(sessionId);
954
900
  return result;
955
901
  }
956
902
  async approvePlan(input) {
@@ -1049,7 +995,7 @@ export class SessionManager {
1049
995
  : options.admitTurn;
1050
996
  yield* this.runtimeKernel.startTurn(sessionId, input, { ...options, admitTurn });
1051
997
  }
1052
- async planSafeBoundaryContinuation(sessionId, input) {
998
+ async planSafeBoundaryContinuation(sessionId, input, preview) {
1053
999
  let admissionRoute;
1054
1000
  try {
1055
1001
  if (!this.deps.runStore)
@@ -1107,19 +1053,23 @@ export class SessionManager {
1107
1053
  throw new Error('AgentRunStore is not configured');
1108
1054
  return (await this.listInvocations(targetSessionId)).find((run) => {
1109
1055
  const source = run.opening.source;
1110
- return (source.kind === 'continuation' &&
1056
+ return (source.kind !== 'fresh' &&
1111
1057
  source.sourceRunId === sourceRunId &&
1112
1058
  source.sourceRuntimeEventHighWater === sourceRuntimeEventHighWater);
1113
1059
  });
1114
1060
  },
1115
1061
  newId: this.deps.newId,
1116
1062
  });
1117
- const plan = await planner.plan({ sessionId, admissionRoute, ...input });
1118
- this.recordContinuationPlan(sessionId, input.sourceRunId, plan);
1063
+ const plannerInput = { sessionId, admissionRoute, ...input };
1064
+ const plan = preview
1065
+ ? await planner.previewHandoff(plannerInput, preview)
1066
+ : await planner.plan(plannerInput);
1067
+ if (!preview)
1068
+ this.recordContinuationPlan(sessionId, input.sourceRunId, plan);
1119
1069
  return plan;
1120
1070
  }
1121
- async planAuthoritativeSafeBoundaryContinuation(sessionId, input) {
1122
- if (this.deps.safeBoundaryResumeEnabled !== true) {
1071
+ async planAuthoritativeSafeBoundaryContinuation(sessionId, input, preview) {
1072
+ if (input.purpose !== 'handoff' && this.deps.safeBoundaryResumeEnabled !== true) {
1123
1073
  const plan = resumeFeatureDisabledPlan();
1124
1074
  this.recordContinuationPlan(sessionId, input.sourceRunId, plan);
1125
1075
  return plan;
@@ -1184,6 +1134,7 @@ export class SessionManager {
1184
1134
  return plan;
1185
1135
  }
1186
1136
  return this.planSafeBoundaryContinuation(sessionId, {
1137
+ ...(input.purpose ? { purpose: input.purpose } : {}),
1187
1138
  sourceRunId: input.sourceRunId,
1188
1139
  currentCwd: header.cwd,
1189
1140
  sourceWorkspaceIdentity: sourceRun.opening.configuration.workspaceIdentity,
@@ -1196,7 +1147,7 @@ export class SessionManager {
1196
1147
  ...(observation.workspaceCheckpoint
1197
1148
  ? { workspaceCheckpoint: observation.workspaceCheckpoint }
1198
1149
  : {}),
1199
- });
1150
+ }, preview);
1200
1151
  }
1201
1152
  async planLatestAuthoritativeSafeBoundaryContinuation(sessionId) {
1202
1153
  if (this.deps.safeBoundaryResumeEnabled !== true) {
@@ -1241,6 +1192,37 @@ export class SessionManager {
1241
1192
  sourceRunId: candidate.runId,
1242
1193
  });
1243
1194
  }
1195
+ requestRunHandoff(sessionId, runId, intent, signal) {
1196
+ const request = this.runtimeKernel.requestRunHandoff?.(sessionId, runId, intent, signal);
1197
+ if (!request)
1198
+ return undefined;
1199
+ let verified = false;
1200
+ const ready = request.ready.then(async (held) => {
1201
+ if (!held)
1202
+ return false;
1203
+ try {
1204
+ const assessment = await this.planAuthoritativeSafeBoundaryContinuation(sessionId, { sourceRunId: runId, purpose: 'handoff' }, request.preview());
1205
+ request.preview(); // Cancellation or Stop may have released the gate during inspection.
1206
+ verified = assessment.disposition === 'continue' && !signal.aborted;
1207
+ if (!verified)
1208
+ request.cancel();
1209
+ return verified;
1210
+ }
1211
+ catch {
1212
+ request.cancel();
1213
+ return false;
1214
+ }
1215
+ });
1216
+ return {
1217
+ ready,
1218
+ sealed: request.sealed,
1219
+ commit: () => verified && request.commit(),
1220
+ cancel: () => {
1221
+ verified = false;
1222
+ request.cancel();
1223
+ },
1224
+ };
1225
+ }
1244
1226
  async *resumeSafeBoundaryContinuation(continuation, options = {}) {
1245
1227
  const resume = this.runtimeKernel.resumeContinuation;
1246
1228
  if (!resume)
@@ -1695,17 +1677,12 @@ export class SessionManager {
1695
1677
  return claimedAgentGraphIntentResult(claim, await this.projectExistingChildSpawn(child, run));
1696
1678
  }
1697
1679
  await this.finalizeChildWorkspacePatches(child.id);
1698
- const [runs, messages] = await Promise.all([
1699
- this.listInvocations(child.id),
1700
- this.deps.store.readMessages(child.id),
1701
- ]);
1702
- const turnOwner = runs.find((candidate) => candidate.turnId === claim.targetTurnId);
1680
+ // An invocation is what makes a Turn exist on the ledger, so the run listing
1681
+ // is the whole occupancy check: a Turn with durable content has one.
1682
+ const turnOwner = (await this.listInvocations(child.id)).find((candidate) => candidate.turnId === claim.targetTurnId);
1703
1683
  if (turnOwner) {
1704
1684
  throw new Error(`Claimed graph turn ${claim.targetTurnId} is already owned by run ${turnOwner.runId}`);
1705
1685
  }
1706
- if (messages.some((message) => 'turnId' in message && message.turnId === claim.targetTurnId)) {
1707
- throw new Error(`Claimed graph turn ${claim.targetTurnId} already has durable messages`);
1708
- }
1709
1686
  if (child.isArchived || child.status === 'aborted') {
1710
1687
  throw new Error('Claimed graph execution target child session is terminated');
1711
1688
  }
@@ -1841,7 +1818,7 @@ export class SessionManager {
1841
1818
  }
1842
1819
  }
1843
1820
  async assertClaimedAgentGraphPrompt(sessionId, turnId, prompt, expectedUserMessageId) {
1844
- const messages = await this.deps.store.readMessages(sessionId);
1821
+ const { messages } = await this.getSessionView(sessionId);
1845
1822
  const userMessages = messages.filter((message) => message.type === 'user' && message.turnId === turnId);
1846
1823
  if (expectedUserMessageId !== undefined) {
1847
1824
  if (userMessages.length !== 1 ||
@@ -2111,14 +2088,10 @@ export class SessionManager {
2111
2088
  if (!snapshot)
2112
2089
  throw new Error('Stored child session is missing its durable runtime snapshot');
2113
2090
  const facts = invocationListingFacts(run);
2114
- const [messages, runtimeEvents, artifacts] = await Promise.all([
2115
- this.deps.store.readMessages(child.id),
2091
+ const [runtimeEvents, artifacts] = await Promise.all([
2116
2092
  this.deps.runtimeEventStore.readRuntimeEvents(child.id, run.runId),
2117
2093
  this.finalizeAndListChildTurnArtifacts(child.id, run.turnId, facts.status),
2118
2094
  ]);
2119
- const storedSummary = messages
2120
- .filter((message) => message.type === 'assistant' && message.turnId === run.turnId)
2121
- .at(-1)?.text ?? '';
2122
2095
  const runtimeText = runtimeEvents.filter((event) => event.role === 'model' && event.content?.kind === 'text');
2123
2096
  const durableRuntimeSummary = runtimeText.filter((event) => !event.partial).at(-1)
2124
2097
  ?.content.text;
@@ -2135,7 +2108,7 @@ export class SessionManager {
2135
2108
  runId: run.runId,
2136
2109
  status: agentRunStatusForSpawnResult(facts.status),
2137
2110
  permissionMode: child.permissionMode,
2138
- summary: trimSummary(durableRuntimeSummary ?? (storedSummary || partialRuntimeSummary)),
2111
+ summary: trimSummary(durableRuntimeSummary ?? partialRuntimeSummary),
2139
2112
  artifactIds: artifacts.map((artifact) => artifact.id),
2140
2113
  startedAt: facts.createdAt,
2141
2114
  completedAt: facts.updatedAt,
@@ -2536,6 +2509,33 @@ export class SessionManager {
2536
2509
  openedAt: input.admittedAt,
2537
2510
  opening,
2538
2511
  }));
2512
+ if (input.userMessage) {
2513
+ await this.deps.runtimeEventStore.appendRuntimeEvent(input.sessionId, input.runId, {
2514
+ id: input.userMessage.id,
2515
+ ...run,
2516
+ ts: input.admittedAt,
2517
+ partial: false,
2518
+ role: 'user',
2519
+ author: input.userMessage.origin ? 'host' : 'user',
2520
+ content: {
2521
+ kind: 'text',
2522
+ text: input.userMessage.content.text,
2523
+ ...(input.userMessage.content.displayText !== undefined
2524
+ ? { displayText: input.userMessage.content.displayText }
2525
+ : {}),
2526
+ ...(input.userMessage.content.attachments?.length
2527
+ ? { attachments: input.userMessage.content.attachments }
2528
+ : {}),
2529
+ ...(input.userMessage.content.directoryReferences?.length
2530
+ ? { directoryReferences: input.userMessage.content.directoryReferences }
2531
+ : {}),
2532
+ ...(input.userMessage.content.quotes?.length
2533
+ ? { quotes: input.userMessage.content.quotes }
2534
+ : {}),
2535
+ ...(input.userMessage.origin ? { origin: input.userMessage.origin } : {}),
2536
+ },
2537
+ });
2538
+ }
2539
2539
  const ts = this.deps.now();
2540
2540
  const terminalEvent = buildRecoveredTerminalRuntimeEvent({
2541
2541
  id: this.deps.newId(),
@@ -2642,22 +2642,7 @@ export class SessionManager {
2642
2642
  }
2643
2643
  /** Canonical, repaired source view for a Host-owned cross-Session copy. */
2644
2644
  async readConversationCopySnapshot(sessionId) {
2645
- const readMessagesSnapshot = this.deps.store.readMessagesSnapshot;
2646
- if (!readMessagesSnapshot) {
2647
- throw new Error('Conversation copy requires a side-effect-free message snapshot');
2648
- }
2649
- const readMessages = readMessagesSnapshot.bind(this.deps.store);
2650
- const view = await this.getSessionView(sessionId, { readMessages });
2651
- if (view.invocations.length > 0 || view.messages.length > 0)
2652
- return view;
2653
- const messages = await readMessages(sessionId);
2654
- if (messages.length === 0)
2655
- return view;
2656
- return {
2657
- ...view,
2658
- messages,
2659
- turns: deriveTurnRecords(messages),
2660
- };
2645
+ return this.getSessionView(sessionId);
2661
2646
  }
2662
2647
  async respondToSandboxBoundary(sessionId, response) {
2663
2648
  if (this.deps.interactionAuthority) {
@@ -2725,14 +2710,10 @@ export class SessionManager {
2725
2710
  catch (error) {
2726
2711
  if (!(error instanceof RuntimeReadModelError))
2727
2712
  throw error;
2728
- // ShellRun hydration is a best-effort UI projection. A legacy RuntimeEvent
2729
- // incompatibility must not turn its retry loop into a permanent IPC error.
2730
- try {
2731
- return await this.deps.store.readMessages(sessionId);
2732
- }
2733
- catch {
2734
- return null;
2735
- }
2713
+ // ShellRun hydration is a best-effort UI projection. A ledger the read
2714
+ // model cannot project yet must not turn its retry loop into a permanent
2715
+ // IPC error; there is no second transcript to fall back to.
2716
+ return null;
2736
2717
  }
2737
2718
  }
2738
2719
  async findChildRunForOutput(sessionId, input) {
@@ -2814,37 +2795,12 @@ export class SessionManager {
2814
2795
  : header;
2815
2796
  this.runtimeKernel.updateCachedHeader(sessionId, next);
2816
2797
  }
2817
- async finalizePlanAbandonment(sessionId, operationId, replay) {
2798
+ async finalizePlanAbandonment(sessionId) {
2818
2799
  const header = await this.deps.store.readHeader(sessionId);
2819
- const from = header.collaborationMode ?? 'agent';
2820
- const changed = from !== 'agent';
2821
- const next = changed
2822
- ? await this.deps.store.updateHeader(sessionId, { collaborationMode: 'agent' })
2823
- : header;
2800
+ const next = (header.collaborationMode ?? 'agent') === 'agent'
2801
+ ? header
2802
+ : await this.deps.store.updateHeader(sessionId, { collaborationMode: 'agent' });
2824
2803
  this.runtimeKernel.updateCachedHeader(sessionId, next);
2825
- if (!changed && !replay)
2826
- return;
2827
- if (!operationId) {
2828
- await this.deps.store.appendMessage(sessionId, {
2829
- type: 'system_note',
2830
- id: this.deps.newId(),
2831
- ts: this.deps.now(),
2832
- kind: 'mode_change',
2833
- data: { dimension: 'collaboration', from, to: 'agent' },
2834
- });
2835
- return;
2836
- }
2837
- const noteId = planAbandonmentNoteId(operationId);
2838
- const messages = await this.deps.store.readMessages(sessionId);
2839
- if (messages.some((message) => message.id === noteId))
2840
- return;
2841
- await this.deps.store.appendMessage(sessionId, {
2842
- type: 'system_note',
2843
- id: noteId,
2844
- ts: this.deps.now(),
2845
- kind: 'mode_change',
2846
- data: { dimension: 'collaboration', from: 'plan', to: 'agent' },
2847
- });
2848
2804
  }
2849
2805
  requirePlanStore() {
2850
2806
  if (!this.deps.planStore)
@@ -2876,23 +2832,6 @@ export class SessionManager {
2876
2832
  throw new SessionConfigurationTransitionError('operation_conflict', 'A pending Plan proposal must be resolved before leaving Plan mode');
2877
2833
  }
2878
2834
  }
2879
- async appendTurnState(sessionId, turnId, status, lineage = {}, options = {}) {
2880
- const ts = options.ts ?? this.deps.now();
2881
- await this.deps.store.appendMessage(sessionId, buildTurnStateMessage({
2882
- id: this.deps.newId(),
2883
- turnId,
2884
- ts,
2885
- status,
2886
- lineage,
2887
- ...(options.abortSource ? { abortSource: options.abortSource } : {}),
2888
- ...(options.errorClass !== undefined ? { errorClass: options.errorClass } : {}),
2889
- partialOutputRetained: await this.turnHasRetainedOutput(sessionId, turnId),
2890
- }));
2891
- }
2892
- async turnHasRetainedOutput(sessionId, turnId) {
2893
- const messages = await this.deps.store.readMessages(sessionId).catch(() => []);
2894
- return messagesHaveRetainedOutput(messages, turnId);
2895
- }
2896
2835
  async requireTurnForAction(sessionId, turnId, allowed, action) {
2897
2836
  const turn = (await this.getSessionView(sessionId)).turns.find((candidate) => candidate.turnId === turnId);
2898
2837
  if (!turn)
@@ -2902,21 +2841,41 @@ export class SessionManager {
2902
2841
  }
2903
2842
  return turn;
2904
2843
  }
2905
- async getSessionView(sessionId, projectionCache = this.deps.store) {
2906
- return this.readModel(projectionCache).getSessionView(sessionId);
2844
+ /**
2845
+ * The Session as its ledger tells it.
2846
+ *
2847
+ * A transcript written before the ledger owned execution facts is converted
2848
+ * here, on the first read, because there is no second transcript left to read
2849
+ * it from: the importer is what gives those turns an invocation to be
2850
+ * projected from, so a read that skipped it would report the Session empty.
2851
+ */
2852
+ async getSessionView(sessionId) {
2853
+ await this.ensureTranscriptLedgerForRead(sessionId);
2854
+ return this.readModel().getSessionView(sessionId);
2907
2855
  }
2908
- readModel(projectionCache = this.deps.store) {
2856
+ readModel() {
2909
2857
  if (!this.deps.runStore || !this.deps.runtimeEventStore) {
2910
2858
  throw new Error('RuntimeReadModel requires AgentRunStore and RuntimeEventStore');
2911
2859
  }
2912
2860
  return new RuntimeReadModel({
2913
2861
  runtimeEventStore: this.deps.runtimeEventStore,
2914
- projectionCache,
2915
2862
  ...(this.deps.canonicalPermissionOutcomes
2916
2863
  ? { canonicalPermissionOutcomes: this.deps.canonicalPermissionOutcomes }
2917
2864
  : {}),
2918
2865
  });
2919
2866
  }
2867
+ /**
2868
+ * Convert a transcript written before the ledger owned execution facts, so a
2869
+ * reader that goes straight to the ledger still sees the whole Session.
2870
+ *
2871
+ * Idempotent and cheap after the first call: the conversion is remembered per
2872
+ * Session, and a Session born on the ledger has nothing to convert.
2873
+ */
2874
+ async ensureTranscriptLedgerForRead(sessionId) {
2875
+ const repair = this.runtimeLedgerRepair;
2876
+ if (repair)
2877
+ await this.ensureTranscriptLedger(sessionId, repair, 'compatibility');
2878
+ }
2920
2879
  async prepareImportedSessionHistory(sessionId) {
2921
2880
  const repair = this.runtimeLedgerRepair;
2922
2881
  if (!repair)
@@ -2930,6 +2889,14 @@ export class SessionManager {
2930
2889
  if (header.transcriptLedgerVersion === 0 && source !== 'import') {
2931
2890
  throw new Error('Imported Session history is still being prepared');
2932
2891
  }
2892
+ // Version 1 says a conversion ran, not that every legacy fact reached the
2893
+ // ledger. A released build set it on the first send and went on writing
2894
+ // context notes to the transcript alone, so those notes stay behind on
2895
+ // Sessions it touched. Re-running the converter cannot reach them: they
2896
+ // belong to turns a real run already sealed, and a sealed run refuses the
2897
+ // append. They are hidden from the model and describe context, so they are
2898
+ // the accepted cost of the cutover — do not read this marker as proof that
2899
+ // nothing is left in `session_messages`.
2933
2900
  if (header.transcriptLedgerVersion !== 1) {
2934
2901
  await repair.materializeTranscriptLedger(header);
2935
2902
  await this.updateHeader(sessionId, { transcriptLedgerVersion: 1 });
@@ -3025,7 +2992,9 @@ export class SessionManager {
3025
2992
  async recoverAgentRunsFromLedger(sessionId, policy = { kind: 'best_effort' }) {
3026
2993
  if (!this.deps.runStore || !this.deps.runtimeEventStore)
3027
2994
  return { hasLedger: false, recovered: false };
3028
- const runs = await this.listInvocations(sessionId);
2995
+ // The importer may have committed only a prefix before a restart. Sealing
2996
+ // that prefix here would make the next read skip the unconverted history.
2997
+ const runs = (await this.listInvocations(sessionId)).filter((run) => !isTranscriptLedgerInvocation(run));
3029
2998
  if (runs.length === 0)
3030
2999
  return { hasLedger: false, recovered: false };
3031
3000
  const continuationAuthority = runtimeContinuationAuthority(this.deps.runtimeEventStore);
@@ -3066,6 +3035,14 @@ export class SessionManager {
3066
3035
  diagnostic.code === 'operational_event_corrupt')) {
3067
3036
  throw new Error(`AgentRun event ledger is unreadable for run ${run.runId}`);
3068
3037
  }
3038
+ if (run.terminalEvent && runtimeHandoffPause(run.terminalEvent)) {
3039
+ if (inspected.runtimeEvents.at(-1)?.id !== run.terminalEvent.id) {
3040
+ throw new Error(`Handoff source has events after its seal: ${run.runId}`);
3041
+ }
3042
+ // The original Root admission owns this logical execution. Generic
3043
+ // restart repair must neither replay its tools nor manufacture failure.
3044
+ continue;
3045
+ }
3069
3046
  if (claimOwnedUnsettledRunIds.has(run.runId) &&
3070
3047
  !inspected.runtimeEvents.some(isTerminalRuntimeEvent)) {
3071
3048
  // Every unresolved claim target belongs to the claim saga. This
@@ -3162,30 +3139,12 @@ export class SessionManager {
3162
3139
  throw error;
3163
3140
  return false;
3164
3141
  }
3165
- const appendedTurnState = await recoverOr(policy, () => this.appendTerminalTurnStateIfNeeded(sessionId, inspected.invocation, decision, terminalTurnStatus(status), {
3166
- ts,
3167
- ...(failureClass ? { errorClass: failureClass } : {}),
3168
- ...(abortSource ? { abortSource } : {}),
3169
- }, policy), false);
3170
- // A run that already carried a complete terminal fact and a terminal Turn
3171
- // state had nothing to recover. Saying otherwise makes recovery rewrite the
3172
- // Session status of every healthy run it walks past.
3173
- return inspected.terminalRuntimeFact === undefined || appendedTurnState;
3174
- }
3175
- async appendTerminalTurnStateIfNeeded(sessionId, run, decision, status, options, policy = { kind: 'best_effort' }) {
3176
- if (!isSessionInlineInvocation(run.opening))
3177
- return false;
3178
- const messages = await recoverOr(policy, () => this.deps.store.readMessages(sessionId), []);
3179
- const latest = latestTurnState(messages, decision.turnId);
3180
- if (latest && isTerminalTurnStatus(latest.status) && latest.status === status)
3181
- return false;
3182
- await this.appendTurnState(sessionId, decision.turnId, status, decision.lineage, options);
3183
- return true;
3142
+ // A run that already carried a complete terminal fact had nothing to
3143
+ // recover. Saying otherwise makes recovery rewrite the Session status of
3144
+ // every healthy run it walks past.
3145
+ return inspected.terminalRuntimeFact === undefined;
3184
3146
  }
3185
3147
  }
3186
- function planAbandonmentNoteId(operationId) {
3187
- return `plan-abandonment-${createHash('sha256').update(operationId).digest('hex')}`;
3188
- }
3189
3148
  function resumeFeatureDisabledPlan() {
3190
3149
  return {
3191
3150
  disposition: 'park',
@@ -3549,91 +3508,15 @@ class ChildAgentSummaryAccumulator {
3549
3508
  this.textDeltaTail = this.textDeltaTail.slice(-CHILD_AGENT_SUMMARY_MAX_CHARS);
3550
3509
  }
3551
3510
  }
3552
- function hasRevisionUserMessage(messages) {
3553
- let boundary = -1;
3554
- for (let index = 0; index < messages.length; index += 1) {
3555
- const message = messages[index];
3556
- if (message.type === 'system_note' &&
3557
- message.kind === 'session_start' &&
3558
- message.data &&
3559
- typeof message.data === 'object' &&
3560
- 'revisionRootSessionId' in message.data) {
3561
- boundary = index;
3562
- }
3563
- }
3564
- return boundary >= 0 && messages.slice(boundary + 1).some((message) => message.type === 'user');
3565
- }
3566
- function interruptedTurnRecoveries(messages) {
3567
- const byTurn = new Map();
3568
- for (const message of messages) {
3569
- const turnId = message.turnId;
3570
- if (!turnId)
3571
- continue;
3572
- const bucket = byTurn.get(turnId) ?? { hasAssistant: false, states: [] };
3573
- if (message.type === 'assistant')
3574
- bucket.hasAssistant = true;
3575
- if (message.type === 'turn_state')
3576
- bucket.states.push(message);
3577
- byTurn.set(turnId, bucket);
3578
- }
3579
- const recoveries = [];
3580
- for (const [turnId, bucket] of byTurn) {
3581
- const latest = bucket.states.at(-1);
3582
- if (!latest)
3583
- continue;
3584
- if (latest.status === 'running') {
3585
- recoveries.push({
3586
- turnId,
3587
- errorClass: 'app_restarted',
3588
- lineage: turnStateLineage(latest),
3589
- });
3590
- continue;
3591
- }
3592
- const failed = [...bucket.states].reverse().find((state) => state.status === 'failed');
3593
- if (latest.status === 'completed' && !bucket.hasAssistant && failed) {
3594
- recoveries.push({
3595
- turnId,
3596
- errorClass: failed.errorClass ?? 'unknown',
3597
- lineage: turnStateLineage(failed),
3598
- });
3599
- }
3600
- }
3601
- return recoveries;
3602
- }
3603
- function turnStateLineage(state) {
3604
- return {
3605
- ...(state.parentTurnId ? { parentTurnId: state.parentTurnId } : {}),
3606
- ...(state.retriedFromTurnId ? { retriedFromTurnId: state.retriedFromTurnId } : {}),
3607
- ...(state.regeneratedFromTurnId ? { regeneratedFromTurnId: state.regeneratedFromTurnId } : {}),
3608
- ...(state.branchOfTurnId ? { branchOfTurnId: state.branchOfTurnId } : {}),
3609
- ...(state.parentSessionId ? { parentSessionId: state.parentSessionId } : {}),
3610
- };
3611
- }
3612
3511
  function isTerminalRunStatus(status) {
3613
3512
  return status === 'completed' || status === 'failed' || status === 'cancelled';
3614
3513
  }
3615
- function isTerminalTurnStatus(status) {
3616
- return status === 'completed' || status === 'failed' || status === 'aborted';
3617
- }
3618
- function terminalTurnStatus(status) {
3619
- if (status === 'cancelled')
3620
- return 'aborted';
3621
- return status;
3622
- }
3623
3514
  function diagnosticRecoveryReason(diagnostic) {
3624
3515
  const recoveryReason = diagnostic?.recoveryReason;
3625
3516
  return typeof recoveryReason === 'string' && recoveryReason.length > 0
3626
3517
  ? recoveryReason
3627
3518
  : 'agent_run_recovery';
3628
3519
  }
3629
- function latestTurnState(messages, turnId) {
3630
- for (let index = messages.length - 1; index >= 0; index -= 1) {
3631
- const message = messages[index];
3632
- if (message?.type === 'turn_state' && message.turnId === turnId)
3633
- return message;
3634
- }
3635
- return undefined;
3636
- }
3637
3520
  function runtimeTerminalFactToRecoveryDecision(invocation, fact) {
3638
3521
  return {
3639
3522
  runId: fact.runId,