@team-agent/installer 0.5.127 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (421) hide show
  1. package/README.md +15 -4
  2. package/README.zh.md +1 -1
  3. package/package.json +4 -8
  4. package/skills/team-agent/SKILL.md +41 -26
  5. package/skills/team-agent/command-coverage.json +170 -184
  6. package/skills/team-agent/docs/reference/team-agent-operator.md +66 -32
  7. package/skills/team-agent/references/recovery-runbook.md +1 -1
  8. package/skills/team-agent/references/team-agent-operator.md +66 -32
  9. package/templates/team_state.md +1 -1
  10. package/Cargo.lock +0 -1063
  11. package/Cargo.toml +0 -36
  12. package/crates/team-agent/Cargo.toml +0 -69
  13. package/crates/team-agent/src/app_server_test_support.rs +0 -258
  14. package/crates/team-agent/src/cli/adapters.rs +0 -1298
  15. package/crates/team-agent/src/cli/arguments.rs +0 -401
  16. package/crates/team-agent/src/cli/attach_app_server_leader.rs +0 -98
  17. package/crates/team-agent/src/cli/diagnose.rs +0 -1675
  18. package/crates/team-agent/src/cli/emit.rs +0 -2898
  19. package/crates/team-agent/src/cli/grok_slot.rs +0 -384
  20. package/crates/team-agent/src/cli/helpers.rs +0 -91
  21. package/crates/team-agent/src/cli/intent/runtime.rs +0 -1189
  22. package/crates/team-agent/src/cli/intent/runtime_tests.rs +0 -821
  23. package/crates/team-agent/src/cli/intent/tests.rs +0 -691
  24. package/crates/team-agent/src/cli/intent.rs +0 -664
  25. package/crates/team-agent/src/cli/leader.rs +0 -300
  26. package/crates/team-agent/src/cli/leader_prompt.rs +0 -261
  27. package/crates/team-agent/src/cli/leaders.rs +0 -418
  28. package/crates/team-agent/src/cli/mod.rs +0 -6528
  29. package/crates/team-agent/src/cli/models.rs +0 -449
  30. package/crates/team-agent/src/cli/named_address.rs +0 -1651
  31. package/crates/team-agent/src/cli/profile.rs +0 -342
  32. package/crates/team-agent/src/cli/route.rs +0 -212
  33. package/crates/team-agent/src/cli/send/coordinator.rs +0 -164
  34. package/crates/team-agent/src/cli/send/mailbox.rs +0 -145
  35. package/crates/team-agent/src/cli/send/persist.rs +0 -192
  36. package/crates/team-agent/src/cli/send/presentation.rs +0 -370
  37. package/crates/team-agent/src/cli/send/resolve.rs +0 -573
  38. package/crates/team-agent/src/cli/send.rs +0 -201
  39. package/crates/team-agent/src/cli/shutdown_socket.rs +0 -288
  40. package/crates/team-agent/src/cli/spec.rs +0 -159
  41. package/crates/team-agent/src/cli/status.rs +0 -280
  42. package/crates/team-agent/src/cli/status_port/agents.rs +0 -358
  43. package/crates/team-agent/src/cli/status_port/approvals.rs +0 -79
  44. package/crates/team-agent/src/cli/status_port/brief.rs +0 -2043
  45. package/crates/team-agent/src/cli/status_port/compact.rs +0 -240
  46. package/crates/team-agent/src/cli/status_port/format.rs +0 -146
  47. package/crates/team-agent/src/cli/status_port/inbox.rs +0 -62
  48. package/crates/team-agent/src/cli/status_port/runtime.rs +0 -197
  49. package/crates/team-agent/src/cli/status_port/snapshot.rs +0 -208
  50. package/crates/team-agent/src/cli/status_port/store.rs +0 -416
  51. package/crates/team-agent/src/cli/status_port/tests.rs +0 -90
  52. package/crates/team-agent/src/cli/status_port.rs +0 -92
  53. package/crates/team-agent/src/cli/tests/base.rs +0 -885
  54. package/crates/team-agent/src/cli/tests/divergence.rs +0 -518
  55. package/crates/team-agent/src/cli/tests/lane_c.rs +0 -453
  56. package/crates/team-agent/src/cli/tests/leader_watch.rs +0 -372
  57. package/crates/team-agent/src/cli/tests/main_preserved.rs +0 -430
  58. package/crates/team-agent/src/cli/tests/missing_subcommands.rs +0 -336
  59. package/crates/team-agent/src/cli/tests/mod.rs +0 -137
  60. package/crates/team-agent/src/cli/tests/named_address.rs +0 -760
  61. package/crates/team-agent/src/cli/tests/parser_safety.rs +0 -383
  62. package/crates/team-agent/src/cli/tests/run_delegation.rs +0 -481
  63. package/crates/team-agent/src/cli/tests/shutdown_kill_plan.rs +0 -2179
  64. package/crates/team-agent/src/cli/tests/status_brief.rs +0 -1514
  65. package/crates/team-agent/src/cli/tests/status_send.rs +0 -1091
  66. package/crates/team-agent/src/cli/tests/verb_install_skill.rs +0 -93
  67. package/crates/team-agent/src/cli/tests/verb_profile.rs +0 -392
  68. package/crates/team-agent/src/cli/triage.rs +0 -234
  69. package/crates/team-agent/src/cli/types.rs +0 -591
  70. package/crates/team-agent/src/codex_app_server.rs +0 -546
  71. package/crates/team-agent/src/communication_mode/mod.rs +0 -56
  72. package/crates/team-agent/src/compiler/tests.rs +0 -842
  73. package/crates/team-agent/src/compiler.rs +0 -691
  74. package/crates/team-agent/src/conpty/backend.rs +0 -829
  75. package/crates/team-agent/src/conpty/mod.rs +0 -33
  76. package/crates/team-agent/src/contract_runtime/backend.rs +0 -1610
  77. package/crates/team-agent/src/contract_runtime/commands.rs +0 -671
  78. package/crates/team-agent/src/contract_runtime/config.rs +0 -354
  79. package/crates/team-agent/src/contract_runtime/config_tests.rs +0 -56
  80. package/crates/team-agent/src/contract_runtime/discovery.rs +0 -438
  81. package/crates/team-agent/src/contract_runtime/fork.rs +0 -368
  82. package/crates/team-agent/src/contract_runtime/forward.rs +0 -288
  83. package/crates/team-agent/src/contract_runtime/framework.rs +0 -350
  84. package/crates/team-agent/src/contract_runtime/mcp.rs +0 -399
  85. package/crates/team-agent/src/contract_runtime/mod.rs +0 -17
  86. package/crates/team-agent/src/contract_runtime/prompt.rs +0 -216
  87. package/crates/team-agent/src/contract_runtime/pump.rs +0 -271
  88. package/crates/team-agent/src/contract_runtime/registry.rs +0 -589
  89. package/crates/team-agent/src/contract_runtime/workspace.rs +0 -228
  90. package/crates/team-agent/src/coordinator/backoff.rs +0 -741
  91. package/crates/team-agent/src/coordinator/conpty_shim.rs +0 -805
  92. package/crates/team-agent/src/coordinator/health.rs +0 -1185
  93. package/crates/team-agent/src/coordinator/mod.rs +0 -119
  94. package/crates/team-agent/src/coordinator/orphan.rs +0 -110
  95. package/crates/team-agent/src/coordinator/runtime_detectors.rs +0 -798
  96. package/crates/team-agent/src/coordinator/runtime_observation.rs +0 -84
  97. package/crates/team-agent/src/coordinator/steps/abnormal.rs +0 -2309
  98. package/crates/team-agent/src/coordinator/steps/delivery.rs +0 -15
  99. package/crates/team-agent/src/coordinator/steps/health_sync.rs +0 -15
  100. package/crates/team-agent/src/coordinator/steps/mod.rs +0 -126
  101. package/crates/team-agent/src/coordinator/steps/persist.rs +0 -15
  102. package/crates/team-agent/src/coordinator/steps/runtime_prompts.rs +0 -15
  103. package/crates/team-agent/src/coordinator/steps/session_gate.rs +0 -16
  104. package/crates/team-agent/src/coordinator/tests/a0_lostupdate.rs +0 -158
  105. package/crates/team-agent/src/coordinator/tests/abnormal.rs +0 -312
  106. package/crates/team-agent/src/coordinator/tests/api_error_recovery.rs +0 -338
  107. package/crates/team-agent/src/coordinator/tests/basics.rs +0 -211
  108. package/crates/team-agent/src/coordinator/tests/daemon.rs +0 -514
  109. package/crates/team-agent/src/coordinator/tests/energy.rs +0 -549
  110. package/crates/team-agent/src/coordinator/tests/health_sync.rs +0 -461
  111. package/crates/team-agent/src/coordinator/tests/main_preserved.rs +0 -186
  112. package/crates/team-agent/src/coordinator/tests/mod.rs +0 -295
  113. package/crates/team-agent/src/coordinator/tests/s3_bounded.rs +0 -207
  114. package/crates/team-agent/src/coordinator/tests/spine.rs +0 -308
  115. package/crates/team-agent/src/coordinator/tests/takeover.rs +0 -286
  116. package/crates/team-agent/src/coordinator/tests/tick_core.rs +0 -237
  117. package/crates/team-agent/src/coordinator/tick.rs +0 -3112
  118. package/crates/team-agent/src/coordinator/types.rs +0 -540
  119. package/crates/team-agent/src/db/agent_health_capture.rs +0 -126
  120. package/crates/team-agent/src/db/message_store.rs +0 -1585
  121. package/crates/team-agent/src/db/migration.rs +0 -984
  122. package/crates/team-agent/src/db/mod.rs +0 -26
  123. package/crates/team-agent/src/db/schema.rs +0 -663
  124. package/crates/team-agent/src/diagnose/comms.rs +0 -242
  125. package/crates/team-agent/src/diagnose/mod.rs +0 -44
  126. package/crates/team-agent/src/diagnose/orphans.rs +0 -889
  127. package/crates/team-agent/src/event_log.rs +0 -502
  128. package/crates/team-agent/src/fake_worker.rs +0 -303
  129. package/crates/team-agent/src/kill_audit.rs +0 -106
  130. package/crates/team-agent/src/layout/manager.rs +0 -248
  131. package/crates/team-agent/src/layout/mod.rs +0 -36
  132. package/crates/team-agent/src/layout/overlay.rs +0 -134
  133. package/crates/team-agent/src/layout/placement.rs +0 -52
  134. package/crates/team-agent/src/layout/recovery.rs +0 -106
  135. package/crates/team-agent/src/layout/runtime_sessions.rs +0 -317
  136. package/crates/team-agent/src/layout/sessions.rs +0 -294
  137. package/crates/team-agent/src/layout/tmux_endpoint.rs +0 -165
  138. package/crates/team-agent/src/layout/worker_env.rs +0 -721
  139. package/crates/team-agent/src/layout/worker_window_helpers.rs +0 -37
  140. package/crates/team-agent/src/leader/helpers.rs +0 -178
  141. package/crates/team-agent/src/leader/incident.rs +0 -6
  142. package/crates/team-agent/src/leader/lease.rs +0 -3356
  143. package/crates/team-agent/src/leader/mod.rs +0 -104
  144. package/crates/team-agent/src/leader/owner_bind.rs +0 -400
  145. package/crates/team-agent/src/leader/prompt.rs +0 -905
  146. package/crates/team-agent/src/leader/provider_attribution.rs +0 -247
  147. package/crates/team-agent/src/leader/rediscover/tests.rs +0 -689
  148. package/crates/team-agent/src/leader/rediscover.rs +0 -1192
  149. package/crates/team-agent/src/leader/registry.rs +0 -883
  150. package/crates/team-agent/src/leader/start.rs +0 -4500
  151. package/crates/team-agent/src/leader/takeover.rs +0 -65
  152. package/crates/team-agent/src/leader/tests/basics.rs +0 -337
  153. package/crates/team-agent/src/leader/tests/byte_findings.rs +0 -355
  154. package/crates/team-agent/src/leader/tests/claim_leader_mailbox_flush_contract.rs +0 -544
  155. package/crates/team-agent/src/leader/tests/historical_inventory_upgrade_gate_red.rs +0 -624
  156. package/crates/team-agent/src/leader/tests/identity.rs +0 -465
  157. package/crates/team-agent/src/leader/tests/identity_session_names.rs +0 -42
  158. package/crates/team-agent/src/leader/tests/idle.rs +0 -113
  159. package/crates/team-agent/src/leader/tests/lease_api.rs +0 -520
  160. package/crates/team-agent/src/leader/tests/lease_claim.rs +0 -629
  161. package/crates/team-agent/src/leader/tests/mod.rs +0 -106
  162. package/crates/team-agent/src/leader/tests/prompt_contract.rs +0 -267
  163. package/crates/team-agent/src/leader/tests/rediscover.rs +0 -403
  164. package/crates/team-agent/src/leader/tests/rehomed_env.rs +0 -83
  165. package/crates/team-agent/src/leader/tests/team_in_team_state_scope_red.rs +0 -1273
  166. package/crates/team-agent/src/leader/tests/terminal_and_replay_vs_rerender_invariants_red.rs +0 -417
  167. package/crates/team-agent/src/leader/tests/wake_start_owner.rs +0 -168
  168. package/crates/team-agent/src/leader/types.rs +0 -534
  169. package/crates/team-agent/src/lib.rs +0 -145
  170. package/crates/team-agent/src/lifecycle/helpers.rs +0 -212
  171. package/crates/team-agent/src/lifecycle/launch/add_agent.rs +0 -848
  172. package/crates/team-agent/src/lifecycle/launch/add_agent_state.rs +0 -393
  173. package/crates/team-agent/src/lifecycle/launch/agent_state.rs +0 -332
  174. package/crates/team-agent/src/lifecycle/launch/clone_agent.rs +0 -178
  175. package/crates/team-agent/src/lifecycle/launch/fork_agent.rs +0 -82
  176. package/crates/team-agent/src/lifecycle/launch/fork_entry.rs +0 -63
  177. package/crates/team-agent/src/lifecycle/launch/identity.rs +0 -674
  178. package/crates/team-agent/src/lifecycle/launch/layout.rs +0 -350
  179. package/crates/team-agent/src/lifecycle/launch/leader_context.rs +0 -589
  180. package/crates/team-agent/src/lifecycle/launch/mcp_config.rs +0 -152
  181. package/crates/team-agent/src/lifecycle/launch/ownership.rs +0 -105
  182. package/crates/team-agent/src/lifecycle/launch/pi_mcp.rs +0 -629
  183. package/crates/team-agent/src/lifecycle/launch/pi_mcp_extension.js +0 -226
  184. package/crates/team-agent/src/lifecycle/launch/plan.rs +0 -269
  185. package/crates/team-agent/src/lifecycle/launch/quick_start.rs +0 -5176
  186. package/crates/team-agent/src/lifecycle/launch/quick_start_transport.rs +0 -368
  187. package/crates/team-agent/src/lifecycle/launch/readiness.rs +0 -519
  188. package/crates/team-agent/src/lifecycle/launch/role_source.rs +0 -287
  189. package/crates/team-agent/src/lifecycle/launch/spawn.rs +0 -450
  190. package/crates/team-agent/src/lifecycle/launch/spec_state.rs +0 -801
  191. package/crates/team-agent/src/lifecycle/launch/state_projection.rs +0 -624
  192. package/crates/team-agent/src/lifecycle/launch/worker_env.rs +0 -558
  193. package/crates/team-agent/src/lifecycle/launch.rs +0 -534
  194. package/crates/team-agent/src/lifecycle/lock.rs +0 -350
  195. package/crates/team-agent/src/lifecycle/mod.rs +0 -79
  196. package/crates/team-agent/src/lifecycle/pane_input_lock.rs +0 -239
  197. package/crates/team-agent/src/lifecycle/profile_launch.rs +0 -757
  198. package/crates/team-agent/src/lifecycle/profile_smoke.rs +0 -557
  199. package/crates/team-agent/src/lifecycle/restart/agent.rs +0 -2198
  200. package/crates/team-agent/src/lifecycle/restart/common.rs +0 -2052
  201. package/crates/team-agent/src/lifecycle/restart/orchestrator.rs +0 -65
  202. package/crates/team-agent/src/lifecycle/restart/preflight.rs +0 -113
  203. package/crates/team-agent/src/lifecycle/restart/rebuild.rs +0 -5135
  204. package/crates/team-agent/src/lifecycle/restart/remove.rs +0 -1504
  205. package/crates/team-agent/src/lifecycle/restart/selection.rs +0 -559
  206. package/crates/team-agent/src/lifecycle/restart/team_state.rs +0 -329
  207. package/crates/team-agent/src/lifecycle/restart.rs +0 -223
  208. package/crates/team-agent/src/lifecycle/role_config.rs +0 -1205
  209. package/crates/team-agent/src/lifecycle/tests/acceptance_b_batch_red.rs +0 -1021
  210. package/crates/team-agent/src/lifecycle/tests/agent_ops.rs +0 -1205
  211. package/crates/team-agent/src/lifecycle/tests/b0_legacy_snapshot_nonauthority_contract.rs +0 -265
  212. package/crates/team-agent/src/lifecycle/tests/b0_reader_hideone_audit_contract.rs +0 -490
  213. package/crates/team-agent/src/lifecycle/tests/behavioral_diff_264_red.rs +0 -656
  214. package/crates/team-agent/src/lifecycle/tests/claude_profile_launch_red.rs +0 -135
  215. package/crates/team-agent/src/lifecycle/tests/cli_argv_routing_red.rs +0 -1415
  216. package/crates/team-agent/src/lifecycle/tests/clone_agent_preserves_source_tools.rs +0 -427
  217. package/crates/team-agent/src/lifecycle/tests/clone_fork_copilot_perms_red.rs +0 -396
  218. package/crates/team-agent/src/lifecycle/tests/communication_mode_runtime_contract_red.rs +0 -418
  219. package/crates/team-agent/src/lifecycle/tests/copilot_provider_red.rs +0 -2039
  220. package/crates/team-agent/src/lifecycle/tests/core.rs +0 -1298
  221. package/crates/team-agent/src/lifecycle/tests/f032_startup_prompt_best_effort_red.rs +0 -315
  222. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_g0.stdout.txt +0 -222
  223. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_spaced_ids.stdout.txt +0 -9
  224. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_native_mcp_host.mjs +0 -71
  225. package/crates/team-agent/src/lifecycle/tests/gate_fixtures.rs +0 -562
  226. package/crates/team-agent/src/lifecycle/tests/grok_require_explicit_model_red.rs +0 -110
  227. package/crates/team-agent/src/lifecycle/tests/harvest2_a_batch_red.rs +0 -472
  228. package/crates/team-agent/src/lifecycle/tests/host_cotenant_death_p0_contract.rs +0 -921
  229. package/crates/team-agent/src/lifecycle/tests/issue238_codex_effort_contract.rs +0 -68
  230. package/crates/team-agent/src/lifecycle/tests/lane_ops.rs +0 -1851
  231. package/crates/team-agent/src/lifecycle/tests/launch_spawn.rs +0 -3981
  232. package/crates/team-agent/src/lifecycle/tests/lifecycle_lock.rs +0 -339
  233. package/crates/team-agent/src/lifecycle/tests/lifecycle_rollback_red.rs +0 -596
  234. package/crates/team-agent/src/lifecycle/tests/main_preserved.rs +0 -513
  235. package/crates/team-agent/src/lifecycle/tests/mcp_tool_name_format_red.rs +0 -69
  236. package/crates/team-agent/src/lifecycle/tests/phase_b_contracts.rs +0 -824
  237. package/crates/team-agent/src/lifecycle/tests/phase_golden.rs +0 -723
  238. package/crates/team-agent/src/lifecycle/tests/pi_catalog_red.rs +0 -152
  239. package/crates/team-agent/src/lifecycle/tests/pi_command_red.rs +0 -182
  240. package/crates/team-agent/src/lifecycle/tests/pi_dual_entry_red.rs +0 -374
  241. package/crates/team-agent/src/lifecycle/tests/pi_executable_mcp_red.rs +0 -546
  242. package/crates/team-agent/src/lifecycle/tests/pi_lifecycle_doctor_red.rs +0 -31
  243. package/crates/team-agent/src/lifecycle/tests/pi_native_mcp_capability_red.rs +0 -528
  244. package/crates/team-agent/src/lifecycle/tests/pi_session_delivery_red.rs +0 -134
  245. package/crates/team-agent/src/lifecycle/tests/quick_start_worker_readiness_red.rs +0 -333
  246. package/crates/team-agent/src/lifecycle/tests/realmachine_clusters_1_6_red.rs +0 -786
  247. package/crates/team-agent/src/lifecycle/tests/realmachine_residual_g1_g4_red.rs +0 -648
  248. package/crates/team-agent/src/lifecycle/tests/restart.rs +0 -185
  249. package/crates/team-agent/src/lifecycle/tests/restart_build_before_destroy_0540_contract.rs +0 -1053
  250. package/crates/team-agent/src/lifecycle/tests/restart_liveness_red.rs +0 -679
  251. package/crates/team-agent/src/lifecycle/tests/restart_rebind_hotfix_252_red.rs +0 -1126
  252. package/crates/team-agent/src/lifecycle/tests/restart_session_capture_red.rs +0 -153
  253. package/crates/team-agent/src/lifecycle/tests/resume_recover_red.rs +0 -427
  254. package/crates/team-agent/src/lifecycle/tests/stale_team_saveconflict_contract.rs +0 -431
  255. package/crates/team-agent/src/lifecycle/tests/startup_latency_contract.rs +0 -1066
  256. package/crates/team-agent/src/lifecycle/tests/status_credential_redaction_contract.rs +0 -876
  257. package/crates/team-agent/src/lifecycle/tests/subprep_codex_trust_roundtrip_red.rs +0 -1026
  258. package/crates/team-agent/src/lifecycle/tests/swallow_batch4_semantics_red.rs +0 -90
  259. package/crates/team-agent/src/lifecycle/tests/team_in_team_identity_scope_red.rs +0 -543
  260. package/crates/team-agent/src/lifecycle/tests/team_in_team_sibling_quick_start_red.rs +0 -1103
  261. package/crates/team-agent/src/lifecycle/tests/team_in_team_state_scope_red.rs +0 -1276
  262. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_roster_red.rs +0 -145
  263. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_txn_red.rs +0 -603
  264. package/crates/team-agent/src/lifecycle/tests/test_isolation_escape_contract.rs +0 -936
  265. package/crates/team-agent/src/lifecycle/tests/upgrade_compat_0211_red.rs +0 -970
  266. package/crates/team-agent/src/lifecycle/tests/verify_rs031_window_consistency_red.rs +0 -996
  267. package/crates/team-agent/src/lifecycle/tests/worker_spawn_env_red.rs +0 -827
  268. package/crates/team-agent/src/lifecycle/tests.rs +0 -102
  269. package/crates/team-agent/src/lifecycle/types.rs +0 -861
  270. package/crates/team-agent/src/lifecycle/worker_command_context.rs +0 -370
  271. package/crates/team-agent/src/main.rs +0 -52
  272. package/crates/team-agent/src/mcp_server/helpers.rs +0 -510
  273. package/crates/team-agent/src/mcp_server/lifecycle_tools/mod.rs +0 -6
  274. package/crates/team-agent/src/mcp_server/lifecycle_tools/state_status.rs +0 -43
  275. package/crates/team-agent/src/mcp_server/mod.rs +0 -119
  276. package/crates/team-agent/src/mcp_server/normalize.rs +0 -485
  277. package/crates/team-agent/src/mcp_server/readiness.rs +0 -546
  278. package/crates/team-agent/src/mcp_server/readiness_tests.rs +0 -369
  279. package/crates/team-agent/src/mcp_server/tests/golden.rs +0 -285
  280. package/crates/team-agent/src/mcp_server/tests/normalize.rs +0 -247
  281. package/crates/team-agent/src/mcp_server/tests/scoped.rs +0 -168
  282. package/crates/team-agent/src/mcp_server/tests/send.rs +0 -388
  283. package/crates/team-agent/src/mcp_server/tests/tools.rs +0 -343
  284. package/crates/team-agent/src/mcp_server/tests/wire.rs +0 -254
  285. package/crates/team-agent/src/mcp_server/tests.rs +0 -43
  286. package/crates/team-agent/src/mcp_server/tools.rs +0 -1015
  287. package/crates/team-agent/src/mcp_server/types.rs +0 -396
  288. package/crates/team-agent/src/mcp_server/wire.rs +0 -867
  289. package/crates/team-agent/src/messaging/activity.rs +0 -461
  290. package/crates/team-agent/src/messaging/address.rs +0 -87
  291. package/crates/team-agent/src/messaging/delivery.rs +0 -3785
  292. package/crates/team-agent/src/messaging/delivery_consumption_tests.rs +0 -234
  293. package/crates/team-agent/src/messaging/enter_rescue.rs +0 -362
  294. package/crates/team-agent/src/messaging/enter_rescue_tests.rs +0 -633
  295. package/crates/team-agent/src/messaging/helpers.rs +0 -354
  296. package/crates/team-agent/src/messaging/leader_channel.rs +0 -287
  297. package/crates/team-agent/src/messaging/leader_receiver.rs +0 -786
  298. package/crates/team-agent/src/messaging/mod.rs +0 -166
  299. package/crates/team-agent/src/messaging/persist.rs +0 -377
  300. package/crates/team-agent/src/messaging/presentation.rs +0 -417
  301. package/crates/team-agent/src/messaging/results/collection_tests.rs +0 -719
  302. package/crates/team-agent/src/messaging/results.rs +0 -1415
  303. package/crates/team-agent/src/messaging/scheduler.rs +0 -217
  304. package/crates/team-agent/src/messaging/selftest.rs +0 -315
  305. package/crates/team-agent/src/messaging/send.rs +0 -981
  306. package/crates/team-agent/src/messaging/tests/basic.rs +0 -346
  307. package/crates/team-agent/src/messaging/tests/dup_inject.rs +0 -551
  308. package/crates/team-agent/src/messaging/tests/e23.rs +0 -49
  309. package/crates/team-agent/src/messaging/tests/leader_channel.rs +0 -169
  310. package/crates/team-agent/src/messaging/tests/leader_inject_acceptance.rs +0 -817
  311. package/crates/team-agent/src/messaging/tests/main_preserved.rs +0 -85
  312. package/crates/team-agent/src/messaging/tests/mod.rs +0 -306
  313. package/crates/team-agent/src/messaging/tests/runtime.rs +0 -3655
  314. package/crates/team-agent/src/messaging/tests/spine.rs +0 -837
  315. package/crates/team-agent/src/messaging/tests/wave2.rs +0 -381
  316. package/crates/team-agent/src/messaging/trust.rs +0 -215
  317. package/crates/team-agent/src/messaging/types.rs +0 -471
  318. package/crates/team-agent/src/messaging/wait.rs +0 -366
  319. package/crates/team-agent/src/messaging/watchers.rs +0 -916
  320. package/crates/team-agent/src/model/enums.rs +0 -356
  321. package/crates/team-agent/src/model/errors.rs +0 -18
  322. package/crates/team-agent/src/model/ids.rs +0 -165
  323. package/crates/team-agent/src/model/mod.rs +0 -29
  324. package/crates/team-agent/src/model/name_similarity.rs +0 -252
  325. package/crates/team-agent/src/model/pane_authority_refusal.rs +0 -359
  326. package/crates/team-agent/src/model/paths.rs +0 -257
  327. package/crates/team-agent/src/model/routing.rs +0 -387
  328. package/crates/team-agent/src/model/spec.rs +0 -1184
  329. package/crates/team-agent/src/model/task_graph.rs +0 -321
  330. package/crates/team-agent/src/model/testdata/fuzz.golden.yaml +0 -43
  331. package/crates/team-agent/src/model/testdata/fuzz.yaml +0 -43
  332. package/crates/team-agent/src/model/testdata/spec_invalid_a.yaml +0 -209
  333. package/crates/team-agent/src/model/testdata/team.spec.golden.yaml +0 -208
  334. package/crates/team-agent/src/model/testdata/team.spec.yaml +0 -208
  335. package/crates/team-agent/src/model/yaml/tests.rs +0 -188
  336. package/crates/team-agent/src/model/yaml.rs +0 -802
  337. package/crates/team-agent/src/os_probe.rs +0 -280
  338. package/crates/team-agent/src/packaging/install.rs +0 -219
  339. package/crates/team-agent/src/packaging/migrate.rs +0 -38
  340. package/crates/team-agent/src/packaging/mod.rs +0 -91
  341. package/crates/team-agent/src/packaging/repair.rs +0 -33
  342. package/crates/team-agent/src/packaging/tests.rs +0 -822
  343. package/crates/team-agent/src/packaging/types.rs +0 -417
  344. package/crates/team-agent/src/platform/argv.rs +0 -331
  345. package/crates/team-agent/src/platform/errors.rs +0 -104
  346. package/crates/team-agent/src/platform/file_lock.rs +0 -279
  347. package/crates/team-agent/src/platform/mod.rs +0 -5
  348. package/crates/team-agent/src/platform/process.rs +0 -545
  349. package/crates/team-agent/src/provider/adapter.rs +0 -898
  350. package/crates/team-agent/src/provider/adapters/copilot.rs +0 -75
  351. package/crates/team-agent/src/provider/adapters/copilot_fork.rs +0 -307
  352. package/crates/team-agent/src/provider/adapters/fake.rs +0 -18
  353. package/crates/team-agent/src/provider/adapters/mod.rs +0 -28
  354. package/crates/team-agent/src/provider/approvals/mod.rs +0 -3
  355. package/crates/team-agent/src/provider/approvals/parsing.rs +0 -586
  356. package/crates/team-agent/src/provider/approvals/runtime_prompts.rs +0 -205
  357. package/crates/team-agent/src/provider/argv_route.rs +0 -405
  358. package/crates/team-agent/src/provider/bypass_flags.rs +0 -116
  359. package/crates/team-agent/src/provider/classify.rs +0 -773
  360. package/crates/team-agent/src/provider/command_helpers.rs +0 -45
  361. package/crates/team-agent/src/provider/faults.rs +0 -165
  362. package/crates/team-agent/src/provider/helpers.rs +0 -52
  363. package/crates/team-agent/src/provider/mod.rs +0 -78
  364. package/crates/team-agent/src/provider/model_catalog.rs +0 -722
  365. package/crates/team-agent/src/provider/session/capture.rs +0 -2631
  366. package/crates/team-agent/src/provider/session/context_fork/outcome.rs +0 -168
  367. package/crates/team-agent/src/provider/session/context_fork.rs +0 -264
  368. package/crates/team-agent/src/provider/session/mod.rs +0 -36
  369. package/crates/team-agent/src/provider/session/resume.rs +0 -269
  370. package/crates/team-agent/src/provider/session_scan/common/tests.rs +0 -316
  371. package/crates/team-agent/src/provider/session_scan/common.rs +0 -618
  372. package/crates/team-agent/src/provider/session_scan/copilot.rs +0 -280
  373. package/crates/team-agent/src/provider/session_scan/pi.rs +0 -152
  374. package/crates/team-agent/src/provider/session_scan.rs +0 -61
  375. package/crates/team-agent/src/provider/startup_prompt.rs +0 -757
  376. package/crates/team-agent/src/provider/submit_now.rs +0 -71
  377. package/crates/team-agent/src/provider/testdata/copilot-ready-marker.txt +0 -5
  378. package/crates/team-agent/src/provider/testdata/copilot-trust-prompt.txt +0 -19
  379. package/crates/team-agent/src/provider/testdata/grok-models-authenticated.stdout +0 -9
  380. package/crates/team-agent/src/provider/testdata/grok-models-unauthenticated.stdout +0 -7
  381. package/crates/team-agent/src/provider/tests/adapter.rs +0 -354
  382. package/crates/team-agent/src/provider/tests/classify.rs +0 -201
  383. package/crates/team-agent/src/provider/tests/command_helpers.rs +0 -26
  384. package/crates/team-agent/src/provider/tests/copilot_fork.rs +0 -191
  385. package/crates/team-agent/src/provider/tests/faults.rs +0 -200
  386. package/crates/team-agent/src/provider/tests/idle.rs +0 -140
  387. package/crates/team-agent/src/provider/tests/wire.rs +0 -213
  388. package/crates/team-agent/src/provider/tests.rs +0 -32
  389. package/crates/team-agent/src/provider/types.rs +0 -529
  390. package/crates/team-agent/src/provider/wire.rs +0 -406
  391. package/crates/team-agent/src/redaction.rs +0 -259
  392. package/crates/team-agent/src/state/abnormal_watch/tests/mod.rs +0 -248
  393. package/crates/team-agent/src/state/abnormal_watch.rs +0 -144
  394. package/crates/team-agent/src/state/identity.rs +0 -914
  395. package/crates/team-agent/src/state/identity_keys.rs +0 -132
  396. package/crates/team-agent/src/state/mod.rs +0 -74
  397. package/crates/team-agent/src/state/owner_gate.rs +0 -482
  398. package/crates/team-agent/src/state/ownership.rs +0 -563
  399. package/crates/team-agent/src/state/paths.rs +0 -395
  400. package/crates/team-agent/src/state/persist.rs +0 -3811
  401. package/crates/team-agent/src/state/projection.rs +0 -1508
  402. package/crates/team-agent/src/state/repository/intent.rs +0 -14
  403. package/crates/team-agent/src/state/repository/tests.rs +0 -184
  404. package/crates/team-agent/src/state/repository.rs +0 -866
  405. package/crates/team-agent/src/state/selector.rs +0 -160
  406. package/crates/team-agent/src/state/testdata/state-rich.canonical.json +0 -133
  407. package/crates/team-agent/src/tmux_backend/enter_rescue.rs +0 -325
  408. package/crates/team-agent/src/tmux_backend/enter_rescue_tests.rs +0 -432
  409. package/crates/team-agent/src/tmux_backend/native_input.rs +0 -513
  410. package/crates/team-agent/src/tmux_backend/native_input_tests.rs +0 -742
  411. package/crates/team-agent/src/tmux_backend/tests.rs +0 -4254
  412. package/crates/team-agent/src/tmux_backend.rs +0 -4527
  413. package/crates/team-agent/src/topology.rs +0 -537
  414. package/crates/team-agent/src/transport/enter_rescue.rs +0 -166
  415. package/crates/team-agent/src/transport/native_input.rs +0 -491
  416. package/crates/team-agent/src/transport/test_support.rs +0 -743
  417. package/crates/team-agent/src/transport/tests/behavior.rs +0 -326
  418. package/crates/team-agent/src/transport/tests/mod.rs +0 -194
  419. package/crates/team-agent/src/transport/tests/wire.rs +0 -574
  420. package/crates/team-agent/src/transport.rs +0 -1655
  421. package/crates/team-agent/src/transport_factory.rs +0 -819
@@ -1,1585 +0,0 @@
1
- // unit-10 (Stage 4): moved from crate::message_store to crate::db::message_store.
2
- // The historical body uses unwrap/expect/panic for SQL-row failures; the parent
3
- // db/ module denies these lints, so re-allow them here so the move is a pure
4
- // physical relocation (zero behavior change).
5
- #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6
-
7
- //!
8
- //! step 7 · message_store — core message lifecycle over `team.db`.
9
- //!
10
- //! Truth source (READ-ONLY): `team-agent-public` @ v0.2.11,
11
- //! `team_agent/message_store/core.py` + `leader_notification_log.py`.
12
- //! Builds on step 3 [`crate::db::schema`] (DDL/migration already create all 8
13
- //! tables incl. `messages` + `leader_notification_log`).
14
- //!
15
- //! SCOPE (this slice) = the semantic-tricky core lifecycle:
16
- //! 1. [`MessageStore::create_message`] — insert a fresh `msg_<hex12>` row,
17
- //! status `accepted` (`core.py:71-114`).
18
- //! 2. [`MessageStore::claim_for_delivery`] — atomic single-winner claim; flips
19
- //! an eligible row to `target_resolved`, bumps `delivery_attempts`, returns
20
- //! whether THIS caller won (`rowcount == 1`) (`core.py:190-205`).
21
- //! 3. [`MessageStore::mark`] — status state machine; the only guard is that
22
- //! `acknowledged` is STICKY against delivery statuses (injected/visible/
23
- //! submitted/submitted_unverified/delivered) but NOT against others
24
- //! (e.g. `failed` overwrites) (`core.py:116-138`, the SQL CASE).
25
- //! 4. [`MessageStore::claim_leader_notification_delivery`] — exactly-once dedup
26
- //! at the leader-injection boundary. Dedup key = `(result_id, owner_team_id,
27
- //! owner_epoch)` via the PK + `INSERT OR IGNORE`; **`leader_session_uuid` is
28
- //! NOT part of the key** (nullable audit metadata only). When `owner_epoch`
29
- //! is `None` it is derived from the uuid via [`legacy_epoch_from_uuid`]
30
- //! (`leader_notification_log.py:30-101,145-147`).
31
- //!
32
- //! DEFERRED (note, don't build) — follow-on RED slices: scheduled events, token
33
- //! accounting (incl. the `delivery_tokens` side-effect of `mark`), agent health,
34
- //! result watchers, results store, `artifact_refs` payloads, busy-retry timing.
35
- //!
36
- //! §10: pure-ish lib over SQLite — no panic on malformed input; every path
37
- //! returns `Result<_, MessageStoreError>`.
38
-
39
- use std::path::Path;
40
- use std::sync::atomic::{AtomicU64, Ordering};
41
- use std::time::{Duration, SystemTime, UNIX_EPOCH};
42
-
43
- use rusqlite::{params, OptionalExtension};
44
- use thiserror::Error;
45
-
46
- static MESSAGE_COUNTER: AtomicU64 = AtomicU64::new(0);
47
-
48
- #[derive(Debug, Error)]
49
- pub enum MessageStoreError {
50
- #[error("db: {0}")]
51
- Db(#[from] crate::db::DbError),
52
- #[error("sqlite: {0}")]
53
- Sqlite(#[from] rusqlite::Error),
54
- #[error("io: {0}")]
55
- Io(#[from] std::io::Error),
56
- #[error("event log: {0}")]
57
- EventLog(#[from] crate::event_log::EventLogError),
58
- #[error("delivery receipt missing for message: {0}")]
59
- DeliveryReceiptMissing(String),
60
- #[error("invalid message transition from {from} to {to}")]
61
- InvalidTransition { from: String, to: String },
62
- #[error("submitted recovery refused: {0}")]
63
- RecoveryRefused(&'static str),
64
- }
65
-
66
- /// Outcome of [`MessageStore::claim_leader_notification_delivery`]
67
- /// (`leader_notification_log.py:73-101`). `status` is `"claimed_by_you"` for the
68
- /// winner, `"already_notified_by"` for a deduped loser; `notified_message_id` is
69
- /// always the WINNER's proposed id (a loser sees the first winner's id).
70
- #[derive(Debug, Clone, PartialEq, Eq)]
71
- pub struct NotificationClaim {
72
- pub status: String,
73
- pub notified_message_id: String,
74
- }
75
-
76
- /// Args for [`MessageStore::claim_leader_notification_delivery`]
77
- /// (`leader_notification_log.py:30-40`).
78
- #[derive(Debug, Clone)]
79
- pub struct NotificationClaimParams<'a> {
80
- pub result_id: &'a str,
81
- pub owner_team_id: Option<&'a str>,
82
- /// `None` → derived from `leader_session_uuid` via [`legacy_epoch_from_uuid`].
83
- pub owner_epoch: Option<i64>,
84
- pub leader_session_uuid: Option<&'a str>,
85
- pub proposed_message_id: &'a str,
86
- pub envelope_hash: &'a str,
87
- pub pane_id: Option<&'a str>,
88
- }
89
-
90
- /// Error of a row parked by [`MessageStore::park_delivery_before_input`] (#372).
91
- pub(crate) const MCP_HANDSHAKE_TIMEOUT: &str = "mcp_handshake_timeout";
92
-
93
- /// Canonical initial message-row statuses shared by persistence, presentation,
94
- /// claiming and recovery. New durable dispositions must be added here first.
95
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
96
- pub enum MessageRowStatus {
97
- Accepted,
98
- StoredOnly,
99
- QueuedUntilLeaderAttach,
100
- QueuedCoordinatorUnavailable,
101
- QueuedPaneMissing,
102
- TargetResolved,
103
- SubmittedAwaitingReceipt,
104
- InjectedAwaitingReceipt,
105
- SubmittedUnverified,
106
- Delivered,
107
- Acknowledged,
108
- Consumed,
109
- Failed,
110
- BlockedLeaderUnbound,
111
- BlockedWorkerPaneMissing,
112
- }
113
-
114
- impl MessageRowStatus {
115
- pub const ALL: &[Self] = &[
116
- Self::Accepted,
117
- Self::StoredOnly,
118
- Self::QueuedUntilLeaderAttach,
119
- Self::QueuedCoordinatorUnavailable,
120
- Self::QueuedPaneMissing,
121
- Self::TargetResolved,
122
- Self::SubmittedAwaitingReceipt,
123
- Self::InjectedAwaitingReceipt,
124
- Self::SubmittedUnverified,
125
- Self::Delivered,
126
- Self::Acknowledged,
127
- Self::Consumed,
128
- Self::Failed,
129
- Self::BlockedLeaderUnbound,
130
- Self::BlockedWorkerPaneMissing,
131
- ];
132
-
133
- pub const fn as_str(self) -> &'static str {
134
- match self {
135
- Self::Accepted => "accepted",
136
- Self::StoredOnly => "stored_only",
137
- Self::QueuedUntilLeaderAttach => "queued_until_leader_attach",
138
- Self::QueuedCoordinatorUnavailable => "queued_coordinator_unavailable",
139
- Self::QueuedPaneMissing => "queued_pane_missing",
140
- Self::TargetResolved => "target_resolved",
141
- Self::SubmittedAwaitingReceipt => "submitted_pending_acceptance",
142
- Self::InjectedAwaitingReceipt => "injected_awaiting_receipt",
143
- Self::SubmittedUnverified => "submitted_unverified",
144
- Self::Delivered => "delivered",
145
- Self::Acknowledged => "acknowledged",
146
- Self::Consumed => "consumed",
147
- Self::Failed => "failed",
148
- Self::BlockedLeaderUnbound => "blocked_leader_unbound",
149
- Self::BlockedWorkerPaneMissing => "queued_pane_missing",
150
- }
151
- }
152
- }
153
-
154
- #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
155
- pub struct BlockedLeaderRequeueCounts {
156
- pub blocked_leader_unbound: usize,
157
- pub queued_until_leader_attach: usize,
158
- }
159
-
160
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
161
- pub struct RecoveryBudget {
162
- pub attempt_budget: u32,
163
- pub max_age_seconds: u64,
164
- pub owner_epoch: i64,
165
- }
166
-
167
- #[derive(Debug, Clone, PartialEq, Eq)]
168
- pub struct PaneAvailable {
169
- pub agent_id: String,
170
- pub pane_id: String,
171
- }
172
-
173
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
174
- pub enum RedisplayKind {
175
- FrameworkReplay,
176
- ProviderRerender,
177
- }
178
-
179
- impl RedisplayKind {
180
- pub const fn as_str(self) -> &'static str {
181
- match self {
182
- Self::FrameworkReplay => "framework_replay",
183
- Self::ProviderRerender => "provider_rerender",
184
- }
185
- }
186
- }
187
-
188
- impl BlockedLeaderRequeueCounts {
189
- pub const fn total(self) -> usize {
190
- self.blocked_leader_unbound + self.queued_until_leader_attach
191
- }
192
- }
193
-
194
- /// Fully resolved durable-message insert. Grammar, scope and transport data do
195
- /// not belong here; callers must resolve those before crossing this boundary.
196
- pub struct PersistMessageInput<'a> {
197
- pub message_id: Option<&'a str>,
198
- pub owner_team_id: Option<&'a str>,
199
- pub task_id: Option<&'a str>,
200
- pub sender: &'a str,
201
- pub recipient: &'a str,
202
- pub reply_to: Option<&'a str>,
203
- pub requires_ack: bool,
204
- pub status: MessageRowStatus,
205
- pub content: &'a str,
206
- pub presentation: &'a str,
207
- pub error: Option<&'a str>,
208
- }
209
-
210
- /// `leader_notification_log._legacy_epoch_from_uuid` (line 145-147):
211
- /// `int(zlib.crc32(str(uuid or "").encode("utf-8")) & 0x7FFFFFFF)`.
212
- fn legacy_epoch_from_uuid(leader_session_uuid: Option<&str>) -> i64 {
213
- let mut crc = 0xFFFF_FFFFu32;
214
- for byte in leader_session_uuid.unwrap_or("").as_bytes() {
215
- crc ^= u32::from(*byte);
216
- for _ in 0..8 {
217
- let mask = 0u32.wrapping_sub(crc & 1);
218
- crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
219
- }
220
- }
221
- i64::from((!crc) & 0x7FFF_FFFF)
222
- }
223
-
224
- /// SQLite-backed message store (`core.py:MessageStore`). `open` mirrors
225
- /// `__init__`: `runtime_dir(workspace)/team.db`, mkdir parents, init schema.
226
- pub struct MessageStore {
227
- #[allow(dead_code)]
228
- path: std::path::PathBuf,
229
- }
230
-
231
- impl MessageStore {
232
- /// `MessageStore.__init__` (`core.py:51-55`): `workspace/.team/runtime/team.db`,
233
- /// create parents, `initialize_schema`.
234
- pub fn open(workspace: &Path) -> Result<Self, MessageStoreError> {
235
- let runtime_dir = workspace.join(".team").join("runtime");
236
- std::fs::create_dir_all(&runtime_dir)?;
237
- let path = runtime_dir.join("team.db");
238
- let existed = path.exists();
239
- let conn = crate::db::schema::open_db(&path)?;
240
- if existed {
241
- conn.busy_timeout(Duration::from_millis(5))?;
242
- let version = conn.query_row("pragma user_version", [], |row| row.get::<_, i64>(0));
243
- conn.busy_timeout(Duration::from_millis(30_000))?;
244
- match version {
245
- Ok(version) if version == crate::db::schema::SCHEMA_VERSION => {}
246
- Ok(_) => crate::db::schema::initialize_schema(&conn, Some(&path))?,
247
- Err(rusqlite::Error::SqliteFailure(err, _))
248
- if matches!(
249
- err.code,
250
- rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked
251
- ) => {}
252
- Err(error) => return Err(error.into()),
253
- }
254
- } else {
255
- crate::db::schema::initialize_schema(&conn, Some(&path))?;
256
- }
257
- Ok(Self { path })
258
- }
259
-
260
- /// Absolute path to the backing `team.db` (test/diagnostic accessor).
261
- pub fn db_path(&self) -> &Path {
262
- &self.path
263
- }
264
-
265
- pub fn persist_message(
266
- &self,
267
- input: PersistMessageInput<'_>,
268
- ) -> Result<String, MessageStoreError> {
269
- let conn = crate::db::schema::open_db(&self.path)?;
270
- let message_id = input
271
- .message_id
272
- .map(ToOwned::to_owned)
273
- .unwrap_or_else(next_message_id);
274
- let now = now_ts();
275
- conn.execute(
276
- "insert into messages(
277
- message_id, owner_team_id, task_id, sender, recipient, reply_to, requires_ack,
278
- status, content, presentation, artifact_refs, created_at, updated_at, delivered_at,
279
- acknowledged_at, error, delivery_attempts
280
- ) values (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, '[]', ?11, ?11, null, null, ?12, 0)",
281
- params![
282
- message_id,
283
- input.owner_team_id,
284
- input.task_id,
285
- input.sender,
286
- input.recipient,
287
- input.reply_to,
288
- if input.requires_ack { 1 } else { 0 },
289
- input.status.as_str(),
290
- input.content,
291
- input.presentation,
292
- now,
293
- input.error,
294
- ],
295
- )?;
296
- Ok(message_id)
297
- }
298
-
299
- /// `create_message` (`core.py:71-114`). Returns `msg_<uuid4 hex[:12]>`; inserts
300
- /// a row with `status='accepted'`, `requires_ack` as 0/1 int, `artifact_refs`
301
- /// defaulting to `'[]'`, `delivery_attempts=0`, timestamps = now.
302
- #[allow(clippy::too_many_arguments)]
303
- pub fn create_message(
304
- &self,
305
- task_id: Option<&str>,
306
- sender: &str,
307
- recipient: &str,
308
- content: &str,
309
- reply_to: Option<&str>,
310
- requires_ack: bool,
311
- owner_team_id: Option<&str>,
312
- ) -> Result<String, MessageStoreError> {
313
- self.persist_message(PersistMessageInput {
314
- message_id: None,
315
- owner_team_id,
316
- task_id,
317
- sender,
318
- recipient,
319
- reply_to,
320
- requires_ack,
321
- status: MessageRowStatus::Accepted,
322
- content,
323
- presentation: r#"{"sink":"leader","class":"message"}"#,
324
- error: None,
325
- })
326
- }
327
-
328
- /// Caller-supplied-id variant of [`create_message`] (CR-015/054 — `--message-id`).
329
- /// Inserts exactly the given `message_id` instead of generating one. The store
330
- /// PK is `message_id`, so a repeat with the same id is rejected by SQLite; the
331
- /// caller is expected to gate via [`message_exists`] first to map collision to
332
- /// a typed `Duplicate` refusal rather than an opaque sqlite error.
333
- ///
334
- /// [`message_exists`]: Self::message_exists
335
- #[allow(clippy::too_many_arguments)]
336
- pub fn create_message_with_id(
337
- &self,
338
- message_id: &str,
339
- task_id: Option<&str>,
340
- sender: &str,
341
- recipient: &str,
342
- content: &str,
343
- reply_to: Option<&str>,
344
- requires_ack: bool,
345
- owner_team_id: Option<&str>,
346
- ) -> Result<String, MessageStoreError> {
347
- self.persist_message(PersistMessageInput {
348
- message_id: Some(message_id),
349
- owner_team_id,
350
- task_id,
351
- sender,
352
- recipient,
353
- reply_to,
354
- requires_ack,
355
- status: MessageRowStatus::Accepted,
356
- content,
357
- presentation: r#"{"sink":"leader","class":"message"}"#,
358
- error: None,
359
- })
360
- }
361
-
362
- /// `true` iff a `messages` row with this `message_id` already exists. Used by
363
- /// the send path to map a caller-key collision (CR-015/054) to a `Duplicate`
364
- /// refusal before attempting an insert that would otherwise fail on the PK.
365
- pub fn message_exists(&self, message_id: &str) -> Result<bool, MessageStoreError> {
366
- let conn = crate::db::schema::open_db(&self.path)?;
367
- let row: Option<i64> = conn
368
- .query_row(
369
- "select 1 from messages where message_id = ?1",
370
- params![message_id],
371
- |row| row.get(0),
372
- )
373
- .optional()?;
374
- Ok(row.is_some())
375
- }
376
-
377
- /// `mark` (`core.py:116-138`) — the messages.status state machine (this slice
378
- /// excludes the `delivery_tokens` side-effect, which is deferred).
379
- pub fn mark(
380
- &self,
381
- message_id: &str,
382
- status: &str,
383
- error: Option<&str>,
384
- ) -> Result<(), MessageStoreError> {
385
- let mut conn = crate::db::schema::open_db(&self.path)?;
386
- let tx = conn.transaction()?;
387
- let now = now_ts();
388
- let changed = tx.execute(
389
- "update messages
390
- set status = case
391
- when status = 'acknowledged'
392
- and ?2 in ('injected', 'visible', 'submitted', 'submitted_unverified', 'delivered')
393
- then status
394
- else ?2
395
- end,
396
- updated_at = ?3,
397
- delivered_at = case
398
- when ?2 in ('injected', 'visible', 'submitted', 'delivered')
399
- then ?3
400
- else delivered_at
401
- end,
402
- acknowledged_at = case when ?2 = 'acknowledged' then ?3 else acknowledged_at end,
403
- error = case when ?2 = 'delivered' then null else coalesce(?4, error) end
404
- where message_id = ?1
405
- and status not in (
406
- 'acknowledged', 'consumed', 'submitted_pending_acceptance',
407
- 'injected_awaiting_receipt'
408
- )
409
- and (status != 'delivered' or ?2 in ('delivered', 'acknowledged'))
410
- and (?2 != 'acknowledged' or status = 'delivered')",
411
- params![message_id, status, now, error],
412
- )?;
413
- if changed == 0 {
414
- let prior: Option<String> = tx
415
- .query_row(
416
- "select status from messages where message_id = ?1",
417
- params![message_id],
418
- |row| row.get(0),
419
- )
420
- .optional()?;
421
- let workspace = self
422
- .path
423
- .parent()
424
- .and_then(Path::parent)
425
- .and_then(Path::parent)
426
- .unwrap_or(Path::new("."));
427
- if status == MessageRowStatus::Acknowledged.as_str()
428
- && prior.as_deref() != Some(MessageRowStatus::Delivered.as_str())
429
- {
430
- crate::event_log::EventLog::new(workspace).write(
431
- "message.mark_refused",
432
- serde_json::json!({
433
- "message_id": message_id,
434
- "prior_status": prior,
435
- "requested_status": status,
436
- "reason": "invalid_acknowledgement_transition",
437
- }),
438
- )?;
439
- return Err(MessageStoreError::InvalidTransition {
440
- from: prior.unwrap_or_else(|| "missing".to_string()),
441
- to: status.to_string(),
442
- });
443
- }
444
- let event_log = crate::event_log::EventLog::new(workspace);
445
- event_log.write(
446
- "message.mark_refused",
447
- serde_json::json!({
448
- "message_id": message_id,
449
- "prior_status": prior,
450
- "requested_status": status,
451
- "reason": "protected_prior_state",
452
- }),
453
- )?;
454
- return Ok(());
455
- }
456
- if status == "submitted_unverified" {
457
- // Uncertainty and its independent safety net are one durable transition.
458
- // Registration never depends on provider, parser, binding or paste proof.
459
- crate::messaging::enter_rescue::schedule_in_tx(&tx, message_id, chrono::Utc::now())?;
460
- }
461
- tx.commit()?;
462
- Ok(())
463
- }
464
-
465
- /// Record that the transport submitted a message without claiming that the
466
- /// provider accepted it. The stable message id is also the receipt token.
467
- pub fn record_delivery_submission(
468
- &self,
469
- message_id: &str,
470
- visible: bool,
471
- ) -> Result<(), MessageStoreError> {
472
- let conn = crate::db::schema::open_db(&self.path)?;
473
- let now = now_ts();
474
- conn.execute(
475
- "insert into delivery_tokens(
476
- message_id, unique_token, injected_at, visible_at,
477
- consumed_at, failed_at, failure_reason
478
- ) values (?1, ?1, ?2, ?3, null, null, null)
479
- on conflict(message_id) do update set
480
- visible_at = coalesce(delivery_tokens.visible_at, excluded.visible_at),
481
- failed_at = null,
482
- failure_reason = null",
483
- params![message_id, now, visible.then_some(now_ts())],
484
- )?;
485
- Ok(())
486
- }
487
-
488
- /// Persist a verified leader transport submission when no provider receipt
489
- /// source is available. This state is claim/requeue-ineligible but does not
490
- /// clear the delivery obligation; `consumed_at` remains unset until a
491
- /// provider-side receipt reaches `mark_delivered_with_receipt`.
492
- pub fn mark_injected_awaiting_receipt(
493
- &self,
494
- message_id: &str,
495
- ) -> Result<(), MessageStoreError> {
496
- let conn = crate::db::schema::open_db(&self.path)?;
497
- let changed = conn.execute(
498
- "update messages
499
- set status = ?2,
500
- updated_at = ?3,
501
- error = 'leader_receipt_source_unavailable'
502
- where message_id = ?1
503
- and status in (?4, ?5, ?6)
504
- and exists (
505
- select 1 from delivery_tokens
506
- where delivery_tokens.message_id = messages.message_id
507
- and delivery_tokens.injected_at is not null
508
- )",
509
- params![
510
- message_id,
511
- MessageRowStatus::InjectedAwaitingReceipt.as_str(),
512
- now_ts(),
513
- MessageRowStatus::TargetResolved.as_str(),
514
- MessageRowStatus::SubmittedAwaitingReceipt.as_str(),
515
- MessageRowStatus::InjectedAwaitingReceipt.as_str(),
516
- ],
517
- )?;
518
- if changed != 1 {
519
- return Err(MessageStoreError::DeliveryReceiptMissing(
520
- message_id.to_string(),
521
- ));
522
- }
523
- Ok(())
524
- }
525
-
526
- /// Atomically persist the provider-side receipt and advance the message to
527
- /// delivered. A transport-only caller cannot use this without first
528
- /// recording the submission row above.
529
- pub fn mark_delivered_with_receipt(&self, message_id: &str) -> Result<(), MessageStoreError> {
530
- let mut conn = crate::db::schema::open_db(&self.path)?;
531
- let tx = conn.transaction()?;
532
- let now = now_ts();
533
- let receipts = tx.execute(
534
- "update delivery_tokens
535
- set consumed_at = coalesce(consumed_at, ?2),
536
- failed_at = null,
537
- failure_reason = null
538
- where message_id = ?1",
539
- params![message_id, now],
540
- )?;
541
- if receipts != 1 {
542
- return Err(MessageStoreError::DeliveryReceiptMissing(
543
- message_id.to_string(),
544
- ));
545
- }
546
- tx.execute(
547
- "update messages
548
- set status = case when status = 'acknowledged' then status else 'delivered' end,
549
- updated_at = ?2,
550
- delivered_at = ?2,
551
- error = null
552
- where message_id = ?1",
553
- params![message_id, now_ts()],
554
- )?;
555
- tx.commit()?;
556
- Ok(())
557
- }
558
-
559
- /// `claim_for_delivery` (`core.py:190-205`): atomic single-winner claim. Flips an
560
- /// eligible row (status ∈ pending/accepted/queued_until_idle/queued_until_start/
561
- /// queued_stopped/queued_pane_missing, **or** `target_resolved` with a non-null
562
- /// error — the retry/error-bypass path) to `target_resolved`, clears `error`,
563
- /// `delivery_attempts += 1`. Returns `true` iff THIS update matched exactly one
564
- /// row. Clearing `error` is the CAS: a concurrent retry cannot also match
565
- /// `error is not null`.
566
- pub fn claim_for_delivery(&self, message_id: &str) -> Result<bool, MessageStoreError> {
567
- let conn = crate::db::schema::open_db(&self.path)?;
568
- let rows = conn.execute(
569
- "update messages
570
- set status = 'target_resolved',
571
- delivery_attempts = delivery_attempts + 1,
572
- error = null,
573
- updated_at = ?2
574
- where message_id = ?1
575
- and (
576
- status in (
577
- 'pending', 'accepted', 'queued_until_idle', 'queued_until_start',
578
- 'queued_stopped', 'queued_pane_missing', ?3
579
- )
580
- or (status = 'target_resolved' and error is not null)
581
- )",
582
- params![
583
- message_id,
584
- now_ts(),
585
- MessageRowStatus::QueuedCoordinatorUnavailable.as_str()
586
- ],
587
- )?;
588
- Ok(rows == 1)
589
- }
590
-
591
- /// Release only an owned claim that has performed no input. Readiness
592
- /// waiting must remain retryable without consuming the input-attempt budget.
593
- /// A changed attempt, status, or error means this caller no longer owns it.
594
- pub(crate) fn release_delivery_before_input(
595
- &self,
596
- message_id: &str,
597
- attempt: u32,
598
- reason: &str,
599
- ) -> Result<bool, MessageStoreError> {
600
- if attempt == 0 || reason.is_empty() {
601
- return Ok(false);
602
- }
603
- let conn = crate::db::schema::open_db(&self.path)?;
604
- let rows = conn.execute(
605
- "update messages
606
- set delivery_attempts = delivery_attempts - 1,
607
- error = ?3, updated_at = ?4
608
- where message_id = ?1 and status = 'target_resolved'
609
- and error is null and delivery_attempts = ?2",
610
- params![message_id, attempt, reason, now_ts()],
611
- )?;
612
- Ok(rows == 1)
613
- }
614
-
615
- /// Park an owned pre-input claim whose readiness wait reached its bound.
616
- /// `queued_until_start` is claimable but never polled by `deliver_pending`;
617
- /// only [`Self::requeue_parked_deliveries`] or a seat restart resumes it.
618
- pub(crate) fn park_delivery_before_input(
619
- &self,
620
- message_id: &str,
621
- attempt: u32,
622
- ) -> Result<bool, MessageStoreError> {
623
- if attempt == 0 {
624
- return Ok(false);
625
- }
626
- let conn = crate::db::schema::open_db(&self.path)?;
627
- let rows = conn.execute(
628
- "update messages
629
- set status = 'queued_until_start',
630
- delivery_attempts = delivery_attempts - 1,
631
- error = ?3, updated_at = ?4
632
- where message_id = ?1 and status = 'target_resolved'
633
- and error is null and delivery_attempts = ?2",
634
- params![message_id, attempt, MCP_HANDSHAKE_TIMEOUT, now_ts()],
635
- )?;
636
- Ok(rows == 1)
637
- }
638
-
639
- /// Return one seat's parked rows to the normal delivery queue.
640
- pub(crate) fn requeue_parked_deliveries(
641
- &self,
642
- recipient: &str,
643
- owner_team_id: &str,
644
- ) -> Result<usize, MessageStoreError> {
645
- let conn = crate::db::schema::open_db(&self.path)?;
646
- Ok(conn.execute(
647
- "update messages
648
- set status = 'accepted', error = null, updated_at = ?4
649
- where recipient = ?1 and status = 'queued_until_start' and error = ?3
650
- and (owner_team_id = ?2 or owner_team_id is null)",
651
- params![recipient, owner_team_id, MCP_HANDSHAKE_TIMEOUT, now_ts()],
652
- )?)
653
- }
654
-
655
- /// Read inbox rows through [`Self::inbox`]; recovery transitions below are
656
- /// separate repository owners and are not claim eligibility.
657
- pub fn requeue_blocked_leader_messages(
658
- &self,
659
- owner_team_id: &str,
660
- ) -> Result<BlockedLeaderRequeueCounts, MessageStoreError> {
661
- let mut conn = crate::db::schema::open_db(&self.path)?;
662
- let tx = conn.transaction()?;
663
- let now = now_ts();
664
- let blocked_leader_unbound = tx.execute(
665
- "update messages
666
- set status = 'accepted', error = null, updated_at = ?1
667
- where recipient = 'leader'
668
- and owner_team_id = ?2
669
- and status = ?3
670
- and error = 'leader_not_attached'",
671
- params![now, owner_team_id, MessageRowStatus::Failed.as_str()],
672
- )?;
673
- let queued_until_leader_attach = tx.execute(
674
- "update messages
675
- set status = 'accepted', error = null, updated_at = ?1
676
- where recipient = 'leader'
677
- and owner_team_id = ?2
678
- and status = ?3",
679
- params![
680
- now,
681
- owner_team_id,
682
- MessageRowStatus::QueuedUntilLeaderAttach.as_str()
683
- ],
684
- )?;
685
- tx.commit()?;
686
- Ok(BlockedLeaderRequeueCounts {
687
- blocked_leader_unbound,
688
- queued_until_leader_attach,
689
- })
690
- }
691
-
692
- pub fn recover_worker_pane_available(
693
- &self,
694
- agent_id: &str,
695
- owner_team_id: Option<&str>,
696
- ) -> Result<Vec<String>, MessageStoreError> {
697
- let mut conn = crate::db::schema::open_db(&self.path)?;
698
- let tx = conn.transaction()?;
699
- let ids = {
700
- let mut stmt = tx.prepare(
701
- "select message_id from messages
702
- where recipient = ?1
703
- and ((status = ?2 and error = 'tmux_target_missing')
704
- or (status = 'queued_until_start' and error = ?4))
705
- and (
706
- (?3 is null and owner_team_id is null)
707
- or owner_team_id = ?3
708
- )
709
- order by created_at, message_id",
710
- )?;
711
- let rows = stmt
712
- .query_map(
713
- params![
714
- agent_id,
715
- MessageRowStatus::QueuedPaneMissing.as_str(),
716
- owner_team_id,
717
- MCP_HANDSHAKE_TIMEOUT
718
- ],
719
- |row| row.get::<_, String>(0),
720
- )?
721
- .collect::<Result<Vec<_>, _>>()?;
722
- rows
723
- };
724
- let now = now_ts();
725
- for message_id in &ids {
726
- tx.execute(
727
- "update messages
728
- set status = ?1, error = null, updated_at = ?2
729
- where message_id = ?3",
730
- params![MessageRowStatus::Accepted.as_str(), now, message_id],
731
- )?;
732
- }
733
- tx.commit()?;
734
- Ok(ids)
735
- }
736
-
737
- pub fn retry_submitted_explicit(
738
- &self,
739
- message_id: &str,
740
- incident_id: &str,
741
- operator_reason: &str,
742
- budget: RecoveryBudget,
743
- ) -> Result<bool, MessageStoreError> {
744
- if incident_id.trim().is_empty() || operator_reason.trim().is_empty() {
745
- return Err(MessageStoreError::RecoveryRefused(
746
- "incident_id_and_operator_reason_required",
747
- ));
748
- }
749
- if budget.attempt_budget == 0 || budget.max_age_seconds == 0 || budget.owner_epoch <= 0 {
750
- return Err(MessageStoreError::RecoveryRefused(
751
- "invalid_recovery_budget",
752
- ));
753
- }
754
- let conn = crate::db::schema::open_db(&self.path)?;
755
- let row: Option<(String, i64, String)> = conn
756
- .query_row(
757
- "select status, delivery_attempts, updated_at
758
- from messages where message_id = ?1",
759
- params![message_id],
760
- |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
761
- )
762
- .optional()?;
763
- let Some((status, attempts, updated_at)) = row else {
764
- return Ok(false);
765
- };
766
- if status != MessageRowStatus::SubmittedAwaitingReceipt.as_str()
767
- && status != MessageRowStatus::SubmittedUnverified.as_str()
768
- {
769
- return Err(MessageStoreError::RecoveryRefused(
770
- "message_not_submitted_recoverable",
771
- ));
772
- }
773
- if attempts >= i64::from(budget.attempt_budget) {
774
- return Err(MessageStoreError::RecoveryRefused(
775
- "attempt_budget_exhausted",
776
- ));
777
- }
778
- let updated_at = chrono::DateTime::parse_from_rfc3339(&updated_at)
779
- .map_err(|_| MessageStoreError::RecoveryRefused("invalid_updated_at"))?;
780
- let age = chrono::Utc::now()
781
- .signed_duration_since(updated_at.with_timezone(&chrono::Utc))
782
- .num_seconds();
783
- if age < 0 || u64::try_from(age).unwrap_or(u64::MAX) > budget.max_age_seconds {
784
- return Err(MessageStoreError::RecoveryRefused("message_too_old"));
785
- }
786
- let changed = conn.execute(
787
- "update messages
788
- set status = ?1, error = ?2, updated_at = ?3
789
- where message_id = ?4
790
- and status in (?5, ?6)
791
- and delivery_attempts < ?7",
792
- params![
793
- MessageRowStatus::Accepted.as_str(),
794
- format!("explicit_recovery:{incident_id}:{operator_reason}"),
795
- now_ts(),
796
- message_id,
797
- MessageRowStatus::SubmittedAwaitingReceipt.as_str(),
798
- MessageRowStatus::SubmittedUnverified.as_str(),
799
- budget.attempt_budget
800
- ],
801
- )?;
802
- Ok(changed == 1)
803
- }
804
-
805
- /// Read ordinary inbox rows for an agent. Leader stage-result notifications are
806
- /// delivered through the leader receiver, not exposed as mailbox fallback rows.
807
- /// This projection intentionally has no owner-team filter when the caller does
808
- /// not provide one: legacy/CLI inbox must surface NULL-owner messages stored for
809
- /// the agent.
810
- pub fn inbox(
811
- &self,
812
- agent_id: &str,
813
- limit: usize,
814
- owner_team_id: Option<&str>,
815
- ) -> Result<Vec<serde_json::Value>, MessageStoreError> {
816
- let conn = crate::db::schema::open_db(&self.path)?;
817
- let limit = i64::try_from(limit).unwrap_or(i64::MAX);
818
- let sql = match owner_team_id {
819
- Some(_) => {
820
- "select message_id, owner_team_id, task_id, sender, recipient, reply_to, requires_ack,
821
- status, content, artifact_refs, created_at, updated_at, delivered_at,
822
- acknowledged_at, error, delivery_attempts
823
- from messages
824
- where (sender = ?1 or recipient = ?1)
825
- and owner_team_id = ?3
826
- and coalesce(json_extract(presentation, '$.class'), 'message') != 'stage_result'
827
- order by created_at desc
828
- limit ?2"
829
- }
830
- None => {
831
- "select message_id, owner_team_id, task_id, sender, recipient, reply_to, requires_ack,
832
- status, content, artifact_refs, created_at, updated_at, delivered_at,
833
- acknowledged_at, error, delivery_attempts
834
- from messages
835
- where (sender = ?1 or recipient = ?1)
836
- and coalesce(json_extract(presentation, '$.class'), 'message') != 'stage_result'
837
- order by created_at desc
838
- limit ?2"
839
- }
840
- };
841
- let rows = match owner_team_id {
842
- Some(team) => {
843
- let mut stmt = conn.prepare(sql)?;
844
- let values = stmt
845
- .query_map(params![agent_id, limit, team], row_to_message_value)?
846
- .collect::<Result<Vec<_>, _>>()?;
847
- values
848
- }
849
- None => {
850
- let mut stmt = conn.prepare(sql)?;
851
- let values = stmt
852
- .query_map(params![agent_id, limit], row_to_message_value)?
853
- .collect::<Result<Vec<_>, _>>()?;
854
- values
855
- }
856
- };
857
- Ok(rows.into_iter().rev().collect())
858
- }
859
-
860
- /// `latest_results` (`core.py:458-471`): newest non-invalid result rows, oldest
861
- /// first (Python fetches `created_at desc limit ?` then reverses).
862
- pub fn latest_results(
863
- &self,
864
- limit: usize,
865
- owner_team_id: Option<&str>,
866
- ) -> Result<Vec<serde_json::Value>, MessageStoreError> {
867
- let conn = crate::db::schema::open_db(&self.path)?;
868
- let limit = i64::try_from(limit).unwrap_or(i64::MAX);
869
- let sql = match owner_team_id {
870
- Some(_) => {
871
- "select owner_team_id, result_id, task_id, agent_id, envelope, status, created_at
872
- from results
873
- where status != 'invalid' and owner_team_id = ?2
874
- order by created_at desc
875
- limit ?1"
876
- }
877
- None => {
878
- "select owner_team_id, result_id, task_id, agent_id, envelope, status, created_at
879
- from results
880
- where status != 'invalid'
881
- order by created_at desc
882
- limit ?1"
883
- }
884
- };
885
- let mut stmt = conn.prepare(sql)?;
886
- let map_row = |row: &rusqlite::Row<'_>| {
887
- Ok(serde_json::json!({
888
- "owner_team_id": row.get::<_, Option<String>>(0)?,
889
- "result_id": row.get::<_, String>(1)?,
890
- "task_id": row.get::<_, Option<String>>(2)?,
891
- "agent_id": row.get::<_, Option<String>>(3)?,
892
- "envelope": row.get::<_, Option<String>>(4)?,
893
- "status": row.get::<_, Option<String>>(5)?,
894
- "created_at": row.get::<_, Option<String>>(6)?,
895
- }))
896
- };
897
- let rows = match owner_team_id {
898
- Some(team) => stmt
899
- .query_map(params![limit, team], map_row)?
900
- .collect::<Result<Vec<_>, _>>()?,
901
- None => stmt
902
- .query_map(params![limit], map_row)?
903
- .collect::<Result<Vec<_>, _>>()?,
904
- };
905
- Ok(rows.into_iter().rev().collect())
906
- }
907
-
908
- /// `claim_leader_notification_delivery` (`leader_notification_log.py:30-101`):
909
- /// `INSERT OR IGNORE` on PK `(result_id, owner_team_id, owner_epoch)`. rowcount==1
910
- /// → `claimed_by_you`; else read the existing winner row → `already_notified_by`.
911
- /// `owner_team_id` defaults to `""`; `owner_epoch=None` → [`legacy_epoch_from_uuid`].
912
- pub fn claim_leader_notification_delivery(
913
- &self,
914
- params: NotificationClaimParams<'_>,
915
- ) -> Result<NotificationClaim, MessageStoreError> {
916
- let conn = crate::db::schema::open_db(&self.path)?;
917
- let owner_team_id = params.owner_team_id.unwrap_or("");
918
- let owner_epoch = match params.owner_epoch {
919
- Some(epoch) => epoch,
920
- None => legacy_epoch_from_uuid(params.leader_session_uuid),
921
- };
922
- let rows = conn.execute(
923
- "insert or ignore into leader_notification_log(
924
- result_id, owner_team_id, owner_epoch, leader_session_uuid, notified_message_id,
925
- notified_at, leader_pane_id_at_notify, envelope_content_hash
926
- ) values (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
927
- params![
928
- params.result_id,
929
- owner_team_id,
930
- owner_epoch,
931
- params.leader_session_uuid,
932
- params.proposed_message_id,
933
- now_ts(),
934
- params.pane_id,
935
- params.envelope_hash,
936
- ],
937
- )?;
938
- if rows == 1 {
939
- return Ok(NotificationClaim {
940
- status: "claimed_by_you".to_string(),
941
- notified_message_id: params.proposed_message_id.to_string(),
942
- });
943
- }
944
-
945
- let notified_message_id = conn
946
- .query_row(
947
- "select notified_message_id from leader_notification_log
948
- where result_id = ?1 and owner_team_id = ?2 and owner_epoch = ?3",
949
- params![params.result_id, owner_team_id, owner_epoch],
950
- |row| row.get::<_, String>(0),
951
- )
952
- .optional()?
953
- .ok_or(rusqlite::Error::QueryReturnedNoRows)?;
954
- Ok(NotificationClaim {
955
- status: "already_notified_by".to_string(),
956
- notified_message_id,
957
- })
958
- }
959
- }
960
-
961
- fn row_to_message_value(row: &rusqlite::Row<'_>) -> rusqlite::Result<serde_json::Value> {
962
- Ok(serde_json::json!({
963
- "message_id": row.get::<_, String>(0)?,
964
- "owner_team_id": row.get::<_, Option<String>>(1)?,
965
- "task_id": row.get::<_, Option<String>>(2)?,
966
- "sender": row.get::<_, Option<String>>(3)?,
967
- "recipient": row.get::<_, Option<String>>(4)?,
968
- "reply_to": row.get::<_, Option<String>>(5)?,
969
- "requires_ack": row.get::<_, Option<i64>>(6)?,
970
- "status": row.get::<_, Option<String>>(7)?,
971
- "content": row.get::<_, Option<String>>(8)?,
972
- "artifact_refs": row.get::<_, Option<String>>(9)?,
973
- "created_at": row.get::<_, Option<String>>(10)?,
974
- "updated_at": row.get::<_, Option<String>>(11)?,
975
- "delivered_at": row.get::<_, Option<String>>(12)?,
976
- "acknowledged_at": row.get::<_, Option<String>>(13)?,
977
- "error": row.get::<_, Option<String>>(14)?,
978
- "delivery_attempts": row.get::<_, Option<i64>>(15)?,
979
- }))
980
- }
981
-
982
- /// `result_summary_from_row`(`status/queries.py:92-106`):解析 result 行的 envelope,
983
- /// 产出 status/watch 共用的 result 摘要;envelope 坏/非对象 → `None`。
984
- pub fn result_summary_from_row(row: &serde_json::Value) -> Option<serde_json::Value> {
985
- let envelope = match row.get("envelope") {
986
- Some(serde_json::Value::String(text)) => {
987
- serde_json::from_str::<serde_json::Value>(text).ok()?
988
- }
989
- Some(value @ serde_json::Value::Object(_)) => value.clone(),
990
- _ => return None,
991
- };
992
- if !envelope.is_object() {
993
- return None;
994
- }
995
- // Python `envelope.get(k) or row.get(k)` — falsy (null/empty) falls through to the row.
996
- let pick = |key: &str| {
997
- envelope
998
- .get(key)
999
- .filter(|v| !v.is_null() && v.as_str() != Some(""))
1000
- .or_else(|| row.get(key))
1001
- .cloned()
1002
- .unwrap_or(serde_json::Value::Null)
1003
- };
1004
- Some(serde_json::json!({
1005
- "result_id": row.get("result_id").cloned().unwrap_or(serde_json::Value::Null),
1006
- "task_id": pick("task_id"),
1007
- "agent_id": pick("agent_id"),
1008
- "status": pick("status"),
1009
- "summary": envelope.get("summary").cloned().unwrap_or(serde_json::Value::Null),
1010
- "created_at": row.get("created_at").cloned().unwrap_or(serde_json::Value::Null),
1011
- }))
1012
- }
1013
-
1014
- fn now_ts() -> String {
1015
- chrono::Utc::now().to_rfc3339()
1016
- }
1017
-
1018
- fn next_message_id() -> String {
1019
- let nanos = match SystemTime::now().duration_since(UNIX_EPOCH) {
1020
- Ok(duration) => {
1021
- let low = duration.as_nanos() & u128::from(u64::MAX);
1022
- u64::try_from(low).unwrap_or(0)
1023
- }
1024
- Err(_) => 0,
1025
- };
1026
- let counter = MESSAGE_COUNTER.fetch_add(1, Ordering::Relaxed);
1027
- let pid = u64::from(std::process::id());
1028
- let value = nanos ^ counter.rotate_left(17) ^ pid.rotate_left(32);
1029
- format!("msg_{:012x}", value & 0xFFFF_FFFF_FFFF)
1030
- }
1031
-
1032
- #[cfg(test)]
1033
- mod tests {
1034
- #![allow(clippy::unwrap_used)]
1035
- use super::*;
1036
- use crate::db;
1037
- use rusqlite::Connection;
1038
- use std::path::PathBuf;
1039
- use std::sync::atomic::{AtomicU32, Ordering};
1040
-
1041
- static COUNTER: AtomicU32 = AtomicU32::new(0);
1042
-
1043
- fn temp_workspace() -> PathBuf {
1044
- let n = COUNTER.fetch_add(1, Ordering::Relaxed);
1045
- let ws = std::env::temp_dir().join(format!("ta_rs_msgstore_{}_{}", std::process::id(), n));
1046
- std::fs::create_dir_all(&ws).unwrap();
1047
- ws
1048
- }
1049
-
1050
- fn store() -> MessageStore {
1051
- MessageStore::open(&temp_workspace()).unwrap()
1052
- }
1053
-
1054
- /// Fresh read connection onto the store's team.db (asserts DB-STATE parity
1055
- /// independently of the store's own connection).
1056
- fn read(store: &MessageStore) -> Connection {
1057
- db::schema::open_db(store.db_path()).unwrap()
1058
- }
1059
-
1060
- fn col_str(conn: &Connection, mid: &str, col: &str) -> Option<String> {
1061
- // `col` is a fixed test literal, never user input.
1062
- conn.query_row(
1063
- &format!("select {col} from messages where message_id = ?1"),
1064
- [mid],
1065
- |r| r.get::<_, Option<String>>(0),
1066
- )
1067
- .unwrap()
1068
- }
1069
-
1070
- fn col_i64(conn: &Connection, mid: &str, col: &str) -> i64 {
1071
- conn.query_row(
1072
- &format!("select {col} from messages where message_id = ?1"),
1073
- [mid],
1074
- |r| r.get(0),
1075
- )
1076
- .unwrap()
1077
- }
1078
-
1079
- fn status_of(conn: &Connection, mid: &str) -> String {
1080
- col_str(conn, mid, "status").unwrap()
1081
- }
1082
-
1083
- /// (result_id, owner_team_id, owner_epoch, leader_session_uuid, notified_message_id)
1084
- /// ordered by notified_at — the dedup-relevant projection of leader_notification_log.
1085
- fn notif_rows(conn: &Connection) -> Vec<(String, String, i64, Option<String>, String)> {
1086
- let mut stmt = conn
1087
- .prepare(
1088
- "select result_id, owner_team_id, owner_epoch, leader_session_uuid, notified_message_id \
1089
- from leader_notification_log order by notified_at",
1090
- )
1091
- .unwrap();
1092
- stmt.query_map([], |r| {
1093
- Ok((
1094
- r.get::<_, String>(0)?,
1095
- r.get::<_, String>(1)?,
1096
- r.get::<_, i64>(2)?,
1097
- r.get::<_, Option<String>>(3)?,
1098
- r.get::<_, String>(4)?,
1099
- ))
1100
- })
1101
- .unwrap()
1102
- .collect::<Result<_, _>>()
1103
- .unwrap()
1104
- }
1105
-
1106
- // ───────────────────────────── create_message ─────────────────────────────
1107
-
1108
- #[test]
1109
- fn create_message_inserts_accepted_row() {
1110
- let s = store();
1111
- let mid = s
1112
- .create_message(
1113
- Some("task_1"),
1114
- "leader",
1115
- "alice",
1116
- "hello",
1117
- None,
1118
- true,
1119
- Some("team_A"),
1120
- )
1121
- .unwrap();
1122
- assert!(mid.starts_with("msg_"), "id: {mid}");
1123
- assert_eq!(mid.len(), 16, "msg_ + 12 hex");
1124
-
1125
- let c = read(&s);
1126
- assert_eq!(status_of(&c, &mid), "accepted");
1127
- assert_eq!(col_str(&c, &mid, "task_id").as_deref(), Some("task_1"));
1128
- assert_eq!(col_str(&c, &mid, "sender").as_deref(), Some("leader"));
1129
- assert_eq!(col_str(&c, &mid, "recipient").as_deref(), Some("alice"));
1130
- assert_eq!(
1131
- col_str(&c, &mid, "owner_team_id").as_deref(),
1132
- Some("team_A")
1133
- );
1134
- assert_eq!(col_str(&c, &mid, "content").as_deref(), Some("hello"));
1135
- assert_eq!(col_str(&c, &mid, "artifact_refs").as_deref(), Some("[]"));
1136
- assert_eq!(col_str(&c, &mid, "reply_to"), None);
1137
- assert_eq!(col_i64(&c, &mid, "requires_ack"), 1);
1138
- assert_eq!(col_i64(&c, &mid, "delivery_attempts"), 0);
1139
- assert_eq!(col_str(&c, &mid, "delivered_at"), None);
1140
- assert_eq!(col_str(&c, &mid, "acknowledged_at"), None);
1141
- assert_eq!(col_str(&c, &mid, "error"), None);
1142
- }
1143
-
1144
- #[test]
1145
- fn create_message_no_task_no_owner_ack_false() {
1146
- let s = store();
1147
- let mid = s
1148
- .create_message(None, "leader", "bob", "hi", None, false, None)
1149
- .unwrap();
1150
- let c = read(&s);
1151
- assert_eq!(col_str(&c, &mid, "task_id"), None);
1152
- assert_eq!(col_str(&c, &mid, "owner_team_id"), None);
1153
- assert_eq!(col_i64(&c, &mid, "requires_ack"), 0);
1154
- assert_eq!(status_of(&c, &mid), "accepted");
1155
- }
1156
-
1157
- // ───────────────────────── claim_for_delivery (atomic claim) ─────────────────────────
1158
-
1159
- #[test]
1160
- fn claim_for_delivery_first_caller_wins() {
1161
- let s = store();
1162
- let mid = s
1163
- .create_message(Some("t"), "s", "r", "c", None, true, None)
1164
- .unwrap();
1165
-
1166
- assert!(
1167
- s.claim_for_delivery(&mid).unwrap(),
1168
- "accepted is eligible → claim wins"
1169
- );
1170
- let c = read(&s);
1171
- assert_eq!(status_of(&c, &mid), "target_resolved");
1172
- assert_eq!(col_i64(&c, &mid, "delivery_attempts"), 1);
1173
- }
1174
-
1175
- #[test]
1176
- fn claim_for_delivery_second_caller_loses_and_state_unchanged() {
1177
- // Atomic single-winner: once target_resolved, a re-claim returns false and
1178
- // must NOT bump delivery_attempts again.
1179
- let s = store();
1180
- let mid = s
1181
- .create_message(Some("t"), "s", "r", "c", None, true, None)
1182
- .unwrap();
1183
- assert!(s.claim_for_delivery(&mid).unwrap());
1184
- assert!(
1185
- !s.claim_for_delivery(&mid).unwrap(),
1186
- "already target_resolved → no second winner"
1187
- );
1188
-
1189
- let c = read(&s);
1190
- assert_eq!(status_of(&c, &mid), "target_resolved");
1191
- assert_eq!(col_i64(&c, &mid, "delivery_attempts"), 1);
1192
- }
1193
-
1194
- #[test]
1195
- fn claim_for_delivery_nonexistent_is_false() {
1196
- let s = store();
1197
- assert!(!s.claim_for_delivery("msg_doesnotexist").unwrap());
1198
- }
1199
-
1200
- #[test]
1201
- fn claim_for_delivery_ineligible_status_is_false() {
1202
- // 'failed' is not in the eligible set → claim returns false, status unchanged.
1203
- let s = store();
1204
- let mid = s
1205
- .create_message(Some("t"), "s", "r", "c", None, true, None)
1206
- .unwrap();
1207
- s.mark(&mid, "failed", Some("boom")).unwrap();
1208
- assert!(!s.claim_for_delivery(&mid).unwrap());
1209
- assert_eq!(status_of(&read(&s), &mid), "failed");
1210
- }
1211
-
1212
- #[test]
1213
- fn claim_for_delivery_error_retry_is_atomic_single_winner() {
1214
- let s = store();
1215
- let mid = s
1216
- .create_message(Some("t"), "s", "r", "c", None, true, None)
1217
- .unwrap();
1218
- s.mark(&mid, "target_resolved", Some("probe_failed"))
1219
- .unwrap();
1220
- assert_eq!(
1221
- col_str(&read(&s), &mid, "error").as_deref(),
1222
- Some("probe_failed")
1223
- );
1224
- assert!(
1225
- s.claim_for_delivery(&mid).unwrap(),
1226
- "target_resolved+error must enter the claim gate, not a non-CAS bypass"
1227
- );
1228
- let c = read(&s);
1229
- assert_eq!(status_of(&c, &mid), "target_resolved");
1230
- assert_eq!(col_str(&c, &mid, "error"), None);
1231
- assert_eq!(col_i64(&c, &mid, "delivery_attempts"), 1);
1232
- assert!(
1233
- !s.claim_for_delivery(&mid).unwrap(),
1234
- "cleared error must lose the second claim"
1235
- );
1236
- assert_eq!(col_i64(&read(&s), &mid, "delivery_attempts"), 1);
1237
- }
1238
-
1239
- #[test]
1240
- fn release_delivery_before_input_preserves_budget_and_single_winner() {
1241
- let s = store();
1242
- let mid = s.create_message(Some("t"), "s", "r", "c", None, true, None).unwrap();
1243
- assert!(s.claim_for_delivery(&mid).unwrap());
1244
- assert!(!s.claim_for_delivery(&mid).unwrap());
1245
- assert!(s.release_delivery_before_input(&mid, 1, "mcp_handshake_missing").unwrap());
1246
- assert_eq!(col_i64(&read(&s), &mid, "delivery_attempts"), 0);
1247
- assert_eq!(col_str(&read(&s), &mid, "error").as_deref(), Some("mcp_handshake_missing"));
1248
- assert!(!s.release_delivery_before_input(&mid, 1, "late").unwrap());
1249
- assert!(s.claim_for_delivery(&mid).unwrap());
1250
- assert!(!s.claim_for_delivery(&mid).unwrap());
1251
- assert_eq!(col_i64(&read(&s), &mid, "delivery_attempts"), 1);
1252
- }
1253
-
1254
- #[test]
1255
- fn release_delivery_before_input_cannot_overwrite_changed_claims() {
1256
- let s = store();
1257
- let mid = s.create_message(Some("t"), "s", "r", "c", None, true, None).unwrap();
1258
- assert!(s.claim_for_delivery(&mid).unwrap());
1259
- assert!(!s.release_delivery_before_input(&mid, 0, "missing").unwrap());
1260
- assert!(!s.release_delivery_before_input(&mid, 2, "stale").unwrap());
1261
- s.mark(&mid, "target_resolved", Some("other_owner")).unwrap();
1262
- assert!(!s.release_delivery_before_input(&mid, 1, "stale").unwrap());
1263
- assert_eq!(col_str(&read(&s), &mid, "error").as_deref(), Some("other_owner"));
1264
- assert!(s.claim_for_delivery(&mid).unwrap());
1265
- assert!(!s.release_delivery_before_input(&mid, 1, "old_claim").unwrap());
1266
- assert_eq!(col_i64(&read(&s), &mid, "delivery_attempts"), 2);
1267
- assert_eq!(col_str(&read(&s), &mid, "error"), None);
1268
- for status in ["cancelled", "delivered", "submitted_unverified"] {
1269
- // Each terminal/effect state needs its own row: mark correctly
1270
- // refuses to downgrade a previously delivered row.
1271
- let changed = s.create_message(Some("t"), "s", "r", "c", None, true, None).unwrap();
1272
- assert!(s.claim_for_delivery(&changed).unwrap());
1273
- s.mark(&changed, status, None).unwrap();
1274
- assert!(!s.release_delivery_before_input(&changed, 1, "stale").unwrap());
1275
- assert_eq!(status_of(&read(&s), &changed), status);
1276
- assert_eq!(col_i64(&read(&s), &changed, "delivery_attempts"), 1);
1277
- }
1278
- }
1279
-
1280
- #[test]
1281
- fn issue372_parked_handshake_claim_is_exact_and_resumes_per_seat() {
1282
- let s = store();
1283
- let mid = s.create_message(Some("t"), "s", "r", "c", None, true, Some("team-a")).unwrap();
1284
- assert!(!s.park_delivery_before_input(&mid, 1).unwrap(), "unclaimed rows never park");
1285
- assert!(s.claim_for_delivery(&mid).unwrap());
1286
- assert!(!s.park_delivery_before_input(&mid, 2).unwrap(), "a stale claim cannot park");
1287
- assert!(s.park_delivery_before_input(&mid, 1).unwrap());
1288
- assert!(!s.park_delivery_before_input(&mid, 1).unwrap(), "single winner");
1289
- let c = read(&s);
1290
- assert_eq!(status_of(&c, &mid), "queued_until_start");
1291
- assert_eq!(col_str(&c, &mid, "error").as_deref(), Some(MCP_HANDSHAKE_TIMEOUT));
1292
- assert_eq!(col_i64(&c, &mid, "delivery_attempts"), 0, "waiting spends no input attempt");
1293
- assert_eq!(s.requeue_parked_deliveries("other", "team-a").unwrap(), 0);
1294
- assert_eq!(s.requeue_parked_deliveries("r", "team-b").unwrap(), 0);
1295
- assert_eq!(s.requeue_parked_deliveries("r", "team-a").unwrap(), 1);
1296
- let c = read(&s);
1297
- assert_eq!(status_of(&c, &mid), "accepted");
1298
- assert_eq!(col_str(&c, &mid, "error"), None);
1299
- }
1300
-
1301
- #[test]
1302
- fn issue372_seat_restart_also_resumes_parked_handshake_rows() {
1303
- let s = store();
1304
- let mid = s.create_message(Some("t"), "s", "r", "c", None, true, Some("team-a")).unwrap();
1305
- assert!(s.claim_for_delivery(&mid).unwrap());
1306
- assert!(s.park_delivery_before_input(&mid, 1).unwrap());
1307
- assert_eq!(s.recover_worker_pane_available("r", Some("team-a")).unwrap(), vec![mid.clone()]);
1308
- assert_eq!(status_of(&read(&s), &mid), "accepted");
1309
- }
1310
-
1311
- #[test]
1312
- fn claim_for_delivery_never_claims_stored_only_presentation() {
1313
- let s = store();
1314
- let mid = s
1315
- .persist_message(PersistMessageInput {
1316
- message_id: None,
1317
- owner_team_id: Some("team-a"),
1318
- task_id: None,
1319
- sender: "worker",
1320
- recipient: "leader",
1321
- reply_to: None,
1322
- requires_ack: false,
1323
- status: MessageRowStatus::StoredOnly,
1324
- content: "casefile evidence",
1325
- presentation: r#"{"sink":"casefile","class":"stage_result"}"#,
1326
- error: None,
1327
- })
1328
- .unwrap();
1329
- assert!(!s.claim_for_delivery(&mid).unwrap());
1330
- assert_eq!(status_of(&read(&s), &mid), "stored_only");
1331
- assert_eq!(col_i64(&read(&s), &mid, "delivery_attempts"), 0);
1332
- }
1333
-
1334
- // ───────────────────────────── mark state machine ─────────────────────────────
1335
-
1336
- #[test]
1337
- fn mark_injected_sets_status_and_delivered_at() {
1338
- let s = store();
1339
- let mid = s
1340
- .create_message(Some("t"), "s", "r", "c", None, true, None)
1341
- .unwrap();
1342
- s.mark(&mid, "injected", None).unwrap();
1343
- let c = read(&s);
1344
- assert_eq!(status_of(&c, &mid), "injected");
1345
- assert!(
1346
- col_str(&c, &mid, "delivered_at").is_some(),
1347
- "delivered_at set for injected"
1348
- );
1349
- assert_eq!(col_str(&c, &mid, "acknowledged_at"), None);
1350
- }
1351
-
1352
- #[test]
1353
- fn mark_acknowledged_is_sticky_against_delivery_statuses() {
1354
- // CASE guard: once acknowledged, marks to injected/visible/... are ignored.
1355
- let s = store();
1356
- let mid = s
1357
- .create_message(Some("t"), "s", "r", "c", None, true, None)
1358
- .unwrap();
1359
- s.mark(&mid, "delivered", None).unwrap();
1360
- s.mark(&mid, "acknowledged", None).unwrap();
1361
- assert_eq!(status_of(&read(&s), &mid), "acknowledged");
1362
- assert!(col_str(&read(&s), &mid, "acknowledged_at").is_some());
1363
-
1364
- s.mark(&mid, "injected", None).unwrap();
1365
- assert_eq!(
1366
- status_of(&read(&s), &mid),
1367
- "acknowledged",
1368
- "injected ignored after ack"
1369
- );
1370
- s.mark(&mid, "visible", None).unwrap();
1371
- assert_eq!(
1372
- status_of(&read(&s), &mid),
1373
- "acknowledged",
1374
- "visible ignored after ack"
1375
- );
1376
- }
1377
-
1378
- #[test]
1379
- fn mark_acknowledged_then_failed_stays_terminal() {
1380
- let s = store();
1381
- let mid = s
1382
- .create_message(Some("t"), "s", "r", "c", None, true, None)
1383
- .unwrap();
1384
- s.mark(&mid, "delivered", None).unwrap();
1385
- s.mark(&mid, "acknowledged", None).unwrap();
1386
- s.mark(&mid, "failed", Some("x")).unwrap();
1387
- assert_eq!(status_of(&read(&s), &mid), "acknowledged");
1388
- }
1389
-
1390
- #[test]
1391
- fn mark_overwrites_for_non_acknowledged() {
1392
- let s = store();
1393
- let mid = s
1394
- .create_message(Some("t"), "s", "r", "c", None, true, None)
1395
- .unwrap();
1396
- s.mark(&mid, "injected", None).unwrap();
1397
- s.mark(&mid, "visible", None).unwrap();
1398
- assert_eq!(status_of(&read(&s), &mid), "visible");
1399
- }
1400
-
1401
- // ───────────────────── leader_notification_log dedup ─────────────────────
1402
-
1403
- fn params<'a>(
1404
- result_id: &'a str,
1405
- owner_team_id: Option<&'a str>,
1406
- owner_epoch: Option<i64>,
1407
- uuid: Option<&'a str>,
1408
- proposed: &'a str,
1409
- ) -> NotificationClaimParams<'a> {
1410
- NotificationClaimParams {
1411
- result_id,
1412
- owner_team_id,
1413
- owner_epoch,
1414
- leader_session_uuid: uuid,
1415
- proposed_message_id: proposed,
1416
- envelope_hash: "h1",
1417
- pane_id: Some("%1"),
1418
- }
1419
- }
1420
-
1421
- #[test]
1422
- fn leader_notification_dedup_key_excludes_session_uuid() {
1423
- // SAME (result_id, owner_team_id, owner_epoch) but DIFFERENT leader_session_uuid
1424
- // and proposed id → second is deduped to the first winner.
1425
- let s = store();
1426
- let r1 = s
1427
- .claim_leader_notification_delivery(params(
1428
- "res_1",
1429
- Some("team_A"),
1430
- Some(7),
1431
- Some("uuid-AAA"),
1432
- "msg_notif_1",
1433
- ))
1434
- .unwrap();
1435
- assert_eq!(r1.status, "claimed_by_you");
1436
- assert_eq!(r1.notified_message_id, "msg_notif_1");
1437
-
1438
- let r2 = s
1439
- .claim_leader_notification_delivery(params(
1440
- "res_1",
1441
- Some("team_A"),
1442
- Some(7),
1443
- Some("uuid-BBB"),
1444
- "msg_notif_2",
1445
- ))
1446
- .unwrap();
1447
- assert_eq!(r2.status, "already_notified_by");
1448
- assert_eq!(
1449
- r2.notified_message_id, "msg_notif_1",
1450
- "loser sees first winner's id, not its own"
1451
- );
1452
-
1453
- // Exactly ONE row — carrying the FIRST caller's uuid (uuid not in the key).
1454
- assert_eq!(
1455
- notif_rows(&read(&s)),
1456
- vec![(
1457
- "res_1".to_string(),
1458
- "team_A".to_string(),
1459
- 7,
1460
- Some("uuid-AAA".to_string()),
1461
- "msg_notif_1".to_string()
1462
- )]
1463
- );
1464
- }
1465
-
1466
- #[test]
1467
- fn leader_notification_different_epoch_is_a_new_claim() {
1468
- let s = store();
1469
- s.claim_leader_notification_delivery(params(
1470
- "res_1",
1471
- Some("team_A"),
1472
- Some(7),
1473
- Some("uuid-AAA"),
1474
- "msg_notif_1",
1475
- ))
1476
- .unwrap();
1477
- let r3 = s
1478
- .claim_leader_notification_delivery(params(
1479
- "res_1",
1480
- Some("team_A"),
1481
- Some(8),
1482
- Some("uuid-AAA"),
1483
- "msg_notif_3",
1484
- ))
1485
- .unwrap();
1486
- assert_eq!(
1487
- r3.status, "claimed_by_you",
1488
- "different owner_epoch → different PK → new claim"
1489
- );
1490
-
1491
- let rows = notif_rows(&read(&s));
1492
- assert_eq!(rows.len(), 2);
1493
- assert_eq!(rows[0].2, 7);
1494
- assert_eq!(rows[1].2, 8);
1495
- assert_eq!(rows[1].4, "msg_notif_3");
1496
- }
1497
-
1498
- #[test]
1499
- fn leader_notification_none_epoch_derives_from_uuid() {
1500
- // owner_epoch=None → epoch derived from uuid. Same uuid dedups; different uuid
1501
- // yields a different derived epoch → a new claim.
1502
- let s = store();
1503
- let a1 = s
1504
- .claim_leader_notification_delivery(params(
1505
- "res_2",
1506
- Some("team_B"),
1507
- None,
1508
- Some("uuid-AAA"),
1509
- "m1",
1510
- ))
1511
- .unwrap();
1512
- assert_eq!(a1.status, "claimed_by_you");
1513
-
1514
- let a2 = s
1515
- .claim_leader_notification_delivery(params(
1516
- "res_2",
1517
- Some("team_B"),
1518
- None,
1519
- Some("uuid-AAA"),
1520
- "m2",
1521
- ))
1522
- .unwrap();
1523
- assert_eq!(a2.status, "already_notified_by");
1524
- assert_eq!(a2.notified_message_id, "m1");
1525
-
1526
- let a3 = s
1527
- .claim_leader_notification_delivery(params(
1528
- "res_2",
1529
- Some("team_B"),
1530
- None,
1531
- Some("uuid-BBB"),
1532
- "m3",
1533
- ))
1534
- .unwrap();
1535
- assert_eq!(
1536
- a3.status, "claimed_by_you",
1537
- "different uuid → different derived epoch → new claim"
1538
- );
1539
-
1540
- // Stored epochs equal the crc32 derivation of each uuid.
1541
- let rows = notif_rows(&read(&s));
1542
- assert_eq!(rows.len(), 2);
1543
- assert_eq!(rows[0].2, 926068568); // crc32('uuid-AAA') & 0x7FFFFFFF
1544
- assert_eq!(rows[1].2, 122688376); // crc32('uuid-BBB') & 0x7FFFFFFF
1545
- }
1546
-
1547
- #[test]
1548
- fn legacy_epoch_from_uuid_crc32_golden() {
1549
- assert_eq!(legacy_epoch_from_uuid(None), 0);
1550
- assert_eq!(legacy_epoch_from_uuid(Some("")), 0);
1551
- assert_eq!(legacy_epoch_from_uuid(Some("uuid-AAA")), 926068568);
1552
- assert_eq!(legacy_epoch_from_uuid(Some("uuid-BBB")), 122688376);
1553
- }
1554
-
1555
- // ════════════════════════ FIX-LOOP (wave-1) RED test ════════════════════════
1556
- // B1: mark() error column = coalesce(?, error) — a NEW error overwrites, but a
1557
- // mark WITHOUT an error must PRESERVE the existing error (current impl clobbers
1558
- // it to NULL). Golden /tmp/probe_b1.py vs team-agent-public v0.2.11.
1559
-
1560
- #[test]
1561
- fn fix_b1_mark_preserves_existing_error_when_none_given() {
1562
- let s = store();
1563
- let mid = s
1564
- .create_message(Some("t"), "a", "b", "c", None, true, None)
1565
- .unwrap();
1566
-
1567
- s.mark(&mid, "failed", Some("boom")).unwrap();
1568
- assert_eq!(col_str(&read(&s), &mid, "error").as_deref(), Some("boom"));
1569
-
1570
- // Non-error mark to a delivery status: status/delivered_at advance, but error
1571
- // must remain 'boom' (coalesce(NULL, error)), NOT be clobbered to NULL.
1572
- s.mark(&mid, "injected", None).unwrap();
1573
- let c = read(&s);
1574
- assert_eq!(status_of(&c, &mid), "injected");
1575
- assert_eq!(
1576
- col_str(&c, &mid, "error").as_deref(),
1577
- Some("boom"),
1578
- "existing error must survive a no-error mark"
1579
- );
1580
-
1581
- // A NEW error overwrites.
1582
- s.mark(&mid, "failed", Some("second")).unwrap();
1583
- assert_eq!(col_str(&read(&s), &mid, "error").as_deref(), Some("second"));
1584
- }
1585
- }