@team-agent/installer 0.5.128 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (436) hide show
  1. package/README.md +4 -4
  2. package/README.zh.md +1 -1
  3. package/package.json +4 -8
  4. package/skills/team-agent/SKILL.md +37 -20
  5. package/skills/team-agent/command-coverage.json +169 -183
  6. package/skills/team-agent/docs/reference/team-agent-operator.md +64 -30
  7. package/skills/team-agent/references/recovery-runbook.md +1 -1
  8. package/skills/team-agent/references/team-agent-operator.md +64 -30
  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 -1288
  15. package/crates/team-agent/src/cli/arguments.rs +0 -405
  16. package/crates/team-agent/src/cli/attach_app_server_leader.rs +0 -98
  17. package/crates/team-agent/src/cli/diagnose.rs +0 -1721
  18. package/crates/team-agent/src/cli/emit.rs +0 -2930
  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 -1216
  22. package/crates/team-agent/src/cli/intent/runtime_tests.rs +0 -912
  23. package/crates/team-agent/src/cli/intent/tests.rs +0 -689
  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 -6545
  29. package/crates/team-agent/src/cli/models.rs +0 -1206
  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/schedule.rs +0 -175
  34. package/crates/team-agent/src/cli/send/coordinator.rs +0 -164
  35. package/crates/team-agent/src/cli/send/mailbox.rs +0 -145
  36. package/crates/team-agent/src/cli/send/persist.rs +0 -156
  37. package/crates/team-agent/src/cli/send/presentation.rs +0 -370
  38. package/crates/team-agent/src/cli/send/resolve.rs +0 -573
  39. package/crates/team-agent/src/cli/send.rs +0 -199
  40. package/crates/team-agent/src/cli/shutdown_socket.rs +0 -288
  41. package/crates/team-agent/src/cli/spec.rs +0 -165
  42. package/crates/team-agent/src/cli/status.rs +0 -280
  43. package/crates/team-agent/src/cli/status_port/agents.rs +0 -358
  44. package/crates/team-agent/src/cli/status_port/approvals.rs +0 -79
  45. package/crates/team-agent/src/cli/status_port/brief.rs +0 -1981
  46. package/crates/team-agent/src/cli/status_port/compact.rs +0 -240
  47. package/crates/team-agent/src/cli/status_port/format.rs +0 -146
  48. package/crates/team-agent/src/cli/status_port/inbox.rs +0 -62
  49. package/crates/team-agent/src/cli/status_port/runtime.rs +0 -197
  50. package/crates/team-agent/src/cli/status_port/snapshot.rs +0 -208
  51. package/crates/team-agent/src/cli/status_port/store.rs +0 -416
  52. package/crates/team-agent/src/cli/status_port/tests.rs +0 -90
  53. package/crates/team-agent/src/cli/status_port.rs +0 -92
  54. package/crates/team-agent/src/cli/tests/base.rs +0 -885
  55. package/crates/team-agent/src/cli/tests/divergence.rs +0 -518
  56. package/crates/team-agent/src/cli/tests/lane_c.rs +0 -453
  57. package/crates/team-agent/src/cli/tests/leader_watch.rs +0 -322
  58. package/crates/team-agent/src/cli/tests/main_preserved.rs +0 -430
  59. package/crates/team-agent/src/cli/tests/missing_subcommands.rs +0 -336
  60. package/crates/team-agent/src/cli/tests/mod.rs +0 -137
  61. package/crates/team-agent/src/cli/tests/named_address.rs +0 -761
  62. package/crates/team-agent/src/cli/tests/parser_safety.rs +0 -383
  63. package/crates/team-agent/src/cli/tests/run_delegation.rs +0 -484
  64. package/crates/team-agent/src/cli/tests/shutdown_kill_plan.rs +0 -2179
  65. package/crates/team-agent/src/cli/tests/status_brief.rs +0 -1514
  66. package/crates/team-agent/src/cli/tests/status_send.rs +0 -888
  67. package/crates/team-agent/src/cli/tests/verb_install_skill.rs +0 -93
  68. package/crates/team-agent/src/cli/tests/verb_profile.rs +0 -392
  69. package/crates/team-agent/src/cli/triage.rs +0 -234
  70. package/crates/team-agent/src/cli/types.rs +0 -591
  71. package/crates/team-agent/src/codex_app_server.rs +0 -546
  72. package/crates/team-agent/src/communication_mode/mod.rs +0 -56
  73. package/crates/team-agent/src/compiler/tests.rs +0 -827
  74. package/crates/team-agent/src/compiler.rs +0 -890
  75. package/crates/team-agent/src/conpty/backend.rs +0 -829
  76. package/crates/team-agent/src/conpty/mod.rs +0 -33
  77. package/crates/team-agent/src/contract_runtime/backend.rs +0 -1744
  78. package/crates/team-agent/src/contract_runtime/commands.rs +0 -671
  79. package/crates/team-agent/src/contract_runtime/config.rs +0 -364
  80. package/crates/team-agent/src/contract_runtime/config_tests.rs +0 -76
  81. package/crates/team-agent/src/contract_runtime/discovery.rs +0 -449
  82. package/crates/team-agent/src/contract_runtime/fork.rs +0 -361
  83. package/crates/team-agent/src/contract_runtime/forward.rs +0 -288
  84. package/crates/team-agent/src/contract_runtime/framework.rs +0 -367
  85. package/crates/team-agent/src/contract_runtime/mcp.rs +0 -394
  86. package/crates/team-agent/src/contract_runtime/mod.rs +0 -17
  87. package/crates/team-agent/src/contract_runtime/prompt.rs +0 -216
  88. package/crates/team-agent/src/contract_runtime/pump.rs +0 -271
  89. package/crates/team-agent/src/contract_runtime/registry.rs +0 -553
  90. package/crates/team-agent/src/contract_runtime/workspace.rs +0 -228
  91. package/crates/team-agent/src/coordinator/backoff.rs +0 -741
  92. package/crates/team-agent/src/coordinator/conpty_shim.rs +0 -805
  93. package/crates/team-agent/src/coordinator/health.rs +0 -1185
  94. package/crates/team-agent/src/coordinator/mod.rs +0 -119
  95. package/crates/team-agent/src/coordinator/orphan.rs +0 -110
  96. package/crates/team-agent/src/coordinator/runtime_detectors.rs +0 -798
  97. package/crates/team-agent/src/coordinator/runtime_observation.rs +0 -84
  98. package/crates/team-agent/src/coordinator/steps/abnormal.rs +0 -2309
  99. package/crates/team-agent/src/coordinator/steps/delivery.rs +0 -15
  100. package/crates/team-agent/src/coordinator/steps/health_sync.rs +0 -15
  101. package/crates/team-agent/src/coordinator/steps/mod.rs +0 -126
  102. package/crates/team-agent/src/coordinator/steps/persist.rs +0 -15
  103. package/crates/team-agent/src/coordinator/steps/runtime_prompts.rs +0 -15
  104. package/crates/team-agent/src/coordinator/steps/session_gate.rs +0 -16
  105. package/crates/team-agent/src/coordinator/tests/a0_lostupdate.rs +0 -158
  106. package/crates/team-agent/src/coordinator/tests/abnormal.rs +0 -312
  107. package/crates/team-agent/src/coordinator/tests/api_error_recovery.rs +0 -300
  108. package/crates/team-agent/src/coordinator/tests/basics.rs +0 -211
  109. package/crates/team-agent/src/coordinator/tests/daemon.rs +0 -514
  110. package/crates/team-agent/src/coordinator/tests/energy.rs +0 -549
  111. package/crates/team-agent/src/coordinator/tests/health_sync.rs +0 -503
  112. package/crates/team-agent/src/coordinator/tests/main_preserved.rs +0 -186
  113. package/crates/team-agent/src/coordinator/tests/mod.rs +0 -295
  114. package/crates/team-agent/src/coordinator/tests/s3_bounded.rs +0 -207
  115. package/crates/team-agent/src/coordinator/tests/spine.rs +0 -308
  116. package/crates/team-agent/src/coordinator/tests/takeover.rs +0 -286
  117. package/crates/team-agent/src/coordinator/tests/tick_core.rs +0 -237
  118. package/crates/team-agent/src/coordinator/tick.rs +0 -3024
  119. package/crates/team-agent/src/coordinator/types.rs +0 -540
  120. package/crates/team-agent/src/db/agent_health_capture.rs +0 -126
  121. package/crates/team-agent/src/db/message_store.rs +0 -1527
  122. package/crates/team-agent/src/db/migration.rs +0 -984
  123. package/crates/team-agent/src/db/mod.rs +0 -26
  124. package/crates/team-agent/src/db/schema.rs +0 -663
  125. package/crates/team-agent/src/diagnose/comms.rs +0 -242
  126. package/crates/team-agent/src/diagnose/mod.rs +0 -44
  127. package/crates/team-agent/src/diagnose/orphans.rs +0 -889
  128. package/crates/team-agent/src/direct_delivery.rs +0 -368
  129. package/crates/team-agent/src/event_log.rs +0 -502
  130. package/crates/team-agent/src/fake_worker.rs +0 -303
  131. package/crates/team-agent/src/inbox_store.rs +0 -169
  132. package/crates/team-agent/src/kill_audit.rs +0 -106
  133. package/crates/team-agent/src/layout/manager.rs +0 -248
  134. package/crates/team-agent/src/layout/mod.rs +0 -36
  135. package/crates/team-agent/src/layout/overlay.rs +0 -134
  136. package/crates/team-agent/src/layout/placement.rs +0 -52
  137. package/crates/team-agent/src/layout/recovery.rs +0 -106
  138. package/crates/team-agent/src/layout/runtime_sessions.rs +0 -317
  139. package/crates/team-agent/src/layout/sessions.rs +0 -294
  140. package/crates/team-agent/src/layout/tmux_endpoint.rs +0 -165
  141. package/crates/team-agent/src/layout/worker_env.rs +0 -721
  142. package/crates/team-agent/src/layout/worker_window_helpers.rs +0 -37
  143. package/crates/team-agent/src/leader/helpers.rs +0 -178
  144. package/crates/team-agent/src/leader/incident.rs +0 -6
  145. package/crates/team-agent/src/leader/lease.rs +0 -3356
  146. package/crates/team-agent/src/leader/mod.rs +0 -104
  147. package/crates/team-agent/src/leader/owner_bind.rs +0 -400
  148. package/crates/team-agent/src/leader/prompt.rs +0 -905
  149. package/crates/team-agent/src/leader/provider_attribution.rs +0 -247
  150. package/crates/team-agent/src/leader/rediscover/tests.rs +0 -689
  151. package/crates/team-agent/src/leader/rediscover.rs +0 -1192
  152. package/crates/team-agent/src/leader/registry.rs +0 -888
  153. package/crates/team-agent/src/leader/start.rs +0 -4501
  154. package/crates/team-agent/src/leader/takeover.rs +0 -65
  155. package/crates/team-agent/src/leader/tests/basics.rs +0 -337
  156. package/crates/team-agent/src/leader/tests/byte_findings.rs +0 -355
  157. package/crates/team-agent/src/leader/tests/claim_leader_mailbox_flush_contract.rs +0 -544
  158. package/crates/team-agent/src/leader/tests/historical_inventory_upgrade_gate_red.rs +0 -624
  159. package/crates/team-agent/src/leader/tests/identity.rs +0 -465
  160. package/crates/team-agent/src/leader/tests/identity_session_names.rs +0 -42
  161. package/crates/team-agent/src/leader/tests/idle.rs +0 -113
  162. package/crates/team-agent/src/leader/tests/lease_api.rs +0 -520
  163. package/crates/team-agent/src/leader/tests/lease_claim.rs +0 -629
  164. package/crates/team-agent/src/leader/tests/mod.rs +0 -106
  165. package/crates/team-agent/src/leader/tests/prompt_contract.rs +0 -268
  166. package/crates/team-agent/src/leader/tests/rediscover.rs +0 -403
  167. package/crates/team-agent/src/leader/tests/rehomed_env.rs +0 -83
  168. package/crates/team-agent/src/leader/tests/team_in_team_state_scope_red.rs +0 -1273
  169. package/crates/team-agent/src/leader/tests/terminal_and_replay_vs_rerender_invariants_red.rs +0 -417
  170. package/crates/team-agent/src/leader/tests/wake_start_owner.rs +0 -168
  171. package/crates/team-agent/src/leader/types.rs +0 -534
  172. package/crates/team-agent/src/lib.rs +0 -147
  173. package/crates/team-agent/src/lifecycle/helpers.rs +0 -212
  174. package/crates/team-agent/src/lifecycle/launch/add_agent.rs +0 -881
  175. package/crates/team-agent/src/lifecycle/launch/add_agent_state.rs +0 -598
  176. package/crates/team-agent/src/lifecycle/launch/agent_state.rs +0 -332
  177. package/crates/team-agent/src/lifecycle/launch/clone_agent.rs +0 -204
  178. package/crates/team-agent/src/lifecycle/launch/fork_agent.rs +0 -107
  179. package/crates/team-agent/src/lifecycle/launch/fork_entry.rs +0 -144
  180. package/crates/team-agent/src/lifecycle/launch/identity.rs +0 -674
  181. package/crates/team-agent/src/lifecycle/launch/layout.rs +0 -350
  182. package/crates/team-agent/src/lifecycle/launch/leader_context.rs +0 -589
  183. package/crates/team-agent/src/lifecycle/launch/mcp_config.rs +0 -160
  184. package/crates/team-agent/src/lifecycle/launch/ownership.rs +0 -105
  185. package/crates/team-agent/src/lifecycle/launch/pi_mcp.rs +0 -899
  186. package/crates/team-agent/src/lifecycle/launch/pi_mcp_extension.js +0 -225
  187. package/crates/team-agent/src/lifecycle/launch/plan.rs +0 -269
  188. package/crates/team-agent/src/lifecycle/launch/quick_start.rs +0 -5200
  189. package/crates/team-agent/src/lifecycle/launch/quick_start_transport.rs +0 -368
  190. package/crates/team-agent/src/lifecycle/launch/readiness.rs +0 -519
  191. package/crates/team-agent/src/lifecycle/launch/role_source.rs +0 -287
  192. package/crates/team-agent/src/lifecycle/launch/spawn.rs +0 -473
  193. package/crates/team-agent/src/lifecycle/launch/spec_state.rs +0 -801
  194. package/crates/team-agent/src/lifecycle/launch/state_projection.rs +0 -624
  195. package/crates/team-agent/src/lifecycle/launch/worker_env.rs +0 -558
  196. package/crates/team-agent/src/lifecycle/launch.rs +0 -557
  197. package/crates/team-agent/src/lifecycle/lock.rs +0 -350
  198. package/crates/team-agent/src/lifecycle/mod.rs +0 -79
  199. package/crates/team-agent/src/lifecycle/pane_input_lock.rs +0 -239
  200. package/crates/team-agent/src/lifecycle/profile_launch.rs +0 -1067
  201. package/crates/team-agent/src/lifecycle/profile_smoke.rs +0 -557
  202. package/crates/team-agent/src/lifecycle/restart/agent.rs +0 -2199
  203. package/crates/team-agent/src/lifecycle/restart/avatar.rs +0 -1798
  204. package/crates/team-agent/src/lifecycle/restart/claude_fork.rs +0 -163
  205. package/crates/team-agent/src/lifecycle/restart/common.rs +0 -2362
  206. package/crates/team-agent/src/lifecycle/restart/orchestrator.rs +0 -65
  207. package/crates/team-agent/src/lifecycle/restart/preflight.rs +0 -113
  208. package/crates/team-agent/src/lifecycle/restart/rebuild.rs +0 -5135
  209. package/crates/team-agent/src/lifecycle/restart/remove.rs +0 -1504
  210. package/crates/team-agent/src/lifecycle/restart/selection.rs +0 -559
  211. package/crates/team-agent/src/lifecycle/restart/team_state.rs +0 -329
  212. package/crates/team-agent/src/lifecycle/restart.rs +0 -227
  213. package/crates/team-agent/src/lifecycle/role_config.rs +0 -1230
  214. package/crates/team-agent/src/lifecycle/tests/acceptance_b_batch_red.rs +0 -1021
  215. package/crates/team-agent/src/lifecycle/tests/agent_ops.rs +0 -1205
  216. package/crates/team-agent/src/lifecycle/tests/b0_legacy_snapshot_nonauthority_contract.rs +0 -265
  217. package/crates/team-agent/src/lifecycle/tests/b0_reader_hideone_audit_contract.rs +0 -490
  218. package/crates/team-agent/src/lifecycle/tests/behavioral_diff_264_red.rs +0 -656
  219. package/crates/team-agent/src/lifecycle/tests/claude_compatible_config_red.rs +0 -325
  220. package/crates/team-agent/src/lifecycle/tests/claude_profile_launch_red.rs +0 -447
  221. package/crates/team-agent/src/lifecycle/tests/cli_argv_routing_red.rs +0 -1638
  222. package/crates/team-agent/src/lifecycle/tests/clone_agent_preserves_source_tools.rs +0 -427
  223. package/crates/team-agent/src/lifecycle/tests/clone_fork_copilot_perms_red.rs +0 -770
  224. package/crates/team-agent/src/lifecycle/tests/communication_mode_runtime_contract_red.rs +0 -419
  225. package/crates/team-agent/src/lifecycle/tests/copilot_provider_red.rs +0 -2035
  226. package/crates/team-agent/src/lifecycle/tests/core.rs +0 -1327
  227. package/crates/team-agent/src/lifecycle/tests/f032_startup_prompt_best_effort_red.rs +0 -315
  228. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_g0.stdout.txt +0 -222
  229. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_spaced_ids.stdout.txt +0 -9
  230. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_native_mcp_host.mjs +0 -72
  231. package/crates/team-agent/src/lifecycle/tests/gate_fixtures.rs +0 -562
  232. package/crates/team-agent/src/lifecycle/tests/grok_require_explicit_model_red.rs +0 -110
  233. package/crates/team-agent/src/lifecycle/tests/harvest2_a_batch_red.rs +0 -512
  234. package/crates/team-agent/src/lifecycle/tests/host_cotenant_death_p0_contract.rs +0 -921
  235. package/crates/team-agent/src/lifecycle/tests/issue238_codex_effort_contract.rs +0 -68
  236. package/crates/team-agent/src/lifecycle/tests/lane_ops.rs +0 -1851
  237. package/crates/team-agent/src/lifecycle/tests/launch_spawn.rs +0 -3983
  238. package/crates/team-agent/src/lifecycle/tests/lifecycle_lock.rs +0 -339
  239. package/crates/team-agent/src/lifecycle/tests/lifecycle_rollback_red.rs +0 -596
  240. package/crates/team-agent/src/lifecycle/tests/main_preserved.rs +0 -513
  241. package/crates/team-agent/src/lifecycle/tests/mcp_tool_name_format_red.rs +0 -69
  242. package/crates/team-agent/src/lifecycle/tests/phase_b_contracts.rs +0 -824
  243. package/crates/team-agent/src/lifecycle/tests/phase_golden.rs +0 -723
  244. package/crates/team-agent/src/lifecycle/tests/pi_catalog_red.rs +0 -164
  245. package/crates/team-agent/src/lifecycle/tests/pi_command_red.rs +0 -200
  246. package/crates/team-agent/src/lifecycle/tests/pi_compiler_red.rs +0 -210
  247. package/crates/team-agent/src/lifecycle/tests/pi_dual_entry_red.rs +0 -527
  248. package/crates/team-agent/src/lifecycle/tests/pi_executable_mcp_red.rs +0 -1062
  249. package/crates/team-agent/src/lifecycle/tests/pi_fork_session_inheritance_red.rs +0 -1419
  250. package/crates/team-agent/src/lifecycle/tests/pi_lifecycle_doctor_red.rs +0 -98
  251. package/crates/team-agent/src/lifecycle/tests/pi_native_mcp_capability_red.rs +0 -550
  252. package/crates/team-agent/src/lifecycle/tests/pi_session_delivery_red.rs +0 -226
  253. package/crates/team-agent/src/lifecycle/tests/quick_start_worker_readiness_red.rs +0 -332
  254. package/crates/team-agent/src/lifecycle/tests/realmachine_clusters_1_6_red.rs +0 -786
  255. package/crates/team-agent/src/lifecycle/tests/realmachine_residual_g1_g4_red.rs +0 -648
  256. package/crates/team-agent/src/lifecycle/tests/restart.rs +0 -185
  257. package/crates/team-agent/src/lifecycle/tests/restart_build_before_destroy_0540_contract.rs +0 -1053
  258. package/crates/team-agent/src/lifecycle/tests/restart_liveness_red.rs +0 -679
  259. package/crates/team-agent/src/lifecycle/tests/restart_rebind_hotfix_252_red.rs +0 -1126
  260. package/crates/team-agent/src/lifecycle/tests/restart_session_capture_red.rs +0 -153
  261. package/crates/team-agent/src/lifecycle/tests/resume_recover_red.rs +0 -427
  262. package/crates/team-agent/src/lifecycle/tests/stale_team_saveconflict_contract.rs +0 -431
  263. package/crates/team-agent/src/lifecycle/tests/startup_latency_contract.rs +0 -1066
  264. package/crates/team-agent/src/lifecycle/tests/status_credential_redaction_contract.rs +0 -876
  265. package/crates/team-agent/src/lifecycle/tests/subprep_codex_trust_roundtrip_red.rs +0 -1026
  266. package/crates/team-agent/src/lifecycle/tests/swallow_batch4_semantics_red.rs +0 -342
  267. package/crates/team-agent/src/lifecycle/tests/team_in_team_identity_scope_red.rs +0 -543
  268. package/crates/team-agent/src/lifecycle/tests/team_in_team_sibling_quick_start_red.rs +0 -1103
  269. package/crates/team-agent/src/lifecycle/tests/team_in_team_state_scope_red.rs +0 -1276
  270. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_roster_red.rs +0 -145
  271. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_txn_red.rs +0 -603
  272. package/crates/team-agent/src/lifecycle/tests/test_isolation_escape_contract.rs +0 -936
  273. package/crates/team-agent/src/lifecycle/tests/upgrade_compat_0211_red.rs +0 -970
  274. package/crates/team-agent/src/lifecycle/tests/verify_rs031_window_consistency_red.rs +0 -995
  275. package/crates/team-agent/src/lifecycle/tests/worker_spawn_env_red.rs +0 -836
  276. package/crates/team-agent/src/lifecycle/tests.rs +0 -105
  277. package/crates/team-agent/src/lifecycle/types.rs +0 -877
  278. package/crates/team-agent/src/lifecycle/worker_command_context.rs +0 -363
  279. package/crates/team-agent/src/main.rs +0 -52
  280. package/crates/team-agent/src/mcp_server/helpers.rs +0 -510
  281. package/crates/team-agent/src/mcp_server/lifecycle_tools/mod.rs +0 -6
  282. package/crates/team-agent/src/mcp_server/lifecycle_tools/state_status.rs +0 -43
  283. package/crates/team-agent/src/mcp_server/mod.rs +0 -119
  284. package/crates/team-agent/src/mcp_server/normalize.rs +0 -485
  285. package/crates/team-agent/src/mcp_server/readiness.rs +0 -527
  286. package/crates/team-agent/src/mcp_server/readiness_tests.rs +0 -348
  287. package/crates/team-agent/src/mcp_server/tests/golden.rs +0 -285
  288. package/crates/team-agent/src/mcp_server/tests/normalize.rs +0 -247
  289. package/crates/team-agent/src/mcp_server/tests/scoped.rs +0 -158
  290. package/crates/team-agent/src/mcp_server/tests/send.rs +0 -353
  291. package/crates/team-agent/src/mcp_server/tests/tools.rs +0 -341
  292. package/crates/team-agent/src/mcp_server/tests/wire.rs +0 -254
  293. package/crates/team-agent/src/mcp_server/tests.rs +0 -43
  294. package/crates/team-agent/src/mcp_server/tools.rs +0 -889
  295. package/crates/team-agent/src/mcp_server/types.rs +0 -396
  296. package/crates/team-agent/src/mcp_server/wire.rs +0 -867
  297. package/crates/team-agent/src/messaging/activity.rs +0 -461
  298. package/crates/team-agent/src/messaging/address.rs +0 -87
  299. package/crates/team-agent/src/messaging/delivery.rs +0 -3727
  300. package/crates/team-agent/src/messaging/delivery_consumption_tests.rs +0 -234
  301. package/crates/team-agent/src/messaging/enter_rescue.rs +0 -362
  302. package/crates/team-agent/src/messaging/enter_rescue_tests.rs +0 -633
  303. package/crates/team-agent/src/messaging/helpers.rs +0 -336
  304. package/crates/team-agent/src/messaging/leader_channel.rs +0 -287
  305. package/crates/team-agent/src/messaging/leader_receiver.rs +0 -786
  306. package/crates/team-agent/src/messaging/mod.rs +0 -167
  307. package/crates/team-agent/src/messaging/persist.rs +0 -377
  308. package/crates/team-agent/src/messaging/presentation.rs +0 -417
  309. package/crates/team-agent/src/messaging/reminders.rs +0 -316
  310. package/crates/team-agent/src/messaging/results/collection_tests.rs +0 -719
  311. package/crates/team-agent/src/messaging/results.rs +0 -1415
  312. package/crates/team-agent/src/messaging/scheduler.rs +0 -223
  313. package/crates/team-agent/src/messaging/selftest.rs +0 -315
  314. package/crates/team-agent/src/messaging/send.rs +0 -981
  315. package/crates/team-agent/src/messaging/tests/basic.rs +0 -346
  316. package/crates/team-agent/src/messaging/tests/dup_inject.rs +0 -657
  317. package/crates/team-agent/src/messaging/tests/e23.rs +0 -49
  318. package/crates/team-agent/src/messaging/tests/leader_channel.rs +0 -169
  319. package/crates/team-agent/src/messaging/tests/leader_inject_acceptance.rs +0 -817
  320. package/crates/team-agent/src/messaging/tests/main_preserved.rs +0 -85
  321. package/crates/team-agent/src/messaging/tests/mod.rs +0 -306
  322. package/crates/team-agent/src/messaging/tests/runtime.rs +0 -3549
  323. package/crates/team-agent/src/messaging/tests/spine.rs +0 -853
  324. package/crates/team-agent/src/messaging/tests/wave2.rs +0 -381
  325. package/crates/team-agent/src/messaging/trust.rs +0 -215
  326. package/crates/team-agent/src/messaging/types.rs +0 -472
  327. package/crates/team-agent/src/messaging/wait.rs +0 -366
  328. package/crates/team-agent/src/messaging/watchers.rs +0 -916
  329. package/crates/team-agent/src/model/enums.rs +0 -356
  330. package/crates/team-agent/src/model/errors.rs +0 -18
  331. package/crates/team-agent/src/model/ids.rs +0 -165
  332. package/crates/team-agent/src/model/mod.rs +0 -29
  333. package/crates/team-agent/src/model/name_similarity.rs +0 -252
  334. package/crates/team-agent/src/model/pane_authority_refusal.rs +0 -359
  335. package/crates/team-agent/src/model/paths.rs +0 -257
  336. package/crates/team-agent/src/model/routing.rs +0 -387
  337. package/crates/team-agent/src/model/spec.rs +0 -1184
  338. package/crates/team-agent/src/model/task_graph.rs +0 -321
  339. package/crates/team-agent/src/model/testdata/fuzz.golden.yaml +0 -43
  340. package/crates/team-agent/src/model/testdata/fuzz.yaml +0 -43
  341. package/crates/team-agent/src/model/testdata/spec_invalid_a.yaml +0 -209
  342. package/crates/team-agent/src/model/testdata/team.spec.golden.yaml +0 -208
  343. package/crates/team-agent/src/model/testdata/team.spec.yaml +0 -208
  344. package/crates/team-agent/src/model/yaml/tests.rs +0 -188
  345. package/crates/team-agent/src/model/yaml.rs +0 -802
  346. package/crates/team-agent/src/os_probe.rs +0 -280
  347. package/crates/team-agent/src/packaging/install.rs +0 -219
  348. package/crates/team-agent/src/packaging/migrate.rs +0 -38
  349. package/crates/team-agent/src/packaging/mod.rs +0 -91
  350. package/crates/team-agent/src/packaging/repair.rs +0 -33
  351. package/crates/team-agent/src/packaging/tests.rs +0 -822
  352. package/crates/team-agent/src/packaging/types.rs +0 -417
  353. package/crates/team-agent/src/platform/argv.rs +0 -331
  354. package/crates/team-agent/src/platform/errors.rs +0 -104
  355. package/crates/team-agent/src/platform/file_lock.rs +0 -279
  356. package/crates/team-agent/src/platform/mod.rs +0 -5
  357. package/crates/team-agent/src/platform/process.rs +0 -545
  358. package/crates/team-agent/src/provider/adapter.rs +0 -1150
  359. package/crates/team-agent/src/provider/adapters/claude.rs +0 -78
  360. package/crates/team-agent/src/provider/adapters/claude_fork.rs +0 -131
  361. package/crates/team-agent/src/provider/adapters/copilot.rs +0 -75
  362. package/crates/team-agent/src/provider/adapters/copilot_fork.rs +0 -307
  363. package/crates/team-agent/src/provider/adapters/fake.rs +0 -18
  364. package/crates/team-agent/src/provider/adapters/mod.rs +0 -30
  365. package/crates/team-agent/src/provider/adapters/pi.rs +0 -106
  366. package/crates/team-agent/src/provider/approvals/mod.rs +0 -3
  367. package/crates/team-agent/src/provider/approvals/parsing.rs +0 -586
  368. package/crates/team-agent/src/provider/approvals/runtime_prompts.rs +0 -205
  369. package/crates/team-agent/src/provider/argv_route.rs +0 -405
  370. package/crates/team-agent/src/provider/bypass_flags.rs +0 -116
  371. package/crates/team-agent/src/provider/classify.rs +0 -708
  372. package/crates/team-agent/src/provider/command_helpers.rs +0 -45
  373. package/crates/team-agent/src/provider/faults.rs +0 -165
  374. package/crates/team-agent/src/provider/helpers.rs +0 -52
  375. package/crates/team-agent/src/provider/mod.rs +0 -78
  376. package/crates/team-agent/src/provider/model_catalog.rs +0 -910
  377. package/crates/team-agent/src/provider/session/capture.rs +0 -2731
  378. package/crates/team-agent/src/provider/session/context_fork/claude.rs +0 -123
  379. package/crates/team-agent/src/provider/session/context_fork/outcome.rs +0 -172
  380. package/crates/team-agent/src/provider/session/context_fork.rs +0 -396
  381. package/crates/team-agent/src/provider/session/mod.rs +0 -36
  382. package/crates/team-agent/src/provider/session/resume.rs +0 -269
  383. package/crates/team-agent/src/provider/session_scan/claude.rs +0 -523
  384. package/crates/team-agent/src/provider/session_scan/common/tests.rs +0 -316
  385. package/crates/team-agent/src/provider/session_scan/common.rs +0 -654
  386. package/crates/team-agent/src/provider/session_scan/copilot.rs +0 -280
  387. package/crates/team-agent/src/provider/session_scan/pi.rs +0 -185
  388. package/crates/team-agent/src/provider/session_scan.rs +0 -71
  389. package/crates/team-agent/src/provider/startup_prompt.rs +0 -757
  390. package/crates/team-agent/src/provider/submit_now.rs +0 -71
  391. package/crates/team-agent/src/provider/testdata/copilot-ready-marker.txt +0 -5
  392. package/crates/team-agent/src/provider/testdata/copilot-trust-prompt.txt +0 -19
  393. package/crates/team-agent/src/provider/testdata/grok-models-authenticated.stdout +0 -9
  394. package/crates/team-agent/src/provider/testdata/grok-models-unauthenticated.stdout +0 -7
  395. package/crates/team-agent/src/provider/tests/adapter.rs +0 -441
  396. package/crates/team-agent/src/provider/tests/classify.rs +0 -148
  397. package/crates/team-agent/src/provider/tests/command_helpers.rs +0 -35
  398. package/crates/team-agent/src/provider/tests/copilot_fork.rs +0 -191
  399. package/crates/team-agent/src/provider/tests/faults.rs +0 -200
  400. package/crates/team-agent/src/provider/tests/idle.rs +0 -177
  401. package/crates/team-agent/src/provider/tests/wire.rs +0 -213
  402. package/crates/team-agent/src/provider/tests.rs +0 -32
  403. package/crates/team-agent/src/provider/types.rs +0 -529
  404. package/crates/team-agent/src/provider/wire.rs +0 -394
  405. package/crates/team-agent/src/redaction.rs +0 -259
  406. package/crates/team-agent/src/state/abnormal_watch/tests/mod.rs +0 -248
  407. package/crates/team-agent/src/state/abnormal_watch.rs +0 -144
  408. package/crates/team-agent/src/state/identity.rs +0 -914
  409. package/crates/team-agent/src/state/identity_keys.rs +0 -132
  410. package/crates/team-agent/src/state/mod.rs +0 -74
  411. package/crates/team-agent/src/state/owner_gate.rs +0 -482
  412. package/crates/team-agent/src/state/ownership.rs +0 -563
  413. package/crates/team-agent/src/state/paths.rs +0 -395
  414. package/crates/team-agent/src/state/persist.rs +0 -3811
  415. package/crates/team-agent/src/state/projection.rs +0 -1508
  416. package/crates/team-agent/src/state/repository/intent.rs +0 -14
  417. package/crates/team-agent/src/state/repository/tests.rs +0 -184
  418. package/crates/team-agent/src/state/repository.rs +0 -866
  419. package/crates/team-agent/src/state/selector.rs +0 -160
  420. package/crates/team-agent/src/state/testdata/state-rich.canonical.json +0 -133
  421. package/crates/team-agent/src/test_support/models_timeout_fixture.rs +0 -144
  422. package/crates/team-agent/src/tmux_backend/enter_rescue.rs +0 -325
  423. package/crates/team-agent/src/tmux_backend/enter_rescue_tests.rs +0 -432
  424. package/crates/team-agent/src/tmux_backend/native_input.rs +0 -513
  425. package/crates/team-agent/src/tmux_backend/native_input_tests.rs +0 -742
  426. package/crates/team-agent/src/tmux_backend/tests.rs +0 -4103
  427. package/crates/team-agent/src/tmux_backend.rs +0 -4492
  428. package/crates/team-agent/src/topology.rs +0 -537
  429. package/crates/team-agent/src/transport/enter_rescue.rs +0 -166
  430. package/crates/team-agent/src/transport/native_input.rs +0 -491
  431. package/crates/team-agent/src/transport/test_support.rs +0 -743
  432. package/crates/team-agent/src/transport/tests/behavior.rs +0 -326
  433. package/crates/team-agent/src/transport/tests/mod.rs +0 -194
  434. package/crates/team-agent/src/transport/tests/wire.rs +0 -574
  435. package/crates/team-agent/src/transport.rs +0 -1655
  436. package/crates/team-agent/src/transport_factory.rs +0 -819
@@ -1,2731 +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 行;provider 字段决定要不要套 claude leader-marker 过滤
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 家族额外过滤 leader-marker transcript;其它 provider 无等价归属过滤
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
- // E57 postflight: read the agent's provider once; needed for the Claude
655
- // leader-marker filter below. Falls back to None on non-string / missing,
656
- // in which case the marker filter is skipped (only meaningful for Claude).
657
- let provider = previous
658
- .get("provider")
659
- .and_then(Value::as_str)
660
- .and_then(parse_provider);
661
- let events = crate::event_log::EventLog::new(workspace)
662
- .tail(0)
663
- .map_err(|e| ProviderError::Io(e.to_string()))?;
664
- let current_session = previous
665
- .get("session_id")
666
- .and_then(Value::as_str)
667
- .filter(|session| !session.is_empty());
668
- for event in events.iter().rev() {
669
- if !event_matches_agent(event, agent_id) {
670
- continue;
671
- }
672
- match event.get("event").and_then(Value::as_str) {
673
- Some("discard.session_tombstone") => return Ok(None),
674
- Some("session.captured") => {}
675
- _ => continue,
676
- }
677
- let Some(session_id) = event
678
- .get("session_id")
679
- .and_then(Value::as_str)
680
- .filter(|session| !session.is_empty())
681
- else {
682
- continue;
683
- };
684
- if current_session == Some(session_id) || exclude_session_ids.contains(session_id) {
685
- continue;
686
- }
687
- let Some(rollout_path) = event_rollout_path(event).filter(|path| path.exists()) else {
688
- continue;
689
- };
690
- // E57 postflight (lane-046-capture-gap): the capture allocator already
691
- // refuses Claude leader transcripts (P0 d39b5104,
692
- // provider/session_scan/claude.rs leader marker). Event-log
693
- // repair must apply the SAME filter — otherwise a stale `session.captured`
694
- // event from a pre-fix run (or from a window where the allocator was
695
- // bypassed) still pulls the 590MB leader transcript onto a worker on the
696
- // next restart (Mac mini repro: session_id=ea059b82 reassigned to
697
- // release-engineer via captured_via=event_log_repair). The check is
698
- // a no-op for non-Claude providers.
699
- if let Some(p) = provider {
700
- if crate::provider::session_scan::rollout_path_has_claude_leader_marker(
701
- p,
702
- &rollout_path,
703
- ) {
704
- continue;
705
- }
706
- }
707
- let session = SessionId::new(session_id.to_string());
708
- if !adapter.session_is_resumable(Some(&session), auth_mode)? {
709
- continue;
710
- }
711
- let mut repaired = previous.clone();
712
- if !repaired.is_object() {
713
- repaired = serde_json::json!({});
714
- }
715
- let Some(obj) = repaired.as_object_mut() else {
716
- continue;
717
- };
718
- // 0.4.6 tuple-atomic contract (audit §Capture 修改清单, line 113):
719
- // repair must yield a COMPLETE tuple. session_id + rollout_path are
720
- // already validated above; ensure captured_at + captured_via are
721
- // also always written (fall back to now() if the event has no ts).
722
- obj.insert("session_id".to_string(), serde_json::json!(session_id));
723
- obj.insert(
724
- "rollout_path".to_string(),
725
- serde_json::json!(rollout_path.to_string_lossy().to_string()),
726
- );
727
- let captured_at = event
728
- .get("ts")
729
- .and_then(Value::as_str)
730
- .filter(|ts| !ts.is_empty())
731
- .map(str::to_string)
732
- .unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
733
- obj.insert("captured_at".to_string(), serde_json::json!(captured_at));
734
- obj.insert(
735
- "captured_via".to_string(),
736
- serde_json::json!("event_log_repair"),
737
- );
738
- if let Some(confidence) = event.get("attribution_confidence").cloned() {
739
- obj.insert("attribution_confidence".to_string(), confidence);
740
- }
741
- obj.remove("attribution_ambiguous");
742
- return Ok(Some(repaired));
743
- }
744
- Ok(None)
745
- }
746
-
747
- fn event_matches_agent(event: &Value, agent_id: &str) -> bool {
748
- ["agent_id", "worker_id"]
749
- .iter()
750
- .any(|key| event.get(*key).and_then(Value::as_str) == Some(agent_id))
751
- }
752
-
753
- fn event_rollout_path(event: &Value) -> Option<PathBuf> {
754
- event
755
- .get("rollout_path")
756
- .or_else(|| event.get("transcript_path"))
757
- .and_then(Value::as_str)
758
- .filter(|path| !path.is_empty())
759
- .map(PathBuf::from)
760
- }
761
-
762
- /// ---
763
- /// purpose: 在「会话不完整」清单上再筛出真正被用过的席位——有 first_send_at 才算交互过
764
- /// params:
765
- /// state: 只读的 state JSON
766
- /// returns: 按 agent id 升序的子集
767
- /// contract:
768
- /// provides:
769
- /// - name: incomplete_interacted_resumable_agent_ids
770
- /// what: incomplete_resumable_agent_ids 的过滤视图,只读
771
- /// boundary:
772
- /// - 交互判据只看 first_send_at 非空,不看 last_result_at / pane 输出
773
- /// - 从没派过活的席位不进清单——沉默席位不算捕获失败
774
- /// ---
775
- pub fn incomplete_interacted_resumable_agent_ids(state: &Value) -> Vec<String> {
776
- let mut out = incomplete_resumable_agent_ids(state)
777
- .into_iter()
778
- .filter(|agent_id| {
779
- state
780
- .get("agents")
781
- .and_then(|agents| agents.get(agent_id))
782
- .and_then(|agent| agent.get("first_send_at"))
783
- .and_then(Value::as_str)
784
- .is_some_and(|value| !value.is_empty())
785
- })
786
- .collect::<Vec<_>>();
787
- out.sort();
788
- out
789
- }
790
-
791
- struct PendingSessionCapture {
792
- agent_id: String,
793
- provider: Provider,
794
- team_key: String,
795
- context: CaptureSessionContext,
796
- }
797
-
798
- fn pending_session_capture<F>(
799
- agent_id: &str,
800
- agent: &Value,
801
- adapter_for: &mut F,
802
- ) -> Option<PendingSessionCapture>
803
- where
804
- F: FnMut(Provider) -> Box<dyn ProviderAdapter>,
805
- {
806
- if agent.get("capture_state").and_then(Value::as_str) == Some("attribution_ambiguous") {
807
- return None;
808
- }
809
- let provider = incomplete_resumable_provider(agent, adapter_for)?;
810
- let spawn_cwd = agent
811
- .get("spawn_cwd")
812
- .and_then(Value::as_str)
813
- .filter(|cwd| !cwd.is_empty())?;
814
- // New cohorts carry a boundary and are filtered fail-closed by the
815
- // canonical scanner. Legacy rows may predate spawned_at; keep their
816
- // boundary absent so they can still use the allocator's identity,
817
- // collision, and unique-candidate guards instead of being skipped.
818
- let spawned_at = agent
819
- .get("spawned_at")
820
- .and_then(Value::as_str)
821
- .filter(|value| !value.is_empty())
822
- .map(str::to_string);
823
- let expected_session_id = agent
824
- .get("_pending_session_id")
825
- .and_then(Value::as_str)
826
- .filter(|value| !value.is_empty())
827
- .map(SessionId::new);
828
- if matches!(provider, Provider::Codex)
829
- && agent.get("capture_state").and_then(Value::as_str) == Some("pending_context_fork")
830
- && expected_session_id.is_none()
831
- {
832
- return None;
833
- }
834
- Some(PendingSessionCapture {
835
- agent_id: agent_id.to_string(),
836
- provider,
837
- team_key: agent
838
- .get("owner_team_id")
839
- .or_else(|| agent.get("team_key"))
840
- .and_then(Value::as_str)
841
- .filter(|s| !s.is_empty())
842
- .unwrap_or("current")
843
- .to_string(),
844
- context: CaptureSessionContext {
845
- agent_id: agent_id.to_string(),
846
- spawn_cwd: PathBuf::from(spawn_cwd),
847
- pane_id: agent
848
- .get("pane_id")
849
- .and_then(Value::as_str)
850
- .filter(|pane| !pane.is_empty())
851
- .map(str::to_string),
852
- pane_pid: agent
853
- .get("pane_pid")
854
- .and_then(Value::as_u64)
855
- .and_then(|pid| u32::try_from(pid).ok()),
856
- spawned_at,
857
- expected_session_id,
858
- provider_projects_root: agent
859
- .get("claude_projects_root")
860
- .and_then(Value::as_str)
861
- .filter(|value| !value.is_empty())
862
- .map(PathBuf::from),
863
- },
864
- })
865
- }
866
-
867
- fn incomplete_resumable_provider<F>(agent: &Value, adapter_for: &mut F) -> Option<Provider>
868
- where
869
- F: FnMut(Provider) -> Box<dyn ProviderAdapter>,
870
- {
871
- if crate::state::projection::agent_explicit_stop(agent)
872
- || agent
873
- .get("status")
874
- .and_then(Value::as_str)
875
- .is_some_and(|status| status != "running")
876
- {
877
- return None;
878
- }
879
- if agent_session_complete(agent) {
880
- return None;
881
- }
882
- let provider = agent
883
- .get("provider")
884
- .and_then(Value::as_str)
885
- .and_then(parse_provider)?;
886
- agent
887
- .get("spawn_cwd")
888
- .and_then(Value::as_str)
889
- .filter(|cwd| !cwd.is_empty())?;
890
- if !adapter_for(provider).caps().resume {
891
- return None;
892
- }
893
- Some(provider)
894
- }
895
-
896
- #[cfg(test)]
897
- mod stopped_capture_tests {
898
- use super::*;
899
-
900
- #[test]
901
- fn explicit_stop_is_checked_before_adapter_or_backing_probes() {
902
- for row in [
903
- serde_json::json!({"status":"stopped","provider":"pi","spawn_cwd":"/controlled"}),
904
- serde_json::json!({"status":"running","explicit_stop":true,"provider":"pi","spawn_cwd":"/controlled"}),
905
- serde_json::json!({"status":"running","explicit_stop":"false","provider":"pi","spawn_cwd":"/controlled"}),
906
- ] {
907
- assert!(incomplete_resumable_provider(&row, &mut |_| panic!("held seat reached adapter lookup")).is_none());
908
- }
909
- let mut calls = 0;
910
- let _ = incomplete_resumable_provider(
911
- &serde_json::json!({"status":"running","explicit_stop":false,"provider":"pi","spawn_cwd":"/controlled"}),
912
- &mut |provider| { calls += 1; crate::provider::get_adapter(provider) },
913
- );
914
- assert_eq!(calls, 1, "active control must still be eligible for capture");
915
- }
916
- }
917
-
918
- fn agent_session_complete(agent: &Value) -> bool {
919
- // RM-039-SESS-001 step 1 (architect verdict 2026-06-22): historically
920
- // this returned true the moment `rollout_path` was non-empty — even when
921
- // the file no longer existed on disk. That created a "stale-positive"
922
- // capture tuple: the worker had a session_id + a stored rollout_path,
923
- // but the provider had rotated/garbage-collected the actual transcript
924
- // file. `pending_session_capture` skipped agents whose
925
- // `agent_session_complete()` was true, so the runtime never recaptured
926
- // the now-broken backing, and downstream consumers saw the stale tuple
927
- // as authoritative.
928
- //
929
- // Fix: a non-empty `rollout_path` only counts as complete when the path
930
- // actually exists. session_id remains a required non-empty check
931
- // (architect directive: "Keep session_id non-empty as required; do not
932
- // infer context from event log alone unless the referenced transcript
933
- // path exists.").
934
- //
935
- // Blocker-2 Layer-1 (prerelease 0.4.0, architect bugs-prerelease-blockers.md §139):
936
- // existence alone is not enough — a small Claude session-metadata JSON
937
- // (~/.claude/sessions/<pid>.json, ~300-400 bytes, sessionId only, no
938
- // assistant/user records) used to satisfy this and prevent recapture of
939
- // the real .claude/projects/<cwd>/<sid>.jsonl transcript. For
940
- // Claude/ClaudeCode rollout paths, additionally require a recognizable
941
- // transcript lifecycle record (an assistant or user record). Other
942
- // providers keep existence-only semantics (codex 不可改项).
943
- let session_id_ok = agent
944
- .get("session_id")
945
- .and_then(Value::as_str)
946
- .is_some_and(|session| !session.is_empty());
947
- if !session_id_ok {
948
- return false;
949
- }
950
- // S1-CAPTURE-001 (0.4.8, CR M3 provider-agnostic): pending mismatch guard.
951
- // When fresh-start has written a new `_pending_session_id` but the old
952
- // authoritative `session_id` is still present and differs, the tuple is
953
- // STALE — the new process has a different session that has not been
954
- // captured yet. Returning true here would let capture skip this agent
955
- // and keep treating the old transcript as authoritative (the gate's
956
- // observed mis-attribution). Force re-capture by reporting incomplete.
957
- // The fresh-tuple clear in mark_agent_started (lifecycle/restart/agent.rs)
958
- // is the primary fix; this guard handles historical poison state where
959
- // both fields already coexist from a prior version.
960
- let pending = agent
961
- .get("_pending_session_id")
962
- .and_then(Value::as_str)
963
- .filter(|s| !s.is_empty());
964
- let current = agent
965
- .get("session_id")
966
- .and_then(Value::as_str)
967
- .filter(|s| !s.is_empty());
968
- if let (Some(pending), Some(current)) = (pending, current) {
969
- if pending != current {
970
- return false;
971
- }
972
- }
973
- let rollout_path = match agent
974
- .get("rollout_path")
975
- .and_then(Value::as_str)
976
- .filter(|path| !path.is_empty())
977
- {
978
- Some(path) => path,
979
- None => return false,
980
- };
981
- // 0.4.6 tuple-atomic contract (audit §Capture 修改清单, line 110):
982
- // a "complete" agent session requires the FULL authoritative tuple —
983
- // session_id + rollout_path + captured_at + captured_via. Without these
984
- // last two, a row is a partial tuple and capture must re-run.
985
- let captured_at_ok = agent
986
- .get("captured_at")
987
- .and_then(Value::as_str)
988
- .is_some_and(|ts| !ts.is_empty());
989
- let captured_via_ok = agent
990
- .get("captured_via")
991
- .and_then(Value::as_str)
992
- .is_some_and(|via| !via.is_empty());
993
- if !captured_at_ok || !captured_via_ok {
994
- return false;
995
- }
996
- let path = std::path::Path::new(rollout_path);
997
- if !path.exists() {
998
- return false;
999
- }
1000
- let provider_wire = agent.get("provider").and_then(Value::as_str).unwrap_or("");
1001
- if parse_provider(provider_wire).is_some_and(is_claude_family) {
1002
- return claude_rollout_has_lifecycle_records(path);
1003
- }
1004
- true
1005
- }
1006
-
1007
- /// Blocker-2 Layer-1 (prerelease 0.4.0): a Claude rollout file qualifies as
1008
- /// activity backing only when it contains at least one recognizable transcript
1009
- /// lifecycle record (top-level `type:"assistant"` or `type:"user"`). The
1010
- /// ~/.claude/sessions/<pid>.json metadata file has neither, so this returns
1011
- /// false for it and the runtime recaptures via the .claude/projects/<cwd>/
1012
- /// scan in adapter.rs. Bounded read so a large transcript is not slurped.
1013
- fn claude_rollout_has_lifecycle_records(path: &std::path::Path) -> bool {
1014
- use std::io::Read;
1015
- const MAX_BYTES: u64 = 65_536;
1016
- let Ok(file) = std::fs::File::open(path) else {
1017
- return false;
1018
- };
1019
- let mut bytes = Vec::new();
1020
- if file.take(MAX_BYTES).read_to_end(&mut bytes).is_err() {
1021
- return false;
1022
- }
1023
- let text = String::from_utf8_lossy(&bytes);
1024
- for line in text.lines() {
1025
- let trimmed = line.trim();
1026
- if trimmed.is_empty() {
1027
- continue;
1028
- }
1029
- let Ok(value) = serde_json::from_str::<serde_json::Value>(trimmed) else {
1030
- continue;
1031
- };
1032
- let kind = value.get("type").and_then(Value::as_str).unwrap_or("");
1033
- if matches!(kind, "assistant" | "user") {
1034
- return true;
1035
- }
1036
- }
1037
- false
1038
- }
1039
-
1040
- fn allocate_session_candidates(
1041
- pending: &[PendingSessionCapture],
1042
- candidates_by_agent: &BTreeMap<String, Vec<CapturedSessionCandidate>>,
1043
- claimed: &mut BTreeSet<String>,
1044
- ) -> (BTreeMap<String, CapturedSessionCandidate>, BTreeSet<String>) {
1045
- let mut assignments = BTreeMap::new();
1046
- let mut ambiguous = BTreeSet::new();
1047
-
1048
- // Stage 1 amendment (architect direction 2026-06-23, S1-CAPTURE-002 fix):
1049
- // ExpectedSessionId pre-pass. For each pending agent that carries an
1050
- // `_pending_session_id`, the strongest possible binding is the candidate
1051
- // whose `session_id` exactly matches that expected id. Run this BEFORE
1052
- // the existing PositiveAgentId / PathAgentId / global one-to-one passes,
1053
- // because the global one-to-one pass uses
1054
- // `remaining_agents.zip(candidates.into_values())` (BTreeMap sorted by
1055
- // candidate-key, not by agent ownership) and can produce CROSS
1056
- // assignments (claude-a → claude-b's transcript and vice versa) when two
1057
- // pending agents both have expected ids but no PositiveAgentId/PathAgentId
1058
- // hint — those would be rejected by the mismatch guard at apply time,
1059
- // leaving both agents `attribution_ambiguous` instead of correctly
1060
- // bound. With this pre-pass the global one-to-one only ever sees agents
1061
- // that have NO expected id (or whose expected candidate is unavailable
1062
- // / collides), and the cross-assignment hazard is eliminated.
1063
- for item in pending {
1064
- let Some(expected) = item.context.expected_session_id.as_ref() else {
1065
- continue;
1066
- };
1067
- let Some(agent_candidates) = candidates_by_agent.get(&item.agent_id) else {
1068
- continue;
1069
- };
1070
- let exact_matches: Vec<&CapturedSessionCandidate> = agent_candidates
1071
- .iter()
1072
- .filter(|candidate| {
1073
- candidate
1074
- .captured
1075
- .session_id
1076
- .as_ref()
1077
- .is_some_and(|sid| sid.as_str() == expected.as_str())
1078
- })
1079
- .filter(|candidate| !candidate_keys_collide(item, candidate, claimed))
1080
- .collect();
1081
- // Uniqueness requirement: only assign when the expected id maps to
1082
- // exactly one available candidate. Multiple matches or a colliding
1083
- // single match leave the agent for the ambiguity path below.
1084
- if exact_matches.len() == 1 {
1085
- let candidate = exact_matches[0].clone();
1086
- claimed.extend(captured_provider_session_keys(item, &candidate.captured));
1087
- assignments.insert(item.agent_id.clone(), candidate);
1088
- }
1089
- }
1090
-
1091
- for item in pending {
1092
- if assignments.contains_key(&item.agent_id) {
1093
- continue;
1094
- }
1095
- if let Some(candidate) = unique_available_candidate(
1096
- candidates_by_agent.get(&item.agent_id),
1097
- claimed,
1098
- CandidateMatchKind::PositiveAgentId,
1099
- item,
1100
- ) {
1101
- claimed.extend(captured_provider_session_keys(item, &candidate.captured));
1102
- assignments.insert(item.agent_id.clone(), candidate);
1103
- }
1104
- }
1105
- for item in pending {
1106
- if assignments.contains_key(&item.agent_id) {
1107
- continue;
1108
- }
1109
- if let Some(candidate) = unique_available_candidate(
1110
- candidates_by_agent.get(&item.agent_id),
1111
- claimed,
1112
- CandidateMatchKind::PathAgentId,
1113
- item,
1114
- ) {
1115
- claimed.extend(captured_provider_session_keys(item, &candidate.captured));
1116
- assignments.insert(item.agent_id.clone(), candidate);
1117
- }
1118
- }
1119
- allocate_global_one_to_one(pending, candidates_by_agent, claimed, &mut assignments);
1120
- for item in pending {
1121
- if assignments.contains_key(&item.agent_id) {
1122
- continue;
1123
- }
1124
- // P0 (lane-046-capture-gap): Claude without a framework expected
1125
- // session id must not accept the weak `Any` fallback.
1126
- if provider_no_expected_requires_positive_attribution(item) {
1127
- if candidates_by_agent
1128
- .get(&item.agent_id)
1129
- .is_some_and(|candidates| !candidates.is_empty())
1130
- {
1131
- ambiguous.insert(item.agent_id.clone());
1132
- }
1133
- continue;
1134
- }
1135
- // 0.5.x Codex cross-bind: a single provider-specific candidate may be
1136
- // captured when it has no conflicting embedded identity, but a same-cwd
1137
- // multi-candidate set must remain ambiguous instead of using weak
1138
- // sorted zip / Any attribution.
1139
- if codex_no_expected(item)
1140
- && candidates_by_agent
1141
- .get(&item.agent_id)
1142
- .is_some_and(|candidates| candidates.len() > 1)
1143
- {
1144
- ambiguous.insert(item.agent_id.clone());
1145
- continue;
1146
- }
1147
- match unique_available_candidate(
1148
- candidates_by_agent.get(&item.agent_id),
1149
- claimed,
1150
- CandidateMatchKind::Any,
1151
- item,
1152
- ) {
1153
- Some(candidate)
1154
- if codex_no_expected(item)
1155
- && candidate_is_visible_to_pending_peer(
1156
- item,
1157
- &candidate,
1158
- pending,
1159
- candidates_by_agent,
1160
- ) =>
1161
- {
1162
- ambiguous.insert(item.agent_id.clone());
1163
- }
1164
- Some(candidate) => {
1165
- claimed.extend(captured_provider_session_keys(item, &candidate.captured));
1166
- assignments.insert(item.agent_id.clone(), candidate);
1167
- }
1168
- None => {
1169
- if candidates_by_agent
1170
- .get(&item.agent_id)
1171
- .is_some_and(|candidates| !candidates.is_empty())
1172
- {
1173
- ambiguous.insert(item.agent_id.clone());
1174
- }
1175
- }
1176
- }
1177
- }
1178
- (assignments, ambiguous)
1179
- }
1180
-
1181
- fn candidate_is_visible_to_pending_peer(
1182
- owner: &PendingSessionCapture,
1183
- candidate: &CapturedSessionCandidate,
1184
- pending: &[PendingSessionCapture],
1185
- candidates_by_agent: &BTreeMap<String, Vec<CapturedSessionCandidate>>,
1186
- ) -> bool {
1187
- let owner_keys = captured_provider_session_keys(owner, &candidate.captured);
1188
- pending.iter().any(|peer| {
1189
- peer.agent_id != owner.agent_id
1190
- && peer.provider == owner.provider
1191
- && peer.team_key == owner.team_key
1192
- && candidates_by_agent
1193
- .get(&peer.agent_id)
1194
- .is_some_and(|candidates| {
1195
- candidates.iter().any(|peer_candidate| {
1196
- !owner_keys.is_disjoint(&captured_provider_session_keys(
1197
- peer,
1198
- &peer_candidate.captured,
1199
- ))
1200
- })
1201
- })
1202
- })
1203
- }
1204
-
1205
- fn allocate_global_one_to_one(
1206
- pending: &[PendingSessionCapture],
1207
- candidates_by_agent: &BTreeMap<String, Vec<CapturedSessionCandidate>>,
1208
- claimed: &mut BTreeSet<String>,
1209
- assignments: &mut BTreeMap<String, CapturedSessionCandidate>,
1210
- ) {
1211
- // P0 (lane-046-capture-gap + 0.5.x Codex cross-bind): exclude
1212
- // no-expected agents from the global one-to-one weak allocator. They must
1213
- // use PositiveAgentId, PathAgentId, or the per-agent unique-candidate path
1214
- // only.
1215
- let remaining_agents = pending
1216
- .iter()
1217
- .filter(|item| !assignments.contains_key(&item.agent_id))
1218
- .filter(|item| !provider_no_expected_disables_global_one_to_one(item))
1219
- .map(|item| item.agent_id.clone())
1220
- .collect::<Vec<_>>();
1221
- if remaining_agents.is_empty() {
1222
- return;
1223
- }
1224
- let mut candidates = BTreeMap::new();
1225
- for agent_id in &remaining_agents {
1226
- let Some(agent_candidates) = candidates_by_agent.get(agent_id) else {
1227
- return;
1228
- };
1229
- let Some(owner) = pending.iter().find(|item| item.agent_id == *agent_id) else {
1230
- continue;
1231
- };
1232
- for candidate in agent_candidates {
1233
- if candidate_keys_collide(owner, candidate, claimed) {
1234
- continue;
1235
- }
1236
- let key = candidate_key(owner, candidate);
1237
- if key.is_empty() {
1238
- continue;
1239
- }
1240
- candidates.entry(key).or_insert_with(|| candidate.clone());
1241
- }
1242
- }
1243
- if candidates.len() != remaining_agents.len() {
1244
- return;
1245
- }
1246
- for (agent_id, candidate) in remaining_agents.into_iter().zip(candidates.into_values()) {
1247
- if let Some(item) = pending.iter().find(|item| item.agent_id == agent_id) {
1248
- claimed.extend(captured_provider_session_keys(item, &candidate.captured));
1249
- }
1250
- assignments.insert(agent_id, candidate);
1251
- }
1252
- }
1253
-
1254
- fn provider_no_expected_requires_positive_attribution(item: &PendingSessionCapture) -> bool {
1255
- matches!(item.provider, Provider::Claude | Provider::ClaudeCode)
1256
- && item.context.expected_session_id.is_none()
1257
- }
1258
-
1259
- fn provider_no_expected_disables_global_one_to_one(item: &PendingSessionCapture) -> bool {
1260
- matches!(
1261
- item.provider,
1262
- Provider::Codex | Provider::Claude | Provider::ClaudeCode
1263
- ) && item.context.expected_session_id.is_none()
1264
- }
1265
-
1266
- fn codex_no_expected(item: &PendingSessionCapture) -> bool {
1267
- matches!(item.provider, Provider::Codex) && item.context.expected_session_id.is_none()
1268
- }
1269
-
1270
- fn unique_available_candidate(
1271
- candidates: Option<&Vec<CapturedSessionCandidate>>,
1272
- claimed: &BTreeSet<String>,
1273
- match_kind: CandidateMatchKind,
1274
- owner: &PendingSessionCapture,
1275
- ) -> Option<CapturedSessionCandidate> {
1276
- let matches = candidates?
1277
- .iter()
1278
- .filter(|candidate| match match_kind {
1279
- CandidateMatchKind::PositiveAgentId => candidate.positive_agent_id_match,
1280
- CandidateMatchKind::PathAgentId => candidate.agent_path_match,
1281
- CandidateMatchKind::Any => true,
1282
- })
1283
- .filter(|candidate| !candidate_keys_collide(owner, candidate, claimed))
1284
- .cloned()
1285
- .collect::<Vec<_>>();
1286
- if matches.len() == 1 {
1287
- matches.into_iter().next()
1288
- } else {
1289
- None
1290
- }
1291
- }
1292
-
1293
- #[derive(Clone, Copy)]
1294
- enum CandidateMatchKind {
1295
- PositiveAgentId,
1296
- PathAgentId,
1297
- Any,
1298
- }
1299
-
1300
- fn candidate_keys_collide(
1301
- owner: &PendingSessionCapture,
1302
- candidate: &CapturedSessionCandidate,
1303
- claimed: &BTreeSet<String>,
1304
- ) -> bool {
1305
- captured_provider_session_keys(owner, &candidate.captured)
1306
- .iter()
1307
- .any(|key| claimed.contains(key))
1308
- }
1309
-
1310
- fn candidate_key(owner: &PendingSessionCapture, candidate: &CapturedSessionCandidate) -> String {
1311
- captured_provider_session_keys(owner, &candidate.captured)
1312
- .into_iter()
1313
- .collect::<Vec<_>>()
1314
- .join("|")
1315
- }
1316
-
1317
- /// 0.4.6 tuple-atomic contract (audit §Capture 修改清单, line 111): writes
1318
- /// the authoritative session tuple if and only if the candidate carries
1319
- /// BOTH `session_id` and `rollout_path`. A partial candidate (e.g.
1320
- /// scanner returned ambiguous attribution with no session_id) MUST NOT
1321
- /// stamp `captured_at` / `captured_via` onto the row, because that
1322
- /// produces a partial tuple that downstream readers treat as authority.
1323
- /// Returns true iff the full tuple was written.
1324
- fn apply_captured_session(
1325
- agent_obj: &mut serde_json::Map<String, Value>,
1326
- captured: &CapturedSession,
1327
- ) -> bool {
1328
- let Some(session_id) = captured.session_id.as_ref() else {
1329
- return false;
1330
- };
1331
- let Some(rollout_path) = captured.rollout_path.as_ref() else {
1332
- return false;
1333
- };
1334
- agent_obj.insert(
1335
- "session_id".to_string(),
1336
- serde_json::json!(session_id.as_str()),
1337
- );
1338
- agent_obj.insert(
1339
- "rollout_path".to_string(),
1340
- serde_json::json!(rollout_path.as_path().to_string_lossy()),
1341
- );
1342
- agent_obj.insert(
1343
- "captured_at".to_string(),
1344
- serde_json::json!(chrono::Utc::now().to_rfc3339()),
1345
- );
1346
- agent_obj.insert(
1347
- "captured_via".to_string(),
1348
- serde_json::to_value(captured.captured_via).unwrap_or(Value::Null),
1349
- );
1350
- agent_obj.insert(
1351
- "attribution_confidence".to_string(),
1352
- serde_json::to_value(captured.attribution_confidence).unwrap_or(Value::Null),
1353
- );
1354
- agent_obj.remove("attribution_ambiguous");
1355
- // S1-CAPTURE-001 (0.4.8): after writing the authoritative tuple, the
1356
- // `_pending_session_id` placeholder is no longer needed — remove it so
1357
- // future reads don't trip the pending-mismatch guard in
1358
- // agent_session_complete. Also stamp capture_state="captured" for
1359
- // diagnose/status observability.
1360
- agent_obj.remove("_pending_session_id");
1361
- agent_obj.insert("capture_state".to_string(), serde_json::json!("captured"));
1362
- true
1363
- }
1364
-
1365
- fn claimed_provider_session_keys(
1366
- state: &Value,
1367
- agents: &serde_json::Map<String, Value>,
1368
- pending_ids: &BTreeSet<String>,
1369
- ) -> BTreeSet<String> {
1370
- let mut keys = BTreeSet::new();
1371
- let team_key = crate::state::projection::team_state_key(state);
1372
- // 1. Every other already-known worker session. The pending row itself is
1373
- // excluded so an incomplete tuple can still be repaired in place.
1374
- for (agent_id, agent) in agents {
1375
- if pending_ids.contains(agent_id) {
1376
- continue;
1377
- }
1378
- push_provider_session_keys(&mut keys, &team_key, agent_id, agent);
1379
- }
1380
- if let Some(teams) = state.get("teams").and_then(Value::as_object) {
1381
- for (nested_team_key, team_state) in teams {
1382
- if let Some(nested_agents) = team_state.get("agents").and_then(Value::as_object) {
1383
- for (agent_id, agent) in nested_agents {
1384
- if nested_team_key == &team_key && pending_ids.contains(agent_id) {
1385
- continue;
1386
- }
1387
- push_provider_session_keys(&mut keys, nested_team_key, agent_id, agent);
1388
- }
1389
- }
1390
- }
1391
- }
1392
- // 2. P0 (lane-046-capture-gap): leader anchor sessions. The leader's
1393
- // own provider transcript must never be attributed to a worker. Scan
1394
- // state.leader_receiver, state.team_owner, and the same fields under
1395
- // state.teams.<key>. Cover all known provider session field names so
1396
- // a present transcript path/id excludes that session from worker
1397
- // allocation.
1398
- push_leader_provider_session_keys(&mut keys, state);
1399
- if let Some(teams) = state.get("teams").and_then(Value::as_object) {
1400
- for team_state in teams.values() {
1401
- push_leader_provider_session_keys(&mut keys, team_state);
1402
- }
1403
- }
1404
- keys
1405
- }
1406
-
1407
- fn push_provider_session_keys(
1408
- keys: &mut BTreeSet<String>,
1409
- fallback_team_key: &str,
1410
- fallback_agent_id: &str,
1411
- value: &Value,
1412
- ) {
1413
- let provider = value
1414
- .get("provider")
1415
- .and_then(Value::as_str)
1416
- .and_then(parse_provider)
1417
- .unwrap_or(Provider::Fake);
1418
- let team_key = value
1419
- .get("owner_team_id")
1420
- .or_else(|| value.get("team_key"))
1421
- .and_then(Value::as_str)
1422
- .filter(|s| !s.is_empty())
1423
- .unwrap_or(fallback_team_key);
1424
- let agent_id = value
1425
- .get("agent_id")
1426
- .and_then(Value::as_str)
1427
- .filter(|s| !s.is_empty())
1428
- .unwrap_or(fallback_agent_id);
1429
- for field in ["session_id", "provider_session_id"] {
1430
- if let Some(session_id) = value
1431
- .get(field)
1432
- .and_then(Value::as_str)
1433
- .filter(|s| !s.is_empty())
1434
- {
1435
- if let Some(key) = SessionAttributionKey::new(provider, team_key, agent_id, session_id)
1436
- {
1437
- keys.insert(session_attribution_key_string(&key));
1438
- }
1439
- keys.insert(global_session_attribution_key_string(session_id));
1440
- }
1441
- }
1442
- // Copilot stores every session in one shared session-store.db. Session id
1443
- // is the attribution identity; treating the shared DB path as globally
1444
- // exclusive makes an exact expected id collide with every sibling.
1445
- if matches!(provider, Provider::Copilot) {
1446
- return;
1447
- }
1448
- for field in ["rollout_path", "transcript_path"] {
1449
- if let Some(path) = value
1450
- .get(field)
1451
- .and_then(Value::as_str)
1452
- .filter(|s| !s.is_empty())
1453
- {
1454
- keys.insert(transcript_attribution_key_string(
1455
- provider, team_key, agent_id, path,
1456
- ));
1457
- keys.insert(global_transcript_attribution_key_string(path));
1458
- }
1459
- }
1460
- }
1461
-
1462
- fn push_leader_provider_session_keys(keys: &mut BTreeSet<String>, scope: &Value) {
1463
- for anchor in ["leader_receiver", "team_owner"] {
1464
- if let Some(node) = scope.get(anchor) {
1465
- push_provider_session_keys(keys, "leader", "leader", node);
1466
- }
1467
- }
1468
- }
1469
-
1470
- fn captured_provider_session_keys(
1471
- owner: &PendingSessionCapture,
1472
- captured: &CapturedSession,
1473
- ) -> BTreeSet<String> {
1474
- let mut keys = BTreeSet::new();
1475
- let team_key = owner.team_key.as_str();
1476
- if let Some(session_id) = &captured.session_id {
1477
- if let Some(key) = SessionAttributionKey::new(
1478
- owner.provider,
1479
- team_key,
1480
- owner.agent_id.as_str(),
1481
- session_id.as_str(),
1482
- ) {
1483
- keys.insert(session_attribution_key_string(&key));
1484
- }
1485
- keys.insert(global_session_attribution_key_string(session_id.as_str()));
1486
- }
1487
- if !matches!(owner.provider, Provider::Copilot) {
1488
- if let Some(rollout_path) = &captured.rollout_path {
1489
- let path = rollout_path.as_path().to_string_lossy();
1490
- keys.insert(transcript_attribution_key_string(
1491
- owner.provider,
1492
- team_key,
1493
- owner.agent_id.as_str(),
1494
- &path,
1495
- ));
1496
- keys.insert(global_transcript_attribution_key_string(&path));
1497
- }
1498
- }
1499
- keys
1500
- }
1501
-
1502
- fn session_attribution_key_string(key: &SessionAttributionKey) -> String {
1503
- format!(
1504
- "SessionAttributionKey(provider={:?},team={},agent={},session={})",
1505
- key.provider(),
1506
- key.team_key(),
1507
- key.agent_id(),
1508
- key.session_id()
1509
- )
1510
- }
1511
-
1512
- fn transcript_attribution_key_string(
1513
- provider: Provider,
1514
- team_key: &str,
1515
- agent_id: &str,
1516
- path: &str,
1517
- ) -> String {
1518
- format!("TranscriptAttributionKey(provider={provider:?},team={team_key},agent={agent_id},path={path})")
1519
- }
1520
-
1521
- fn global_session_attribution_key_string(session_id: &str) -> String {
1522
- format!("GlobalSessionAttributionKey(session={session_id})")
1523
- }
1524
-
1525
- fn global_transcript_attribution_key_string(path: &str) -> String {
1526
- format!("GlobalTranscriptAttributionKey(path={path})")
1527
- }
1528
-
1529
- #[cfg(test)]
1530
- pub(crate) mod test_support {
1531
- use super::*;
1532
- use std::sync::Arc;
1533
-
1534
- #[derive(Clone)]
1535
- pub(crate) struct CaptureCandidatesAdapter {
1536
- provider: Provider,
1537
- fail_agent_id: Option<String>,
1538
- error: String,
1539
- /// Stage 1 amendment test support (architect direction 2026-06-23):
1540
- /// per-agent candidate map. When set, the adapter returns the mapped
1541
- /// candidates for `context.agent_id` instead of an empty list. Lets
1542
- /// the allocator-level test inject expected-id candidates for two
1543
- /// pending agents and observe cross-assignment regressions.
1544
- candidates_by_agent: Option<Arc<BTreeMap<String, Vec<CapturedSessionCandidate>>>>,
1545
- }
1546
-
1547
- impl CaptureCandidatesAdapter {
1548
- /// ---
1549
- /// purpose: 造一个可控的测试替身 adapter:指定 provider,并可让某个席位的候选扫描必定失败
1550
- /// params:
1551
- /// provider: 替身自称的 provider
1552
- /// fail_agent_id: 该席位的 capture_session_candidates 返回错误;None 表示都不失败
1553
- /// error: 失败时携带的错误文本
1554
- /// returns: 未挂候选表的替身;候选表另经 with_candidates 注入
1555
- /// contract:
1556
- /// provides:
1557
- /// - name: new
1558
- /// what: 纯构造,无 I/O
1559
- /// boundary:
1560
- /// - 仅 cfg(test) 存在,不进产品二进制
1561
- /// ---
1562
- pub(crate) fn new(provider: Provider, fail_agent_id: Option<&str>, error: &str) -> Self {
1563
- Self {
1564
- provider,
1565
- fail_agent_id: fail_agent_id.map(str::to_string),
1566
- error: error.to_string(),
1567
- candidates_by_agent: None,
1568
- }
1569
- }
1570
-
1571
- /// ---
1572
- /// purpose: 给测试替身挂一张 agent_id → 候选列表的表,用来构造分配器层面的交叉归属回归
1573
- /// params:
1574
- /// candidates_by_agent: 按席位 id 索引的候选;未列入的席位仍返回空列表
1575
- /// returns: 挂好表的自身(builder 风格,消费 self)
1576
- /// contract:
1577
- /// provides:
1578
- /// - name: with_candidates
1579
- /// what: 只改替身内部状态,不触发任何扫描
1580
- /// boundary:
1581
- /// - 仅 cfg(test) 存在,不进产品二进制
1582
- /// ---
1583
- pub(crate) fn with_candidates(
1584
- mut self,
1585
- candidates_by_agent: BTreeMap<String, Vec<CapturedSessionCandidate>>,
1586
- ) -> Self {
1587
- self.candidates_by_agent = Some(Arc::new(candidates_by_agent));
1588
- self
1589
- }
1590
- }
1591
-
1592
- impl ProviderAdapter for CaptureCandidatesAdapter {
1593
- fn provider(&self) -> Provider {
1594
- self.provider
1595
- }
1596
-
1597
- fn caps(&self) -> crate::provider::ProviderCaps {
1598
- crate::provider::ProviderCaps {
1599
- resume: true,
1600
- fork: false,
1601
- native_mcp_config: false,
1602
- writes_global_settings: false,
1603
- }
1604
- }
1605
-
1606
- fn is_installed(&self) -> bool {
1607
- true
1608
- }
1609
-
1610
- fn version(&self) -> Result<String, ProviderError> {
1611
- Ok("test".to_string())
1612
- }
1613
-
1614
- fn auth_hint(
1615
- &self,
1616
- _auth_mode: crate::provider::AuthMode,
1617
- ) -> crate::provider::AuthHintStatus {
1618
- crate::provider::AuthHintStatus::Unknown
1619
- }
1620
-
1621
- fn build_command(
1622
- &self,
1623
- _auth_mode: crate::provider::AuthMode,
1624
- _mcp_config: Option<&crate::provider::McpConfig>,
1625
- _system_prompt: Option<&str>,
1626
- _model: Option<&str>,
1627
- ) -> Result<Vec<String>, ProviderError> {
1628
- Err(ProviderError::CapabilityUnsupported(
1629
- "test adapter".to_string(),
1630
- ))
1631
- }
1632
-
1633
- fn build_command_with_permissions(
1634
- &self,
1635
- _auth_mode: crate::provider::AuthMode,
1636
- _mcp_config: Option<&crate::provider::McpConfig>,
1637
- _system_prompt: Option<&str>,
1638
- _model: Option<&str>,
1639
- _dangerously_skip_permissions: bool,
1640
- ) -> Result<Vec<String>, ProviderError> {
1641
- Err(ProviderError::CapabilityUnsupported(
1642
- "test adapter".to_string(),
1643
- ))
1644
- }
1645
-
1646
- fn capture_session_id(
1647
- &self,
1648
- _agent_id: &str,
1649
- _spawn_cwd: &std::path::Path,
1650
- _timeout_s: u64,
1651
- ) -> Result<Option<CapturedSession>, ProviderError> {
1652
- Err(ProviderError::CapabilityUnsupported(
1653
- "test adapter".to_string(),
1654
- ))
1655
- }
1656
-
1657
- fn capture_session_candidates(
1658
- &self,
1659
- context: &CaptureSessionContext,
1660
- _timeout_s: u64,
1661
- ) -> Result<Vec<CapturedSessionCandidate>, ProviderError> {
1662
- if self.fail_agent_id.as_deref() == Some(context.agent_id.as_str()) {
1663
- return Err(ProviderError::Io(self.error.clone()));
1664
- }
1665
- if let Some(map) = self.candidates_by_agent.as_ref() {
1666
- if let Some(candidates) = map.get(&context.agent_id) {
1667
- return Ok(candidates.clone());
1668
- }
1669
- }
1670
- Ok(Vec::new())
1671
- }
1672
-
1673
- fn recover_session_id(
1674
- &self,
1675
- _agent_id: &str,
1676
- _spawn_cwd: &std::path::Path,
1677
- ) -> Result<Option<SessionId>, ProviderError> {
1678
- Err(ProviderError::CapabilityUnsupported(
1679
- "test adapter".to_string(),
1680
- ))
1681
- }
1682
-
1683
- fn session_is_resumable(
1684
- &self,
1685
- _session_id: Option<&SessionId>,
1686
- _auth_mode: crate::provider::AuthMode,
1687
- ) -> Result<bool, ProviderError> {
1688
- Ok(true)
1689
- }
1690
-
1691
- fn build_resume_command(
1692
- &self,
1693
- _session_id: Option<&SessionId>,
1694
- _auth_mode: crate::provider::AuthMode,
1695
- _mcp_config: Option<&crate::provider::McpConfig>,
1696
- ) -> Result<Vec<String>, ProviderError> {
1697
- Err(ProviderError::CapabilityUnsupported(
1698
- "test adapter".to_string(),
1699
- ))
1700
- }
1701
-
1702
- fn build_resume_command_with_context(
1703
- &self,
1704
- _session_id: Option<&SessionId>,
1705
- _auth_mode: crate::provider::AuthMode,
1706
- _mcp_config: Option<&crate::provider::McpConfig>,
1707
- _system_prompt: Option<&str>,
1708
- _model: Option<&str>,
1709
- _dangerously_skip_permissions: bool,
1710
- ) -> Result<Vec<String>, ProviderError> {
1711
- Err(ProviderError::CapabilityUnsupported(
1712
- "test adapter".to_string(),
1713
- ))
1714
- }
1715
-
1716
- fn fork(
1717
- &self,
1718
- _session_id: Option<&SessionId>,
1719
- _auth_mode: crate::provider::AuthMode,
1720
- _mcp_config: Option<&crate::provider::McpConfig>,
1721
- ) -> Result<Vec<String>, ProviderError> {
1722
- Err(ProviderError::CapabilityUnsupported(
1723
- "test adapter".to_string(),
1724
- ))
1725
- }
1726
-
1727
- fn fork_with_context(
1728
- &self,
1729
- _session_id: Option<&SessionId>,
1730
- _auth_mode: crate::provider::AuthMode,
1731
- _mcp_config: Option<&crate::provider::McpConfig>,
1732
- _system_prompt: Option<&str>,
1733
- _model: Option<&str>,
1734
- _dangerously_skip_permissions: bool,
1735
- ) -> Result<Vec<String>, ProviderError> {
1736
- Err(ProviderError::CapabilityUnsupported(
1737
- "test adapter".to_string(),
1738
- ))
1739
- }
1740
-
1741
- fn mcp_config(
1742
- &self,
1743
- _auth_mode: crate::provider::AuthMode,
1744
- ) -> Result<crate::provider::McpConfig, ProviderError> {
1745
- Err(ProviderError::CapabilityUnsupported(
1746
- "test adapter".to_string(),
1747
- ))
1748
- }
1749
-
1750
- fn install_mcp(&self, _config: &crate::provider::McpConfig) -> Result<(), ProviderError> {
1751
- Err(ProviderError::CapabilityUnsupported(
1752
- "test adapter".to_string(),
1753
- ))
1754
- }
1755
-
1756
- fn status_patterns(&self) -> Result<crate::provider::StatusPatterns, ProviderError> {
1757
- Err(ProviderError::CapabilityUnsupported(
1758
- "test adapter".to_string(),
1759
- ))
1760
- }
1761
-
1762
- fn validate_model(&self, _model: &str) -> Result<bool, ProviderError> {
1763
- Ok(true)
1764
- }
1765
- }
1766
- }
1767
-
1768
- #[cfg(test)]
1769
- #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1770
- mod u1_tests {
1771
- use super::*;
1772
-
1773
- use crate::provider::{CaptureVia, CapturedSession, Confidence, RolloutPath, SessionId};
1774
- use std::path::PathBuf;
1775
-
1776
- fn leader_like_candidate(session_id: &str, path: &str) -> CapturedSessionCandidate {
1777
- CapturedSessionCandidate {
1778
- captured: CapturedSession {
1779
- session_id: Some(SessionId::new(session_id)),
1780
- rollout_path: Some(RolloutPath::new(PathBuf::from(path))),
1781
- captured_via: CaptureVia::FsWatch,
1782
- attribution_confidence: Confidence::High,
1783
- spawn_cwd: PathBuf::from("/tmp/u1-cwd"),
1784
- },
1785
- embedded_agent_id: None,
1786
- positive_agent_id_match: false,
1787
- agent_path_match: false,
1788
- }
1789
- }
1790
-
1791
- fn worker_owned_candidate(session_id: &str, path: &str) -> CapturedSessionCandidate {
1792
- CapturedSessionCandidate {
1793
- captured: CapturedSession {
1794
- session_id: Some(SessionId::new(session_id)),
1795
- rollout_path: Some(RolloutPath::new(PathBuf::from(path))),
1796
- captured_via: CaptureVia::FsWatch,
1797
- attribution_confidence: Confidence::High,
1798
- spawn_cwd: PathBuf::from("/tmp/u1-cwd"),
1799
- },
1800
- embedded_agent_id: None,
1801
- positive_agent_id_match: true,
1802
- agent_path_match: false,
1803
- }
1804
- }
1805
-
1806
- /// P0 RED-1 (lane-046-capture-gap): a Claude worker with
1807
- /// expected_session_id=None must NOT capture a candidate that has neither
1808
- /// positive_agent_id_match nor agent_path_match — even when it is the
1809
- /// only candidate (the leader-transcript-as-only-candidate failure mode
1810
- /// from the macmini repro). Must end up ambiguous, not assigned.
1811
- #[test]
1812
- fn claude_no_expected_single_leader_candidate_is_not_assigned() {
1813
- let mut state = serde_json::json!({
1814
- "agents": {
1815
- "release_engineer": {
1816
- "provider": "claude",
1817
- "status": "running",
1818
- "spawn_cwd": "/tmp/u1-cwd"
1819
- }
1820
- }
1821
- });
1822
- let mut canned = BTreeMap::new();
1823
- canned.insert(
1824
- "release_engineer".to_string(),
1825
- vec![leader_like_candidate(
1826
- "ea059b82-c53e-4654-9590-9f3e6d46f0ca",
1827
- "/Users/alauda/.claude/projects/-Users-alauda-team/ea059b82.jsonl",
1828
- )],
1829
- );
1830
- let canned_for_adapter = canned.clone();
1831
- let mut adapter_for = move |provider| {
1832
- Box::new(
1833
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
1834
- .with_candidates(canned_for_adapter.clone()),
1835
- ) as Box<dyn ProviderAdapter>
1836
- };
1837
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
1838
- .expect("capture pass succeeds");
1839
- assert!(
1840
- report.assigned.is_empty(),
1841
- "Claude no-expected + weak (no positive/path) candidate must NOT be assigned; got {:?}",
1842
- report.assigned
1843
- );
1844
- let agent = state
1845
- .get("agents")
1846
- .and_then(|a| a.get("release_engineer"))
1847
- .expect("agent present");
1848
- assert!(
1849
- agent.get("session_id").is_none(),
1850
- "agent.session_id must remain empty when capture is refused; got {agent:?}"
1851
- );
1852
- }
1853
-
1854
- #[test]
1855
- fn codex_no_expected_same_cwd_candidates_without_identity_do_not_global_zip_assign() {
1856
- let mut state = serde_json::json!({
1857
- "agents": {
1858
- "frontend": {
1859
- "provider": "codex",
1860
- "status": "running",
1861
- "spawn_cwd": "/tmp/u1-cwd"
1862
- },
1863
- "ios-dev": {
1864
- "provider": "codex",
1865
- "status": "running",
1866
- "spawn_cwd": "/tmp/u1-cwd"
1867
- }
1868
- }
1869
- });
1870
- let candidates = vec![
1871
- leader_like_candidate(
1872
- "019f3327-c35a-7023-b3cd-1bea93a7a157",
1873
- "/Users/alauda/.codex/sessions/2026/07/06/rollout-frontend-poison.jsonl",
1874
- ),
1875
- leader_like_candidate(
1876
- "019f3327-d6d7-7c80-846a-0db4821714fb",
1877
- "/Users/alauda/.codex/sessions/2026/07/06/rollout-ios-poison.jsonl",
1878
- ),
1879
- ];
1880
- let mut canned = BTreeMap::new();
1881
- canned.insert("frontend".to_string(), candidates.clone());
1882
- canned.insert("ios-dev".to_string(), candidates);
1883
- let canned_for_adapter = canned.clone();
1884
- let mut adapter_for = move |provider| {
1885
- Box::new(
1886
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
1887
- .with_candidates(canned_for_adapter.clone()),
1888
- ) as Box<dyn ProviderAdapter>
1889
- };
1890
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
1891
- .expect("capture pass succeeds");
1892
- assert!(
1893
- report.assigned.is_empty(),
1894
- "Codex no-expected same-cwd candidates with no positive identity must stay ambiguous, not global one-to-one assigned; report={report:?}"
1895
- );
1896
- assert_eq!(
1897
- report
1898
- .ambiguous
1899
- .iter()
1900
- .map(|item| item.agent_id.as_str())
1901
- .collect::<Vec<_>>(),
1902
- vec!["frontend", "ios-dev"],
1903
- "both workers should be marked ambiguous instead of receiving weak zipped tuples"
1904
- );
1905
- let agents = state["agents"].as_object().expect("agents object");
1906
- assert!(agents["frontend"].get("session_id").is_none());
1907
- assert!(agents["ios-dev"].get("session_id").is_none());
1908
- }
1909
-
1910
- #[test]
1911
- fn codex_no_expected_single_candidate_without_identity_still_captures() {
1912
- let mut state = serde_json::json!({
1913
- "agents": {
1914
- "subgreeter": {
1915
- "provider": "codex",
1916
- "status": "running",
1917
- "spawn_cwd": "/tmp/u1-cwd"
1918
- }
1919
- }
1920
- });
1921
- let mut canned = BTreeMap::new();
1922
- canned.insert(
1923
- "subgreeter".to_string(),
1924
- vec![leader_like_candidate(
1925
- "sess-sub-captured",
1926
- "/Users/alauda/.codex/sessions/2026/07/06/rollout-sub.jsonl",
1927
- )],
1928
- );
1929
- let canned_for_adapter = canned.clone();
1930
- let mut adapter_for = move |provider| {
1931
- Box::new(
1932
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
1933
- .with_candidates(canned_for_adapter.clone()),
1934
- ) as Box<dyn ProviderAdapter>
1935
- };
1936
-
1937
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
1938
- .expect("capture pass succeeds");
1939
-
1940
- assert_eq!(report.assigned, vec!["subgreeter".to_string()]);
1941
- assert!(report.ambiguous.is_empty(), "report={report:?}");
1942
- assert_eq!(
1943
- state["agents"]["subgreeter"]["session_id"].as_str(),
1944
- Some("sess-sub-captured")
1945
- );
1946
- }
1947
-
1948
- #[test]
1949
- fn codex_shared_single_candidate_without_identity_is_deferred() {
1950
- let mut state = serde_json::json!({
1951
- "agents": {
1952
- "parent-peer": {
1953
- "provider": "codex",
1954
- "status": "running",
1955
- "spawn_cwd": "/tmp/u1-cwd"
1956
- },
1957
- "worker-a": {
1958
- "provider": "codex",
1959
- "status": "running",
1960
- "spawn_cwd": "/tmp/u1-cwd"
1961
- }
1962
- }
1963
- });
1964
- let candidate = leader_like_candidate(
1965
- "019f3327-shared",
1966
- "/Users/alauda/.codex/sessions/2026/07/06/rollout-shared.jsonl",
1967
- );
1968
- let mut canned = BTreeMap::new();
1969
- canned.insert("parent-peer".to_string(), vec![candidate.clone()]);
1970
- canned.insert("worker-a".to_string(), vec![candidate]);
1971
- let canned_for_adapter = canned.clone();
1972
- let mut adapter_for = move |provider| {
1973
- Box::new(
1974
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
1975
- .with_candidates(canned_for_adapter.clone()),
1976
- ) as Box<dyn ProviderAdapter>
1977
- };
1978
-
1979
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
1980
- .expect("capture pass succeeds");
1981
-
1982
- assert!(report.assigned.is_empty(), "report={report:?}");
1983
- assert!(state["agents"]["parent-peer"].get("session_id").is_none());
1984
- assert!(state["agents"]["worker-a"].get("session_id").is_none());
1985
- }
1986
-
1987
- #[test]
1988
- fn codex_embedded_identity_assigns_each_same_cwd_worker_to_own_rollout() {
1989
- let mut state = serde_json::json!({
1990
- "agents": {
1991
- "frontend": {
1992
- "provider": "codex",
1993
- "status": "running",
1994
- "spawn_cwd": "/tmp/u1-cwd"
1995
- },
1996
- "ios-dev": {
1997
- "provider": "codex",
1998
- "status": "running",
1999
- "spawn_cwd": "/tmp/u1-cwd"
2000
- }
2001
- }
2002
- });
2003
- let frontend = CapturedSessionCandidate {
2004
- embedded_agent_id: Some("frontend".to_string()),
2005
- positive_agent_id_match: true,
2006
- ..leader_like_candidate(
2007
- "019f3327-frontend",
2008
- "/Users/alauda/.codex/sessions/2026/07/06/rollout-frontend.jsonl",
2009
- )
2010
- };
2011
- let ios = CapturedSessionCandidate {
2012
- embedded_agent_id: Some("ios-dev".to_string()),
2013
- positive_agent_id_match: true,
2014
- ..leader_like_candidate(
2015
- "019f3327-ios-dev",
2016
- "/Users/alauda/.codex/sessions/2026/07/06/rollout-ios-dev.jsonl",
2017
- )
2018
- };
2019
- let mut canned = BTreeMap::new();
2020
- canned.insert("frontend".to_string(), vec![frontend]);
2021
- canned.insert("ios-dev".to_string(), vec![ios]);
2022
- let canned_for_adapter = canned.clone();
2023
- let mut adapter_for = move |provider| {
2024
- Box::new(
2025
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
2026
- .with_candidates(canned_for_adapter.clone()),
2027
- ) as Box<dyn ProviderAdapter>
2028
- };
2029
-
2030
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
2031
- .expect("capture pass succeeds");
2032
-
2033
- assert_eq!(
2034
- report.assigned,
2035
- vec!["frontend".to_string(), "ios-dev".to_string()]
2036
- );
2037
- assert!(report.ambiguous.is_empty());
2038
- assert_eq!(
2039
- state["agents"]["frontend"]["session_id"].as_str(),
2040
- Some("019f3327-frontend")
2041
- );
2042
- assert_eq!(
2043
- state["agents"]["ios-dev"]["session_id"].as_str(),
2044
- Some("019f3327-ios-dev")
2045
- );
2046
- }
2047
-
2048
- #[test]
2049
- fn apply_time_identity_guard_refuses_mismatched_candidate() {
2050
- let mut state = serde_json::json!({
2051
- "agents": {
2052
- "frontend": {
2053
- "provider": "codex",
2054
- "status": "running",
2055
- "spawn_cwd": "/tmp/u1-cwd"
2056
- }
2057
- }
2058
- });
2059
- let candidate = CapturedSessionCandidate {
2060
- embedded_agent_id: Some("ios-dev".to_string()),
2061
- positive_agent_id_match: true,
2062
- ..leader_like_candidate(
2063
- "019f3327-c35a-7023-b3cd-1bea93a7a157",
2064
- "/Users/alauda/.codex/sessions/2026/07/06/rollout-ios-dev.jsonl",
2065
- )
2066
- };
2067
- let mut canned = BTreeMap::new();
2068
- canned.insert("frontend".to_string(), vec![candidate]);
2069
- let canned_for_adapter = canned.clone();
2070
- let mut adapter_for = move |provider| {
2071
- Box::new(
2072
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
2073
- .with_candidates(canned_for_adapter.clone()),
2074
- ) as Box<dyn ProviderAdapter>
2075
- };
2076
-
2077
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
2078
- .expect("capture pass succeeds");
2079
-
2080
- assert!(report.assigned.is_empty());
2081
- assert_eq!(report.identity_mismatches.len(), 1);
2082
- assert_eq!(report.identity_mismatches[0].agent_id, "frontend");
2083
- assert_eq!(report.identity_mismatches[0].embedded_agent_id, "ios-dev");
2084
- assert!(state["agents"]["frontend"].get("session_id").is_none());
2085
- assert_eq!(
2086
- state["agents"]["frontend"]["capture_state"].as_str(),
2087
- Some("session_identity_mismatch")
2088
- );
2089
- }
2090
-
2091
- /// P0 RED-2: same shape but with a positive_agent_id_match candidate →
2092
- /// must capture (positive agent id is authoritative for Claude
2093
- /// no-expected).
2094
- #[test]
2095
- fn claude_no_expected_positive_worker_candidate_still_captures() {
2096
- let mut state = serde_json::json!({
2097
- "agents": {
2098
- "release_engineer": {
2099
- "provider": "claude",
2100
- "status": "running",
2101
- "spawn_cwd": "/tmp/u1-cwd"
2102
- }
2103
- }
2104
- });
2105
- let mut canned = BTreeMap::new();
2106
- canned.insert(
2107
- "release_engineer".to_string(),
2108
- vec![worker_owned_candidate(
2109
- "abc12345-worker-owned",
2110
- "/Users/alauda/.claude/projects/-Users-alauda-team/abc12345.jsonl",
2111
- )],
2112
- );
2113
- let canned_for_adapter = canned.clone();
2114
- let mut adapter_for = move |provider| {
2115
- Box::new(
2116
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
2117
- .with_candidates(canned_for_adapter.clone()),
2118
- ) as Box<dyn ProviderAdapter>
2119
- };
2120
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
2121
- .expect("capture pass succeeds");
2122
- assert_eq!(
2123
- report.assigned,
2124
- vec!["release_engineer".to_string()],
2125
- "Claude no-expected + positive_agent_id candidate MUST capture; got {:?}",
2126
- report.assigned
2127
- );
2128
- }
2129
-
2130
- /// P0 RED-3: leader_receiver under teams.<key> with provider session
2131
- /// fields must exclude that session from worker capture even if the
2132
- /// candidate would otherwise match.
2133
- #[test]
2134
- fn claimed_session_keys_include_team_scoped_leader_receiver() {
2135
- let mut state = serde_json::json!({
2136
- "agents": {
2137
- "release_engineer": {
2138
- "provider": "claude",
2139
- "status": "running",
2140
- "spawn_cwd": "/tmp/u1-cwd"
2141
- }
2142
- },
2143
- "teams": {
2144
- "teamA": {
2145
- "leader_receiver": {
2146
- "session_id": "leader-session-id-zzz",
2147
- "rollout_path": "/Users/alauda/.claude/projects/-Users-alauda-team/zzz.jsonl"
2148
- }
2149
- }
2150
- }
2151
- });
2152
- let mut canned = BTreeMap::new();
2153
- canned.insert(
2154
- "release_engineer".to_string(),
2155
- vec![worker_owned_candidate(
2156
- "leader-session-id-zzz",
2157
- "/Users/alauda/.claude/projects/-Users-alauda-team/zzz.jsonl",
2158
- )],
2159
- );
2160
- let canned_for_adapter = canned.clone();
2161
- let mut adapter_for = move |provider| {
2162
- Box::new(
2163
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
2164
- .with_candidates(canned_for_adapter.clone()),
2165
- ) as Box<dyn ProviderAdapter>
2166
- };
2167
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
2168
- .expect("capture pass succeeds");
2169
- assert!(
2170
- report.assigned.is_empty(),
2171
- "worker candidate that collides with team-scoped leader_receiver \
2172
- session MUST be excluded by claimed_provider_session_keys; got {:?}",
2173
- report.assigned
2174
- );
2175
- }
2176
-
2177
- #[test]
2178
- fn pending_capture_state_stays_pending_until_a_trigger_expires() {
2179
- let old = (chrono::Utc::now() - chrono::Duration::seconds(60)).to_rfc3339();
2180
- let mut agent = serde_json::Map::new();
2181
- agent.insert("spawned_at".to_string(), serde_json::json!(old));
2182
- assert_eq!(
2183
- super::classify_pending_capture_state(&agent, 0),
2184
- "pending_first_turn"
2185
- );
2186
-
2187
- let trigger = (chrono::Utc::now() - chrono::Duration::seconds(20)).to_rfc3339();
2188
- agent.insert("first_send_at".to_string(), serde_json::json!(trigger));
2189
- assert_eq!(
2190
- super::classify_pending_capture_state(&agent, 0),
2191
- "transcript_missing"
2192
- );
2193
- }
2194
-
2195
- #[test]
2196
- fn pending_context_fork_keeps_typed_state_until_trigger_grace_expires() {
2197
- let old = (chrono::Utc::now() - chrono::Duration::seconds(60)).to_rfc3339();
2198
- let mut agent = serde_json::Map::new();
2199
- agent.insert("spawned_at".to_string(), serde_json::json!(old));
2200
- agent.insert(
2201
- "capture_state".to_string(),
2202
- serde_json::json!("pending_context_fork"),
2203
- );
2204
- assert_eq!(
2205
- super::classify_pending_capture_state(&agent, 0),
2206
- "pending_context_fork"
2207
- );
2208
- let trigger = (chrono::Utc::now() - chrono::Duration::seconds(20)).to_rfc3339();
2209
- agent.insert("first_send_at".to_string(), serde_json::json!(trigger));
2210
- assert_eq!(
2211
- super::classify_pending_capture_state(&agent, 0),
2212
- "transcript_missing"
2213
- );
2214
- }
2215
-
2216
- #[test]
2217
- fn canonical_pending_capture_preserves_legacy_missing_boundary() {
2218
- let agent = serde_json::json!({
2219
- "provider": "copilot",
2220
- "status": "running",
2221
- "spawn_cwd": "/tmp/u1-cwd",
2222
- "capture_state": "pending_first_turn"
2223
- });
2224
- let mut adapter_for = crate::provider::get_adapter;
2225
- let pending = pending_session_capture("clone", &agent, &mut adapter_for)
2226
- .expect("legacy row still participates in canonical capture");
2227
- assert_eq!(pending.context.spawned_at, None);
2228
- }
2229
-
2230
- #[test]
2231
- fn existing_team_session_is_rejected_while_fresh_candidate_is_accepted() {
2232
- let mut state = serde_json::json!({
2233
- "session_name": "current",
2234
- "agents": {
2235
- "clone": {
2236
- "provider": "copilot",
2237
- "status": "running",
2238
- "spawn_cwd": "/tmp/u1-cwd"
2239
- }
2240
- },
2241
- "teams": {
2242
- "archived": {
2243
- "agents": {
2244
- "old-seat": {
2245
- "provider": "copilot",
2246
- "session_id": "stale-session",
2247
- "rollout_path": "/tmp/stale.jsonl"
2248
- }
2249
- }
2250
- }
2251
- }
2252
- });
2253
- let mut canned = BTreeMap::new();
2254
- canned.insert(
2255
- "clone".to_string(),
2256
- vec![
2257
- worker_owned_candidate("stale-session", "/tmp/stale.jsonl"),
2258
- worker_owned_candidate("fresh-session", "/tmp/fresh.jsonl"),
2259
- ],
2260
- );
2261
- let canned_for_adapter = canned.clone();
2262
- let mut adapter_for = move |provider| {
2263
- Box::new(
2264
- test_support::CaptureCandidatesAdapter::new(provider, None, "")
2265
- .with_candidates(canned_for_adapter.clone()),
2266
- ) as Box<dyn ProviderAdapter>
2267
- };
2268
-
2269
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
2270
- .expect("capture pass succeeds");
2271
-
2272
- assert_eq!(report.assigned, vec!["clone".to_string()]);
2273
- assert_eq!(
2274
- state["agents"]["clone"]["session_id"].as_str(),
2275
- Some("fresh-session")
2276
- );
2277
- }
2278
-
2279
- #[test]
2280
- fn capture_pass_keeps_pending_agent_when_one_adapter_capture_fails() {
2281
- let mut state = serde_json::json!({
2282
- "agents": {
2283
- "bad": {
2284
- "provider": "copilot",
2285
- "status": "running",
2286
- "spawn_cwd": "/tmp/u1-bad"
2287
- },
2288
- "good": {
2289
- "provider": "copilot",
2290
- "status": "running",
2291
- "spawn_cwd": "/tmp/u1-good"
2292
- }
2293
- }
2294
- });
2295
- let mut adapter_for = |provider| {
2296
- Box::new(test_support::CaptureCandidatesAdapter::new(
2297
- provider,
2298
- Some("bad"),
2299
- "capture exploded",
2300
- )) as Box<dyn ProviderAdapter>
2301
- };
2302
-
2303
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
2304
- .expect("one agent capture failure must not abort the whole pass");
2305
-
2306
- assert_eq!(report.pending, vec!["bad".to_string(), "good".to_string()]);
2307
- assert_eq!(report.assigned, Vec::<String>::new());
2308
- assert_eq!(
2309
- report.candidate_count_by_agent.get("good"),
2310
- Some(&0),
2311
- "the non-failing agent must still be probed"
2312
- );
2313
- assert_eq!(
2314
- report.capture_failures,
2315
- vec![SessionCaptureFailure {
2316
- agent_id: "bad".to_string(),
2317
- error: "provider io error: capture exploded".to_string(),
2318
- }]
2319
- );
2320
- }
2321
-
2322
- /// RM-039-SESS-001 step 1 (architect verdict 2026-06-22): the
2323
- /// `agent_session_complete` predicate must NOT treat a non-empty
2324
- /// `rollout_path` as complete when the file does not exist. The
2325
- /// historical bug was that a stale-positive capture tuple
2326
- /// (`session_id` + `rollout_path` both present, but the path had
2327
- /// been rotated away by the provider) was reported as complete and
2328
- /// blocked `pending_session_capture` from recapturing. Now the
2329
- /// predicate returns false if the path does not exist, so the
2330
- /// session is re-evaluated on the next convergence tick.
2331
- #[test]
2332
- fn rm039_sess001_agent_session_complete_requires_existing_rollout_path() {
2333
- // Case 1: session_id + rollout_path both non-empty, path absent.
2334
- let missing = "/tmp/ta-rm039-sess001-nonexistent-rollout.jsonl";
2335
- // Guard against a previous test run leaving the file behind.
2336
- let _ = std::fs::remove_file(missing);
2337
- let agent_stale = serde_json::json!({
2338
- "session_id": "sess-stale-positive",
2339
- "rollout_path": missing,
2340
- });
2341
- assert!(
2342
- !agent_session_complete(&agent_stale),
2343
- "RM-039-SESS-001: stale-positive tuple (session_id + missing rollout_path) \
2344
- must NOT be reported complete"
2345
- );
2346
-
2347
- // Case 2: session_id + rollout_path both non-empty, path exists.
2348
- use std::sync::atomic::{AtomicU64, Ordering};
2349
- static N: AtomicU64 = AtomicU64::new(0);
2350
- let n = N.fetch_add(1, Ordering::Relaxed);
2351
- let existing = std::env::temp_dir().join(format!(
2352
- "ta-rm039-sess001-existing-{}-{}.jsonl",
2353
- std::process::id(),
2354
- n
2355
- ));
2356
- std::fs::write(&existing, b"{}\n").expect("write fixture rollout file");
2357
- // 0.4.6 tuple-atomic contract: `agent_session_complete` now requires
2358
- // the full authoritative tuple (session_id + rollout_path +
2359
- // captured_at + captured_via), not just session_id + rollout_path.
2360
- // Pre-0.4.6 partial tuples are no longer treated as complete.
2361
- let agent_complete = serde_json::json!({
2362
- "session_id": "sess-real",
2363
- "rollout_path": existing.to_string_lossy(),
2364
- "captured_at": "2026-06-25T10:00:00+00:00",
2365
- "captured_via": "session.captured",
2366
- });
2367
- assert!(
2368
- agent_session_complete(&agent_complete),
2369
- "0.4.6: agent with full tuple (session_id + rollout_path + captured_at + captured_via) + existing rollout file is complete"
2370
- );
2371
- let _ = std::fs::remove_file(&existing);
2372
-
2373
- // Case 3: empty session_id must still fail completeness regardless.
2374
- let agent_no_session = serde_json::json!({
2375
- "session_id": "",
2376
- "rollout_path": "/tmp/whatever",
2377
- });
2378
- assert!(!agent_session_complete(&agent_no_session));
2379
-
2380
- // Case 4: empty rollout_path remains incomplete (legacy contract).
2381
- let agent_no_path = serde_json::json!({
2382
- "session_id": "sess-x",
2383
- "rollout_path": "",
2384
- });
2385
- assert!(!agent_session_complete(&agent_no_path));
2386
- }
2387
-
2388
- /// Stage 1 amendment regression (architect direction 2026-06-23,
2389
- /// S1-CAPTURE-002): two pending agents, each with a distinct
2390
- /// `_pending_session_id`. Each agent's candidate list contains ONLY its
2391
- /// own expected transcript (no positive worker identity hint, no path
2392
- /// agent id hint — the file basename is just a UUID). Pre-fix, the
2393
- /// allocator's `allocate_global_one_to_one` zipped agents (sorted by
2394
- /// agent_id) with candidates (sorted by candidate-key), producing CROSS
2395
- /// assignments that the mismatch guard then rejected — leaving both
2396
- /// agents `attribution_ambiguous`. Post-fix, the ExpectedSessionId
2397
- /// pre-pass binds each agent to its own expected candidate before any
2398
- /// global one-to-one runs.
2399
- #[test]
2400
- fn capture_allocator_expected_session_id_binds_each_worker_to_its_own_transcript() {
2401
- // 0.4.6 P0 amendment: Claude no longer carries _pending_session_id
2402
- // (fresh spawn doesn't inject --session-id; capture anchors on
2403
- // cwd+spawned_at+identity). The ExpectedSessionId pre-pass remains
2404
- // valid for providers that DO use expected_session_id (Copilot is the
2405
- // only one left that honors framework-supplied --session-id). Switch
2406
- // this test to Copilot to preserve the pre-pass invariant coverage.
2407
- use crate::provider::{CaptureVia, Confidence, RolloutPath};
2408
- let dir = std::env::temp_dir().join(format!("ta-stage1-allocator-{}", std::process::id()));
2409
- std::fs::create_dir_all(&dir).unwrap();
2410
- let rollout_a = dir.join("9a2d1668.jsonl");
2411
- let rollout_b = dir.join("3e824e89.jsonl");
2412
- std::fs::write(&rollout_a, b"{}\n").unwrap();
2413
- std::fs::write(&rollout_b, b"{}\n").unwrap();
2414
- let candidate_a = CapturedSessionCandidate {
2415
- captured: CapturedSession {
2416
- session_id: Some(SessionId::new("9a2d1668-8987-4c36-8bde-a5135b10da02")),
2417
- rollout_path: Some(RolloutPath::new(rollout_a.clone())),
2418
- captured_via: CaptureVia::FsWatch,
2419
- attribution_confidence: Confidence::High,
2420
- spawn_cwd: dir.clone(),
2421
- },
2422
- embedded_agent_id: None,
2423
- positive_agent_id_match: false,
2424
- agent_path_match: false,
2425
- };
2426
- let candidate_b = CapturedSessionCandidate {
2427
- captured: CapturedSession {
2428
- session_id: Some(SessionId::new("3e824e89-25ac-4b3f-b272-b4f733f6403c")),
2429
- rollout_path: Some(RolloutPath::new(rollout_b.clone())),
2430
- captured_via: CaptureVia::FsWatch,
2431
- attribution_confidence: Confidence::High,
2432
- spawn_cwd: dir.clone(),
2433
- },
2434
- embedded_agent_id: None,
2435
- positive_agent_id_match: false,
2436
- agent_path_match: false,
2437
- };
2438
- let mut candidates_by_agent: BTreeMap<String, Vec<CapturedSessionCandidate>> =
2439
- BTreeMap::new();
2440
- candidates_by_agent.insert("copilot-a".to_string(), vec![candidate_a.clone()]);
2441
- candidates_by_agent.insert("copilot-b".to_string(), vec![candidate_b.clone()]);
2442
-
2443
- let cwd_str = dir.to_string_lossy().to_string();
2444
- let mut state = serde_json::json!({
2445
- "agents": {
2446
- "copilot-a": {
2447
- "provider": "copilot",
2448
- "status": "running",
2449
- "spawn_cwd": cwd_str,
2450
- "_pending_session_id": "9a2d1668-8987-4c36-8bde-a5135b10da02"
2451
- },
2452
- "copilot-b": {
2453
- "provider": "copilot",
2454
- "status": "running",
2455
- "spawn_cwd": cwd_str,
2456
- "_pending_session_id": "3e824e89-25ac-4b3f-b272-b4f733f6403c"
2457
- }
2458
- }
2459
- });
2460
- let adapter = test_support::CaptureCandidatesAdapter::new(Provider::Copilot, None, "")
2461
- .with_candidates(candidates_by_agent);
2462
- let mut adapter_for =
2463
- move |_provider| Box::new(adapter.clone()) as Box<dyn ProviderAdapter>;
2464
-
2465
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
2466
- .expect("allocator pass should succeed");
2467
-
2468
- // ExpectedSessionId pre-pass must bind each agent to its own
2469
- // expected transcript. No cross-assignment, no ambiguous mark.
2470
- let agents = state["agents"].as_object().expect("agents object");
2471
- assert_eq!(
2472
- agents["copilot-a"]["session_id"].as_str(),
2473
- Some("9a2d1668-8987-4c36-8bde-a5135b10da02"),
2474
- "Stage 1 fix: copilot-a must bind to its own expected transcript; \
2475
- state.copilot-a={}",
2476
- agents["copilot-a"]
2477
- );
2478
- assert_eq!(
2479
- agents["copilot-b"]["session_id"].as_str(),
2480
- Some("3e824e89-25ac-4b3f-b272-b4f733f6403c"),
2481
- "Stage 1 fix: copilot-b must bind to its own expected transcript; \
2482
- state.copilot-b={}",
2483
- agents["copilot-b"]
2484
- );
2485
- assert!(
2486
- agents["copilot-a"]
2487
- .get("attribution_ambiguous")
2488
- .is_none_or(|v| v.as_bool() != Some(true)),
2489
- "Stage 1 fix: copilot-a must NOT be flagged ambiguous after the \
2490
- expected-id pre-pass bound it; state.copilot-a={}",
2491
- agents["copilot-a"]
2492
- );
2493
- assert!(
2494
- agents["copilot-b"]
2495
- .get("attribution_ambiguous")
2496
- .is_none_or(|v| v.as_bool() != Some(true)),
2497
- "Stage 1 fix: copilot-b must NOT be flagged ambiguous; \
2498
- state.copilot-b={}",
2499
- agents["copilot-b"]
2500
- );
2501
- assert_eq!(
2502
- report.ambiguous.len(),
2503
- 0,
2504
- "Stage 1 fix: capture report must record zero ambiguous; report={report:?}"
2505
- );
2506
-
2507
- let _ = std::fs::remove_file(&rollout_a);
2508
- let _ = std::fs::remove_file(&rollout_b);
2509
- let _ = std::fs::remove_dir(&dir);
2510
- }
2511
-
2512
- #[test]
2513
- fn copilot_exact_session_id_does_not_collide_on_shared_store_path() {
2514
- use crate::provider::{CaptureVia, Confidence, RolloutPath};
2515
- let dir =
2516
- std::env::temp_dir().join(format!("ta-copilot-shared-store-{}", std::process::id()));
2517
- let _ = std::fs::remove_dir_all(&dir);
2518
- std::fs::create_dir_all(&dir).unwrap();
2519
- let store = dir.join("session-store.db");
2520
- std::fs::write(&store, b"fixture").unwrap();
2521
- let expected = "22222222-2222-4222-8222-222222222222";
2522
- let candidate = CapturedSessionCandidate {
2523
- captured: CapturedSession {
2524
- session_id: Some(SessionId::new(expected)),
2525
- rollout_path: Some(RolloutPath::new(store.clone())),
2526
- captured_via: CaptureVia::FsWatch,
2527
- attribution_confidence: Confidence::High,
2528
- spawn_cwd: dir.clone(),
2529
- },
2530
- embedded_agent_id: None,
2531
- positive_agent_id_match: false,
2532
- agent_path_match: false,
2533
- };
2534
- let mut by_agent = BTreeMap::new();
2535
- by_agent.insert("clone".to_string(), vec![candidate]);
2536
- let mut state = serde_json::json!({
2537
- "agents": {
2538
- "source": {
2539
- "provider": "copilot",
2540
- "status": "running",
2541
- "spawn_cwd": dir.to_string_lossy(),
2542
- "session_id": "11111111-1111-4111-8111-111111111111",
2543
- "rollout_path": store.to_string_lossy(),
2544
- "captured_at": "2026-07-22T01:00:00+00:00",
2545
- "captured_via": "fs_watch"
2546
- },
2547
- "clone": {
2548
- "provider": "copilot",
2549
- "status": "running",
2550
- "spawn_cwd": dir.to_string_lossy(),
2551
- "spawned_at": "2026-07-22T02:00:00+00:00",
2552
- "_pending_session_id": expected
2553
- }
2554
- }
2555
- });
2556
- let adapter = test_support::CaptureCandidatesAdapter::new(Provider::Copilot, None, "")
2557
- .with_candidates(by_agent);
2558
- let mut adapter_for =
2559
- move |_provider| Box::new(adapter.clone()) as Box<dyn ProviderAdapter>;
2560
-
2561
- let report = capture_missing_provider_sessions_once(&mut state, &mut adapter_for, true, 0)
2562
- .expect("capture shared Copilot store");
2563
-
2564
- assert_eq!(report.assigned, vec!["clone".to_string()]);
2565
- assert_eq!(state["agents"]["clone"]["session_id"], expected);
2566
- assert_eq!(
2567
- state["agents"]["clone"]["rollout_path"],
2568
- store.to_string_lossy().as_ref()
2569
- );
2570
- assert_eq!(
2571
- state["agents"]["source"]["session_id"],
2572
- "11111111-1111-4111-8111-111111111111"
2573
- );
2574
- let _ = std::fs::remove_dir_all(&dir);
2575
- }
2576
-
2577
- /// E57 RED postflight (lane-046-capture-gap): `recover_resume_session_from_events`
2578
- /// must refuse to repair a worker's session from a stale `session.captured`
2579
- /// event whose rollout file is a Claude LEADER transcript
2580
- /// (`customTitle == "claude leader"`). Without this filter, a fresh restart
2581
- /// after a pre-fix run still pulls the leader transcript onto a worker via
2582
- /// captured_via=event_log_repair (Mac mini evidence:
2583
- /// resume.session_repaired session_id=ea059b82 → release-engineer).
2584
- #[test]
2585
- fn e57_recover_resume_refuses_claude_leader_marker_rollout() {
2586
- use std::io::Write;
2587
- use std::sync::atomic::{AtomicU64, Ordering};
2588
- static COUNTER: AtomicU64 = AtomicU64::new(0);
2589
- let uniq = COUNTER.fetch_add(1, Ordering::Relaxed);
2590
- let workspace =
2591
- std::env::temp_dir().join(format!("ta-e57-recover-{}-{}", std::process::id(), uniq));
2592
- let _ = std::fs::remove_dir_all(&workspace);
2593
- std::fs::create_dir_all(&workspace).expect("workspace");
2594
-
2595
- // Write a leader-marker rollout file (claude TUI leader transcript).
2596
- let rollout = workspace.join("ea059b82-leader.jsonl");
2597
- let mut f = std::fs::File::create(&rollout).expect("rollout");
2598
- writeln!(
2599
- f,
2600
- "{{\"customTitle\":\"claude leader\",\"sessionId\":\"ea059b82-c53e-4654-9590-9f3e6d46f0ca\",\"cwd\":\"/tmp/e57\"}}"
2601
- )
2602
- .unwrap();
2603
- writeln!(f, "{{\"role\":\"user\",\"content\":\"hi\"}}").unwrap();
2604
- drop(f);
2605
-
2606
- // Write a `session.captured` event into events.jsonl pointing
2607
- // release-engineer at the leader rollout — simulates the stale
2608
- // pre-fix event that triggered the bug.
2609
- let event_log = crate::event_log::EventLog::new(&workspace);
2610
- event_log
2611
- .write(
2612
- "session.captured",
2613
- serde_json::json!({
2614
- "agent_id": "release-engineer",
2615
- "provider": "claude",
2616
- "session_id": "ea059b82-c53e-4654-9590-9f3e6d46f0ca",
2617
- "rollout_path": rollout.to_string_lossy().to_string(),
2618
- "captured_via": "fs_watch",
2619
- }),
2620
- )
2621
- .expect("event write");
2622
-
2623
- let previous = serde_json::json!({
2624
- "provider": "claude",
2625
- "session_id": null,
2626
- "rollout_path": null,
2627
- });
2628
- let adapter = test_support::CaptureCandidatesAdapter::new(Provider::Claude, None, "");
2629
- let exclude = BTreeSet::new();
2630
- let result = recover_resume_session_from_events(
2631
- &workspace,
2632
- "release-engineer",
2633
- &previous,
2634
- &adapter,
2635
- crate::provider::AuthMode::Subscription,
2636
- &exclude,
2637
- )
2638
- .expect("recover call ok");
2639
-
2640
- assert!(
2641
- result.is_none(),
2642
- "E57 postflight: recover_resume_session_from_events must REFUSE \
2643
- to repair from a Claude leader-marker rollout (event_log_repair \
2644
- cannot resurrect a stale leader-to-worker assignment); got {result:?}"
2645
- );
2646
-
2647
- let _ = std::fs::remove_file(&rollout);
2648
- let _ = std::fs::remove_file(workspace.join(".team/logs/events.jsonl"));
2649
- let _ = std::fs::remove_dir_all(workspace.join(".team"));
2650
- let _ = std::fs::remove_dir_all(&workspace);
2651
- }
2652
-
2653
- /// S1-CAPTURE-001 (0.4.8): pending mismatch guard. When fresh-start has
2654
- /// written a new `_pending_session_id` but the old authoritative
2655
- /// `session_id` is still present and differs, `agent_session_complete`
2656
- /// must return false so capture re-runs and re-binds to the new process.
2657
- /// Without this, the historical poison state (old + new coexist) lets
2658
- /// the stale rollout look authoritative.
2659
- #[test]
2660
- fn agent_session_complete_returns_false_on_pending_mismatch() {
2661
- let dir = std::env::temp_dir().join(format!("ta-pending-mismatch-{}", std::process::id()));
2662
- let _ = std::fs::create_dir_all(&dir);
2663
- let rollout = dir.join("old.jsonl");
2664
- std::fs::write(&rollout, "{\"type\":\"assistant\"}\n").unwrap();
2665
-
2666
- let agent = serde_json::json!({
2667
- "provider": "claude",
2668
- "session_id": "old",
2669
- "rollout_path": rollout.to_string_lossy(),
2670
- "captured_at": "2026-01-01T00:00:00+00:00",
2671
- "captured_via": "fs_watch",
2672
- "_pending_session_id": "new",
2673
- });
2674
-
2675
- assert!(
2676
- !super::agent_session_complete(&agent),
2677
- "S1-CAPTURE-001: pending != session_id must force incomplete \
2678
- (capture must re-attribute to new session)"
2679
- );
2680
-
2681
- // Sanity: when they match, complete is true.
2682
- let agent_match = serde_json::json!({
2683
- "provider": "claude",
2684
- "session_id": "new",
2685
- "rollout_path": rollout.to_string_lossy(),
2686
- "captured_at": "2026-01-01T00:00:00+00:00",
2687
- "captured_via": "fs_watch",
2688
- "_pending_session_id": "new",
2689
- });
2690
- assert!(
2691
- super::agent_session_complete(&agent_match),
2692
- "pending == session_id (in-progress capture confirmed): must be complete"
2693
- );
2694
-
2695
- let _ = std::fs::remove_file(&rollout);
2696
- let _ = std::fs::remove_dir_all(&dir);
2697
- }
2698
-
2699
- /// S1-CAPTURE-001 (0.4.8): apply_captured_session clears
2700
- /// `_pending_session_id` and stamps `capture_state="captured"` so the
2701
- /// pending-mismatch guard doesn't fire on subsequent reads.
2702
- #[test]
2703
- fn apply_captured_session_clears_pending_and_stamps_capture_state() {
2704
- let mut agent = serde_json::Map::new();
2705
- agent.insert(
2706
- "_pending_session_id".to_string(),
2707
- serde_json::json!("new-sess"),
2708
- );
2709
- let captured = CapturedSession {
2710
- session_id: Some(SessionId::new("new-sess")),
2711
- rollout_path: Some(RolloutPath::new(PathBuf::from("/tmp/new.jsonl"))),
2712
- captured_via: CaptureVia::FsWatch,
2713
- attribution_confidence: Confidence::High,
2714
- spawn_cwd: PathBuf::from("/tmp/cwd"),
2715
- };
2716
- let written = super::apply_captured_session(&mut agent, &captured);
2717
- assert!(written, "apply must accept valid captured");
2718
- assert!(
2719
- agent.get("_pending_session_id").is_none(),
2720
- "S1-CAPTURE-001: _pending_session_id must be removed after capture \
2721
- (agent={agent:?})"
2722
- );
2723
- assert_eq!(
2724
- agent
2725
- .get("capture_state")
2726
- .and_then(serde_json::Value::as_str),
2727
- Some("captured"),
2728
- "S1-CAPTURE-001: capture_state must be stamped 'captured'"
2729
- );
2730
- }
2731
- }