@qlairoslabs/acp-client 0.12.0 → 0.13.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (467) hide show
  1. package/CHANGELOG-consumer-fixes.md +17 -3
  2. package/CHANGELOG-controller-interface.md +258 -0
  3. package/CHANGELOG-metering.md +29 -0
  4. package/CHANGELOG-operation-lifecycle.md +15 -1
  5. package/CONSUMER_GUIDE.md +847 -7
  6. package/MIGRATION-0.10-to-0.12.md +4 -1
  7. package/MIGRATION-0.12-to-0.13.md +275 -0
  8. package/README.md +17 -16
  9. package/package.json +4 -2
  10. package/src/acp-client-handlers.ts +48 -0
  11. package/src/activity.ts +3 -0
  12. package/src/adapters.ts +30 -0
  13. package/src/agent/adoption/provider-attachment.ts +33 -0
  14. package/src/agent/adoption/provider-session-delete.ts +1 -1
  15. package/src/agent/adoption/provider-sessions.ts +3 -2
  16. package/src/agent/append-assistant-message.ts +91 -0
  17. package/src/agent/config.ts +54 -6
  18. package/src/agent/conversation-manager.ts +94 -158
  19. package/src/agent/manager-settings.ts +1 -0
  20. package/src/agent/native-channel-lifecycle.ts +111 -0
  21. package/src/agent/persisted-lifecycle.ts +44 -4
  22. package/src/agent/persistence-policy/context.ts +13 -0
  23. package/src/agent/persistence-policy/resolver.ts +7 -0
  24. package/src/agent/persistence-policy/types.ts +1 -0
  25. package/src/agent/record-capture.ts +1 -0
  26. package/src/agent-adapter-registry.ts +33 -7
  27. package/src/agent-conversation-contracts.ts +14 -1
  28. package/src/agent-conversation-errors.ts +8 -0
  29. package/src/agent-conversation-owner.ts +9 -4
  30. package/src/agent-session-config.ts +135 -0
  31. package/src/agent-session.ts +439 -934
  32. package/src/agent.ts +73 -0
  33. package/src/capabilities.ts +2 -0
  34. package/src/checkpointing/recovery.ts +10 -0
  35. package/src/cli/index.ts +3 -3
  36. package/src/cli/managed.ts +2 -2
  37. package/src/client.ts +68 -98
  38. package/src/connection-attempt.ts +95 -0
  39. package/src/controller-connection.ts +114 -0
  40. package/src/controller.ts +156 -148
  41. package/src/conversation-controller/capabilities.ts +88 -0
  42. package/src/conversation-controller/contracts.ts +208 -0
  43. package/src/conversation-controller/factory.ts +39 -0
  44. package/src/conversation-controller/guards.ts +98 -0
  45. package/src/conversation-controller/index.ts +20 -0
  46. package/src/conversation-startup.ts +35 -0
  47. package/src/conversation-turns/backend-turns.ts +373 -0
  48. package/src/conversation-turns/clear-operations.ts +37 -0
  49. package/src/conversation-turns/context.ts +135 -0
  50. package/src/conversation-turns/index.ts +4 -0
  51. package/src/conversation-turns/record-helpers.ts +75 -0
  52. package/src/conversation-turns/recording.ts +235 -0
  53. package/src/conversation-turns/run-turn.ts +367 -0
  54. package/src/conversation-turns/turn-run.ts +57 -0
  55. package/src/errors.ts +41 -0
  56. package/src/handoff-options.ts +81 -0
  57. package/src/identity/checkpoint-backed.ts +1 -1
  58. package/src/index.ts +58 -3
  59. package/src/internal-inference/coordination/manager.ts +11 -0
  60. package/src/internal-inference/runtime/harness-runtime.ts +4 -4
  61. package/src/launcher.ts +35 -2
  62. package/src/media/parts.ts +5 -0
  63. package/src/message-status.ts +83 -0
  64. package/src/metering/engine.ts +39 -64
  65. package/src/metering/measurement-provenance.ts +36 -0
  66. package/src/metering/native/durability.ts +115 -0
  67. package/src/metering/native/ledger.ts +104 -0
  68. package/src/metering/native/operation.ts +85 -0
  69. package/src/metering/native/projection.ts +114 -0
  70. package/src/metering/native/proof.ts +51 -0
  71. package/src/metering/native/requirements.ts +10 -0
  72. package/src/metering/native/retirement.ts +92 -0
  73. package/src/metering/native/source.ts +90 -0
  74. package/src/metering/record.ts +38 -1
  75. package/src/metering/state.ts +13 -3
  76. package/src/native/approvals.ts +169 -0
  77. package/src/native/capabilities.ts +17 -0
  78. package/src/native/channel-changes.ts +211 -0
  79. package/src/native/connection.ts +56 -0
  80. package/src/native/controller.ts +591 -0
  81. package/src/native/delegation-sender.ts +26 -0
  82. package/src/native/errors.ts +35 -0
  83. package/src/native/functions.ts +156 -0
  84. package/src/native/host-config.ts +59 -0
  85. package/src/native/host.ts +909 -0
  86. package/src/native/item-receipts.ts +15 -0
  87. package/src/native/metering.ts +12 -0
  88. package/src/native/records.ts +166 -0
  89. package/src/native/recovery.ts +186 -0
  90. package/src/native/reminders/fixtures/schema21.sqlite.gz +0 -0
  91. package/src/native/reminders/idle.ts +70 -0
  92. package/src/native/reminders/limits.ts +19 -0
  93. package/src/native/reminders/notifications.ts +29 -0
  94. package/src/native/reminders/reminders.test.ts +553 -0
  95. package/src/native/reminders/routine-config.typecheck.ts +13 -0
  96. package/src/native/reminders/routine-guard.ts +66 -0
  97. package/src/native/reminders/routine-schedule.ts +25 -0
  98. package/src/native/reminders/routine-wire.ts +21 -0
  99. package/src/native/reminders/schedule.ts +97 -0
  100. package/src/native/reminders/service.ts +280 -0
  101. package/src/native/reminders/supervisor.ts +91 -0
  102. package/src/native/reminders/sync.ts +301 -0
  103. package/src/native/reminders/wire.ts +197 -0
  104. package/src/native/reminders/wire.typecheck.ts +13 -0
  105. package/src/native/submission-withdrawal.ts +65 -0
  106. package/src/native/usage.ts +15 -0
  107. package/src/native/worker-delivery.ts +61 -0
  108. package/src/native-harness/.res/README.md +1 -0
  109. package/src/native-harness/.res/architecture/README.md +21 -0
  110. package/src/native-harness/.res/architecture/context-and-data.md +31 -0
  111. package/src/native-harness/.res/architecture/execution.md +42 -0
  112. package/src/native-harness/.res/architecture/overview.md +44 -0
  113. package/src/native-harness/.res/architecture/persistence.md +56 -0
  114. package/src/native-harness/.res/architecture/suspend-and-resume.md +45 -0
  115. package/src/native-harness/.res/architecture/technical-architecture.md +50 -0
  116. package/src/native-harness/.res/decisions/0001-basic-loop.md +11 -0
  117. package/src/native-harness/.res/decisions/0002-channel-input.md +17 -0
  118. package/src/native-harness/.res/decisions/0003-inference-inspection.md +14 -0
  119. package/src/native-harness/.res/decisions/0004-shared-context.md +21 -0
  120. package/src/native-harness/.res/decisions/0005-notice-inbox.md +20 -0
  121. package/src/native-harness/.res/decisions/0006-explicit-notices.md +12 -0
  122. package/src/native-harness/.res/decisions/0007-channel-output.md +12 -0
  123. package/src/native-harness/.res/decisions/0008-browser-client.md +16 -0
  124. package/src/native-harness/.res/decisions/0009-scripted-model.md +18 -0
  125. package/src/native-harness/.res/decisions/0010-inprocess-protocol.md +19 -0
  126. package/src/native-harness/.res/decisions/0011-stdio-transport.md +21 -0
  127. package/src/native-harness/.res/decisions/0012-session-storage-contract.md +37 -0
  128. package/src/native-harness/.res/decisions/0013-durable-delivery-contract.md +64 -0
  129. package/src/native-harness/.res/decisions/0014-channel-controls-contract.md +73 -0
  130. package/src/native-harness/.res/decisions/0015-session-file-contract.md +72 -0
  131. package/src/native-harness/.res/decisions/0016-configuration-permissions.md +159 -0
  132. package/src/native-harness/.res/decisions/0017-openrouter-managed-config.md +69 -0
  133. package/src/native-harness/.res/decisions/0018-tool-dispatch-evidence.md +78 -0
  134. package/src/native-harness/.res/decisions/0019-model-execution.md +188 -0
  135. package/src/native-harness/.res/decisions/0020-startup-channel-changes.md +71 -0
  136. package/src/native-harness/.res/decisions/0021-tools-and-host-callbacks.md +100 -0
  137. package/src/native-harness/.res/decisions/0022-operator-controls.md +115 -0
  138. package/src/native-harness/.res/decisions/0023-long-running-mock.md +82 -0
  139. package/src/native-harness/.res/decisions/0024-callback-policy-names.md +46 -0
  140. package/src/native-harness/.res/decisions/0025-external-notices.md +364 -0
  141. package/src/native-harness/.res/decisions/0026-bounded-context.md +81 -0
  142. package/src/native-harness/.res/decisions/0027-development-instructions.md +22 -0
  143. package/src/native-harness/.res/decisions/0028-debug-tools.md +16 -0
  144. package/src/native-harness/.res/decisions/0029-bounded-model-call-pages.md +37 -0
  145. package/src/native-harness/.res/decisions/0030-timeline-retrieval.md +145 -0
  146. package/src/native-harness/.res/decisions/0031-one-off-reminders.md +173 -0
  147. package/src/native-harness/.res/docs/11-15.md +148 -0
  148. package/src/native-harness/.res/docs/BUSINESS_RULES.md +111 -0
  149. package/src/native-harness/.res/docs/WORK.md +65 -0
  150. package/src/native-harness/.res/docs/_/11-16-persistence/LOG.md +312 -0
  151. package/src/native-harness/.res/docs/_/11-16-persistence/PLAN.md +77 -0
  152. package/src/native-harness/.res/docs/_/11-16-persistence/SPEC.md +313 -0
  153. package/src/native-harness/.res/docs/_/11-19-channel-controls/LOG.md +160 -0
  154. package/src/native-harness/.res/docs/_/11-19-channel-controls/PLAN.md +89 -0
  155. package/src/native-harness/.res/docs/_/11-19-channel-controls/SPEC.md +135 -0
  156. package/src/native-harness/.res/docs/_/11-19-config-permissions/LOG.md +143 -0
  157. package/src/native-harness/.res/docs/_/11-19-config-permissions/PLAN.md +93 -0
  158. package/src/native-harness/.res/docs/_/11-19-config-permissions/SPEC.md +181 -0
  159. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/11-20-LOG.md +433 -0
  160. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PLAN.md +60 -0
  161. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PROTOCOL.md +141 -0
  162. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/SPEC.md +168 -0
  163. package/src/native-harness/.res/docs/attachments/0001-DESIGN/SPEC.md +111 -0
  164. package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/PLAN.md +129 -0
  165. package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/SPEC.md +135 -0
  166. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/LOG.md +437 -0
  167. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/PLAN.md +127 -0
  168. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/SPEC.md +203 -0
  169. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/LOG.md +292 -0
  170. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/PLAN.md +91 -0
  171. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/SPEC.md +187 -0
  172. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/LOG.md +148 -0
  173. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/PLAN.md +95 -0
  174. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/SPEC.md +200 -0
  175. package/src/native-harness/.res/docs/model-execution/0002-AMENDMENT-accounting/SPEC.md +80 -0
  176. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/LOG.md +206 -0
  177. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/PLAN.md +106 -0
  178. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/SPEC.md +297 -0
  179. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/LOG.md +41 -0
  180. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/PLAN.md +36 -0
  181. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/SPEC.md +84 -0
  182. package/src/native-harness/.res/docs/shell-execution/0001-DESIGN/SPEC.md +147 -0
  183. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/LOG.md +15 -0
  184. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/PLAN.md +107 -0
  185. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/SPEC.md +114 -0
  186. package/src/native-harness/.res/docs/todos/11-19-TODO-auto_review-approve.md +24 -0
  187. package/src/native-harness/.res/docs/todos/11-20-TODO-user-entered-tool-code.md +23 -0
  188. package/src/native-harness/.res/docs/todos/11-21-TODO-node-resource-coordination.md +103 -0
  189. package/src/native-harness/.res/docs/todos/11-22-TODO-harness-m1-sequence.md +50 -0
  190. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/LOG.md +337 -0
  191. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/PLAN.md +76 -0
  192. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/SPEC.md +204 -0
  193. package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/LOG.md +73 -0
  194. package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/SPEC.md +64 -0
  195. package/src/native-harness/.res/docs/tools-and-callbacks/0003-DESIGN-attachment-tools/SPEC.md +58 -0
  196. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/LOG.md +45 -0
  197. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/PLAN.md +108 -0
  198. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/SPEC.md +169 -0
  199. package/src/native-harness/.res/docs/web-tools/0001-DESIGN/SPEC.md +128 -0
  200. package/src/native-harness/.res/marketing-draft.md +22 -0
  201. package/src/native-harness/.res/sandbox/1-simple-harness/README.md +285 -0
  202. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-1.md +19 -0
  203. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-10.md +138 -0
  204. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-11.md +148 -0
  205. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-12.md +172 -0
  206. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-13.md +194 -0
  207. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-14.md +233 -0
  208. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-15.md +249 -0
  209. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-16.md +265 -0
  210. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-17.md +279 -0
  211. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-18.md +293 -0
  212. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-19.md +307 -0
  213. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-2.md +29 -0
  214. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-20.md +317 -0
  215. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-21.md +327 -0
  216. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-3.md +40 -0
  217. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-4.md +59 -0
  218. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-5.md +69 -0
  219. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-6.md +79 -0
  220. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-7.md +89 -0
  221. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-8.md +102 -0
  222. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-9.md +116 -0
  223. package/src/native-harness/.res/sandbox/1-simple-harness/conversation.jsonl +49 -0
  224. package/src/native-harness/.res/sandbox/1-simple-harness/doc.md +87 -0
  225. package/src/native-harness/.res/sandbox/1-simple-harness/harness.py +289 -0
  226. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 2.py +221 -0
  227. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 3.py +287 -0
  228. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy.py +165 -0
  229. package/src/native-harness/.res/sandbox/1-simple-harness/state.json +22 -0
  230. package/src/native-harness/.res/sandbox/1-simple-harness/system-prompt.md +2 -0
  231. package/src/native-harness/AGENTS.md +70 -0
  232. package/src/native-harness/ARCHITECTURE.md +249 -0
  233. package/src/native-harness/README.md +726 -0
  234. package/src/native-harness/bun.lock +26 -0
  235. package/src/native-harness/package.json +24 -0
  236. package/src/native-harness/src/capabilities/context/build.ts +59 -0
  237. package/src/native-harness/src/capabilities/context/instructions/agent-demo.md +11 -0
  238. package/src/native-harness/src/capabilities/context/instructions/agent.md +5 -0
  239. package/src/native-harness/src/capabilities/context/instructions/harness.md +7 -0
  240. package/src/native-harness/src/capabilities/context/load-instructions.ts +22 -0
  241. package/src/native-harness/src/capabilities/context/session.ts +92 -0
  242. package/src/native-harness/src/capabilities/model/attempt.ts +27 -0
  243. package/src/native-harness/src/capabilities/model/openrouter-stream.ts +72 -0
  244. package/src/native-harness/src/capabilities/model/openrouter.ts +62 -0
  245. package/src/native-harness/src/capabilities/model/runner.ts +116 -0
  246. package/src/native-harness/src/capabilities/model/scenario-attempt.ts +50 -0
  247. package/src/native-harness/src/capabilities/model/scenario-file.ts +125 -0
  248. package/src/native-harness/src/capabilities/model/scripted-error.ts +6 -0
  249. package/src/native-harness/src/capabilities/model/scripted.ts +81 -0
  250. package/src/native-harness/src/capabilities/model/usage.ts +15 -0
  251. package/src/native-harness/src/capabilities/tools/builtin/current-time.ts +28 -0
  252. package/src/native-harness/src/capabilities/tools/builtin/notify-channel.ts +17 -0
  253. package/src/native-harness/src/capabilities/tools/debug/index.ts +13 -0
  254. package/src/native-harness/src/capabilities/tools/debug/result.ts +12 -0
  255. package/src/native-harness/src/capabilities/tools/debug/test-echo.ts +16 -0
  256. package/src/native-harness/src/capabilities/tools/debug/test-fail.ts +14 -0
  257. package/src/native-harness/src/capabilities/tools/debug/test-wait.ts +19 -0
  258. package/src/native-harness/src/capabilities/tools/reminders/index.ts +75 -0
  259. package/src/native-harness/src/capabilities/tools/runtime/catalog.ts +103 -0
  260. package/src/native-harness/src/capabilities/tools/runtime/functions.ts +130 -0
  261. package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +48 -0
  262. package/src/native-harness/src/capabilities/tools/testing/echo.ts +18 -0
  263. package/src/native-harness/src/capabilities/tools/testing/record.ts +47 -0
  264. package/src/native-harness/src/capabilities/tools/timeline/index.ts +41 -0
  265. package/src/native-harness/src/client.ts +18 -0
  266. package/src/native-harness/src/contracts/agent.ts +105 -0
  267. package/src/native-harness/src/contracts/config-permissions.ts +47 -0
  268. package/src/native-harness/src/contracts/context.ts +112 -0
  269. package/src/native-harness/src/contracts/events.ts +47 -0
  270. package/src/native-harness/src/contracts/input-limits.ts +7 -0
  271. package/src/native-harness/src/contracts/inspection.ts +22 -0
  272. package/src/native-harness/src/contracts/loop.ts +31 -0
  273. package/src/native-harness/src/contracts/model-execution.ts +83 -0
  274. package/src/native-harness/src/contracts/operator-controls.ts +106 -0
  275. package/src/native-harness/src/contracts/output.ts +13 -0
  276. package/src/native-harness/src/contracts/protocol.ts +320 -0
  277. package/src/native-harness/src/contracts/reminders.ts +132 -0
  278. package/src/native-harness/src/contracts/scenario.ts +42 -0
  279. package/src/native-harness/src/contracts/session-file.ts +19 -0
  280. package/src/native-harness/src/contracts/session.ts +184 -0
  281. package/src/native-harness/src/contracts/storage.ts +596 -0
  282. package/src/native-harness/src/contracts/timeline-retrieval.ts +40 -0
  283. package/src/native-harness/src/contracts/tools.ts +133 -0
  284. package/src/native-harness/src/governance/permissions/gate.ts +129 -0
  285. package/src/native-harness/src/governance/policy/resolve.ts +32 -0
  286. package/src/native-harness/src/index.ts +318 -0
  287. package/src/native-harness/src/interfaces/cli/chat.ts +83 -0
  288. package/src/native-harness/src/interfaces/cli/development.ts +145 -0
  289. package/src/native-harness/src/interfaces/cli/format-reply.ts +27 -0
  290. package/src/native-harness/src/interfaces/cli/listeners.ts +74 -0
  291. package/src/native-harness/src/interfaces/cli/main.ts +47 -0
  292. package/src/native-harness/src/interfaces/cli/scenario.ts +37 -0
  293. package/src/native-harness/src/interfaces/cli/serve.ts +21 -0
  294. package/src/native-harness/src/interfaces/cli/start.ts +106 -0
  295. package/src/native-harness/src/interfaces/client.ts +225 -0
  296. package/src/native-harness/src/interfaces/inspector/index.html +283 -0
  297. package/src/native-harness/src/interfaces/inspector/observe.ts +35 -0
  298. package/src/native-harness/src/interfaces/inspector/server.ts +56 -0
  299. package/src/native-harness/src/interfaces/inspector/state.ts +92 -0
  300. package/src/native-harness/src/interfaces/protocol/channel-changes.ts +153 -0
  301. package/src/native-harness/src/interfaces/protocol/framing.ts +47 -0
  302. package/src/native-harness/src/interfaces/protocol/functions.ts +87 -0
  303. package/src/native-harness/src/interfaces/protocol/in-process.ts +67 -0
  304. package/src/native-harness/src/interfaces/protocol/live-queue.ts +55 -0
  305. package/src/native-harness/src/interfaces/protocol/load.ts +60 -0
  306. package/src/native-harness/src/interfaces/protocol/local.ts +120 -0
  307. package/src/native-harness/src/interfaces/protocol/operator.ts +120 -0
  308. package/src/native-harness/src/interfaces/protocol/output.ts +59 -0
  309. package/src/native-harness/src/interfaces/protocol/server.ts +517 -0
  310. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +119 -0
  311. package/src/native-harness/src/interfaces/protocol/stdio-server.ts +82 -0
  312. package/src/native-harness/src/interfaces/protocol/subscribe.ts +41 -0
  313. package/src/native-harness/src/interfaces/protocol/transfers.ts +146 -0
  314. package/src/native-harness/src/interfaces/web-chat/index.html +94 -0
  315. package/src/native-harness/src/interfaces/web-chat/server.ts +34 -0
  316. package/src/native-harness/src/kernel/channels.ts +405 -0
  317. package/src/native-harness/src/kernel/loop.ts +45 -0
  318. package/src/native-harness/src/runtime/config/development.ts +23 -0
  319. package/src/native-harness/src/runtime/config/managed.ts +2 -0
  320. package/src/native-harness/src/runtime/config/paths.ts +27 -0
  321. package/src/native-harness/src/runtime/reminder-timer.ts +42 -0
  322. package/src/native-harness/src/runtime/reminder-validation.ts +104 -0
  323. package/src/native-harness/src/runtime/reminders.ts +66 -0
  324. package/src/native-harness/src/state/storage/archive.ts +239 -0
  325. package/src/native-harness/src/state/storage/engine.ts +1013 -0
  326. package/src/native-harness/src/state/storage/inference.ts +124 -0
  327. package/src/native-harness/src/state/storage/memory-reminders.ts +78 -0
  328. package/src/native-harness/src/state/storage/memory.ts +341 -0
  329. package/src/native-harness/src/state/storage/policy-metadata.ts +32 -0
  330. package/src/native-harness/src/state/storage/reminder-archive.ts +63 -0
  331. package/src/native-harness/src/state/storage/reminder-change.ts +92 -0
  332. package/src/native-harness/src/state/storage/reminder-tables.ts +27 -0
  333. package/src/native-harness/src/state/storage/retrieval.ts +122 -0
  334. package/src/native-harness/src/state/storage/script-identity.ts +7 -0
  335. package/src/native-harness/src/state/storage/session-file.ts +85 -0
  336. package/src/native-harness/src/state/storage/sqlite-reminders.ts +134 -0
  337. package/src/native-harness/src/state/storage/sqlite.ts +625 -0
  338. package/src/native-harness/src/testing.ts +190 -0
  339. package/src/native-harness/src/util/config.ts +58 -0
  340. package/src/native-harness/src/util/json.ts +41 -0
  341. package/src/native-harness/src/util/message-position.ts +3 -0
  342. package/src/native-harness/src/util/reminder-schedule.ts +44 -0
  343. package/src/native-harness/src/util/schema.ts +40 -0
  344. package/src/native-harness/src/util/timeline-text.ts +72 -0
  345. package/src/native-harness/src/util/timeline-tool-names.ts +3 -0
  346. package/src/native-harness/test/agent.test.ts +130 -0
  347. package/src/native-harness/test/approval-gate.test.ts +255 -0
  348. package/src/native-harness/test/approval-protocol.test.ts +94 -0
  349. package/src/native-harness/test/boundaries.test.ts +18 -0
  350. package/src/native-harness/test/channel-controls.test.ts +322 -0
  351. package/src/native-harness/test/client-abort.test.ts +136 -0
  352. package/src/native-harness/test/config-policy.test.ts +301 -0
  353. package/src/native-harness/test/conformance/storage.ts +1141 -0
  354. package/src/native-harness/test/context.test.ts +177 -0
  355. package/src/native-harness/test/crash.test.ts +187 -0
  356. package/src/native-harness/test/debug-tools.test.ts +67 -0
  357. package/src/native-harness/test/development-cli.test.ts +67 -0
  358. package/src/native-harness/test/development.test.ts +171 -0
  359. package/src/native-harness/test/dispatch-evidence.test.ts +58 -0
  360. package/src/native-harness/test/e2e.test.ts +186 -0
  361. package/src/native-harness/test/external-notices.test.ts +101 -0
  362. package/src/native-harness/test/fixtures/approval-e2e.jsonl +4 -0
  363. package/src/native-harness/test/fixtures/crash-scenario.jsonl +5 -0
  364. package/src/native-harness/test/fixtures/development-lifecycle.jsonl +10 -0
  365. package/src/native-harness/test/fixtures/echo-scenario.jsonl +3 -0
  366. package/src/native-harness/test/fixtures/format2-schema.ts +27 -0
  367. package/src/native-harness/test/fixtures/format3-schema.ts +16 -0
  368. package/src/native-harness/test/fixtures/hold-scenario.jsonl +4 -0
  369. package/src/native-harness/test/fixtures/model-e2e.jsonl +3 -0
  370. package/src/native-harness/test/fixtures/storage-owner.ts +20 -0
  371. package/src/native-harness/test/format-reply.test.ts +10 -0
  372. package/src/native-harness/test/helpers/operator-view.ts +41 -0
  373. package/src/native-harness/test/helpers/scenario.ts +9 -0
  374. package/src/native-harness/test/helpers/session.ts +38 -0
  375. package/src/native-harness/test/helpers/stdio.ts +46 -0
  376. package/src/native-harness/test/inspector.test.ts +77 -0
  377. package/src/native-harness/test/listeners.test.ts +49 -0
  378. package/src/native-harness/test/loop.test.ts +88 -0
  379. package/src/native-harness/test/model-channel-double.test.ts +87 -0
  380. package/src/native-harness/test/model-crash.test.ts +62 -0
  381. package/src/native-harness/test/model-delivery-regressions.test.ts +55 -0
  382. package/src/native-harness/test/model-e2e.test.ts +71 -0
  383. package/src/native-harness/test/model-final-filter.test.ts +30 -0
  384. package/src/native-harness/test/model-large-reply.test.ts +28 -0
  385. package/src/native-harness/test/model-live-queue.test.ts +33 -0
  386. package/src/native-harness/test/model-runner.test.ts +117 -0
  387. package/src/native-harness/test/model-storage.test.ts +99 -0
  388. package/src/native-harness/test/model-stream-adapter.test.ts +26 -0
  389. package/src/native-harness/test/model-stream-public.test.ts +77 -0
  390. package/src/native-harness/test/notices.test.ts +64 -0
  391. package/src/native-harness/test/openrouter-config.test.ts +218 -0
  392. package/src/native-harness/test/operator-controls.test.ts +132 -0
  393. package/src/native-harness/test/output.test.ts +44 -0
  394. package/src/native-harness/test/owner-config.test.ts +64 -0
  395. package/src/native-harness/test/permissions-e2e.test.ts +68 -0
  396. package/src/native-harness/test/persistence.test.ts +236 -0
  397. package/src/native-harness/test/portability.test.ts +337 -0
  398. package/src/native-harness/test/protocol.test.ts +160 -0
  399. package/src/native-harness/test/reminder-clock.test.ts +61 -0
  400. package/src/native-harness/test/reminder-stdio.test.ts +140 -0
  401. package/src/native-harness/test/reminder-storage.test.ts +124 -0
  402. package/src/native-harness/test/scenario-jsonl.test.ts +112 -0
  403. package/src/native-harness/test/scripted.test.ts +92 -0
  404. package/src/native-harness/test/session-file.test.ts +51 -0
  405. package/src/native-harness/test/startup-channel-changes.test.ts +256 -0
  406. package/src/native-harness/test/stdio.test.ts +132 -0
  407. package/src/native-harness/test/storage-memory.test.ts +4 -0
  408. package/src/native-harness/test/storage-sqlite.test.ts +420 -0
  409. package/src/native-harness/test/suspension.test.ts +430 -0
  410. package/src/native-harness/test/timeline-retrieval.test.ts +211 -0
  411. package/src/native-harness/test/tools-catalog.test.ts +468 -0
  412. package/src/native-harness/test/tools-protocol.test.ts +418 -0
  413. package/src/native-harness/test/transfers.test.ts +94 -0
  414. package/src/native-harness/test/web-chat.test.ts +35 -0
  415. package/src/native-harness/tsconfig.json +20 -0
  416. package/src/observation/agent-event-bus.ts +44 -18
  417. package/src/observation/index.ts +1 -0
  418. package/src/operations/contracts.ts +11 -3
  419. package/src/operations/errors.ts +5 -0
  420. package/src/operations/stale-policy.ts +1 -1
  421. package/src/operations/supervisor.ts +34 -10
  422. package/src/orchestrator/acp-delivery.ts +68 -0
  423. package/src/orchestrator/assignments.ts +27 -0
  424. package/src/orchestrator/busy.ts +15 -0
  425. package/src/orchestrator/config.ts +41 -0
  426. package/src/orchestrator/consumer-api.ts +24 -0
  427. package/src/orchestrator/contracts.ts +71 -0
  428. package/src/orchestrator/durable-assignments.ts +111 -0
  429. package/src/orchestrator/native-delegation.ts +103 -0
  430. package/src/orchestrator/orchestrator.ts +318 -0
  431. package/src/orchestrator/permissions.ts +25 -0
  432. package/src/orchestrator/policy.ts +44 -0
  433. package/src/orchestrator/pool.ts +123 -0
  434. package/src/orchestrator/tool-descriptions.ts +11 -0
  435. package/src/permissions/acp.ts +18 -0
  436. package/src/permissions/arrival.ts +13 -0
  437. package/src/permissions/consumer-config.ts +19 -0
  438. package/src/permissions/conversation.ts +280 -0
  439. package/src/permissions/matcher.ts +85 -0
  440. package/src/permissions/outcome.ts +15 -0
  441. package/src/permissions/policy.ts +81 -0
  442. package/src/permissions/request.ts +26 -0
  443. package/src/persistence/activity-projection.ts +1 -0
  444. package/src/persistence/backend.ts +34 -1
  445. package/src/persistence/channels.ts +23 -0
  446. package/src/persistence/index.ts +4 -0
  447. package/src/persistence/protocol-method.ts +5 -0
  448. package/src/persistence/reminder-wake.ts +49 -0
  449. package/src/persistence/reminders.ts +385 -0
  450. package/src/persistence/sqlite-backend.ts +84 -6
  451. package/src/persistence/sqlite-channels.ts +65 -0
  452. package/src/persistence/sqlite-reminders.ts +85 -0
  453. package/src/persistence/sqlite-schema.ts +108 -3
  454. package/src/persistence/sqlite-worker-delivery.ts +374 -0
  455. package/src/persistence/sqlite-workers.ts +59 -0
  456. package/src/persistence/worker-delivery-contract.ts +104 -0
  457. package/src/persistence/worker-terminal-reason.ts +29 -0
  458. package/src/persistence/workers.ts +19 -0
  459. package/src/provider-notices.ts +137 -0
  460. package/src/repl/commands.ts +2 -2
  461. package/src/steering/combine.ts +3 -1
  462. package/src/steering/contracts.ts +11 -2
  463. package/src/steering/controller.ts +3 -2
  464. package/src/transport/acp-transport.ts +24 -14
  465. package/src/types.ts +15 -12
  466. package/src/updates.ts +14 -2
  467. package/src/wire-log.ts +1 -1
@@ -0,0 +1,171 @@
1
+ import { afterAll, expect, test } from "bun:test";
2
+ import { mkdtempSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { openDevelopment } from "../src/interfaces/cli/development.ts";
6
+ import { serveInspector } from "../src/interfaces/inspector/server.ts";
7
+ import { controlLocal, sendLocal, serveLocal } from "../src/interfaces/protocol/local.ts";
8
+ import { composeSystemPrompt } from "../src/capabilities/context/load-instructions.ts";
9
+ import { buildSharedContext } from "../src/capabilities/context/build.ts";
10
+ import { ask, turnsEnd } from "./helpers/session.ts";
11
+
12
+ const root = mkdtempSync(join(tmpdir(), "harness-dev-"));
13
+ afterAll(() => rmSync(root, { recursive: true, force: true }));
14
+ const script = new URL("./fixtures/development-lifecycle.jsonl", import.meta.url).pathname;
15
+ const systemPrompt = "Development test system";
16
+ function holdTool(wait: () => Promise<void>) {
17
+ return {
18
+ tools: [{ name: "test_hold", description: "Wait until the test releases the turn.", parameters: { type: "object" } }],
19
+ async executeTool() { await wait(); return JSON.stringify({ ok: true }); },
20
+ };
21
+ }
22
+ async function until(check: () => boolean, what: string) {
23
+ for (let i = 0; i < 400; i++) { if (check()) return; await new Promise(resolve => setTimeout(resolve, 5)); }
24
+ throw new Error(`Timed out waiting for ${what}`);
25
+ }
26
+
27
+ test("a reopened development session shows its restored timeline and status in the inspector before any new message", async () => {
28
+ const database = join(mkdtempSync(join(root, "db-")), "session.sqlite");
29
+ await expect(openDevelopment({ systemPrompt, database, script })).rejects.toThrow("Pass --create");
30
+ const first = await openDevelopment({ systemPrompt, database, create: true, script, scriptedTools: holdTool(async () => {}) });
31
+ first.session.start();
32
+ expect(await ask(first.session, { channelId: "channel2", participantId: "bob", text: "Hi, I am Bob" })).toBe("Hello Bob.");
33
+ // Alice's channel notifies Bob's, which answers in a notice-started turn.
34
+ const noticed = turnsEnd(first.session, 2);
35
+ first.local.agent.send({ channelId: "channel1", participantId: "alice", text: "Send the verification notice to Bob" });
36
+ await noticed.done;
37
+ const before = first.inspection.status();
38
+ const liveBefore = first.inspection.liveContext();
39
+ const callsBefore = before.channels.map(channel => first.inspection.modelCalls(channel.id).modelCalls);
40
+ expect(before.session).toMatchObject({ storage: database, lifecycle: "running", execution: "idle" });
41
+ first.close();
42
+ await expect(openDevelopment({ systemPrompt, database, create: true, script })).rejects.toThrow("already_exists");
43
+
44
+ const second = await openDevelopment({ systemPrompt, database, script, scriptedTools: holdTool(async () => {}) });
45
+ const server = serveInspector(second.inspection, 0);
46
+ try {
47
+ // Nothing has been sent, started or resumed in this process.
48
+ const state = second.inspection.status();
49
+ const live = second.inspection.liveContext();
50
+ expect(live.entries).toEqual(liveBefore.entries);
51
+ expect(live.entries.map(entry => `${entry.channelId}:${entry.message.role}`).sort()).toEqual([
52
+ "channel1:assistant", "channel1:assistant", "channel1:tool", "channel1:user", "channel2:assistant", "channel2:assistant", "channel2:user", "channel2:user"]);
53
+ expect(live.base).toEqual(buildSharedContext(second.session.store.snapshot(), composeSystemPrompt(systemPrompt)));
54
+ expect(live.base[1]!.content).toContain("Verification notice from channel1.");
55
+ expect(state.channels.map(channel => [channel.id, channel.pending, channel.running])).toEqual([
56
+ ["channel2", 0, false], ["channel1", 0, false]]);
57
+ expect(state.session).toMatchObject({ storage: database, sessionId: "development", lifecycle: "running", execution: "idle", revision: before.session.revision });
58
+ const calls = state.channels.map(channel => second.inspection.modelCalls(channel.id).modelCalls);
59
+ expect(calls).toEqual(callsBefore);
60
+ expect(calls.flat().every(call => call.outcome === "succeeded")).toBe(true);
61
+ // The served page data is the same restored state.
62
+ expect(await (await fetch(new URL("/state", server.url))).json()).toEqual(state);
63
+ expect((await (await fetch(server.url)).text())).toContain("session ' + session.lifecycle");
64
+ // New work continues the same session: IDs and each channel's script carry on.
65
+ second.session.start();
66
+ expect(await ask(second.session, { channelId: "channel2", participantId: "bob", text: "Anything new?" })).toBe("Bob, I received your later message.");
67
+ expect(second.session.snapshot().turns.map(turn => turn.turnId)).toEqual([1, 2, 3, 4]);
68
+ } finally { await server.stop(true); second.close(); }
69
+ });
70
+
71
+ test("development startup controls: suspend over the local socket, reopen paused, inspect, then resume", async () => {
72
+ const directory = mkdtempSync(join(root, "db-")), database = join(directory, "session.sqlite"), socket = join(directory, "agent.sock");
73
+ let releaseHold!: () => void;
74
+ const holdGate = new Promise<void>(resolve => { releaseHold = resolve; });
75
+ let waits = 0;
76
+ const first = await openDevelopment({ systemPrompt, database, create: true, script, scriptedTools: holdTool(() => { waits++; return holdGate; }) });
77
+ first.session.start();
78
+ const firstServer = serveLocal(first.local, socket, undefined, first.session);
79
+ try {
80
+ expect(await sendLocal(socket, { channelId: "channel2", participantId: "bob", text: "Hi" })).toBe("Hello Bob.");
81
+ expect(await sendLocal(socket, { channelId: "channel1", participantId: "alice", text: "Tell Bob" })).toBe("Test: the harness accepted the notice for Bob’s channel.");
82
+ await until(() => first.session.agent.idle(), "notice turn");
83
+ // A test callback is running when suspension is requested.
84
+ const working = sendLocal(socket, { channelId: "channel1", participantId: "alice", text: "Run the hold tool" }).then(() => "answered", error => String(error));
85
+ await until(() => waits === 1, "test callback to start");
86
+ expect(await controlLocal(socket, "status")).toMatchObject({ lifecycle: "running", execution: "working" });
87
+ const suspending = controlLocal(socket, "suspend");
88
+ await until(() => first.inspection.status().session!.lifecycle === "suspending", "suspension to begin");
89
+ await expect(sendLocal(socket, { channelId: "channel2", participantId: "bob", text: "too late" })).rejects.toThrow("not admitted");
90
+ releaseHold();
91
+ expect(await suspending).toMatchObject({ lifecycle: "suspended", execution: "suspended" });
92
+ expect(first.inspection.status().channels.find(channel => channel.id === "channel1")).toMatchObject({ turn: "suspended", running: false });
93
+ // The request held for that turn is released rather than left open across the suspension.
94
+ expect(await working).toContain("suspended before this turn finished");
95
+ } finally { await firstServer.stop(true); first.session.stop("test shutdown"); first.close(); }
96
+
97
+ // Reopened without --resume: paused, fully visible, and inert.
98
+ const second = await openDevelopment({ systemPrompt, database, script, scriptedTools: holdTool(async () => { waits++; }) });
99
+ const secondServer = serveLocal(second.local, socket, undefined, second.session);
100
+ try {
101
+ second.session.start();
102
+ const state = second.inspection.status();
103
+ expect(state.session).toMatchObject({ lifecycle: "suspended", execution: "suspended" });
104
+ expect(state.channels.find(channel => channel.id === "channel1")).toMatchObject({ turn: "suspended", running: false, pending: 0 });
105
+ expect(second.inspection.liveContext().entries.at(-1)).toMatchObject({ channelId: "channel1", message: { role: "tool", callId: "hold-1" } });
106
+ await new Promise(resolve => setTimeout(resolve, 50));
107
+ expect(second.inspection.status()).toEqual(state);
108
+ expect(state.channels.every(channel => second.inspection.channel(channel.id).requests.length === 0)).toBe(true);
109
+ await expect(sendLocal(socket, { channelId: "channel2", participantId: "bob", text: "still paused" })).rejects.toThrow("not admitted");
110
+ // Explicit resume continues the checkpointed turn without repeating the test callback.
111
+ const ended = turnsEnd(second.session);
112
+ expect(await controlLocal(socket, "resume")).toMatchObject({ lifecycle: "running" });
113
+ const events = await ended.done;
114
+ expect(events.map(event => event.event.type)).toEqual(["turn_resumed", "message_completed", "turn_ended"]);
115
+ expect(waits).toBe(1);
116
+ expect(second.inspection.status().session).toMatchObject({ lifecycle: "running", execution: "idle" });
117
+ expect(await sendLocal(socket, { channelId: "channel2", participantId: "bob", text: "back?" })).toBe("Bob, I received your later message.");
118
+ await expect(fetch("http://localhost/session?action=delete", { unix: socket, method: "POST" }).then(response => response.status)).resolves.toBe(400);
119
+ } finally { await secondServer.stop(true); second.close(); }
120
+ }, 15000);
121
+
122
+ test("a process that ends without suspending reopens with its unfinished turn shown as interrupted, not retried", async () => {
123
+ const database = join(mkdtempSync(join(root, "db-")), "session.sqlite");
124
+ let waits = 0;
125
+ const first = await openDevelopment({ systemPrompt, database, create: true, script: new URL("./fixtures/development-lifecycle.jsonl", import.meta.url).pathname,
126
+ scriptedTools: holdTool(() => { waits++; return new Promise(() => {}); }) });
127
+ first.session.start();
128
+ await ask(first.session, { channelId: "channel2", participantId: "bob", text: "Hi" });
129
+ await ask(first.session, { channelId: "channel1", participantId: "alice", text: "Tell Bob" });
130
+ await until(() => first.session.agent.idle(), "notice turn");
131
+ first.local.agent.send({ channelId: "channel1", participantId: "alice", text: "Run the hold tool" });
132
+ await until(() => waits === 1, "test callback to start");
133
+ // Closing storage with a tool in flight is what an abrupt exit leaves behind.
134
+ first.close();
135
+
136
+ const second = await openDevelopment({ systemPrompt, database, script, scriptedTools: holdTool(async () => { waits++; }) });
137
+ try {
138
+ const channel = second.inspection.status().channels.find(candidate => candidate.id === "channel1")!;
139
+ expect(channel).toMatchObject({ running: false, unresolved: { status: "interrupted", uncertainCallIds: ["hold-1"] } });
140
+ expect(channel.error).toContain("interrupted");
141
+ expect(second.inspection.liveContext().base[1]!.content).toContain('"uncertainToolCalls":["hold-1"]');
142
+ second.session.start();
143
+ await new Promise(resolve => setTimeout(resolve, 30));
144
+ expect(waits).toBe(1);
145
+ expect(second.session.agent.idle()).toBe(true);
146
+ } finally { second.close(); }
147
+ });
148
+
149
+ test("opted-in Channels diagnostics annotate the actual scripted request with its context revision", async () => {
150
+ const development = await openDevelopment({ systemPrompt, script, environment: { HARNESS_CAPTURE_SCRIPT_REQUESTS: "1" } });
151
+ try {
152
+ development.session.start();
153
+ await ask(development.session, { channelId: "channel2", participantId: "bob", text: "Hello" });
154
+ const snapshot = development.inspection.status();
155
+ const request = development.inspection.channel("channel2").requests[0]!;
156
+ expect(request.context!.revision).toBeLessThan(snapshot.session!.revision);
157
+ expect(request.context!.estimatedInputBytes).toBeGreaterThan(0);
158
+ expect(request.context!.records).toMatchObject({ included: expect.any(Array), trimmed: [] });
159
+ const modelCall = development.inspection.modelCalls("channel2").modelCalls[0]!;
160
+ expect(request.context!.modelCallId).toBe(modelCall.callId);
161
+ expect(modelCall.attempts[0]?.outcome).toBe("succeeded");
162
+ expect(request.context!.omitted).toEqual({ active: 0, local: 0, shared: 0 });
163
+ const preview = development.inspection.liveContext().base[0];
164
+ expect(preview?.content).toBe(composeSystemPrompt(systemPrompt));
165
+ expect((request.body as { messages: unknown[] }).messages[0]).toEqual(preview);
166
+ expect(request.body).toMatchObject({
167
+ messages: expect.arrayContaining([{ role: "user", content: 'Participant: "bob"\n\nHello' }]),
168
+ tools: expect.any(Array),
169
+ });
170
+ } finally { development.close(); }
171
+ });
@@ -0,0 +1,58 @@
1
+ import { expect, test } from "bun:test";
2
+ import { mkdtempSync, rmSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import { createMemoryStorageAdapter } from "../src/state/storage/memory.ts";
6
+ import { createSqliteStorageAdapter } from "../src/state/storage/sqlite.ts";
7
+
8
+ for (const kind of ["memory", "sqlite"] as const) test(`${kind}: dispatch evidence fences duplicates and distinguishes uncertain effects`, () => {
9
+ const dir = mkdtempSync(join(tmpdir(), "dispatch-evidence-"));
10
+ try {
11
+ const adapter = kind === "memory" ? createMemoryStorageAdapter() : createSqliteStorageAdapter(join(dir, "db.sqlite"));
12
+ const identity = { sessionId: "s", compatibilityKey: "k" };
13
+ const must = <T>(r: { ok: true; value: T } | { ok: false; error: { message: string } }) => { if (!r.ok) throw new Error(r.error.message); return r.value; };
14
+ const s = must(adapter.open({ mode: "create", identity }));
15
+ must(s.acceptItem({ kind: "participant_message", channelId: "a", senderId: "u", text: "hello", itemId: "m" }));
16
+ const turn = must(s.beginTurn("a"))!.turn.turnId;
17
+ must(s.appendMessage(turn, { role: "assistant", content: null, calls: [{ id: "a", name: "t", arguments: "{}" }, { id: "b", name: "t", arguments: "{}" }] }));
18
+ expect(must(s.snapshot()).turns[0]!.state).toMatchObject({ status: "running", dispatchedCallIds: [] });
19
+ must(s.markToolDispatched(turn, "a")); const before = must(s.snapshot());
20
+ expect(s.markToolDispatched(turn, "a")).toMatchObject({ ok: false });
21
+ expect(s.markToolDispatched(turn, "missing")).toMatchObject({ ok: false });
22
+ expect(must(s.snapshot())).toEqual(before);
23
+ s.close();
24
+ const recovered = must(adapter.open({ mode: "open", identity }));
25
+ expect(must(recovered.snapshot()).turns[0]!.state).toMatchObject({ status: "interrupted", uncertainCallIds: ["a"] });
26
+ recovered.close();
27
+ } finally { rmSync(dir, { recursive: true, force: true }); }
28
+ });
29
+
30
+ for (const kind of ["memory", "sqlite"] as const) test(`${kind}: import validates dispatch evidence and legacy resumed calls start a fresh list`, () => {
31
+ const dir = mkdtempSync(join(tmpdir(), "dispatch-import-"));
32
+ try {
33
+ const create = (name: string) => kind === "memory" ? createMemoryStorageAdapter() : createSqliteStorageAdapter(join(dir, name));
34
+ const adapter = create("source"), identity = { sessionId: "s", compatibilityKey: "k" };
35
+ const must = <T>(r: { ok: true; value: T } | { ok: false; error: { message: string } }) => { if (!r.ok) throw new Error(r.error.message); return r.value; };
36
+ const s = must(adapter.open({ mode: "create", identity }));
37
+ must(s.acceptItem({ kind: "participant_message", channelId: "a", senderId: "u", text: "hello", itemId: "m" }));
38
+ const turn = must(s.beginTurn("a"))!.turn.turnId;
39
+ must(s.appendMessage(turn, { role: "assistant", content: null, calls: [{ id: "one", name: "t", arguments: "{}" }] }));
40
+ must(s.markToolDispatched(turn, "one")); must(s.appendMessage(turn, { role: "tool", callId: "one", content: "ok" }));
41
+ expect(s.markToolDispatched(turn, "one")).toMatchObject({ ok: false });
42
+ must(s.beginChannelSuspend("a")); must(s.checkpointTurn(turn)); must(s.beginSuspend()); must(s.completeSuspend());
43
+ const archive = must(s.exportArchive()); s.close();
44
+ for (const invalid of [["one", "one"], [""], ["foreign"]]) {
45
+ const copy = structuredClone(archive), state = copy.snapshot.turns[0]!.state as { dispatchedCallIds?: string[] };
46
+ state.dispatchedCallIds = invalid;
47
+ expect(create(`bad-${invalid.join("-")}`).importArchive(copy)).toMatchObject({ ok: false, error: { code: "invalid_archive" } });
48
+ }
49
+ const missingResult = structuredClone(archive); missingResult.snapshot.timeline = missingResult.snapshot.timeline.filter(entry => entry.message.role !== "tool");
50
+ expect(create("bad-unanswered").importArchive(missingResult)).toMatchObject({ ok: false, error: { code: "invalid_archive" } });
51
+ const legacy = structuredClone(archive); delete (legacy.snapshot.turns[0]!.state as { dispatchedCallIds?: string[] }).dispatchedCallIds;
52
+ const destination = create("legacy"); must(destination.importArchive(legacy)); const reopened = must(destination.open({ mode: "open", identity }));
53
+ must(reopened.resume()); must(reopened.resumeChannel("a"));
54
+ must(reopened.appendMessage(turn, { role: "assistant", content: null, calls: [{ id: "two", name: "t", arguments: "{}" }] }));
55
+ expect(must(reopened.snapshot()).turns[0]!.state).toMatchObject({ status: "running", dispatchedCallIds: [] });
56
+ reopened.close();
57
+ } finally { rmSync(dir, { recursive: true, force: true }); }
58
+ });
@@ -0,0 +1,186 @@
1
+ import { inspectOperatorView } from "./helpers/operator-view.ts";
2
+ import { afterAll, expect, test } from "bun:test";
3
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import type { ChannelEvent, CreateParams, ProtocolConfig } from "../src/client.ts";
7
+ import { spawnHarness } from "./helpers/stdio.ts";
8
+
9
+ // The two end-to-end scenarios of the persistence spec. Everything goes through
10
+ // the public client (src/client.ts) to real `serve --stdio --home` child
11
+ // processes with SQLite sessions and scripted models; no provider key is used.
12
+ const root = mkdtempSync(join(tmpdir(), "harness-e2e-"));
13
+ afterAll(() => rmSync(root, { recursive: true, force: true }));
14
+ const fixture = (name: string) => new URL(`./fixtures/${name}`, import.meta.url).pathname;
15
+ const push = (channel: string, id: string, text: string) => ({ channel, item: { id, kind: "user_message" as const, sender: `user-${channel}`, content: [{ type: "text" as const, text }] } });
16
+ const lines = (path: string) => existsSync(path) ? readFileSync(path, "utf8").split("\n").filter(Boolean) : [];
17
+ async function until(check: () => boolean | Promise<boolean>, what: string) {
18
+ for (let i = 0; i < 600; i++) { if (await check()) return; await new Promise(resolve => setTimeout(resolve, 5)); }
19
+ throw new Error(`Timed out waiting for ${what}`);
20
+ }
21
+ function watch(harness: ReturnType<typeof spawnHarness>) {
22
+ const events: ChannelEvent[] = [];
23
+ harness.client.onChannelEvent(event => { events.push(event); });
24
+ return events;
25
+ }
26
+ const texts = (events: ChannelEvent[]) => events.flatMap(event => event.event.type === "message_completed" ? [event.event.parts![0]!.text] : []);
27
+ const taken = (events: ChannelEvent[]) => events.flatMap(({ event }) => event.type === "turn_started" || event.type === "turn_took" ? event.items.map(item => `${item}@${event.turnId}`) : []);
28
+
29
+ test("crash during individual suspension reopens the channel and preserves pending input", async () => {
30
+ const config: ProtocolConfig = { version: 1, system: "Crash during channel suspension", model: { protocol: "scripted", script: fixture("hold-scenario.jsonl") }, defaultPolicy: "__legacy_allow", policies: { __legacy_allow: { fallback: "allow", tools: {} } } };
31
+ const home = mkdtempSync(join(root, "channel-crash-")), effects = join(home, "effects.log");
32
+ const first = spawnHarness({ home, effects, fault: "beginChannelSuspend:1" });
33
+ await first.client.initialize(); await first.client.createSession({ sessionId: "crash", config, participants: [], channels: {} });
34
+ await first.client.push(push("a", "a1", "start"));
35
+ await until(() => lines(effects).includes("start:k"), "tool start");
36
+ await first.client.push(push("a", "a2", "pending"));
37
+ void first.client.suspendChannel({ channel: "a" }).catch(() => {});
38
+ expect(await first.child.exited).not.toBe(0);
39
+ first.client.close();
40
+ const second = spawnHarness({ home, effects });
41
+ try {
42
+ await second.client.initialize();
43
+ const loaded = await inspectOperatorView(second.client, { sessionId: "crash", config });
44
+ expect(loaded.status.channels).toMatchObject([{ channel: "a", lifecycle: "open" }]);
45
+ expect(loaded.turns[0]).toMatchObject({ turnId: "1", state: "interrupted", items: ["a1"], uncertainCalls: ["hold-1"] });
46
+ expect(loaded.items.find(item => item.id === "a2")).toBeDefined();
47
+ await second.client.push(push("a", "a3", "new work"));
48
+ } finally { await second.close(); }
49
+ }, 20000);
50
+
51
+ test("clean relocation: suspend with a tool running, export, import into a fresh home, verify, then resume exactly once", async () => {
52
+ const config: ProtocolConfig = { version: 1, system: "Relocation system", model: { protocol: "scripted", script: fixture("hold-scenario.jsonl") }, defaultPolicy: "__legacy_allow", policies: { __legacy_allow: { fallback: "allow", tools: {} } } };
53
+ const setup: CreateParams = { sessionId: "office", participants: [], channels: {}, config };
54
+ const effects = join(mkdtempSync(join(root, "fx-")), "effects.log");
55
+ const sourceHome = mkdtempSync(join(root, "source-")), destinationHome = mkdtempSync(join(root, "destination-"));
56
+
57
+ // Source process: two channels working, input accepted mid-tool, clean suspension, export.
58
+ const source = spawnHarness({ home: sourceHome, effects });
59
+ const sourceEvents = watch(source);
60
+ await source.client.initialize(); await source.client.createSession(setup);
61
+ await Promise.all([source.client.push(push("a", "a1", "start a")), source.client.push(push("b", "b1", "start b"))]);
62
+ await until(() => lines(effects).filter(line => line === "start:k").length === 2, "both tools to start");
63
+ expect(await source.client.push(push("a", "a2", "arrived while the tool ran"))).toMatchObject({ duplicate: false, item: { milestone: "received" } });
64
+ const suspending = source.client.suspend();
65
+ await until(async () => (await source.client.status()).lifecycle === "suspending", "suspension to begin");
66
+ writeFileSync(`${effects}.release-k`, "");
67
+ expect(await suspending).toMatchObject({ lifecycle: "suspended" });
68
+ const sourceView = await inspectOperatorView(source.client, { sessionId: "office", config });
69
+ const archive = await source.client.exportArchive();
70
+ // Stop the source before the copy runs anywhere. Closing stdin is stop; a suspended session keeps its checkpoints.
71
+ await source.close();
72
+ expect(taken(sourceEvents).sort()).toEqual(["a1@1", "b1@2"]);
73
+ expect(lines(effects).sort()).toEqual(["done:k", "done:k", "start:k", "start:k"]);
74
+
75
+ // Destination process: a fresh home on the same machine stands in for another host.
76
+ const destination = spawnHarness({ home: destinationHome, effects });
77
+ const events = watch(destination);
78
+ try {
79
+ await destination.client.initialize();
80
+ await expect(destination.client.openSession({ sessionId: "office", config })).rejects.toMatchObject({ code: "not_found" });
81
+ expect(await destination.client.importArchive(archive)).toMatchObject({ sessionId: "office", lifecycle: "suspended" });
82
+ const loaded = await inspectOperatorView(destination.client, { sessionId: "office", config });
83
+ // Verified before resuming: the same timeline messages, turn IDs and pending input as the source.
84
+ expect(loaded).toEqual(sourceView);
85
+ expect(loaded.status).toMatchObject({ lifecycle: "suspended", execution: "suspended" });
86
+ expect(loaded.turns).toMatchObject([{ turnId: "1", channel: "a", state: "suspended", items: ["a1"] }, { turnId: "2", channel: "b", state: "suspended", items: ["b1"] }]);
87
+ expect(loaded.messages.map(message => [message.channel, message.turnId, message.parts![0]!.text]).sort()).toEqual([["a", "1", "Working."], ["b", "2", "Working."]]);
88
+ expect(loaded.items.find(item => item.id === "a2")).toMatchObject({ milestone: "received", channel: "a" });
89
+ expect(loaded.status.channels.find(channel => channel.channel === "a")!.pending).toEqual(["a2"]);
90
+ await new Promise(resolve => setTimeout(resolve, 150));
91
+ expect(events).toEqual([]);
92
+
93
+ await destination.client.resume();
94
+ await until(() => events.filter(event => event.event.type === "turn_ended").length === 2, "both resumed turns");
95
+ // The pending input reached exactly one turn, in exactly one process.
96
+ expect(taken(events)).toEqual(["a2@1"]);
97
+ expect([...taken(sourceEvents), ...taken(events)].filter(entry => entry.startsWith("a2@"))).toEqual(["a2@1"]);
98
+ expect(events.filter(event => event.event.type === "turn_ended").map(event => event.event.type === "turn_ended" && event.event.outcome)).toEqual(["completed", "completed"]);
99
+ expect(texts(events).sort()).toEqual(["Finished.", "Finished."]);
100
+ // The completed tool calls ran once across both processes.
101
+ expect(events.filter(event => event.event.type === "tool_call")).toEqual([]);
102
+ expect(lines(effects).sort()).toEqual(["done:k", "done:k", "start:k", "start:k"]);
103
+ const after = await inspectOperatorView(destination.client, { sessionId: "office", config });
104
+ expect(after.turns).toMatchObject([{ turnId: "1", state: "completed", items: ["a1", "a2"] }, { turnId: "2", state: "completed", items: ["b1"] }]);
105
+ expect(after.items.map(item => [item.id, item.milestone, item.turnId])).toEqual([["a1", "seen", "1"], ["b1", "seen", "2"], ["a2", "seen", "1"]]);
106
+ expect(after.status).toMatchObject({ lifecycle: "running", execution: "idle" });
107
+ } finally { await destination.close(); }
108
+ }, 30000);
109
+
110
+ test("crash recovery: kills on both sides of take, a tool effect without a result and a missed reply are all reported, and nothing is replayed", async () => {
111
+ const config: ProtocolConfig = { version: 1, system: "Recovery system", model: { protocol: "scripted", script: fixture("crash-scenario.jsonl") }, defaultPolicy: "__legacy_allow", policies: { __legacy_allow: { fallback: "allow", tools: {} } } };
112
+ const setup: CreateParams = { sessionId: "ledger", participants: [], channels: {}, config };
113
+ const home = mkdtempSync(join(root, "crash-")), effects = join(home, "effects.log");
114
+ const all: ChannelEvent[] = [];
115
+ /** One process lifetime: optional load, one action, and (when a fault is set) death at that exact commit. */
116
+ async function life(fault: string | undefined, act: (harness: ReturnType<typeof spawnHarness>, loaded: Awaited<ReturnType<typeof inspectOperatorView>> | undefined, events: ChannelEvent[]) => Promise<void>, create = false) {
117
+ const harness = spawnHarness({ home, effects, fault });
118
+ const events = watch(harness);
119
+ try {
120
+ await harness.client.initialize();
121
+ const loaded = create ? (await harness.client.createSession(setup), undefined) : fault === "tool:1"
122
+ ? (expect(await harness.client.openSession({ sessionId: "ledger", config })).toMatchObject({ lifecycle: "running" }), undefined)
123
+ : await inspectOperatorView(harness.client, { sessionId: "ledger", config });
124
+ await act(harness, loaded, events);
125
+ if (fault) expect(await harness.child.exited).not.toBe(0);
126
+ } finally { all.push(...events); if (fault) harness.client.close(); else await harness.close(); }
127
+ }
128
+
129
+ // 1. Killed right after the input is accepted, before any turn takes it.
130
+ await life("acceptItem:1", async harness => { void harness.client.push(push("a", "m1", "record this")).catch(() => {}); }, true);
131
+
132
+ // 2. The input is still pending and runs. Killed after the tool's external effect, before its result commits.
133
+ await life("tool:1", async () => {});
134
+ expect(lines(effects)).toEqual(["effect"]);
135
+
136
+ // 3. The effect is reported uncertain and not replayed. A fresh message is answered, but the process
137
+ // is killed after that reply commits and before the client receives it.
138
+ await life("commitResponse:1", async (harness, loaded, events) => {
139
+ expect(loaded!.turns).toMatchObject([{ turnId: "1", state: "interrupted", items: ["m1"], uncertainCalls: ["rec-1"] }]);
140
+ expect(loaded!.items).toMatchObject([{ id: "m1", milestone: "seen", turnId: "1" }]);
141
+ expect(loaded!.status).toMatchObject({ execution: "idle", channels: [{ channel: "a", pending: [], unresolved: { turnId: "1" } }] });
142
+ await new Promise(resolve => setTimeout(resolve, 150));
143
+ expect(events).toEqual([]);
144
+ expect(lines(effects)).toEqual(["effect"]);
145
+ void harness.client.push(push("a", "m2", "fresh after the crash")).catch(() => {});
146
+ });
147
+
148
+ // 4. Load returns the reply the client missed. Killed again right after the next input is taken.
149
+ await life("beginTurn:1", async (harness, loaded) => {
150
+ expect(loaded!.messages.map(message => [message.turnId, message.parts![0]!.text])).toEqual([["1", "Recording."], ["2", "First reply."]]);
151
+ expect(texts(all)).not.toContain("First reply.");
152
+ expect(loaded!.turns).toMatchObject([{ turnId: "1", state: "interrupted", uncertainCalls: ["rec-1"] }, { turnId: "2", state: "interrupted", items: ["m2"], uncertainCalls: [] }]);
153
+ void harness.client.push(push("a", "m3", "taken, then the process dies")).catch(() => {});
154
+ });
155
+
156
+ // 5. A healthy process: the taken input is attached to exactly one interrupted turn and is not run again;
157
+ // the same channel accepts and completes fresh work.
158
+ await life(undefined, async (harness, loaded, events) => {
159
+ expect(loaded!.turns).toMatchObject([{ turnId: "1", state: "interrupted" }, { turnId: "2", state: "interrupted" }, { turnId: "3", state: "interrupted", items: ["m3"], uncertainCalls: [] }]);
160
+ expect(loaded!.items.map(item => [item.id, item.milestone, item.turnId])).toEqual([["m1", "seen", "1"], ["m2", "seen", "2"], ["m3", "taken", "3"]]);
161
+ // m2's receipt was committed before its reply and survives the crash.
162
+ expect(loaded!.status.channels).toMatchObject([{ channel: "a", pending: [], unresolved: { turnId: "3", state: "interrupted" } }]);
163
+ for (const [id, text] of [["m1", "record this"], ["m2", "fresh after the crash"], ["m3", "taken, then the process dies"]] as const)
164
+ expect(await harness.client.push(push("a", id, text))).toMatchObject({ duplicate: true });
165
+ await new Promise(resolve => setTimeout(resolve, 150));
166
+ expect(events).toEqual([]);
167
+ await harness.client.push(push("a", "m4", "fresh work on the same channel"));
168
+ await until(() => events.some(event => event.event.type === "turn_ended"), "fresh turn");
169
+ expect(taken(events)).toEqual(["m4@4"]);
170
+ expect(events.at(-1)!.event).toMatchObject({ type: "turn_ended", turnId: "4", outcome: "completed" });
171
+ expect(texts(events)).toEqual(["Second reply."]);
172
+ const final = await inspectOperatorView(harness.client, { sessionId: "ledger", config });
173
+ expect(final.turns.map(turn => [turn.turnId, turn.state, turn.items, turn.uncertainCalls ?? []])).toEqual([
174
+ ["1", "interrupted", ["m1"], ["rec-1"]], ["2", "interrupted", ["m2"], []], ["3", "interrupted", ["m3"], []], ["4", "completed", ["m4"], []]]);
175
+ expect(final.messages.map(message => message.parts![0]!.text)).toEqual(["Recording.", "First reply.", "Second reply."]);
176
+ expect(final.status).toMatchObject({ execution: "idle", channels: [{ channel: "a", pending: [] }] });
177
+ expect(final.status.channels[0]!.unresolved).toBeUndefined();
178
+ });
179
+
180
+ // Across five processes: every input was taken by exactly one turn, and the recorded tool ran once.
181
+ // Events from a dying process may be lost, but none may ever name an input twice.
182
+ expect(new Set(taken(all).map(entry => entry.split("@")[0])).size).toBe(taken(all).length);
183
+ expect(taken(all)).toContain("m4@4");
184
+ expect(all.filter(event => event.event.type === "tool_call" && event.event.status === "completed")).toEqual([]);
185
+ expect(lines(effects)).toEqual(["effect"]);
186
+ }, 60000);
@@ -0,0 +1,101 @@
1
+ import { expect, test } from "bun:test";
2
+ import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import { createInProcessHarness } from "../src/testing.ts";
6
+ import { spawnHarness } from "./helpers/stdio.ts";
7
+ import { modelScenario } from "./helpers/scenario.ts";
8
+ import type { ProtocolConfig } from "../src/client.ts";
9
+
10
+ async function until(check: () => boolean | Promise<boolean>) {
11
+ for (let attempt = 0; attempt < 500; attempt++) { if (await check()) return; await Bun.sleep(10); }
12
+ throw new Error("Timed out waiting for notice evidence");
13
+ }
14
+
15
+ for (const transport of ["in-process", "stdio"] as const) test(`${transport}: external notices wake and steer a detached channel with inherited restrictions`, async () => {
16
+ const home = mkdtempSync(join(tmpdir(), "external-notice-"));
17
+ const script = join(home, "model.jsonl"), effects = join(home, "effects"), requests = join(home, "requests");
18
+ writeFileSync(script, modelScenario([
19
+ { content: null, calls: [{ id: "hold", name: "hold", arguments: { key: "wait" } }] },
20
+ { content: null, calls: [{ id: "deny", name: "record", arguments: { text: "forbidden" } }] },
21
+ { content: "Done" },
22
+ ]));
23
+ const config: ProtocolConfig = { version: 1, system: "external", model: { protocol: "scripted", script }, defaultPolicy: "owner",
24
+ policies: { owner: { fallback: "allow", tools: {} }, guest: { fallback: "allow", tools: { record: "deny" } } } };
25
+ const connect = () => transport === "stdio" ? spawnHarness({ home, effects, requests }) : createInProcessHarness({ home, effects, requests });
26
+ const first = connect();
27
+ const notify = (id: string, policyNames = ["guest"], source: string | undefined = "worker") =>
28
+ ({ channel: "alice", notice: { id, text: "result", source, policyNames } });
29
+ try {
30
+ const init = await first.client.initialize();
31
+ expect(init.description.capabilities.methods).toContain("channel/notify");
32
+ await expect(first.client.notify(notify("one"))).rejects.toMatchObject({ code: "invalid_state" });
33
+ await first.client.createSession({ sessionId: "s", participants: [], channels: {}, config });
34
+ await expect(first.client.notify(notify("one"))).rejects.toMatchObject({ code: "not_found" });
35
+ await first.client.createChannel({ channel: "alice" });
36
+ await first.client.createChannel({ channel: "retired" });
37
+ await first.client.deleteChannel({ channel: "retired" });
38
+ await expect(first.client.notify({ ...notify("retired-id"), channel: "retired" })).rejects.toMatchObject({ code: "channel_retired" });
39
+ await first.client.suspendChannel({ channel: "alice" });
40
+ await expect(first.client.notify(notify("suspended-id"))).rejects.toMatchObject({ code: "channel_suspended" });
41
+ await first.client.resumeChannel({ channel: "alice" });
42
+ await expect(first.client.notify(notify("one", ["unknown"]))).rejects.toMatchObject({ code: "invalid_policy" });
43
+ expect(await first.client.notify(notify("one"))).toMatchObject({ accepted: true, duplicate: false, item: { kind: "external_notice", externalSource: "worker" } });
44
+ await until(() => existsSync(effects) && readFileSync(effects, "utf8").includes("start:wait"));
45
+ expect(await first.client.notify(notify("two"))).toMatchObject({ item: { milestone: "received" } });
46
+ writeFileSync(effects + ".release-wait", "");
47
+ await until(async () => (await first.client.status()).execution === "idle");
48
+ const items = await first.client.reconcileChannel({ channel: "alice", itemIds: ["one", "two"] });
49
+ expect(items.items.map(item => item.turnId)).toEqual(["1", "1"]);
50
+ const timeline = await first.client.timeline();
51
+ expect(timeline.events.filter(event => event.kind === "external_notice").map(event => [event.itemId, event.externalSource])).toEqual([["one", "worker"], ["two", "worker"]]);
52
+ expect((await first.client.channelMessages({ channel: "alice" })).messages.map(message => "parts" in message ? message.parts?.[0]?.text : undefined)).toEqual(["Done"]);
53
+ const captured = readFileSync(requests, "utf8");
54
+ expect(captured).toContain('External notice from \\"worker\\" to channel \\"alice\\"');
55
+ expect(captured).toContain("policy_denied");
56
+ expect(readFileSync(effects, "utf8")).not.toContain("forbidden");
57
+ await first.client.suspend();
58
+ const revision = (await first.client.status()).revision;
59
+ expect(await first.client.notify(notify("one", ["guest", "guest"]))).toMatchObject({ duplicate: true });
60
+ expect((await first.client.status()).revision).toBe(revision);
61
+ await expect(first.client.notify(notify("new"))).rejects.toMatchObject({ code: "not_running" });
62
+ await expect(first.client.notify(notify("one", ["guest"], "changed"))).rejects.toMatchObject({ code: "item_conflict" });
63
+ } finally { await first.close(); }
64
+ const second = connect();
65
+ try {
66
+ await second.client.initialize();
67
+ await second.client.openSession({ sessionId: "s", config: { ...config, policies: { owner: config.policies!.owner! } } });
68
+ const revision = (await second.client.status()).revision;
69
+ expect(await second.client.notify(notify("one"))).toMatchObject({ duplicate: true });
70
+ await expect(second.client.notify(notify("new"))).rejects.toMatchObject({ code: "incompatible" });
71
+ expect((await second.client.status()).revision).toBe(revision);
72
+ } finally { await second.close(); rmSync(home, { recursive: true, force: true }); }
73
+ }, 20000);
74
+
75
+ test("stdio: a lost external notice receipt reopens with one accepted item and one take", async () => {
76
+ const home = mkdtempSync(join(tmpdir(), "notice-receipt-loss-"));
77
+ const script = join(home, "model.jsonl");
78
+ writeFileSync(script, modelScenario([{ content: "Once" }, { content: "Unexpected second take" }]));
79
+ const first = spawnHarness({ home, fault: "acceptItem:1" });
80
+ const params = { channel: "alice", notice: { id: "stable", text: "result", policyNames: [] } };
81
+ try {
82
+ await first.client.initialize();
83
+ await first.client.createSession({ sessionId: "s", participants: [], channels: {}, config: {
84
+ version: 1, system: "test", model: { protocol: "scripted", script }, defaultPolicy: "open",
85
+ policies: { open: { fallback: "allow", tools: {} } },
86
+ } });
87
+ await first.client.createChannel({ channel: "alice" });
88
+ await expect(first.client.notify(params)).rejects.toBeDefined();
89
+ expect(await first.child.exited).not.toBe(0);
90
+ const recovered = spawnHarness({ home });
91
+ try {
92
+ await recovered.client.initialize();
93
+ await recovered.client.openSession({ sessionId: "s" });
94
+ expect(await recovered.client.notify(params)).toMatchObject({ duplicate: true });
95
+ await until(async () => (await recovered.client.status()).execution === "idle");
96
+ expect((await recovered.client.timeline()).events.filter(event => event.kind === "external_notice")).toHaveLength(1);
97
+ expect((await recovered.client.modelCalls()).calls).toHaveLength(1);
98
+ await expect(recovered.client.notify({ ...params, notice: { ...params.notice, source: "host" } })).rejects.toMatchObject({ code: "item_conflict" });
99
+ } finally { await recovered.close(); }
100
+ } finally { first.client.close(); first.child.kill(); rmSync(home, { recursive: true, force: true }); }
101
+ }, 20000);
@@ -0,0 +1,4 @@
1
+ {"type":"scenario","version":1,"name":"approval-e2e"}
2
+ {"type":"model","content":"Requesting the action.","calls":[{"id":"first","name":"record","arguments":{"text":"approved"}}]}
3
+ {"type":"model","content":"Requesting the action again.","calls":[{"id":"second","name":"record","arguments":{"text":"approved"}}]}
4
+ {"type":"model","content":"Finished.","calls":[]}
@@ -0,0 +1,5 @@
1
+ {"type":"scenario","version":1,"name":"crash-scenario"}
2
+ {"type":"model","content":"Recording.","calls":[{"id":"rec-1","name":"record","arguments":{"text":"effect"}}]}
3
+ {"type":"model","content":"First reply.","calls":[]}
4
+ {"type":"model","content":"Second reply.","calls":[]}
5
+ {"type":"model","content":"Third reply.","calls":[]}
@@ -0,0 +1,10 @@
1
+ {"type":"scenario","version":1,"name":"development-lifecycle"}
2
+ {"type":"model","channelId":"channel1","content":"Test: I will send a verification notice to Bob’s channel.","calls":[{"id":"notify-1","name":"notify_channel","arguments":{"channelId":"channel2","text":"Verification notice from channel1."}}]}
3
+ {"type":"model","channelId":"channel1","content":"Test: the harness accepted the notice for Bob’s channel.","calls":[]}
4
+ {"type":"model","channelId":"channel1","content":"Test: I am invoking the hold tool.","calls":[{"id":"hold-1","name":"test_hold","arguments":{}}]}
5
+ {"type":"model","channelId":"channel1","content":"Test: the hold tool finished.","calls":[]}
6
+ {"type":"model","channelId":"channel1","content":"Alice, the session is running again.","calls":[]}
7
+ {"type":"model","channelId":"channel2","content":"Hello Bob.","calls":[]}
8
+ {"type":"model","channelId":"channel2","content":"Noted: the design is approved.","calls":[]}
9
+ {"type":"model","channelId":"channel2","content":"Bob, I received your later message.","calls":[]}
10
+ {"type":"model","channelId":"channel2","content":"Bob, the session is running again.","calls":[]}
@@ -0,0 +1,3 @@
1
+ {"type":"scenario","version":1,"name":"echo-scenario"}
2
+ {"type":"model","content":"I'll echo that.","calls":[{"id":"echo-1","name":"echo","arguments":{"text":"hello"}}]}
3
+ {"type":"model","content":"The tool returned hello.","calls":[]}
@@ -0,0 +1,27 @@
1
+ /** The SQLite schema written by the persistence revision (storage format 2, commit 3a236ac),
2
+ * kept verbatim so tests can build real format 2 databases (decision 0014). */
3
+ export const FORMAT2_SCHEMA = `
4
+ CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;
5
+ CREATE TABLE channels (channel_id TEXT PRIMARY KEY, position INTEGER NOT NULL);
6
+ CREATE TABLE participants (participant_id TEXT PRIMARY KEY, position INTEGER NOT NULL);
7
+ CREATE TABLE turns (
8
+ turn_id INTEGER PRIMARY KEY, channel_id TEXT NOT NULL REFERENCES channels(channel_id),
9
+ started_seq INTEGER NOT NULL, started_at TEXT NOT NULL, compatibility_key TEXT NOT NULL,
10
+ status TEXT NOT NULL CHECK (status IN ('running','suspended','completed','failed','interrupted')),
11
+ state TEXT NOT NULL);
12
+ CREATE UNIQUE INDEX one_live_turn ON turns(channel_id) WHERE status IN ('running','suspended');
13
+ CREATE TABLE entries (
14
+ seq INTEGER PRIMARY KEY, at TEXT NOT NULL, channel_id TEXT NOT NULL REFERENCES channels(channel_id),
15
+ turn_id INTEGER NOT NULL REFERENCES turns(turn_id), sender TEXT NOT NULL, kind TEXT,
16
+ source_channel_id TEXT, item_id TEXT, message TEXT NOT NULL);
17
+ CREATE INDEX entries_by_turn ON entries(turn_id, seq);
18
+ CREATE TABLE items (
19
+ item_id TEXT PRIMARY KEY, kind TEXT NOT NULL, channel_id TEXT NOT NULL REFERENCES channels(channel_id),
20
+ sender_id TEXT NOT NULL, source_channel_id TEXT, text TEXT NOT NULL, signature TEXT NOT NULL,
21
+ accepted_seq INTEGER NOT NULL UNIQUE, accepted_at TEXT NOT NULL,
22
+ milestone TEXT NOT NULL CHECK (milestone IN ('received','taken','delivered','seen')),
23
+ turn_id INTEGER REFERENCES turns(turn_id), entry_seq INTEGER REFERENCES entries(seq),
24
+ CHECK ((milestone = 'received') = (turn_id IS NULL)));
25
+ CREATE INDEX items_pending ON items(channel_id, accepted_seq) WHERE milestone = 'received';
26
+ CREATE INDEX items_by_turn ON items(turn_id, entry_seq);
27
+ `;
@@ -0,0 +1,16 @@
1
+ import type { Database } from "bun:sqlite";
2
+
3
+ /** Strip current storage features from a test database seeded with legacy
4
+ * signatures, including derived structures that reference newer columns. */
5
+ export function useFormat3Schema(db: Database): void {
6
+ db.exec(`
7
+ DROP TRIGGER context_policy_insert;
8
+ DROP TRIGGER context_policy_take;
9
+ DROP TABLE context_turn_policies;
10
+ ALTER TABLE items DROP COLUMN external_source;
11
+ ALTER TABLE entries DROP COLUMN external_source;
12
+ ALTER TABLE items DROP COLUMN policy_metadata;
13
+ ALTER TABLE channels DROP COLUMN policy;
14
+ UPDATE meta SET value = '3' WHERE key = 'formatVersion';
15
+ `);
16
+ }
@@ -0,0 +1,4 @@
1
+ {"type":"scenario","version":1,"name":"hold-scenario"}
2
+ {"type":"model","content":"Working.","calls":[{"id":"hold-1","name":"hold","arguments":{"key":"k"}}]}
3
+ {"type":"model","content":"Finished.","calls":[]}
4
+ {"type":"model","content":"Next.","calls":[]}
@@ -0,0 +1,3 @@
1
+ {"type":"scenario","version":1,"name":"model-e2e"}
2
+ {"type":"model","content":"Bob completed"}
3
+ {"type":"model","content":"Fresh work completed"}