@team-agent/installer 0.5.127 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (421) hide show
  1. package/README.md +15 -4
  2. package/README.zh.md +1 -1
  3. package/package.json +4 -8
  4. package/skills/team-agent/SKILL.md +41 -26
  5. package/skills/team-agent/command-coverage.json +170 -184
  6. package/skills/team-agent/docs/reference/team-agent-operator.md +66 -32
  7. package/skills/team-agent/references/recovery-runbook.md +1 -1
  8. package/skills/team-agent/references/team-agent-operator.md +66 -32
  9. package/templates/team_state.md +1 -1
  10. package/Cargo.lock +0 -1063
  11. package/Cargo.toml +0 -36
  12. package/crates/team-agent/Cargo.toml +0 -69
  13. package/crates/team-agent/src/app_server_test_support.rs +0 -258
  14. package/crates/team-agent/src/cli/adapters.rs +0 -1298
  15. package/crates/team-agent/src/cli/arguments.rs +0 -401
  16. package/crates/team-agent/src/cli/attach_app_server_leader.rs +0 -98
  17. package/crates/team-agent/src/cli/diagnose.rs +0 -1675
  18. package/crates/team-agent/src/cli/emit.rs +0 -2898
  19. package/crates/team-agent/src/cli/grok_slot.rs +0 -384
  20. package/crates/team-agent/src/cli/helpers.rs +0 -91
  21. package/crates/team-agent/src/cli/intent/runtime.rs +0 -1189
  22. package/crates/team-agent/src/cli/intent/runtime_tests.rs +0 -821
  23. package/crates/team-agent/src/cli/intent/tests.rs +0 -691
  24. package/crates/team-agent/src/cli/intent.rs +0 -664
  25. package/crates/team-agent/src/cli/leader.rs +0 -300
  26. package/crates/team-agent/src/cli/leader_prompt.rs +0 -261
  27. package/crates/team-agent/src/cli/leaders.rs +0 -418
  28. package/crates/team-agent/src/cli/mod.rs +0 -6528
  29. package/crates/team-agent/src/cli/models.rs +0 -449
  30. package/crates/team-agent/src/cli/named_address.rs +0 -1651
  31. package/crates/team-agent/src/cli/profile.rs +0 -342
  32. package/crates/team-agent/src/cli/route.rs +0 -212
  33. package/crates/team-agent/src/cli/send/coordinator.rs +0 -164
  34. package/crates/team-agent/src/cli/send/mailbox.rs +0 -145
  35. package/crates/team-agent/src/cli/send/persist.rs +0 -192
  36. package/crates/team-agent/src/cli/send/presentation.rs +0 -370
  37. package/crates/team-agent/src/cli/send/resolve.rs +0 -573
  38. package/crates/team-agent/src/cli/send.rs +0 -201
  39. package/crates/team-agent/src/cli/shutdown_socket.rs +0 -288
  40. package/crates/team-agent/src/cli/spec.rs +0 -159
  41. package/crates/team-agent/src/cli/status.rs +0 -280
  42. package/crates/team-agent/src/cli/status_port/agents.rs +0 -358
  43. package/crates/team-agent/src/cli/status_port/approvals.rs +0 -79
  44. package/crates/team-agent/src/cli/status_port/brief.rs +0 -2043
  45. package/crates/team-agent/src/cli/status_port/compact.rs +0 -240
  46. package/crates/team-agent/src/cli/status_port/format.rs +0 -146
  47. package/crates/team-agent/src/cli/status_port/inbox.rs +0 -62
  48. package/crates/team-agent/src/cli/status_port/runtime.rs +0 -197
  49. package/crates/team-agent/src/cli/status_port/snapshot.rs +0 -208
  50. package/crates/team-agent/src/cli/status_port/store.rs +0 -416
  51. package/crates/team-agent/src/cli/status_port/tests.rs +0 -90
  52. package/crates/team-agent/src/cli/status_port.rs +0 -92
  53. package/crates/team-agent/src/cli/tests/base.rs +0 -885
  54. package/crates/team-agent/src/cli/tests/divergence.rs +0 -518
  55. package/crates/team-agent/src/cli/tests/lane_c.rs +0 -453
  56. package/crates/team-agent/src/cli/tests/leader_watch.rs +0 -372
  57. package/crates/team-agent/src/cli/tests/main_preserved.rs +0 -430
  58. package/crates/team-agent/src/cli/tests/missing_subcommands.rs +0 -336
  59. package/crates/team-agent/src/cli/tests/mod.rs +0 -137
  60. package/crates/team-agent/src/cli/tests/named_address.rs +0 -760
  61. package/crates/team-agent/src/cli/tests/parser_safety.rs +0 -383
  62. package/crates/team-agent/src/cli/tests/run_delegation.rs +0 -481
  63. package/crates/team-agent/src/cli/tests/shutdown_kill_plan.rs +0 -2179
  64. package/crates/team-agent/src/cli/tests/status_brief.rs +0 -1514
  65. package/crates/team-agent/src/cli/tests/status_send.rs +0 -1091
  66. package/crates/team-agent/src/cli/tests/verb_install_skill.rs +0 -93
  67. package/crates/team-agent/src/cli/tests/verb_profile.rs +0 -392
  68. package/crates/team-agent/src/cli/triage.rs +0 -234
  69. package/crates/team-agent/src/cli/types.rs +0 -591
  70. package/crates/team-agent/src/codex_app_server.rs +0 -546
  71. package/crates/team-agent/src/communication_mode/mod.rs +0 -56
  72. package/crates/team-agent/src/compiler/tests.rs +0 -842
  73. package/crates/team-agent/src/compiler.rs +0 -691
  74. package/crates/team-agent/src/conpty/backend.rs +0 -829
  75. package/crates/team-agent/src/conpty/mod.rs +0 -33
  76. package/crates/team-agent/src/contract_runtime/backend.rs +0 -1610
  77. package/crates/team-agent/src/contract_runtime/commands.rs +0 -671
  78. package/crates/team-agent/src/contract_runtime/config.rs +0 -354
  79. package/crates/team-agent/src/contract_runtime/config_tests.rs +0 -56
  80. package/crates/team-agent/src/contract_runtime/discovery.rs +0 -438
  81. package/crates/team-agent/src/contract_runtime/fork.rs +0 -368
  82. package/crates/team-agent/src/contract_runtime/forward.rs +0 -288
  83. package/crates/team-agent/src/contract_runtime/framework.rs +0 -350
  84. package/crates/team-agent/src/contract_runtime/mcp.rs +0 -399
  85. package/crates/team-agent/src/contract_runtime/mod.rs +0 -17
  86. package/crates/team-agent/src/contract_runtime/prompt.rs +0 -216
  87. package/crates/team-agent/src/contract_runtime/pump.rs +0 -271
  88. package/crates/team-agent/src/contract_runtime/registry.rs +0 -589
  89. package/crates/team-agent/src/contract_runtime/workspace.rs +0 -228
  90. package/crates/team-agent/src/coordinator/backoff.rs +0 -741
  91. package/crates/team-agent/src/coordinator/conpty_shim.rs +0 -805
  92. package/crates/team-agent/src/coordinator/health.rs +0 -1185
  93. package/crates/team-agent/src/coordinator/mod.rs +0 -119
  94. package/crates/team-agent/src/coordinator/orphan.rs +0 -110
  95. package/crates/team-agent/src/coordinator/runtime_detectors.rs +0 -798
  96. package/crates/team-agent/src/coordinator/runtime_observation.rs +0 -84
  97. package/crates/team-agent/src/coordinator/steps/abnormal.rs +0 -2309
  98. package/crates/team-agent/src/coordinator/steps/delivery.rs +0 -15
  99. package/crates/team-agent/src/coordinator/steps/health_sync.rs +0 -15
  100. package/crates/team-agent/src/coordinator/steps/mod.rs +0 -126
  101. package/crates/team-agent/src/coordinator/steps/persist.rs +0 -15
  102. package/crates/team-agent/src/coordinator/steps/runtime_prompts.rs +0 -15
  103. package/crates/team-agent/src/coordinator/steps/session_gate.rs +0 -16
  104. package/crates/team-agent/src/coordinator/tests/a0_lostupdate.rs +0 -158
  105. package/crates/team-agent/src/coordinator/tests/abnormal.rs +0 -312
  106. package/crates/team-agent/src/coordinator/tests/api_error_recovery.rs +0 -338
  107. package/crates/team-agent/src/coordinator/tests/basics.rs +0 -211
  108. package/crates/team-agent/src/coordinator/tests/daemon.rs +0 -514
  109. package/crates/team-agent/src/coordinator/tests/energy.rs +0 -549
  110. package/crates/team-agent/src/coordinator/tests/health_sync.rs +0 -461
  111. package/crates/team-agent/src/coordinator/tests/main_preserved.rs +0 -186
  112. package/crates/team-agent/src/coordinator/tests/mod.rs +0 -295
  113. package/crates/team-agent/src/coordinator/tests/s3_bounded.rs +0 -207
  114. package/crates/team-agent/src/coordinator/tests/spine.rs +0 -308
  115. package/crates/team-agent/src/coordinator/tests/takeover.rs +0 -286
  116. package/crates/team-agent/src/coordinator/tests/tick_core.rs +0 -237
  117. package/crates/team-agent/src/coordinator/tick.rs +0 -3112
  118. package/crates/team-agent/src/coordinator/types.rs +0 -540
  119. package/crates/team-agent/src/db/agent_health_capture.rs +0 -126
  120. package/crates/team-agent/src/db/message_store.rs +0 -1585
  121. package/crates/team-agent/src/db/migration.rs +0 -984
  122. package/crates/team-agent/src/db/mod.rs +0 -26
  123. package/crates/team-agent/src/db/schema.rs +0 -663
  124. package/crates/team-agent/src/diagnose/comms.rs +0 -242
  125. package/crates/team-agent/src/diagnose/mod.rs +0 -44
  126. package/crates/team-agent/src/diagnose/orphans.rs +0 -889
  127. package/crates/team-agent/src/event_log.rs +0 -502
  128. package/crates/team-agent/src/fake_worker.rs +0 -303
  129. package/crates/team-agent/src/kill_audit.rs +0 -106
  130. package/crates/team-agent/src/layout/manager.rs +0 -248
  131. package/crates/team-agent/src/layout/mod.rs +0 -36
  132. package/crates/team-agent/src/layout/overlay.rs +0 -134
  133. package/crates/team-agent/src/layout/placement.rs +0 -52
  134. package/crates/team-agent/src/layout/recovery.rs +0 -106
  135. package/crates/team-agent/src/layout/runtime_sessions.rs +0 -317
  136. package/crates/team-agent/src/layout/sessions.rs +0 -294
  137. package/crates/team-agent/src/layout/tmux_endpoint.rs +0 -165
  138. package/crates/team-agent/src/layout/worker_env.rs +0 -721
  139. package/crates/team-agent/src/layout/worker_window_helpers.rs +0 -37
  140. package/crates/team-agent/src/leader/helpers.rs +0 -178
  141. package/crates/team-agent/src/leader/incident.rs +0 -6
  142. package/crates/team-agent/src/leader/lease.rs +0 -3356
  143. package/crates/team-agent/src/leader/mod.rs +0 -104
  144. package/crates/team-agent/src/leader/owner_bind.rs +0 -400
  145. package/crates/team-agent/src/leader/prompt.rs +0 -905
  146. package/crates/team-agent/src/leader/provider_attribution.rs +0 -247
  147. package/crates/team-agent/src/leader/rediscover/tests.rs +0 -689
  148. package/crates/team-agent/src/leader/rediscover.rs +0 -1192
  149. package/crates/team-agent/src/leader/registry.rs +0 -883
  150. package/crates/team-agent/src/leader/start.rs +0 -4500
  151. package/crates/team-agent/src/leader/takeover.rs +0 -65
  152. package/crates/team-agent/src/leader/tests/basics.rs +0 -337
  153. package/crates/team-agent/src/leader/tests/byte_findings.rs +0 -355
  154. package/crates/team-agent/src/leader/tests/claim_leader_mailbox_flush_contract.rs +0 -544
  155. package/crates/team-agent/src/leader/tests/historical_inventory_upgrade_gate_red.rs +0 -624
  156. package/crates/team-agent/src/leader/tests/identity.rs +0 -465
  157. package/crates/team-agent/src/leader/tests/identity_session_names.rs +0 -42
  158. package/crates/team-agent/src/leader/tests/idle.rs +0 -113
  159. package/crates/team-agent/src/leader/tests/lease_api.rs +0 -520
  160. package/crates/team-agent/src/leader/tests/lease_claim.rs +0 -629
  161. package/crates/team-agent/src/leader/tests/mod.rs +0 -106
  162. package/crates/team-agent/src/leader/tests/prompt_contract.rs +0 -267
  163. package/crates/team-agent/src/leader/tests/rediscover.rs +0 -403
  164. package/crates/team-agent/src/leader/tests/rehomed_env.rs +0 -83
  165. package/crates/team-agent/src/leader/tests/team_in_team_state_scope_red.rs +0 -1273
  166. package/crates/team-agent/src/leader/tests/terminal_and_replay_vs_rerender_invariants_red.rs +0 -417
  167. package/crates/team-agent/src/leader/tests/wake_start_owner.rs +0 -168
  168. package/crates/team-agent/src/leader/types.rs +0 -534
  169. package/crates/team-agent/src/lib.rs +0 -145
  170. package/crates/team-agent/src/lifecycle/helpers.rs +0 -212
  171. package/crates/team-agent/src/lifecycle/launch/add_agent.rs +0 -848
  172. package/crates/team-agent/src/lifecycle/launch/add_agent_state.rs +0 -393
  173. package/crates/team-agent/src/lifecycle/launch/agent_state.rs +0 -332
  174. package/crates/team-agent/src/lifecycle/launch/clone_agent.rs +0 -178
  175. package/crates/team-agent/src/lifecycle/launch/fork_agent.rs +0 -82
  176. package/crates/team-agent/src/lifecycle/launch/fork_entry.rs +0 -63
  177. package/crates/team-agent/src/lifecycle/launch/identity.rs +0 -674
  178. package/crates/team-agent/src/lifecycle/launch/layout.rs +0 -350
  179. package/crates/team-agent/src/lifecycle/launch/leader_context.rs +0 -589
  180. package/crates/team-agent/src/lifecycle/launch/mcp_config.rs +0 -152
  181. package/crates/team-agent/src/lifecycle/launch/ownership.rs +0 -105
  182. package/crates/team-agent/src/lifecycle/launch/pi_mcp.rs +0 -629
  183. package/crates/team-agent/src/lifecycle/launch/pi_mcp_extension.js +0 -226
  184. package/crates/team-agent/src/lifecycle/launch/plan.rs +0 -269
  185. package/crates/team-agent/src/lifecycle/launch/quick_start.rs +0 -5176
  186. package/crates/team-agent/src/lifecycle/launch/quick_start_transport.rs +0 -368
  187. package/crates/team-agent/src/lifecycle/launch/readiness.rs +0 -519
  188. package/crates/team-agent/src/lifecycle/launch/role_source.rs +0 -287
  189. package/crates/team-agent/src/lifecycle/launch/spawn.rs +0 -450
  190. package/crates/team-agent/src/lifecycle/launch/spec_state.rs +0 -801
  191. package/crates/team-agent/src/lifecycle/launch/state_projection.rs +0 -624
  192. package/crates/team-agent/src/lifecycle/launch/worker_env.rs +0 -558
  193. package/crates/team-agent/src/lifecycle/launch.rs +0 -534
  194. package/crates/team-agent/src/lifecycle/lock.rs +0 -350
  195. package/crates/team-agent/src/lifecycle/mod.rs +0 -79
  196. package/crates/team-agent/src/lifecycle/pane_input_lock.rs +0 -239
  197. package/crates/team-agent/src/lifecycle/profile_launch.rs +0 -757
  198. package/crates/team-agent/src/lifecycle/profile_smoke.rs +0 -557
  199. package/crates/team-agent/src/lifecycle/restart/agent.rs +0 -2198
  200. package/crates/team-agent/src/lifecycle/restart/common.rs +0 -2052
  201. package/crates/team-agent/src/lifecycle/restart/orchestrator.rs +0 -65
  202. package/crates/team-agent/src/lifecycle/restart/preflight.rs +0 -113
  203. package/crates/team-agent/src/lifecycle/restart/rebuild.rs +0 -5135
  204. package/crates/team-agent/src/lifecycle/restart/remove.rs +0 -1504
  205. package/crates/team-agent/src/lifecycle/restart/selection.rs +0 -559
  206. package/crates/team-agent/src/lifecycle/restart/team_state.rs +0 -329
  207. package/crates/team-agent/src/lifecycle/restart.rs +0 -223
  208. package/crates/team-agent/src/lifecycle/role_config.rs +0 -1205
  209. package/crates/team-agent/src/lifecycle/tests/acceptance_b_batch_red.rs +0 -1021
  210. package/crates/team-agent/src/lifecycle/tests/agent_ops.rs +0 -1205
  211. package/crates/team-agent/src/lifecycle/tests/b0_legacy_snapshot_nonauthority_contract.rs +0 -265
  212. package/crates/team-agent/src/lifecycle/tests/b0_reader_hideone_audit_contract.rs +0 -490
  213. package/crates/team-agent/src/lifecycle/tests/behavioral_diff_264_red.rs +0 -656
  214. package/crates/team-agent/src/lifecycle/tests/claude_profile_launch_red.rs +0 -135
  215. package/crates/team-agent/src/lifecycle/tests/cli_argv_routing_red.rs +0 -1415
  216. package/crates/team-agent/src/lifecycle/tests/clone_agent_preserves_source_tools.rs +0 -427
  217. package/crates/team-agent/src/lifecycle/tests/clone_fork_copilot_perms_red.rs +0 -396
  218. package/crates/team-agent/src/lifecycle/tests/communication_mode_runtime_contract_red.rs +0 -418
  219. package/crates/team-agent/src/lifecycle/tests/copilot_provider_red.rs +0 -2039
  220. package/crates/team-agent/src/lifecycle/tests/core.rs +0 -1298
  221. package/crates/team-agent/src/lifecycle/tests/f032_startup_prompt_best_effort_red.rs +0 -315
  222. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_g0.stdout.txt +0 -222
  223. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_spaced_ids.stdout.txt +0 -9
  224. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_native_mcp_host.mjs +0 -71
  225. package/crates/team-agent/src/lifecycle/tests/gate_fixtures.rs +0 -562
  226. package/crates/team-agent/src/lifecycle/tests/grok_require_explicit_model_red.rs +0 -110
  227. package/crates/team-agent/src/lifecycle/tests/harvest2_a_batch_red.rs +0 -472
  228. package/crates/team-agent/src/lifecycle/tests/host_cotenant_death_p0_contract.rs +0 -921
  229. package/crates/team-agent/src/lifecycle/tests/issue238_codex_effort_contract.rs +0 -68
  230. package/crates/team-agent/src/lifecycle/tests/lane_ops.rs +0 -1851
  231. package/crates/team-agent/src/lifecycle/tests/launch_spawn.rs +0 -3981
  232. package/crates/team-agent/src/lifecycle/tests/lifecycle_lock.rs +0 -339
  233. package/crates/team-agent/src/lifecycle/tests/lifecycle_rollback_red.rs +0 -596
  234. package/crates/team-agent/src/lifecycle/tests/main_preserved.rs +0 -513
  235. package/crates/team-agent/src/lifecycle/tests/mcp_tool_name_format_red.rs +0 -69
  236. package/crates/team-agent/src/lifecycle/tests/phase_b_contracts.rs +0 -824
  237. package/crates/team-agent/src/lifecycle/tests/phase_golden.rs +0 -723
  238. package/crates/team-agent/src/lifecycle/tests/pi_catalog_red.rs +0 -152
  239. package/crates/team-agent/src/lifecycle/tests/pi_command_red.rs +0 -182
  240. package/crates/team-agent/src/lifecycle/tests/pi_dual_entry_red.rs +0 -374
  241. package/crates/team-agent/src/lifecycle/tests/pi_executable_mcp_red.rs +0 -546
  242. package/crates/team-agent/src/lifecycle/tests/pi_lifecycle_doctor_red.rs +0 -31
  243. package/crates/team-agent/src/lifecycle/tests/pi_native_mcp_capability_red.rs +0 -528
  244. package/crates/team-agent/src/lifecycle/tests/pi_session_delivery_red.rs +0 -134
  245. package/crates/team-agent/src/lifecycle/tests/quick_start_worker_readiness_red.rs +0 -333
  246. package/crates/team-agent/src/lifecycle/tests/realmachine_clusters_1_6_red.rs +0 -786
  247. package/crates/team-agent/src/lifecycle/tests/realmachine_residual_g1_g4_red.rs +0 -648
  248. package/crates/team-agent/src/lifecycle/tests/restart.rs +0 -185
  249. package/crates/team-agent/src/lifecycle/tests/restart_build_before_destroy_0540_contract.rs +0 -1053
  250. package/crates/team-agent/src/lifecycle/tests/restart_liveness_red.rs +0 -679
  251. package/crates/team-agent/src/lifecycle/tests/restart_rebind_hotfix_252_red.rs +0 -1126
  252. package/crates/team-agent/src/lifecycle/tests/restart_session_capture_red.rs +0 -153
  253. package/crates/team-agent/src/lifecycle/tests/resume_recover_red.rs +0 -427
  254. package/crates/team-agent/src/lifecycle/tests/stale_team_saveconflict_contract.rs +0 -431
  255. package/crates/team-agent/src/lifecycle/tests/startup_latency_contract.rs +0 -1066
  256. package/crates/team-agent/src/lifecycle/tests/status_credential_redaction_contract.rs +0 -876
  257. package/crates/team-agent/src/lifecycle/tests/subprep_codex_trust_roundtrip_red.rs +0 -1026
  258. package/crates/team-agent/src/lifecycle/tests/swallow_batch4_semantics_red.rs +0 -90
  259. package/crates/team-agent/src/lifecycle/tests/team_in_team_identity_scope_red.rs +0 -543
  260. package/crates/team-agent/src/lifecycle/tests/team_in_team_sibling_quick_start_red.rs +0 -1103
  261. package/crates/team-agent/src/lifecycle/tests/team_in_team_state_scope_red.rs +0 -1276
  262. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_roster_red.rs +0 -145
  263. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_txn_red.rs +0 -603
  264. package/crates/team-agent/src/lifecycle/tests/test_isolation_escape_contract.rs +0 -936
  265. package/crates/team-agent/src/lifecycle/tests/upgrade_compat_0211_red.rs +0 -970
  266. package/crates/team-agent/src/lifecycle/tests/verify_rs031_window_consistency_red.rs +0 -996
  267. package/crates/team-agent/src/lifecycle/tests/worker_spawn_env_red.rs +0 -827
  268. package/crates/team-agent/src/lifecycle/tests.rs +0 -102
  269. package/crates/team-agent/src/lifecycle/types.rs +0 -861
  270. package/crates/team-agent/src/lifecycle/worker_command_context.rs +0 -370
  271. package/crates/team-agent/src/main.rs +0 -52
  272. package/crates/team-agent/src/mcp_server/helpers.rs +0 -510
  273. package/crates/team-agent/src/mcp_server/lifecycle_tools/mod.rs +0 -6
  274. package/crates/team-agent/src/mcp_server/lifecycle_tools/state_status.rs +0 -43
  275. package/crates/team-agent/src/mcp_server/mod.rs +0 -119
  276. package/crates/team-agent/src/mcp_server/normalize.rs +0 -485
  277. package/crates/team-agent/src/mcp_server/readiness.rs +0 -546
  278. package/crates/team-agent/src/mcp_server/readiness_tests.rs +0 -369
  279. package/crates/team-agent/src/mcp_server/tests/golden.rs +0 -285
  280. package/crates/team-agent/src/mcp_server/tests/normalize.rs +0 -247
  281. package/crates/team-agent/src/mcp_server/tests/scoped.rs +0 -168
  282. package/crates/team-agent/src/mcp_server/tests/send.rs +0 -388
  283. package/crates/team-agent/src/mcp_server/tests/tools.rs +0 -343
  284. package/crates/team-agent/src/mcp_server/tests/wire.rs +0 -254
  285. package/crates/team-agent/src/mcp_server/tests.rs +0 -43
  286. package/crates/team-agent/src/mcp_server/tools.rs +0 -1015
  287. package/crates/team-agent/src/mcp_server/types.rs +0 -396
  288. package/crates/team-agent/src/mcp_server/wire.rs +0 -867
  289. package/crates/team-agent/src/messaging/activity.rs +0 -461
  290. package/crates/team-agent/src/messaging/address.rs +0 -87
  291. package/crates/team-agent/src/messaging/delivery.rs +0 -3785
  292. package/crates/team-agent/src/messaging/delivery_consumption_tests.rs +0 -234
  293. package/crates/team-agent/src/messaging/enter_rescue.rs +0 -362
  294. package/crates/team-agent/src/messaging/enter_rescue_tests.rs +0 -633
  295. package/crates/team-agent/src/messaging/helpers.rs +0 -354
  296. package/crates/team-agent/src/messaging/leader_channel.rs +0 -287
  297. package/crates/team-agent/src/messaging/leader_receiver.rs +0 -786
  298. package/crates/team-agent/src/messaging/mod.rs +0 -166
  299. package/crates/team-agent/src/messaging/persist.rs +0 -377
  300. package/crates/team-agent/src/messaging/presentation.rs +0 -417
  301. package/crates/team-agent/src/messaging/results/collection_tests.rs +0 -719
  302. package/crates/team-agent/src/messaging/results.rs +0 -1415
  303. package/crates/team-agent/src/messaging/scheduler.rs +0 -217
  304. package/crates/team-agent/src/messaging/selftest.rs +0 -315
  305. package/crates/team-agent/src/messaging/send.rs +0 -981
  306. package/crates/team-agent/src/messaging/tests/basic.rs +0 -346
  307. package/crates/team-agent/src/messaging/tests/dup_inject.rs +0 -551
  308. package/crates/team-agent/src/messaging/tests/e23.rs +0 -49
  309. package/crates/team-agent/src/messaging/tests/leader_channel.rs +0 -169
  310. package/crates/team-agent/src/messaging/tests/leader_inject_acceptance.rs +0 -817
  311. package/crates/team-agent/src/messaging/tests/main_preserved.rs +0 -85
  312. package/crates/team-agent/src/messaging/tests/mod.rs +0 -306
  313. package/crates/team-agent/src/messaging/tests/runtime.rs +0 -3655
  314. package/crates/team-agent/src/messaging/tests/spine.rs +0 -837
  315. package/crates/team-agent/src/messaging/tests/wave2.rs +0 -381
  316. package/crates/team-agent/src/messaging/trust.rs +0 -215
  317. package/crates/team-agent/src/messaging/types.rs +0 -471
  318. package/crates/team-agent/src/messaging/wait.rs +0 -366
  319. package/crates/team-agent/src/messaging/watchers.rs +0 -916
  320. package/crates/team-agent/src/model/enums.rs +0 -356
  321. package/crates/team-agent/src/model/errors.rs +0 -18
  322. package/crates/team-agent/src/model/ids.rs +0 -165
  323. package/crates/team-agent/src/model/mod.rs +0 -29
  324. package/crates/team-agent/src/model/name_similarity.rs +0 -252
  325. package/crates/team-agent/src/model/pane_authority_refusal.rs +0 -359
  326. package/crates/team-agent/src/model/paths.rs +0 -257
  327. package/crates/team-agent/src/model/routing.rs +0 -387
  328. package/crates/team-agent/src/model/spec.rs +0 -1184
  329. package/crates/team-agent/src/model/task_graph.rs +0 -321
  330. package/crates/team-agent/src/model/testdata/fuzz.golden.yaml +0 -43
  331. package/crates/team-agent/src/model/testdata/fuzz.yaml +0 -43
  332. package/crates/team-agent/src/model/testdata/spec_invalid_a.yaml +0 -209
  333. package/crates/team-agent/src/model/testdata/team.spec.golden.yaml +0 -208
  334. package/crates/team-agent/src/model/testdata/team.spec.yaml +0 -208
  335. package/crates/team-agent/src/model/yaml/tests.rs +0 -188
  336. package/crates/team-agent/src/model/yaml.rs +0 -802
  337. package/crates/team-agent/src/os_probe.rs +0 -280
  338. package/crates/team-agent/src/packaging/install.rs +0 -219
  339. package/crates/team-agent/src/packaging/migrate.rs +0 -38
  340. package/crates/team-agent/src/packaging/mod.rs +0 -91
  341. package/crates/team-agent/src/packaging/repair.rs +0 -33
  342. package/crates/team-agent/src/packaging/tests.rs +0 -822
  343. package/crates/team-agent/src/packaging/types.rs +0 -417
  344. package/crates/team-agent/src/platform/argv.rs +0 -331
  345. package/crates/team-agent/src/platform/errors.rs +0 -104
  346. package/crates/team-agent/src/platform/file_lock.rs +0 -279
  347. package/crates/team-agent/src/platform/mod.rs +0 -5
  348. package/crates/team-agent/src/platform/process.rs +0 -545
  349. package/crates/team-agent/src/provider/adapter.rs +0 -898
  350. package/crates/team-agent/src/provider/adapters/copilot.rs +0 -75
  351. package/crates/team-agent/src/provider/adapters/copilot_fork.rs +0 -307
  352. package/crates/team-agent/src/provider/adapters/fake.rs +0 -18
  353. package/crates/team-agent/src/provider/adapters/mod.rs +0 -28
  354. package/crates/team-agent/src/provider/approvals/mod.rs +0 -3
  355. package/crates/team-agent/src/provider/approvals/parsing.rs +0 -586
  356. package/crates/team-agent/src/provider/approvals/runtime_prompts.rs +0 -205
  357. package/crates/team-agent/src/provider/argv_route.rs +0 -405
  358. package/crates/team-agent/src/provider/bypass_flags.rs +0 -116
  359. package/crates/team-agent/src/provider/classify.rs +0 -773
  360. package/crates/team-agent/src/provider/command_helpers.rs +0 -45
  361. package/crates/team-agent/src/provider/faults.rs +0 -165
  362. package/crates/team-agent/src/provider/helpers.rs +0 -52
  363. package/crates/team-agent/src/provider/mod.rs +0 -78
  364. package/crates/team-agent/src/provider/model_catalog.rs +0 -722
  365. package/crates/team-agent/src/provider/session/capture.rs +0 -2631
  366. package/crates/team-agent/src/provider/session/context_fork/outcome.rs +0 -168
  367. package/crates/team-agent/src/provider/session/context_fork.rs +0 -264
  368. package/crates/team-agent/src/provider/session/mod.rs +0 -36
  369. package/crates/team-agent/src/provider/session/resume.rs +0 -269
  370. package/crates/team-agent/src/provider/session_scan/common/tests.rs +0 -316
  371. package/crates/team-agent/src/provider/session_scan/common.rs +0 -618
  372. package/crates/team-agent/src/provider/session_scan/copilot.rs +0 -280
  373. package/crates/team-agent/src/provider/session_scan/pi.rs +0 -152
  374. package/crates/team-agent/src/provider/session_scan.rs +0 -61
  375. package/crates/team-agent/src/provider/startup_prompt.rs +0 -757
  376. package/crates/team-agent/src/provider/submit_now.rs +0 -71
  377. package/crates/team-agent/src/provider/testdata/copilot-ready-marker.txt +0 -5
  378. package/crates/team-agent/src/provider/testdata/copilot-trust-prompt.txt +0 -19
  379. package/crates/team-agent/src/provider/testdata/grok-models-authenticated.stdout +0 -9
  380. package/crates/team-agent/src/provider/testdata/grok-models-unauthenticated.stdout +0 -7
  381. package/crates/team-agent/src/provider/tests/adapter.rs +0 -354
  382. package/crates/team-agent/src/provider/tests/classify.rs +0 -201
  383. package/crates/team-agent/src/provider/tests/command_helpers.rs +0 -26
  384. package/crates/team-agent/src/provider/tests/copilot_fork.rs +0 -191
  385. package/crates/team-agent/src/provider/tests/faults.rs +0 -200
  386. package/crates/team-agent/src/provider/tests/idle.rs +0 -140
  387. package/crates/team-agent/src/provider/tests/wire.rs +0 -213
  388. package/crates/team-agent/src/provider/tests.rs +0 -32
  389. package/crates/team-agent/src/provider/types.rs +0 -529
  390. package/crates/team-agent/src/provider/wire.rs +0 -406
  391. package/crates/team-agent/src/redaction.rs +0 -259
  392. package/crates/team-agent/src/state/abnormal_watch/tests/mod.rs +0 -248
  393. package/crates/team-agent/src/state/abnormal_watch.rs +0 -144
  394. package/crates/team-agent/src/state/identity.rs +0 -914
  395. package/crates/team-agent/src/state/identity_keys.rs +0 -132
  396. package/crates/team-agent/src/state/mod.rs +0 -74
  397. package/crates/team-agent/src/state/owner_gate.rs +0 -482
  398. package/crates/team-agent/src/state/ownership.rs +0 -563
  399. package/crates/team-agent/src/state/paths.rs +0 -395
  400. package/crates/team-agent/src/state/persist.rs +0 -3811
  401. package/crates/team-agent/src/state/projection.rs +0 -1508
  402. package/crates/team-agent/src/state/repository/intent.rs +0 -14
  403. package/crates/team-agent/src/state/repository/tests.rs +0 -184
  404. package/crates/team-agent/src/state/repository.rs +0 -866
  405. package/crates/team-agent/src/state/selector.rs +0 -160
  406. package/crates/team-agent/src/state/testdata/state-rich.canonical.json +0 -133
  407. package/crates/team-agent/src/tmux_backend/enter_rescue.rs +0 -325
  408. package/crates/team-agent/src/tmux_backend/enter_rescue_tests.rs +0 -432
  409. package/crates/team-agent/src/tmux_backend/native_input.rs +0 -513
  410. package/crates/team-agent/src/tmux_backend/native_input_tests.rs +0 -742
  411. package/crates/team-agent/src/tmux_backend/tests.rs +0 -4254
  412. package/crates/team-agent/src/tmux_backend.rs +0 -4527
  413. package/crates/team-agent/src/topology.rs +0 -537
  414. package/crates/team-agent/src/transport/enter_rescue.rs +0 -166
  415. package/crates/team-agent/src/transport/native_input.rs +0 -491
  416. package/crates/team-agent/src/transport/test_support.rs +0 -743
  417. package/crates/team-agent/src/transport/tests/behavior.rs +0 -326
  418. package/crates/team-agent/src/transport/tests/mod.rs +0 -194
  419. package/crates/team-agent/src/transport/tests/wire.rs +0 -574
  420. package/crates/team-agent/src/transport.rs +0 -1655
  421. package/crates/team-agent/src/transport_factory.rs +0 -819
@@ -1,1415 +0,0 @@
1
- //!
2
- //! results.py — report_result + envelope 校验编排 (card §66/§67)。
3
-
4
- use std::path::{Path, PathBuf};
5
-
6
- use rusqlite::params;
7
-
8
- use crate::event_log::EventLog;
9
- use crate::message_store::MessageStore;
10
- use crate::model::ids::TaskId;
11
-
12
- use super::helpers::{next_result_id, required_str, validate_result_envelope};
13
- use super::types::SEND_RETRY_MAX_ATTEMPTS;
14
- use super::MessagingError;
15
- use crate::state::projection::OwnerTeamResolution;
16
-
17
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
18
- pub enum ResultRoute {
19
- Leader,
20
- Pipeline,
21
- }
22
-
23
- impl ResultRoute {
24
- pub const ALL: [Self; 2] = [Self::Leader, Self::Pipeline];
25
-
26
- pub const fn as_str(self) -> &'static str {
27
- match self {
28
- Self::Leader => "leader",
29
- Self::Pipeline => "pipeline",
30
- }
31
- }
32
-
33
- pub fn parse(value: &str) -> Option<Self> {
34
- match value {
35
- "leader" => Some(Self::Leader),
36
- "pipeline" => Some(Self::Pipeline),
37
- _ => None,
38
- }
39
- }
40
- }
41
-
42
- impl Default for ResultRoute {
43
- fn default() -> Self {
44
- Self::Leader
45
- }
46
- }
47
-
48
- /// `collect` (`results.py:45`):投递 pending、捞 uncollected results、校验 envelope、更新任务态、
49
- /// 写 team_state、ensure coordinator。CLI `collect` + coordinator tick 调。
50
- pub fn collect(
51
- workspace: &Path,
52
- result_file: Option<&Path>,
53
- ensure_coordinator: bool,
54
- ) -> Result<serde_json::Value, MessagingError> {
55
- collect_scoped(workspace, result_file, ensure_coordinator, None)
56
- }
57
-
58
- pub fn collect_for_team(
59
- workspace: &Path,
60
- result_file: Option<&Path>,
61
- ensure_coordinator: bool,
62
- owner_team_id: Option<&str>,
63
- ) -> Result<serde_json::Value, MessagingError> {
64
- collect_scoped(workspace, result_file, ensure_coordinator, owner_team_id)
65
- }
66
-
67
- fn collect_scoped(
68
- workspace: &Path,
69
- result_file: Option<&Path>,
70
- ensure_coordinator: bool,
71
- owner_team_id: Option<&str>,
72
- ) -> Result<serde_json::Value, MessagingError> {
73
- let paths = collect_paths(workspace)?;
74
- #[cfg(test)]
75
- collection_tests::boundary("before_lock")?;
76
- // Serialize collectors, but do not hold a SQLite write transaction while
77
- // committing state. A process exit releases this existing OS file lock.
78
- let collection_lock =
79
- crate::state::persist::acquire_result_collection_lock(&paths.run_workspace)?;
80
- let log = EventLog::new(&paths.run_workspace);
81
- let resolved_owner_team_id = match owner_team_id.filter(|team| !team.is_empty()) {
82
- Some(team) => Some(resolve_owner_team_for_read(
83
- &paths.run_workspace,
84
- team,
85
- Some(&log),
86
- )?),
87
- None => None,
88
- };
89
- let owner_team_id = resolved_owner_team_id.as_deref();
90
- let mut state = match owner_team_id {
91
- Some(team) => {
92
- crate::state::projection::select_runtime_state(&paths.run_workspace, Some(team))?
93
- }
94
- None => crate::state::persist::load_runtime_state(&paths.run_workspace)?,
95
- };
96
- let spec_workspace = owner_team_id
97
- .and_then(|_| state_spec_workspace_from_value(&state))
98
- .unwrap_or_else(|| paths.spec_workspace.clone());
99
- let spec_path = spec_workspace.join("team.spec.yaml");
100
- if !spec_path.exists() {
101
- return Err(MessagingError::Validation(format!(
102
- "Cannot read {}",
103
- spec_path.display()
104
- )));
105
- }
106
- let store = MessageStore::open(&paths.run_workspace)?;
107
- let conn = crate::db::schema::open_db(store.db_path())?;
108
- if let Some(path) = result_file {
109
- #[cfg(test)]
110
- collection_tests::boundary("before_ingest")?;
111
- ingest_result_file(&conn, path, owner_team_id)?;
112
- #[cfg(test)]
113
- collection_tests::boundary("after_ingest")?;
114
- }
115
- let sql = match owner_team_id {
116
- Some(_) => {
117
- "select result_id, task_id, agent_id, envelope, status, created_at
118
- from results
119
- where status not in ('collected', 'invalid') and owner_team_id = ?1
120
- order by created_at, result_id"
121
- }
122
- None => {
123
- "select result_id, task_id, agent_id, envelope, status, created_at
124
- from results
125
- where status not in ('collected', 'invalid')
126
- order by created_at, result_id"
127
- }
128
- };
129
- let mut stmt = conn.prepare(sql)?;
130
- let row_mapper = |row: &rusqlite::Row<'_>| {
131
- Ok(StoredResult {
132
- result_id: row.get(0)?,
133
- task_id: row.get(1)?,
134
- agent_id: row.get(2)?,
135
- envelope: row.get(3)?,
136
- status: row.get(4)?,
137
- created_at: row.get(5)?,
138
- })
139
- };
140
- let rows = match owner_team_id {
141
- Some(team) => stmt.query_map(params![team], row_mapper),
142
- None => stmt.query_map([], row_mapper),
143
- }?
144
- .collect::<Result<Vec<_>, _>>()?;
145
- drop(stmt);
146
-
147
- let mut collected = Vec::new();
148
- let mut collected_results = Vec::new();
149
- let mut invalid_results = Vec::new();
150
- let mut fatal_invalid_results = 0usize;
151
- let mut ready = Vec::new();
152
- let mut task_updates = Vec::new();
153
- for row in rows {
154
- let envelope: serde_json::Value = match serde_json::from_str(&row.envelope) {
155
- Ok(envelope) => envelope,
156
- Err(error) => {
157
- fatal_invalid_results = fatal_invalid_results.saturating_add(1);
158
- record_invalid_result(
159
- &conn,
160
- &mut invalid_results,
161
- &row,
162
- result_file,
163
- &error.to_string(),
164
- )?;
165
- continue;
166
- }
167
- };
168
- if let Err(error) = validate_result_envelope(&envelope) {
169
- fatal_invalid_results = fatal_invalid_results.saturating_add(1);
170
- record_invalid_result(
171
- &conn,
172
- &mut invalid_results,
173
- &row,
174
- result_file,
175
- &error.to_string(),
176
- )?;
177
- continue;
178
- }
179
- let scope = if task_exists(&state, &row.task_id) {
180
- "task"
181
- } else if is_message_scoped_result(&conn, &row.task_id, &row.agent_id, owner_team_id)? {
182
- "message"
183
- } else {
184
- if result_file.is_some() || row.task_id != "manual" {
185
- fatal_invalid_results = fatal_invalid_results.saturating_add(1);
186
- }
187
- record_invalid_result(
188
- &conn,
189
- &mut invalid_results,
190
- &row,
191
- result_file,
192
- &format!("unknown task id: {}", row.task_id),
193
- )?;
194
- continue;
195
- };
196
- if scope == "task" {
197
- task_updates.push((row.task_id.clone(), row.result_id.clone()));
198
- }
199
- ready.push((row, envelope, scope));
200
- }
201
- // Pending DB rows remain eligible until the complete task delta is durable.
202
- // Preserve the original created_at/result_id order: its last row per task wins.
203
- if !task_updates.is_empty() {
204
- let mut task_winners = Vec::new();
205
- let mut updated = std::collections::BTreeSet::new();
206
- for (task_id, result_id) in task_updates.iter().rev() {
207
- if updated.insert(task_id) {
208
- task_winners.push((task_id.clone(), result_id.clone()));
209
- }
210
- }
211
- #[cfg(test)]
212
- collection_tests::boundary("before_state")?;
213
- state = crate::state::repository::StateRepository::new(&paths.run_workspace).commit(
214
- crate::state::repository::StateWriteIntent::ResultCollection { owner_team_id },
215
- |latest| {
216
- for (task_id, result_id) in &task_winners {
217
- let already_applied = latest
218
- .get("tasks")
219
- .and_then(serde_json::Value::as_array)
220
- .is_some_and(|tasks| {
221
- tasks.iter().any(|task| {
222
- task.get("id").and_then(serde_json::Value::as_str)
223
- == Some(task_id.as_str())
224
- && task.get("status").and_then(serde_json::Value::as_str)
225
- == Some("done")
226
- && task
227
- .get("accepted_result_id")
228
- .and_then(serde_json::Value::as_str)
229
- == Some(result_id.as_str())
230
- })
231
- });
232
- if !already_applied {
233
- mark_task_done(latest, task_id, result_id);
234
- }
235
- }
236
- },
237
- )?;
238
- for (task_id, result_id) in &task_winners {
239
- let applied = state
240
- .get("tasks")
241
- .and_then(serde_json::Value::as_array)
242
- .is_some_and(|tasks| {
243
- tasks.iter().any(|task| {
244
- task.get("id").and_then(serde_json::Value::as_str) == Some(task_id.as_str())
245
- && task.get("status").and_then(serde_json::Value::as_str)
246
- == Some("done")
247
- && task
248
- .get("accepted_result_id")
249
- .and_then(serde_json::Value::as_str)
250
- == Some(result_id.as_str())
251
- })
252
- });
253
- if !applied {
254
- return Err(MessagingError::Validation(format!(
255
- "task result projection missing after commit: task_id={task_id} result_id={result_id}"
256
- )));
257
- }
258
- }
259
- #[cfg(test)]
260
- collection_tests::boundary("after_state")?;
261
- }
262
- for (row, envelope, scope) in ready {
263
- #[cfg(test)]
264
- collection_tests::boundary("before_event")?;
265
- log.write(
266
- "collect.result",
267
- serde_json::json!({
268
- "result_id": row.result_id,
269
- "task_id": row.task_id,
270
- "agent_id": row.agent_id,
271
- "scope": scope,
272
- }),
273
- )?;
274
- #[cfg(test)]
275
- collection_tests::boundary("after_event")?;
276
- #[cfg(test)]
277
- collection_tests::boundary("before_finalize")?;
278
- let finalized = match owner_team_id {
279
- Some(team) => {
280
- conn.execute(
281
- "update results set status = 'collected' where result_id = ?1 and owner_team_id = ?2 and status not in ('collected', 'invalid')",
282
- params![row.result_id.as_str(), team],
283
- )?
284
- }
285
- None => {
286
- conn.execute(
287
- "update results set status = 'collected' where result_id = ?1 and status not in ('collected', 'invalid')",
288
- params![row.result_id.as_str()],
289
- )?
290
- }
291
- };
292
- #[cfg(test)]
293
- collection_tests::boundary("after_finalize")?;
294
- if finalized == 0 {
295
- continue;
296
- }
297
- collected.push(envelope.clone());
298
- let summary = serde_json::json!({
299
- "result_id": row.result_id,
300
- "task_id": row.task_id,
301
- "agent_id": row.agent_id,
302
- "status": envelope
303
- .get("status")
304
- .cloned()
305
- .unwrap_or_else(|| serde_json::Value::String(row.status)),
306
- "summary": envelope.get("summary").cloned().unwrap_or(serde_json::Value::Null),
307
- "tests": envelope.get("tests").cloned().unwrap_or_else(|| serde_json::json!([])),
308
- "created_at": row.created_at,
309
- "scope": scope,
310
- });
311
- collected_results.push(summary);
312
- }
313
- let counts = result_counts(&conn, owner_team_id)?;
314
- drop(collection_lock);
315
- // results.py:157 — ensure_coordinator=true runs the REAL ensure step; the
316
- // `{ok:false,status:"not_required"}` literal is ONLY the ensure=false branch.
317
- let coordinator = if ensure_coordinator {
318
- ensure_coordinator_after_collect(&paths.run_workspace, &state, &log)
319
- } else {
320
- serde_json::json!({"ok": false, "status": "not_required"})
321
- };
322
- Ok(serde_json::json!({
323
- "ok": fatal_invalid_results == 0,
324
- "collected": collected,
325
- "collected_results": collected_results,
326
- "delivered_messages": [],
327
- "invalid_results": invalid_results,
328
- "results": counts,
329
- "state_file": spec_workspace.join("team_state.md").to_string_lossy().to_string(),
330
- "coordinator": coordinator,
331
- }))
332
- }
333
-
334
- /// `_ensure_coordinator_after_collect`(`results.py:176-184`)。
335
- fn ensure_coordinator_after_collect(
336
- workspace: &Path,
337
- state: &serde_json::Value,
338
- log: &EventLog,
339
- ) -> serde_json::Value {
340
- if !coordinator_should_run(state) {
341
- return serde_json::json!({"ok": false, "status": "not_required"});
342
- }
343
- let workspace_path = crate::coordinator::WorkspacePath::new(workspace.to_path_buf());
344
- let coordinator = match crate::coordinator::start_coordinator(&workspace_path) {
345
- Ok(report) => start_report_value(&report),
346
- Err(e) => {
347
- serde_json::json!({"ok": false, "status": "start_failed", "error": e.to_string()})
348
- }
349
- };
350
- let _ = log.write(
351
- "collect.coordinator_checked",
352
- serde_json::json!({"coordinator": coordinator.clone()}),
353
- );
354
- coordinator
355
- }
356
-
357
- /// `_coordinator_should_run`(`results.py:187-188`)。
358
- ///
359
- /// The top-level `state.leader_receiver` read below is a coordinator-scope
360
- /// legacy compat bridge (pre-teams-map single-team layout) — deliberately
361
- /// NOT team-scoped because this predicate answers "is a coordinator worth
362
- /// starting for this workspace at all?" and does not itself route any
363
- /// message. The `ALLOWED-LEGACY-READ` marker documents the exception and
364
- /// keeps grep sweeps honest; delete once B1 canonical layout lands and
365
- /// every state carries a `teams` map
366
- /// (`.team/artifacts/next-version-staged-plan.md §5 Phase-Foundation-1`).
367
- fn coordinator_should_run(state: &serde_json::Value) -> bool {
368
- let has_session = state
369
- .get("session_name")
370
- .and_then(serde_json::Value::as_str)
371
- .is_some_and(|s| !s.is_empty());
372
- // ALLOWED-LEGACY-READ: pre-teams-map coordinator-scope existence probe; never used for routing.
373
- has_session || leader_receiver_is_direct(state.get("leader_receiver"))
374
- }
375
-
376
- /// `_leader_receiver_is_direct`(`messaging/leader.py:449-450`)。
377
- fn leader_receiver_is_direct(receiver: Option<&serde_json::Value>) -> bool {
378
- receiver.is_some_and(|receiver| {
379
- receiver.get("mode").and_then(serde_json::Value::as_str) == Some("direct_tmux")
380
- && receiver
381
- .get("pane_id")
382
- .and_then(serde_json::Value::as_str)
383
- .is_some_and(|pane| !pane.is_empty())
384
- })
385
- }
386
-
387
- /// `start_coordinator` dict 形(`lifecycle.py:54/86/121` 的 JSON 面)。
388
- fn start_report_value(report: &crate::coordinator::StartReport) -> serde_json::Value {
389
- let status = match report.status {
390
- crate::coordinator::StartOutcome::AlreadyRunning => "already_running",
391
- crate::coordinator::StartOutcome::RestartIncompatibleStopFailed => {
392
- "restart_incompatible_stop_failed"
393
- }
394
- crate::coordinator::StartOutcome::SchemaIncompatible => "schema_incompatible",
395
- crate::coordinator::StartOutcome::Started => "started",
396
- crate::coordinator::StartOutcome::StartedAfterRotation => "started_after_rotation",
397
- };
398
- let mut value = serde_json::json!({
399
- "ok": report.ok,
400
- "pid": report.pid.map(|p| p.get()),
401
- "status": status,
402
- "binary_path": report.binary_path.clone(),
403
- "binary_version": report.binary_version.clone(),
404
- "rotation_reason": report.rotation_reason.clone(),
405
- });
406
- if let Some(previous_pid) = report.previous_pid {
407
- value["previous_pid"] = serde_json::json!(previous_pid.get());
408
- }
409
- if let Some(log) = &report.log {
410
- value["log"] = serde_json::json!(log.to_string_lossy().to_string());
411
- }
412
- if let Some(error) = &report.schema_error {
413
- value["schema_error"] = serde_json::json!(format!("{error:?}"));
414
- }
415
- if let Some(action) = &report.action {
416
- value["action"] = serde_json::json!(action);
417
- }
418
- value
419
- }
420
-
421
- fn resolve_owner_team_for_read(
422
- workspace: &Path,
423
- requested: &str,
424
- event_log: Option<&EventLog>,
425
- ) -> Result<String, MessagingError> {
426
- let state = crate::state::persist::load_runtime_state(workspace)?;
427
- match crate::state::projection::resolve_owner_team_id(&state, requested) {
428
- OwnerTeamResolution::Canonical(canonical) => Ok(canonical),
429
- OwnerTeamResolution::LegacyAlias {
430
- requested,
431
- canonical,
432
- } => {
433
- crate::messaging::delivery::normalize_owner_team_id_rows(
434
- workspace, &requested, &canonical, None, event_log,
435
- )?;
436
- Ok(canonical)
437
- }
438
- OwnerTeamResolution::Unresolved { requested } => Err(MessagingError::Routing(format!(
439
- "owner_team_unresolved: {requested}"
440
- ))),
441
- OwnerTeamResolution::Ambiguous { requested, matches } => {
442
- Err(MessagingError::Routing(format!(
443
- "owner_team_ambiguous: {requested} matches {}",
444
- matches.join(",")
445
- )))
446
- }
447
- }
448
- }
449
-
450
- struct CollectPaths {
451
- run_workspace: PathBuf,
452
- spec_workspace: PathBuf,
453
- }
454
-
455
- fn collect_paths(workspace: &Path) -> Result<CollectPaths, MessagingError> {
456
- if collect_input_has_no_local_team_context(workspace) {
457
- return Ok(CollectPaths {
458
- run_workspace: workspace.to_path_buf(),
459
- spec_workspace: workspace.to_path_buf(),
460
- });
461
- }
462
- let run_workspace = crate::model::paths::canonical_run_workspace(workspace)
463
- .map_err(|e| MessagingError::Routing(e.to_string()))?;
464
- let spec_workspace = if workspace.join("team.spec.yaml").exists() {
465
- workspace.to_path_buf()
466
- } else if run_workspace.join("team.spec.yaml").exists() {
467
- run_workspace.clone()
468
- } else {
469
- state_spec_workspace(&run_workspace).unwrap_or_else(|| run_workspace.clone())
470
- };
471
- Ok(CollectPaths {
472
- run_workspace,
473
- spec_workspace,
474
- })
475
- }
476
-
477
- fn collect_input_has_no_local_team_context(workspace: &Path) -> bool {
478
- !workspace.join("team.spec.yaml").exists()
479
- && !workspace.join(".team").exists()
480
- && !crate::state::persist::runtime_state_path(workspace).exists()
481
- && workspace.file_name().and_then(|s| s.to_str()) != Some(".team")
482
- && workspace
483
- .parent()
484
- .and_then(|p| p.file_name())
485
- .and_then(|s| s.to_str())
486
- != Some(".team")
487
- }
488
-
489
- fn state_spec_workspace(run_workspace: &Path) -> Option<PathBuf> {
490
- let state = crate::state::persist::load_runtime_state(run_workspace).ok()?;
491
- state_spec_workspace_from_value(&state)
492
- }
493
-
494
- fn state_spec_workspace_from_value(state: &serde_json::Value) -> Option<PathBuf> {
495
- if let Some(spec_path) = state.get("spec_path").and_then(serde_json::Value::as_str) {
496
- return PathBuf::from(spec_path).parent().map(Path::to_path_buf);
497
- }
498
- state
499
- .get("team_dir")
500
- .and_then(serde_json::Value::as_str)
501
- .map(PathBuf::from)
502
- }
503
-
504
- fn record_invalid_result(
505
- conn: &rusqlite::Connection,
506
- invalid_results: &mut Vec<serde_json::Value>,
507
- row: &StoredResult,
508
- result_file: Option<&Path>,
509
- error: &str,
510
- ) -> Result<(), MessagingError> {
511
- conn.execute(
512
- "update results set status = 'invalid' where result_id = ?1",
513
- params![row.result_id.as_str()],
514
- )?;
515
- invalid_results.push(serde_json::json!({
516
- "result_id": row.result_id,
517
- "task_id": row.task_id,
518
- "agent_id": row.agent_id,
519
- "path": result_file.map(|p| p.to_string_lossy().to_string()),
520
- "error": error,
521
- }));
522
- Ok(())
523
- }
524
-
525
- fn ingest_result_file(
526
- conn: &rusqlite::Connection,
527
- path: &Path,
528
- owner_team_id: Option<&str>,
529
- ) -> Result<(), MessagingError> {
530
- let raw = std::fs::read_to_string(path)?;
531
- let mut envelope: serde_json::Value = serde_json::from_str(&raw)?;
532
- validate_result_envelope(&envelope)?;
533
- let result_id = envelope
534
- .get("result_id")
535
- .and_then(serde_json::Value::as_str)
536
- .map_or_else(next_result_id, ToString::to_string);
537
- if envelope.get("result_id").is_none() {
538
- if let Some(obj) = envelope.as_object_mut() {
539
- obj.insert(
540
- "result_id".to_string(),
541
- serde_json::Value::String(result_id.clone()),
542
- );
543
- }
544
- }
545
- let task_id = required_str(&envelope, "task_id")?;
546
- let agent_id = required_str(&envelope, "agent_id")?;
547
- let status = required_str(&envelope, "status")?;
548
- insert_result_if_absent(
549
- conn,
550
- &result_id,
551
- task_id,
552
- agent_id,
553
- &envelope.to_string(),
554
- status,
555
- owner_team_id,
556
- )?;
557
- Ok(())
558
- }
559
-
560
- struct StoredResult {
561
- result_id: String,
562
- task_id: String,
563
- agent_id: String,
564
- envelope: String,
565
- status: String,
566
- created_at: String,
567
- }
568
-
569
- fn mark_task_done(state: &mut serde_json::Value, task_id: &str, result_id: &str) {
570
- let Some(tasks) = state
571
- .get_mut("tasks")
572
- .and_then(serde_json::Value::as_array_mut)
573
- else {
574
- return;
575
- };
576
- for task in tasks {
577
- if task.get("id").and_then(serde_json::Value::as_str) != Some(task_id) {
578
- continue;
579
- }
580
- if let Some(obj) = task.as_object_mut() {
581
- obj.insert(
582
- "status".to_string(),
583
- serde_json::Value::String("done".to_string()),
584
- );
585
- obj.insert(
586
- "accepted_result_id".to_string(),
587
- serde_json::Value::String(result_id.to_string()),
588
- );
589
- }
590
- }
591
- }
592
-
593
- fn task_exists(state: &serde_json::Value, task_id: &str) -> bool {
594
- state
595
- .get("tasks")
596
- .and_then(serde_json::Value::as_array)
597
- .is_some_and(|tasks| {
598
- tasks
599
- .iter()
600
- .any(|task| task.get("id").and_then(serde_json::Value::as_str) == Some(task_id))
601
- })
602
- }
603
-
604
- fn task_exists_for_owner(state: &serde_json::Value, owner_team: &str, task_id: &str) -> bool {
605
- state
606
- .get("teams")
607
- .and_then(|teams| teams.get(owner_team))
608
- .is_some_and(|team| task_exists(team, task_id))
609
- || task_exists(state, task_id)
610
- }
611
-
612
- fn is_message_scoped_result(
613
- conn: &rusqlite::Connection,
614
- task_id: &str,
615
- agent_id: &str,
616
- owner_team_id: Option<&str>,
617
- ) -> Result<bool, MessagingError> {
618
- if !task_id.starts_with("msg_") {
619
- return Ok(false);
620
- }
621
- let count: i64 = match owner_team_id {
622
- Some(team) => conn.query_row(
623
- "select count(*) from messages where message_id = ?1 and recipient = ?2 and owner_team_id = ?3",
624
- params![task_id, agent_id, team],
625
- |row| row.get(0),
626
- )?,
627
- None => conn.query_row(
628
- "select count(*) from messages where message_id = ?1 and recipient = ?2",
629
- params![task_id, agent_id],
630
- |row| row.get(0),
631
- )?,
632
- };
633
- Ok(count > 0)
634
- }
635
-
636
- fn result_counts(
637
- conn: &rusqlite::Connection,
638
- owner_team_id: Option<&str>,
639
- ) -> Result<serde_json::Value, MessagingError> {
640
- let total: i64 = count_results(conn, owner_team_id, None)?;
641
- let collected: i64 = count_results(conn, owner_team_id, Some("collected"))?;
642
- let invalid: i64 = count_results(conn, owner_team_id, Some("invalid"))?;
643
- let uncollected = total - collected - invalid;
644
- let mut by_status = serde_json::Map::new();
645
- let sql = match owner_team_id {
646
- Some(_) => {
647
- "select status, count(*) from results
648
- where status not in ('collected', 'invalid') and owner_team_id = ?1
649
- group by status
650
- order by status"
651
- }
652
- None => {
653
- "select status, count(*) from results
654
- where status not in ('collected', 'invalid')
655
- group by status
656
- order by status"
657
- }
658
- };
659
- let mut stmt = conn.prepare(sql)?;
660
- let row_mapper =
661
- |row: &rusqlite::Row<'_>| Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?));
662
- let rows = match owner_team_id {
663
- Some(team) => stmt.query_map(params![team], row_mapper),
664
- None => stmt.query_map([], row_mapper),
665
- }?;
666
- for row in rows {
667
- let (status, count) = row?;
668
- by_status.insert(status, serde_json::Value::Number(count.into()));
669
- }
670
- Ok(serde_json::json!({
671
- "total": total,
672
- "uncollected": uncollected,
673
- "collected": collected,
674
- "invalid": invalid,
675
- "by_status": by_status,
676
- }))
677
- }
678
-
679
- fn count_results(
680
- conn: &rusqlite::Connection,
681
- owner_team_id: Option<&str>,
682
- status: Option<&str>,
683
- ) -> Result<i64, MessagingError> {
684
- match (owner_team_id, status) {
685
- (Some(team), Some(status)) => Ok(conn.query_row(
686
- "select count(*) from results where owner_team_id = ?1 and status = ?2",
687
- params![team, status],
688
- |row| row.get(0),
689
- )?),
690
- (Some(team), None) => Ok(conn.query_row(
691
- "select count(*) from results where owner_team_id = ?1",
692
- params![team],
693
- |row| row.get(0),
694
- )?),
695
- (None, Some(status)) => Ok(conn.query_row(
696
- "select count(*) from results where status = ?1",
697
- params![status],
698
- |row| row.get(0),
699
- )?),
700
- (None, None) => Ok(conn.query_row("select count(*) from results", [], |row| row.get(0))?),
701
- }
702
- }
703
-
704
- /// `report_result` (`results.py:191`): worker 报结果 —— 校验 envelope、持久化并自动结案。
705
- /// MCP `report_result` 工具调。
706
- pub fn report_result(
707
- workspace: &Path,
708
- envelope: &serde_json::Value,
709
- ) -> Result<serde_json::Value, MessagingError> {
710
- report_result_for_owner_team(workspace, envelope, None)
711
- }
712
-
713
- pub fn report_result_for_owner_team(
714
- workspace: &Path,
715
- envelope: &serde_json::Value,
716
- explicit_owner_team: Option<&str>,
717
- ) -> Result<serde_json::Value, MessagingError> {
718
- report_result_for_owner_team_inner(workspace, envelope, explicit_owner_team, None)
719
- }
720
-
721
- pub fn report_result_for_owner_team_with_primary_error(
722
- workspace: &Path,
723
- envelope: &serde_json::Value,
724
- explicit_owner_team: Option<&str>,
725
- fallback_primary_error: Option<&str>,
726
- ) -> Result<serde_json::Value, MessagingError> {
727
- report_result_for_owner_team_inner(
728
- workspace,
729
- envelope,
730
- explicit_owner_team,
731
- fallback_primary_error,
732
- )
733
- }
734
-
735
- fn report_result_for_owner_team_inner(
736
- workspace: &Path,
737
- envelope: &serde_json::Value,
738
- explicit_owner_team: Option<&str>,
739
- _fallback_primary_error: Option<&str>,
740
- ) -> Result<serde_json::Value, MessagingError> {
741
- if envelope.get("result_route").is_some() {
742
- return Err(MessagingError::Validation(
743
- "report_result result_route is task-owned and cannot be set by a worker".to_string(),
744
- ));
745
- }
746
- validate_result_envelope(envelope)?;
747
- let store = MessageStore::open(workspace)?;
748
- let result_id = envelope
749
- .get("result_id")
750
- .and_then(|v| v.as_str())
751
- .map_or_else(next_result_id, ToString::to_string);
752
- let task_id = required_str(envelope, "task_id")?;
753
- let agent_id = required_str(envelope, "agent_id")?;
754
- let status = required_str(envelope, "status")?;
755
- let mut stored = envelope.clone();
756
- if stored.get("result_id").is_none() {
757
- if let Some(obj) = stored.as_object_mut() {
758
- obj.insert(
759
- "result_id".to_string(),
760
- serde_json::Value::String(result_id.clone()),
761
- );
762
- }
763
- }
764
- let conn = crate::db::schema::open_db(store.db_path())?;
765
- let state_for_owner =
766
- crate::state::persist::load_runtime_state(workspace).unwrap_or(serde_json::json!({}));
767
- let owner_team = explicit_owner_team
768
- .filter(|team| !team.is_empty())
769
- .map(str::to_string)
770
- .unwrap_or_else(|| super::leader_receiver::active_team_key(workspace, &state_for_owner));
771
- let (result_route, route_declared) = task_result_route(&state_for_owner, &owner_team, task_id)?;
772
- let presentation = if route_declared {
773
- let request = super::presentation::PresentationRequest {
774
- sink: match result_route {
775
- ResultRoute::Leader => super::presentation::PresentationSink::Leader,
776
- ResultRoute::Pipeline => super::presentation::PresentationSink::Casefile,
777
- },
778
- class: match result_route {
779
- ResultRoute::Leader => super::presentation::PresentationClass::Message,
780
- ResultRoute::Pipeline => super::presentation::PresentationClass::StageResult,
781
- },
782
- case_id: (result_route == ResultRoute::Pipeline).then(|| task_id.to_string()),
783
- };
784
- super::presentation::decide_presentation(
785
- &request,
786
- super::presentation::PresentationSource::ReportResult,
787
- )
788
- } else {
789
- let (request, error) =
790
- super::presentation::normalize_report_presentation(envelope.get("presentation"));
791
- if let Some(error) = error {
792
- return Err(MessagingError::Validation(format!(
793
- "invalid presentation: {error}"
794
- )));
795
- }
796
- super::presentation::decide_presentation(
797
- &request,
798
- super::presentation::PresentationSource::ReportResult,
799
- )
800
- };
801
- if let Some(obj) = stored.as_object_mut() {
802
- obj.insert(
803
- "presentation".to_string(),
804
- serde_json::to_value(&presentation)?,
805
- );
806
- }
807
- let inserted = insert_result_if_absent(
808
- &conn,
809
- &result_id,
810
- task_id,
811
- agent_id,
812
- &stored.to_string(),
813
- status,
814
- Some(&owner_team),
815
- )?;
816
- let event_log = EventLog::new(workspace);
817
- let finalized_scope = auto_finalize_result(
818
- workspace,
819
- &conn,
820
- &state_for_owner,
821
- &owner_team,
822
- &result_id,
823
- task_id,
824
- agent_id,
825
- )?;
826
- if inserted {
827
- super::watchers::notify_fifo_result_watchers(&conn, &event_log, task_id, &result_id)?;
828
- } else {
829
- event_log.write(
830
- "mcp.report_result_duplicate_ignored",
831
- serde_json::json!({
832
- "owner_team_id": owner_team,
833
- "result_id": result_id,
834
- }),
835
- )?;
836
- }
837
- let mut leader_notified = false;
838
- let mut notification_message_id = None;
839
- let mut notification_channel = "none".to_string();
840
- let mut notification_status = if finalized_scope.is_some() {
841
- "auto_finalized".to_string()
842
- } else {
843
- "already_finalized".to_string()
844
- };
845
- if inserted && presentation.effective_sink == super::presentation::PresentationSink::Leader {
846
- let content = format_report_result_leader_summary(&result_id, task_id, agent_id, status, envelope);
847
- let leader_state = report_owner_state(&state_for_owner, &owner_team);
848
- let leader_presentation = leader_result_presentation(task_id);
849
- match super::leader_receiver::send_to_leader_receiver_with_presentation(
850
- workspace,
851
- &leader_state,
852
- "leader",
853
- &content,
854
- Some(&TaskId::new(task_id.to_string())),
855
- agent_id,
856
- false,
857
- Some(&result_id),
858
- None,
859
- &leader_presentation,
860
- &event_log,
861
- ) {
862
- Ok(outcome) => {
863
- leader_notified = matches!(
864
- outcome.status,
865
- super::DeliveryStatus::Delivered
866
- );
867
- notification_message_id = outcome.message_id;
868
- notification_channel = outcome
869
- .channel
870
- .unwrap_or_else(|| "leader_receiver".to_string());
871
- notification_status = if leader_notified {
872
- "delivered".to_string()
873
- } else if outcome.ok {
874
- "queued".to_string()
875
- } else {
876
- "refused".to_string()
877
- };
878
- }
879
- Err(error) => {
880
- event_log.write(
881
- "leader_receiver.result_notification_failed",
882
- serde_json::json!({
883
- "owner_team_id": owner_team,
884
- "result_id": result_id,
885
- "error": error.to_string(),
886
- }),
887
- )?;
888
- notification_channel = "leader_receiver".to_string();
889
- notification_status = "refused".to_string();
890
- }
891
- }
892
- }
893
- event_log.write(
894
- "mcp.report_result",
895
- serde_json::json!({
896
- "leader_notified": leader_notified,
897
- "notification_channel": notification_channel.clone(),
898
- "notification_message_id": notification_message_id.clone(),
899
- "notification_status": notification_status,
900
- "finalization_status": if finalized_scope.is_some() {
901
- "auto_finalized"
902
- } else {
903
- "already_finalized"
904
- },
905
- "owner_team_id": owner_team,
906
- "result_id": result_id,
907
- }),
908
- )?;
909
-
910
- let mut out = serde_json::Map::new();
911
- out.insert("ok".to_string(), serde_json::Value::Bool(true));
912
- out.insert(
913
- "result_id".to_string(),
914
- serde_json::Value::String(result_id),
915
- );
916
- out.insert(
917
- "task_id".to_string(),
918
- serde_json::Value::String(task_id.to_string()),
919
- );
920
- copy_report_attribution_fields(envelope, &mut out);
921
- out.insert(
922
- "agent_id".to_string(),
923
- serde_json::Value::String(agent_id.to_string()),
924
- );
925
- out.insert("acknowledged_messages".to_string(), serde_json::json!([]));
926
- out.insert(
927
- "leader_notified".to_string(),
928
- serde_json::Value::Bool(leader_notified),
929
- );
930
- out.insert(
931
- "notification_message_id".to_string(),
932
- notification_message_id.map_or(serde_json::Value::Null, serde_json::Value::String),
933
- );
934
- out.insert(
935
- "notification_status".to_string(),
936
- serde_json::Value::String(if inserted {
937
- notification_status
938
- } else {
939
- "duplicate_ignored".to_string()
940
- }),
941
- );
942
- out.insert(
943
- "finalization_status".to_string(),
944
- serde_json::Value::String(if finalized_scope.is_some() {
945
- "auto_finalized".to_string()
946
- } else {
947
- "already_finalized".to_string()
948
- }),
949
- );
950
- out.insert(
951
- "notification_channel".to_string(),
952
- serde_json::Value::String(notification_channel),
953
- );
954
- out.insert("notification_event_id".to_string(), serde_json::Value::Null);
955
- if let Some(warnings) = report_result_array(envelope, "warnings") {
956
- out.insert(
957
- "warnings".to_string(),
958
- serde_json::Value::Array(warnings.clone()),
959
- );
960
- }
961
- Ok(serde_json::Value::Object(out))
962
- }
963
-
964
- fn report_owner_state(state: &serde_json::Value, owner_team: &str) -> serde_json::Value {
965
- let mut state = match crate::state::projection::resolve_owner_team_id(state, owner_team)
966
- .canonical_key()
967
- {
968
- Some(team) => crate::state::projection::project_top_level_view(state, team),
969
- None => state.clone(),
970
- };
971
- if let Some(obj) = state.as_object_mut() {
972
- obj.insert(
973
- "active_team_key".to_string(),
974
- serde_json::Value::String(owner_team.to_string()),
975
- );
976
- }
977
- state
978
- }
979
-
980
- fn leader_result_presentation(task_id: &str) -> super::presentation::PresentationDecision {
981
- super::presentation::decide_presentation(
982
- &super::presentation::PresentationRequest {
983
- sink: super::presentation::PresentationSink::Leader,
984
- class: super::presentation::PresentationClass::StageResult,
985
- case_id: Some(task_id.to_string()),
986
- },
987
- super::presentation::PresentationSource::ReportResult,
988
- )
989
- }
990
-
991
- fn format_report_result_leader_summary(
992
- result_id: &str,
993
- task_id: &str,
994
- agent_id: &str,
995
- status: &str,
996
- envelope: &serde_json::Value,
997
- ) -> String {
998
- let summary = envelope
999
- .get("summary")
1000
- .and_then(serde_json::Value::as_str)
1001
- .unwrap_or("");
1002
- format!("Task {task_id} reported {status} from {agent_id}: {summary}; Result id: {result_id}")
1003
- }
1004
-
1005
- fn auto_finalize_result(
1006
- workspace: &Path,
1007
- conn: &rusqlite::Connection,
1008
- state: &serde_json::Value,
1009
- owner_team: &str,
1010
- result_id: &str,
1011
- task_id: &str,
1012
- agent_id: &str,
1013
- ) -> Result<Option<&'static str>, MessagingError> {
1014
- let message_scoped = is_message_scoped_result(conn, task_id, agent_id, Some(owner_team))?;
1015
- let scope = if message_scoped { "message" } else { "task" };
1016
- let projected_task_id = if message_scoped {
1017
- crate::mcp_server::latest_task_for_assignee(workspace, agent_id, Some(owner_team))
1018
- } else if task_exists_for_owner(state, owner_team, task_id) {
1019
- Some(task_id.to_string())
1020
- } else {
1021
- None
1022
- };
1023
- if let Some(projected_task_id) = projected_task_id {
1024
- crate::state::repository::StateRepository::new(workspace).commit(
1025
- crate::state::repository::StateWriteIntent::ResultCollection {
1026
- owner_team_id: Some(owner_team),
1027
- },
1028
- |latest| mark_task_done(latest, &projected_task_id, result_id),
1029
- )?;
1030
- }
1031
- let finalized = conn.execute(
1032
- "update results set status = 'collected' where result_id = ?1 and owner_team_id = ?2 and status not in ('collected', 'invalid')",
1033
- params![result_id, owner_team],
1034
- )?;
1035
- if finalized == 0 {
1036
- return Ok(None);
1037
- }
1038
- EventLog::new(workspace).write(
1039
- "collect.result",
1040
- serde_json::json!({
1041
- "result_id": result_id,
1042
- "task_id": task_id,
1043
- "agent_id": agent_id,
1044
- "scope": scope,
1045
- }),
1046
- )?;
1047
- Ok(Some(scope))
1048
- }
1049
-
1050
- fn task_result_route(
1051
- state: &serde_json::Value,
1052
- owner_team: &str,
1053
- task_id: &str,
1054
- ) -> Result<(ResultRoute, bool), MessagingError> {
1055
- let scoped_tasks = state
1056
- .get("teams")
1057
- .and_then(|teams| teams.get(owner_team))
1058
- .and_then(|team| team.get("tasks"))
1059
- .and_then(serde_json::Value::as_array);
1060
- let top_level_tasks = state.get("tasks").and_then(serde_json::Value::as_array);
1061
- let task = scoped_tasks
1062
- .into_iter()
1063
- .flatten()
1064
- .chain(top_level_tasks.into_iter().flatten())
1065
- .find(|task| task.get("id").and_then(serde_json::Value::as_str) == Some(task_id));
1066
- let Some(route) = task.and_then(|task| task.get("result_route")) else {
1067
- return Ok((ResultRoute::default(), false));
1068
- };
1069
- let route = route.as_str().ok_or_else(|| {
1070
- MessagingError::Validation(format!(
1071
- "task {task_id} has non-string result_route and cannot accept results"
1072
- ))
1073
- })?;
1074
- ResultRoute::parse(route)
1075
- .map(|route| (route, true))
1076
- .ok_or_else(|| {
1077
- MessagingError::Validation(format!(
1078
- "task {task_id} has unknown result_route {route:?} and cannot accept results"
1079
- ))
1080
- })
1081
- }
1082
-
1083
- fn copy_report_attribution_fields(
1084
- envelope: &serde_json::Value,
1085
- out: &mut serde_json::Map<String, serde_json::Value>,
1086
- ) {
1087
- for key in [
1088
- "attributed_message_id",
1089
- "attribution_scope",
1090
- "task_id_source",
1091
- ] {
1092
- if let Some(value) = envelope.get(key) {
1093
- out.insert(key.to_string(), value.clone());
1094
- }
1095
- }
1096
- }
1097
-
1098
- fn insert_result_if_absent(
1099
- conn: &rusqlite::Connection,
1100
- result_id: &str,
1101
- task_id: &str,
1102
- agent_id: &str,
1103
- envelope: &str,
1104
- status: &str,
1105
- owner_team_id: Option<&str>,
1106
- ) -> Result<bool, MessagingError> {
1107
- let rows = conn.execute(
1108
- "insert or ignore into results(result_id, owner_team_id, task_id, agent_id, envelope, status, created_at)
1109
- values (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
1110
- params![
1111
- result_id,
1112
- owner_team_id,
1113
- task_id,
1114
- agent_id,
1115
- envelope,
1116
- status,
1117
- chrono::Utc::now().to_rfc3339(),
1118
- ],
1119
- )?;
1120
- Ok(rows == 1)
1121
- }
1122
-
1123
- fn format_report_result_notification(
1124
- result_id: &str,
1125
- task_id: &str,
1126
- agent_id: &str,
1127
- status: &str,
1128
- envelope: &serde_json::Value,
1129
- ) -> String {
1130
- let summary = envelope
1131
- .get("summary")
1132
- .and_then(serde_json::Value::as_str)
1133
- .unwrap_or("");
1134
- let mut lines = vec![format!(
1135
- "Task {task_id} reported {status} from {agent_id}: {summary}"
1136
- )];
1137
- if let Some(tests) = format_report_result_tests(envelope) {
1138
- lines.push(tests);
1139
- }
1140
- if let Some(warnings) = format_report_result_warnings(envelope) {
1141
- lines.push(warnings);
1142
- }
1143
- if let Some(changes) = format_report_result_changes(envelope) {
1144
- lines.push(changes);
1145
- }
1146
- if let Some(risks) = format_report_result_risks(envelope) {
1147
- lines.push(risks);
1148
- }
1149
- if let Some(artifacts) = format_report_result_artifacts(envelope) {
1150
- lines.push(artifacts);
1151
- }
1152
- if let Some(next_actions) = format_report_result_next_actions(envelope) {
1153
- lines.push(next_actions);
1154
- }
1155
- lines.push(format!("Result id: {result_id}"));
1156
- lines.push(
1157
- "Team Agent stored this result. The coordinator/collect path will update team_state.md; no manual polling loop is needed."
1158
- .to_string(),
1159
- );
1160
- lines.join("\n")
1161
- }
1162
-
1163
- fn format_report_result_tests(envelope: &serde_json::Value) -> Option<String> {
1164
- let tests = envelope
1165
- .get("tests")
1166
- .and_then(serde_json::Value::as_array)?;
1167
- let parts = tests
1168
- .iter()
1169
- .filter_map(|test| {
1170
- let command = test.get("command").and_then(serde_json::Value::as_str)?;
1171
- let status = test.get("status").and_then(serde_json::Value::as_str)?;
1172
- Some(format!("{command}={status}"))
1173
- })
1174
- .collect::<Vec<_>>();
1175
- if parts.is_empty() {
1176
- None
1177
- } else {
1178
- Some(format!("Tests: {}", parts.join(", ")))
1179
- }
1180
- }
1181
-
1182
- fn format_report_result_warnings(envelope: &serde_json::Value) -> Option<String> {
1183
- let parts = report_result_array(envelope, "warnings")?
1184
- .iter()
1185
- .filter_map(|warning| {
1186
- let code = report_field(warning, "code")?;
1187
- let field = report_field(warning, "field").unwrap_or("result");
1188
- let severity = report_field(warning, "severity").unwrap_or("warning");
1189
- let advisory =
1190
- if warning.get("advisory").and_then(serde_json::Value::as_bool) == Some(true) {
1191
- " advisory"
1192
- } else {
1193
- ""
1194
- };
1195
- Some(format!("{severity}{advisory} {field}: {code}"))
1196
- })
1197
- .collect::<Vec<_>>();
1198
- if parts.is_empty() {
1199
- None
1200
- } else {
1201
- Some(format!("Verification warnings: {}", parts.join(", ")))
1202
- }
1203
- }
1204
-
1205
- fn report_result_array<'a>(
1206
- envelope: &'a serde_json::Value,
1207
- key: &str,
1208
- ) -> Option<&'a Vec<serde_json::Value>> {
1209
- let values = envelope.get(key).and_then(serde_json::Value::as_array)?;
1210
- if values.is_empty() {
1211
- None
1212
- } else {
1213
- Some(values)
1214
- }
1215
- }
1216
-
1217
- fn report_field<'a>(value: &'a serde_json::Value, key: &str) -> Option<&'a str> {
1218
- value
1219
- .get(key)
1220
- .and_then(serde_json::Value::as_str)
1221
- .filter(|text| !text.is_empty())
1222
- }
1223
-
1224
- fn report_field_any<'a>(value: &'a serde_json::Value, keys: &[&str]) -> Option<&'a str> {
1225
- keys.iter().find_map(|key| report_field(value, key))
1226
- }
1227
-
1228
- fn format_report_result_changes(envelope: &serde_json::Value) -> Option<String> {
1229
- let parts = report_result_array(envelope, "changes")?
1230
- .iter()
1231
- .filter_map(|change| {
1232
- let path = report_field_any(change, &["path", "file", "filepath", "filename"])?;
1233
- let kind = report_field_any(change, &["kind", "type", "action"]).unwrap_or("changed");
1234
- let description = report_field_any(
1235
- change,
1236
- &["description", "summary", "detail", "details", "message"],
1237
- )
1238
- .unwrap_or(path);
1239
- Some(format!("{kind} {path}: {description}"))
1240
- })
1241
- .collect::<Vec<_>>();
1242
- if parts.is_empty() {
1243
- None
1244
- } else {
1245
- Some(format!("Changes: {}", parts.join(", ")))
1246
- }
1247
- }
1248
-
1249
- fn format_report_result_risks(envelope: &serde_json::Value) -> Option<String> {
1250
- let parts = report_result_array(envelope, "risks")?
1251
- .iter()
1252
- .filter_map(|risk| {
1253
- let severity = report_field_any(risk, &["severity", "level"]).unwrap_or("low");
1254
- let description =
1255
- report_field_any(risk, &["description", "summary", "detail", "message"])?;
1256
- Some(format!("{severity}: {description}"))
1257
- })
1258
- .collect::<Vec<_>>();
1259
- if parts.is_empty() {
1260
- None
1261
- } else {
1262
- Some(format!("Risks: {}", parts.join(", ")))
1263
- }
1264
- }
1265
-
1266
- fn format_report_result_artifacts(envelope: &serde_json::Value) -> Option<String> {
1267
- let parts = report_result_array(envelope, "artifacts")?
1268
- .iter()
1269
- .filter_map(|artifact| {
1270
- let path = report_field_any(artifact, &["path", "file", "filepath", "filename"])?;
1271
- let description =
1272
- report_field_any(artifact, &["description", "summary", "detail"]).unwrap_or(path);
1273
- Some(format!("{path}: {description}"))
1274
- })
1275
- .collect::<Vec<_>>();
1276
- if parts.is_empty() {
1277
- None
1278
- } else {
1279
- Some(format!("Artifacts: {}", parts.join(", ")))
1280
- }
1281
- }
1282
-
1283
- fn format_report_result_next_actions(envelope: &serde_json::Value) -> Option<String> {
1284
- let parts = report_result_array(envelope, "next_actions")?
1285
- .iter()
1286
- .filter_map(|action| {
1287
- report_field_any(
1288
- action,
1289
- &["description", "summary", "action", "todo", "message"],
1290
- )
1291
- .map(|text| text.to_string())
1292
- })
1293
- .collect::<Vec<_>>();
1294
- if parts.is_empty() {
1295
- None
1296
- } else {
1297
- Some(format!("Next actions: {}", parts.join(", ")))
1298
- }
1299
- }
1300
-
1301
- #[cfg(test)]
1302
- mod collection_tests;
1303
-
1304
- #[cfg(test)]
1305
- mod tests {
1306
- use super::{format_report_result_notification, report_result};
1307
- use crate::message_store::MessageStore;
1308
-
1309
- #[test]
1310
- fn report_result_notification_includes_full_envelope_sections() {
1311
- let envelope = serde_json::json!({
1312
- "schema_version": "result_envelope_v1",
1313
- "task_id": "task-1",
1314
- "agent_id": "worker",
1315
- "status": "success",
1316
- "summary": "done",
1317
- "changes": [
1318
- {"path": "src/a.rs", "kind": "modified", "description": "patched delivery"}
1319
- ],
1320
- "tests": [
1321
- {"command": "cargo test", "status": "passed"}
1322
- ],
1323
- "warnings": [
1324
- {
1325
- "code": "result_success_without_executed_tests",
1326
- "field": "tests",
1327
- "severity": "warning",
1328
- "advisory": true
1329
- }
1330
- ],
1331
- "risks": [
1332
- {"severity": "low", "description": "none known"}
1333
- ],
1334
- "artifacts": [
1335
- {"path": ".team/artifacts/evidence.md", "description": "evidence"}
1336
- ],
1337
- "next_actions": [
1338
- {"description": "ship after review"}
1339
- ]
1340
- });
1341
- let notification =
1342
- format_report_result_notification("res_1", "task-1", "worker", "success", &envelope);
1343
- assert!(notification.contains("Task task-1 reported success from worker: done"));
1344
- assert!(notification.contains("Tests: cargo test=passed"));
1345
- assert!(notification.contains(
1346
- "Verification warnings: warning advisory tests: result_success_without_executed_tests"
1347
- ));
1348
- assert!(notification.contains("Changes: modified src/a.rs: patched delivery"));
1349
- assert!(notification.contains("Risks: low: none known"));
1350
- assert!(notification.contains("Artifacts: .team/artifacts/evidence.md: evidence"));
1351
- assert!(notification.contains("Next actions: ship after review"));
1352
- assert!(notification.contains("Result id: res_1"));
1353
- }
1354
-
1355
- #[test]
1356
- fn leader_result_summary_preserves_long_multiline_text_verbatim() {
1357
- let source = format!("首行\nbranch: fix/keyboard-receive-and-compose\ncommit: {}", "a1b2c3d4e5f67890".repeat(24));
1358
- let envelope = serde_json::json!({"summary": source});
1359
- let summary = super::format_report_result_leader_summary(
1360
- "res-1", "task-1", "worker", "success", &envelope,
1361
- );
1362
- let source = envelope["summary"].as_str().unwrap();
1363
- assert_eq!(summary, format!("Task task-1 reported success from worker: {source}; Result id: res-1"));
1364
- assert!(summary.len() > 160);
1365
- assert!(summary.contains("\nbranch: fix/keyboard-receive-and-compose\ncommit: "));
1366
- assert!(summary.contains("a1b2c3d4e5f67890".repeat(24).as_str()));
1367
- }
1368
-
1369
- #[test]
1370
- fn casefile_result_is_stored_without_a_leader_notification_row() {
1371
- let workspace = std::env::temp_dir().join(format!(
1372
- "ta-casefile-result-{}-{}",
1373
- std::process::id(),
1374
- super::next_result_id()
1375
- ));
1376
- std::fs::create_dir_all(&workspace).unwrap();
1377
- let out = report_result(
1378
- &workspace,
1379
- &serde_json::json!({
1380
- "schema_version": "result_envelope_v1",
1381
- "task_id": "task-1",
1382
- "agent_id": "worker",
1383
- "status": "success",
1384
- "summary": "stage evidence",
1385
- "changes": [],
1386
- "tests": [],
1387
- "risks": [],
1388
- "artifacts": [],
1389
- "next_actions": [],
1390
- "presentation": {
1391
- "sink": "casefile",
1392
- "class": "stage_result",
1393
- "case_id": "case-1"
1394
- }
1395
- }),
1396
- )
1397
- .unwrap();
1398
- assert_eq!(out["notification_status"], "auto_finalized");
1399
- assert_eq!(out["leader_notified"], false);
1400
- let store = MessageStore::open(&workspace).unwrap();
1401
- let conn = crate::db::schema::open_db(store.db_path()).unwrap();
1402
- let result_count: i64 = conn
1403
- .query_row("select count(*) from results", [], |row| row.get(0))
1404
- .unwrap();
1405
- let message_count: i64 = conn
1406
- .query_row("select count(*) from messages", [], |row| row.get(0))
1407
- .unwrap();
1408
- let status: String = conn
1409
- .query_row("select status from results", [], |row| row.get(0))
1410
- .unwrap();
1411
- assert_eq!(result_count, 1);
1412
- assert_eq!(status, "collected");
1413
- assert_eq!(message_count, 0);
1414
- }
1415
- }