@qlairoslabs/acp-client 0.13.0-alpha.1 → 0.13.2-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 (343) hide show
  1. package/CONSUMER_GUIDE.md +181 -8
  2. package/MIGRATION-0.12-to-0.13.md +20 -7
  3. package/package.json +13 -2
  4. package/src/agent/config.ts +2 -0
  5. package/src/agent/conversation-manager.ts +1 -0
  6. package/src/agent/native-operations.ts +40 -0
  7. package/src/agent-session-config.ts +2 -0
  8. package/src/agent-session.ts +12 -2
  9. package/src/agent.ts +100 -2
  10. package/src/client.ts +5 -3
  11. package/src/controller-connection.ts +1 -0
  12. package/src/controller.ts +2 -0
  13. package/src/index.ts +3 -0
  14. package/src/launcher.ts +2 -0
  15. package/src/native/approvals.ts +20 -3
  16. package/src/native/capabilities.ts +2 -2
  17. package/src/native/connection.ts +1 -1
  18. package/src/native/controller.ts +5 -3
  19. package/src/native/host-config.ts +2 -0
  20. package/src/native/host.ts +83 -4
  21. package/src/native/mcp.ts +47 -0
  22. package/src/native/recovery.ts +8 -7
  23. package/src/native/reminders/routine-guard.ts +4 -3
  24. package/src/native/reminders/routine-wire.ts +1 -1
  25. package/src/native-harness/README.md +58 -1
  26. package/src/native-harness/package.json +4 -0
  27. package/src/native-harness/scripts/build-routine-zones.py +47 -0
  28. package/src/native-harness/src/capabilities/attachments/admission.ts +42 -0
  29. package/src/native-harness/src/capabilities/attachments/image-validation.ts +98 -0
  30. package/src/native-harness/src/capabilities/attachments/input.ts +1 -0
  31. package/src/native-harness/src/capabilities/attachments/read.ts +76 -0
  32. package/src/native-harness/src/capabilities/attachments/recovery.ts +26 -0
  33. package/src/native-harness/src/capabilities/attachments/selection.ts +37 -0
  34. package/src/native-harness/src/capabilities/attachments/service.ts +75 -0
  35. package/src/native-harness/src/capabilities/attachments/upload.ts +164 -0
  36. package/src/native-harness/src/capabilities/attachments/vision.ts +45 -0
  37. package/src/native-harness/src/capabilities/context/build.ts +5 -0
  38. package/src/native-harness/src/capabilities/context/session.ts +2 -1
  39. package/src/native-harness/src/capabilities/model/openrouter-stream.ts +80 -17
  40. package/src/native-harness/src/capabilities/model/runner.ts +6 -3
  41. package/src/native-harness/src/capabilities/reminders/cron-calendar.ts +50 -0
  42. package/src/native-harness/src/capabilities/reminders/cron-fields.ts +46 -0
  43. package/src/native-harness/src/capabilities/reminders/cron-proof.ts +32 -0
  44. package/src/native-harness/src/capabilities/reminders/cron-zone.ts +53 -0
  45. package/src/native-harness/src/capabilities/reminders/iana-zones.json.gz +0 -0
  46. package/src/native-harness/src/capabilities/reminders/iana-zones.ts +34 -0
  47. package/src/native-harness/src/capabilities/reminders/interval.ts +30 -0
  48. package/src/native-harness/src/capabilities/reminders/routine-advance.ts +47 -0
  49. package/src/native-harness/src/capabilities/reminders/routine-backlog.ts +47 -0
  50. package/src/native-harness/src/capabilities/reminders/routine-expiry.ts +15 -0
  51. package/src/native-harness/src/capabilities/reminders/routine-occurrence.ts +65 -0
  52. package/src/native-harness/src/capabilities/reminders/routine-schedule.ts +70 -0
  53. package/src/native-harness/src/capabilities/reminders/unattended.ts +8 -0
  54. package/src/native-harness/src/capabilities/tools/mcp/client.ts +97 -0
  55. package/src/native-harness/src/capabilities/tools/mcp/http.ts +183 -0
  56. package/src/native-harness/src/capabilities/tools/mcp/registry.ts +62 -0
  57. package/src/native-harness/src/capabilities/tools/mcp/result.ts +33 -0
  58. package/src/native-harness/src/capabilities/tools/mcp/schema.ts +77 -0
  59. package/src/native-harness/src/capabilities/tools/mcp/secrets.ts +28 -0
  60. package/src/native-harness/src/capabilities/tools/mcp/stdio.ts +105 -0
  61. package/src/native-harness/src/capabilities/tools/reminders/index.ts +27 -5
  62. package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +4 -1
  63. package/src/native-harness/src/capabilities/tools/web/config.ts +1 -0
  64. package/src/native-harness/src/capabilities/tools/web/definitions.ts +18 -0
  65. package/src/native-harness/src/capabilities/tools/web/direct-address.ts +56 -0
  66. package/src/native-harness/src/capabilities/tools/web/direct-transport.ts +235 -0
  67. package/src/native-harness/src/capabilities/tools/web/direct.ts +149 -0
  68. package/src/native-harness/src/capabilities/tools/web/exa-transport.ts +41 -0
  69. package/src/native-harness/src/capabilities/tools/web/exa.ts +71 -0
  70. package/src/native-harness/src/capabilities/tools/web/preview.ts +44 -0
  71. package/src/native-harness/src/capabilities/tools/web/registry.ts +47 -0
  72. package/src/native-harness/src/capabilities/tools/web/usage.ts +1 -0
  73. package/src/native-harness/src/contracts/agent.ts +3 -1
  74. package/src/native-harness/src/contracts/attachments.ts +62 -0
  75. package/src/native-harness/src/contracts/config-permissions.ts +14 -3
  76. package/src/native-harness/src/contracts/context.ts +1 -1
  77. package/src/native-harness/src/contracts/events.ts +2 -2
  78. package/src/native-harness/src/contracts/loop.ts +3 -3
  79. package/src/native-harness/src/contracts/mcp.ts +22 -0
  80. package/src/native-harness/src/contracts/model-execution.ts +2 -1
  81. package/src/native-harness/src/contracts/operator-controls.ts +8 -1
  82. package/src/native-harness/src/contracts/protocol.ts +21 -5
  83. package/src/native-harness/src/contracts/reminders.ts +4 -2
  84. package/src/native-harness/src/contracts/routines.ts +20 -0
  85. package/src/native-harness/src/contracts/session-file.ts +2 -0
  86. package/src/native-harness/src/contracts/session.ts +8 -3
  87. package/src/native-harness/src/contracts/storage.ts +32 -13
  88. package/src/native-harness/src/contracts/tools.ts +2 -0
  89. package/src/native-harness/src/contracts/web.ts +16 -0
  90. package/src/native-harness/src/governance/permissions/gate.ts +9 -2
  91. package/src/native-harness/src/governance/policy/resolve.ts +6 -1
  92. package/src/native-harness/src/index.ts +48 -12
  93. package/src/native-harness/src/interfaces/cli/development.ts +108 -53
  94. package/src/native-harness/src/interfaces/cli/serve.ts +2 -2
  95. package/src/native-harness/src/interfaces/cli/start.ts +22 -13
  96. package/src/native-harness/src/interfaces/client.ts +8 -2
  97. package/src/native-harness/src/interfaces/inspector/index.html +7 -1
  98. package/src/native-harness/src/interfaces/inspector/state.ts +6 -2
  99. package/src/native-harness/src/interfaces/protocol/load.ts +3 -1
  100. package/src/native-harness/src/interfaces/protocol/local.ts +13 -4
  101. package/src/native-harness/src/interfaces/protocol/operator.ts +8 -2
  102. package/src/native-harness/src/interfaces/protocol/server.ts +102 -36
  103. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +8 -0
  104. package/src/native-harness/src/interfaces/web-chat/index.html +65 -12
  105. package/src/native-harness/src/interfaces/web-chat/server.ts +30 -3
  106. package/src/native-harness/src/kernel/channels.ts +27 -15
  107. package/src/native-harness/src/kernel/loop.ts +1 -1
  108. package/src/native-harness/src/runtime/config/inference-key.ts +7 -0
  109. package/src/native-harness/src/runtime/config/managed.ts +1 -1
  110. package/src/native-harness/src/runtime/config/paths.ts +8 -1
  111. package/src/native-harness/src/runtime/execution/mcp-stdio.ts +31 -0
  112. package/src/native-harness/src/runtime/reminder-validation.ts +31 -10
  113. package/src/native-harness/src/runtime/reminders.ts +2 -2
  114. package/src/native-harness/src/state/storage/archive.ts +113 -12
  115. package/src/native-harness/src/state/storage/attachment-files.ts +58 -0
  116. package/src/native-harness/src/state/storage/attachment-import.ts +106 -0
  117. package/src/native-harness/src/state/storage/attachment-tables.ts +123 -0
  118. package/src/native-harness/src/state/storage/engine.ts +396 -45
  119. package/src/native-harness/src/state/storage/inference.ts +30 -2
  120. package/src/native-harness/src/state/storage/memory-attachments.ts +56 -0
  121. package/src/native-harness/src/state/storage/memory-reminders.ts +31 -6
  122. package/src/native-harness/src/state/storage/memory.ts +32 -4
  123. package/src/native-harness/src/state/storage/reminder-archive.ts +53 -12
  124. package/src/native-harness/src/state/storage/reminder-change.ts +60 -14
  125. package/src/native-harness/src/state/storage/reminder-tables.ts +11 -3
  126. package/src/native-harness/src/state/storage/routine-row.ts +25 -0
  127. package/src/native-harness/src/state/storage/session-file.ts +22 -9
  128. package/src/native-harness/src/state/storage/sqlite-reminders.ts +48 -8
  129. package/src/native-harness/src/state/storage/sqlite.ts +59 -11
  130. package/src/native-harness/src/state/storage/web-tables.ts +47 -0
  131. package/src/native-harness/src/testing.ts +151 -56
  132. package/src/native-harness/src/util/attachment-input.ts +42 -0
  133. package/src/native-harness/src/util/config.ts +64 -9
  134. package/src/native-harness/src/util/intake.ts +7 -0
  135. package/src/native-harness/src/util/mcp-config.ts +102 -0
  136. package/src/native-harness/src/util/web-config.ts +34 -0
  137. package/src/native-harness/src/util/web-usage.ts +33 -0
  138. package/src/orchestrator/permissions.ts +6 -3
  139. package/src/permissions/conversation.ts +13 -5
  140. package/src/permissions/matcher.ts +2 -0
  141. package/src/permissions/outcome.ts +12 -1
  142. package/src/permissions/policy.ts +13 -8
  143. package/src/steering/combine.ts +1 -0
  144. package/src/steering/contracts.ts +3 -0
  145. package/src/terminals.ts +9 -6
  146. package/src/native/reminders/reminders.test.ts +0 -553
  147. package/src/native/reminders/routine-config.typecheck.ts +0 -13
  148. package/src/native/reminders/wire.typecheck.ts +0 -13
  149. package/src/native-harness/.res/README.md +0 -1
  150. package/src/native-harness/.res/architecture/README.md +0 -21
  151. package/src/native-harness/.res/architecture/context-and-data.md +0 -31
  152. package/src/native-harness/.res/architecture/execution.md +0 -42
  153. package/src/native-harness/.res/architecture/overview.md +0 -44
  154. package/src/native-harness/.res/architecture/persistence.md +0 -56
  155. package/src/native-harness/.res/architecture/suspend-and-resume.md +0 -45
  156. package/src/native-harness/.res/architecture/technical-architecture.md +0 -50
  157. package/src/native-harness/.res/decisions/0001-basic-loop.md +0 -11
  158. package/src/native-harness/.res/decisions/0002-channel-input.md +0 -17
  159. package/src/native-harness/.res/decisions/0003-inference-inspection.md +0 -14
  160. package/src/native-harness/.res/decisions/0004-shared-context.md +0 -21
  161. package/src/native-harness/.res/decisions/0005-notice-inbox.md +0 -20
  162. package/src/native-harness/.res/decisions/0006-explicit-notices.md +0 -12
  163. package/src/native-harness/.res/decisions/0007-channel-output.md +0 -12
  164. package/src/native-harness/.res/decisions/0008-browser-client.md +0 -16
  165. package/src/native-harness/.res/decisions/0009-scripted-model.md +0 -18
  166. package/src/native-harness/.res/decisions/0010-inprocess-protocol.md +0 -19
  167. package/src/native-harness/.res/decisions/0011-stdio-transport.md +0 -21
  168. package/src/native-harness/.res/decisions/0012-session-storage-contract.md +0 -37
  169. package/src/native-harness/.res/decisions/0013-durable-delivery-contract.md +0 -64
  170. package/src/native-harness/.res/decisions/0014-channel-controls-contract.md +0 -73
  171. package/src/native-harness/.res/decisions/0015-session-file-contract.md +0 -72
  172. package/src/native-harness/.res/decisions/0016-configuration-permissions.md +0 -159
  173. package/src/native-harness/.res/decisions/0017-openrouter-managed-config.md +0 -69
  174. package/src/native-harness/.res/decisions/0018-tool-dispatch-evidence.md +0 -78
  175. package/src/native-harness/.res/decisions/0019-model-execution.md +0 -188
  176. package/src/native-harness/.res/decisions/0020-startup-channel-changes.md +0 -71
  177. package/src/native-harness/.res/decisions/0021-tools-and-host-callbacks.md +0 -100
  178. package/src/native-harness/.res/decisions/0022-operator-controls.md +0 -115
  179. package/src/native-harness/.res/decisions/0023-long-running-mock.md +0 -82
  180. package/src/native-harness/.res/decisions/0024-callback-policy-names.md +0 -46
  181. package/src/native-harness/.res/decisions/0025-external-notices.md +0 -364
  182. package/src/native-harness/.res/decisions/0026-bounded-context.md +0 -81
  183. package/src/native-harness/.res/decisions/0027-development-instructions.md +0 -22
  184. package/src/native-harness/.res/decisions/0028-debug-tools.md +0 -16
  185. package/src/native-harness/.res/decisions/0029-bounded-model-call-pages.md +0 -37
  186. package/src/native-harness/.res/decisions/0030-timeline-retrieval.md +0 -145
  187. package/src/native-harness/.res/decisions/0031-one-off-reminders.md +0 -173
  188. package/src/native-harness/.res/docs/11-15.md +0 -148
  189. package/src/native-harness/.res/docs/BUSINESS_RULES.md +0 -111
  190. package/src/native-harness/.res/docs/WORK.md +0 -65
  191. package/src/native-harness/.res/docs/_/11-16-persistence/LOG.md +0 -312
  192. package/src/native-harness/.res/docs/_/11-16-persistence/PLAN.md +0 -77
  193. package/src/native-harness/.res/docs/_/11-16-persistence/SPEC.md +0 -313
  194. package/src/native-harness/.res/docs/_/11-19-channel-controls/LOG.md +0 -160
  195. package/src/native-harness/.res/docs/_/11-19-channel-controls/PLAN.md +0 -89
  196. package/src/native-harness/.res/docs/_/11-19-channel-controls/SPEC.md +0 -135
  197. package/src/native-harness/.res/docs/_/11-19-config-permissions/LOG.md +0 -143
  198. package/src/native-harness/.res/docs/_/11-19-config-permissions/PLAN.md +0 -93
  199. package/src/native-harness/.res/docs/_/11-19-config-permissions/SPEC.md +0 -181
  200. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/11-20-LOG.md +0 -433
  201. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PLAN.md +0 -60
  202. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PROTOCOL.md +0 -141
  203. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/SPEC.md +0 -168
  204. package/src/native-harness/.res/docs/attachments/0001-DESIGN/SPEC.md +0 -111
  205. package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/PLAN.md +0 -129
  206. package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/SPEC.md +0 -135
  207. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/LOG.md +0 -437
  208. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/PLAN.md +0 -127
  209. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/SPEC.md +0 -203
  210. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/LOG.md +0 -292
  211. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/PLAN.md +0 -91
  212. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/SPEC.md +0 -187
  213. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/LOG.md +0 -148
  214. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/PLAN.md +0 -95
  215. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/SPEC.md +0 -200
  216. package/src/native-harness/.res/docs/model-execution/0002-AMENDMENT-accounting/SPEC.md +0 -80
  217. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/LOG.md +0 -206
  218. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/PLAN.md +0 -106
  219. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/SPEC.md +0 -297
  220. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/LOG.md +0 -41
  221. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/PLAN.md +0 -36
  222. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/SPEC.md +0 -84
  223. package/src/native-harness/.res/docs/shell-execution/0001-DESIGN/SPEC.md +0 -147
  224. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/LOG.md +0 -15
  225. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/PLAN.md +0 -107
  226. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/SPEC.md +0 -114
  227. package/src/native-harness/.res/docs/todos/11-19-TODO-auto_review-approve.md +0 -24
  228. package/src/native-harness/.res/docs/todos/11-20-TODO-user-entered-tool-code.md +0 -23
  229. package/src/native-harness/.res/docs/todos/11-21-TODO-node-resource-coordination.md +0 -103
  230. package/src/native-harness/.res/docs/todos/11-22-TODO-harness-m1-sequence.md +0 -50
  231. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/LOG.md +0 -337
  232. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/PLAN.md +0 -76
  233. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/SPEC.md +0 -204
  234. package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/LOG.md +0 -73
  235. package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/SPEC.md +0 -64
  236. package/src/native-harness/.res/docs/tools-and-callbacks/0003-DESIGN-attachment-tools/SPEC.md +0 -58
  237. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/LOG.md +0 -45
  238. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/PLAN.md +0 -108
  239. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/SPEC.md +0 -169
  240. package/src/native-harness/.res/docs/web-tools/0001-DESIGN/SPEC.md +0 -128
  241. package/src/native-harness/.res/marketing-draft.md +0 -22
  242. package/src/native-harness/.res/sandbox/1-simple-harness/README.md +0 -285
  243. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-1.md +0 -19
  244. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-10.md +0 -138
  245. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-11.md +0 -148
  246. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-12.md +0 -172
  247. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-13.md +0 -194
  248. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-14.md +0 -233
  249. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-15.md +0 -249
  250. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-16.md +0 -265
  251. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-17.md +0 -279
  252. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-18.md +0 -293
  253. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-19.md +0 -307
  254. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-2.md +0 -29
  255. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-20.md +0 -317
  256. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-21.md +0 -327
  257. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-3.md +0 -40
  258. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-4.md +0 -59
  259. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-5.md +0 -69
  260. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-6.md +0 -79
  261. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-7.md +0 -89
  262. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-8.md +0 -102
  263. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-9.md +0 -116
  264. package/src/native-harness/.res/sandbox/1-simple-harness/conversation.jsonl +0 -49
  265. package/src/native-harness/.res/sandbox/1-simple-harness/doc.md +0 -87
  266. package/src/native-harness/.res/sandbox/1-simple-harness/harness.py +0 -289
  267. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 2.py +0 -221
  268. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 3.py +0 -287
  269. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy.py +0 -165
  270. package/src/native-harness/.res/sandbox/1-simple-harness/state.json +0 -22
  271. package/src/native-harness/.res/sandbox/1-simple-harness/system-prompt.md +0 -2
  272. package/src/native-harness/AGENTS.md +0 -70
  273. package/src/native-harness/ARCHITECTURE.md +0 -249
  274. package/src/native-harness/bun.lock +0 -26
  275. package/src/native-harness/test/agent.test.ts +0 -130
  276. package/src/native-harness/test/approval-gate.test.ts +0 -255
  277. package/src/native-harness/test/approval-protocol.test.ts +0 -94
  278. package/src/native-harness/test/boundaries.test.ts +0 -18
  279. package/src/native-harness/test/channel-controls.test.ts +0 -322
  280. package/src/native-harness/test/client-abort.test.ts +0 -136
  281. package/src/native-harness/test/config-policy.test.ts +0 -301
  282. package/src/native-harness/test/conformance/storage.ts +0 -1141
  283. package/src/native-harness/test/context.test.ts +0 -177
  284. package/src/native-harness/test/crash.test.ts +0 -187
  285. package/src/native-harness/test/debug-tools.test.ts +0 -67
  286. package/src/native-harness/test/development-cli.test.ts +0 -67
  287. package/src/native-harness/test/development.test.ts +0 -171
  288. package/src/native-harness/test/dispatch-evidence.test.ts +0 -58
  289. package/src/native-harness/test/e2e.test.ts +0 -186
  290. package/src/native-harness/test/external-notices.test.ts +0 -101
  291. package/src/native-harness/test/fixtures/approval-e2e.jsonl +0 -4
  292. package/src/native-harness/test/fixtures/crash-scenario.jsonl +0 -5
  293. package/src/native-harness/test/fixtures/development-lifecycle.jsonl +0 -10
  294. package/src/native-harness/test/fixtures/echo-scenario.jsonl +0 -3
  295. package/src/native-harness/test/fixtures/format2-schema.ts +0 -27
  296. package/src/native-harness/test/fixtures/format3-schema.ts +0 -16
  297. package/src/native-harness/test/fixtures/hold-scenario.jsonl +0 -4
  298. package/src/native-harness/test/fixtures/model-e2e.jsonl +0 -3
  299. package/src/native-harness/test/fixtures/storage-owner.ts +0 -20
  300. package/src/native-harness/test/format-reply.test.ts +0 -10
  301. package/src/native-harness/test/helpers/operator-view.ts +0 -41
  302. package/src/native-harness/test/helpers/scenario.ts +0 -9
  303. package/src/native-harness/test/helpers/session.ts +0 -38
  304. package/src/native-harness/test/helpers/stdio.ts +0 -46
  305. package/src/native-harness/test/inspector.test.ts +0 -77
  306. package/src/native-harness/test/listeners.test.ts +0 -49
  307. package/src/native-harness/test/loop.test.ts +0 -88
  308. package/src/native-harness/test/model-channel-double.test.ts +0 -87
  309. package/src/native-harness/test/model-crash.test.ts +0 -62
  310. package/src/native-harness/test/model-delivery-regressions.test.ts +0 -55
  311. package/src/native-harness/test/model-e2e.test.ts +0 -71
  312. package/src/native-harness/test/model-final-filter.test.ts +0 -30
  313. package/src/native-harness/test/model-large-reply.test.ts +0 -28
  314. package/src/native-harness/test/model-live-queue.test.ts +0 -33
  315. package/src/native-harness/test/model-runner.test.ts +0 -117
  316. package/src/native-harness/test/model-storage.test.ts +0 -99
  317. package/src/native-harness/test/model-stream-adapter.test.ts +0 -26
  318. package/src/native-harness/test/model-stream-public.test.ts +0 -77
  319. package/src/native-harness/test/notices.test.ts +0 -64
  320. package/src/native-harness/test/openrouter-config.test.ts +0 -218
  321. package/src/native-harness/test/operator-controls.test.ts +0 -132
  322. package/src/native-harness/test/output.test.ts +0 -44
  323. package/src/native-harness/test/owner-config.test.ts +0 -64
  324. package/src/native-harness/test/permissions-e2e.test.ts +0 -68
  325. package/src/native-harness/test/persistence.test.ts +0 -236
  326. package/src/native-harness/test/portability.test.ts +0 -337
  327. package/src/native-harness/test/protocol.test.ts +0 -160
  328. package/src/native-harness/test/reminder-clock.test.ts +0 -61
  329. package/src/native-harness/test/reminder-stdio.test.ts +0 -140
  330. package/src/native-harness/test/reminder-storage.test.ts +0 -124
  331. package/src/native-harness/test/scenario-jsonl.test.ts +0 -112
  332. package/src/native-harness/test/scripted.test.ts +0 -92
  333. package/src/native-harness/test/session-file.test.ts +0 -51
  334. package/src/native-harness/test/startup-channel-changes.test.ts +0 -256
  335. package/src/native-harness/test/stdio.test.ts +0 -132
  336. package/src/native-harness/test/storage-memory.test.ts +0 -4
  337. package/src/native-harness/test/storage-sqlite.test.ts +0 -420
  338. package/src/native-harness/test/suspension.test.ts +0 -430
  339. package/src/native-harness/test/timeline-retrieval.test.ts +0 -211
  340. package/src/native-harness/test/tools-catalog.test.ts +0 -468
  341. package/src/native-harness/test/tools-protocol.test.ts +0 -418
  342. package/src/native-harness/test/transfers.test.ts +0 -94
  343. package/src/native-harness/test/web-chat.test.ts +0 -35
@@ -1,1141 +0,0 @@
1
- import { createMemoryStorageAdapter } from "../../src/state/storage/memory.ts";
2
- import { legacyItemSignature } from "../../src/state/storage/policy-metadata.ts";
3
- import { describe, expect, test } from "bun:test";
4
- import { createHash } from "node:crypto";
5
- import type { ContextLimits } from "../../src/contracts/context.ts";
6
- import type { SessionStorage, SessionStorageAdapter, StorageErrorCode, StorageResult } from "../../src/contracts/storage.ts";
7
-
8
- /** Shared executable contract for storage revision 3 (decisions 0013, 0014). Each call
9
- * to `location` returns an adapter for a fresh, empty location; reusing that
10
- * adapter reopens the same session. */
11
- export function storageConformance(name: string, location: () => SessionStorageAdapter) {
12
- const id = (key = "k1") => ({ sessionId: "s1", compatibilityKey: key });
13
- function ok<T>(result: StorageResult<T>): T {
14
- if (!result.ok) throw new Error(`${result.error.code}: ${result.error.message}`);
15
- return result.value;
16
- }
17
- function refused(result: StorageResult<unknown>, code: StorageErrorCode) {
18
- expect(result.ok ? "ok" : result.error.code).toBe(code);
19
- }
20
- const create = (adapter = location()) => ({ adapter, s: ok(adapter.open({ mode: "create", identity: id() })) });
21
- const reopen = (adapter: SessionStorageAdapter, s: SessionStorage, key = "k1") => {
22
- ok(s.close());
23
- return ok(adapter.open({ mode: "open", identity: id(key) }));
24
- };
25
- const msg = (s: SessionStorage, text: string, channelId = "c1", itemId?: string) =>
26
- s.acceptItem({ kind: "participant_message", channelId, senderId: "ana", text, ...(itemId ? { itemId } : {}) });
27
- const notice = (s: SessionStorage, text: string, channelId = "c1") =>
28
- s.acceptItem({ kind: "channel_notice", channelId, senderId: "channel:c2", sourceChannelId: "c2", text });
29
- const say = (s: SessionStorage, turnId: number, content: string) => ok(s.appendMessage(turnId, { role: "assistant", content, calls: [] }));
30
- const call = (s: SessionStorage, turnId: number, callId: string) => {
31
- const entry = ok(s.appendMessage(turnId, { role: "assistant", content: null, calls: [{ id: callId, name: "echo", arguments: "{}" }] }));
32
- ok(s.markToolDispatched(turnId, callId));
33
- return entry;
34
- };
35
- const snap = (s: SessionStorage) => ok(s.snapshot());
36
- /** A refused or no-op call must leave the committed state byte-identical. */
37
- function unchanged(s: SessionStorage, act: () => void) {
38
- const before = JSON.stringify(snap(s));
39
- act();
40
- expect(JSON.stringify(snap(s))).toBe(before);
41
- }
42
- const begin = (s: SessionStorage, channelId = "c1") => ok(s.beginTurn(channelId))!;
43
-
44
- describe(`${name} storage conformance`, () => {
45
- const contextLimits: ContextLimits = {
46
- maxInputBytes: 8192, maxTakenTextBytes: 8192, maxTakenItems: 16,
47
- maxReadBytes: 4096, maxReadRecords: 8, maxSharedCandidates: 5,
48
- contextTokens: 16384, outputReserveTokens: 2048, estimationMarginTokens: 1024,
49
- };
50
-
51
- test("bounded inference read shares committed history and preserves required input and whole exchanges", () => {
52
- const adapter = location();
53
- const config = { version: 1 as const, system: "test", model: { protocol: "scripted" as const, script: "fixture" },
54
- defaultPolicy: "owner", policies: { owner: { fallback: "allow" as const, tools: {} }, guest: { fallback: "deny" as const, tools: {} } } };
55
- const seed = createMemoryStorageAdapter();
56
- let s = ok(seed.open({ mode: "create", identity: id(), config }));
57
- try {
58
- ok(s.createChannel({ channelId: "c1" }));
59
- ok(s.createChannel({ channelId: "busy" }));
60
- const historical = (channelId: string, text: string) => {
61
- ok(msg(s, text, channelId));
62
- const { turn } = begin(s, channelId);
63
- const reply = say(s, turn.turnId, "older reply");
64
- ok(s.finishTurn(turn.turnId, { status: "completed" }));
65
- return reply;
66
- };
67
- const local = historical("c1", "local");
68
- for (let i = 0; i < 160; i++) historical("busy", "busy");
69
- ok(adapter.importArchive(ok(s.exportArchive())));
70
- ok(s.close());
71
- s = ok(adapter.open({ mode: "open", identity: id(), config }));
72
- ok(msg(s, "trigger", "c1", "trigger"));
73
- const active = begin(s);
74
- const turnId = active.turn.turnId;
75
- const request = { channelId: "c1", turnId, limits: contextLimits };
76
- const effect = ok(s.appendMessage(turnId, {
77
- role: "assistant", content: null, calls: [{ id: "one", name: "echo", arguments: "{}" }], providerState: { opaque: "state" },
78
- }));
79
- ok(s.appendMessage(turnId, { role: "tool", callId: "one", content: "☃".repeat(4000) }));
80
- ok(s.acceptItem({ kind: "external_notice", itemId: "earlier", channelId: "c1", senderId: "host",
81
- text: "☃".repeat(4000), inheritedPolicyNames: ["guest"] }));
82
- ok(s.takePending(turnId));
83
- const later = call(s, turnId, "two");
84
- const result = ok(s.appendMessage(turnId, { role: "tool", callId: "two", content: "complete" }));
85
- ok(msg(s, "steer", "c1", "latest"));
86
- const steer = ok(s.takePending(turnId)).entries[0]!;
87
- ok(s.beginSuspend());
88
- ok(s.checkpointTurn(turnId));
89
- const revision = s.completeSuspend();
90
- ok(revision);
91
- s = reopenWithConfig();
92
- const snapshot = s.readInferenceContext(request);
93
- const read = ok(snapshot);
94
- if ("code" in read) throw new Error(read.code);
95
- expect(snapshot.ok && snapshot.revision).toBe(revision.ok && revision.revision);
96
- expect(read.required.map(e => e.seq)).toEqual([active.entries[0]!.seq, steer.seq]);
97
- expect(read.takenItemIds).toEqual(["latest"]);
98
- expect(read.optionalTurn.map(e => e.seq)).toEqual([later.seq, result.seq]);
99
- expect(read.localHistory.map(e => e.seq)).toContain(local.seq);
100
- expect(read.sharedHistory).toEqual([]);
101
- expect(read.policyNames).toEqual(["guest", "owner"]);
102
- expect(ok(s.readInferenceContext({ ...request, limits: { ...contextLimits, maxReadBytes: 64 } }))).toEqual({ code: "context_limit" });
103
- expect(ok(s.readInferenceContext({ ...request, limits: { ...contextLimits, maxReadRecords: 1 } }))).toEqual({ code: "context_limit" });
104
- refused(s.readInferenceContext({ ...request, channelId: "busy" }), "not_found");
105
- const withShared = ok(s.readInferenceContext({ ...request, limits: { ...contextLimits, maxSharedCandidates: 8 } }));
106
- if ("code" in withShared) throw new Error(withShared.code);
107
- expect(withShared.sharedHistory.length).toBeGreaterThan(0);
108
- expect(withShared.sharedHistory.every(e => e.channelId === "busy")).toBe(true);
109
- const wider = ok(s.readInferenceContext({ ...request, limits: { ...contextLimits, maxReadRecords: 24, maxReadBytes: 50_000 } }));
110
- if ("code" in wider) throw new Error(wider.code);
111
- expect(wider.optionalTurn.find(e => e.seq === effect.seq)?.message).toEqual(effect.message);
112
- (read.required[0]!.message as { content: string }).content = "changed";
113
- const again = ok(s.readInferenceContext(request));
114
- if ("code" in again) throw new Error(again.code);
115
- expect(again.required[0]!.message.content).toContain("trigger");
116
- } finally { ok(s.close()); }
117
-
118
- function reopenWithConfig() {
119
- ok(s.close());
120
- return ok(adapter.open({ mode: "open", identity: id(), config }));
121
- }
122
- });
123
-
124
- test("inference overflows if complete policy evidence cannot fit", () => {
125
- const policyName = "é".repeat(4000);
126
- const config = { version: 1 as const, system: "test", model: { protocol: "scripted" as const, script: "fixture" },
127
- defaultPolicy: policyName, policies: { [policyName]: { fallback: "allow" as const, tools: {} } } };
128
- const s = ok(location().open({ mode: "create", identity: id(), config }));
129
- try {
130
- ok(s.createChannel({ channelId: "c1" }));
131
- ok(msg(s, "small message"));
132
- const turnId = begin(s).turn.turnId;
133
- const request = { channelId: "c1", turnId };
134
- expect(ok(s.readInferenceContext({ ...request, limits: contextLimits }))).toEqual({ code: "context_limit" });
135
- expect(ok(s.readInferenceContext({ ...request, limits: { ...contextLimits, maxReadBytes: 16_384 } })))
136
- .toMatchObject({ policyNames: [policyName], required: [{ kind: "participant_message" }] });
137
- } finally { ok(s.close()); }
138
- });
139
-
140
- test("inspector pages advance across omitted payloads and pin older positions", () => {
141
- const seed = createMemoryStorageAdapter(), source = create(seed).s;
142
- ok(msg(source, "start"));
143
- const active = begin(source);
144
- for (let i = 0; i < 44; i++) say(source, active.turn.turnId, i === 42 ? "é".repeat(32000) : "reply");
145
- ok(source.finishTurn(active.turn.turnId, { status: "completed" }));
146
- const target = location();
147
- ok(target.importArchive(ok(source.exportArchive())));
148
- ok(source.close());
149
- const s = ok(target.open({ mode: "open", identity: id() }));
150
- try {
151
- expect(ok(s.readInspectionStatus()).channels).toMatchObject([{ id: "c1", pending: 0 }]);
152
- const recent = ok(s.readInspectionPage());
153
- expect(recent.entries).toHaveLength(40);
154
- expect(recent.entries[1]).toEqual({ seq: recent.entries[0]!.seq - 1, omitted: true });
155
- expect(recent.next).toBeDefined();
156
- ok(msg(s, "new pending"));
157
- const older = ok(s.readInspectionPage(recent.next));
158
- expect(older.entries).toHaveLength(5);
159
- expect(older.entries.every(row => row.seq < recent.next!)).toBe(true);
160
- expect(older.next).toBeUndefined();
161
- } finally { ok(s.close()); }
162
- });
163
-
164
- test("external notice identity, drain admission, inspection and archive round trip", () => {
165
- const adapter = location();
166
- const config = { version: 1 as const, system: "test", model: { protocol: "scripted" as const, script: "fixture" },
167
- defaultPolicy: "owner", policies: { owner: { fallback: "allow" as const, tools: {} }, guest: { fallback: "deny" as const, tools: {} } } };
168
- const s = ok(adapter.open({ mode: "create", identity: id(), config }));
169
- ok(s.createChannel({ channelId: "c1" }));
170
- ok(s.createChannel({ channelId: "c2" }));
171
- const notice = { kind: "external_notice" as const, itemId: "external", channelId: "c1", senderId: "worker",
172
- externalSource: "worker", text: "result", inheritedPolicyNames: ["guest", "owner"] };
173
- refused(s.acceptItem({ ...notice, channelId: "missing" }), "not_found");
174
- refused(s.acceptItem({ ...notice, inheritedPolicyNames: ["__legacy_allow"] }), "invalid_policy");
175
- refused(s.acceptItem({ ...notice, inheritedPolicyNames: ["unknown"] }), "invalid_policy");
176
- expect(ok(s.acceptItem(notice)).item.policy).toEqual({ resolved: "owner", inherited: ["guest", "owner"] });
177
- const base = ok(s.snapshot()).revision;
178
- expect(ok(s.acceptItem({ ...notice, inheritedPolicyNames: ["owner", "guest", "guest"] })).duplicate).toBe(true);
179
- for (const change of [{ externalSource: undefined }, { text: "changed" }, { channelId: "c2" }, { inheritedPolicyNames: ["guest"] }])
180
- refused(s.acceptItem({ ...notice, ...change }), "item_conflict");
181
- refused(msg(s, "result", "c1", "external"), "item_conflict");
182
- expect(ok(s.snapshot()).revision).toBe(base);
183
- const taken = begin(s);
184
- expect(taken.entries[0]).toMatchObject({ kind: "external_notice", itemId: "external", externalSource: "worker" });
185
- ok(s.acceptItem({ ...notice, itemId: "pending" }));
186
- ok(s.beginSuspend());
187
- refused(s.acceptItem({ ...notice, itemId: "new" }), "not_running");
188
- expect(ok(s.acceptItem(notice)).item.milestone).toBe("taken");
189
- ok(s.acceptItem({ kind: "channel_notice", channelId: "c2", sourceChannelId: "c1", sourceTurnId: taken.turn.turnId, senderId: "channel:c1", text: "internal drain notice" }));
190
- ok(s.interruptTurn("c1", taken.turn.turnId, "test suspension"));
191
- ok(s.completeSuspend());
192
- const archive = ok(s.exportArchive());
193
- expect(archive.archiveVersion).toBe(5);
194
- ok(s.close());
195
- const inspection = ok(adapter.open({ mode: "open", identity: id(), config: { ...config, policies: { owner: config.policies.owner } } }));
196
- const before = ok(inspection.snapshot()).revision;
197
- expect(ok(inspection.acceptItem(notice)).duplicate).toBe(true);
198
- refused(inspection.acceptItem({ ...notice, itemId: "new" }), "incompatible");
199
- expect(ok(inspection.snapshot()).revision).toBe(before);
200
- ok(inspection.close());
201
- const copy = location();
202
- ok(copy.importArchive(archive));
203
- const imported = ok(copy.open({ mode: "open", identity: id(), config }));
204
- expect(ok(imported.acceptItem(notice)).item).toMatchObject({ milestone: "taken", externalSource: "worker" });
205
- expect(ok(imported.acceptItem({ ...notice, itemId: "pending" })).item).toMatchObject({ milestone: "received", inheritedPolicyNames: ["guest", "owner"] });
206
- ok(imported.close());
207
- });
208
-
209
- test("archive 4 imports without changing existing item identities", () => {
210
- const { s } = create();
211
- const accepted = ok(msg(s, "original", "c1", "old")).item;
212
- const active = begin(s);
213
- say(s, active.turn.turnId, "reply"); ok(s.finishTurn(active.turn.turnId, { status: "completed" }));
214
- const current = ok(s.exportArchive());
215
- const old = { ...current, archiveVersion: 4 as const, snapshot: { ...current.snapshot,
216
- session: { ...current.snapshot.session, formatVersion: 5 as const } } };
217
- const adapter = location();
218
- ok(adapter.importArchive(old));
219
- const imported = ok(adapter.open({ mode: "open", identity: id() }));
220
- const duplicate = ok(msg(imported, "original", "c1", "old"));
221
- expect(duplicate).toMatchObject({ duplicate: true, item: { signature: accepted.signature } });
222
- ok(imported.close()); ok(s.close());
223
- });
224
-
225
- test("scripted owners reject missing, malformed and changed digests before recovery", () => {
226
- const digest = "a".repeat(64), changed = "b".repeat(64);
227
- const tagged = (model: string, system = "c") => id(`scripted-jsonl-v1:${model}:${system.repeat(64)}`);
228
- for (const legacy of [id(), id(`scripted-jsonl-v1:${digest}:bad`), id(tagged(digest).compatibilityKey + "\n")]) {
229
- const adapter = location();
230
- ok(ok(adapter.open({ mode: "create", identity: legacy })).close());
231
- refused(adapter.open({ mode: "open", identity: tagged(digest), requiredScriptDigest: digest }), "incompatible");
232
- }
233
- const adapter = location(), first = ok(adapter.open({ mode: "create", identity: tagged(digest), requiredScriptDigest: digest }));
234
- ok(msg(first, "taken", "c1", "taken")); begin(first);
235
- ok(msg(first, "pending", "c1", "pending"));
236
- const revision = ok(first.snapshot()).revision;
237
- ok(first.close());
238
- refused(adapter.open({ mode: "open", identity: tagged(changed), requiredScriptDigest: changed }), "incompatible");
239
- const reopened = ok(adapter.open({ mode: "open", identity: tagged(digest, "d"), requiredScriptDigest: digest }));
240
- const snapshot = ok(reopened.snapshot());
241
- expect(snapshot.revision).toBe(revision + 1);
242
- expect(snapshot.turns[0]?.state.status).toBe("interrupted");
243
- expect(snapshot.items.find(item => item.itemId === "pending")?.milestone).toBe("received");
244
- expect(snapshot.session.compatibilityKey).toBe(tagged(digest).compatibilityKey);
245
- ok(reopened.close());
246
- });
247
-
248
- test("operator ranges separate conversation text, replies, and timeline activity", () => {
249
- const { adapter, s } = create();
250
- ok(msg(s, "original", "c1", "a"));
251
- const first = begin(s).turn.turnId;
252
- call(s, first, "echo");
253
- ok(s.appendMessage(first, { role: "tool", callId: "echo", content: "result" }));
254
- const reply = say(s, first, "answer");
255
- ok(s.finishTurn(first, { status: "completed" }));
256
- ok(msg(s, "other", "c2", "b"));
257
- const second = begin(s, "c2").turn.turnId;
258
- say(s, second, "other answer");
259
- ok(s.finishTurn(second, { status: "completed" }));
260
- const owner = reopen(adapter, s);
261
- const throughRevision = snap(owner).revision;
262
- const newest = ok(owner.readTimeline({ kind: "conversation", channel: "c1", direction: "older", throughRevision, limit: 1 }));
263
- expect(newest.entries.map(entry => entry.seq)).toEqual([reply.seq]);
264
- expect(newest.more).toBe(true);
265
- const older = ok(owner.readTimeline({ kind: "conversation", channel: "c1", direction: "older", throughRevision, exclusiveSeq: reply.seq, limit: 1 }));
266
- expect(older.entries.map(entry => entry.itemId)).toEqual(["a"]);
267
- expect(older.more).toBe(false);
268
- expect(ok(owner.readTimeline({ kind: "replies", channel: "c1", turnIds: [first, second], direction: "newer", throughRevision, limit: 10 })).entries.map(entry => entry.seq)).toEqual([reply.seq]);
269
- expect(ok(owner.readTimeline({ kind: "timeline", direction: "newer", throughRevision, limit: 10 })).entries.map(entry => entry.message.role)).toEqual(["user", "assistant", "tool", "assistant", "user", "assistant"]);
270
- const tracked = ok(owner.readTracked("c1", ["a", "b"], [first, second]));
271
- expect(tracked.items.map(item => item.itemId)).toEqual(["a"]);
272
- expect(tracked.turns.map(turn => [turn.turnId, turn.itemIds])).toEqual([[first, ["a"]]]);
273
- expect(ok(owner.readChannel("c1")).pendingCount).toBe(0);
274
- ok(owner.close());
275
- });
276
-
277
- test("explicit create/open, ownership, identity and closed handles", () => {
278
- const adapter = location();
279
- refused(adapter.open({ mode: "open", identity: id() }), "not_found");
280
- refused(adapter.open({ mode: "bogus" as "open", identity: id() }), "invalid_input");
281
- const s = ok(adapter.open({ mode: "create", identity: id() }));
282
- refused(adapter.open({ mode: "open", identity: id() }), "owner_conflict");
283
- ok(msg(s, "hello"));
284
- ok(s.close()); ok(s.close());
285
- refused(s.snapshot(), "closed"); refused(msg(s, "x"), "closed"); refused(s.beginTurn("c1"), "closed");
286
- refused(adapter.open({ mode: "create", identity: id() }), "already_exists");
287
- refused(adapter.open({ mode: "open", identity: { sessionId: "other", compatibilityKey: "k1" } }), "incompatible");
288
- // A different key opens normally and is never written.
289
- const again = ok(adapter.open({ mode: "open", identity: id("k2") }));
290
- const view = snap(again);
291
- expect(view.session).toMatchObject({ sessionId: "s1", formatVersion: 6, lifecycle: "running", compatibilityKey: "k1" });
292
- expect(view.items.map(item => item.text)).toEqual(["hello"]);
293
- ok(again.close());
294
- expect(snap(ok(adapter.open({ mode: "open", identity: id() }))).session.compatibilityKey).toBe("k1");
295
- });
296
-
297
- test("acceptance commits a pending item with the exact signature and allocated IDs", () => {
298
- const { s } = create();
299
- const first = ok(msg(s, "one"));
300
- expect(first).toMatchObject({ duplicate: false, item: { itemId: "auto:1", milestone: "received", acceptedSeq: 1 } });
301
- expect(first.item.turnId).toBeUndefined();
302
- expect(first.item.signature).toBe(createHash("sha256")
303
- .update(JSON.stringify(["participant_message", "c1", "ana", null, "one", null]), "utf8").digest("hex"));
304
- expect(ok(notice(s, "ping")).item).toMatchObject({ itemId: "auto:2", sourceChannelId: "c2",
305
- signature: createHash("sha256").update(JSON.stringify(["channel_notice", "c1", "channel:c2", "c2", "ping", null])).digest("hex") });
306
- expect(ok(msg(s, "reserved", "c1", "auto:7")).item.itemId).toBe("auto:7");
307
- expect(ok(msg(s, "next")).item.itemId).toBe("auto:8");
308
- expect(ok(msg(s, "low", "c1", "auto:3")).item.itemId).toBe("auto:3");
309
- expect(ok(msg(s, "after")).item.itemId).toBe("auto:9");
310
- const view = snap(s);
311
- // Accepted work is outside the timeline and creates no turn.
312
- expect(view.timeline).toEqual([]); expect(view.turns).toEqual([]);
313
- expect(view.channels).toEqual([{ channelId: "c1", lifecycle: "open", participantIds: [] }]);
314
- expect(view.participants).toEqual([{ participantId: "ana" }]);
315
- expect(view.items.map(item => item.acceptedSeq)).toEqual([1, 2, 3, 4, 5, 6]);
316
- expect(view.revision).toBe(6);
317
- });
318
-
319
- test("identical retries return the original; conflicts and invalid input change nothing", () => {
320
- const { adapter, s } = create();
321
- const original = ok(msg(s, "pay", "c1", "m1"));
322
- unchanged(s, () => {
323
- const retry = s.acceptItem({ itemId: "m1", kind: "participant_message", channelId: "c1", senderId: "ana", text: "pay" });
324
- expect(ok(retry)).toEqual({ item: original.item, duplicate: true });
325
- expect(retry.ok && retry.revision).toBe(1);
326
- refused(msg(s, "pay twice", "c1", "m1"), "item_conflict");
327
- refused(msg(s, "pay", "c9", "m1"), "item_conflict");
328
- refused(msg(s, " "), "invalid_input");
329
- refused(msg(s, "x", " "), "invalid_input");
330
- refused(s.acceptItem({ kind: "other" as "channel_notice", channelId: "c1", senderId: "ana", text: "x" }), "invalid_input");
331
- refused(s.acceptItem({ kind: "channel_notice", channelId: "c1", senderId: "channel:c2", text: "no source" }), "invalid_input");
332
- refused(s.acceptItem(null as never), "invalid_input");
333
- refused(notice(s, "nobody home", "never-used"), "not_found");
334
- });
335
- const turn = begin(s);
336
- const later = reopen(adapter, s);
337
- // After restart the retry reports where the original now is.
338
- expect(ok(msg(later, "pay", "c1", "m1"))).toMatchObject({ duplicate: true, item: { milestone: "taken", turnId: turn.turn.turnId } });
339
- refused(msg(later, "different", "c1", "m1"), "item_conflict");
340
- });
341
-
342
- test("beginTurn takes every pending item once, in acceptance order", () => {
343
- const { s } = create();
344
- ok(msg(s, "a", "c1", "a")); ok(msg(s, "other", "c2", "z")); ok(notice(s, "n")); ok(msg(s, "b", "c1", "b"));
345
- refused(s.beginTurn("empty"), "not_found");
346
- const taken = begin(s);
347
- expect(taken.turn).toMatchObject({ turnId: 1, channelId: "c1", itemIds: ["a", "auto:1", "b"], compatibilityKey: "k1", state: { status: "running" } });
348
- expect(taken.items.map(item => [item.milestone, item.turnId])).toEqual([["taken", 1], ["taken", 1], ["taken", 1]]);
349
- expect(taken.entries.map(entry => entry.message)).toEqual([
350
- { role: "user", content: 'Participant: "ana"\n\na' }, { role: "user", content: "n" }, { role: "user", content: 'Participant: "ana"\n\nb' }]);
351
- expect(taken.entries.map(entry => [entry.from, entry.kind, entry.itemId, entry.sourceChannelId])).toEqual([
352
- ["ana", "participant_message", "a", undefined], ["channel:c2", "channel_notice", "auto:1", "c2"], ["ana", "participant_message", "b", undefined]]);
353
- expect(taken.items.map(item => item.entrySeq)).toEqual(taken.entries.map(entry => entry.seq));
354
- // One live turn per channel; another channel is independent.
355
- ok(msg(s, "c", "c1", "c"));
356
- unchanged(s, () => expect(ok(s.beginTurn("c1"))).toBeNull());
357
- expect(begin(s, "c2").turn).toMatchObject({ turnId: 2, itemIds: ["z"] });
358
- const view = snap(s);
359
- expect(view.channels).toEqual([{ channelId: "c1", lifecycle: "open", participantIds: ["ana"] }, { channelId: "c2", lifecycle: "open", participantIds: ["ana"] }]);
360
- expect(view.items.find(item => item.itemId === "c")).toMatchObject({ milestone: "received" });
361
- const seqs = view.timeline.map(entry => entry.seq);
362
- expect(seqs).toEqual([...seqs].sort((x, y) => x - y)); expect(new Set(seqs).size).toBe(seqs.length);
363
- });
364
-
365
- test("the finish decision and the pending check are one step", () => {
366
- const { s } = create();
367
- ok(msg(s, "a", "c1", "a"));
368
- const { turn } = begin(s);
369
- unchanged(s, () => refused(s.finishTurn(turn.turnId, { status: "completed" }), "invalid_state"));
370
- say(s, turn.turnId, "answer");
371
- // Accept commits first: the turn stays open and takes the item itself.
372
- ok(msg(s, "b", "c1", "b"));
373
- unchanged(s, () => expect(ok(s.finishTurn(turn.turnId, { status: "completed" }))).toEqual({ finished: false, pending: 1 }));
374
- unchanged(s, () => expect(ok(s.beginTurn("c1"))).toBeNull());
375
- expect(ok(s.takePending(turn.turnId))).toMatchObject({ turn: { itemIds: ["a", "b"] }, items: [{ itemId: "b", turnId: turn.turnId }] });
376
- unchanged(s, () => expect(ok(s.takePending(turn.turnId)).items).toEqual([]));
377
- unchanged(s, () => refused(s.finishTurn(turn.turnId, { status: "completed" }), "invalid_state"));
378
- say(s, turn.turnId, "second answer");
379
- expect(ok(s.finishTurn(turn.turnId, { status: "completed" }))).toMatchObject({ finished: true, turn: { state: { status: "completed" }, itemIds: ["a", "b"] } });
380
- // Finish commits first: the item starts the next turn, exactly once.
381
- ok(msg(s, "c", "c1", "c"));
382
- unchanged(s, () => {
383
- refused(s.takePending(turn.turnId), "invalid_state");
384
- refused(s.finishTurn(turn.turnId, { status: "completed" }), "invalid_state");
385
- refused(s.finishTurn(turn.turnId, { status: "failed", reason: "late" }), "invalid_state");
386
- });
387
- expect(begin(s).turn).toMatchObject({ turnId: 2, itemIds: ["c"] });
388
- expect(snap(s).items.filter(item => item.itemId === "c")).toHaveLength(1);
389
- });
390
-
391
- test("messages pair calls with results and reject unserializable data without partial writes", () => {
392
- const { s } = create();
393
- ok(msg(s, "a"));
394
- const { turn } = begin(s), t = turn.turnId;
395
- unchanged(s, () => {
396
- refused(s.appendMessage(t, { role: "tool", callId: "x", content: "orphan" }), "invalid_input");
397
- refused(s.appendMessage(t, { role: "user", content: "no" } as never), "invalid_input");
398
- refused(s.appendMessage(99, { role: "assistant", content: "x", calls: [] }), "not_found");
399
- refused(s.appendMessage(t, { role: "assistant", content: null, calls: [], providerState: { at: new Date() } }), "serialization_error");
400
- refused(s.appendMessage(t, { role: "assistant", content: null, calls: [], providerState: { fn() {} } }), "serialization_error");
401
- refused(s.appendMessage(t, { role: "assistant", content: null, calls: [], providerState: { gap: undefined } }), "serialization_error");
402
- refused(s.appendMessage(t, { role: "assistant", content: null, calls: [], providerState: 10n }), "serialization_error");
403
- refused(s.appendMessage(t, { role: "assistant", content: null, calls: [{ id: "x", name: "echo", arguments: "{}" }, { id: "x", name: "echo", arguments: "{}" }] }), "invalid_input");
404
- });
405
- const state = { opaque: [1, "two", { three: null }] };
406
- const requested = ok(s.appendMessage(t, { role: "assistant", content: "working", providerState: state,
407
- calls: [{ id: "c1", name: "echo", arguments: "{\"a\":1}" }, { id: "c2", name: "echo", arguments: "{}" }] }));
408
- expect(requested).toMatchObject({ from: "agent", turnId: t, channelId: "c1" });
409
- unchanged(s, () => {
410
- refused(s.appendMessage(t, { role: "assistant", content: "too early", calls: [] }), "invalid_state");
411
- refused(s.finishTurn(t, { status: "completed" }), "invalid_state");
412
- });
413
- expect(ok(s.appendMessage(t, { role: "tool", callId: "c2", content: "r2" })).from).toBe("tool");
414
- unchanged(s, () => refused(s.appendMessage(t, { role: "tool", callId: "c2", content: "again" }), "invalid_input"));
415
- ok(s.appendMessage(t, { role: "tool", callId: "c1", content: "r1" }));
416
- unchanged(s, () => refused(s.appendMessage(t, { role: "assistant", content: null, calls: [{ id: "c1", name: "echo", arguments: "{}" }] }), "invalid_input"));
417
- say(s, t, "done");
418
- ok(s.finishTurn(t, { status: "completed" }));
419
- const stored = snap(s).timeline.find(entry => entry.seq === requested.seq)!.message;
420
- expect(stored.role === "assistant" && stored.providerState).toEqual(state);
421
- });
422
-
423
- test("results and snapshots never alias stored records", () => {
424
- const { s } = create();
425
- const accepted = ok(msg(s, "a"));
426
- accepted.item.text = "tampered";
427
- const taken = begin(s);
428
- taken.turn.itemIds.push("ghost"); taken.entries[0]!.message = { role: "user", content: "tampered" };
429
- const view = snap(s);
430
- view.items[0]!.milestone = "seen"; view.turns[0]!.state = { status: "completed" };
431
- const fresh = snap(s);
432
- expect(fresh.items[0]).toMatchObject({ text: "a", milestone: "taken" });
433
- expect(fresh.turns[0]).toMatchObject({ itemIds: ["auto:1"], state: { status: "running" } });
434
- expect(fresh.timeline[0]!.message).toEqual({ role: "user", content: 'Participant: "ana"\n\na' });
435
- });
436
-
437
- test("receipts advance only for a running turn's items and only forward", () => {
438
- const { adapter, s } = create();
439
- ok(msg(s, "a", "c1", "a")); ok(msg(s, "elsewhere", "c2", "z"));
440
- const { turn } = begin(s), t = turn.turnId;
441
- begin(s, "c2");
442
- expect(ok(s.confirmReceipts(t, "delivered")).map(item => [item.itemId, item.milestone])).toEqual([["a", "delivered"]]);
443
- unchanged(s, () => expect(ok(s.confirmReceipts(t, "delivered"))).toEqual([]));
444
- ok(msg(s, "b", "c1", "b")); ok(s.takePending(t));
445
- expect(ok(s.confirmReceipts(t, "seen")).map(item => item.itemId)).toEqual(["a", "b"]);
446
- unchanged(s, () => {
447
- expect(ok(s.confirmReceipts(t, "delivered"))).toEqual([]);
448
- refused(s.confirmReceipts(t, "taken" as "seen"), "invalid_input");
449
- refused(s.confirmReceipts(77, "seen"), "not_found");
450
- });
451
- // Another channel's inference never advanced these.
452
- expect(snap(s).items.find(item => item.itemId === "z")!.milestone).toBe("taken");
453
- ok(s.finishTurn(t, { status: "interrupted", reason: "stop" }));
454
- unchanged(s, () => refused(s.confirmReceipts(t, "seen"), "invalid_state"));
455
- const view = snap(reopen(adapter, s));
456
- expect(view.items.filter(item => item.channelId === "c1").map(item => [item.milestone, item.turnId])).toEqual([["seen", t], ["seen", t]]);
457
- });
458
-
459
- test("failed and interrupted turns keep their record, fence late output and leave the channel usable", () => {
460
- const { s } = create();
461
- for (const status of ["failed", "interrupted"] as const) {
462
- ok(msg(s, `ask ${status}`));
463
- const { turn } = begin(s), t = turn.turnId;
464
- call(s, t, `${status}-1`);
465
- ok(s.appendMessage(t, { role: "tool", callId: `${status}-1`, content: "kept" }));
466
- call(s, t, `${status}-2`);
467
- ok(msg(s, "queued behind", "c1", `${status}-queued`));
468
- unchanged(s, () => refused(s.finishTurn(t, { status, reason: " " }), "invalid_input"));
469
- expect(ok(s.finishTurn(t, { status, reason: "boom" }))).toMatchObject({ finished: true,
470
- turn: { state: { status, reason: "boom", uncertainCallIds: [`${status}-2`] } } });
471
- // The late result of the uncertain call, a late receipt and a late take all commit nothing.
472
- unchanged(s, () => {
473
- refused(s.appendMessage(t, { role: "tool", callId: `${status}-2`, content: "late" }), "invalid_state");
474
- refused(s.appendMessage(t, { role: "assistant", content: "late", calls: [] }), "invalid_state");
475
- refused(s.confirmReceipts(t, "seen"), "invalid_state");
476
- refused(s.takePending(t), "invalid_state");
477
- refused(s.checkpointTurn(t), "invalid_state");
478
- refused(s.finishTurn(t, { status: "completed" }), "invalid_state");
479
- refused(s.finishTurn(t, { status: "interrupted", reason: "again" }), "invalid_state");
480
- });
481
- const view = snap(s);
482
- expect(view.timeline.filter(entry => entry.turnId === t).map(entry => entry.message.role)).toEqual(["user", "assistant", "tool", "assistant"]);
483
- expect(view.items.find(item => item.turnId === t)).toMatchObject({ milestone: "taken" });
484
- // Fresh work runs on the same channel; the uncertain call stays unanswered forever.
485
- const next = begin(s);
486
- expect(next.turn.itemIds).toEqual([`${status}-queued`]);
487
- say(s, next.turn.turnId, "fresh");
488
- ok(s.finishTurn(next.turn.turnId, { status: "completed" }));
489
- expect(snap(s).turns.find(row => row.turnId === t)!.state).toEqual({ status, reason: "boom", uncertainCallIds: [`${status}-2`] });
490
- }
491
- });
492
-
493
- test("IDs, seq and revision keep increasing across reopen", () => {
494
- const { adapter, s } = create();
495
- ok(msg(s, "a"));
496
- const first = begin(s);
497
- say(s, first.turn.turnId, "one");
498
- ok(s.finishTurn(first.turn.turnId, { status: "completed" }));
499
- const before = snap(s);
500
- const again = reopen(adapter, s);
501
- // A clean, idle reopen writes nothing.
502
- expect(snap(again)).toEqual(before);
503
- expect(ok(msg(again, "b")).item).toMatchObject({ itemId: "auto:2", acceptedSeq: before.revision + 1 });
504
- const second = begin(again);
505
- expect(second.turn.turnId).toBe(2);
506
- expect(second.entries[0]!.seq).toBeGreaterThan(before.timeline.at(-1)!.seq);
507
- const after = snap(again);
508
- expect(after.revision).toBeGreaterThan(before.revision);
509
- expect(after.timeline.slice(0, before.timeline.length)).toEqual(before.timeline);
510
- });
511
-
512
- test("suspension refuses new messages, starts nothing and still accepts notices", () => {
513
- const { s } = create();
514
- ok(msg(s, "a", "c1", "a")); ok(msg(s, "idle channel", "c2", "z"));
515
- const { turn } = begin(s);
516
- unchanged(s, () => { refused(s.checkpointTurn(turn.turnId), "invalid_state"); refused(s.completeSuspend(), "invalid_state"); });
517
- expect(ok(s.beginSuspend()).lifecycle).toBe("suspending");
518
- unchanged(s, () => {
519
- expect(ok(s.beginSuspend()).lifecycle).toBe("suspending");
520
- refused(msg(s, "new"), "not_running");
521
- refused(s.beginTurn("c2"), "not_running");
522
- refused(s.takePending(turn.turnId), "not_running");
523
- refused(s.resume(), "invalid_state");
524
- refused(s.completeSuspend(), "invalid_state");
525
- // A retry of accepted input is still answered.
526
- expect(ok(msg(s, "a", "c1", "a"))).toMatchObject({ duplicate: true, item: { milestone: "taken" } });
527
- });
528
- expect(ok(notice(s, "from finishing work")).item.milestone).toBe("received");
529
- expect(snap(s).items.filter(item => item.milestone === "received").map(item => item.channelId)).toEqual(["c2", "c1"]);
530
- });
531
-
532
- test("while suspending a finished turn completes and a turn needing inference is checkpointed", () => {
533
- const { adapter, s } = create();
534
- ok(msg(s, "done soon", "c1")); ok(msg(s, "needs tools", "c2")); ok(msg(s, "gets a notice", "c3")); ok(msg(s, "just begun", "c4"));
535
- const done = begin(s, "c1").turn.turnId, tools = begin(s, "c2").turn.turnId, noticed = begin(s, "c3").turn.turnId, fresh = begin(s, "c4").turn.turnId;
536
- call(s, tools, "t1");
537
- ok(s.beginSuspend());
538
- // Naturally finished, nothing pending: complete, never checkpoint.
539
- say(s, done, "final");
540
- unchanged(s, () => refused(s.checkpointTurn(done), "invalid_state"));
541
- expect(ok(s.finishTurn(done, { status: "completed" })).finished).toBe(true);
542
- // An unanswered call cannot be checkpointed; after its result the next step is inference.
543
- unchanged(s, () => refused(s.checkpointTurn(tools), "invalid_state"));
544
- const result = ok(s.appendMessage(tools, { role: "tool", callId: "t1", content: "r" }));
545
- expect(ok(s.checkpointTurn(tools)).state).toMatchObject({ status: "suspended", checkpoint: { nextStep: "inference", afterSeq: result.seq } });
546
- // A notice that won the finish race keeps its turn open: checkpoint, do not take.
547
- say(s, noticed, "final?");
548
- ok(notice(s, "wait for me", "c3"));
549
- unchanged(s, () => expect(ok(s.finishTurn(noticed, { status: "completed" }))).toEqual({ finished: false, pending: 1 }));
550
- expect(ok(s.checkpointTurn(noticed)).state.status).toBe("suspended");
551
- unchanged(s, () => { refused(s.completeSuspend(), "invalid_state"); refused(s.checkpointTurn(noticed), "invalid_state"); });
552
- expect(ok(s.checkpointTurn(fresh)).state.status).toBe("suspended");
553
- expect(ok(s.completeSuspend()).lifecycle).toBe("suspended");
554
- unchanged(s, () => {
555
- expect(ok(s.completeSuspend()).lifecycle).toBe("suspended"); expect(ok(s.beginSuspend()).lifecycle).toBe("suspended");
556
- refused(msg(s, "new"), "not_running"); refused(notice(s, "new"), "not_running"); refused(s.beginTurn("c1"), "not_running");
557
- expect(ok(msg(s, "done soon", "c1", "auto:1"))).toMatchObject({ duplicate: true, item: { milestone: "taken", turnId: done } });
558
- refused(msg(s, "changed", "c1", "auto:1"), "item_conflict");
559
- expect(ok(s.interruptActive("stop"))).toEqual([]);
560
- });
561
-
562
- // Clean suspension survives reopen untouched, and nothing runs.
563
- const suspended = snap(s);
564
- const wrong = reopen(adapter, s, "k2");
565
- expect(snap(wrong)).toEqual(suspended);
566
- unchanged(wrong, () => refused(wrong.resume(), "incompatible"));
567
- const right = reopen(adapter, wrong);
568
- expect(snap(right)).toEqual(suspended);
569
- const resumed = ok(right.resume());
570
- expect(resumed.session.lifecycle).toBe("running");
571
- expect(resumed.turns.map(turn => [turn.turnId, turn.state.status])).toEqual([[tools, "running"], [noticed, "running"], [fresh, "running"]]);
572
- unchanged(right, () => expect(ok(right.resume()).turns).toEqual([]));
573
- // The resumed turn takes the item that lost the race; it reaches exactly one turn.
574
- expect(ok(right.takePending(noticed)).items.map(item => item.turnId)).toEqual([noticed]);
575
- expect(ok(right.beginTurn("c3"))).toBeNull();
576
- expect(snap(right).turns.find(turn => turn.turnId === done)!.state).toEqual({ status: "completed" });
577
- });
578
-
579
- test("interruptActive follows the lifecycle", () => {
580
- const { adapter, s } = create();
581
- ok(msg(s, "a", "c1")); ok(msg(s, "b", "c2")); ok(msg(s, "waiting", "c3", "w"));
582
- const one = begin(s, "c1").turn.turnId, two = begin(s, "c2").turn.turnId;
583
- call(s, one, "x1");
584
- unchanged(s, () => refused(s.interruptActive(""), "invalid_input"));
585
- // Running: only running turns, pending input untouched.
586
- expect(ok(s.interruptActive("stop")).map(turn => [turn.turnId, turn.state])).toEqual([
587
- [one, { status: "interrupted", reason: "stop", uncertainCallIds: ["x1"] }], [two, { status: "interrupted", reason: "stop", uncertainCallIds: [] }]]);
588
- unchanged(s, () => expect(ok(s.interruptActive("stop"))).toEqual([]));
589
- expect(snap(s).items.find(item => item.itemId === "w")!.milestone).toBe("received");
590
-
591
- // Suspending: running and already checkpointed turns; this attempt can no longer suspend.
592
- ok(msg(s, "c", "c1")); ok(msg(s, "d", "c2"));
593
- const saved = begin(s, "c1").turn.turnId, active = begin(s, "c2").turn.turnId;
594
- ok(s.beginSuspend()); ok(s.checkpointTurn(saved));
595
- expect(ok(s.interruptActive("stop now")).map(turn => [turn.turnId, turn.state.status])).toEqual([[saved, "interrupted"], [active, "interrupted"]]);
596
- expect(snap(s).session.lifecycle).toBe("running");
597
- unchanged(s, () => refused(s.completeSuspend(), "invalid_state"));
598
-
599
- // Suspended: clean checkpoints are kept.
600
- const kept = begin(s, "c3").turn.turnId;
601
- ok(s.beginSuspend()); ok(s.checkpointTurn(kept)); ok(s.completeSuspend());
602
- unchanged(s, () => expect(ok(s.interruptActive("stop"))).toEqual([]));
603
- expect(snap(reopen(adapter, s)).turns.find(turn => turn.turnId === kept)!.state.status).toBe("suspended");
604
- });
605
-
606
- test("reopen without clean suspension interrupts running and checkpointed turns", () => {
607
- for (const lifecycle of ["running", "suspending"] as const) {
608
- const { adapter, s } = create();
609
- ok(msg(s, "a", "c1", "a")); ok(msg(s, "b", "c2", "b")); ok(msg(s, "never taken", "c3", "p"));
610
- const one = begin(s, "c1").turn.turnId, two = begin(s, "c2").turn.turnId;
611
- call(s, one, "u1");
612
- ok(s.confirmReceipts(one, "seen"));
613
- if (lifecycle === "suspending") { ok(s.beginSuspend()); ok(s.checkpointTurn(two)); }
614
- const before = snap(s);
615
- const again = reopen(adapter, s);
616
- const view = snap(again);
617
- expect(view.session.lifecycle).toBe("running");
618
- expect(view.turns.map(turn => [turn.turnId, turn.state.status])).toEqual([[one, "interrupted"], [two, "interrupted"]]);
619
- expect(view.turns[0]!.state).toMatchObject({ uncertainCallIds: ["u1"] });
620
- // Taken items stay with their turn; untaken input stays pending; history is intact.
621
- expect(view.items.map(item => [item.itemId, item.milestone, item.turnId])).toEqual([["a", "seen", one], ["b", "taken", two], ["p", "received", undefined]]);
622
- expect(view.timeline).toEqual(before.timeline);
623
- expect(view.revision).toBeGreaterThan(before.revision);
624
- // Recovery ran once: a second reopen changes nothing.
625
- expect(snap(reopen(adapter, again))).toEqual(view);
626
- }
627
- });
628
-
629
- test("recovered channels accept and run fresh work without replaying the uncertain call", () => {
630
- const { adapter, s } = create();
631
- ok(msg(s, "a"));
632
- const old = begin(s).turn.turnId;
633
- call(s, old, "effect");
634
- const again = reopen(adapter, s);
635
- unchanged(again, () => refused(again.appendMessage(old, { role: "tool", callId: "effect", content: "late" }), "invalid_state"));
636
- ok(msg(again, "fresh"));
637
- const next = begin(again).turn;
638
- expect(next.turnId).toBe(old + 1);
639
- say(again, next.turnId, "ok");
640
- expect(ok(again.finishTurn(next.turnId, { status: "completed" })).finished).toBe(true);
641
- expect(snap(again).turns[0]!.state).toMatchObject({ status: "interrupted", uncertainCallIds: ["effect"] });
642
- });
643
-
644
- test("decision 0021: revoked tools are a durable sorted set; a repeat writes nothing; they survive reopen, export and import", () => {
645
- const { adapter, s } = create();
646
- expect(snap(s).revokedTools).toBeUndefined();
647
- refused(s.setToolRevoked("", true), "invalid_input");
648
- unchanged(s, () => { expect(ok(s.setToolRevoked("never-revoked", false))).toEqual([]); });
649
- expect(ok(s.setToolRevoked("zeta", true))).toEqual(["zeta"]);
650
- expect(ok(s.setToolRevoked("alpha", true))).toEqual(["alpha", "zeta"]);
651
- unchanged(s, () => { expect(ok(s.setToolRevoked("alpha", true))).toEqual(["alpha", "zeta"]); });
652
- expect(ok(s.setToolRevoked("zeta", false))).toEqual(["alpha"]);
653
- const reopened = reopen(adapter, s);
654
- expect(snap(reopened).revokedTools).toEqual(["alpha"]);
655
- const archive = ok(reopened.exportArchive());
656
- expect(archive.snapshot.revokedTools).toEqual(["alpha"]);
657
- const copy = location();
658
- ok(copy.importArchive(archive));
659
- const imported = ok(copy.open({ mode: "open", identity: id() }));
660
- expect(snap(imported).revokedTools).toEqual(["alpha"]);
661
- for (const bad of [["b", "a"], ["a", "a"], [""], "a"]) {
662
- const broken = structuredClone(archive) as any; broken.snapshot.revokedTools = bad;
663
- refused(location().importArchive(broken), "invalid_archive");
664
- }
665
- ok(imported.close()); ok(reopened.close());
666
- });
667
-
668
- test("decision 0021: a tool result may carry a typed outcome; a malformed one is refused with nothing written", () => {
669
- const { adapter, s } = create();
670
- msg(s, "go"); const turn = begin(s).turn.turnId;
671
- ok(s.appendMessage(turn, { role: "assistant", content: null, calls: [{ id: "a", name: "lookup", arguments: "{}" }, { id: "b", name: "lookup", arguments: "{}" }, { id: "c", name: "lookup", arguments: "{}" }] }));
672
- for (const outcome of [{ status: "done" }, { status: "skipped", code: "" }, { status: "succeeded", extra: 1 }, "skipped",
673
- { status: "succeeded", reference: { resultId: "r", bytes: -1, retention: "temporary" } }, { status: "succeeded", reference: { resultId: "r", bytes: 1, retention: "forever" } }])
674
- unchanged(s, () => refused(s.appendMessage(turn, { role: "tool", callId: "a", content: "x", outcome } as any), "invalid_input"));
675
- const reference = { resultId: "res-1", bytes: 40000, retention: "temporary" as const, expiresAt: "2026-11-21T00:00:00.000Z" };
676
- ok(s.appendMessage(turn, { role: "tool", callId: "a", content: "{}", outcome: { status: "skipped", code: "tool_unavailable" } }));
677
- ok(s.appendMessage(turn, { role: "tool", callId: "b", content: "preview", outcome: { status: "succeeded", reference } }));
678
- ok(s.appendMessage(turn, { role: "tool", callId: "c", content: "legacy" }));
679
- const results = (view: ReturnType<typeof snap>) => view.timeline.filter(entry => entry.message.role === "tool").map(entry => entry.message);
680
- const expected = [{ role: "tool", callId: "a", content: "{}", outcome: { status: "skipped", code: "tool_unavailable" } },
681
- { role: "tool", callId: "b", content: "preview", outcome: { status: "succeeded", reference } }, { role: "tool", callId: "c", content: "legacy" }];
682
- expect(results(snap(s))).toEqual(expected as any);
683
- const reopened = reopen(adapter, s);
684
- expect(results(snap(reopened))).toEqual(expected as any);
685
- ok(reopened.close());
686
- });
687
-
688
- test("export needs an idle or cleanly suspended session", () => {
689
- const { s } = create();
690
- expect(ok(s.exportArchive())).toMatchObject({ format: "harness-session", archiveVersion: 5, allocation: { nextTurnId: 1, nextSeq: 1, nextItemNumber: 1 } });
691
- ok(msg(s, "a"));
692
- unchanged(s, () => refused(s.exportArchive(), "busy"));
693
- const t = begin(s).turn.turnId;
694
- unchanged(s, () => refused(s.exportArchive(), "busy"));
695
- ok(s.beginSuspend()); ok(s.checkpointTurn(t));
696
- // Every turn is checkpointed, yet suspension has not committed.
697
- unchanged(s, () => refused(s.exportArchive(), "busy"));
698
- ok(s.completeSuspend());
699
- unchanged(s, () => expect(ok(s.exportArchive()).snapshot).toEqual(snap(s)));
700
- ok(s.resume()); say(s, t, "x"); ok(s.finishTurn(t, { status: "completed" }));
701
- expect(ok(s.exportArchive()).snapshot.session.lifecycle).toBe("running");
702
- });
703
-
704
- // ---- Channel controls, decision 0014.
705
- const lifecycleOf = (s: SessionStorage, channelId: string) => snap(s).channels.find(c => c.channelId === channelId)?.lifecycle;
706
- const stateOf = (s: SessionStorage, turnId: number) => snap(s).turns.find(t => t.turnId === turnId)!.state.status;
707
- /** Turn on `c1` that took "a", ran one tool call and recorded its result: at an inference boundary. */
708
- function atBoundary(s: SessionStorage, channelId = "c1") {
709
- ok(msg(s, "a", channelId, `a-${channelId}`));
710
- const turn = begin(s, channelId).turn.turnId;
711
- call(s, turn, "k"); ok(s.appendMessage(turn, { role: "tool", callId: "k", content: "done" }));
712
- return turn;
713
- }
714
-
715
- test("channel suspension closes admission, checkpoints with the backlog kept, and survives reopen", () => {
716
- const { adapter, s: first } = create();
717
- let s = first;
718
- const t = atBoundary(s); ok(msg(s, "other", "c2", "o2"));
719
- ok(msg(s, "p", "c1", "p"));
720
- const other = begin(s, "c2").turn.turnId;
721
- expect(ok(s.beginChannelSuspend("c1"))).toMatchObject({ lifecycle: "suspending" });
722
- expect(ok(s.beginChannelSuspend("c1")).lifecycle).toBe("suspending");
723
- // Closed to new input and to taking, for messages and notices alike; retries of accepted input answer.
724
- unchanged(s, () => {
725
- refused(msg(s, "new"), "channel_suspended"); refused(notice(s, "new"), "channel_suspended");
726
- refused(s.takePending(t), "channel_suspended"); refused(s.resumeChannel("c1"), "invalid_state");
727
- refused(s.deleteChannel("c1"), "channel_busy");
728
- expect(ok(msg(s, "p", "c1", "p"))).toMatchObject({ duplicate: true, item: { milestone: "received" } });
729
- refused(msg(s, "different", "c1", "p"), "item_conflict");
730
- });
731
- // Another channel keeps running, and the finishing turn may notify an open channel.
732
- expect(ok(s.acceptItem({ kind: "channel_notice", channelId: "c2", senderId: "channel:c1", sourceChannelId: "c1", text: "hi" })).duplicate).toBe(false);
733
- say(s, other, "ok");
734
- expect(ok(s.finishTurn(other, { status: "completed" })).finished).toBe(false); // the notice arrived first
735
- // A pending item blocks completion: the turn must checkpoint, and the channel suspends with it.
736
- say(s, t, "answer");
737
- expect(ok(s.finishTurn(t, { status: "completed" }))).toEqual({ finished: false, pending: 1 });
738
- expect(lifecycleOf(s, "c1")).toBe("suspending");
739
- const saved = ok(s.checkpointTurn(t));
740
- expect(saved.state).toMatchObject({ status: "suspended" });
741
- expect(lifecycleOf(s, "c1")).toBe("suspended");
742
- refused(s.exportArchive(), "busy");
743
- s = reopen(adapter, s); // the session was never suspended: only the channel's commit holds the checkpoint
744
- expect(lifecycleOf(s, "c1")).toBe("suspended");
745
- expect(stateOf(s, t)).toBe("suspended");
746
- expect(snap(s).items.find(item => item.itemId === "p")!.milestone).toBe("received");
747
- refused(msg(s, "new"), "channel_suspended");
748
- refused(s.beginTurn("c1"), "channel_suspended");
749
- const resumed = ok(s.resumeChannel("c1"));
750
- expect(resumed.channel.lifecycle).toBe("open");
751
- expect(resumed.turn).toMatchObject({ turnId: t, state: { status: "running" } });
752
- expect(ok(s.takePending(t)).items.map(item => item.itemId)).toEqual(["p"]);
753
- expect(ok(s.takePending(t)).items).toEqual([]);
754
- expect(snap(s).turns.filter(turn => turn.channelId === "c1")).toHaveLength(1);
755
- });
756
-
757
- test("an idle or already checkpointed channel suspends at once; resume of an open channel is a no-op", () => {
758
- const { s } = create();
759
- ok(s.createChannel({ channelId: "idle" }));
760
- expect(ok(s.beginChannelSuspend("idle")).lifecycle).toBe("suspended");
761
- unchanged(s, () => expect(ok(s.beginChannelSuspend("idle")).lifecycle).toBe("suspended"));
762
- refused(msg(s, "x", "idle"), "channel_suspended");
763
- expect(ok(s.resumeChannel("idle"))).toMatchObject({ channel: { lifecycle: "open" } });
764
- unchanged(s, () => expect(ok(s.resumeChannel("idle")).turn).toBeUndefined());
765
- ok(msg(s, "x", "idle"));
766
- refused(s.beginChannelSuspend("nope"), "not_found");
767
- });
768
-
769
- test("interrupt competes with checkpoint, completion and late results by commit order", () => {
770
- const { s } = create();
771
- // Interrupt first: the channel suspends with no checkpoint, the backlog stays, late results are fenced.
772
- const t = atBoundary(s); call(s, t, "late"); ok(msg(s, "p", "c1", "p"));
773
- ok(s.beginChannelSuspend("c1"));
774
- const first = ok(s.interruptTurn("c1", t, "stop it"));
775
- expect(first).toMatchObject({ interrupted: true, turn: { turnId: t, state: { status: "interrupted", reason: "stop it", uncertainCallIds: ["late"] } } });
776
- expect(lifecycleOf(s, "c1")).toBe("suspended");
777
- unchanged(s, () => {
778
- refused(s.appendMessage(t, { role: "tool", callId: "late", content: "x" }), "invalid_state");
779
- refused(s.checkpointTurn(t), "invalid_state"); refused(s.confirmReceipts(t, "seen"), "invalid_state");
780
- expect(ok(s.interruptTurn("c1", t, "again"))).toMatchObject({ interrupted: false, turn: { state: { status: "interrupted" } } });
781
- });
782
- expect(snap(s).items.find(item => item.itemId === "p")!.milestone).toBe("received");
783
- expect(ok(s.resumeChannel("c1")).turn).toBeUndefined();
784
- // A stale interrupt never reaches the newer turn that took the backlog.
785
- const next = begin(s).turn.turnId;
786
- expect(next).toBe(t + 1);
787
- unchanged(s, () => expect(ok(s.interruptTurn("c1", t, "stale")).interrupted).toBe(false));
788
- expect(stateOf(s, next)).toBe("running");
789
- refused(s.interruptTurn("c2", next, "wrong channel"), "not_found");
790
- refused(s.interruptTurn("c1", 99, "unknown"), "not_found");
791
- refused(s.interruptTurn("c1", next, " "), "invalid_input");
792
- // Checkpoint first: the turn is no longer active and the checkpoint stays.
793
- ok(s.beginChannelSuspend("c1"));
794
- ok(s.checkpointTurn(next));
795
- unchanged(s, () => expect(ok(s.interruptTurn("c1", next, "late")).interrupted).toBe(false));
796
- expect(stateOf(s, next)).toBe("suspended");
797
- // A turn that can finish completes and the channel suspends without a checkpoint.
798
- ok(s.resumeChannel("c1"));
799
- say(s, next, "done");
800
- ok(s.beginChannelSuspend("c1"));
801
- expect(ok(s.finishTurn(next, { status: "completed" })).finished).toBe(true);
802
- expect(lifecycleOf(s, "c1")).toBe("suspended");
803
- expect(snap(s).turns.some(turn => turn.state.status === "suspended")).toBe(false);
804
- });
805
-
806
- test("withdraw competes with take; withdrawn items stay out of the timeline and cannot be revived", () => {
807
- const { adapter, s: first } = create();
808
- let s = first;
809
- ok(msg(s, "m", "c1", "m")); ok(msg(s, "kept", "c1", "k"));
810
- ok(s.createChannel({ channelId: "c2" }));
811
- ok(notice(s, "n", "c2"));
812
- const noticeId = snap(s).items.find(item => item.kind === "channel_notice")!.itemId;
813
- const w = ok(s.withdrawItem("c1", "m"));
814
- expect(w).toMatchObject({ outcome: "withdrawn", repeated: false, item: { itemId: "m", milestone: "withdrawn" } });
815
- expect(w.outcome === "withdrawn" && w.item.withdrawnAt).toBeTruthy();
816
- expect(ok(s.withdrawItem("c1", "m"))).toMatchObject({ outcome: "withdrawn", repeated: true });
817
- expect(ok(s.withdrawItem("c2", noticeId))).toMatchObject({ outcome: "withdrawn", repeated: false });
818
- refused(s.withdrawItem("c2", "k"), "not_found"); refused(s.withdrawItem("c1", "none"), "not_found");
819
- // Retry cannot make it pending again, in any lifecycle and after reopen.
820
- s = reopen(adapter, s);
821
- expect(ok(msg(s, "m", "c1", "m"))).toMatchObject({ duplicate: true, item: { milestone: "withdrawn" } });
822
- refused(msg(s, "changed", "c1", "m"), "item_conflict");
823
- expect(ok(s.withdrawItem("c1", "m")).outcome).toBe("withdrawn");
824
- expect(ok(s.beginTurn("c2"))).toBeNull();
825
- const taken = begin(s);
826
- expect(taken.items.map(item => item.itemId)).toEqual(["k"]);
827
- expect(snap(s).timeline.some(entry => entry.itemId === "m")).toBe(false);
828
- expect(snap(s).items.map(item => item.itemId)).toContain("m");
829
- expect(snap(s).channels[0]!.participantIds).toEqual(["ana"]);
830
- // Take won: the owning turn is reported and nothing changes, also after the turn ended.
831
- unchanged(s, () => expect(ok(s.withdrawItem("c1", "k"))).toMatchObject({ outcome: "taken", turnId: taken.turn.turnId, item: { milestone: "taken" } }));
832
- say(s, taken.turn.turnId, "x"); ok(s.finishTurn(taken.turn.turnId, { status: "completed" }));
833
- expect(ok(s.withdrawItem("c1", "k")).outcome).toBe("taken");
834
- // Withdrawal works while suspended, so a backlog can be cleared.
835
- ok(msg(s, "later", "c1", "l")); ok(s.beginChannelSuspend("c1"));
836
- expect(ok(s.withdrawItem("c1", "l")).outcome).toBe("withdrawn");
837
- });
838
-
839
- test("create, edit, delete and retired IDs", () => {
840
- const { adapter, s: first } = create();
841
- let s = first;
842
- const made = ok(s.createChannel({ channelId: "c1", displayName: " Alice " }));
843
- expect(made).toMatchObject({ created: true, channel: { channelId: "c1", displayName: "Alice", lifecycle: "open" } });
844
- unchanged(s, () => {
845
- expect(ok(s.createChannel({ channelId: "c1", displayName: "Alice" })).created).toBe(false);
846
- refused(s.createChannel({ channelId: "c1", displayName: "Other" }), "already_exists");
847
- refused(s.createChannel({ channelId: "c1" }), "already_exists");
848
- refused(s.createChannel({ channelId: " " }), "invalid_input");
849
- refused(s.createChannel({ channelId: "x", displayName: "" }), "invalid_input");
850
- refused(s.createChannel({ channelId: "x", displayName: "n".repeat(201) }), "invalid_input");
851
- refused(s.editChannel("c1", " "), "invalid_input"); refused(s.editChannel("nope", "n"), "not_found");
852
- expect(ok(s.editChannel("c1", "Alice")).displayName).toBe("Alice");
853
- });
854
- expect(snap(s).turns).toEqual([]); // creating starts nothing
855
- expect(ok(notice(s, "hi", "c1")).duplicate).toBe(false); // an explicit create is a record
856
- expect(ok(s.editChannel("c1", "Alicia"))).toMatchObject({ displayName: "Alicia", lifecycle: "open" });
857
- expect(ok(s.editChannel("c1", null)).displayName).toBeUndefined();
858
- ok(s.editChannel("c1", "Named"));
859
- // First send still creates an unused channel.
860
- ok(msg(s, "first", "fresh", "f")); expect(lifecycleOf(s, "fresh")).toBe("open");
861
- // Delete: acceptance first blocks it; every unfinished state blocks it.
862
- refused(s.deleteChannel("fresh"), "channel_busy");
863
- const t = begin(s, "fresh").turn.turnId;
864
- refused(s.deleteChannel("fresh"), "channel_busy");
865
- ok(s.beginChannelSuspend("fresh")); ok(s.checkpointTurn(t));
866
- refused(s.deleteChannel("fresh"), "channel_busy"); // a checkpoint blocks, resolved or not
867
- ok(s.resumeChannel("fresh")); say(s, t, "x"); ok(s.finishTurn(t, { status: "completed" }));
868
- ok(s.beginChannelSuspend("fresh")); // deletion from suspended is allowed once nothing is unresolved
869
- const gone = ok(s.deleteChannel("fresh"));
870
- expect(gone).toMatchObject({ lifecycle: "retired", participantIds: ["ana"] });
871
- unchanged(s, () => {
872
- expect(ok(s.deleteChannel("fresh")).lifecycle).toBe("retired");
873
- refused(msg(s, "again", "fresh"), "channel_retired"); refused(notice(s, "again", "fresh"), "channel_retired");
874
- refused(s.createChannel({ channelId: "fresh" }), "channel_retired"); refused(s.editChannel("fresh", "n"), "channel_retired");
875
- refused(s.beginChannelSuspend("fresh"), "channel_retired"); refused(s.resumeChannel("fresh"), "channel_retired");
876
- refused(s.beginTurn("fresh"), "channel_retired");
877
- expect(ok(msg(s, "first", "fresh", "f")).duplicate).toBe(true); // a duplicate answers before the retirement check
878
- });
879
- s = reopen(adapter, s);
880
- expect(lifecycleOf(s, "fresh")).toBe("retired");
881
- refused(msg(s, "again", "fresh"), "channel_retired");
882
- expect(snap(s).timeline.filter(entry => entry.channelId === "fresh").length).toBeGreaterThan(0);
883
- // Delete wins over a later send; withdrawing the backlog first makes delete possible.
884
- ok(msg(s, "x", "c9", "x9")); refused(s.deleteChannel("c9"), "channel_busy");
885
- ok(s.withdrawItem("c9", "x9")); expect(ok(s.deleteChannel("c9")).lifecycle).toBe("retired");
886
- // Allowed while the session is suspended too, and retirement survives.
887
- ok(s.beginSuspend()); ok(s.completeSuspend());
888
- expect(ok(s.createChannel({ channelId: "late", displayName: "L" })).created).toBe(true);
889
- expect(ok(s.deleteChannel("late")).lifecycle).toBe("retired");
890
- refused(msg(s, "x", "late"), "channel_retired"); // retired is reported before the session check
891
- refused(msg(s, "x", "open-one"), "not_running");
892
- });
893
-
894
- test("session resume skips an individually suspended channel and never checks its key", () => {
895
- const { adapter, s: first } = create();
896
- let s = first;
897
- const a = atBoundary(s, "c1"); ok(msg(s, "p", "c1", "p")); ok(msg(s, "q", "c2", "q"));
898
- ok(s.beginChannelSuspend("c1")); ok(s.checkpointTurn(a));
899
- ok(s.beginSuspend());
900
- refused(msg(s, "x", "c1"), "not_running"); // both closed: the session answers first
901
- refused(s.takePending(a), "invalid_state");
902
- ok(s.completeSuspend());
903
- // Another configuration resumes the session; the old checkpoint is neither resumed nor blocking.
904
- s = reopen(adapter, s, "k2");
905
- expect(lifecycleOf(s, "c1")).toBe("suspended");
906
- expect(ok(s.resume()).turns).toEqual([]);
907
- expect(stateOf(s, a)).toBe("suspended");
908
- expect(snap(s).session.lifecycle).toBe("running");
909
- unchanged(s, () => refused(s.resumeChannel("c1"), "incompatible")); // checked only when it would continue the turn
910
- expect(begin(s, "c2").items.map(item => item.itemId)).toEqual(["q"]); // other work runs
911
- s = reopen(adapter, s, "k1");
912
- expect(ok(s.resumeChannel("c1")).turn).toMatchObject({ turnId: a, state: { status: "running" } });
913
- expect(ok(s.takePending(a)).items.map(item => item.itemId)).toEqual(["p"]);
914
- });
915
-
916
- test("resuming a channel during session suspension clears only the channel suspension", () => {
917
- const { adapter, s: first } = create();
918
- let s = first;
919
- const a = atBoundary(s); ok(msg(s, "p", "c1", "p"));
920
- ok(s.beginChannelSuspend("c1")); ok(s.checkpointTurn(a));
921
- ok(s.beginSuspend()); ok(s.completeSuspend());
922
- const resumed = ok(s.resumeChannel("c1"));
923
- expect(resumed.channel.lifecycle).toBe("open");
924
- expect(resumed.turn).toBeUndefined(); // starts no work
925
- expect(stateOf(s, a)).toBe("suspended"); // the checkpoint now sits under the session suspension
926
- refused(s.beginTurn("c1"), "not_running"); refused(msg(s, "x", "c1"), "not_running");
927
- refused(s.deleteChannel("c1"), "channel_busy");
928
- s = reopen(adapter, s); // a clean session suspension keeps it
929
- expect(stateOf(s, a)).toBe("suspended");
930
- const back = ok(s.resume());
931
- expect(back.turns.map(turn => turn.turnId)).toEqual([a]);
932
- expect(ok(s.takePending(a)).items.map(item => item.itemId)).toEqual(["p"]);
933
- // Suspending the channel again while the session is suspended keeps the checkpoint.
934
- ok(s.beginSuspend()); ok(s.checkpointTurn(a)); ok(s.completeSuspend());
935
- expect(lifecycleOf(s, "c1")).toBe("open");
936
- expect(ok(s.beginChannelSuspend("c1")).lifecycle).toBe("suspended");
937
- expect(ok(s.resume()).turns).toEqual([]);
938
- expect(stateOf(s, a)).toBe("suspended");
939
- });
940
-
941
- test("stop and crash keep committed channel suspensions and interrupt everything else", () => {
942
- for (const crash of [false, true]) {
943
- const { adapter, s: first } = create();
944
- let s = first;
945
- const a = atBoundary(s, "c1"), b = atBoundary(s, "c2"), c = atBoundary(s, "c3"), d = atBoundary(s, "c4");
946
- ok(msg(s, "p", "c1", "p")); ok(msg(s, "r", "c3", "r"));
947
- ok(s.beginChannelSuspend("c1")); ok(s.checkpointTurn(a)); // committed individually
948
- ok(s.beginChannelSuspend("c3")); // still suspending: its suspension never commits
949
- ok(s.beginSuspend()); ok(s.checkpointTurn(b)); // c2's checkpoint belongs to the unfinished session suspension
950
- call(s, d, "open-call"); // c4 is mid-iteration
951
- let ended: number[];
952
- if (crash) { s = reopen(adapter, s); ended = snap(s).turns.filter(t => t.state.status === "interrupted").map(t => t.turnId); }
953
- else ended = ok(s.interruptActive("stop")).map(t => t.turnId);
954
- expect(ended.sort()).toEqual([b, c, d]);
955
- const view = snap(s);
956
- expect(view.session.lifecycle).toBe("running");
957
- expect(stateOf(s, a)).toBe("suspended");
958
- expect(lifecycleOf(s, "c1")).toBe("suspended");
959
- expect(lifecycleOf(s, "c3")).toBe("open"); // back to open, its turn interrupted
960
- expect(view.turns.find(t => t.turnId === d)!.state).toMatchObject({ status: "interrupted", uncertainCallIds: ["open-call"] });
961
- expect(view.items.find(item => item.itemId === "r")!.milestone).toBe("received"); // backlog preserved
962
- // The interrupted channel accepts new work; the suspended one still waits for its resume.
963
- ok(msg(s, "again", "c3", "again")); expect(begin(s, "c3").items.map(item => item.itemId)).toEqual(["r", "again"]);
964
- refused(msg(s, "x", "c1"), "channel_suspended");
965
- expect(ok(s.resumeChannel("c1")).turn).toMatchObject({ turnId: a });
966
- }
967
- });
968
-
969
- test("a crash during a channel suspension, before it commits, interrupts the turn and keeps the backlog", () => {
970
- const { adapter, s: first } = create();
971
- const t = atBoundary(first); call(first, t, "inflight"); ok(msg(first, "p", "c1", "p"));
972
- ok(first.beginChannelSuspend("c1"));
973
- const s = reopen(adapter, first);
974
- expect(lifecycleOf(s, "c1")).toBe("open");
975
- expect(snap(s).turns[0]!.state).toMatchObject({ status: "interrupted", uncertainCallIds: ["inflight"] });
976
- expect(snap(s).items.find(item => item.itemId === "p")!.milestone).toBe("received");
977
- ok(msg(s, "new", "c1", "n"));
978
- expect(begin(s).items.map(item => item.itemId)).toEqual(["p", "n"]);
979
- });
980
-
981
- test("export of a running session needs no checkpoint and no suspending channel", () => {
982
- const { s } = create();
983
- const t = atBoundary(s); say(s, t, "done");
984
- ok(s.beginChannelSuspend("c1"));
985
- refused(s.exportArchive(), "busy"); // suspending
986
- ok(s.finishTurn(t, { status: "completed" }));
987
- expect(ok(s.exportArchive()).snapshot.channels[0]!.lifecycle).toBe("suspended"); // no checkpoint, no backlog
988
- ok(s.resumeChannel("c1"));
989
- const u = atBoundary(s, "c2"); ok(s.beginChannelSuspend("c2")); ok(s.checkpointTurn(u));
990
- refused(s.exportArchive(), "busy"); // a checkpoint on a suspended channel
991
- ok(s.beginSuspend()); ok(s.completeSuspend());
992
- expect(ok(s.exportArchive()).snapshot.turns.some(turn => turn.state.status === "suspended")).toBe(true);
993
- });
994
-
995
- /** A suspended-session archive carrying every new record kind. */
996
- function richArchive() {
997
- const { s } = create();
998
- ok(s.createChannel({ channelId: "named", displayName: "Named" }));
999
- const a = atBoundary(s, "c1"); ok(msg(s, "p", "c1", "p"));
1000
- ok(msg(s, "w", "c2", "w")); ok(s.withdrawItem("c2", "w"));
1001
- ok(s.beginChannelSuspend("c1")); ok(s.checkpointTurn(a));
1002
- ok(msg(s, "gone", "c3", "g")); ok(s.withdrawItem("c3", "g")); ok(s.deleteChannel("c3"));
1003
- ok(s.beginSuspend()); ok(s.completeSuspend());
1004
- return { s, a, archive: JSON.parse(JSON.stringify(ok(s.exportArchive()))) };
1005
- }
1006
-
1007
- test("an archive round-trips channel state, names, withdrawn items, retired IDs and checkpoints", () => {
1008
- const { s, a, archive } = richArchive();
1009
- expect(archive.archiveVersion).toBe(5);
1010
- const home = location();
1011
- ok(home.importArchive(archive, { sessionId: "copy" }));
1012
- const copy = ok(home.open({ mode: "open", identity: { sessionId: "copy", compatibilityKey: "k1" } }));
1013
- expect(snap(copy)).toEqual({ ...snap(s), session: { ...snap(s).session, sessionId: "copy" } });
1014
- expect(snap(copy).channels.map(c => [c.channelId, c.lifecycle, c.displayName])).toEqual(
1015
- [["named", "open", "Named"], ["c1", "suspended", undefined], ["c2", "open", undefined], ["c3", "retired", undefined]]);
1016
- expect(ok(msg(copy, "w", "c2", "w"))).toMatchObject({ duplicate: true, item: { milestone: "withdrawn" } });
1017
- refused(msg(copy, "x", "c3"), "channel_retired");
1018
- // The imported individual suspension survives a session resume and ends only by its own resume.
1019
- expect(ok(copy.resume()).turns).toEqual([]);
1020
- expect(ok(copy.resumeChannel("c1")).turn).toMatchObject({ turnId: a });
1021
- });
1022
-
1023
- test("import rejects archives that open would interrupt or that would run a retired channel", () => {
1024
- const { archive } = richArchive();
1025
- const broken: [string, (archive: any) => void][] = [
1026
- ["suspending channel", a => { a.snapshot.channels[1].lifecycle = "suspending"; }],
1027
- ["retired channel holds a checkpoint", a => { a.snapshot.channels[1].lifecycle = "retired"; }],
1028
- ["unknown channel state", a => { a.snapshot.channels[0].lifecycle = "paused"; }],
1029
- ["bad name", a => { a.snapshot.channels[0].displayName = ""; }],
1030
- ["withdrawn with a turn link", a => { const w = a.snapshot.items.find((i: any) => i.milestone === "withdrawn"); w.turnId = 1; w.entrySeq = 1; }],
1031
- ["withdrawn without a time", a => { delete a.snapshot.items.find((i: any) => i.milestone === "withdrawn").withdrawnAt; }],
1032
- ["withdrawal time on a pending item", a => { a.snapshot.items.find((i: any) => i.milestone === "received").withdrawnAt = "t"; }],
1033
- ["pending item on a retired channel", a => { const item = a.snapshot.items.find((i: any) => i.milestone === "received");
1034
- a.snapshot.channels.find((c: any) => c.channelId === item.channelId).lifecycle = "retired"; }],
1035
- ["checkpoint nothing holds", a => { a.snapshot.channels[1].lifecycle = "open"; a.snapshot.session.lifecycle = "running"; }],
1036
- ];
1037
- for (const [label, damage] of broken) {
1038
- const copy = JSON.parse(JSON.stringify(archive)); damage(copy);
1039
- const home = location();
1040
- expect([label, home.importArchive(copy).ok ? "ok" : "rejected"]).toEqual([label, "rejected"]);
1041
- refused(home.open({ mode: "open", identity: id() }), "not_found");
1042
- }
1043
- // A running turn on a retired channel is rejected in a running session as well.
1044
- const idle = JSON.parse(JSON.stringify(archive));
1045
- idle.snapshot.session.lifecycle = "running";
1046
- for (const channel of idle.snapshot.channels) channel.lifecycle = "open";
1047
- idle.snapshot.items = idle.snapshot.items.filter((i: any) => i.milestone !== "received");
1048
- idle.snapshot.turns[0].state = { status: "running" };
1049
- idle.snapshot.channels[1].lifecycle = "retired";
1050
- refused(location().importArchive(idle), "invalid_archive");
1051
- });
1052
-
1053
- test("archive version 1 from the persistence revision imports with every channel open", () => {
1054
- const { s } = create();
1055
- const t = atBoundary(s); ok(msg(s, "p", "c1", "p"));
1056
- ok(s.beginSuspend()); ok(s.checkpointTurn(t)); ok(s.completeSuspend());
1057
- const v1 = JSON.parse(JSON.stringify(ok(s.exportArchive())));
1058
- v1.archiveVersion = 1; v1.snapshot.session.formatVersion = 2;
1059
- for (const item of v1.snapshot.items) { item.signature = legacyItemSignature(item); delete item.policy; delete item.explicitPolicy; }
1060
- for (const channel of v1.snapshot.channels) { delete channel.lifecycle; delete channel.displayName; }
1061
- const home = location();
1062
- ok(home.importArchive(JSON.parse(JSON.stringify(v1))));
1063
- const copy = ok(home.open({ mode: "open", identity: id() }));
1064
- expect(snap(copy).session.formatVersion).toBe(6);
1065
- expect(snap(copy).channels).toEqual([{ channelId: "c1", lifecycle: "open", participantIds: ["ana"] }]);
1066
- expect(ok(copy.resume()).turns.map(turn => turn.turnId)).toEqual([t]); // session-wide resume, as before
1067
- expect(ok(copy.takePending(t)).items.map(item => item.itemId)).toEqual(["p"]);
1068
- // Version 1 cannot carry withdrawn items or newer channel fields it never had.
1069
- const bad = JSON.parse(JSON.stringify(v1)); bad.snapshot.items[0].milestone = "withdrawn"; bad.snapshot.items[0].withdrawnAt = "t";
1070
- refused(location().importArchive(bad), "invalid_archive");
1071
- });
1072
-
1073
- test("an archive round-trips a suspended session with IDs, deduplication and counters", () => {
1074
- const { s } = create();
1075
- ok(msg(s, "a", "c1", "a")); ok(msg(s, "b", "c2", "auto:5"));
1076
- const one = begin(s, "c1").turn.turnId, two = begin(s, "c2").turn.turnId;
1077
- call(s, one, "k1"); ok(s.appendMessage(one, { role: "tool", callId: "k1", content: "once" }));
1078
- ok(s.confirmReceipts(one, "seen"));
1079
- say(s, two, "bye"); ok(s.finishTurn(two, { status: "completed" }));
1080
- ok(msg(s, "pending", "c2", "p"));
1081
- ok(s.beginSuspend()); ok(s.checkpointTurn(one)); ok(s.completeSuspend());
1082
- const archive = JSON.parse(JSON.stringify(ok(s.exportArchive())));
1083
- const source = snap(s);
1084
-
1085
- const home = location();
1086
- const imported = home.importArchive(archive, { sessionId: "copy" });
1087
- expect(ok(imported)).toEqual({ ...source.session, sessionId: "copy" });
1088
- refused(home.importArchive(archive), "already_exists");
1089
- refused(home.open({ mode: "open", identity: id() }), "incompatible");
1090
- const copy = ok(home.open({ mode: "open", identity: { sessionId: "copy", compatibilityKey: "k1" } }));
1091
- // Import does not open, start or resume; the copy is the same session state.
1092
- expect(snap(copy)).toEqual({ ...source, session: { ...source.session, sessionId: "copy" } });
1093
- expect(ok(msg(copy, "a", "c1", "a"))).toMatchObject({ duplicate: true, item: { milestone: "seen", turnId: one } });
1094
- refused(msg(copy, "changed", "c2", "p"), "item_conflict");
1095
- expect(ok(copy.resume()).turns.map(turn => turn.turnId)).toEqual([one]);
1096
- expect(ok(msg(copy, "new")).item.itemId).toBe("auto:6");
1097
- expect(begin(copy, "c2").turn).toMatchObject({ turnId: two + 1, itemIds: ["p"] });
1098
- expect(ok(copy.appendMessage(one, { role: "assistant", content: "resumed", calls: [] })).seq).toBeGreaterThan(source.revision);
1099
- });
1100
-
1101
- test("invalid archives and occupied destinations leave nothing partial", () => {
1102
- const { s } = create();
1103
- ok(msg(s, "a", "c1", "a"));
1104
- const t = begin(s).turn.turnId;
1105
- say(s, t, "x"); ok(s.finishTurn(t, { status: "completed" }));
1106
- const good = JSON.stringify(ok(s.exportArchive()));
1107
- const broken: ((archive: any) => void)[] = [
1108
- a => { a.format = "something-else"; },
1109
- a => { a.archiveVersion = 6; },
1110
- a => { a.snapshot.session.formatVersion = 7; },
1111
- a => { a.snapshot.session.lifecycle = "suspending"; },
1112
- a => { a.snapshot.turns[0].state = { status: "running" }; },
1113
- a => { a.snapshot.turns[0].state = { status: "suspended", checkpoint: { nextStep: "inference", afterSeq: 1 } }; },
1114
- a => { a.snapshot.items[0].text = "edited"; },
1115
- a => { a.snapshot.items[0].turnId = 9; },
1116
- a => { a.snapshot.items.push({ ...a.snapshot.items[0] }); },
1117
- // A second item at an existing acceptance position, otherwise self-consistent.
1118
- a => { const copy = { ...a.snapshot.items[0], itemId: "twin" }; delete copy.turnId; delete copy.entrySeq; copy.milestone = "received";
1119
- a.snapshot.session.lifecycle = "suspended"; a.snapshot.items.push(copy); },
1120
- a => { a.snapshot.timeline.reverse(); },
1121
- a => { a.snapshot.timeline[0].turnId = 4; },
1122
- a => { a.snapshot.turns[0].itemIds = []; },
1123
- a => { a.allocation.nextSeq = 1; },
1124
- a => { a.allocation.nextTurnId = 1; },
1125
- a => { delete a.snapshot.timeline; },
1126
- ];
1127
- for (const damage of broken) {
1128
- const archive = JSON.parse(good); damage(archive);
1129
- const home = location();
1130
- refused(home.importArchive(archive), "invalid_archive");
1131
- refused(home.open({ mode: "open", identity: id() }), "not_found");
1132
- }
1133
- for (const junk of [null, "text", 5, [], {}]) refused(location().importArchive(junk as never), "invalid_archive");
1134
- refused(location().importArchive(JSON.parse(good), { sessionId: " " }), "invalid_input");
1135
- // An occupied destination keeps its own session.
1136
- const occupied = create();
1137
- ok(msg(occupied.s, "mine", "c1", "mine"));
1138
- unchanged(occupied.s, () => refused(occupied.adapter.importArchive(JSON.parse(good)), "already_exists"));
1139
- });
1140
- });
1141
- }