@team-agent/installer 0.5.107 → 0.5.108

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.
@@ -117,6 +117,14 @@ struct BriefNode {
117
117
  tmux_command: Option<String>,
118
118
  }
119
119
 
120
+ #[derive(Clone, Debug, PartialEq, Eq)]
121
+ struct AttachContext {
122
+ endpoint: String,
123
+ session: String,
124
+ window: String,
125
+ pane: String,
126
+ }
127
+
120
128
  #[derive(Debug)]
121
129
  struct ProbeResult {
122
130
  nodes: Vec<ProbeNode>,
@@ -150,34 +158,45 @@ pub(crate) fn status_brief_scoped(
150
158
  state: &Value,
151
159
  agent: Option<&str>,
152
160
  ) -> Value {
153
- let registered = registered_nodes(state, agent);
154
- let probes = probe_registered_endpoints(&registered);
155
- let nodes = registered
156
- .iter()
157
- .map(|node| project_node(node, probes.get(node.endpoint.as_deref().unwrap_or(""))))
158
- .collect::<Vec<_>>();
161
+ let nodes = project_status_nodes(state, agent);
159
162
  json!({
160
- "nodes": nodes.into_iter().map(BriefNode::into_json).collect::<Vec<_>>()
163
+ "nodes": nodes
164
+ .into_iter()
165
+ .map(|(node, _)| node.into_json())
166
+ .collect::<Vec<_>>()
161
167
  })
162
168
  }
163
169
 
164
- /// Human output is the exact same nine-field projection as JSON, rendered in
165
- /// stable field order. Null values remain explicit rather than becoming a
166
- /// diagnostic or an inferred value.
170
+ /// Human output keeps the legacy single-node form and groups shared attach
171
+ /// context only when multiple nodes make that repetition useful.
167
172
  pub(crate) fn format_status_brief(
168
- workspace: &Path,
173
+ _workspace: &Path,
169
174
  state: &Value,
170
175
  agent: Option<&str>,
171
176
  ) -> String {
172
- let value = status_brief_scoped(workspace, state, agent);
173
- value
174
- .get("nodes")
175
- .and_then(Value::as_array)
176
- .into_iter()
177
- .flatten()
178
- .filter_map(format_brief_node)
179
- .collect::<Vec<_>>()
180
- .join("\n")
177
+ let nodes = project_status_nodes(state, agent);
178
+ if nodes.len() <= 1 {
179
+ return nodes
180
+ .into_iter()
181
+ .filter_map(|(node, _)| format_brief_node(&node.into_json()))
182
+ .collect::<Vec<_>>()
183
+ .join("\n");
184
+ }
185
+ format_multi_node_brief(nodes)
186
+ }
187
+
188
+ fn project_status_nodes(
189
+ state: &Value,
190
+ agent: Option<&str>,
191
+ ) -> Vec<(BriefNode, Option<AttachContext>)> {
192
+ let registered = registered_nodes(state, agent);
193
+ let probes = probe_registered_endpoints(&registered);
194
+ registered
195
+ .iter()
196
+ .map(|node| {
197
+ project_node_with_attach(node, probes.get(node.endpoint.as_deref().unwrap_or("")))
198
+ })
199
+ .collect()
181
200
  }
182
201
 
183
202
  pub(crate) fn registered_agent_exists(state: &Value, agent: &str) -> bool {
@@ -322,6 +341,86 @@ fn format_brief_node(value: &Value) -> Option<String> {
322
341
  ))
323
342
  }
324
343
 
344
+ fn format_multi_node_brief(nodes: Vec<(BriefNode, Option<AttachContext>)>) -> String {
345
+ let mut groups = Vec::<(String, String)>::new();
346
+ for (_, context) in &nodes {
347
+ let Some(context) = context else { continue };
348
+ if !groups.iter().any(|(endpoint, session)| {
349
+ endpoint == &context.endpoint && session == &context.session
350
+ }) {
351
+ groups.push((context.endpoint.clone(), context.session.clone()));
352
+ }
353
+ }
354
+
355
+ let mut lines = groups
356
+ .iter()
357
+ .enumerate()
358
+ .map(|(index, (endpoint, session))| {
359
+ format_attach_template(index + 1, endpoint, session)
360
+ })
361
+ .collect::<Vec<_>>();
362
+ if !groups.is_empty() {
363
+ lines.push(
364
+ "TMUX templates: replace <target> with the window.pane part of the matching ATTACH value."
365
+ .to_string(),
366
+ );
367
+ }
368
+ lines.push(
369
+ "NAME\tPROVIDER\tMODEL\tEFFORT\tRUNTIME_STATUS\tACTIVITY\tHEALTH\tSESSION_NAME\tATTACH"
370
+ .to_string(),
371
+ );
372
+ for (node, context) in nodes {
373
+ let attach = context
374
+ .as_ref()
375
+ .and_then(|context| {
376
+ groups
377
+ .iter()
378
+ .position(|(endpoint, session)| {
379
+ endpoint == &context.endpoint && session == &context.session
380
+ })
381
+ .map(|index| format!("{}:{}.{}", index + 1, context.window, context.pane))
382
+ })
383
+ .unwrap_or_else(|| "null".to_string());
384
+ lines.push(
385
+ [
386
+ escape_human_cell(&node.name),
387
+ escape_human_cell(&node.provider),
388
+ escape_human_cell(node.model.as_deref().unwrap_or("null")),
389
+ escape_human_cell(node.effort.as_deref().unwrap_or("null")),
390
+ escape_human_cell(&node.runtime_status),
391
+ escape_human_cell(&node.activity),
392
+ escape_human_cell(&node.health),
393
+ escape_human_cell(node.session_name.as_deref().unwrap_or("null")),
394
+ escape_human_cell(&attach),
395
+ ]
396
+ .join("\t"),
397
+ );
398
+ }
399
+ lines.join("\n")
400
+ }
401
+
402
+ fn format_attach_template(group: usize, endpoint: &str, session: &str) -> String {
403
+ let flag = if Path::new(endpoint).is_absolute() {
404
+ "-S"
405
+ } else {
406
+ "-L"
407
+ };
408
+ let target = format!("{session}:<target>");
409
+ format!(
410
+ "TMUX[{group}] tmux {flag} {} attach -t {}",
411
+ shell_quote(endpoint),
412
+ shell_quote(&target)
413
+ )
414
+ }
415
+
416
+ fn escape_human_cell(value: &str) -> String {
417
+ value
418
+ .replace('\\', "\\\\")
419
+ .replace('\t', "\\t")
420
+ .replace('\n', "\\n")
421
+ .replace('\r', "\\r")
422
+ }
423
+
325
424
  fn display_optional(value: &Value) -> String {
326
425
  value
327
426
  .as_str()
@@ -1051,14 +1150,22 @@ fn non_empty(value: &Value, key: &str) -> Option<String> {
1051
1150
  .map(str::to_string)
1052
1151
  }
1053
1152
 
1153
+ #[cfg(test)]
1054
1154
  fn project_node(node: &RegisteredNode, probe: Option<&Option<ProbeResult>>) -> BriefNode {
1155
+ project_node_with_attach(node, probe).0
1156
+ }
1157
+
1158
+ fn project_node_with_attach(
1159
+ node: &RegisteredNode,
1160
+ probe: Option<&Option<ProbeResult>>,
1161
+ ) -> (BriefNode, Option<AttachContext>) {
1055
1162
  let stopped = matches!(
1056
1163
  node.lifecycle.as_deref(),
1057
1164
  Some("stopped" | "done" | "failed" | "error" | "terminated")
1058
1165
  );
1059
1166
  let matched = match_result(node, probe);
1060
1167
  if stopped {
1061
- return match matched {
1168
+ let projected = match matched {
1062
1169
  MatchResult::Missing => BriefNode {
1063
1170
  name: node.name.clone(),
1064
1171
  provider: node.provider.clone(),
@@ -1072,14 +1179,15 @@ fn project_node(node: &RegisteredNode, probe: Option<&Option<ProbeResult>>) -> B
1072
1179
  },
1073
1180
  MatchResult::Unique(_) | MatchResult::Ambiguous => BriefNode::unknown(node),
1074
1181
  };
1182
+ return (projected, None);
1075
1183
  }
1076
1184
  let MatchResult::Unique(observed) = matched else {
1077
- return BriefNode::unknown(node);
1185
+ return (BriefNode::unknown(node), None);
1078
1186
  };
1079
1187
  if !node.provider.eq_ignore_ascii_case("unknown")
1080
1188
  && !node.provider.eq_ignore_ascii_case(&observed.provider)
1081
1189
  {
1082
- return BriefNode::unknown(node);
1190
+ return (BriefNode::unknown(node), None);
1083
1191
  }
1084
1192
  let pi_channel = observed.provider.eq_ignore_ascii_case("pi")
1085
1193
  && observed.evidence_method.as_deref() == Some("pi_activity_channel");
@@ -1097,21 +1205,31 @@ fn project_node(node: &RegisteredNode, probe: Option<&Option<ProbeResult>>) -> B
1097
1205
  } else {
1098
1206
  valid_health(&observed.health)
1099
1207
  };
1100
- BriefNode {
1101
- name: node.name.clone(),
1102
- provider: if node.provider.eq_ignore_ascii_case("unknown") {
1103
- observed.provider.clone()
1104
- } else {
1105
- node.provider.clone()
1208
+ let tmux_command = tmux_command(node, observed);
1209
+ let attach = tmux_command.as_ref().map(|_| AttachContext {
1210
+ endpoint: observed.socket.clone(),
1211
+ session: observed.session.clone(),
1212
+ window: observed.window.clone(),
1213
+ pane: observed.pane.clone(),
1214
+ });
1215
+ (
1216
+ BriefNode {
1217
+ name: node.name.clone(),
1218
+ provider: if node.provider.eq_ignore_ascii_case("unknown") {
1219
+ observed.provider.clone()
1220
+ } else {
1221
+ node.provider.clone()
1222
+ },
1223
+ model: node.model.clone(),
1224
+ effort: node.effort.clone(),
1225
+ runtime_status: "running".to_string(),
1226
+ activity: activity.to_string(),
1227
+ health: health.to_string(),
1228
+ session_name: observed.session_name.clone(),
1229
+ tmux_command,
1106
1230
  },
1107
- model: node.model.clone(),
1108
- effort: node.effort.clone(),
1109
- runtime_status: "running".to_string(),
1110
- activity: activity.to_string(),
1111
- health: health.to_string(),
1112
- session_name: observed.session_name.clone(),
1113
- tmux_command: tmux_command(node, observed),
1114
- }
1231
+ attach,
1232
+ )
1115
1233
  }
1116
1234
 
1117
1235
  fn match_result<'a>(
@@ -1930,3 +1930,187 @@ fn unit0_sessions_to_kill_leader_prefixed_session_is_always_spared() {
1930
1930
  ),
1931
1931
  }
1932
1932
  }
1933
+
1934
+ const ISSUE_269_ROOT_PID: u32 = 2_147_000_001;
1935
+
1936
+ std::thread_local! {
1937
+ static ISSUE_269_LIVENESS_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1938
+ static ISSUE_269_FIRST_ALIVE: std::cell::RefCell<Option<std::time::Instant>> = const { std::cell::RefCell::new(None) };
1939
+ static ISSUE_269_DEATH_DELAY: std::cell::Cell<Option<std::time::Duration>> = const { std::cell::Cell::new(None) };
1940
+ }
1941
+
1942
+ struct ShutdownWorkspaceCleanup(PathBuf);
1943
+
1944
+ impl Drop for ShutdownWorkspaceCleanup {
1945
+ fn drop(&mut self) {
1946
+ let _ = std::fs::remove_dir_all(&self.0);
1947
+ }
1948
+ }
1949
+
1950
+ fn reset_issue_269_probe_state() {
1951
+ ISSUE_269_LIVENESS_CALLS.with(|calls| calls.set(0));
1952
+ ISSUE_269_FIRST_ALIVE.with(|first| *first.borrow_mut() = None);
1953
+ ISSUE_269_DEATH_DELAY.with(|delay| delay.set(None));
1954
+ }
1955
+
1956
+ fn issue_269_liveness_call_count() -> usize {
1957
+ ISSUE_269_LIVENESS_CALLS.with(std::cell::Cell::get)
1958
+ }
1959
+
1960
+ fn issue_269_empty_process_table() -> Result<Vec<String>, String> {
1961
+ Ok(Vec::new())
1962
+ }
1963
+
1964
+ fn issue_269_transient_liveness(pid: u32) -> bool {
1965
+ if pid != ISSUE_269_ROOT_PID {
1966
+ return false;
1967
+ }
1968
+ ISSUE_269_LIVENESS_CALLS.with(|calls| {
1969
+ let call = calls.get();
1970
+ calls.set(call + 1);
1971
+ match call {
1972
+ 0 => {
1973
+ ISSUE_269_FIRST_ALIVE.with(|first| *first.borrow_mut() = Some(std::time::Instant::now()));
1974
+ true
1975
+ }
1976
+ 1 => {
1977
+ let elapsed = ISSUE_269_FIRST_ALIVE.with(|first| {
1978
+ first.borrow().as_ref().map(std::time::Instant::elapsed)
1979
+ });
1980
+ ISSUE_269_DEATH_DELAY.with(|delay| delay.set(elapsed));
1981
+ false
1982
+ }
1983
+ _ => false,
1984
+ }
1985
+ })
1986
+ }
1987
+
1988
+ fn issue_269_persistent_liveness(pid: u32) -> bool {
1989
+ if pid == ISSUE_269_ROOT_PID {
1990
+ ISSUE_269_LIVENESS_CALLS.with(|calls| calls.set(calls.get() + 1));
1991
+ true
1992
+ } else {
1993
+ false
1994
+ }
1995
+ }
1996
+
1997
+ fn issue_269_already_gone_liveness(pid: u32) -> bool {
1998
+ if pid == ISSUE_269_ROOT_PID {
1999
+ ISSUE_269_LIVENESS_CALLS.with(|calls| calls.set(calls.get() + 1));
2000
+ }
2001
+ false
2002
+ }
2003
+
2004
+ fn save_issue_269_root_state(workspace: &Path, session: &str) {
2005
+ crate::state::persist::save_runtime_state(
2006
+ workspace,
2007
+ &json!({
2008
+ "session_name": session,
2009
+ "team_key": session,
2010
+ "generation": session,
2011
+ "agents": {
2012
+ "worker": {
2013
+ "status": "running",
2014
+ "provider": "fake",
2015
+ "window": "worker",
2016
+ "provider_pid": ISSUE_269_ROOT_PID
2017
+ }
2018
+ }
2019
+ }),
2020
+ )
2021
+ .unwrap();
2022
+ }
2023
+
2024
+ fn shutdown_issue_269_with_probes(
2025
+ workspace: &Path,
2026
+ session: &str,
2027
+ liveness: fn(u32) -> bool,
2028
+ ) -> serde_json::Value {
2029
+ let transport = CleanShutdownTransport::new().with_owned_session(
2030
+ workspace,
2031
+ session,
2032
+ session,
2033
+ session,
2034
+ );
2035
+ crate::cli::lifecycle_port::with_process_table_test_probe(
2036
+ issue_269_empty_process_table,
2037
+ || {
2038
+ crate::cli::lifecycle_port::with_pid_liveness_test_probe(liveness, || {
2039
+ crate::cli::lifecycle_port::shutdown_with_transport(
2040
+ workspace,
2041
+ true,
2042
+ None,
2043
+ &transport,
2044
+ )
2045
+ .expect("shutdown should complete")
2046
+ })
2047
+ },
2048
+ )
2049
+ }
2050
+
2051
+ #[test]
2052
+ fn issue269_transient_unmatched_root_converges_inside_grace() {
2053
+ let workspace = tmp_shutdown_workspace("issue269-transient-root");
2054
+ let _workspace_cleanup = ShutdownWorkspaceCleanup(workspace.clone());
2055
+ let session = "team-issue269-transient";
2056
+ save_issue_269_root_state(&workspace, session);
2057
+ reset_issue_269_probe_state();
2058
+
2059
+ let started = std::time::Instant::now();
2060
+ let out = shutdown_issue_269_with_probes(&workspace, session, issue_269_transient_liveness);
2061
+ let elapsed = started.elapsed();
2062
+ let calls = issue_269_liveness_call_count();
2063
+ let death_delay = ISSUE_269_DEATH_DELAY.with(std::cell::Cell::get);
2064
+
2065
+ assert_eq!(
2066
+ out["ok"],
2067
+ json!(true),
2068
+ "an absent final process-table row plus a root that dies during the bounded grace must converge; ppid=0/empty-command is only a conservative placeholder, not a measured identity: {out}"
2069
+ );
2070
+ assert_eq!(out["residuals"]["processes"], json!([]), "{out}");
2071
+ assert!(calls >= 2, "the wait must observe both live and gone states; calls={calls}");
2072
+ assert!(death_delay.is_some_and(|delay| delay <= std::time::Duration::from_millis(500)), "root did not disappear within the bounded grace: {death_delay:?}");
2073
+ assert!(elapsed < std::time::Duration::from_secs(2), "shutdown exceeded the bounded wait: {elapsed:?}");
2074
+ }
2075
+
2076
+ #[test]
2077
+ fn issue269_persistent_unmatched_root_remains_a_residual_after_grace() {
2078
+ let workspace = tmp_shutdown_workspace("issue269-persistent-root");
2079
+ let _workspace_cleanup = ShutdownWorkspaceCleanup(workspace.clone());
2080
+ let session = "team-issue269-persistent";
2081
+ save_issue_269_root_state(&workspace, session);
2082
+ reset_issue_269_probe_state();
2083
+
2084
+ let started = std::time::Instant::now();
2085
+ let out = shutdown_issue_269_with_probes(&workspace, session, issue_269_persistent_liveness);
2086
+ let elapsed = started.elapsed();
2087
+ let calls = issue_269_liveness_call_count();
2088
+ let residuals = out["residuals"]["processes"].as_array().unwrap();
2089
+
2090
+ assert_eq!(out["ok"], json!(false), "a live root must not be filtered by placeholder fields: {out}");
2091
+ assert_eq!(residuals.len(), 1, "{out}");
2092
+ assert_eq!(residuals[0]["pid"], json!(ISSUE_269_ROOT_PID), "{out}");
2093
+ assert_eq!(residuals[0]["ppid"], json!(0), "{out}");
2094
+ assert_eq!(residuals[0]["command"], json!(""), "{out}");
2095
+ assert!((2..=30).contains(&calls), "persistent-root polling must remain bounded; calls={calls}");
2096
+ assert!(elapsed < std::time::Duration::from_secs(2), "shutdown exceeded the bounded wait: {elapsed:?}");
2097
+ }
2098
+
2099
+ #[test]
2100
+ fn issue269_already_gone_root_returns_without_fixed_grace_sleep() {
2101
+ let workspace = tmp_shutdown_workspace("issue269-already-gone-root");
2102
+ let _workspace_cleanup = ShutdownWorkspaceCleanup(workspace.clone());
2103
+ let session = "team-issue269-gone";
2104
+ save_issue_269_root_state(&workspace, session);
2105
+ reset_issue_269_probe_state();
2106
+
2107
+ let started = std::time::Instant::now();
2108
+ let out = shutdown_issue_269_with_probes(&workspace, session, issue_269_already_gone_liveness);
2109
+ let elapsed = started.elapsed();
2110
+ let calls = issue_269_liveness_call_count();
2111
+
2112
+ assert_eq!(out["ok"], json!(true), "{out}");
2113
+ assert_eq!(out["residuals"]["processes"], json!([]), "{out}");
2114
+ assert!(calls >= 2, "the final verification path and wait path must both observe liveness; calls={calls}");
2115
+ assert!(elapsed < std::time::Duration::from_millis(450), "already-gone roots must not incur a fixed grace sleep: {elapsed:?}");
2116
+ }