@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,2631 +0,0 @@
1
- //! ---
2
- //! purpose: 会话捕获通道——把「席位有 pending id 但还没有权威会话」这件事,经扫描候选 + 分配器,收敛成 state 上的原子四元组(session_id + rollout_path + captured_at + captured_via),收敛不了就写明确的诊断态
3
- //! contract:
4
- //! provides:
5
- //! - name: capture_missing_provider_sessions_once
6
- //! what: 单次捕获通道:挑 pending 席位 → adapter 扫候选 → 分配 → 写四元组或写 ambiguous/identity_mismatch/transcript_missing
7
- //! - name: converge_missing_provider_sessions
8
- //! what: 破坏性生命周期门用的有界收敛屏障:显式 deadline + poll_interval,反复调上一函数直到无缺口或超预算
9
- //! - name: recover_resume_session_from_events
10
- //! what: 从 event log 的 session.captured 记录补回缺失的四元组,captured_via=event_log_repair
11
- //! - name: incomplete_resumable_agent_ids
12
- //! what: 列出「provider 支持 resume 但四元组不完整」的席位 id,已排序
13
- //! - name: incomplete_interacted_resumable_agent_ids
14
- //! what: 上一条再筛「有过 first_send_at」的子集
15
- //! - name: CapturePassReport
16
- //! what: 单次捕获的结果面:changed/pending/assigned/ambiguous/identity_mismatches/capture_failures/candidate_count_by_agent/transcript_missing
17
- //! - name: SessionConvergence
18
- //! what: 收敛结果:converged 是否达成、changed、剩余 missing、预算与实耗
19
- //! - name: SessionConvergenceProgress
20
- //! what: 每轮回调给调用方的进度快照
21
- //! - name: SESSION_CAPTURE_CONVERGENCE_DEADLINE_MS
22
- //! what: 默认收敛预算 12s(restart 复用同一常量)
23
- //! - name: SESSION_CAPTURE_CONVERGENCE_POLL_MS
24
- //! what: 默认轮询间隔 250ms
25
- //! requires:
26
- //! - name: crate::provider::ProviderAdapter
27
- //! what: 候选扫描一律经 adapter.capture_session_candidates,本文件不直接读 provider 存档
28
- //! - name: crate::state::identity_keys::SessionAttributionKey
29
- //! what: 分配器的 claimed 键空间(Session/Transcript × team-scoped/global)
30
- //! - name: crate::event_log::EventLog
31
- //! what: event-log 修复通道的事实源
32
- //! boundary:
33
- //! - 四元组是原子的:缺 session_id 或 rollout_path 就整条不写,宁可留 pending 也不写半条
34
- //! - 不发事件——transcript_missing 只进报告,事件由 coordinator tick 节流发出
35
- //! - 不启动/销毁席位,不决定 restart 走向;只提供事实与诊断态
36
- //! - capture_state 只是诊断字段,写它不等于写权威四元组
37
- //! - 歧义只在 finalize_ambiguous=true 的那一趟才落盘;收敛超时的那趟不 finalize
38
- //! maturity: wired
39
- //! ---
40
- use std::collections::{BTreeMap, BTreeSet};
41
- use std::path::{Path, PathBuf};
42
-
43
- use serde_json::Value;
44
-
45
- use crate::provider::wire::{is_claude_family, parse_provider};
46
- use crate::provider::{
47
- CaptureSessionContext, CapturedSession, CapturedSessionCandidate, Provider, ProviderAdapter,
48
- ProviderError, SessionId,
49
- };
50
- use crate::state::identity_keys::SessionAttributionKey;
51
-
52
- pub const SESSION_CAPTURE_CONVERGENCE_DEADLINE_MS: u64 = 12_000;
53
- pub const SESSION_CAPTURE_CONVERGENCE_POLL_MS: u64 = 250;
54
- pub const RESTART_SESSION_CONVERGENCE_DEADLINE_MS: u64 = SESSION_CAPTURE_CONVERGENCE_DEADLINE_MS;
55
- pub const RESTART_SESSION_CONVERGENCE_POLL_MS: u64 = SESSION_CAPTURE_CONVERGENCE_POLL_MS;
56
-
57
- #[derive(Debug, Clone, Default, PartialEq, Eq)]
58
- pub struct CapturePassReport {
59
- pub changed: bool,
60
- pub pending: Vec<String>,
61
- pub assigned: Vec<String>,
62
- pub ambiguous: Vec<AmbiguousSessionCapture>,
63
- pub identity_mismatches: Vec<SessionIdentityMismatch>,
64
- pub capture_failures: Vec<SessionCaptureFailure>,
65
- pub candidate_count_by_agent: BTreeMap<String, usize>,
66
- /// 0.4.6 Stage 3: agents that transitioned into the
67
- /// `transcript_missing` capture_state during this pass. The caller
68
- /// (coordinator tick) emits a throttled
69
- /// `provider.session.transcript_missing` event for each entry.
70
- pub transcript_missing: Vec<TranscriptMissing>,
71
- }
72
-
73
- #[derive(Debug, Clone, PartialEq, Eq)]
74
- pub struct SessionCaptureFailure {
75
- pub agent_id: String,
76
- pub error: String,
77
- }
78
-
79
- #[derive(Debug, Clone, PartialEq, Eq)]
80
- pub struct AmbiguousSessionCapture {
81
- pub agent_id: String,
82
- pub spawn_cwd: String,
83
- }
84
-
85
- #[derive(Debug, Clone, PartialEq, Eq)]
86
- pub struct SessionIdentityMismatch {
87
- pub agent_id: String,
88
- pub expected_agent_id: String,
89
- pub embedded_agent_id: String,
90
- pub session_id: Option<String>,
91
- pub rollout_path: Option<String>,
92
- pub spawn_cwd: String,
93
- }
94
-
95
- /// 0.4.6 Stage 3: information emitted when a pending agent transitions
96
- /// into the `transcript_missing` capture_state. Carries the diagnostic
97
- /// fields the caller uses to write the
98
- /// `provider.session.transcript_missing` event.
99
- #[derive(Debug, Clone, PartialEq, Eq)]
100
- pub struct TranscriptMissing {
101
- pub agent_id: String,
102
- pub spawn_cwd: String,
103
- pub spawn_epoch: u64,
104
- pub expected_session_id: Option<String>,
105
- pub candidate_count: usize,
106
- }
107
-
108
- #[derive(Debug, Clone, PartialEq, Eq)]
109
- pub struct SessionConvergence {
110
- pub converged: bool,
111
- pub changed: bool,
112
- pub missing: Vec<String>,
113
- pub deadline: std::time::Duration,
114
- pub elapsed: std::time::Duration,
115
- }
116
-
117
- #[derive(Debug, Clone, PartialEq, Eq)]
118
- pub struct SessionConvergenceProgress {
119
- pub iteration: u64,
120
- pub elapsed_ms: u128,
121
- pub deadline_ms: u128,
122
- pub remaining_ms: u128,
123
- pub changed: bool,
124
- pub assigned: Vec<String>,
125
- pub missing: Vec<String>,
126
- pub required_missing_agent_ids: Vec<String>,
127
- pub pending_agent_ids: Vec<String>,
128
- pub candidate_count_by_agent: BTreeMap<String, usize>,
129
- }
130
-
131
- /// Bounded session convergence barrier for destructive lifecycle gates.
132
- ///
133
- /// This is intentionally not one opportunistic capture pass and not an
134
- /// unbounded wait: callers must pass an explicit `deadline` and `poll_interval`.
135
- /// Each poll runs the shared allocator once, reports progress, and sleeps until
136
- /// either all required agents have provider sessions or the deadline expires.
137
- /// ---
138
- /// purpose: 有界收敛屏障——在显式预算内反复跑单次捕获,直到调用方指定的必需席位都拿到会话,或预算耗尽
139
- /// params:
140
- /// state: 就地修改的 state JSON;每轮的写入都直接落在它上面
141
- /// adapter_for: provider → adapter 的工厂
142
- /// deadline: 总预算;绝不无限等待
143
- /// poll_interval: 轮询间隔;同时用作单次捕获的 timeout(取秒数,至少 1)
144
- /// missing_agent_ids: 由调用方定义「谁必须有会话」——本函数不自己判定必需集
145
- /// progress: 每轮回调;返回 Err 即整体中止并把该错误上抛
146
- /// returns: converged=true 表示 missing 已空;converged=false 表示预算到期仍有缺口,两者都是正常返回而非错误
147
- /// errors: 单次捕获的 ProviderError 与 progress 回调的错误都被转成 String 上抛
148
- /// contract:
149
- /// provides:
150
- /// - name: converge_missing_provider_sessions
151
- /// what: 只有 missing 清空后才会补跑一趟 finalize_ambiguous=true;超时路径不补跑
152
- /// boundary:
153
- /// - 不是机会式单次捕获,也不是无界等待——预算必须由调用方显式给出
154
- /// - 超时返回时歧义态未被 finalize:行上不会出现 attribution_ambiguous 标记;capture_state 保持前值(可能缺失)——非歧义的 pending 席位仍会被单次捕获写成 pending_first_turn / pending_context_fork / transcript_missing,这不受 finalize 开关控制
155
- /// - progress 只报告不决策;是否继续由预算决定
156
- /// ---
157
- pub fn converge_missing_provider_sessions<F, M, P>(
158
- state: &mut Value,
159
- adapter_for: &mut F,
160
- deadline: std::time::Duration,
161
- poll_interval: std::time::Duration,
162
- mut missing_agent_ids: M,
163
- mut progress: P,
164
- ) -> Result<SessionConvergence, String>
165
- where
166
- F: FnMut(Provider) -> Box<dyn ProviderAdapter>,
167
- M: FnMut(&Value) -> Vec<String>,
168
- P: FnMut(SessionConvergenceProgress) -> Result<(), String>,
169
- {
170
- let start = std::time::Instant::now();
171
- let deadline_at = start + deadline;
172
- let mut changed = false;
173
- let mut iteration = 0_u64;
174
- loop {
175
- let timeout_s = poll_interval.as_secs().max(1);
176
- let required_missing = missing_agent_ids(state);
177
- let report = capture_missing_provider_sessions_once(state, adapter_for, false, timeout_s)
178
- .map_err(|e| e.to_string())?;
179
- changed |= report.changed;
180
- let missing = missing_agent_ids(state);
181
- progress(SessionConvergenceProgress {
182
- iteration,
183
- elapsed_ms: start.elapsed().as_millis(),
184
- deadline_ms: deadline.as_millis(),
185
- remaining_ms: deadline_at
186
- .saturating_duration_since(std::time::Instant::now())
187
- .as_millis(),
188
- changed: report.changed,
189
- assigned: report.assigned,
190
- missing: missing.clone(),
191
- required_missing_agent_ids: required_missing,
192
- pending_agent_ids: missing.clone(),
193
- candidate_count_by_agent: report.candidate_count_by_agent.clone(),
194
- })?;
195
- if missing.is_empty() {
196
- if !report.ambiguous.is_empty() {
197
- let final_report =
198
- capture_missing_provider_sessions_once(state, adapter_for, true, timeout_s)
199
- .map_err(|e| e.to_string())?;
200
- changed |= final_report.changed;
201
- }
202
- return Ok(SessionConvergence {
203
- converged: true,
204
- changed,
205
- missing,
206
- deadline,
207
- elapsed: start.elapsed(),
208
- });
209
- }
210
- let now = std::time::Instant::now();
211
- if now >= deadline_at {
212
- return Ok(SessionConvergence {
213
- converged: false,
214
- changed,
215
- missing: missing_agent_ids(state),
216
- deadline,
217
- elapsed: start.elapsed(),
218
- });
219
- }
220
- std::thread::sleep(std::cmp::min(
221
- poll_interval,
222
- deadline_at.saturating_duration_since(now),
223
- ));
224
- iteration += 1;
225
- }
226
- }
227
-
228
- /// ---
229
- /// purpose: 跑一趟捕获——为每个还缺权威会话的席位扫候选、经分配器定归属,把能确定的写成原子四元组,把不能确定的写成诊断态
230
- /// params:
231
- /// state: 就地修改的 state JSON;无 agents 对象时直接返回空报告
232
- /// adapter_for: provider → adapter 的工厂;扫描一律经 adapter
233
- /// finalize_ambiguous: false 时歧义只进报告不落盘;true 时才把 attribution_ambiguous / capture_state 写进 agent 行
234
- /// timeout_s: 传给 adapter.capture_session_candidates 的单席位扫描预算
235
- /// returns: CapturePassReport;changed 表示 state 被改过,调用方据此决定是否持久化
236
- /// errors: 当前实现不产生 Err(Result 签名为与调用方同形);取不到 agents 视图返回空报告;单席位扫描失败进 capture_failures 且该席位保持 pending,不中断整趟
237
- /// contract:
238
- /// provides:
239
- /// - name: capture_missing_provider_sessions_once
240
- /// what: 写权威四元组的唯一常规通道(另一条是 event-log 修复)
241
- /// boundary:
242
- /// - 候选的 embedded worker id 与本席位不符 → 记 identity_mismatch 并跳过,绝不写会话
243
- /// - 候选 session id 与 pending expected id 不符 → 记 ambiguous 并跳过,绝不写会话
244
- /// - _pending_session_id 与行上 session_id 不一致时不 stamp captured——重开在途,旧会话不得被宣告为新席位的权威
245
- /// - 不发事件;transcript_missing 只进报告
246
- /// ---
247
- pub fn capture_missing_provider_sessions_once<F>(
248
- state: &mut Value,
249
- adapter_for: &mut F,
250
- finalize_ambiguous: bool,
251
- timeout_s: u64,
252
- ) -> Result<CapturePassReport, ProviderError>
253
- where
254
- F: FnMut(Provider) -> Box<dyn ProviderAdapter>,
255
- {
256
- let Some(agent_map) = state.get("agents").and_then(Value::as_object) else {
257
- return Ok(CapturePassReport::default());
258
- };
259
- let mut pending = Vec::new();
260
- let mut capture_failures = Vec::new();
261
- let mut candidates_by_agent = BTreeMap::new();
262
- for (agent_id, agent) in agent_map {
263
- let Some(capture) = pending_session_capture(agent_id, agent, adapter_for) else {
264
- continue;
265
- };
266
- let adapter = adapter_for(capture.provider);
267
- let candidates = match adapter.capture_session_candidates(&capture.context, timeout_s) {
268
- Ok(candidates) => candidates,
269
- Err(error) => {
270
- capture_failures.push(SessionCaptureFailure {
271
- agent_id: capture.agent_id.clone(),
272
- error: error.to_string(),
273
- });
274
- pending.push(capture);
275
- continue;
276
- }
277
- };
278
- candidates_by_agent.insert(capture.agent_id.clone(), candidates);
279
- pending.push(capture);
280
- }
281
-
282
- let pending_ids = pending
283
- .iter()
284
- .map(|item| item.agent_id.clone())
285
- .collect::<BTreeSet<_>>();
286
- let mut claimed = claimed_provider_session_keys(state, agent_map, &pending_ids);
287
- let (assignments, ambiguous_ids) =
288
- allocate_session_candidates(&pending, &candidates_by_agent, &mut claimed);
289
-
290
- let Some(agents) = state.get_mut("agents").and_then(Value::as_object_mut) else {
291
- return Ok(CapturePassReport::default());
292
- };
293
- let mut report = CapturePassReport {
294
- pending: pending.iter().map(|item| item.agent_id.clone()).collect(),
295
- capture_failures,
296
- candidate_count_by_agent: candidates_by_agent
297
- .iter()
298
- .map(|(agent_id, candidates)| (agent_id.clone(), candidates.len()))
299
- .collect(),
300
- ..CapturePassReport::default()
301
- };
302
- for item in pending {
303
- let Some(agent_obj) = agents
304
- .get_mut(&item.agent_id)
305
- .and_then(Value::as_object_mut)
306
- else {
307
- continue;
308
- };
309
- if let Some(candidate) = assignments.get(&item.agent_id) {
310
- if let Some(embedded_agent_id) = candidate
311
- .embedded_agent_id
312
- .as_deref()
313
- .filter(|embedded| *embedded != item.agent_id.as_str())
314
- {
315
- report.identity_mismatches.push(SessionIdentityMismatch {
316
- agent_id: item.agent_id.clone(),
317
- expected_agent_id: item.agent_id.clone(),
318
- embedded_agent_id: embedded_agent_id.to_string(),
319
- session_id: candidate
320
- .captured
321
- .session_id
322
- .as_ref()
323
- .map(|session| session.as_str().to_string()),
324
- rollout_path: candidate
325
- .captured
326
- .rollout_path
327
- .as_ref()
328
- .map(|path| path.as_path().to_string_lossy().to_string()),
329
- spawn_cwd: item.context.spawn_cwd.to_string_lossy().to_string(),
330
- });
331
- if finalize_ambiguous {
332
- agent_obj.insert(
333
- "capture_state".to_string(),
334
- serde_json::json!("session_identity_mismatch"),
335
- );
336
- agent_obj.insert(
337
- "session_identity_mismatch".to_string(),
338
- serde_json::json!({
339
- "expected_agent_id": item.agent_id,
340
- "embedded_agent_id": embedded_agent_id,
341
- }),
342
- );
343
- report.changed = true;
344
- }
345
- continue;
346
- }
347
- // Stage 1 (identity-boundary unified plan, architect direction
348
- // 2026-06-23): defensive expected-id guard. The adapter scanner
349
- // is the primary defence (Claude no longer falls back to same-
350
- // cwd latest when expected_session_id is set), but the allocator
351
- // also goes through a one-to-one global pass that could match a
352
- // wrong candidate if the per-agent list still has stale entries.
353
- // Refuse to write `session_id`/`rollout_path` when the candidate's
354
- // session_id is set AND differs from the pending expected_session_id.
355
- // Capture stays pending; the agent is marked ambiguous so the
356
- // operator sees it.
357
- let mismatch = item
358
- .context
359
- .expected_session_id
360
- .as_ref()
361
- .zip(candidate.captured.session_id.as_ref())
362
- .is_some_and(|(expected, captured)| expected.as_str() != captured.as_str());
363
- if mismatch {
364
- let ambiguity_changed = agent_obj
365
- .get("attribution_ambiguous")
366
- .and_then(Value::as_bool)
367
- != Some(true);
368
- if !finalize_ambiguous || ambiguity_changed {
369
- report.ambiguous.push(AmbiguousSessionCapture {
370
- agent_id: item.agent_id.clone(),
371
- spawn_cwd: item.context.spawn_cwd.to_string_lossy().to_string(),
372
- });
373
- }
374
- if finalize_ambiguous {
375
- if ambiguity_changed {
376
- agent_obj
377
- .insert("attribution_ambiguous".to_string(), serde_json::json!(true));
378
- report.changed = true;
379
- }
380
- // 0.4.6 tuple-atomic contract (audit:93): do NOT write
381
- // `captured_at` for ambiguity diagnostics. `captured_at`
382
- // is part of the authoritative tuple and may only be
383
- // set together with `session_id + rollout_path +
384
- // captured_via`. Overloading it as both capture
385
- // timestamp and ambiguity timestamp created false
386
- // "looks captured" rows. Ambiguity diagnostics live in
387
- // the `attribution_ambiguous` flag + events; persist
388
- // event log for the timestamp.
389
- }
390
- continue;
391
- }
392
- // 0.4.6 tuple-atomic contract: apply_captured_session refuses
393
- // partial candidates (no session_id or no rollout_path). When
394
- // it returns false, the row stays unchanged; capture re-runs
395
- // on the next coordinator tick.
396
- if apply_captured_session(agent_obj, &candidate.captured) {
397
- report.changed = true;
398
- report.assigned.push(item.agent_id);
399
- }
400
- continue;
401
- }
402
- if ambiguous_ids.contains(&item.agent_id) {
403
- let ambiguity_changed = agent_obj
404
- .get("attribution_ambiguous")
405
- .and_then(Value::as_bool)
406
- != Some(true)
407
- || agent_obj.get("capture_state").and_then(Value::as_str)
408
- != Some("attribution_ambiguous");
409
- if !finalize_ambiguous || ambiguity_changed {
410
- report.ambiguous.push(AmbiguousSessionCapture {
411
- agent_id: item.agent_id.clone(),
412
- spawn_cwd: item.context.spawn_cwd.to_string_lossy().to_string(),
413
- });
414
- }
415
- if finalize_ambiguous {
416
- if ambiguity_changed {
417
- agent_obj.insert("attribution_ambiguous".to_string(), serde_json::json!(true));
418
- agent_obj.insert(
419
- "capture_state".to_string(),
420
- serde_json::json!("attribution_ambiguous"),
421
- );
422
- // 0.4.6 tuple-atomic contract: see comment above. Removed
423
- // `captured_at` ambiguity write.
424
- report.changed = true;
425
- }
426
- }
427
- continue;
428
- }
429
- // 0.4.6 Stage 3: transcript-ready handshake. For pending agents that
430
- // are NOT ambiguous and were NOT captured this pass, classify into:
431
- // * `captured` — session_id + rollout_path already on row
432
- // * `transcript_missing` — trigger event has fired (report_result /
433
- // first_send_at / pane_output_advanced) AND elapsed > threshold
434
- // AND zero candidates / no backing
435
- // * `pending_first_turn` — no verified backing yet, still in grace
436
- // The state field surfaces in status/diagnose without changing the
437
- // authoritative tuple contract (we never write session_id without
438
- // backing). Throttled event emission is done by the caller (tick).
439
- let has_session = agent_obj
440
- .get("session_id")
441
- .and_then(Value::as_str)
442
- .is_some_and(|s| !s.is_empty())
443
- && agent_obj
444
- .get("rollout_path")
445
- .and_then(Value::as_str)
446
- .is_some_and(|s| !s.is_empty());
447
- // S1-CAPTURE-001 (0.4.8): a pending_session_id that differs from the
448
- // on-row session_id means a fresh respawn is in flight — the prior
449
- // worker's session_id may still be on the row (concurrent capture race,
450
- // delayed persist, or persist-backfill replay) but the NEW worker has
451
- // not yet been bound. Stamping capture_state=captured here would
452
- // falsely declare the OLD session authoritative for the NEW worker
453
- // pane — the leader/unassigned mis-attribution surfaced in S1-CAPTURE-001
454
- // gate evidence. Only stamp `captured` when session_id agrees with
455
- // _pending_session_id (or _pending is absent, meaning no rebind in
456
- // flight).
457
- let pending_mismatch = match (
458
- agent_obj
459
- .get("_pending_session_id")
460
- .and_then(Value::as_str)
461
- .filter(|s| !s.is_empty()),
462
- agent_obj
463
- .get("session_id")
464
- .and_then(Value::as_str)
465
- .filter(|s| !s.is_empty()),
466
- ) {
467
- (Some(pending), Some(current)) => pending != current,
468
- _ => false,
469
- };
470
- if has_session && !pending_mismatch {
471
- // Captured already — fix state field if drifted.
472
- if agent_obj.get("capture_state").and_then(Value::as_str) != Some("captured") {
473
- agent_obj.insert("capture_state".to_string(), serde_json::json!("captured"));
474
- report.changed = true;
475
- }
476
- continue;
477
- }
478
- let candidate_count = report
479
- .candidate_count_by_agent
480
- .get(&item.agent_id)
481
- .copied()
482
- .unwrap_or(0);
483
- let next_state = classify_pending_capture_state(agent_obj, candidate_count);
484
- let prev_state = agent_obj
485
- .get("capture_state")
486
- .and_then(Value::as_str)
487
- .map(str::to_string);
488
- if prev_state.as_deref() != Some(next_state) {
489
- agent_obj.insert("capture_state".to_string(), serde_json::json!(next_state));
490
- report.changed = true;
491
- if next_state == "transcript_missing" {
492
- report.transcript_missing.push(TranscriptMissing {
493
- agent_id: item.agent_id.clone(),
494
- spawn_cwd: item.context.spawn_cwd.to_string_lossy().to_string(),
495
- spawn_epoch: agent_obj
496
- .get("spawn_epoch")
497
- .and_then(Value::as_u64)
498
- .unwrap_or(0),
499
- expected_session_id: item
500
- .context
501
- .expected_session_id
502
- .as_ref()
503
- .map(|s| s.as_str().to_string()),
504
- candidate_count,
505
- });
506
- }
507
- }
508
- }
509
- Ok(report)
510
- }
511
-
512
- /// 0.4.6 Stage 3: classify a pending agent's capture state into one of:
513
- /// * `transcript_missing` — has had a strong trigger event AND elapsed
514
- /// beyond grace threshold AND still no backing
515
- /// * `pending_first_turn` — still in grace period or no trigger yet
516
- ///
517
- /// Trigger events (CR M2): any of `first_send_at`, `last_result_at`, or a
518
- /// recent `last_pane_output_at` indicates the worker has been interactively
519
- /// used / done something. Without ANY trigger, we stay pending
520
- /// even past the grace window (silent worker is not a failure to capture).
521
- ///
522
- /// Threshold: 30 seconds from spawned_at OR 15 seconds from the first
523
- /// trigger event, whichever is later. This avoids spurious
524
- /// transcript_missing on slow first-paint while catching the
525
- /// release-engineer scenario (report_result fired but no jsonl).
526
- fn classify_pending_capture_state(
527
- agent_obj: &serde_json::Map<String, Value>,
528
- candidate_count: usize,
529
- ) -> &'static str {
530
- // Already-captured agents don't reach here (caller skips). We only
531
- // classify pending agents.
532
- let now = chrono::Utc::now();
533
- let spawned_at = agent_obj
534
- .get("spawned_at")
535
- .and_then(Value::as_str)
536
- .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
537
- .map(|dt| dt.with_timezone(&chrono::Utc));
538
- let elapsed_since_spawn = spawned_at
539
- .map(|t| now.signed_duration_since(t).num_seconds())
540
- .unwrap_or(0);
541
- // Trigger event detection — any strong signal that the worker has
542
- // actually been used. Pre-conditions (CR M2 in architect doc).
543
- let has_trigger = ["first_send_at", "last_result_at", "last_pane_output_at"]
544
- .iter()
545
- .any(|key| {
546
- agent_obj
547
- .get(*key)
548
- .and_then(Value::as_str)
549
- .is_some_and(|s| !s.is_empty())
550
- });
551
- // Earliest trigger timestamp for the secondary threshold.
552
- let earliest_trigger = ["first_send_at", "last_result_at", "last_pane_output_at"]
553
- .iter()
554
- .filter_map(|key| {
555
- agent_obj
556
- .get(*key)
557
- .and_then(Value::as_str)
558
- .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
559
- .map(|dt| dt.with_timezone(&chrono::Utc))
560
- })
561
- .min();
562
- let elapsed_since_trigger = earliest_trigger
563
- .map(|t| now.signed_duration_since(t).num_seconds())
564
- .unwrap_or(0);
565
- const SPAWN_GRACE_SECS: i64 = 30;
566
- const TRIGGER_GRACE_SECS: i64 = 15;
567
- let past_spawn_grace = elapsed_since_spawn >= SPAWN_GRACE_SECS;
568
- let past_trigger_grace = has_trigger && elapsed_since_trigger >= TRIGGER_GRACE_SECS;
569
- let fork_pending_expired = agent_obj.get("capture_state").and_then(Value::as_str)
570
- == Some("pending_context_fork")
571
- && crate::provider::session::transition_pending_context_fork(
572
- has_trigger,
573
- past_spawn_grace && past_trigger_grace,
574
- )
575
- .is_some();
576
- // transcript_missing requires BOTH: a trigger occurred AND we've
577
- // waited past the spawn grace (so we're not blamed for slow startup).
578
- // candidate_count == 0 is the "no backing" signal; non-zero
579
- // candidates that didn't satisfy assignment go through the ambiguous
580
- // path above and don't reach here.
581
- if (fork_pending_expired || has_trigger && past_spawn_grace && past_trigger_grace)
582
- && candidate_count == 0
583
- {
584
- "transcript_missing"
585
- } else if agent_obj.get("capture_state").and_then(Value::as_str) == Some("pending_context_fork")
586
- {
587
- "pending_context_fork"
588
- } else {
589
- "pending_first_turn"
590
- }
591
- }
592
-
593
- /// ---
594
- /// purpose: 列出「provider 本可 resume、但会话事实还不完整」的席位——即捕获通道该继续照看的那批
595
- /// params:
596
- /// state: 只读的 state JSON;无 agents 对象时返回空
597
- /// returns: 按 agent id 升序的清单
598
- /// contract:
599
- /// provides:
600
- /// - name: incomplete_resumable_agent_ids
601
- /// what: 只读判定,不修改 state
602
- /// boundary:
603
- /// - 用全局 get_adapter 取 adapter,不接受注入——测试要替身请走 capture 通道那两个函数
604
- /// - 不区分「从没捕获过」与「捕获过但四元组残缺」,两者都在清单里
605
- /// ---
606
- pub fn incomplete_resumable_agent_ids(state: &Value) -> Vec<String> {
607
- let Some(agents) = state.get("agents").and_then(Value::as_object) else {
608
- return Vec::new();
609
- };
610
- let mut out = agents
611
- .iter()
612
- .filter_map(|(agent_id, agent)| {
613
- if incomplete_resumable_provider(agent, &mut crate::provider::get_adapter).is_some() {
614
- Some(agent_id.clone())
615
- } else {
616
- None
617
- }
618
- })
619
- .collect::<Vec<_>>();
620
- out.sort();
621
- out
622
- }
623
-
624
- /// ---
625
- /// purpose: 会话四元组缺失时的第二条修复通道——倒序翻 event log,用该席位最近一条可信的 session.captured 记录把行补全
626
- /// params:
627
- /// workspace: event log 所在工作区
628
- /// agent_id: 目标席位;事件的 agent_id 或 worker_id 命中即算该席位
629
- /// previous: 修复前的 agent 行
630
- /// adapter: 用于二次确认候选会话确实可 resume
631
- /// auth_mode: 传给 session_is_resumable 的鉴权模式
632
- /// exclude_session_ids: 调用方给出的黑名单(例如刚被判为不可用的会话)
633
- /// returns: Some(补好四元组的新行) 表示找到可用记录;None 表示没找到,或先撞上 discard.session_tombstone 而主动放弃
634
- /// errors: 读 event log 的 Io 错误、以及 session_is_resumable 的 ProviderError
635
- /// contract:
636
- /// provides:
637
- /// - name: recover_resume_session_from_events
638
- /// what: 修复结果一定是完整四元组;captured_at 缺事件 ts 时退到当前时间,captured_via 固定 event_log_repair
639
- /// boundary:
640
- /// - 只读 event log 与 rollout 路径存在性,不扫 provider 存档、不调分配器
641
- /// - 不走分配器的 claimed-key 冲突检查,只看 exclude_session_ids 与 tombstone
642
- /// - rollout_path 存在性用 exists()——对目录型 backing(grok)只要目录在就为真
643
- /// - 遗留 claude/pi worker 行由 adapter 判为不可 resume,修复不会落到它们身上
644
- /// - 修复成功会清掉 attribution_ambiguous 标记
645
- /// ---
646
- pub fn recover_resume_session_from_events(
647
- workspace: &Path,
648
- agent_id: &str,
649
- previous: &Value,
650
- adapter: &dyn ProviderAdapter,
651
- auth_mode: crate::provider::AuthMode,
652
- exclude_session_ids: &BTreeSet<String>,
653
- ) -> Result<Option<Value>, ProviderError> {
654
- let events = crate::event_log::EventLog::new(workspace)
655
- .tail(0)
656
- .map_err(|e| ProviderError::Io(e.to_string()))?;
657
- let current_session = previous
658
- .get("session_id")
659
- .and_then(Value::as_str)
660
- .filter(|session| !session.is_empty());
661
- for event in events.iter().rev() {
662
- if !event_matches_agent(event, agent_id) {
663
- continue;
664
- }
665
- match event.get("event").and_then(Value::as_str) {
666
- Some("discard.session_tombstone") => return Ok(None),
667
- Some("session.captured") => {}
668
- _ => continue,
669
- }
670
- let Some(session_id) = event
671
- .get("session_id")
672
- .and_then(Value::as_str)
673
- .filter(|session| !session.is_empty())
674
- else {
675
- continue;
676
- };
677
- if current_session == Some(session_id) || exclude_session_ids.contains(session_id) {
678
- continue;
679
- }
680
- let Some(rollout_path) = event_rollout_path(event).filter(|path| path.exists()) else {
681
- continue;
682
- };
683
- let session = SessionId::new(session_id.to_string());
684
- if !adapter.session_is_resumable(Some(&session), auth_mode)? {
685
- continue;
686
- }
687
- let mut repaired = previous.clone();
688
- if !repaired.is_object() {
689
- repaired = serde_json::json!({});
690
- }
691
- let Some(obj) = repaired.as_object_mut() else {
692
- continue;
693
- };
694
- // 0.4.6 tuple-atomic contract (audit §Capture 修改清单, line 113):
695
- // repair must yield a COMPLETE tuple. session_id + rollout_path are
696
- // already validated above; ensure captured_at + captured_via are
697
- // also always written (fall back to now() if the event has no ts).
698
- obj.insert("session_id".to_string(), serde_json::json!(session_id));
699
- obj.insert(
700
- "rollout_path".to_string(),
701
- serde_json::json!(rollout_path.to_string_lossy().to_string()),
702
- );
703
- let captured_at = event
704
- .get("ts")
705
- .and_then(Value::as_str)
706
- .filter(|ts| !ts.is_empty())
707
- .map(str::to_string)
708
- .unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
709
- obj.insert("captured_at".to_string(), serde_json::json!(captured_at));
710
- obj.insert(
711
- "captured_via".to_string(),
712
- serde_json::json!("event_log_repair"),
713
- );
714
- if let Some(confidence) = event.get("attribution_confidence").cloned() {
715
- obj.insert("attribution_confidence".to_string(), confidence);
716
- }
717
- obj.remove("attribution_ambiguous");
718
- return Ok(Some(repaired));
719
- }
720
- Ok(None)
721
- }
722
-
723
- fn event_matches_agent(event: &Value, agent_id: &str) -> bool {
724
- ["agent_id", "worker_id"]
725
- .iter()
726
- .any(|key| event.get(*key).and_then(Value::as_str) == Some(agent_id))
727
- }
728
-
729
- fn event_rollout_path(event: &Value) -> Option<PathBuf> {
730
- event
731
- .get("rollout_path")
732
- .or_else(|| event.get("transcript_path"))
733
- .and_then(Value::as_str)
734
- .filter(|path| !path.is_empty())
735
- .map(PathBuf::from)
736
- }
737
-
738
- /// ---
739
- /// purpose: 在「会话不完整」清单上再筛出真正被用过的席位——有 first_send_at 才算交互过
740
- /// params:
741
- /// state: 只读的 state JSON
742
- /// returns: 按 agent id 升序的子集
743
- /// contract:
744
- /// provides:
745
- /// - name: incomplete_interacted_resumable_agent_ids
746
- /// what: incomplete_resumable_agent_ids 的过滤视图,只读
747
- /// boundary:
748
- /// - 交互判据只看 first_send_at 非空,不看 last_result_at / pane 输出
749
- /// - 从没派过活的席位不进清单——沉默席位不算捕获失败
750
- /// ---
751
- pub fn incomplete_interacted_resumable_agent_ids(state: &Value) -> Vec<String> {
752
- let mut out = incomplete_resumable_agent_ids(state)
753
- .into_iter()
754
- .filter(|agent_id| {
755
- state
756
- .get("agents")
757
- .and_then(|agents| agents.get(agent_id))
758
- .and_then(|agent| agent.get("first_send_at"))
759
- .and_then(Value::as_str)
760
- .is_some_and(|value| !value.is_empty())
761
- })
762
- .collect::<Vec<_>>();
763
- out.sort();
764
- out
765
- }
766
-
767
- struct PendingSessionCapture {
768
- agent_id: String,
769
- provider: Provider,
770
- team_key: String,
771
- context: CaptureSessionContext,
772
- }
773
-
774
- fn pending_session_capture<F>(
775
- agent_id: &str,
776
- agent: &Value,
777
- adapter_for: &mut F,
778
- ) -> Option<PendingSessionCapture>
779
- where
780
- F: FnMut(Provider) -> Box<dyn ProviderAdapter>,
781
- {
782
- if agent.get("capture_state").and_then(Value::as_str) == Some("attribution_ambiguous") {
783
- return None;
784
- }
785
- let provider = incomplete_resumable_provider(agent, adapter_for)?;
786
- let spawn_cwd = agent
787
- .get("spawn_cwd")
788
- .and_then(Value::as_str)
789
- .filter(|cwd| !cwd.is_empty())?;
790
- // New cohorts carry a boundary and are filtered fail-closed by the
791
- // canonical scanner. Legacy rows may predate spawned_at; keep their
792
- // boundary absent so they can still use the allocator's identity,
793
- // collision, and unique-candidate guards instead of being skipped.
794
- let spawned_at = agent
795
- .get("spawned_at")
796
- .and_then(Value::as_str)
797
- .filter(|value| !value.is_empty())
798
- .map(str::to_string);
799
- let expected_session_id = agent
800
- .get("_pending_session_id")
801
- .and_then(Value::as_str)
802
- .filter(|value| !value.is_empty())
803
- .map(SessionId::new);
804
- if matches!(provider, Provider::Codex)
805
- && agent.get("capture_state").and_then(Value::as_str) == Some("pending_context_fork")
806
- && expected_session_id.is_none()
807
- {
808
- return None;
809
- }
810
- Some(PendingSessionCapture {
811
- agent_id: agent_id.to_string(),
812
- provider,
813
- team_key: agent
814
- .get("owner_team_id")
815
- .or_else(|| agent.get("team_key"))
816
- .and_then(Value::as_str)
817
- .filter(|s| !s.is_empty())
818
- .unwrap_or("current")
819
- .to_string(),
820
- context: CaptureSessionContext {
821
- agent_id: agent_id.to_string(),
822
- spawn_cwd: PathBuf::from(spawn_cwd),
823
- pane_id: agent
824
- .get("pane_id")
825
- .and_then(Value::as_str)
826
- .filter(|pane| !pane.is_empty())
827
- .map(str::to_string),
828
- pane_pid: agent
829
- .get("pane_pid")
830
- .and_then(Value::as_u64)
831
- .and_then(|pid| u32::try_from(pid).ok()),
832
- spawned_at,
833
- expected_session_id,
834
- provider_projects_root: agent
835
- .get("claude_projects_root")
836
- .and_then(Value::as_str)
837
- .filter(|value| !value.is_empty())
838
- .map(PathBuf::from),
839
- },
840
- })
841
- }
842
-
843
- fn incomplete_resumable_provider<F>(agent: &Value, adapter_for: &mut F) -> Option<Provider>
844
- where
845
- F: FnMut(Provider) -> Box<dyn ProviderAdapter>,
846
- {
847
- if crate::state::projection::agent_explicit_stop(agent)
848
- || agent
849
- .get("status")
850
- .and_then(Value::as_str)
851
- .is_some_and(|status| status != "running")
852
- {
853
- return None;
854
- }
855
- if agent_session_complete(agent) {
856
- return None;
857
- }
858
- let provider = agent
859
- .get("provider")
860
- .and_then(Value::as_str)
861
- .and_then(parse_provider)?;
862
- agent
863
- .get("spawn_cwd")
864
- .and_then(Value::as_str)
865
- .filter(|cwd| !cwd.is_empty())?;
866
- if !adapter_for(provider).caps().resume {
867
- return None;
868
- }
869
- Some(provider)
870
- }
871
-
872
- #[cfg(test)]
873
- mod stopped_capture_tests {
874
- use super::*;
875
-
876
- #[test]
877
- fn explicit_stop_is_checked_before_adapter_or_backing_probes() {
878
- for row in [
879
- serde_json::json!({"status":"stopped","provider":"copilot","spawn_cwd":"/controlled"}),
880
- serde_json::json!({"status":"running","explicit_stop":true,"provider":"copilot","spawn_cwd":"/controlled"}),
881
- serde_json::json!({"status":"running","explicit_stop":"false","provider":"copilot","spawn_cwd":"/controlled"}),
882
- ] {
883
- assert!(incomplete_resumable_provider(&row, &mut |_| panic!("held seat reached adapter lookup")).is_none());
884
- }
885
- let mut calls = 0;
886
- let _ = incomplete_resumable_provider(
887
- &serde_json::json!({"status":"running","explicit_stop":false,"provider":"copilot","spawn_cwd":"/controlled"}),
888
- &mut |provider| { calls += 1; crate::provider::get_adapter(provider) },
889
- );
890
- assert_eq!(calls, 1, "active control must still be eligible for capture");
891
- }
892
- }
893
-
894
- fn agent_session_complete(agent: &Value) -> bool {
895
- // RM-039-SESS-001 step 1 (architect verdict 2026-06-22): historically
896
- // this returned true the moment `rollout_path` was non-empty — even when
897
- // the file no longer existed on disk. That created a "stale-positive"
898
- // capture tuple: the worker had a session_id + a stored rollout_path,
899
- // but the provider had rotated/garbage-collected the actual transcript
900
- // file. `pending_session_capture` skipped agents whose
901
- // `agent_session_complete()` was true, so the runtime never recaptured
902
- // the now-broken backing, and downstream consumers saw the stale tuple
903
- // as authoritative.
904
- //
905
- // Fix: a non-empty `rollout_path` only counts as complete when the path
906
- // actually exists. session_id remains a required non-empty check
907
- // (architect directive: "Keep session_id non-empty as required; do not
908
- // infer context from event log alone unless the referenced transcript
909
- // path exists.").
910
- //
911
- // Blocker-2 Layer-1 (prerelease 0.4.0, architect bugs-prerelease-blockers.md §139):
912
- // existence alone is not enough — a small Claude session-metadata JSON
913
- // (~/.claude/sessions/<pid>.json, ~300-400 bytes, sessionId only, no
914
- // assistant/user records) used to satisfy this and prevent recapture of
915
- // the real .claude/projects/<cwd>/<sid>.jsonl transcript. For
916
- // Claude/ClaudeCode rollout paths, additionally require a recognizable
917
- // transcript lifecycle record (an assistant or user record). Other
918
- // providers keep existence-only semantics (codex 不可改项).
919
- let session_id_ok = agent
920
- .get("session_id")
921
- .and_then(Value::as_str)
922
- .is_some_and(|session| !session.is_empty());
923
- if !session_id_ok {
924
- return false;
925
- }
926
- // S1-CAPTURE-001 (0.4.8, CR M3 provider-agnostic): pending mismatch guard.
927
- // When fresh-start has written a new `_pending_session_id` but the old
928
- // authoritative `session_id` is still present and differs, the tuple is
929
- // STALE — the new process has a different session that has not been
930
- // captured yet. Returning true here would let capture skip this agent
931
- // and keep treating the old transcript as authoritative (the gate's
932
- // observed mis-attribution). Force re-capture by reporting incomplete.
933
- // The fresh-tuple clear in mark_agent_started (lifecycle/restart/agent.rs)
934
- // is the primary fix; this guard handles historical poison state where
935
- // both fields already coexist from a prior version.
936
- let pending = agent
937
- .get("_pending_session_id")
938
- .and_then(Value::as_str)
939
- .filter(|s| !s.is_empty());
940
- let current = agent
941
- .get("session_id")
942
- .and_then(Value::as_str)
943
- .filter(|s| !s.is_empty());
944
- if let (Some(pending), Some(current)) = (pending, current) {
945
- if pending != current {
946
- return false;
947
- }
948
- }
949
- let rollout_path = match agent
950
- .get("rollout_path")
951
- .and_then(Value::as_str)
952
- .filter(|path| !path.is_empty())
953
- {
954
- Some(path) => path,
955
- None => return false,
956
- };
957
- // 0.4.6 tuple-atomic contract (audit §Capture 修改清单, line 110):
958
- // a "complete" agent session requires the FULL authoritative tuple —
959
- // session_id + rollout_path + captured_at + captured_via. Without these
960
- // last two, a row is a partial tuple and capture must re-run.
961
- let captured_at_ok = agent
962
- .get("captured_at")
963
- .and_then(Value::as_str)
964
- .is_some_and(|ts| !ts.is_empty());
965
- let captured_via_ok = agent
966
- .get("captured_via")
967
- .and_then(Value::as_str)
968
- .is_some_and(|via| !via.is_empty());
969
- if !captured_at_ok || !captured_via_ok {
970
- return false;
971
- }
972
- let path = std::path::Path::new(rollout_path);
973
- if !path.exists() {
974
- return false;
975
- }
976
- let provider_wire = agent.get("provider").and_then(Value::as_str).unwrap_or("");
977
- if parse_provider(provider_wire).is_some_and(is_claude_family) {
978
- return claude_rollout_has_lifecycle_records(path);
979
- }
980
- true
981
- }
982
-
983
- /// Blocker-2 Layer-1 (prerelease 0.4.0): a Claude rollout file qualifies as
984
- /// activity backing only when it contains at least one recognizable transcript
985
- /// lifecycle record (top-level `type:"assistant"` or `type:"user"`). The
986
- /// ~/.claude/sessions/<pid>.json metadata file has neither, so this returns
987
- /// false for it and the runtime recaptures via the .claude/projects/<cwd>/
988
- /// scan in adapter.rs. Bounded read so a large transcript is not slurped.
989
- fn claude_rollout_has_lifecycle_records(path: &std::path::Path) -> bool {
990
- use std::io::Read;
991
- const MAX_BYTES: u64 = 65_536;
992
- let Ok(file) = std::fs::File::open(path) else {
993
- return false;
994
- };
995
- let mut bytes = Vec::new();
996
- if file.take(MAX_BYTES).read_to_end(&mut bytes).is_err() {
997
- return false;
998
- }
999
- let text = String::from_utf8_lossy(&bytes);
1000
- for line in text.lines() {
1001
- let trimmed = line.trim();
1002
- if trimmed.is_empty() {
1003
- continue;
1004
- }
1005
- let Ok(value) = serde_json::from_str::<serde_json::Value>(trimmed) else {
1006
- continue;
1007
- };
1008
- let kind = value.get("type").and_then(Value::as_str).unwrap_or("");
1009
- if matches!(kind, "assistant" | "user") {
1010
- return true;
1011
- }
1012
- }
1013
- false
1014
- }
1015
-
1016
- fn allocate_session_candidates(
1017
- pending: &[PendingSessionCapture],
1018
- candidates_by_agent: &BTreeMap<String, Vec<CapturedSessionCandidate>>,
1019
- claimed: &mut BTreeSet<String>,
1020
- ) -> (BTreeMap<String, CapturedSessionCandidate>, BTreeSet<String>) {
1021
- let mut assignments = BTreeMap::new();
1022
- let mut ambiguous = BTreeSet::new();
1023
-
1024
- // Stage 1 amendment (architect direction 2026-06-23, S1-CAPTURE-002 fix):
1025
- // ExpectedSessionId pre-pass. For each pending agent that carries an
1026
- // `_pending_session_id`, the strongest possible binding is the candidate
1027
- // whose `session_id` exactly matches that expected id. Run this BEFORE
1028
- // the existing PositiveAgentId / PathAgentId / global one-to-one passes,
1029
- // because the global one-to-one pass uses
1030
- // `remaining_agents.zip(candidates.into_values())` (BTreeMap sorted by
1031
- // candidate-key, not by agent ownership) and can produce CROSS
1032
- // assignments (claude-a → claude-b's transcript and vice versa) when two
1033
- // pending agents both have expected ids but no PositiveAgentId/PathAgentId
1034
- // hint — those would be rejected by the mismatch guard at apply time,
1035
- // leaving both agents `attribution_ambiguous` instead of correctly
1036
- // bound. With this pre-pass the global one-to-one only ever sees agents
1037
- // that have NO expected id (or whose expected candidate is unavailable
1038
- // / collides), and the cross-assignment hazard is eliminated.
1039
- for item in pending {
1040
- let Some(expected) = item.context.expected_session_id.as_ref() else {
1041
- continue;
1042
- };
1043
- let Some(agent_candidates) = candidates_by_agent.get(&item.agent_id) else {
1044
- continue;
1045
- };
1046
- let exact_matches: Vec<&CapturedSessionCandidate> = agent_candidates
1047
- .iter()
1048
- .filter(|candidate| {
1049
- candidate
1050
- .captured
1051
- .session_id
1052
- .as_ref()
1053
- .is_some_and(|sid| sid.as_str() == expected.as_str())
1054
- })
1055
- .filter(|candidate| !candidate_keys_collide(item, candidate, claimed))
1056
- .collect();
1057
- // Uniqueness requirement: only assign when the expected id maps to
1058
- // exactly one available candidate. Multiple matches or a colliding
1059
- // single match leave the agent for the ambiguity path below.
1060
- if exact_matches.len() == 1 {
1061
- let candidate = exact_matches[0].clone();
1062
- claimed.extend(captured_provider_session_keys(item, &candidate.captured));
1063
- assignments.insert(item.agent_id.clone(), candidate);
1064
- }
1065
- }
1066
-
1067
- for item in pending {
1068
- if assignments.contains_key(&item.agent_id) {
1069
- continue;
1070
- }
1071
- if let Some(candidate) = unique_available_candidate(
1072
- candidates_by_agent.get(&item.agent_id),
1073
- claimed,
1074
- CandidateMatchKind::PositiveAgentId,
1075
- item,
1076
- ) {
1077
- claimed.extend(captured_provider_session_keys(item, &candidate.captured));
1078
- assignments.insert(item.agent_id.clone(), candidate);
1079
- }
1080
- }
1081
- for item in pending {
1082
- if assignments.contains_key(&item.agent_id) {
1083
- continue;
1084
- }
1085
- if let Some(candidate) = unique_available_candidate(
1086
- candidates_by_agent.get(&item.agent_id),
1087
- claimed,
1088
- CandidateMatchKind::PathAgentId,
1089
- item,
1090
- ) {
1091
- claimed.extend(captured_provider_session_keys(item, &candidate.captured));
1092
- assignments.insert(item.agent_id.clone(), candidate);
1093
- }
1094
- }
1095
- allocate_global_one_to_one(pending, candidates_by_agent, claimed, &mut assignments);
1096
- for item in pending {
1097
- if assignments.contains_key(&item.agent_id) {
1098
- continue;
1099
- }
1100
- // P0 (lane-046-capture-gap): Claude without a framework expected
1101
- // session id must not accept the weak `Any` fallback.
1102
- if provider_no_expected_requires_positive_attribution(item) {
1103
- if candidates_by_agent
1104
- .get(&item.agent_id)
1105
- .is_some_and(|candidates| !candidates.is_empty())
1106
- {
1107
- ambiguous.insert(item.agent_id.clone());
1108
- }
1109
- continue;
1110
- }
1111
- // 0.5.x Codex cross-bind: a single provider-specific candidate may be
1112
- // captured when it has no conflicting embedded identity, but a same-cwd
1113
- // multi-candidate set must remain ambiguous instead of using weak
1114
- // sorted zip / Any attribution.
1115
- if codex_no_expected(item)
1116
- && candidates_by_agent
1117
- .get(&item.agent_id)
1118
- .is_some_and(|candidates| candidates.len() > 1)
1119
- {
1120
- ambiguous.insert(item.agent_id.clone());
1121
- continue;
1122
- }
1123
- match unique_available_candidate(
1124
- candidates_by_agent.get(&item.agent_id),
1125
- claimed,
1126
- CandidateMatchKind::Any,
1127
- item,
1128
- ) {
1129
- Some(candidate)
1130
- if codex_no_expected(item)
1131
- && candidate_is_visible_to_pending_peer(
1132
- item,
1133
- &candidate,
1134
- pending,
1135
- candidates_by_agent,
1136
- ) =>
1137
- {
1138
- ambiguous.insert(item.agent_id.clone());
1139
- }
1140
- Some(candidate) => {
1141
- claimed.extend(captured_provider_session_keys(item, &candidate.captured));
1142
- assignments.insert(item.agent_id.clone(), candidate);
1143
- }
1144
- None => {
1145
- if candidates_by_agent
1146
- .get(&item.agent_id)
1147
- .is_some_and(|candidates| !candidates.is_empty())
1148
- {
1149
- ambiguous.insert(item.agent_id.clone());
1150
- }
1151
- }
1152
- }
1153
- }
1154
- (assignments, ambiguous)
1155
- }
1156
-
1157
- fn candidate_is_visible_to_pending_peer(
1158
- owner: &PendingSessionCapture,
1159
- candidate: &CapturedSessionCandidate,
1160
- pending: &[PendingSessionCapture],
1161
- candidates_by_agent: &BTreeMap<String, Vec<CapturedSessionCandidate>>,
1162
- ) -> bool {
1163
- let owner_keys = captured_provider_session_keys(owner, &candidate.captured);
1164
- pending.iter().any(|peer| {
1165
- peer.agent_id != owner.agent_id
1166
- && peer.provider == owner.provider
1167
- && peer.team_key == owner.team_key
1168
- && candidates_by_agent
1169
- .get(&peer.agent_id)
1170
- .is_some_and(|candidates| {
1171
- candidates.iter().any(|peer_candidate| {
1172
- !owner_keys.is_disjoint(&captured_provider_session_keys(
1173
- peer,
1174
- &peer_candidate.captured,
1175
- ))
1176
- })
1177
- })
1178
- })
1179
- }
1180
-
1181
- fn allocate_global_one_to_one(
1182
- pending: &[PendingSessionCapture],
1183
- candidates_by_agent: &BTreeMap<String, Vec<CapturedSessionCandidate>>,
1184
- claimed: &mut BTreeSet<String>,
1185
- assignments: &mut BTreeMap<String, CapturedSessionCandidate>,
1186
- ) {
1187
- // P0 (lane-046-capture-gap + 0.5.x Codex cross-bind): exclude
1188
- // no-expected agents from the global one-to-one weak allocator. They must
1189
- // use PositiveAgentId, PathAgentId, or the per-agent unique-candidate path
1190
- // only.
1191
- let remaining_agents = pending
1192
- .iter()
1193
- .filter(|item| !assignments.contains_key(&item.agent_id))
1194
- .filter(|item| !provider_no_expected_disables_global_one_to_one(item))
1195
- .map(|item| item.agent_id.clone())
1196
- .collect::<Vec<_>>();
1197
- if remaining_agents.is_empty() {
1198
- return;
1199
- }
1200
- let mut candidates = BTreeMap::new();
1201
- for agent_id in &remaining_agents {
1202
- let Some(agent_candidates) = candidates_by_agent.get(agent_id) else {
1203
- return;
1204
- };
1205
- let Some(owner) = pending.iter().find(|item| item.agent_id == *agent_id) else {
1206
- continue;
1207
- };
1208
- for candidate in agent_candidates {
1209
- if candidate_keys_collide(owner, candidate, claimed) {
1210
- continue;
1211
- }
1212
- let key = candidate_key(owner, candidate);
1213
- if key.is_empty() {
1214
- continue;
1215
- }
1216
- candidates.entry(key).or_insert_with(|| candidate.clone());
1217
- }
1218
- }
1219
- if candidates.len() != remaining_agents.len() {
1220
- return;
1221
- }
1222
- for (agent_id, candidate) in remaining_agents.into_iter().zip(candidates.into_values()) {
1223
- if let Some(item) = pending.iter().find(|item| item.agent_id == agent_id) {
1224
- claimed.extend(captured_provider_session_keys(item, &candidate.captured));
1225
- }
1226
- assignments.insert(agent_id, candidate);
1227
- }
1228
- }
1229
-
1230
- fn provider_no_expected_requires_positive_attribution(item: &PendingSessionCapture) -> bool {
1231
- matches!(item.provider, Provider::Claude | Provider::ClaudeCode)
1232
- && item.context.expected_session_id.is_none()
1233
- }
1234
-
1235
- fn provider_no_expected_disables_global_one_to_one(item: &PendingSessionCapture) -> bool {
1236
- matches!(
1237
- item.provider,
1238
- Provider::Codex | Provider::Claude | Provider::ClaudeCode
1239
- ) && item.context.expected_session_id.is_none()
1240
- }
1241
-
1242
- fn codex_no_expected(item: &PendingSessionCapture) -> bool {
1243
- matches!(item.provider, Provider::Codex) && item.context.expected_session_id.is_none()
1244
- }
1245
-
1246
- fn unique_available_candidate(
1247
- candidates: Option<&Vec<CapturedSessionCandidate>>,
1248
- claimed: &BTreeSet<String>,
1249
- match_kind: CandidateMatchKind,
1250
- owner: &PendingSessionCapture,
1251
- ) -> Option<CapturedSessionCandidate> {
1252
- let matches = candidates?
1253
- .iter()
1254
- .filter(|candidate| match match_kind {
1255
- CandidateMatchKind::PositiveAgentId => candidate.positive_agent_id_match,
1256
- CandidateMatchKind::PathAgentId => candidate.agent_path_match,
1257
- CandidateMatchKind::Any => true,
1258
- })
1259
- .filter(|candidate| !candidate_keys_collide(owner, candidate, claimed))
1260
- .cloned()
1261
- .collect::<Vec<_>>();
1262
- if matches.len() == 1 {
1263
- matches.into_iter().next()
1264
- } else {
1265
- None
1266
- }
1267
- }
1268
-
1269
- #[derive(Clone, Copy)]
1270
- enum CandidateMatchKind {
1271
- PositiveAgentId,
1272
- PathAgentId,
1273
- Any,
1274
- }
1275
-
1276
- fn candidate_keys_collide(
1277
- owner: &PendingSessionCapture,
1278
- candidate: &CapturedSessionCandidate,
1279
- claimed: &BTreeSet<String>,
1280
- ) -> bool {
1281
- captured_provider_session_keys(owner, &candidate.captured)
1282
- .iter()
1283
- .any(|key| claimed.contains(key))
1284
- }
1285
-
1286
- fn candidate_key(owner: &PendingSessionCapture, candidate: &CapturedSessionCandidate) -> String {
1287
- captured_provider_session_keys(owner, &candidate.captured)
1288
- .into_iter()
1289
- .collect::<Vec<_>>()
1290
- .join("|")
1291
- }
1292
-
1293
- /// 0.4.6 tuple-atomic contract (audit §Capture 修改清单, line 111): writes
1294
- /// the authoritative session tuple if and only if the candidate carries
1295
- /// BOTH `session_id` and `rollout_path`. A partial candidate (e.g.
1296
- /// scanner returned ambiguous attribution with no session_id) MUST NOT
1297
- /// stamp `captured_at` / `captured_via` onto the row, because that
1298
- /// produces a partial tuple that downstream readers treat as authority.
1299
- /// Returns true iff the full tuple was written.
1300
- fn apply_captured_session(
1301
- agent_obj: &mut serde_json::Map<String, Value>,
1302
- captured: &CapturedSession,
1303
- ) -> bool {
1304
- let Some(session_id) = captured.session_id.as_ref() else {
1305
- return false;
1306
- };
1307
- let Some(rollout_path) = captured.rollout_path.as_ref() else {
1308
- return false;
1309
- };
1310
- agent_obj.insert(
1311
- "session_id".to_string(),
1312
- serde_json::json!(session_id.as_str()),
1313
- );
1314
- agent_obj.insert(
1315
- "rollout_path".to_string(),
1316
- serde_json::json!(rollout_path.as_path().to_string_lossy()),
1317
- );
1318
- agent_obj.insert(
1319
- "captured_at".to_string(),
1320
- serde_json::json!(chrono::Utc::now().to_rfc3339()),
1321
- );
1322
- agent_obj.insert(
1323
- "captured_via".to_string(),
1324
- serde_json::to_value(captured.captured_via).unwrap_or(Value::Null),
1325
- );
1326
- agent_obj.insert(
1327
- "attribution_confidence".to_string(),
1328
- serde_json::to_value(captured.attribution_confidence).unwrap_or(Value::Null),
1329
- );
1330
- agent_obj.remove("attribution_ambiguous");
1331
- // S1-CAPTURE-001 (0.4.8): after writing the authoritative tuple, the
1332
- // `_pending_session_id` placeholder is no longer needed — remove it so
1333
- // future reads don't trip the pending-mismatch guard in
1334
- // agent_session_complete. Also stamp capture_state="captured" for
1335
- // diagnose/status observability.
1336
- agent_obj.remove("_pending_session_id");
1337
- agent_obj.insert("capture_state".to_string(), serde_json::json!("captured"));
1338
- true
1339
- }
1340
-
1341
- fn claimed_provider_session_keys(
1342
- state: &Value,
1343
- agents: &serde_json::Map<String, Value>,
1344
- pending_ids: &BTreeSet<String>,
1345
- ) -> BTreeSet<String> {
1346
- let mut keys = BTreeSet::new();
1347
- let team_key = crate::state::projection::team_state_key(state);
1348
- // 1. Every other already-known worker session. The pending row itself is
1349
- // excluded so an incomplete tuple can still be repaired in place.
1350
- for (agent_id, agent) in agents {
1351
- if pending_ids.contains(agent_id) {
1352
- continue;
1353
- }
1354
- push_provider_session_keys(&mut keys, &team_key, agent_id, agent);
1355
- }
1356
- if let Some(teams) = state.get("teams").and_then(Value::as_object) {
1357
- for (nested_team_key, team_state) in teams {
1358
- if let Some(nested_agents) = team_state.get("agents").and_then(Value::as_object) {
1359
- for (agent_id, agent) in nested_agents {
1360
- if nested_team_key == &team_key && pending_ids.contains(agent_id) {
1361
- continue;
1362
- }
1363
- push_provider_session_keys(&mut keys, nested_team_key, agent_id, agent);
1364
- }
1365
- }
1366
- }
1367
- }
1368
- // 2. P0 (lane-046-capture-gap): leader anchor sessions. The leader's
1369
- // own provider transcript must never be attributed to a worker. Scan
1370
- // state.leader_receiver, state.team_owner, and the same fields under
1371
- // state.teams.<key>. Cover all known provider session field names so
1372
- // a present transcript path/id excludes that session from worker
1373
- // allocation.
1374
- push_leader_provider_session_keys(&mut keys, state);
1375
- if let Some(teams) = state.get("teams").and_then(Value::as_object) {
1376
- for team_state in teams.values() {
1377
- push_leader_provider_session_keys(&mut keys, team_state);
1378
- }
1379
- }
1380
- keys
1381
- }
1382
-
1383
- fn push_provider_session_keys(
1384
- keys: &mut BTreeSet<String>,
1385
- fallback_team_key: &str,
1386
- fallback_agent_id: &str,
1387
- value: &Value,
1388
- ) {
1389
- let provider = value
1390
- .get("provider")
1391
- .and_then(Value::as_str)
1392
- .and_then(parse_provider)
1393
- .unwrap_or(Provider::Fake);
1394
- let team_key = value
1395
- .get("owner_team_id")
1396
- .or_else(|| value.get("team_key"))
1397
- .and_then(Value::as_str)
1398
- .filter(|s| !s.is_empty())
1399
- .unwrap_or(fallback_team_key);
1400
- let agent_id = value
1401
- .get("agent_id")
1402
- .and_then(Value::as_str)
1403
- .filter(|s| !s.is_empty())
1404
- .unwrap_or(fallback_agent_id);
1405
- for field in ["session_id", "provider_session_id"] {
1406
- if let Some(session_id) = value
1407
- .get(field)
1408
- .and_then(Value::as_str)
1409
- .filter(|s| !s.is_empty())
1410
- {
1411
- if let Some(key) = SessionAttributionKey::new(provider, team_key, agent_id, session_id)
1412
- {
1413
- keys.insert(session_attribution_key_string(&key));
1414
- }
1415
- keys.insert(global_session_attribution_key_string(session_id));
1416
- }
1417
- }
1418
- // Copilot stores every session in one shared session-store.db. Session id
1419
- // is the attribution identity; treating the shared DB path as globally
1420
- // exclusive makes an exact expected id collide with every sibling.
1421
- if matches!(provider, Provider::Copilot) {
1422
- return;
1423
- }
1424
- for field in ["rollout_path", "transcript_path"] {
1425
- if let Some(path) = value
1426
- .get(field)
1427
- .and_then(Value::as_str)
1428
- .filter(|s| !s.is_empty())
1429
- {
1430
- keys.insert(transcript_attribution_key_string(
1431
- provider, team_key, agent_id, path,
1432
- ));
1433
- keys.insert(global_transcript_attribution_key_string(path));
1434
- }
1435
- }
1436
- }
1437
-
1438
- fn push_leader_provider_session_keys(keys: &mut BTreeSet<String>, scope: &Value) {
1439
- for anchor in ["leader_receiver", "team_owner"] {
1440
- if let Some(node) = scope.get(anchor) {
1441
- push_provider_session_keys(keys, "leader", "leader", node);
1442
- }
1443
- }
1444
- }
1445
-
1446
- fn captured_provider_session_keys(
1447
- owner: &PendingSessionCapture,
1448
- captured: &CapturedSession,
1449
- ) -> BTreeSet<String> {
1450
- let mut keys = BTreeSet::new();
1451
- let team_key = owner.team_key.as_str();
1452
- if let Some(session_id) = &captured.session_id {
1453
- if let Some(key) = SessionAttributionKey::new(
1454
- owner.provider,
1455
- team_key,
1456
- owner.agent_id.as_str(),
1457
- session_id.as_str(),
1458
- ) {
1459
- keys.insert(session_attribution_key_string(&key));
1460
- }
1461
- keys.insert(global_session_attribution_key_string(session_id.as_str()));
1462
- }
1463
- if !matches!(owner.provider, Provider::Copilot) {
1464
- if let Some(rollout_path) = &captured.rollout_path {
1465
- let path = rollout_path.as_path().to_string_lossy();
1466
- keys.insert(transcript_attribution_key_string(
1467
- owner.provider,
1468
- team_key,
1469
- owner.agent_id.as_str(),
1470
- &path,
1471
- ));
1472
- keys.insert(global_transcript_attribution_key_string(&path));
1473
- }
1474
- }
1475
- keys
1476
- }
1477
-
1478
- fn session_attribution_key_string(key: &SessionAttributionKey) -> String {
1479
- format!(
1480
- "SessionAttributionKey(provider={:?},team={},agent={},session={})",
1481
- key.provider(),
1482
- key.team_key(),
1483
- key.agent_id(),
1484
- key.session_id()
1485
- )
1486
- }
1487
-
1488
- fn transcript_attribution_key_string(
1489
- provider: Provider,
1490
- team_key: &str,
1491
- agent_id: &str,
1492
- path: &str,
1493
- ) -> String {
1494
- format!("TranscriptAttributionKey(provider={provider:?},team={team_key},agent={agent_id},path={path})")
1495
- }
1496
-
1497
- fn global_session_attribution_key_string(session_id: &str) -> String {
1498
- format!("GlobalSessionAttributionKey(session={session_id})")
1499
- }
1500
-
1501
- fn global_transcript_attribution_key_string(path: &str) -> String {
1502
- format!("GlobalTranscriptAttributionKey(path={path})")
1503
- }
1504
-
1505
- #[cfg(test)]
1506
- pub(crate) mod test_support {
1507
- use super::*;
1508
- use std::sync::Arc;
1509
-
1510
- #[derive(Clone)]
1511
- pub(crate) struct CaptureCandidatesAdapter {
1512
- provider: Provider,
1513
- fail_agent_id: Option<String>,
1514
- error: String,
1515
- /// Stage 1 amendment test support (architect direction 2026-06-23):
1516
- /// per-agent candidate map. When set, the adapter returns the mapped
1517
- /// candidates for `context.agent_id` instead of an empty list. Lets
1518
- /// the allocator-level test inject expected-id candidates for two
1519
- /// pending agents and observe cross-assignment regressions.
1520
- candidates_by_agent: Option<Arc<BTreeMap<String, Vec<CapturedSessionCandidate>>>>,
1521
- }
1522
-
1523
- impl CaptureCandidatesAdapter {
1524
- /// ---
1525
- /// purpose: 造一个可控的测试替身 adapter:指定 provider,并可让某个席位的候选扫描必定失败
1526
- /// params:
1527
- /// provider: 替身自称的 provider
1528
- /// fail_agent_id: 该席位的 capture_session_candidates 返回错误;None 表示都不失败
1529
- /// error: 失败时携带的错误文本
1530
- /// returns: 未挂候选表的替身;候选表另经 with_candidates 注入
1531
- /// contract:
1532
- /// provides:
1533
- /// - name: new
1534
- /// what: 纯构造,无 I/O
1535
- /// boundary:
1536
- /// - 仅 cfg(test) 存在,不进产品二进制
1537
- /// ---
1538
- pub(crate) fn new(provider: Provider, fail_agent_id: Option<&str>, error: &str) -> Self {
1539
- Self {
1540
- provider,
1541
- fail_agent_id: fail_agent_id.map(str::to_string),
1542
- error: error.to_string(),
1543
- candidates_by_agent: None,
1544
- }
1545
- }
1546
-
1547
- /// ---
1548
- /// purpose: 给测试替身挂一张 agent_id → 候选列表的表,用来构造分配器层面的交叉归属回归
1549
- /// params:
1550
- /// candidates_by_agent: 按席位 id 索引的候选;未列入的席位仍返回空列表
1551
- /// returns: 挂好表的自身(builder 风格,消费 self)
1552
- /// contract:
1553
- /// provides:
1554
- /// - name: with_candidates
1555
- /// what: 只改替身内部状态,不触发任何扫描
1556
- /// boundary:
1557
- /// - 仅 cfg(test) 存在,不进产品二进制
1558
- /// ---
1559
- pub(crate) fn with_candidates(
1560
- mut self,
1561
- candidates_by_agent: BTreeMap<String, Vec<CapturedSessionCandidate>>,
1562
- ) -> Self {
1563
- self.candidates_by_agent = Some(Arc::new(candidates_by_agent));
1564
- self
1565
- }
1566
- }
1567
-
1568
- impl ProviderAdapter for CaptureCandidatesAdapter {
1569
- fn provider(&self) -> Provider {
1570
- self.provider
1571
- }
1572
-
1573
- fn caps(&self) -> crate::provider::ProviderCaps {
1574
- crate::provider::ProviderCaps {
1575
- resume: true,
1576
- fork: false,
1577
- native_mcp_config: false,
1578
- writes_global_settings: false,
1579
- }
1580
- }
1581
-
1582
- fn is_installed(&self) -> bool {
1583
- true
1584
- }
1585
-
1586
- fn version(&self) -> Result<String, ProviderError> {
1587
- Ok("test".to_string())
1588
- }
1589
-
1590
- fn auth_hint(
1591
- &self,
1592
- _auth_mode: crate::provider::AuthMode,
1593
- ) -> crate::provider::AuthHintStatus {
1594
- crate::provider::AuthHintStatus::Unknown
1595
- }
1596
-
1597
- fn build_command(
1598
- &self,
1599
- _auth_mode: crate::provider::AuthMode,
1600
- _mcp_config: Option<&crate::provider::McpConfig>,
1601
- _system_prompt: Option<&str>,
1602
- _model: Option<&str>,
1603
- ) -> Result<Vec<String>, ProviderError> {
1604
- Err(ProviderError::CapabilityUnsupported(
1605
- "test adapter".to_string(),
1606
- ))
1607
- }
1608
-
1609
- fn build_command_with_permissions(
1610
- &self,
1611
- _auth_mode: crate::provider::AuthMode,
1612
- _mcp_config: Option<&crate::provider::McpConfig>,
1613
- _system_prompt: Option<&str>,
1614
- _model: Option<&str>,
1615
- _dangerously_skip_permissions: bool,
1616
- ) -> Result<Vec<String>, ProviderError> {
1617
- Err(ProviderError::CapabilityUnsupported(
1618
- "test adapter".to_string(),
1619
- ))
1620
- }
1621
-
1622
- fn capture_session_id(
1623
- &self,
1624
- _agent_id: &str,
1625
- _spawn_cwd: &std::path::Path,
1626
- _timeout_s: u64,
1627
- ) -> Result<Option<CapturedSession>, ProviderError> {
1628
- Err(ProviderError::CapabilityUnsupported(
1629
- "test adapter".to_string(),
1630
- ))
1631
- }
1632
-
1633
- fn capture_session_candidates(
1634
- &self,
1635
- context: &CaptureSessionContext,
1636
- _timeout_s: u64,
1637
- ) -> Result<Vec<CapturedSessionCandidate>, ProviderError> {
1638
- if self.fail_agent_id.as_deref() == Some(context.agent_id.as_str()) {
1639
- return Err(ProviderError::Io(self.error.clone()));
1640
- }
1641
- if let Some(map) = self.candidates_by_agent.as_ref() {
1642
- if let Some(candidates) = map.get(&context.agent_id) {
1643
- return Ok(candidates.clone());
1644
- }
1645
- }
1646
- Ok(Vec::new())
1647
- }
1648
-
1649
- fn recover_session_id(
1650
- &self,
1651
- _agent_id: &str,
1652
- _spawn_cwd: &std::path::Path,
1653
- ) -> Result<Option<SessionId>, ProviderError> {
1654
- Err(ProviderError::CapabilityUnsupported(
1655
- "test adapter".to_string(),
1656
- ))
1657
- }
1658
-
1659
- fn session_is_resumable(
1660
- &self,
1661
- _session_id: Option<&SessionId>,
1662
- _auth_mode: crate::provider::AuthMode,
1663
- ) -> Result<bool, ProviderError> {
1664
- Ok(true)
1665
- }
1666
-
1667
- fn build_resume_command(
1668
- &self,
1669
- _session_id: Option<&SessionId>,
1670
- _auth_mode: crate::provider::AuthMode,
1671
- _mcp_config: Option<&crate::provider::McpConfig>,
1672
- ) -> Result<Vec<String>, ProviderError> {
1673
- Err(ProviderError::CapabilityUnsupported(
1674
- "test adapter".to_string(),
1675
- ))
1676
- }
1677
-
1678
- fn build_resume_command_with_context(
1679
- &self,
1680
- _session_id: Option<&SessionId>,
1681
- _auth_mode: crate::provider::AuthMode,
1682
- _mcp_config: Option<&crate::provider::McpConfig>,
1683
- _system_prompt: Option<&str>,
1684
- _model: Option<&str>,
1685
- _dangerously_skip_permissions: bool,
1686
- ) -> Result<Vec<String>, ProviderError> {
1687
- Err(ProviderError::CapabilityUnsupported(
1688
- "test adapter".to_string(),
1689
- ))
1690
- }
1691
-
1692
- fn fork(
1693
- &self,
1694
- _session_id: Option<&SessionId>,
1695
- _auth_mode: crate::provider::AuthMode,
1696
- _mcp_config: Option<&crate::provider::McpConfig>,
1697
- ) -> Result<Vec<String>, ProviderError> {
1698
- Err(ProviderError::CapabilityUnsupported(
1699
- "test adapter".to_string(),
1700
- ))
1701
- }
1702
-
1703
- fn fork_with_context(
1704
- &self,
1705
- _session_id: Option<&SessionId>,
1706
- _auth_mode: crate::provider::AuthMode,
1707
- _mcp_config: Option<&crate::provider::McpConfig>,
1708
- _system_prompt: Option<&str>,
1709
- _model: Option<&str>,
1710
- _dangerously_skip_permissions: bool,
1711
- ) -> Result<Vec<String>, ProviderError> {
1712
- Err(ProviderError::CapabilityUnsupported(
1713
- "test adapter".to_string(),
1714
- ))
1715
- }
1716
-
1717
- fn mcp_config(
1718
- &self,
1719
- _auth_mode: crate::provider::AuthMode,
1720
- ) -> Result<crate::provider::McpConfig, ProviderError> {
1721
- Err(ProviderError::CapabilityUnsupported(
1722
- "test adapter".to_string(),
1723
- ))
1724
- }
1725
-
1726
- fn install_mcp(&self, _config: &crate::provider::McpConfig) -> Result<(), ProviderError> {
1727
- Err(ProviderError::CapabilityUnsupported(
1728
- "test adapter".to_string(),
1729
- ))
1730
- }
1731
-
1732
- fn status_patterns(&self) -> Result<crate::provider::StatusPatterns, ProviderError> {
1733
- Err(ProviderError::CapabilityUnsupported(
1734
- "test adapter".to_string(),
1735
- ))
1736
- }
1737
-
1738
- fn validate_model(&self, _model: &str) -> Result<bool, ProviderError> {
1739
- Ok(true)
1740
- }
1741
- }
1742
- }
1743
-
1744
- #[cfg(test)]
1745
- #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1746
- mod u1_tests {
1747
- use super::*;
1748
-
1749
- use crate::provider::{CaptureVia, CapturedSession, Confidence, RolloutPath, SessionId};
1750
- use std::path::PathBuf;
1751
-
1752
- fn leader_like_candidate(session_id: &str, path: &str) -> CapturedSessionCandidate {
1753
- CapturedSessionCandidate {
1754
- captured: CapturedSession {
1755
- session_id: Some(SessionId::new(session_id)),
1756
- rollout_path: Some(RolloutPath::new(PathBuf::from(path))),
1757
- captured_via: CaptureVia::FsWatch,
1758
- attribution_confidence: Confidence::High,
1759
- spawn_cwd: PathBuf::from("/tmp/u1-cwd"),
1760
- },
1761
- embedded_agent_id: None,
1762
- positive_agent_id_match: false,
1763
- agent_path_match: false,
1764
- }
1765
- }
1766
-
1767
- fn worker_owned_candidate(session_id: &str, path: &str) -> CapturedSessionCandidate {
1768
- CapturedSessionCandidate {
1769
- captured: CapturedSession {
1770
- session_id: Some(SessionId::new(session_id)),
1771
- rollout_path: Some(RolloutPath::new(PathBuf::from(path))),
1772
- captured_via: CaptureVia::FsWatch,
1773
- attribution_confidence: Confidence::High,
1774
- spawn_cwd: PathBuf::from("/tmp/u1-cwd"),
1775
- },
1776
- embedded_agent_id: None,
1777
- positive_agent_id_match: true,
1778
- agent_path_match: false,
1779
- }
1780
- }
1781
-
1782
- /// P0 RED-1 (lane-046-capture-gap): a Claude worker with
1783
- /// expected_session_id=None must NOT capture a candidate that has neither
1784
- /// positive_agent_id_match nor agent_path_match — even when it is the
1785
- /// only candidate (the leader-transcript-as-only-candidate failure mode
1786
- /// from the macmini repro). Must end up ambiguous, not assigned.
1787
- #[test]
1788
- fn claude_no_expected_single_leader_candidate_is_not_assigned() {
1789
- let mut state = serde_json::json!({
1790
- "agents": {
1791
- "release_engineer": {
1792
- "provider": "claude",
1793
- "status": "running",
1794
- "spawn_cwd": "/tmp/u1-cwd"
1795
- }
1796
- }
1797
- });
1798
- let mut canned = BTreeMap::new();
1799
- canned.insert(
1800
- "release_engineer".to_string(),
1801
- vec![leader_like_candidate(
1802
- "ea059b82-c53e-4654-9590-9f3e6d46f0ca",
1803
- "/Users/alauda/.claude/projects/-Users-alauda-team/ea059b82.jsonl",
1804
- )],
1805
- );
1806
- let canned_for_adapter = canned.clone();
1807
- let mut adapter_for = move |provider| {
1808
- Box::new(
1809
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
1810
- .with_candidates(canned_for_adapter.clone()),
1811
- ) as Box<dyn ProviderAdapter>
1812
- };
1813
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
1814
- .expect("capture pass succeeds");
1815
- assert!(
1816
- report.assigned.is_empty(),
1817
- "Claude no-expected + weak (no positive/path) candidate must NOT be assigned; got {:?}",
1818
- report.assigned
1819
- );
1820
- let agent = state
1821
- .get("agents")
1822
- .and_then(|a| a.get("release_engineer"))
1823
- .expect("agent present");
1824
- assert!(
1825
- agent.get("session_id").is_none(),
1826
- "agent.session_id must remain empty when capture is refused; got {agent:?}"
1827
- );
1828
- }
1829
-
1830
- #[test]
1831
- fn codex_no_expected_same_cwd_candidates_without_identity_do_not_global_zip_assign() {
1832
- let mut state = serde_json::json!({
1833
- "agents": {
1834
- "frontend": {
1835
- "provider": "codex",
1836
- "status": "running",
1837
- "spawn_cwd": "/tmp/u1-cwd"
1838
- },
1839
- "ios-dev": {
1840
- "provider": "codex",
1841
- "status": "running",
1842
- "spawn_cwd": "/tmp/u1-cwd"
1843
- }
1844
- }
1845
- });
1846
- let candidates = vec![
1847
- leader_like_candidate(
1848
- "019f3327-c35a-7023-b3cd-1bea93a7a157",
1849
- "/Users/alauda/.codex/sessions/2026/07/06/rollout-frontend-poison.jsonl",
1850
- ),
1851
- leader_like_candidate(
1852
- "019f3327-d6d7-7c80-846a-0db4821714fb",
1853
- "/Users/alauda/.codex/sessions/2026/07/06/rollout-ios-poison.jsonl",
1854
- ),
1855
- ];
1856
- let mut canned = BTreeMap::new();
1857
- canned.insert("frontend".to_string(), candidates.clone());
1858
- canned.insert("ios-dev".to_string(), candidates);
1859
- let canned_for_adapter = canned.clone();
1860
- let mut adapter_for = move |provider| {
1861
- Box::new(
1862
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
1863
- .with_candidates(canned_for_adapter.clone()),
1864
- ) as Box<dyn ProviderAdapter>
1865
- };
1866
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
1867
- .expect("capture pass succeeds");
1868
- assert!(
1869
- report.assigned.is_empty(),
1870
- "Codex no-expected same-cwd candidates with no positive identity must stay ambiguous, not global one-to-one assigned; report={report:?}"
1871
- );
1872
- assert_eq!(
1873
- report
1874
- .ambiguous
1875
- .iter()
1876
- .map(|item| item.agent_id.as_str())
1877
- .collect::<Vec<_>>(),
1878
- vec!["frontend", "ios-dev"],
1879
- "both workers should be marked ambiguous instead of receiving weak zipped tuples"
1880
- );
1881
- let agents = state["agents"].as_object().expect("agents object");
1882
- assert!(agents["frontend"].get("session_id").is_none());
1883
- assert!(agents["ios-dev"].get("session_id").is_none());
1884
- }
1885
-
1886
- #[test]
1887
- fn codex_no_expected_single_candidate_without_identity_still_captures() {
1888
- let mut state = serde_json::json!({
1889
- "agents": {
1890
- "subgreeter": {
1891
- "provider": "codex",
1892
- "status": "running",
1893
- "spawn_cwd": "/tmp/u1-cwd"
1894
- }
1895
- }
1896
- });
1897
- let mut canned = BTreeMap::new();
1898
- canned.insert(
1899
- "subgreeter".to_string(),
1900
- vec![leader_like_candidate(
1901
- "sess-sub-captured",
1902
- "/Users/alauda/.codex/sessions/2026/07/06/rollout-sub.jsonl",
1903
- )],
1904
- );
1905
- let canned_for_adapter = canned.clone();
1906
- let mut adapter_for = move |provider| {
1907
- Box::new(
1908
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
1909
- .with_candidates(canned_for_adapter.clone()),
1910
- ) as Box<dyn ProviderAdapter>
1911
- };
1912
-
1913
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
1914
- .expect("capture pass succeeds");
1915
-
1916
- assert_eq!(report.assigned, vec!["subgreeter".to_string()]);
1917
- assert!(report.ambiguous.is_empty(), "report={report:?}");
1918
- assert_eq!(
1919
- state["agents"]["subgreeter"]["session_id"].as_str(),
1920
- Some("sess-sub-captured")
1921
- );
1922
- }
1923
-
1924
- #[test]
1925
- fn codex_shared_single_candidate_without_identity_is_deferred() {
1926
- let mut state = serde_json::json!({
1927
- "agents": {
1928
- "parent-peer": {
1929
- "provider": "codex",
1930
- "status": "running",
1931
- "spawn_cwd": "/tmp/u1-cwd"
1932
- },
1933
- "worker-a": {
1934
- "provider": "codex",
1935
- "status": "running",
1936
- "spawn_cwd": "/tmp/u1-cwd"
1937
- }
1938
- }
1939
- });
1940
- let candidate = leader_like_candidate(
1941
- "019f3327-shared",
1942
- "/Users/alauda/.codex/sessions/2026/07/06/rollout-shared.jsonl",
1943
- );
1944
- let mut canned = BTreeMap::new();
1945
- canned.insert("parent-peer".to_string(), vec![candidate.clone()]);
1946
- canned.insert("worker-a".to_string(), vec![candidate]);
1947
- let canned_for_adapter = canned.clone();
1948
- let mut adapter_for = move |provider| {
1949
- Box::new(
1950
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
1951
- .with_candidates(canned_for_adapter.clone()),
1952
- ) as Box<dyn ProviderAdapter>
1953
- };
1954
-
1955
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
1956
- .expect("capture pass succeeds");
1957
-
1958
- assert!(report.assigned.is_empty(), "report={report:?}");
1959
- assert!(state["agents"]["parent-peer"].get("session_id").is_none());
1960
- assert!(state["agents"]["worker-a"].get("session_id").is_none());
1961
- }
1962
-
1963
- #[test]
1964
- fn codex_embedded_identity_assigns_each_same_cwd_worker_to_own_rollout() {
1965
- let mut state = serde_json::json!({
1966
- "agents": {
1967
- "frontend": {
1968
- "provider": "codex",
1969
- "status": "running",
1970
- "spawn_cwd": "/tmp/u1-cwd"
1971
- },
1972
- "ios-dev": {
1973
- "provider": "codex",
1974
- "status": "running",
1975
- "spawn_cwd": "/tmp/u1-cwd"
1976
- }
1977
- }
1978
- });
1979
- let frontend = CapturedSessionCandidate {
1980
- embedded_agent_id: Some("frontend".to_string()),
1981
- positive_agent_id_match: true,
1982
- ..leader_like_candidate(
1983
- "019f3327-frontend",
1984
- "/Users/alauda/.codex/sessions/2026/07/06/rollout-frontend.jsonl",
1985
- )
1986
- };
1987
- let ios = CapturedSessionCandidate {
1988
- embedded_agent_id: Some("ios-dev".to_string()),
1989
- positive_agent_id_match: true,
1990
- ..leader_like_candidate(
1991
- "019f3327-ios-dev",
1992
- "/Users/alauda/.codex/sessions/2026/07/06/rollout-ios-dev.jsonl",
1993
- )
1994
- };
1995
- let mut canned = BTreeMap::new();
1996
- canned.insert("frontend".to_string(), vec![frontend]);
1997
- canned.insert("ios-dev".to_string(), vec![ios]);
1998
- let canned_for_adapter = canned.clone();
1999
- let mut adapter_for = move |provider| {
2000
- Box::new(
2001
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
2002
- .with_candidates(canned_for_adapter.clone()),
2003
- ) as Box<dyn ProviderAdapter>
2004
- };
2005
-
2006
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
2007
- .expect("capture pass succeeds");
2008
-
2009
- assert_eq!(
2010
- report.assigned,
2011
- vec!["frontend".to_string(), "ios-dev".to_string()]
2012
- );
2013
- assert!(report.ambiguous.is_empty());
2014
- assert_eq!(
2015
- state["agents"]["frontend"]["session_id"].as_str(),
2016
- Some("019f3327-frontend")
2017
- );
2018
- assert_eq!(
2019
- state["agents"]["ios-dev"]["session_id"].as_str(),
2020
- Some("019f3327-ios-dev")
2021
- );
2022
- }
2023
-
2024
- #[test]
2025
- fn apply_time_identity_guard_refuses_mismatched_candidate() {
2026
- let mut state = serde_json::json!({
2027
- "agents": {
2028
- "frontend": {
2029
- "provider": "codex",
2030
- "status": "running",
2031
- "spawn_cwd": "/tmp/u1-cwd"
2032
- }
2033
- }
2034
- });
2035
- let candidate = CapturedSessionCandidate {
2036
- embedded_agent_id: Some("ios-dev".to_string()),
2037
- positive_agent_id_match: true,
2038
- ..leader_like_candidate(
2039
- "019f3327-c35a-7023-b3cd-1bea93a7a157",
2040
- "/Users/alauda/.codex/sessions/2026/07/06/rollout-ios-dev.jsonl",
2041
- )
2042
- };
2043
- let mut canned = BTreeMap::new();
2044
- canned.insert("frontend".to_string(), vec![candidate]);
2045
- let canned_for_adapter = canned.clone();
2046
- let mut adapter_for = move |provider| {
2047
- Box::new(
2048
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
2049
- .with_candidates(canned_for_adapter.clone()),
2050
- ) as Box<dyn ProviderAdapter>
2051
- };
2052
-
2053
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
2054
- .expect("capture pass succeeds");
2055
-
2056
- assert!(report.assigned.is_empty());
2057
- assert_eq!(report.identity_mismatches.len(), 1);
2058
- assert_eq!(report.identity_mismatches[0].agent_id, "frontend");
2059
- assert_eq!(report.identity_mismatches[0].embedded_agent_id, "ios-dev");
2060
- assert!(state["agents"]["frontend"].get("session_id").is_none());
2061
- assert_eq!(
2062
- state["agents"]["frontend"]["capture_state"].as_str(),
2063
- Some("session_identity_mismatch")
2064
- );
2065
- }
2066
-
2067
- /// P0 RED-2: same shape but with a positive_agent_id_match candidate →
2068
- /// must capture (positive agent id is authoritative for Claude
2069
- /// no-expected).
2070
- #[test]
2071
- fn claude_no_expected_positive_worker_candidate_still_captures() {
2072
- let mut state = serde_json::json!({
2073
- "agents": {
2074
- "release_engineer": {
2075
- "provider": "claude",
2076
- "status": "running",
2077
- "spawn_cwd": "/tmp/u1-cwd"
2078
- }
2079
- }
2080
- });
2081
- let mut canned = BTreeMap::new();
2082
- canned.insert(
2083
- "release_engineer".to_string(),
2084
- vec![worker_owned_candidate(
2085
- "abc12345-worker-owned",
2086
- "/Users/alauda/.claude/projects/-Users-alauda-team/abc12345.jsonl",
2087
- )],
2088
- );
2089
- let canned_for_adapter = canned.clone();
2090
- let mut adapter_for = move |provider| {
2091
- Box::new(
2092
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
2093
- .with_candidates(canned_for_adapter.clone()),
2094
- ) as Box<dyn ProviderAdapter>
2095
- };
2096
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
2097
- .expect("capture pass succeeds");
2098
- assert_eq!(
2099
- report.assigned,
2100
- vec!["release_engineer".to_string()],
2101
- "Claude no-expected + positive_agent_id candidate MUST capture; got {:?}",
2102
- report.assigned
2103
- );
2104
- }
2105
-
2106
- /// P0 RED-3: leader_receiver under teams.<key> with provider session
2107
- /// fields must exclude that session from worker capture even if the
2108
- /// candidate would otherwise match.
2109
- #[test]
2110
- fn claimed_session_keys_include_team_scoped_leader_receiver() {
2111
- let mut state = serde_json::json!({
2112
- "agents": {
2113
- "release_engineer": {
2114
- "provider": "claude",
2115
- "status": "running",
2116
- "spawn_cwd": "/tmp/u1-cwd"
2117
- }
2118
- },
2119
- "teams": {
2120
- "teamA": {
2121
- "leader_receiver": {
2122
- "session_id": "leader-session-id-zzz",
2123
- "rollout_path": "/Users/alauda/.claude/projects/-Users-alauda-team/zzz.jsonl"
2124
- }
2125
- }
2126
- }
2127
- });
2128
- let mut canned = BTreeMap::new();
2129
- canned.insert(
2130
- "release_engineer".to_string(),
2131
- vec![worker_owned_candidate(
2132
- "leader-session-id-zzz",
2133
- "/Users/alauda/.claude/projects/-Users-alauda-team/zzz.jsonl",
2134
- )],
2135
- );
2136
- let canned_for_adapter = canned.clone();
2137
- let mut adapter_for = move |provider| {
2138
- Box::new(
2139
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
2140
- .with_candidates(canned_for_adapter.clone()),
2141
- ) as Box<dyn ProviderAdapter>
2142
- };
2143
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
2144
- .expect("capture pass succeeds");
2145
- assert!(
2146
- report.assigned.is_empty(),
2147
- "worker candidate that collides with team-scoped leader_receiver \
2148
- session MUST be excluded by claimed_provider_session_keys; got {:?}",
2149
- report.assigned
2150
- );
2151
- }
2152
-
2153
- #[test]
2154
- fn pending_capture_state_stays_pending_until_a_trigger_expires() {
2155
- let old = (chrono::Utc::now() - chrono::Duration::seconds(60)).to_rfc3339();
2156
- let mut agent = serde_json::Map::new();
2157
- agent.insert("spawned_at".to_string(), serde_json::json!(old));
2158
- assert_eq!(
2159
- super::classify_pending_capture_state(&agent, 0),
2160
- "pending_first_turn"
2161
- );
2162
-
2163
- let trigger = (chrono::Utc::now() - chrono::Duration::seconds(20)).to_rfc3339();
2164
- agent.insert("first_send_at".to_string(), serde_json::json!(trigger));
2165
- assert_eq!(
2166
- super::classify_pending_capture_state(&agent, 0),
2167
- "transcript_missing"
2168
- );
2169
- }
2170
-
2171
- #[test]
2172
- fn pending_context_fork_keeps_typed_state_until_trigger_grace_expires() {
2173
- let old = (chrono::Utc::now() - chrono::Duration::seconds(60)).to_rfc3339();
2174
- let mut agent = serde_json::Map::new();
2175
- agent.insert("spawned_at".to_string(), serde_json::json!(old));
2176
- agent.insert(
2177
- "capture_state".to_string(),
2178
- serde_json::json!("pending_context_fork"),
2179
- );
2180
- assert_eq!(
2181
- super::classify_pending_capture_state(&agent, 0),
2182
- "pending_context_fork"
2183
- );
2184
- let trigger = (chrono::Utc::now() - chrono::Duration::seconds(20)).to_rfc3339();
2185
- agent.insert("first_send_at".to_string(), serde_json::json!(trigger));
2186
- assert_eq!(
2187
- super::classify_pending_capture_state(&agent, 0),
2188
- "transcript_missing"
2189
- );
2190
- }
2191
-
2192
- #[test]
2193
- fn canonical_pending_capture_preserves_legacy_missing_boundary() {
2194
- let agent = serde_json::json!({
2195
- "provider": "copilot",
2196
- "status": "running",
2197
- "spawn_cwd": "/tmp/u1-cwd",
2198
- "capture_state": "pending_first_turn"
2199
- });
2200
- let mut adapter_for = crate::provider::get_adapter;
2201
- let pending = pending_session_capture("clone", &agent, &mut adapter_for)
2202
- .expect("legacy row still participates in canonical capture");
2203
- assert_eq!(pending.context.spawned_at, None);
2204
- }
2205
-
2206
- #[test]
2207
- fn existing_team_session_is_rejected_while_fresh_candidate_is_accepted() {
2208
- let mut state = serde_json::json!({
2209
- "session_name": "current",
2210
- "agents": {
2211
- "clone": {
2212
- "provider": "copilot",
2213
- "status": "running",
2214
- "spawn_cwd": "/tmp/u1-cwd"
2215
- }
2216
- },
2217
- "teams": {
2218
- "archived": {
2219
- "agents": {
2220
- "old-seat": {
2221
- "provider": "copilot",
2222
- "session_id": "stale-session",
2223
- "rollout_path": "/tmp/stale.jsonl"
2224
- }
2225
- }
2226
- }
2227
- }
2228
- });
2229
- let mut canned = BTreeMap::new();
2230
- canned.insert(
2231
- "clone".to_string(),
2232
- vec![
2233
- worker_owned_candidate("stale-session", "/tmp/stale.jsonl"),
2234
- worker_owned_candidate("fresh-session", "/tmp/fresh.jsonl"),
2235
- ],
2236
- );
2237
- let canned_for_adapter = canned.clone();
2238
- let mut adapter_for = move |provider| {
2239
- Box::new(
2240
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
2241
- .with_candidates(canned_for_adapter.clone()),
2242
- ) as Box<dyn ProviderAdapter>
2243
- };
2244
-
2245
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
2246
- .expect("capture pass succeeds");
2247
-
2248
- assert_eq!(report.assigned, vec!["clone".to_string()]);
2249
- assert_eq!(
2250
- state["agents"]["clone"]["session_id"].as_str(),
2251
- Some("fresh-session")
2252
- );
2253
- }
2254
-
2255
- #[test]
2256
- fn capture_pass_keeps_pending_agent_when_one_adapter_capture_fails() {
2257
- let mut state = serde_json::json!({
2258
- "agents": {
2259
- "bad": {
2260
- "provider": "copilot",
2261
- "status": "running",
2262
- "spawn_cwd": "/tmp/u1-bad"
2263
- },
2264
- "good": {
2265
- "provider": "copilot",
2266
- "status": "running",
2267
- "spawn_cwd": "/tmp/u1-good"
2268
- }
2269
- }
2270
- });
2271
- let mut adapter_for = |provider| {
2272
- Box::new(test_support::CaptureCandidatesAdapter::new(
2273
- provider,
2274
- Some("bad"),
2275
- "capture exploded",
2276
- )) as Box<dyn ProviderAdapter>
2277
- };
2278
-
2279
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
2280
- .expect("one agent capture failure must not abort the whole pass");
2281
-
2282
- assert_eq!(report.pending, vec!["bad".to_string(), "good".to_string()]);
2283
- assert_eq!(report.assigned, Vec::<String>::new());
2284
- assert_eq!(
2285
- report.candidate_count_by_agent.get("good"),
2286
- Some(&0),
2287
- "the non-failing agent must still be probed"
2288
- );
2289
- assert_eq!(
2290
- report.capture_failures,
2291
- vec![SessionCaptureFailure {
2292
- agent_id: "bad".to_string(),
2293
- error: "provider io error: capture exploded".to_string(),
2294
- }]
2295
- );
2296
- }
2297
-
2298
- /// RM-039-SESS-001 step 1 (architect verdict 2026-06-22): the
2299
- /// `agent_session_complete` predicate must NOT treat a non-empty
2300
- /// `rollout_path` as complete when the file does not exist. The
2301
- /// historical bug was that a stale-positive capture tuple
2302
- /// (`session_id` + `rollout_path` both present, but the path had
2303
- /// been rotated away by the provider) was reported as complete and
2304
- /// blocked `pending_session_capture` from recapturing. Now the
2305
- /// predicate returns false if the path does not exist, so the
2306
- /// session is re-evaluated on the next convergence tick.
2307
- #[test]
2308
- fn rm039_sess001_agent_session_complete_requires_existing_rollout_path() {
2309
- // Case 1: session_id + rollout_path both non-empty, path absent.
2310
- let missing = "/tmp/ta-rm039-sess001-nonexistent-rollout.jsonl";
2311
- // Guard against a previous test run leaving the file behind.
2312
- let _ = std::fs::remove_file(missing);
2313
- let agent_stale = serde_json::json!({
2314
- "session_id": "sess-stale-positive",
2315
- "rollout_path": missing,
2316
- });
2317
- assert!(
2318
- !agent_session_complete(&agent_stale),
2319
- "RM-039-SESS-001: stale-positive tuple (session_id + missing rollout_path) \
2320
- must NOT be reported complete"
2321
- );
2322
-
2323
- // Case 2: session_id + rollout_path both non-empty, path exists.
2324
- use std::sync::atomic::{AtomicU64, Ordering};
2325
- static N: AtomicU64 = AtomicU64::new(0);
2326
- let n = N.fetch_add(1, Ordering::Relaxed);
2327
- let existing = std::env::temp_dir().join(format!(
2328
- "ta-rm039-sess001-existing-{}-{}.jsonl",
2329
- std::process::id(),
2330
- n
2331
- ));
2332
- std::fs::write(&existing, b"{}\n").expect("write fixture rollout file");
2333
- // 0.4.6 tuple-atomic contract: `agent_session_complete` now requires
2334
- // the full authoritative tuple (session_id + rollout_path +
2335
- // captured_at + captured_via), not just session_id + rollout_path.
2336
- // Pre-0.4.6 partial tuples are no longer treated as complete.
2337
- let agent_complete = serde_json::json!({
2338
- "session_id": "sess-real",
2339
- "rollout_path": existing.to_string_lossy(),
2340
- "captured_at": "2026-06-25T10:00:00+00:00",
2341
- "captured_via": "session.captured",
2342
- });
2343
- assert!(
2344
- agent_session_complete(&agent_complete),
2345
- "0.4.6: agent with full tuple (session_id + rollout_path + captured_at + captured_via) + existing rollout file is complete"
2346
- );
2347
- let _ = std::fs::remove_file(&existing);
2348
-
2349
- // Case 3: empty session_id must still fail completeness regardless.
2350
- let agent_no_session = serde_json::json!({
2351
- "session_id": "",
2352
- "rollout_path": "/tmp/whatever",
2353
- });
2354
- assert!(!agent_session_complete(&agent_no_session));
2355
-
2356
- // Case 4: empty rollout_path remains incomplete (legacy contract).
2357
- let agent_no_path = serde_json::json!({
2358
- "session_id": "sess-x",
2359
- "rollout_path": "",
2360
- });
2361
- assert!(!agent_session_complete(&agent_no_path));
2362
- }
2363
-
2364
- /// Stage 1 amendment regression (architect direction 2026-06-23,
2365
- /// S1-CAPTURE-002): two pending agents, each with a distinct
2366
- /// `_pending_session_id`. Each agent's candidate list contains ONLY its
2367
- /// own expected transcript (no positive worker identity hint, no path
2368
- /// agent id hint — the file basename is just a UUID). Pre-fix, the
2369
- /// allocator's `allocate_global_one_to_one` zipped agents (sorted by
2370
- /// agent_id) with candidates (sorted by candidate-key), producing CROSS
2371
- /// assignments that the mismatch guard then rejected — leaving both
2372
- /// agents `attribution_ambiguous`. Post-fix, the ExpectedSessionId
2373
- /// pre-pass binds each agent to its own expected candidate before any
2374
- /// global one-to-one runs.
2375
- #[test]
2376
- fn capture_allocator_expected_session_id_binds_each_worker_to_its_own_transcript() {
2377
- // 0.4.6 P0 amendment: Claude no longer carries _pending_session_id
2378
- // (fresh spawn doesn't inject --session-id; capture anchors on
2379
- // cwd+spawned_at+identity). The ExpectedSessionId pre-pass remains
2380
- // valid for providers that DO use expected_session_id (Copilot is the
2381
- // only one left that honors framework-supplied --session-id). Switch
2382
- // this test to Copilot to preserve the pre-pass invariant coverage.
2383
- use crate::provider::{CaptureVia, Confidence, RolloutPath};
2384
- let dir = std::env::temp_dir().join(format!("ta-stage1-allocator-{}", std::process::id()));
2385
- std::fs::create_dir_all(&dir).unwrap();
2386
- let rollout_a = dir.join("9a2d1668.jsonl");
2387
- let rollout_b = dir.join("3e824e89.jsonl");
2388
- std::fs::write(&rollout_a, b"{}\n").unwrap();
2389
- std::fs::write(&rollout_b, b"{}\n").unwrap();
2390
- let candidate_a = CapturedSessionCandidate {
2391
- captured: CapturedSession {
2392
- session_id: Some(SessionId::new("9a2d1668-8987-4c36-8bde-a5135b10da02")),
2393
- rollout_path: Some(RolloutPath::new(rollout_a.clone())),
2394
- captured_via: CaptureVia::FsWatch,
2395
- attribution_confidence: Confidence::High,
2396
- spawn_cwd: dir.clone(),
2397
- },
2398
- embedded_agent_id: None,
2399
- positive_agent_id_match: false,
2400
- agent_path_match: false,
2401
- };
2402
- let candidate_b = CapturedSessionCandidate {
2403
- captured: CapturedSession {
2404
- session_id: Some(SessionId::new("3e824e89-25ac-4b3f-b272-b4f733f6403c")),
2405
- rollout_path: Some(RolloutPath::new(rollout_b.clone())),
2406
- captured_via: CaptureVia::FsWatch,
2407
- attribution_confidence: Confidence::High,
2408
- spawn_cwd: dir.clone(),
2409
- },
2410
- embedded_agent_id: None,
2411
- positive_agent_id_match: false,
2412
- agent_path_match: false,
2413
- };
2414
- let mut candidates_by_agent: BTreeMap<String, Vec<CapturedSessionCandidate>> =
2415
- BTreeMap::new();
2416
- candidates_by_agent.insert("copilot-a".to_string(), vec![candidate_a.clone()]);
2417
- candidates_by_agent.insert("copilot-b".to_string(), vec![candidate_b.clone()]);
2418
-
2419
- let cwd_str = dir.to_string_lossy().to_string();
2420
- let mut state = serde_json::json!({
2421
- "agents": {
2422
- "copilot-a": {
2423
- "provider": "copilot",
2424
- "status": "running",
2425
- "spawn_cwd": cwd_str,
2426
- "_pending_session_id": "9a2d1668-8987-4c36-8bde-a5135b10da02"
2427
- },
2428
- "copilot-b": {
2429
- "provider": "copilot",
2430
- "status": "running",
2431
- "spawn_cwd": cwd_str,
2432
- "_pending_session_id": "3e824e89-25ac-4b3f-b272-b4f733f6403c"
2433
- }
2434
- }
2435
- });
2436
- let adapter = test_support::CaptureCandidatesAdapter::new(Provider::Copilot, None, "")
2437
- .with_candidates(candidates_by_agent);
2438
- let mut adapter_for =
2439
- move |_provider| Box::new(adapter.clone()) as Box<dyn ProviderAdapter>;
2440
-
2441
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
2442
- .expect("allocator pass should succeed");
2443
-
2444
- // ExpectedSessionId pre-pass must bind each agent to its own
2445
- // expected transcript. No cross-assignment, no ambiguous mark.
2446
- let agents = state["agents"].as_object().expect("agents object");
2447
- assert_eq!(
2448
- agents["copilot-a"]["session_id"].as_str(),
2449
- Some("9a2d1668-8987-4c36-8bde-a5135b10da02"),
2450
- "Stage 1 fix: copilot-a must bind to its own expected transcript; \
2451
- state.copilot-a={}",
2452
- agents["copilot-a"]
2453
- );
2454
- assert_eq!(
2455
- agents["copilot-b"]["session_id"].as_str(),
2456
- Some("3e824e89-25ac-4b3f-b272-b4f733f6403c"),
2457
- "Stage 1 fix: copilot-b must bind to its own expected transcript; \
2458
- state.copilot-b={}",
2459
- agents["copilot-b"]
2460
- );
2461
- assert!(
2462
- agents["copilot-a"]
2463
- .get("attribution_ambiguous")
2464
- .is_none_or(|v| v.as_bool() != Some(true)),
2465
- "Stage 1 fix: copilot-a must NOT be flagged ambiguous after the \
2466
- expected-id pre-pass bound it; state.copilot-a={}",
2467
- agents["copilot-a"]
2468
- );
2469
- assert!(
2470
- agents["copilot-b"]
2471
- .get("attribution_ambiguous")
2472
- .is_none_or(|v| v.as_bool() != Some(true)),
2473
- "Stage 1 fix: copilot-b must NOT be flagged ambiguous; \
2474
- state.copilot-b={}",
2475
- agents["copilot-b"]
2476
- );
2477
- assert_eq!(
2478
- report.ambiguous.len(),
2479
- 0,
2480
- "Stage 1 fix: capture report must record zero ambiguous; report={report:?}"
2481
- );
2482
-
2483
- let _ = std::fs::remove_file(&rollout_a);
2484
- let _ = std::fs::remove_file(&rollout_b);
2485
- let _ = std::fs::remove_dir(&dir);
2486
- }
2487
-
2488
- #[test]
2489
- fn copilot_exact_session_id_does_not_collide_on_shared_store_path() {
2490
- use crate::provider::{CaptureVia, Confidence, RolloutPath};
2491
- let dir =
2492
- std::env::temp_dir().join(format!("ta-copilot-shared-store-{}", std::process::id()));
2493
- let _ = std::fs::remove_dir_all(&dir);
2494
- std::fs::create_dir_all(&dir).unwrap();
2495
- let store = dir.join("session-store.db");
2496
- std::fs::write(&store, b"fixture").unwrap();
2497
- let expected = "22222222-2222-4222-8222-222222222222";
2498
- let candidate = CapturedSessionCandidate {
2499
- captured: CapturedSession {
2500
- session_id: Some(SessionId::new(expected)),
2501
- rollout_path: Some(RolloutPath::new(store.clone())),
2502
- captured_via: CaptureVia::FsWatch,
2503
- attribution_confidence: Confidence::High,
2504
- spawn_cwd: dir.clone(),
2505
- },
2506
- embedded_agent_id: None,
2507
- positive_agent_id_match: false,
2508
- agent_path_match: false,
2509
- };
2510
- let mut by_agent = BTreeMap::new();
2511
- by_agent.insert("clone".to_string(), vec![candidate]);
2512
- let mut state = serde_json::json!({
2513
- "agents": {
2514
- "source": {
2515
- "provider": "copilot",
2516
- "status": "running",
2517
- "spawn_cwd": dir.to_string_lossy(),
2518
- "session_id": "11111111-1111-4111-8111-111111111111",
2519
- "rollout_path": store.to_string_lossy(),
2520
- "captured_at": "2026-07-22T01:00:00+00:00",
2521
- "captured_via": "fs_watch"
2522
- },
2523
- "clone": {
2524
- "provider": "copilot",
2525
- "status": "running",
2526
- "spawn_cwd": dir.to_string_lossy(),
2527
- "spawned_at": "2026-07-22T02:00:00+00:00",
2528
- "_pending_session_id": expected
2529
- }
2530
- }
2531
- });
2532
- let adapter = test_support::CaptureCandidatesAdapter::new(Provider::Copilot, None, "")
2533
- .with_candidates(by_agent);
2534
- let mut adapter_for =
2535
- move |_provider| Box::new(adapter.clone()) as Box<dyn ProviderAdapter>;
2536
-
2537
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
2538
- .expect("capture shared Copilot store");
2539
-
2540
- assert_eq!(report.assigned, vec!["clone".to_string()]);
2541
- assert_eq!(state["agents"]["clone"]["session_id"], expected);
2542
- assert_eq!(
2543
- state["agents"]["clone"]["rollout_path"],
2544
- store.to_string_lossy().as_ref()
2545
- );
2546
- assert_eq!(
2547
- state["agents"]["source"]["session_id"],
2548
- "11111111-1111-4111-8111-111111111111"
2549
- );
2550
- let _ = std::fs::remove_dir_all(&dir);
2551
- }
2552
-
2553
- /// S1-CAPTURE-001 (0.4.8): pending mismatch guard. When fresh-start has
2554
- /// written a new `_pending_session_id` but the old authoritative
2555
- /// `session_id` is still present and differs, `agent_session_complete`
2556
- /// must return false so capture re-runs and re-binds to the new process.
2557
- /// Without this, the historical poison state (old + new coexist) lets
2558
- /// the stale rollout look authoritative.
2559
- #[test]
2560
- fn agent_session_complete_returns_false_on_pending_mismatch() {
2561
- let dir = std::env::temp_dir().join(format!("ta-pending-mismatch-{}", std::process::id()));
2562
- let _ = std::fs::create_dir_all(&dir);
2563
- let rollout = dir.join("old.jsonl");
2564
- std::fs::write(&rollout, "{\"type\":\"assistant\"}\n").unwrap();
2565
-
2566
- let agent = serde_json::json!({
2567
- "provider": "claude",
2568
- "session_id": "old",
2569
- "rollout_path": rollout.to_string_lossy(),
2570
- "captured_at": "2026-01-01T00:00:00+00:00",
2571
- "captured_via": "fs_watch",
2572
- "_pending_session_id": "new",
2573
- });
2574
-
2575
- assert!(
2576
- !super::agent_session_complete(&agent),
2577
- "S1-CAPTURE-001: pending != session_id must force incomplete \
2578
- (capture must re-attribute to new session)"
2579
- );
2580
-
2581
- // Sanity: when they match, complete is true.
2582
- let agent_match = serde_json::json!({
2583
- "provider": "claude",
2584
- "session_id": "new",
2585
- "rollout_path": rollout.to_string_lossy(),
2586
- "captured_at": "2026-01-01T00:00:00+00:00",
2587
- "captured_via": "fs_watch",
2588
- "_pending_session_id": "new",
2589
- });
2590
- assert!(
2591
- super::agent_session_complete(&agent_match),
2592
- "pending == session_id (in-progress capture confirmed): must be complete"
2593
- );
2594
-
2595
- let _ = std::fs::remove_file(&rollout);
2596
- let _ = std::fs::remove_dir_all(&dir);
2597
- }
2598
-
2599
- /// S1-CAPTURE-001 (0.4.8): apply_captured_session clears
2600
- /// `_pending_session_id` and stamps `capture_state="captured"` so the
2601
- /// pending-mismatch guard doesn't fire on subsequent reads.
2602
- #[test]
2603
- fn apply_captured_session_clears_pending_and_stamps_capture_state() {
2604
- let mut agent = serde_json::Map::new();
2605
- agent.insert(
2606
- "_pending_session_id".to_string(),
2607
- serde_json::json!("new-sess"),
2608
- );
2609
- let captured = CapturedSession {
2610
- session_id: Some(SessionId::new("new-sess")),
2611
- rollout_path: Some(RolloutPath::new(PathBuf::from("/tmp/new.jsonl"))),
2612
- captured_via: CaptureVia::FsWatch,
2613
- attribution_confidence: Confidence::High,
2614
- spawn_cwd: PathBuf::from("/tmp/cwd"),
2615
- };
2616
- let written = super::apply_captured_session(&mut agent, &captured);
2617
- assert!(written, "apply must accept valid captured");
2618
- assert!(
2619
- agent.get("_pending_session_id").is_none(),
2620
- "S1-CAPTURE-001: _pending_session_id must be removed after capture \
2621
- (agent={agent:?})"
2622
- );
2623
- assert_eq!(
2624
- agent
2625
- .get("capture_state")
2626
- .and_then(serde_json::Value::as_str),
2627
- Some("captured"),
2628
- "S1-CAPTURE-001: capture_state must be stamped 'captured'"
2629
- );
2630
- }
2631
- }