@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,2043 +0,0 @@
1
- //! Read-only status: native runtime samples plus accepted launch model/effort.
2
- //!
3
- //! This intentionally does not reuse RuntimeSnapshot: the legacy snapshot reads
4
- //! coordinator/db/history and carries diagnostic fields that are outside the
5
- //! status brief contract.
6
-
7
- use serde_json::{json, Map, Value};
8
- use std::collections::{BTreeMap, BTreeSet};
9
- use std::path::Path;
10
- use std::process::Command;
11
-
12
- #[cfg(test)]
13
- use serde::Deserialize;
14
- #[cfg(test)]
15
- use sha2::{Digest, Sha256};
16
- #[cfg(test)]
17
- use std::fs::{File, OpenOptions};
18
- #[cfg(test)]
19
- use std::io::Read;
20
- #[cfg(test)]
21
- use std::path::PathBuf;
22
- #[cfg(test)]
23
- use std::process::{Child, ExitStatus, Stdio};
24
- #[cfg(test)]
25
- use std::sync::atomic::{AtomicBool, Ordering};
26
- #[cfg(test)]
27
- use std::sync::mpsc;
28
- #[cfg(test)]
29
- use std::sync::Arc;
30
- #[cfg(test)]
31
- use std::thread;
32
- #[cfg(test)]
33
- use std::time::{Duration, Instant};
34
-
35
- #[cfg(test)]
36
- const NODEPROBE_TIMEOUT: Duration = Duration::from_secs(2);
37
- #[cfg(test)]
38
- const NODEPROBE_OUTPUT_LIMIT: u64 = 1024 * 1024;
39
- #[cfg(test)]
40
- const NODEPROBE_KILL_GRACE: Duration = Duration::from_millis(100);
41
- #[cfg(test)]
42
- const NODEPROBE_RECEIPT_LIMIT: u64 = 64 * 1024;
43
- #[cfg(test)]
44
- const NODEPROBE_BINARY_LIMIT: u64 = 64 * 1024 * 1024;
45
- #[cfg(test)]
46
- const NODEPROBE_READ_CHUNK: usize = 64 * 1024;
47
- #[cfg(test)]
48
- const NODEPROBE_NAME: &str = "nodeprobe";
49
- #[cfg(test)]
50
- const NODEPROBE_RECEIPT_SUFFIX: &str = ".capability.json";
51
- #[cfg(test)]
52
- const NODEPROBE_RECEIPT_SCHEMA: &str = "nodeprobe-capability-v1";
53
- #[cfg(test)]
54
- const NODEPROBE_SOURCE_REPO: &str = "Florious95/team-agent-scratch/nodeprobe";
55
- #[cfg(test)]
56
- const NODEPROBE_SOURCE_COMMIT: &str = "ff316dc0afe8ab280e61d30934e7624579be6224";
57
- #[cfg(test)]
58
- const NODEPROBE_SOURCE_TREE: &str = "5217a41aa914ddcb72c27f39f1b4af9ead68b1b6";
59
- #[cfg(test)]
60
- const NODEPROBE_REPORT_SCHEMA: u64 = 1;
61
- #[cfg(test)]
62
- const NODEPROBE_CAPABILITIES: &[&str] = &["tmux.list-panes", "ps.pid_ppid_stat_comm"];
63
- #[cfg(test)]
64
- const NODEPROBE_FORBIDDEN: &[&str] = &[
65
- "tmux.capture-pane",
66
- "tmux.attach",
67
- "tmux.send-keys",
68
- "process.argv",
69
- "pane_body",
70
- ];
71
-
72
- #[cfg(test)]
73
- thread_local! {
74
- static TEST_NODEPROBE: std::cell::RefCell<Option<Vec<PathBuf>>> = const { std::cell::RefCell::new(None) };
75
- static TEST_RESOLVER_DELAY: std::cell::RefCell<Option<TestResolverDelay>> = const { std::cell::RefCell::new(None) };
76
- }
77
-
78
- #[cfg(test)]
79
- static NODEPROBE_RESOLVER_ACTIVE: AtomicBool = AtomicBool::new(false);
80
-
81
- #[derive(Clone, Debug, PartialEq, Eq)]
82
- struct RegisteredNode {
83
- name: String,
84
- provider: String,
85
- model: Option<String>,
86
- effort: Option<String>,
87
- endpoint: Option<String>,
88
- session: Option<String>,
89
- window: Option<String>,
90
- pane: Option<String>,
91
- lifecycle: Option<String>,
92
- claude_registry: Option<(std::path::PathBuf, String)>,
93
- }
94
-
95
- #[derive(Clone, Debug, PartialEq, Eq)]
96
- struct ProbeNode {
97
- socket: String,
98
- session: String,
99
- window: String,
100
- pane: String,
101
- provider: String,
102
- activity: String,
103
- health: String,
104
- session_name: Option<String>,
105
- evidence_method: Option<String>,
106
- }
107
-
108
- #[derive(Clone, Debug, PartialEq, Eq)]
109
- struct BriefNode {
110
- name: String,
111
- provider: String,
112
- model: Option<String>,
113
- effort: Option<String>,
114
- runtime_status: String,
115
- activity: String,
116
- health: String,
117
- session_name: Option<String>,
118
- tmux_command: Option<String>,
119
- observation_reason: Option<&'static str>,
120
- }
121
-
122
- #[derive(Clone, Debug, PartialEq, Eq)]
123
- struct AttachContext {
124
- endpoint: String,
125
- session: String,
126
- window: String,
127
- pane: String,
128
- }
129
-
130
- #[derive(Debug, Default)]
131
- struct ProbeResult {
132
- nodes: Vec<ProbeNode>,
133
- exited: BTreeSet<(String, String, String)>,
134
- }
135
-
136
- #[derive(Debug, Deserialize)]
137
- #[cfg(test)]
138
- struct NodeprobeCapabilityReceipt {
139
- schema: String,
140
- binary: String,
141
- binary_sha256: String,
142
- source_repo: String,
143
- source_commit: String,
144
- source_tree: String,
145
- target: String,
146
- report_schema: u64,
147
- capabilities: Vec<String>,
148
- forbidden: Vec<String>,
149
- }
150
-
151
- enum MatchResult<'a> {
152
- Missing,
153
- Unique(&'a ProbeNode),
154
- Ambiguous,
155
- }
156
-
157
- /// The CLI's concise JSON projection. `agent` filters the registered list but
158
- /// never synthesizes an unregistered node.
159
- pub(crate) fn status_brief_scoped(workspace: &Path, state: &Value, agent: Option<&str>) -> Value {
160
- let nodes = project_status_nodes(workspace, state, agent);
161
- json!({
162
- "nodes": nodes
163
- .into_iter()
164
- .map(|(node, _)| scoped_node_json(node, workspace, state))
165
- .collect::<Vec<_>>()
166
- })
167
- }
168
-
169
- /// Human output keeps the legacy single-node form and groups shared attach
170
- /// context only when multiple nodes make that repetition useful.
171
- pub(crate) fn format_status_brief(workspace: &Path, state: &Value, agent: Option<&str>) -> String {
172
- let nodes = project_status_nodes(workspace, state, agent);
173
- let diagnostics = nodes.iter().filter(|(node, _)| node.observation_reason.is_some())
174
- .map(|(node, _)| {
175
- let value = scoped_node_json(node.clone(), workspace, state);
176
- format!("observation {}: {}; next_action: {}", node.name,
177
- value["observation_reason"].as_str().unwrap_or("observation_inconclusive"),
178
- value["next_action"].as_str().unwrap_or(""))
179
- }).collect::<Vec<_>>();
180
- let mut output = if nodes.len() <= 1 {
181
- nodes.into_iter().filter_map(|(node, _)| format_brief_node(&node.into_json()))
182
- .collect::<Vec<_>>().join("\n")
183
- } else { format_multi_node_brief(nodes) };
184
- if !diagnostics.is_empty() {
185
- output.push('\n');
186
- output.push_str(&diagnostics.join("\n"));
187
- }
188
- output
189
- }
190
-
191
- fn project_status_nodes(
192
- _workspace: &Path,
193
- state: &Value,
194
- agent: Option<&str>,
195
- ) -> Vec<(BriefNode, Option<AttachContext>)> {
196
- let registered = registered_nodes(state, agent);
197
- let legacy: Vec<_> = registered
198
- .iter()
199
- .filter(|_node| {
200
- #[cfg(unix)]
201
- if crate::contract_runtime::registry::descriptor(&_node.provider).is_some() {
202
- return false;
203
- }
204
- true
205
- })
206
- .cloned()
207
- .collect();
208
- let probes = probe_registered_endpoints(&legacy);
209
- registered
210
- .iter()
211
- .map(|node| {
212
- #[cfg(unix)]
213
- if crate::contract_runtime::registry::descriptor(&node.provider).is_some() {
214
- let mut brief = BriefNode::unknown(node).with_reason("native_runtime_projection_unavailable");
215
- if let Ok(native) = crate::contract_runtime::framework::project_seat(
216
- _workspace,
217
- &crate::state::projection::team_state_key(state),
218
- &node.name,
219
- ) {
220
- brief.runtime_status = native["status"].as_str().unwrap_or("unknown").into();
221
- brief.observation_reason = match brief.runtime_status.as_str() {
222
- "running" => Some("activity_or_health_not_observed"),
223
- "stopped" => None,
224
- _ => Some("native_runtime_not_ready"),
225
- };
226
- brief.model = native["model"].as_str().map(str::to_owned);
227
- brief.effort = native["effort"].as_str().map(str::to_owned);
228
- if brief.runtime_status == "running" {
229
- brief.tmux_command = native["native_endpoint"].as_str().map(|endpoint| {
230
- format!("tmux -S {} attach-session", shell_quote(endpoint))
231
- });
232
- }
233
- }
234
- // Process alive is T1 only: activity/health remain unknown until
235
- // independently observed. Never probe a private %0 on old tmux.
236
- return (brief, None);
237
- }
238
- project_node_with_attach(node, probes.get(node.endpoint.as_deref().unwrap_or("")))
239
- })
240
- .collect()
241
- }
242
-
243
- pub(crate) fn registered_agent_exists(state: &Value, agent: &str) -> bool {
244
- registered_nodes(state, None)
245
- .iter()
246
- .any(|node| node.name == agent)
247
- }
248
-
249
- #[cfg(test)]
250
- pub(crate) fn with_test_nodeprobe<R>(path: PathBuf, func: impl FnOnce() -> R) -> R {
251
- with_test_nodeprobe_candidates(vec![path], func)
252
- }
253
-
254
- #[cfg(test)]
255
- pub(crate) fn with_test_nodeprobe_unbound<R>(path: PathBuf, func: impl FnOnce() -> R) -> R {
256
- with_test_nodeprobe_candidate(vec![path], func)
257
- }
258
-
259
- #[cfg(test)]
260
- pub(crate) fn with_test_nodeprobe_candidates<R>(
261
- paths: Vec<PathBuf>,
262
- func: impl FnOnce() -> R,
263
- ) -> R {
264
- for path in &paths {
265
- write_test_capability_receipt(path);
266
- }
267
- with_test_nodeprobe_candidate(paths, func)
268
- }
269
-
270
- #[cfg(test)]
271
- #[derive(Clone)]
272
- pub(crate) struct ResolverDelaySignal {
273
- entered: Arc<AtomicBool>,
274
- finished: Arc<AtomicBool>,
275
- }
276
-
277
- #[cfg(test)]
278
- impl ResolverDelaySignal {
279
- pub(crate) fn entered(&self) -> bool {
280
- self.entered.load(Ordering::Acquire)
281
- }
282
-
283
- pub(crate) fn finished(&self) -> bool {
284
- self.finished.load(Ordering::Acquire)
285
- }
286
- }
287
-
288
- #[cfg(test)]
289
- #[derive(Clone)]
290
- struct TestResolverDelay {
291
- delay: Duration,
292
- signal: ResolverDelaySignal,
293
- }
294
-
295
- #[cfg(test)]
296
- pub(crate) fn with_test_nodeprobe_resolver_delay<R>(
297
- delay: Duration,
298
- func: impl FnOnce(&ResolverDelaySignal) -> R,
299
- ) -> R {
300
- struct Guard(Option<TestResolverDelay>);
301
- impl Drop for Guard {
302
- fn drop(&mut self) {
303
- TEST_RESOLVER_DELAY.with(|slot| *slot.borrow_mut() = self.0.take());
304
- }
305
- }
306
- let config = TestResolverDelay {
307
- delay,
308
- signal: ResolverDelaySignal {
309
- entered: Arc::new(AtomicBool::new(false)),
310
- finished: Arc::new(AtomicBool::new(false)),
311
- },
312
- };
313
- let signal = config.signal.clone();
314
- let previous = TEST_RESOLVER_DELAY.with(|slot| slot.replace(Some(config)));
315
- let _guard = Guard(previous);
316
- func(&signal)
317
- }
318
-
319
- #[cfg(test)]
320
- fn with_test_nodeprobe_candidate<R>(paths: Vec<PathBuf>, func: impl FnOnce() -> R) -> R {
321
- struct Guard(Option<Vec<PathBuf>>);
322
- impl Drop for Guard {
323
- fn drop(&mut self) {
324
- TEST_NODEPROBE.with(|slot| *slot.borrow_mut() = self.0.take());
325
- }
326
- }
327
- let previous = TEST_NODEPROBE.with(|slot| slot.replace(Some(paths)));
328
- let _guard = Guard(previous);
329
- let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(func));
330
- let deadline = Instant::now() + NODEPROBE_TIMEOUT;
331
- while NODEPROBE_RESOLVER_ACTIVE.load(Ordering::Acquire) && Instant::now() < deadline {
332
- thread::yield_now();
333
- }
334
- let resolver_idle = !NODEPROBE_RESOLVER_ACTIVE.load(Ordering::Acquire);
335
- match outcome {
336
- Ok(result) => {
337
- assert!(
338
- resolver_idle,
339
- "test nodeprobe fixture ended while resolver worker was still active"
340
- );
341
- result
342
- }
343
- Err(payload) => std::panic::resume_unwind(payload),
344
- }
345
- }
346
-
347
- #[cfg(test)]
348
- fn write_test_capability_receipt(path: &Path) {
349
- let binary_sha256 =
350
- sha256_file(path, Instant::now() + NODEPROBE_TIMEOUT).expect("test nodeprobe fixture hash");
351
- let receipt = json!({
352
- "schema": NODEPROBE_RECEIPT_SCHEMA,
353
- "binary": NODEPROBE_NAME,
354
- "binary_sha256": binary_sha256,
355
- "source_repo": NODEPROBE_SOURCE_REPO,
356
- "source_commit": NODEPROBE_SOURCE_COMMIT,
357
- "source_tree": NODEPROBE_SOURCE_TREE,
358
- "target": current_nodeprobe_target().expect("test target"),
359
- "report_schema": NODEPROBE_REPORT_SCHEMA,
360
- "capabilities": NODEPROBE_CAPABILITIES,
361
- "forbidden": NODEPROBE_FORBIDDEN,
362
- });
363
- std::fs::write(
364
- nodeprobe_receipt_path(path),
365
- serde_json::to_vec(&receipt).unwrap(),
366
- )
367
- .expect("write test nodeprobe capability receipt");
368
- }
369
-
370
- fn format_brief_node(value: &Value) -> Option<String> {
371
- Some(format!(
372
- "name: {} provider: {} model: {} effort: {} runtime_status: {} activity: {} health: {} session_name: {} tmux_command: {}",
373
- value.get("name")?.as_str()?,
374
- value.get("provider")?.as_str()?,
375
- display_optional(value.get("model")?),
376
- display_optional(value.get("effort")?),
377
- value.get("runtime_status")?.as_str()?,
378
- value.get("activity")?.as_str()?,
379
- value.get("health")?.as_str()?,
380
- display_optional(value.get("session_name")?),
381
- display_optional(value.get("tmux_command")?),
382
- ))
383
- }
384
-
385
- fn format_multi_node_brief(nodes: Vec<(BriefNode, Option<AttachContext>)>) -> String {
386
- let mut groups = Vec::<(String, String)>::new();
387
- for (_, context) in &nodes {
388
- let Some(context) = context else { continue };
389
- if !groups
390
- .iter()
391
- .any(|(endpoint, session)| endpoint == &context.endpoint && session == &context.session)
392
- {
393
- groups.push((context.endpoint.clone(), context.session.clone()));
394
- }
395
- }
396
-
397
- let mut lines = groups
398
- .iter()
399
- .enumerate()
400
- .map(|(index, (endpoint, session))| format_attach_template(index + 1, endpoint, session))
401
- .collect::<Vec<_>>();
402
- if !groups.is_empty() {
403
- lines.push(
404
- "TMUX templates: replace <target> with the window.pane part of the matching ATTACH value."
405
- .to_string(),
406
- );
407
- }
408
- lines.push(
409
- "NAME\tPROVIDER\tMODEL\tEFFORT\tRUNTIME_STATUS\tACTIVITY\tHEALTH\tSESSION_NAME\tATTACH"
410
- .to_string(),
411
- );
412
- for (node, context) in nodes {
413
- let attach = context
414
- .as_ref()
415
- .and_then(|context| {
416
- groups
417
- .iter()
418
- .position(|(endpoint, session)| {
419
- endpoint == &context.endpoint && session == &context.session
420
- })
421
- .map(|index| format!("{}:{}.{}", index + 1, context.window, context.pane))
422
- })
423
- .unwrap_or_else(|| "null".to_string());
424
- lines.push(
425
- [
426
- escape_human_cell(&node.name),
427
- escape_human_cell(&node.provider),
428
- escape_human_cell(node.model.as_deref().unwrap_or("null")),
429
- escape_human_cell(node.effort.as_deref().unwrap_or("null")),
430
- escape_human_cell(&node.runtime_status),
431
- escape_human_cell(&node.activity),
432
- escape_human_cell(&node.health),
433
- escape_human_cell(node.session_name.as_deref().unwrap_or("null")),
434
- escape_human_cell(&attach),
435
- ]
436
- .join("\t"),
437
- );
438
- }
439
- lines.join("\n")
440
- }
441
-
442
- fn format_attach_template(group: usize, endpoint: &str, session: &str) -> String {
443
- let flag = if Path::new(endpoint).is_absolute() {
444
- "-S"
445
- } else {
446
- "-L"
447
- };
448
- let target = format!("{session}:<target>");
449
- format!(
450
- "TMUX[{group}] tmux {flag} {} attach -t {}",
451
- shell_quote(endpoint),
452
- shell_quote(&target)
453
- )
454
- }
455
-
456
- fn escape_human_cell(value: &str) -> String {
457
- value
458
- .replace('\\', "\\\\")
459
- .replace('\t', "\\t")
460
- .replace('\n', "\\n")
461
- .replace('\r', "\\r")
462
- }
463
-
464
- fn display_optional(value: &Value) -> String {
465
- value
466
- .as_str()
467
- .map(|value| value.to_string())
468
- .unwrap_or_else(|| "null".to_string())
469
- }
470
-
471
- fn registered_nodes(state: &Value, selected: Option<&str>) -> Vec<RegisteredNode> {
472
- // A projected state can still carry stale top-level agents. Once the
473
- // selector identified a canonical team entry, that entry is authoritative;
474
- // an empty/missing nested roster must not fall back to the stale projection.
475
- let canonical_team = state
476
- .get("active_team_key")
477
- .and_then(Value::as_str)
478
- .and_then(|key| state.get("teams").and_then(|teams| teams.get(key)));
479
- let (agents, lifecycle, defaults) = match canonical_team {
480
- Some(team) => (
481
- team.get("agents").and_then(Value::as_object),
482
- team.get("agent_lifecycle").and_then(Value::as_object),
483
- team,
484
- ),
485
- None => (
486
- state.get("agents").and_then(Value::as_object),
487
- state.get("agent_lifecycle").and_then(Value::as_object),
488
- state,
489
- ),
490
- };
491
- let Some(agents) = agents else {
492
- return Vec::new();
493
- };
494
- agents
495
- .iter()
496
- .filter(|(name, _)| selected.is_none_or(|selected| selected == name.as_str()))
497
- .filter(|(name, _)| {
498
- !lifecycle
499
- .and_then(|entries| entries.get(*name))
500
- .and_then(|entry| entry.get("state"))
501
- .and_then(Value::as_str)
502
- .is_some_and(|state| state == "retired")
503
- })
504
- .map(|(name, value)| registered_node(name, value, defaults))
505
- .collect()
506
- }
507
-
508
- fn registered_node(name: &str, value: &Value, state: &Value) -> RegisteredNode {
509
- let display = value.pointer("/display").unwrap_or(&Value::Null);
510
- let target = value.pointer("/target").unwrap_or(&Value::Null);
511
- let provider = string_at(value, &["provider"])
512
- .or_else(|| string_at(state, &["provider"]))
513
- .unwrap_or_else(|| "unknown".to_string());
514
- RegisteredNode {
515
- name: name.to_string(),
516
- provider,
517
- // Accepted launch settings, not pending role-file edits or guessed
518
- // provider defaults. Runtime liveness remains a separate signal.
519
- model: string_at(value, &["model"]),
520
- effort: string_at(value, &["effort"]),
521
- endpoint: endpoint(value).or_else(|| endpoint(state)),
522
- session: first_string(value, &["session_name", "session"])
523
- .or_else(|| {
524
- first_string(
525
- display,
526
- &["target_worker_session", "display_session", "linked_session"],
527
- )
528
- })
529
- .or_else(|| first_string(target, &["session_name", "session"]))
530
- .or_else(|| first_string(state, &["session_name"])),
531
- window: first_string(value, &["window_name", "window", "layout_window"])
532
- .or_else(|| first_string(display, &["window", "window_name", "layout_window"]))
533
- .or_else(|| first_string(target, &["window_name", "window", "layout_window"])),
534
- pane: first_string(value, &["pane_id"])
535
- .or_else(|| first_string(display, &["pane_id"]))
536
- .or_else(|| first_string(target, &["pane_id"])),
537
- lifecycle: string_at(value, &["status"]).map(|status| status.to_ascii_lowercase()),
538
- claude_registry: crate::provider::claude_registry_key(value),
539
- }
540
- }
541
-
542
- fn endpoint(value: &Value) -> Option<String> {
543
- first_string(value, &["tmux_endpoint", "tmux_socket", "socket"]).or_else(|| {
544
- first_string(
545
- value.pointer("/transport").unwrap_or(&Value::Null),
546
- &["tmux_endpoint", "tmux_socket", "endpoint", "socket"],
547
- )
548
- })
549
- }
550
-
551
- fn string_at(value: &Value, keys: &[&str]) -> Option<String> {
552
- first_string(value, keys)
553
- }
554
-
555
- fn first_string(value: &Value, keys: &[&str]) -> Option<String> {
556
- keys.iter().find_map(|key| {
557
- value
558
- .get(*key)
559
- .and_then(Value::as_str)
560
- .filter(|value| !value.is_empty())
561
- .map(str::to_string)
562
- })
563
- }
564
-
565
- fn probe_registered_endpoints(nodes: &[RegisteredNode]) -> BTreeMap<String, Option<ProbeResult>> {
566
- #[cfg(test)]
567
- {
568
- // Keep the legacy fixture seam for existing hermetic tests; production
569
- // status never searches for or executes nodeprobe.
570
- if TEST_NODEPROBE.with(|slot| slot.borrow().is_some()) {
571
- return probe_registered_endpoints_with_test_nodeprobe(nodes);
572
- }
573
- }
574
- let mut endpoints = BTreeMap::new();
575
- for endpoint in nodes.iter().filter_map(|node| node.endpoint.as_deref()) {
576
- if endpoints.contains_key(endpoint) {
577
- continue;
578
- }
579
- endpoints.insert(
580
- endpoint.to_string(),
581
- sample_native_endpoint(endpoint, nodes),
582
- );
583
- }
584
- endpoints
585
- }
586
-
587
- fn sample_native_endpoint(endpoint: &str, registered: &[RegisteredNode]) -> Option<ProbeResult> {
588
- let output = run_native_tmux_list_panes(endpoint)?;
589
- Some(sample_native_panes(
590
- &output,
591
- endpoint,
592
- registered,
593
- process_snapshots,
594
- ))
595
- }
596
-
597
- fn sample_native_panes(
598
- output: &str,
599
- endpoint: &str,
600
- registered: &[RegisteredNode],
601
- snapshots: impl FnOnce(&BTreeSet<u32>) -> BTreeMap<u32, ProcessSnapshot>,
602
- ) -> ProbeResult {
603
- let panes = output
604
- .lines()
605
- .filter_map(native_pane_fields)
606
- .collect::<Vec<_>>();
607
- let pids = panes
608
- .iter()
609
- .filter_map(|fields| native_pane_pid(fields[3]))
610
- .collect::<BTreeSet<_>>();
611
- let processes = if pids.is_empty() {
612
- BTreeMap::new()
613
- } else {
614
- snapshots(&pids)
615
- };
616
- let exited = panes.iter().filter(|fields| {
617
- native_pane_pid(fields[3]).and_then(|pid| processes.get(&pid)).is_some_and(|p| p.zombie)
618
- }).map(|fields| (fields[0].to_string(), fields[1].to_string(), fields[2].to_string())).collect();
619
- let nodes = panes
620
- .into_iter()
621
- .filter_map(|fields| parse_native_pane(fields, endpoint, registered, &processes))
622
- .collect();
623
- ProbeResult { nodes, exited }
624
- }
625
-
626
- fn native_pane_fields(line: &str) -> Option<[&str; 5]> {
627
- let mut fields = line.split('\t');
628
- let session = fields.next()?;
629
- let window = fields.next()?;
630
- let pane = fields.next()?;
631
- let pid = fields.next().unwrap_or_default();
632
- let command = fields.next().unwrap_or_default();
633
- if session.is_empty() || window.is_empty() || pane.is_empty() {
634
- return None;
635
- }
636
- Some([session, window, pane, pid, command])
637
- }
638
-
639
- fn native_pane_pid(pid: &str) -> Option<u32> {
640
- pid.parse::<u32>()
641
- .ok()
642
- .filter(|pid| *pid > 0 && *pid <= i32::MAX as u32)
643
- }
644
-
645
- fn run_native_tmux_list_panes(endpoint: &str) -> Option<String> {
646
- const FORMAT: &str =
647
- "#{session_name}\t#{window_name}\t#{pane_id}\t#{pane_pid}\t#{pane_current_command}";
648
- let flag = if Path::new(endpoint).is_absolute() {
649
- "-S"
650
- } else {
651
- "-L"
652
- };
653
- let output = Command::new("tmux")
654
- .arg(flag)
655
- .arg(endpoint)
656
- .args(["list-panes", "-a", "-F", FORMAT])
657
- .output()
658
- .ok()?;
659
- output
660
- .status
661
- .success()
662
- .then(|| String::from_utf8(output.stdout).ok())?
663
- }
664
-
665
- fn parse_native_pane(
666
- fields: [&str; 5],
667
- endpoint: &str,
668
- registered: &[RegisteredNode],
669
- processes: &BTreeMap<u32, ProcessSnapshot>,
670
- ) -> Option<ProbeNode> {
671
- let [session, window, pane, pid, command] = fields;
672
- let session = session.to_string();
673
- let window = window.to_string();
674
- let pane = pane.to_string();
675
- let matched = registered.iter().find(|node| {
676
- node.endpoint.as_deref() == Some(endpoint)
677
- && node.session.as_deref() == Some(session.as_str())
678
- && node.window.as_deref().is_none_or(|value| value == window)
679
- && node.pane.as_deref() == Some(pane.as_str())
680
- });
681
- if !pid.is_empty() {
682
- let snapshot = processes.get(&native_pane_pid(pid)?)?;
683
- if snapshot.zombie {
684
- return None;
685
- }
686
- }
687
- let provider = matched
688
- .map(|node| node.provider.clone())
689
- .unwrap_or_else(|| "unknown".to_string());
690
- let activity = if command.is_empty() {
691
- "unknown"
692
- } else if matches!(command, "bash" | "fish" | "sh" | "zsh" | "-bash" | "-zsh") {
693
- "idle"
694
- } else {
695
- "working"
696
- };
697
- Some(ProbeNode {
698
- socket: endpoint.to_string(),
699
- session: session.clone(),
700
- window: window.clone(),
701
- pane,
702
- provider,
703
- activity: activity.to_string(),
704
- health: "normal".to_string(),
705
- session_name: Some(session),
706
- evidence_method: Some("native_tmux".to_string()),
707
- })
708
- }
709
-
710
- struct ProcessSnapshot {
711
- zombie: bool,
712
- }
713
-
714
- fn process_snapshot_command(pids: &BTreeSet<u32>) -> Command {
715
- let pids = pids
716
- .iter()
717
- .map(u32::to_string)
718
- .collect::<Vec<_>>()
719
- .join(",");
720
- let mut command = Command::new("ps");
721
- command.args(["-o", "pid=,ppid=,stat=,comm=", "-p", &pids]);
722
- command
723
- }
724
-
725
- fn process_snapshots(pids: &BTreeSet<u32>) -> BTreeMap<u32, ProcessSnapshot> {
726
- if pids.is_empty() {
727
- return BTreeMap::new();
728
- }
729
- let Ok(output) = process_snapshot_command(pids).output() else {
730
- return BTreeMap::new();
731
- };
732
- if !output.status.success() {
733
- return BTreeMap::new();
734
- }
735
- parse_process_snapshots(&output.stdout, pids)
736
- }
737
-
738
- fn parse_process_snapshots(
739
- bytes: &[u8],
740
- requested: &BTreeSet<u32>,
741
- ) -> BTreeMap<u32, ProcessSnapshot> {
742
- let mut snapshots = BTreeMap::<u32, ProcessSnapshot>::new();
743
- let output = String::from_utf8_lossy(bytes);
744
- for line in output.lines() {
745
- let mut fields = line.split_whitespace();
746
- let Some(pid) = fields.next().and_then(native_pane_pid) else {
747
- continue;
748
- };
749
- if !requested.contains(&pid) {
750
- continue;
751
- }
752
- let Some(_ppid) = fields.next() else {
753
- continue;
754
- };
755
- let Some(stat) = fields.next() else {
756
- continue;
757
- };
758
- let zombie = stat.contains('Z');
759
- snapshots
760
- .entry(pid)
761
- .and_modify(|snapshot| snapshot.zombie |= zombie)
762
- .or_insert(ProcessSnapshot { zombie });
763
- }
764
- snapshots
765
- }
766
-
767
- #[cfg(test)]
768
- fn probe_registered_endpoints_with_test_nodeprobe(
769
- nodes: &[RegisteredNode],
770
- ) -> BTreeMap<String, Option<ProbeResult>> {
771
- let deadline = Instant::now() + NODEPROBE_TIMEOUT;
772
- let candidates = nodeprobe_candidates();
773
- let resolver_options = resolver_options();
774
- let mut endpoints = BTreeMap::new();
775
- let mut selected_binary = None;
776
- let mut resolved = false;
777
- for endpoint in nodes.iter().filter_map(|node| node.endpoint.as_deref()) {
778
- if endpoints.contains_key(endpoint) {
779
- continue;
780
- }
781
- if !resolved {
782
- selected_binary =
783
- resolve_nodeprobe_binary(candidates.clone(), deadline, resolver_options.clone());
784
- resolved = true;
785
- }
786
- let sampled = selected_binary.as_deref().and_then(|binary| {
787
- run_nodeprobe(binary, endpoint, deadline)
788
- .and_then(|bytes| parse_probe(&bytes, endpoint).ok())
789
- });
790
- endpoints.insert(endpoint.to_string(), sampled);
791
- }
792
- endpoints
793
- }
794
-
795
- #[cfg(test)]
796
- fn run_nodeprobe(binary: &Path, endpoint: &str, deadline: Instant) -> Option<Vec<u8>> {
797
- if Instant::now() >= deadline {
798
- return None;
799
- }
800
- let mut child = spawn_nodeprobe(binary, endpoint)?;
801
- let stdout = match child.stdout.take() {
802
- Some(stdout) => stdout,
803
- None => {
804
- terminate_nodeprobe(&mut child);
805
- return None;
806
- }
807
- };
808
- let (tx, rx) = mpsc::channel();
809
- thread::spawn(move || {
810
- let mut bytes = Vec::new();
811
- let read = stdout
812
- .take(NODEPROBE_OUTPUT_LIMIT + 1)
813
- .read_to_end(&mut bytes);
814
- let _ = tx.send(read.map(|_| bytes));
815
- });
816
- loop {
817
- let now = Instant::now();
818
- if now >= deadline {
819
- terminate_nodeprobe(&mut child);
820
- let _ = rx.recv_timeout(NODEPROBE_KILL_GRACE);
821
- return None;
822
- }
823
- let slice = deadline
824
- .saturating_duration_since(now)
825
- .min(Duration::from_millis(20));
826
- match rx.recv_timeout(slice) {
827
- Ok(Ok(bytes)) => {
828
- let status = wait_child_bounded(&mut child, deadline)?;
829
- if !status.success() || bytes.len() as u64 > NODEPROBE_OUTPUT_LIMIT {
830
- terminate_nodeprobe(&mut child);
831
- return None;
832
- }
833
- return Some(bytes);
834
- }
835
- Ok(Err(_)) => {
836
- terminate_nodeprobe(&mut child);
837
- return None;
838
- }
839
- Err(mpsc::RecvTimeoutError::Timeout) => match child.try_wait() {
840
- Ok(Some(status)) => {
841
- if !status.success() {
842
- terminate_nodeprobe(&mut child);
843
- let leftover = deadline.saturating_duration_since(Instant::now());
844
- let _ = rx.recv_timeout(leftover.min(NODEPROBE_KILL_GRACE));
845
- return None;
846
- }
847
- }
848
- Ok(None) => {}
849
- Err(_) => {
850
- terminate_nodeprobe(&mut child);
851
- return None;
852
- }
853
- },
854
- Err(mpsc::RecvTimeoutError::Disconnected) => {
855
- terminate_nodeprobe(&mut child);
856
- return None;
857
- }
858
- }
859
- }
860
- }
861
-
862
- #[cfg(test)]
863
- fn wait_child_bounded(child: &mut Child, deadline: Instant) -> Option<ExitStatus> {
864
- loop {
865
- match child.try_wait() {
866
- Ok(Some(status)) => return Some(status),
867
- Ok(None) if Instant::now() < deadline => thread::sleep(Duration::from_millis(5)),
868
- Ok(None) => {
869
- terminate_nodeprobe(child);
870
- return None;
871
- }
872
- Err(_) => {
873
- terminate_nodeprobe(child);
874
- return None;
875
- }
876
- }
877
- }
878
- }
879
-
880
- #[cfg(test)]
881
- fn terminate_nodeprobe(child: &mut Child) {
882
- #[cfg(unix)]
883
- {
884
- let pid = child.id() as i32;
885
- let _ = unsafe { libc::killpg(pid, libc::SIGKILL) };
886
- }
887
- let _ = child.kill();
888
- let deadline = Instant::now() + NODEPROBE_KILL_GRACE;
889
- while Instant::now() < deadline {
890
- match child.try_wait() {
891
- Ok(Some(_)) | Err(_) => return,
892
- Ok(None) => thread::sleep(Duration::from_millis(5)),
893
- }
894
- }
895
- }
896
-
897
- #[cfg(test)]
898
- fn spawn_nodeprobe(binary: &Path, endpoint: &str) -> Option<Child> {
899
- let flag = if Path::new(endpoint).is_absolute() {
900
- "-S"
901
- } else {
902
- "-L"
903
- };
904
- let mut command = Command::new(binary);
905
- command.arg(flag).arg(endpoint);
906
- configure_nodeprobe_command(&mut command);
907
- command.spawn().ok()
908
- }
909
-
910
- #[derive(Clone, Default)]
911
- #[cfg(test)]
912
- struct ResolverOptions {
913
- #[cfg(test)]
914
- delay_after_selection: Option<TestResolverDelay>,
915
- }
916
-
917
- #[cfg(test)]
918
- fn resolver_options() -> ResolverOptions {
919
- #[cfg(test)]
920
- {
921
- return ResolverOptions {
922
- delay_after_selection: TEST_RESOLVER_DELAY.with(|slot| slot.borrow().clone()),
923
- };
924
- }
925
- #[cfg(not(test))]
926
- {
927
- ResolverOptions::default()
928
- }
929
- }
930
-
931
- // A resolver that is stuck in an uninterruptible filesystem syscall may outlive
932
- // the caller deadline. It owns only its candidate work; the active gate prevents
933
- // repeated status calls from accumulating more detached resolver threads.
934
- #[cfg(test)]
935
- struct ResolverActiveGuard {
936
- #[cfg(test)]
937
- finished_signal: Option<ResolverDelaySignal>,
938
- }
939
-
940
- #[cfg(test)]
941
- impl Drop for ResolverActiveGuard {
942
- fn drop(&mut self) {
943
- NODEPROBE_RESOLVER_ACTIVE.store(false, Ordering::Release);
944
- #[cfg(test)]
945
- if let Some(signal) = self.finished_signal.take() {
946
- signal.finished.store(true, Ordering::Release);
947
- }
948
- }
949
- }
950
-
951
- #[cfg(test)]
952
- fn resolve_nodeprobe_binary(
953
- candidates: Vec<PathBuf>,
954
- deadline: Instant,
955
- options: ResolverOptions,
956
- ) -> Option<PathBuf> {
957
- #[cfg(not(test))]
958
- let _ = options;
959
- if Instant::now() >= deadline || NODEPROBE_RESOLVER_ACTIVE.swap(true, Ordering::AcqRel) {
960
- return None;
961
- }
962
- let (tx, rx) = mpsc::sync_channel(1);
963
- let worker = thread::Builder::new()
964
- .name("team-agent-nodeprobe-resolver".to_string())
965
- .spawn(move || {
966
- #[cfg(test)]
967
- let delay_signal = options
968
- .delay_after_selection
969
- .as_ref()
970
- .map(|config| config.signal.clone());
971
- let _guard = ResolverActiveGuard {
972
- #[cfg(test)]
973
- finished_signal: delay_signal,
974
- };
975
- let result = select_nodeprobe_binary(candidates, deadline);
976
- if result.is_some() {
977
- #[cfg(test)]
978
- if let Some(config) = options.delay_after_selection {
979
- config.signal.entered.store(true, Ordering::Release);
980
- thread::sleep(config.delay);
981
- }
982
- }
983
- let _ = tx.send(result);
984
- });
985
- if worker.is_err() {
986
- NODEPROBE_RESOLVER_ACTIVE.store(false, Ordering::Release);
987
- return None;
988
- }
989
- let timeout = deadline.saturating_duration_since(Instant::now());
990
- // Only the caller may turn a timely result into a child process. A late
991
- // resolver result is dropped with the receiver and can never spawn probe.
992
- match rx.recv_timeout(timeout) {
993
- Ok(Some(binary)) if Instant::now() < deadline => Some(binary),
994
- Ok(_) | Err(_) => None,
995
- }
996
- }
997
-
998
- #[cfg(test)]
999
- fn select_nodeprobe_binary(candidates: Vec<PathBuf>, deadline: Instant) -> Option<PathBuf> {
1000
- for candidate in candidates {
1001
- if Instant::now() >= deadline {
1002
- return None;
1003
- }
1004
- if let Some(binary) = validate_nodeprobe_candidate(&candidate, deadline) {
1005
- return Some(binary);
1006
- }
1007
- }
1008
- None
1009
- }
1010
-
1011
- #[cfg(test)]
1012
- fn nodeprobe_candidates() -> Vec<PathBuf> {
1013
- #[cfg(test)]
1014
- {
1015
- let override_bins = TEST_NODEPROBE.with(|slot| slot.borrow().clone());
1016
- if let Some(paths) = override_bins {
1017
- return paths;
1018
- }
1019
- }
1020
- let mut candidates = std::env::var_os("PATH")
1021
- .map(|path| {
1022
- std::env::split_paths(&path)
1023
- .map(|entry| entry.join(NODEPROBE_NAME))
1024
- .collect::<Vec<_>>()
1025
- })
1026
- .unwrap_or_default();
1027
- if let Some(home) = std::env::var_os("HOME") {
1028
- candidates.push(PathBuf::from(home).join(".local/bin").join(NODEPROBE_NAME));
1029
- }
1030
- candidates
1031
- }
1032
-
1033
- #[cfg(test)]
1034
- fn validate_nodeprobe_candidate(path: &Path, deadline: Instant) -> Option<PathBuf> {
1035
- if Instant::now() >= deadline {
1036
- return None;
1037
- }
1038
- let metadata = std::fs::metadata(path).ok()?;
1039
- if !metadata.is_file() || !is_executable(&metadata) {
1040
- return None;
1041
- }
1042
- let receipt_path = nodeprobe_receipt_path(path);
1043
- let receipt_metadata = std::fs::metadata(&receipt_path).ok()?;
1044
- if !receipt_metadata.is_file() || receipt_metadata.len() > NODEPROBE_RECEIPT_LIMIT {
1045
- return None;
1046
- }
1047
- let receipt: NodeprobeCapabilityReceipt = serde_json::from_slice(&read_bounded_file(
1048
- &receipt_path,
1049
- NODEPROBE_RECEIPT_LIMIT,
1050
- deadline,
1051
- )?)
1052
- .ok()?;
1053
- if !valid_nodeprobe_receipt(&receipt, path) || Instant::now() >= deadline {
1054
- return None;
1055
- }
1056
- let digest = sha256_file(path, deadline)?;
1057
- (digest == receipt.binary_sha256).then_some(path.to_path_buf())
1058
- }
1059
-
1060
- #[cfg(test)]
1061
- fn valid_nodeprobe_receipt(receipt: &NodeprobeCapabilityReceipt, binary: &Path) -> bool {
1062
- receipt.schema == NODEPROBE_RECEIPT_SCHEMA
1063
- && binary.file_name().and_then(|name| name.to_str()) == Some(NODEPROBE_NAME)
1064
- && receipt.binary == NODEPROBE_NAME
1065
- && valid_sha256(&receipt.binary_sha256)
1066
- && receipt.source_repo == NODEPROBE_SOURCE_REPO
1067
- && receipt.source_commit == NODEPROBE_SOURCE_COMMIT
1068
- && receipt.source_tree == NODEPROBE_SOURCE_TREE
1069
- && current_nodeprobe_target().is_some_and(|target| receipt.target == target)
1070
- && receipt.report_schema == NODEPROBE_REPORT_SCHEMA
1071
- && same_string_set(&receipt.capabilities, NODEPROBE_CAPABILITIES)
1072
- && same_string_set(&receipt.forbidden, NODEPROBE_FORBIDDEN)
1073
- }
1074
-
1075
- #[cfg(test)]
1076
- fn valid_sha256(value: &str) -> bool {
1077
- value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit())
1078
- }
1079
-
1080
- #[cfg(test)]
1081
- fn same_string_set(actual: &[String], expected: &[&str]) -> bool {
1082
- let mut actual = actual.to_vec();
1083
- actual.sort_unstable();
1084
- let mut expected = expected
1085
- .iter()
1086
- .map(|value| (*value).to_string())
1087
- .collect::<Vec<_>>();
1088
- expected.sort_unstable();
1089
- actual == expected
1090
- }
1091
-
1092
- #[cfg(test)]
1093
- fn nodeprobe_receipt_path(binary: &Path) -> PathBuf {
1094
- let name = binary
1095
- .file_name()
1096
- .and_then(|name| name.to_str())
1097
- .unwrap_or(NODEPROBE_NAME);
1098
- binary.with_file_name(format!("{name}{NODEPROBE_RECEIPT_SUFFIX}"))
1099
- }
1100
-
1101
- #[cfg(test)]
1102
- fn read_bounded_file(path: &Path, limit: u64, deadline: Instant) -> Option<Vec<u8>> {
1103
- let metadata = std::fs::metadata(path).ok()?;
1104
- if !metadata.is_file() || metadata.len() > limit {
1105
- return None;
1106
- }
1107
- let mut file = open_readonly_nonblocking(path)?;
1108
- let mut bytes = Vec::with_capacity(metadata.len() as usize);
1109
- let mut chunk = [0u8; NODEPROBE_READ_CHUNK];
1110
- loop {
1111
- if Instant::now() >= deadline {
1112
- return None;
1113
- }
1114
- let read = file.read(&mut chunk).ok()?;
1115
- if read == 0 {
1116
- return Some(bytes);
1117
- }
1118
- bytes.extend_from_slice(&chunk[..read]);
1119
- if bytes.len() as u64 > limit {
1120
- return None;
1121
- }
1122
- }
1123
- }
1124
-
1125
- #[cfg(test)]
1126
- fn sha256_file(path: &Path, deadline: Instant) -> Option<String> {
1127
- let metadata = std::fs::metadata(path).ok()?;
1128
- if !metadata.is_file() || metadata.len() > NODEPROBE_BINARY_LIMIT {
1129
- return None;
1130
- }
1131
- let mut file = open_readonly_nonblocking(path)?;
1132
- let mut hasher = Sha256::new();
1133
- let mut chunk = [0u8; NODEPROBE_READ_CHUNK];
1134
- let mut total = 0u64;
1135
- loop {
1136
- if Instant::now() >= deadline {
1137
- return None;
1138
- }
1139
- let read = file.read(&mut chunk).ok()?;
1140
- if read == 0 {
1141
- return Some(format!("{:x}", hasher.finalize()));
1142
- }
1143
- total = total.saturating_add(read as u64);
1144
- if total > NODEPROBE_BINARY_LIMIT {
1145
- return None;
1146
- }
1147
- hasher.update(&chunk[..read]);
1148
- }
1149
- }
1150
-
1151
- #[cfg(test)]
1152
- fn open_readonly_nonblocking(path: &Path) -> Option<File> {
1153
- let mut options = OpenOptions::new();
1154
- options.read(true);
1155
- #[cfg(unix)]
1156
- {
1157
- use std::os::unix::fs::OpenOptionsExt;
1158
- options.custom_flags(libc::O_NONBLOCK);
1159
- }
1160
- options.open(path).ok()
1161
- }
1162
-
1163
- #[cfg(test)]
1164
- fn is_executable(metadata: &std::fs::Metadata) -> bool {
1165
- #[cfg(unix)]
1166
- {
1167
- use std::os::unix::fs::PermissionsExt;
1168
- metadata.permissions().mode() & 0o111 != 0
1169
- }
1170
- #[cfg(not(unix))]
1171
- {
1172
- let _ = metadata;
1173
- true
1174
- }
1175
- }
1176
-
1177
- #[cfg(test)]
1178
- fn current_nodeprobe_target() -> Option<&'static str> {
1179
- match (std::env::consts::OS, std::env::consts::ARCH) {
1180
- ("macos", "aarch64") => Some("aarch64-apple-darwin"),
1181
- ("macos", "x86_64") => Some("x86_64-apple-darwin"),
1182
- ("linux", "aarch64") => Some("aarch64-unknown-linux-gnu"),
1183
- ("linux", "x86_64") => Some("x86_64-unknown-linux-gnu"),
1184
- ("windows", "x86_64") => Some("x86_64-pc-windows-msvc"),
1185
- _ => None,
1186
- }
1187
- }
1188
-
1189
- #[cfg(test)]
1190
- fn configure_nodeprobe_command(command: &mut Command) {
1191
- command
1192
- .stdin(Stdio::null())
1193
- .stdout(Stdio::piped())
1194
- .stderr(Stdio::null());
1195
- #[cfg(unix)]
1196
- {
1197
- use std::os::unix::process::CommandExt;
1198
- command.process_group(0);
1199
- }
1200
- }
1201
-
1202
- #[cfg(test)]
1203
- fn parse_probe(bytes: &[u8], requested_endpoint: &str) -> Result<ProbeResult, ()> {
1204
- let value: Value = serde_json::from_slice(bytes).map_err(|_| ())?;
1205
- if value.get("schema_version").and_then(Value::as_u64) != Some(1) {
1206
- return Err(());
1207
- }
1208
- if probe_has_error(&value) {
1209
- return Err(());
1210
- }
1211
- let report_socket = value.get("socket").and_then(Value::as_str).ok_or(())?;
1212
- if report_socket != requested_endpoint {
1213
- return Err(());
1214
- }
1215
- let nodes = value
1216
- .get("nodes")
1217
- .and_then(Value::as_array)
1218
- .ok_or(())?
1219
- .iter()
1220
- .filter_map(|node| parse_probe_node(node, report_socket))
1221
- .collect();
1222
- Ok(ProbeResult { nodes, ..Default::default() })
1223
- }
1224
-
1225
- #[cfg(test)]
1226
- fn probe_has_error(value: &Value) -> bool {
1227
- match value.get("error") {
1228
- None | Some(Value::Null) => false,
1229
- Some(Value::String(text)) => !text.is_empty(),
1230
- Some(Value::Array(items)) => !items.is_empty(),
1231
- Some(Value::Object(map)) => !map.is_empty(),
1232
- Some(_) => true,
1233
- }
1234
- }
1235
-
1236
- #[cfg(test)]
1237
- fn parse_probe_node(value: &Value, report_socket: &str) -> Option<ProbeNode> {
1238
- Some(ProbeNode {
1239
- // The accepted producer binds the socket once at the report envelope
1240
- // and omits the redundant per-node field. An explicit node socket is
1241
- // still preserved for strict mismatch rejection below.
1242
- socket: non_empty(value, "socket").unwrap_or_else(|| report_socket.to_string()),
1243
- session: non_empty(value, "session")?,
1244
- window: non_empty(value, "window_name")?,
1245
- pane: non_empty(value, "pane_id")?,
1246
- provider: non_empty(value, "provider")?,
1247
- activity: non_empty(value, "activity")?,
1248
- health: non_empty(value, "health")?,
1249
- session_name: value
1250
- .get("session_name")
1251
- .and_then(Value::as_str)
1252
- .filter(|value| !value.is_empty())
1253
- .map(str::to_string),
1254
- evidence_method: value
1255
- .pointer("/evidence/method")
1256
- .and_then(Value::as_str)
1257
- .map(str::to_string),
1258
- })
1259
- }
1260
-
1261
- #[cfg(test)]
1262
- fn non_empty(value: &Value, key: &str) -> Option<String> {
1263
- value
1264
- .get(key)
1265
- .and_then(Value::as_str)
1266
- .filter(|value| !value.is_empty())
1267
- .map(str::to_string)
1268
- }
1269
-
1270
- #[cfg(test)]
1271
- fn project_node(node: &RegisteredNode, probe: Option<&Option<ProbeResult>>) -> BriefNode {
1272
- project_node_with_attach(node, probe).0
1273
- }
1274
-
1275
- fn project_node_with_attach(
1276
- node: &RegisteredNode,
1277
- probe: Option<&Option<ProbeResult>>,
1278
- ) -> (BriefNode, Option<AttachContext>) {
1279
- let stopped = matches!(
1280
- node.lifecycle.as_deref(),
1281
- Some("stopped" | "done" | "failed" | "error" | "terminated")
1282
- );
1283
- let matched = match_result(node, probe);
1284
- if stopped {
1285
- let projected = match matched {
1286
- MatchResult::Missing => BriefNode {
1287
- name: node.name.clone(),
1288
- provider: node.provider.clone(),
1289
- model: node.model.clone(),
1290
- effort: node.effort.clone(),
1291
- runtime_status: "stopped".to_string(),
1292
- activity: "unknown".to_string(),
1293
- health: "unknown".to_string(),
1294
- session_name: None,
1295
- tmux_command: None,
1296
- observation_reason: None,
1297
- },
1298
- MatchResult::Unique(_) | MatchResult::Ambiguous => BriefNode::unknown(node).with_reason("stopped_registration_has_live_pane"),
1299
- };
1300
- return (projected, None);
1301
- }
1302
- let MatchResult::Unique(observed) = matched else {
1303
- let reason = if matches!(matched, MatchResult::Ambiguous) {
1304
- "pane_observation_ambiguous"
1305
- } else if node.endpoint.is_none() {
1306
- "endpoint_unregistered"
1307
- } else if node.session.is_none() || node.pane.is_none() {
1308
- "pane_binding_incomplete"
1309
- } else if let Some(sample) = probe.and_then(Option::as_ref) {
1310
- if sample.exited.iter().any(|(session, window, pane)| {
1311
- node.session.as_deref() == Some(session.as_str())
1312
- && node.window.as_deref().is_none_or(|name| name == window)
1313
- && node.pane.as_deref() == Some(pane.as_str())
1314
- }) { "pane_process_exited" }
1315
- else if matches!(node.lifecycle.as_deref(), Some("starting" | "launching" | "pending")) { "startup_not_yet_observed" }
1316
- else { "registered_pane_not_observed" }
1317
- } else { "endpoint_probe_unavailable" };
1318
- return (BriefNode::unknown(node).with_reason(reason), None);
1319
- };
1320
- if !node.provider.eq_ignore_ascii_case("unknown")
1321
- && !node.provider.eq_ignore_ascii_case(&observed.provider)
1322
- {
1323
- return (BriefNode::unknown(node).with_reason("provider_observation_mismatch"), None);
1324
- }
1325
- let pi_channel = observed.provider.eq_ignore_ascii_case("pi")
1326
- && observed.evidence_method.as_deref() == Some("pi_activity_channel");
1327
- let native_tmux = observed.evidence_method.as_deref() == Some("native_tmux");
1328
- let activity = if observed.provider.eq_ignore_ascii_case("pi") && !pi_channel && !native_tmux {
1329
- "unknown"
1330
- } else if native_tmux && claude_node(node) {
1331
- claude_registry_activity(node)
1332
- } else {
1333
- valid_activity(&observed.activity)
1334
- };
1335
- let health = if observed.provider.eq_ignore_ascii_case("pi") && !pi_channel && !native_tmux {
1336
- "unknown"
1337
- } else {
1338
- valid_health(&observed.health)
1339
- };
1340
- let tmux_command = tmux_command(node, observed);
1341
- let attach = tmux_command.as_ref().map(|_| AttachContext {
1342
- endpoint: observed.socket.clone(),
1343
- session: observed.session.clone(),
1344
- window: observed.window.clone(),
1345
- pane: observed.pane.clone(),
1346
- });
1347
- (
1348
- BriefNode {
1349
- name: node.name.clone(),
1350
- provider: if node.provider.eq_ignore_ascii_case("unknown") {
1351
- observed.provider.clone()
1352
- } else {
1353
- node.provider.clone()
1354
- },
1355
- model: node.model.clone(),
1356
- effort: node.effort.clone(),
1357
- runtime_status: "running".to_string(),
1358
- activity: activity.to_string(),
1359
- health: health.to_string(),
1360
- session_name: observed.session_name.clone(),
1361
- tmux_command,
1362
- observation_reason: (activity == "unknown" || health == "unknown").then_some("activity_or_health_not_observed"),
1363
- },
1364
- attach,
1365
- )
1366
- }
1367
-
1368
- fn match_result<'a>(
1369
- node: &RegisteredNode,
1370
- probe: Option<&'a Option<ProbeResult>>,
1371
- ) -> MatchResult<'a> {
1372
- let Some(probe) = probe.and_then(|probe| probe.as_ref()) else {
1373
- return MatchResult::Missing;
1374
- };
1375
- let mut matches = probe
1376
- .nodes
1377
- .iter()
1378
- .filter(|observed| matches_registered(node, observed));
1379
- let Some(first) = matches.next() else {
1380
- return MatchResult::Missing;
1381
- };
1382
- if matches.next().is_some() {
1383
- MatchResult::Ambiguous
1384
- } else {
1385
- MatchResult::Unique(first)
1386
- }
1387
- }
1388
-
1389
- fn matches_registered(node: &RegisteredNode, observed: &ProbeNode) -> bool {
1390
- node.endpoint.as_deref() == Some(observed.socket.as_str())
1391
- && node.session.as_deref() == Some(observed.session.as_str())
1392
- // Older registrations may not persist a window. The endpoint,
1393
- // session, and pane tuple remains the narrow compatibility key; a
1394
- // present window is still an exact constraint.
1395
- && node
1396
- .window
1397
- .as_deref()
1398
- .is_none_or(|window| window == observed.window)
1399
- && node.pane.as_deref() == Some(observed.pane.as_str())
1400
- }
1401
-
1402
- fn claude_node(node: &RegisteredNode) -> bool {
1403
- crate::provider::wire::parse_provider(&node.provider)
1404
- .is_some_and(crate::provider::wire::is_claude_family)
1405
- }
1406
-
1407
- /// #379: a live Claude pane always runs the Claude process, so its command
1408
- /// name says nothing about the turn; Claude's own session registry does.
1409
- fn claude_registry_activity(node: &RegisteredNode) -> &'static str {
1410
- let state = node.claude_registry.as_ref().and_then(|(sessions, session_id)| {
1411
- crate::provider::claude_registry_turn_state(sessions, session_id, node.pane.as_deref())
1412
- });
1413
- match state {
1414
- Some(crate::provider::TurnState::Working) => "working",
1415
- Some(crate::provider::TurnState::Idle) => "idle",
1416
- _ => "unknown",
1417
- }
1418
- }
1419
-
1420
- fn valid_activity(value: &str) -> &str {
1421
- match value {
1422
- "working" | "idle" => value,
1423
- _ => "unknown",
1424
- }
1425
- }
1426
-
1427
- fn valid_health(value: &str) -> &str {
1428
- match value {
1429
- "normal" | "abnormal" | "unknown" => value,
1430
- _ => "unknown",
1431
- }
1432
- }
1433
-
1434
- fn tmux_command(node: &RegisteredNode, observed: &ProbeNode) -> Option<String> {
1435
- let endpoint = node.endpoint.as_deref()?;
1436
- let target = format!("{}:{}.{}", observed.session, observed.window, observed.pane);
1437
- let flag = if Path::new(endpoint).is_absolute() {
1438
- "-S"
1439
- } else {
1440
- "-L"
1441
- };
1442
- Some(format!(
1443
- "tmux {flag} {} attach -t {}",
1444
- shell_quote(endpoint),
1445
- shell_quote(&target)
1446
- ))
1447
- }
1448
-
1449
- fn shell_quote(value: &str) -> String {
1450
- format!("'{}'", value.replace('\'', "'\\''"))
1451
- }
1452
-
1453
- impl BriefNode {
1454
- fn unknown(node: &RegisteredNode) -> Self {
1455
- Self {
1456
- name: node.name.clone(),
1457
- provider: node.provider.clone(),
1458
- model: node.model.clone(),
1459
- effort: node.effort.clone(),
1460
- runtime_status: "unknown".to_string(),
1461
- activity: "unknown".to_string(),
1462
- health: "unknown".to_string(),
1463
- session_name: None,
1464
- tmux_command: None,
1465
- observation_reason: Some("observation_inconclusive"),
1466
- }
1467
- }
1468
-
1469
- fn with_reason(mut self, reason: &'static str) -> Self {
1470
- self.observation_reason = Some(reason);
1471
- self
1472
- }
1473
-
1474
- fn into_json(self) -> Value {
1475
- let mut object = Map::new();
1476
- object.insert("name".to_string(), json!(self.name));
1477
- object.insert("provider".to_string(), json!(self.provider));
1478
- object.insert("model".to_string(), json!(self.model));
1479
- object.insert("effort".to_string(), json!(self.effort));
1480
- object.insert("runtime_status".to_string(), json!(self.runtime_status));
1481
- object.insert("activity".to_string(), json!(self.activity));
1482
- object.insert("health".to_string(), json!(self.health));
1483
- object.insert(
1484
- "session_name".to_string(),
1485
- self.session_name.map(Value::String).unwrap_or(Value::Null),
1486
- );
1487
- object.insert(
1488
- "tmux_command".to_string(),
1489
- self.tmux_command.map(Value::String).unwrap_or(Value::Null),
1490
- );
1491
- if let Some(reason) = self.observation_reason {
1492
- object.insert("observation_reason".into(), json!(reason));
1493
- }
1494
- Value::Object(object)
1495
- }
1496
- }
1497
-
1498
- fn scoped_node_json(node: BriefNode, workspace: &Path, state: &Value) -> Value {
1499
- let mut value = node.into_json();
1500
- if let Some(reason) = value["observation_reason"].as_str() {
1501
- let guidance = match reason {
1502
- "pane_process_exited" => "pane process exit confirmed; inspect saved session and Leader binding before explicit start",
1503
- "startup_not_yet_observed" | "native_runtime_not_ready" => "wait for startup convergence and recheck this scope; do not reset on unknown",
1504
- _ => "inspect this scope's observation and identity; do not infer process exit or retry lifecycle from unknown alone",
1505
- };
1506
- value["next_action"] = json!(format!(
1507
- "team-agent doctor --workspace {} --team {} --json; {guidance}",
1508
- shell_quote(&workspace.to_string_lossy()),
1509
- shell_quote(&crate::state::projection::team_state_key(state)),
1510
- ));
1511
- }
1512
- value
1513
- }
1514
-
1515
- #[cfg(test)]
1516
- mod native_ps_batch_regressions {
1517
- #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1518
- use super::*;
1519
-
1520
- fn registered(endpoint: &str, pane: &str) -> RegisteredNode {
1521
- RegisteredNode {
1522
- name: format!("{endpoint}-{pane}"),
1523
- provider: "pi".into(),
1524
- model: Some("fixture-model".into()),
1525
- effort: Some("high".into()),
1526
- endpoint: Some(endpoint.into()),
1527
- session: Some("hp".into()),
1528
- window: Some("w".into()),
1529
- pane: Some(pane.into()),
1530
- lifecycle: None,
1531
- claude_registry: None,
1532
- }
1533
- }
1534
-
1535
- #[test]
1536
- fn issue338_unknown_status_has_reason_and_same_scope_next_action() {
1537
- let state = json!({
1538
- "team_key": "scoped-team", "session_name": "sess",
1539
- "agents": {"worker": {"provider": "pi", "status": "running"}}
1540
- });
1541
- let status = status_brief_scoped(Path::new("/owned/workspace with spaces"), &state, None);
1542
- let node = &status["nodes"][0];
1543
- assert_eq!(node["runtime_status"], "unknown");
1544
- assert_eq!(node["observation_reason"], "endpoint_unregistered");
1545
- let action = node["next_action"].as_str().unwrap();
1546
- assert!(action.contains("--workspace '/owned/workspace with spaces'"));
1547
- assert!(action.contains("--team 'scoped-team'"));
1548
- assert!(action.contains("doctor"));
1549
- assert!(!action.contains("restart"));
1550
- }
1551
-
1552
- #[test]
1553
- fn issue338_confirmed_zombie_is_not_reported_as_unexplained_unknown() {
1554
- let node = registered("e1", "%7");
1555
- let probe = sample_native_panes("hp\tw\t%7\t123\tpi\n", "e1", &[node.clone()], |_| {
1556
- BTreeMap::from([(123, ProcessSnapshot { zombie: true })])
1557
- });
1558
- let value = project_node(&node, Some(&Some(probe))).into_json();
1559
- assert_eq!(value["runtime_status"], "unknown");
1560
- assert_eq!(value["observation_reason"], "pane_process_exited");
1561
- assert!(value["tmux_command"].is_null());
1562
- }
1563
-
1564
- #[test]
1565
- fn eight_panes_use_one_endpoint_query() {
1566
- let registered = (0..8)
1567
- .map(|i| registered("e1", &format!("%{i}")))
1568
- .collect::<Vec<_>>();
1569
- let panes = (0..8)
1570
- .map(|i| format!("hp\tw\t%{i}\t{}\tpi\n", 100 + i))
1571
- .collect::<String>();
1572
- let rows = (0..8)
1573
- .map(|i| format!("{} 1 S pi\n", 100 + i))
1574
- .collect::<String>();
1575
- let mut calls = Vec::new();
1576
- let result = sample_native_panes(&panes, "e1", &registered, |pids| {
1577
- calls.push(pids.iter().copied().collect::<Vec<_>>());
1578
- parse_process_snapshots(rows.as_bytes(), pids)
1579
- });
1580
- assert_eq!(calls, vec![(100..108).collect::<Vec<_>>()]);
1581
- assert_eq!(result.nodes.len(), 8);
1582
- assert!(result.nodes.iter().all(|node| node.provider == "pi"
1583
- && node.activity == "working"
1584
- && node.health == "normal"));
1585
- }
1586
-
1587
- #[test]
1588
- fn pid_deduplication_and_command_preserve_the_privacy_whitelist() {
1589
- let mut calls = Vec::new();
1590
- let result = sample_native_panes(
1591
- "hp\tw\t%1\t11\tsh\nhp\tw\t%2\t011\tsh\n",
1592
- "e1",
1593
- &[],
1594
- |pids| {
1595
- calls.push(pids.iter().copied().collect::<Vec<_>>());
1596
- parse_process_snapshots(b"11 1 S sh\n", pids)
1597
- },
1598
- );
1599
- assert_eq!(calls, vec![vec![11]]);
1600
- assert_eq!(result.nodes.len(), 2);
1601
- let pids = BTreeSet::from([22, 11]);
1602
- let command = process_snapshot_command(&pids);
1603
- assert_eq!(command.get_program(), "ps");
1604
- assert_eq!(
1605
- command
1606
- .get_args()
1607
- .map(|arg| arg.to_string_lossy().into_owned())
1608
- .collect::<Vec<_>>(),
1609
- vec!["-o", "pid=,ppid=,stat=,comm=", "-p", "11,22"]
1610
- );
1611
- let command = process_snapshot_command(&BTreeSet::from([11]));
1612
- assert_eq!(command.get_args().last().unwrap(), "11");
1613
- }
1614
-
1615
- #[cfg(unix)]
1616
- #[test]
1617
- fn native_ps_partial_selection_preserves_a_live_pid() {
1618
- let pid = std::process::id();
1619
- let requested = BTreeSet::from([pid, i32::MAX as u32]);
1620
- let command = process_snapshot_command(&requested);
1621
- // Absolute ps avoids unrelated PATH-fixture mutation in parallel unit tests.
1622
- let output = Command::new("/bin/ps")
1623
- .args(command.get_args())
1624
- .output()
1625
- .unwrap();
1626
- assert!(
1627
- output.status.success(),
1628
- "partial PID selection must not poison the live row"
1629
- );
1630
- let snapshots = parse_process_snapshots(&output.stdout, &requested);
1631
- assert!(!snapshots.get(&pid).unwrap().zombie);
1632
- assert!(!snapshots.contains_key(&(i32::MAX as u32)));
1633
- }
1634
-
1635
- #[test]
1636
- fn single_pane_keeps_its_native_health_and_activity() {
1637
- let registered = vec![registered("e1", "%1")];
1638
- let result = sample_native_panes("hp\tw\t%1\t11\tsh\n", "e1", &registered, |pids| {
1639
- assert_eq!(pids, &BTreeSet::from([11]));
1640
- parse_process_snapshots(b"11 1 S sh\n", pids)
1641
- });
1642
- assert_eq!(result.nodes.len(), 1);
1643
- assert_eq!(result.nodes[0].provider, "pi");
1644
- assert_eq!(result.nodes[0].activity, "idle");
1645
- assert_eq!(result.nodes[0].health, "normal");
1646
- }
1647
-
1648
- #[test]
1649
- fn missing_rows_and_zombies_omit_only_their_panes() {
1650
- let panes = "hp\tw\t%1\t11\tsh\nhp\tw\t%2\t22\tpi\nhp\tw\t%3\t33\tpi\nhp\tw\t%4\t\tsh\n";
1651
- let result = sample_native_panes(panes, "e1", &[], |pids| {
1652
- parse_process_snapshots(b"22 1 Z+ dead\n11 1 S sh\n999 1 S unrelated\n33 1\n", pids)
1653
- });
1654
- assert_eq!(
1655
- result
1656
- .nodes
1657
- .iter()
1658
- .map(|node| node.pane.as_str())
1659
- .collect::<Vec<_>>(),
1660
- vec!["%1", "%4"]
1661
- );
1662
- assert!(result
1663
- .nodes
1664
- .iter()
1665
- .all(|node| node.activity == "idle" && node.health == "normal"));
1666
- }
1667
-
1668
- #[test]
1669
- fn empty_or_invalid_pid_sets_do_not_run_ps() {
1670
- let panes = "hp\tw\t%1\t\tsh\nhp\tw\t%2\t0\tsh\nhp\tw\t%3\t1,2\tsh\nhp\tw\t%4\t4294967295\tsh\n\tw\t%5\t99\tsh\n";
1671
- let result = sample_native_panes(panes, "e1", &[], |_| {
1672
- panic!("no valid PID means no ps query")
1673
- });
1674
- assert_eq!(result.nodes.len(), 1);
1675
- assert_eq!(result.nodes[0].pane, "%1");
1676
- assert_eq!(result.nodes[0].health, "normal");
1677
- }
1678
-
1679
- #[test]
1680
- fn snapshot_failure_and_endpoint_results_are_not_shared() {
1681
- let registered = vec![registered("e1", "%1"), registered("e2", "%1")];
1682
- let mut calls = Vec::new();
1683
- let first = sample_native_panes("hp\tw\t%1\t88\tsh\n", "e1", &registered, |pids| {
1684
- calls.push(("e1", pids.iter().copied().collect::<Vec<_>>()));
1685
- BTreeMap::new()
1686
- });
1687
- let second = sample_native_panes("hp\tw\t%1\t88\tsh\n", "e2", &registered, |pids| {
1688
- calls.push(("e2", pids.iter().copied().collect::<Vec<_>>()));
1689
- parse_process_snapshots(b"88 1 S sh\n", pids)
1690
- });
1691
- assert_eq!(calls, vec![("e1", vec![88]), ("e2", vec![88])]);
1692
- assert!(first.nodes.is_empty());
1693
- assert_eq!(second.nodes.len(), 1);
1694
- let failed = Some(first);
1695
- assert_eq!(
1696
- project_node_with_attach(&registered[0], Some(&failed))
1697
- .0
1698
- .health,
1699
- "unknown"
1700
- );
1701
- let live = Some(second);
1702
- assert_eq!(
1703
- project_node_with_attach(&registered[1], Some(&live))
1704
- .0
1705
- .health,
1706
- "normal"
1707
- );
1708
- }
1709
-
1710
- #[test]
1711
- fn duplicate_process_rows_cannot_hide_a_zombie() {
1712
- let requested = BTreeSet::from([11]);
1713
- for rows in [
1714
- b"11 1 Z dead\n11 1 S sh\n".as_slice(),
1715
- b"11 1 S sh\n11 1 Z dead\n".as_slice(),
1716
- ] {
1717
- assert!(
1718
- parse_process_snapshots(rows, &requested)
1719
- .get(&11)
1720
- .unwrap()
1721
- .zombie
1722
- );
1723
- }
1724
- assert!(parse_process_snapshots(b"not a process row\n", &requested).is_empty());
1725
- }
1726
-
1727
- #[test]
1728
- fn json_and_human_keep_nine_fields_without_ps_details() {
1729
- let registered = vec![registered("e1", "%1"), registered("e1", "%2")];
1730
- let probe = Some(sample_native_panes(
1731
- "hp\tw\t%1\t11\tsh\nhp\tw\t%2\t22\tpi\n",
1732
- "e1",
1733
- &registered,
1734
- |pids| {
1735
- parse_process_snapshots(
1736
- b"22 1 R PRIVATE_COMMAND_DETAIL\n11 1 S PRIVATE_COMMAND_DETAIL\n",
1737
- pids,
1738
- )
1739
- },
1740
- ));
1741
- let projected = registered
1742
- .iter()
1743
- .map(|node| project_node_with_attach(node, Some(&probe)))
1744
- .collect::<Vec<_>>();
1745
- let keys = BTreeSet::from([
1746
- "name",
1747
- "provider",
1748
- "model",
1749
- "effort",
1750
- "runtime_status",
1751
- "activity",
1752
- "health",
1753
- "session_name",
1754
- "tmux_command",
1755
- ]);
1756
- for (node, _) in &projected {
1757
- let json = node.clone().into_json();
1758
- assert_eq!(
1759
- json.as_object()
1760
- .unwrap()
1761
- .keys()
1762
- .map(String::as_str)
1763
- .collect::<BTreeSet<_>>(),
1764
- keys
1765
- );
1766
- assert_eq!(json["model"], "fixture-model");
1767
- assert_eq!(json["effort"], "high");
1768
- assert_eq!(json["runtime_status"], "running");
1769
- assert_eq!(json["health"], "normal");
1770
- assert!(!json.to_string().contains("PRIVATE_COMMAND_DETAIL"));
1771
- }
1772
- let human = format_multi_node_brief(projected);
1773
- let mut lines = human.lines().skip_while(|line| !line.starts_with("NAME\t"));
1774
- assert_eq!(lines.next().unwrap().split('\t').count(), 9);
1775
- assert!(lines.all(|line| line.split('\t').count() == 9));
1776
- assert!(!human.contains("PRIVATE_COMMAND_DETAIL"));
1777
- }
1778
- }
1779
-
1780
- #[cfg(test)]
1781
- mod tests {
1782
- #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1783
- use super::*;
1784
-
1785
- fn registered() -> RegisteredNode {
1786
- RegisteredNode {
1787
- name: "worker".to_string(),
1788
- provider: "pi".to_string(),
1789
- model: None,
1790
- effort: None,
1791
- endpoint: Some("/tmp/tmux socket/o'k".to_string()),
1792
- session: Some("sess".to_string()),
1793
- window: Some("win".to_string()),
1794
- pane: Some("%7".to_string()),
1795
- lifecycle: None,
1796
- claude_registry: None,
1797
- }
1798
- }
1799
-
1800
- fn probe(method: &str) -> ProbeNode {
1801
- ProbeNode {
1802
- socket: "/tmp/tmux socket/o'k".to_string(),
1803
- session: "sess".to_string(),
1804
- window: "win".to_string(),
1805
- pane: "%7".to_string(),
1806
- provider: "pi".to_string(),
1807
- activity: "idle".to_string(),
1808
- health: "normal".to_string(),
1809
- session_name: Some("pi-session".to_string()),
1810
- evidence_method: Some(method.to_string()),
1811
- }
1812
- }
1813
-
1814
- fn producer_error_envelope() -> &'static [u8] {
1815
- br#"{"schema_version":1,"socket":"/tmp/sock","sampled_at":"2026-01-01T00:00:00Z","nodes":[],"error":{"kind":"tmux_inventory","message":"missing"}}"#
1816
- }
1817
-
1818
- #[test]
1819
- fn status_model_effort_project_accepted_launch_settings_in_all_runtime_states() {
1820
- for settings in [(None, None), (Some("openai-codex/gpt-6-luna"), Some("max"))] {
1821
- let mut node = registered();
1822
- node.model = settings.0.map(str::to_string);
1823
- node.effort = settings.1.map(str::to_string);
1824
- for lifecycle in [None, Some("stopped")] {
1825
- node.lifecycle = lifecycle.map(str::to_string);
1826
- for sample in [
1827
- None,
1828
- Some(ProbeResult {
1829
- nodes: vec![probe("pi_activity_channel")],
1830
- ..Default::default()
1831
- }),
1832
- ] {
1833
- let value = project_node(&node, Some(&sample)).into_json();
1834
- assert_eq!(value["model"], json!(settings.0));
1835
- assert_eq!(value["effort"], json!(settings.1));
1836
- let human = format_brief_node(&value).unwrap();
1837
- assert!(human.contains(&format!(
1838
- "model: {} effort: {}",
1839
- settings.0.unwrap_or("null"),
1840
- settings.1.unwrap_or("null")
1841
- )));
1842
- let diagnostics = usize::from(value.get("observation_reason").is_some());
1843
- assert_eq!(value.as_object().unwrap().len(), 9 + diagnostics);
1844
- if value["runtime_status"] == "unknown" {
1845
- assert!(!value["observation_reason"].as_str().unwrap().is_empty());
1846
- }
1847
- }
1848
- }
1849
- }
1850
- }
1851
-
1852
- #[test]
1853
- fn status_model_effort_use_canonical_runtime_roster_not_stale_projection() {
1854
- let state = json!({
1855
- "active_team_key": "selected",
1856
- "agents": {"worker": {"model": "stale-model", "effort": "low"}},
1857
- "teams": {"selected": {"agents": {
1858
- "worker": {"model": "accepted-model", "effort": "max"},
1859
- "plain": {}
1860
- }}}
1861
- });
1862
- let selected = registered_nodes(&state, Some("worker"));
1863
- assert_eq!(selected.len(), 1);
1864
- assert_eq!(selected[0].model.as_deref(), Some("accepted-model"));
1865
- assert_eq!(selected[0].effort.as_deref(), Some("max"));
1866
- let plain = registered_nodes(&state, Some("plain"));
1867
- assert!(plain[0].model.is_none());
1868
- assert!(plain[0].effort.is_none());
1869
- }
1870
-
1871
- #[test]
1872
- fn pi_pane_title_is_unknown_not_idle() {
1873
- let node = registered();
1874
- let observed = probe("pane_title");
1875
- let projected = project_node(
1876
- &node,
1877
- Some(&Some(ProbeResult {
1878
- nodes: vec![observed],
1879
- ..Default::default()
1880
- })),
1881
- );
1882
- assert_eq!(projected.runtime_status, "running");
1883
- assert_eq!(projected.activity, "unknown");
1884
- assert_eq!(projected.health, "unknown");
1885
- }
1886
-
1887
- #[test]
1888
- fn exact_probe_generates_quoted_window_pane_command() {
1889
- let node = registered();
1890
- let observed = probe("pi_activity_channel");
1891
- let projected = project_node(
1892
- &node,
1893
- Some(&Some(ProbeResult {
1894
- nodes: vec![observed],
1895
- ..Default::default()
1896
- })),
1897
- );
1898
- assert_eq!(projected.activity, "idle");
1899
- assert_eq!(
1900
- projected.tmux_command.as_deref(),
1901
- Some("tmux -S '/tmp/tmux socket/o'\\''k' attach -t 'sess:win.%7'"),
1902
- );
1903
- }
1904
-
1905
- // #379: a live Claude pane always runs Claude; its registry names the turn.
1906
- #[cfg(unix)]
1907
- #[test]
1908
- fn issue379_claude_activity_comes_from_its_session_registry_not_the_pane_command() {
1909
- let config = std::env::temp_dir().join(format!("ta-379-brief-{}", std::process::id()));
1910
- let _ = std::fs::remove_dir_all(&config);
1911
- let sid = "33333333-4444-4555-8666-777777777777";
1912
- let projects = config.join("projects").join("-owned-cwd");
1913
- std::fs::create_dir_all(&projects).unwrap();
1914
- std::fs::create_dir_all(config.join("sessions")).unwrap();
1915
- let rollout = projects.join(format!("{sid}.jsonl"));
1916
- std::fs::write(&rollout, "").unwrap();
1917
- let record = config.join("sessions").join(format!("{}.json", std::process::id()));
1918
- let mut node = registered();
1919
- node.provider = "claude".to_string();
1920
- node.claude_registry = crate::provider::claude_registry_key(&json!({"rollout_path": rollout}));
1921
- let mut observed = probe("native_tmux");
1922
- observed.provider = "claude".to_string();
1923
- observed.activity = "working".to_string();
1924
- let sample = Some(ProbeResult { nodes: vec![observed], ..Default::default() });
1925
- for (status, expected) in [("busy", "working"), ("idle", "idle"), ("waiting", "unknown")] {
1926
- let body = json!({"pid": std::process::id(), "sessionId": sid, "tmux": "sess:@1.%7", "status": status});
1927
- std::fs::write(&record, body.to_string()).unwrap();
1928
- assert_eq!(project_node(&node, Some(&sample)).activity, expected, "{status}");
1929
- }
1930
- // Cold start: the ready prompt before any transcript is captured.
1931
- let body = json!({"pid": std::process::id(), "sessionId": sid, "tmux": "sess:@1.%7", "status": "idle"});
1932
- std::fs::write(&record, body.to_string()).unwrap();
1933
- let cold = registered_node(
1934
- "worker",
1935
- &json!({"provider": "claude", "_pending_session_id": sid, "claude_projects_root": config.join("projects")}),
1936
- &json!({}),
1937
- );
1938
- node.claude_registry = cold.claude_registry;
1939
- assert_eq!(project_node(&node, Some(&sample)).activity, "idle");
1940
- std::fs::remove_file(&record).unwrap();
1941
- let projected = project_node(&node, Some(&sample));
1942
- assert_eq!(projected.activity, "unknown", "the process name is not a turn state");
1943
- assert_eq!(projected.observation_reason, Some("activity_or_health_not_observed"));
1944
- let _ = std::fs::remove_dir_all(&config);
1945
- }
1946
-
1947
- #[test]
1948
- fn stopped_registration_is_retained_without_sample() {
1949
- let mut node = registered();
1950
- node.lifecycle = Some("stopped".to_string());
1951
- let projected = project_node(&node, None);
1952
- assert_eq!(projected.runtime_status, "stopped");
1953
- assert_eq!(projected.activity, "unknown");
1954
- assert!(projected.tmux_command.is_none());
1955
- }
1956
-
1957
- #[test]
1958
- fn stopped_with_live_sample_is_unknown_conflict() {
1959
- let mut node = registered();
1960
- node.lifecycle = Some("stopped".to_string());
1961
- let observed = probe("pi_activity_channel");
1962
- let projected = project_node(
1963
- &node,
1964
- Some(&Some(ProbeResult {
1965
- nodes: vec![observed],
1966
- ..Default::default()
1967
- })),
1968
- );
1969
- assert_eq!(projected.runtime_status, "unknown");
1970
- assert!(projected.tmux_command.is_none());
1971
- }
1972
-
1973
- #[test]
1974
- fn stopped_with_duplicate_live_samples_is_unknown_conflict() {
1975
- let mut node = registered();
1976
- node.lifecycle = Some("stopped".to_string());
1977
- let projected = project_node(
1978
- &node,
1979
- Some(&Some(ProbeResult {
1980
- nodes: vec![probe("pi_activity_channel"), probe("pi_activity_channel")],
1981
- ..Default::default()
1982
- })),
1983
- );
1984
- assert_eq!(projected.runtime_status, "unknown");
1985
- assert!(projected.tmux_command.is_none());
1986
- }
1987
-
1988
- #[test]
1989
- fn zero_matches_is_unknown_not_panic() {
1990
- let node = registered();
1991
- let mut observed = probe("pi_activity_channel");
1992
- observed.pane = "%9".to_string();
1993
- let projected = project_node(
1994
- &node,
1995
- Some(&Some(ProbeResult {
1996
- nodes: vec![observed],
1997
- ..Default::default()
1998
- })),
1999
- );
2000
- assert_eq!(projected.runtime_status, "unknown");
2001
- }
2002
-
2003
- #[test]
2004
- fn multiple_matches_is_unknown_not_indexed() {
2005
- let node = registered();
2006
- let projected = project_node(
2007
- &node,
2008
- Some(&Some(ProbeResult {
2009
- nodes: vec![probe("pi_activity_channel"), probe("pi_activity_channel")],
2010
- ..Default::default()
2011
- })),
2012
- );
2013
- assert_eq!(projected.runtime_status, "unknown");
2014
- }
2015
-
2016
- // Frozen 1257e8e3 used `br"{\"error\":\"missing\"}"`, which is not a valid
2017
- // raw byte string (VERIFY compile gate: unknown start of token `\\`).
2018
- // Keep that failure as history; this regression uses a real producer envelope.
2019
- #[test]
2020
- fn parse_probe_rejects_producer_error_envelope() {
2021
- assert!(parse_probe(producer_error_envelope(), "/tmp/sock").is_err());
2022
- }
2023
-
2024
- #[test]
2025
- fn parse_probe_rejects_exit_zero_error_with_nodes() {
2026
- let bytes = br#"{"schema_version":1,"socket":"/tmp/sock","sampled_at":"2026-01-01T00:00:00Z","nodes":[{"socket":"/tmp/sock","session":"sess","window_name":"win","pane_id":"%7","provider":"pi","activity":"idle","health":"normal","evidence":{"method":"pi_activity_channel"}}],"error":{"kind":"corpus_error","message":"providers corpus failed"}}"#;
2027
- assert!(parse_probe(bytes, "/tmp/sock").is_err());
2028
- }
2029
-
2030
- #[test]
2031
- fn parse_probe_rejects_wrong_report_socket() {
2032
- let bytes = br#"{"schema_version":1,"socket":"/tmp/other","sampled_at":"2026-01-01T00:00:00Z","nodes":[]}"#;
2033
- assert!(parse_probe(bytes, "/tmp/sock").is_err());
2034
- }
2035
-
2036
- #[test]
2037
- fn parse_probe_accepts_matching_producer_report() {
2038
- let bytes = br#"{"schema_version":1,"socket":"/tmp/sock","sampled_at":"2026-01-01T00:00:00Z","nodes":[{"socket":"/tmp/sock","session":"sess","window_name":"win","pane_id":"%7","provider":"pi","activity":"idle","health":"normal","session_name":"pi-session","evidence":{"method":"pi_activity_channel"}}]}"#;
2039
- let parsed = parse_probe(bytes, "/tmp/sock").expect("valid producer report");
2040
- assert_eq!(parsed.nodes.len(), 1);
2041
- assert_eq!(parsed.nodes[0].pane, "%7");
2042
- }
2043
- }