Skip to content

Commit db13a9b

Browse files
committed
fix(agent): honor global JSON output format
- apply global --format json/json-compact to guard/validate/suggest - preserve legacy subcommand --json compact one-line output - cover offline and server-mode fallback format contracts
1 parent 018d186 commit db13a9b

2 files changed

Lines changed: 234 additions & 16 deletions

File tree

‎crates/terraphim_agent/src/main.rs‎

Lines changed: 56 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1988,8 +1988,15 @@ async fn run_offline_command(
19881988
};
19891989
let result = guard.check(&input_command);
19901990

1991-
if *json {
1992-
println!("{}", serde_json::to_string(&result)?);
1991+
let json_output = *json || output.is_machine_readable();
1992+
let json_mode = if *json && matches!(output.mode, CommandOutputMode::Human) {
1993+
CommandOutputMode::JsonCompact
1994+
} else {
1995+
output.mode
1996+
};
1997+
1998+
if json_output {
1999+
print_json_output(&result, json_mode)?;
19932000
} else if result.decision == guard_patterns::GuardDecision::Block {
19942001
if let Some(reason) = &result.reason {
19952002
eprintln!("BLOCKED: {}", reason);
@@ -2570,12 +2577,18 @@ async fn run_offline_command(
25702577
};
25712578

25722579
let role_name = service.resolve_role(role.as_deref()).await?;
2580+
let json_output = json || output.is_machine_readable();
2581+
let json_mode = if json && matches!(output.mode, CommandOutputMode::Human) {
2582+
CommandOutputMode::JsonCompact
2583+
} else {
2584+
output.mode
2585+
};
25732586

25742587
if connectivity {
25752588
let result = service.check_connectivity(&role_name, &input_text).await?;
25762589

2577-
if json {
2578-
println!("{}", serde_json::to_string(&result)?);
2590+
if json_output {
2591+
print_json_output(&result, json_mode)?;
25792592
} else {
25802593
println!("Connectivity Check for role '{}':", role_name);
25812594
println!(" Connected: {}", result.connected);
@@ -2588,8 +2601,8 @@ async fn run_offline_command(
25882601
.validate_checklist(&role_name, &checklist_name, &input_text)
25892602
.await?;
25902603

2591-
if json {
2592-
println!("{}", serde_json::to_string(&result)?);
2604+
if json_output {
2605+
print_json_output(&result, json_mode)?;
25932606
} else {
25942607
println!(
25952608
"Checklist '{}' Validation for role '{}':",
@@ -2614,13 +2627,13 @@ async fn run_offline_command(
26142627
// Default validation: find matches
26152628
let matches = service.find_matches(&role_name, &input_text).await?;
26162629

2617-
if json {
2630+
if json_output {
26182631
let output = serde_json::json!({
26192632
"role": role_name.to_string(),
26202633
"matched_count": matches.len(),
26212634
"matches": matches.iter().map(|m| m.term.clone()).collect::<Vec<_>>()
26222635
});
2623-
println!("{}", serde_json::to_string(&output)?);
2636+
print_json_output(&output, json_mode)?;
26242637
} else {
26252638
println!("Validation for role '{}':", role_name);
26262639
println!(" Found {} matched term(s)", matches.len());
@@ -2651,13 +2664,19 @@ async fn run_offline_command(
26512664
};
26522665

26532666
let role_name = service.resolve_role(role.as_deref()).await?;
2667+
let json_output = json || output.is_machine_readable();
2668+
let json_mode = if json && matches!(output.mode, CommandOutputMode::Human) {
2669+
CommandOutputMode::JsonCompact
2670+
} else {
2671+
output.mode
2672+
};
26542673

26552674
let suggestions = service
26562675
.fuzzy_suggest(&role_name, &input_query, threshold, Some(limit))
26572676
.await?;
26582677

2659-
if json {
2660-
println!("{}", serde_json::to_string(&suggestions)?);
2678+
if json_output {
2679+
print_json_output(&suggestions, json_mode)?;
26612680
} else if suggestions.is_empty() {
26622681
println!(
26632682
"No suggestions found for '{}' with threshold {}",
@@ -4669,22 +4688,36 @@ async fn run_server_command(
46694688
}
46704689
}
46714690
Command::Validate { json, .. } => {
4672-
if json {
4691+
let json_output = json || output.is_machine_readable();
4692+
let json_mode = if json && matches!(output.mode, CommandOutputMode::Human) {
4693+
CommandOutputMode::JsonCompact
4694+
} else {
4695+
output.mode
4696+
};
4697+
4698+
if json_output {
46734699
let err = serde_json::json!({
46744700
"error": "Validate command is only available in offline mode"
46754701
});
4676-
println!("{}", serde_json::to_string(&err)?);
4702+
print_json_output(&err, json_mode)?;
46774703
} else {
46784704
eprintln!("Validate command is only available in offline mode");
46794705
}
46804706
std::process::exit(1);
46814707
}
46824708
Command::Suggest { json, .. } => {
4683-
if json {
4709+
let json_output = json || output.is_machine_readable();
4710+
let json_mode = if json && matches!(output.mode, CommandOutputMode::Human) {
4711+
CommandOutputMode::JsonCompact
4712+
} else {
4713+
output.mode
4714+
};
4715+
4716+
if json_output {
46844717
let err = serde_json::json!({
46854718
"error": "Suggest command is only available in offline mode"
46864719
});
4687-
println!("{}", serde_json::to_string(&err)?);
4720+
print_json_output(&err, json_mode)?;
46884721
} else {
46894722
eprintln!("Suggest command is only available in offline mode");
46904723
}
@@ -4748,8 +4781,15 @@ async fn run_server_command(
47484781
};
47494782
let result = guard.check(&input_command);
47504783

4751-
if json {
4752-
println!("{}", serde_json::to_string(&result)?);
4784+
let json_output = json || output.is_machine_readable();
4785+
let json_mode = if json && matches!(output.mode, CommandOutputMode::Human) {
4786+
CommandOutputMode::JsonCompact
4787+
} else {
4788+
output.mode
4789+
};
4790+
4791+
if json_output {
4792+
print_json_output(&result, json_mode)?;
47534793
} else if result.decision == guard_patterns::GuardDecision::Block {
47544794
if let Some(reason) = &result.reason {
47554795
eprintln!("BLOCKED: {}", reason);
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
use anyhow::{Context, Result};
2+
use serde_json::Value;
3+
use std::process::Command;
4+
5+
mod support;
6+
use support::cli_test_env::apply_hermetic_env;
7+
8+
fn run_agent(args: &[&str]) -> Result<(String, String, i32)> {
9+
let mut cmd = Command::new(env!("CARGO_BIN_EXE_terraphim-agent"));
10+
cmd.args(args);
11+
apply_hermetic_env(&mut cmd)?;
12+
13+
let output = cmd.output().context("run terraphim-agent")?;
14+
15+
Ok((
16+
String::from_utf8_lossy(&output.stdout).to_string(),
17+
String::from_utf8_lossy(&output.stderr).to_string(),
18+
output.status.code().unwrap_or(-1),
19+
))
20+
}
21+
22+
#[test]
23+
fn global_json_compact_guard_emits_single_line_json() -> Result<()> {
24+
let (stdout, stderr, code) =
25+
run_agent(&["--format", "json-compact", "guard", "git reset --hard HEAD"])?;
26+
27+
assert_eq!(
28+
code, 0,
29+
"machine-readable guard should preserve --json compatibility; stderr={stderr}"
30+
);
31+
assert!(
32+
!stderr.contains("BLOCKED:"),
33+
"human BLOCKED text must not be emitted for global JSON format: {stderr}"
34+
);
35+
36+
let trimmed = stdout.trim();
37+
assert!(!trimmed.is_empty(), "stdout should contain JSON");
38+
assert_eq!(
39+
trimmed.lines().count(),
40+
1,
41+
"json-compact should be single-line"
42+
);
43+
let json: Value = serde_json::from_str(trimmed)?;
44+
assert_eq!(json["decision"], "block");
45+
assert_eq!(json["command"], "git reset --hard HEAD");
46+
Ok(())
47+
}
48+
49+
#[test]
50+
fn global_json_validate_emits_parseable_json() -> Result<()> {
51+
let (stdout, stderr, code) = run_agent(&["--format", "json", "validate", "terraphim"])?;
52+
53+
assert_eq!(code, 0, "validate should succeed; stderr={stderr}");
54+
let json: Value = serde_json::from_str(stdout.trim())?;
55+
assert!(
56+
json.get("matched_count").is_some() || json.get("error").is_some(),
57+
"unexpected validate JSON: {json}"
58+
);
59+
Ok(())
60+
}
61+
62+
#[test]
63+
fn global_json_compact_suggest_emits_parseable_json() -> Result<()> {
64+
let (stdout, stderr, code) = run_agent(&[
65+
"--format",
66+
"json-compact",
67+
"suggest",
68+
"terraphim",
69+
"--limit",
70+
"3",
71+
])?;
72+
73+
assert_eq!(code, 0, "suggest should succeed; stderr={stderr}");
74+
assert_single_line_json(&stdout)?;
75+
Ok(())
76+
}
77+
78+
#[test]
79+
fn legacy_guard_json_stays_single_line_compact() -> Result<()> {
80+
let (stdout, stderr, code) = run_agent(&["guard", "--json", "git reset --hard HEAD"])?;
81+
82+
assert_eq!(
83+
code, 0,
84+
"legacy guard --json compatibility; stderr={stderr}"
85+
);
86+
assert!(
87+
!stderr.contains("BLOCKED:"),
88+
"legacy JSON guard should not emit human BLOCKED text: {stderr}"
89+
);
90+
let json = assert_single_line_json(&stdout)?;
91+
assert_eq!(json["decision"], "block");
92+
Ok(())
93+
}
94+
95+
#[test]
96+
fn legacy_validate_json_stays_single_line_compact() -> Result<()> {
97+
let (stdout, stderr, code) = run_agent(&["validate", "--json", "terraphim"])?;
98+
99+
assert_eq!(
100+
code, 0,
101+
"legacy validate --json compatibility; stderr={stderr}"
102+
);
103+
let json = assert_single_line_json(&stdout)?;
104+
assert!(
105+
json.get("matched_count").is_some() || json.get("error").is_some(),
106+
"unexpected validate JSON: {json}"
107+
);
108+
Ok(())
109+
}
110+
111+
#[test]
112+
fn legacy_suggest_json_stays_single_line_compact() -> Result<()> {
113+
let (stdout, stderr, code) = run_agent(&["suggest", "--json", "terraphim", "--limit", "3"])?;
114+
115+
assert_eq!(
116+
code, 0,
117+
"legacy suggest --json compatibility; stderr={stderr}"
118+
);
119+
assert_single_line_json(&stdout)?;
120+
Ok(())
121+
}
122+
123+
#[test]
124+
fn server_mode_global_json_compact_guard_emits_single_line_json() -> Result<()> {
125+
let (stdout, stderr, code) = run_agent(&[
126+
"--server",
127+
"--format",
128+
"json-compact",
129+
"guard",
130+
"git reset --hard HEAD",
131+
])?;
132+
133+
assert_eq!(
134+
code, 0,
135+
"machine-readable server-mode guard should preserve --json compatibility; stderr={stderr}"
136+
);
137+
assert!(
138+
!stderr.contains("BLOCKED:"),
139+
"human BLOCKED text must not be emitted for server-mode global JSON format: {stderr}"
140+
);
141+
let json = assert_single_line_json(&stdout)?;
142+
assert_eq!(json["decision"], "block");
143+
Ok(())
144+
}
145+
146+
#[test]
147+
fn server_mode_global_json_validate_error_is_parseable_json() -> Result<()> {
148+
let (stdout, stderr, code) = run_agent(&[
149+
"--server",
150+
"--format",
151+
"json-compact",
152+
"validate",
153+
"terraphim",
154+
])?;
155+
156+
assert_eq!(code, 1, "server-mode validate should remain unavailable");
157+
assert!(
158+
!stderr.contains("Validate command is only available in offline mode"),
159+
"machine-readable unavailable error must be stdout JSON, not human stderr: {stderr}"
160+
);
161+
let json = assert_single_line_json(&stdout)?;
162+
assert_eq!(
163+
json["error"],
164+
"Validate command is only available in offline mode"
165+
);
166+
Ok(())
167+
}
168+
169+
fn assert_single_line_json(stdout: &str) -> Result<Value> {
170+
let trimmed = stdout.trim();
171+
assert!(!trimmed.is_empty(), "stdout should contain JSON");
172+
assert_eq!(
173+
trimmed.lines().count(),
174+
1,
175+
"json-compact should be single-line"
176+
);
177+
Ok(serde_json::from_str(trimmed)?)
178+
}

0 commit comments

Comments
 (0)