Skip to main content

harn_cli/
json_envelope.rs

1//! Canonical JSON envelope for `harn` CLI commands.
2//!
3//! Every `--json` mode returns a [`JsonEnvelope<T>`] — a versioned
4//! wrapper that exposes `schemaVersion`, `ok`, and either `data` or
5//! `error`. Soft signals attach as `warnings` so `ok: true` stays
6//! stable as long as the command succeeds.
7//!
8//! Schema versions are per-command and monotonically increasing.
9//! [`catalog`] returns the registry consumed by `harn --json-schemas`.
10//! New commands extend the catalog (and bump their own
11//! [`JsonOutput::SCHEMA_VERSION`]) when their JSON shape changes in a
12//! way agents need to detect.
13//!
14//! See epic #1753 (`--json` everywhere) for the broader contract.
15
16use serde::{Deserialize, Serialize};
17
18/// Schema version of the `harn --json-schemas` catalog itself. Bump
19/// when the shape of [`SchemaEntry`] or the catalog envelope changes.
20pub const CATALOG_SCHEMA_VERSION: u32 = 1;
21
22/// Versioned wrapper for every `--json` CLI output. All five fields
23/// are always serialized so consumers can rely on a flat shape:
24/// missing payloads surface as `null` and the empty `warnings` array
25/// is `[]` rather than absent.
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct JsonEnvelope<T: Serialize> {
28    #[serde(rename = "schemaVersion")]
29    pub schema_version: u32,
30    pub ok: bool,
31    pub data: Option<T>,
32    pub error: Option<JsonError>,
33    #[serde(default)]
34    pub warnings: Vec<JsonWarning>,
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct JsonError {
39    pub code: String,
40    pub message: String,
41    /// Free-form structured context. `null` when the error has no
42    /// structured payload — the field is always present so consumers
43    /// can read `error.details` without an existence check.
44    #[serde(default)]
45    pub details: serde_json::Value,
46}
47
48#[derive(Debug, Clone, Serialize, Deserialize)]
49pub struct JsonWarning {
50    pub code: String,
51    pub message: String,
52}
53
54/// Implemented by every CLI command that exposes a `--json` mode. The
55/// associated `SCHEMA_VERSION` is also surfaced in [`catalog`] so
56/// agents can negotiate per-command compatibility without parsing
57/// every payload.
58pub trait JsonOutput {
59    const SCHEMA_VERSION: u32;
60    type Data: Serialize;
61    fn into_envelope(self) -> JsonEnvelope<Self::Data>;
62}
63
64impl<T: Serialize> JsonEnvelope<T> {
65    pub fn ok(schema_version: u32, data: T) -> Self {
66        Self {
67            schema_version,
68            ok: true,
69            data: Some(data),
70            error: None,
71            warnings: Vec::new(),
72        }
73    }
74
75    pub fn err(
76        schema_version: u32,
77        code: impl Into<String>,
78        message: impl Into<String>,
79    ) -> JsonEnvelope<T> {
80        Self {
81            schema_version,
82            ok: false,
83            data: None,
84            error: Some(JsonError {
85                code: code.into(),
86                message: message.into(),
87                details: serde_json::Value::Null,
88            }),
89            warnings: Vec::new(),
90        }
91    }
92
93    pub fn with_details(mut self, details: serde_json::Value) -> Self {
94        if let Some(err) = self.error.as_mut() {
95            err.details = details;
96        }
97        self
98    }
99
100    pub fn with_warning(mut self, code: impl Into<String>, message: impl Into<String>) -> Self {
101        self.warnings.push(JsonWarning {
102            code: code.into(),
103            message: message.into(),
104        });
105        self
106    }
107}
108
109/// One row of the `harn --json-schemas` catalog. `schema_json` is
110/// inline when small; richer schemas live behind a future
111/// `schema_url` field documented per-command.
112#[derive(Debug, Clone, Serialize)]
113pub struct SchemaEntry {
114    pub command: &'static str,
115    #[serde(rename = "schemaVersion")]
116    pub schema_version: u32,
117    pub description: &'static str,
118    #[serde(skip_serializing_if = "Option::is_none", rename = "schemaJson")]
119    pub schema_json: Option<serde_json::Value>,
120}
121
122/// Static catalog of commands that already emit a stable JSON shape.
123///
124/// E2.1 seeds the commands that ship a `schema_version` today (doctor,
125/// session export, the provider catalog). New commands register here as
126/// they migrate to [`JsonEnvelope`] — for example, the `skills` family
127/// added in E3.2.
128pub fn catalog() -> Vec<SchemaEntry> {
129    vec![
130        SchemaEntry {
131            command: "doctor",
132            schema_version: crate::commands::doctor::DOCTOR_SCHEMA_VERSION,
133            description: "Capability matrix: host, per-target buildability, per-provider reachability, per-stdlib-effect availability.",
134            schema_json: None,
135        },
136        SchemaEntry {
137            command: "host lease",
138            schema_version: crate::commands::host::HOST_LEASE_CLI_SCHEMA_VERSION,
139            description: "Machine-global host lease acquire, renew, release, and status receipts.",
140            schema_json: None,
141        },
142        SchemaEntry {
143            command: "session export",
144            schema_version: 1,
145            description: "Portable Harn session bundle export.",
146            schema_json: None,
147        },
148        SchemaEntry {
149            command: "provider catalog show",
150            schema_version: 1,
151            description: "Resolved provider/model catalog snapshot.",
152            schema_json: None,
153        },
154        SchemaEntry {
155            command: "connect status",
156            schema_version: 1,
157            description: "Outbound-connector readiness report.",
158            schema_json: None,
159        },
160        SchemaEntry {
161            command: "connect setup-plan",
162            schema_version: 1,
163            description: "Step-by-step plan to bring a connector online.",
164            schema_json: None,
165        },
166        SchemaEntry {
167            command: "mcp status",
168            schema_version: crate::commands::mcp::MCP_STATUS_SCHEMA_VERSION,
169            description: "Per-server MCP readiness: transport, connection state, tool/resource/prompt counts, last error.",
170            schema_json: None,
171        },
172        SchemaEntry {
173            command: "mcp discover",
174            schema_version: crate::commands::mcp::MCP_DISCOVERY_SCHEMA_VERSION,
175            description:
176                "Unofficial MCP endpoint discovery from /.well-known/mcp.json: source URL, found flag, and descriptor.",
177            schema_json: None,
178        },
179        SchemaEntry {
180            command: "run",
181            schema_version: crate::commands::run::json_events::RUN_JSON_SCHEMA_VERSION,
182            description: "Pipeline-run NDJSON event stream (stdout, stderr, transcript, tool, hook, persona, result, error).",
183            schema_json: None,
184        },
185        SchemaEntry {
186            command: "parse",
187            schema_version: crate::commands::parse_tokens::PARSE_JSON_SCHEMA_VERSION,
188            description: "Tagged Harn AST tree with byte spans for parser tooling.",
189            schema_json: None,
190        },
191        SchemaEntry {
192            command: "tokens",
193            schema_version: crate::commands::parse_tokens::TOKENS_JSON_SCHEMA_VERSION,
194            description: "Lexer token stream with source lexemes and byte spans.",
195            schema_json: None,
196        },
197        SchemaEntry {
198            command: "check",
199            schema_version: crate::commands::check::CHECK_SCHEMA_VERSION,
200            description: "Per-file static check results with diagnostics and summary counts.",
201            schema_json: None,
202        },
203        SchemaEntry {
204            command: "fmt",
205            schema_version: crate::commands::check::FMT_SCHEMA_VERSION,
206            description: "Per-file formatting result report for write and check modes.",
207            schema_json: None,
208        },
209        SchemaEntry {
210            command: "check provider-matrix",
211            schema_version: crate::commands::check::provider_matrix::PROVIDER_MATRIX_SCHEMA_VERSION,
212            description: "Provider/model capability matrix rows.",
213            schema_json: None,
214        },
215        SchemaEntry {
216            command: "provider catalog support",
217            schema_version: crate::commands::provider_support::PROVIDER_SUPPORT_SCHEMA_VERSION,
218            description: "Generated provider recommendation and support matrix.",
219            schema_json: None,
220        },
221        SchemaEntry {
222            command: "models batch plan",
223            schema_version: 1,
224            description:
225                "Provider Batch API candidates plus Harn live-adapter support for offline workloads.",
226            schema_json: None,
227        },
228        SchemaEntry {
229            command: "models batch manifest",
230            schema_version: 1,
231            description:
232                "Provider-neutral offline batch manifest summary and request groups.",
233            schema_json: None,
234        },
235        SchemaEntry {
236            command: "models batch prepare",
237            schema_version: 1,
238            description:
239                "Provider-native batch request files, deterministic prepare receipt, and lifecycle state.",
240            schema_json: None,
241        },
242        SchemaEntry {
243            command: "models batch submit",
244            schema_version: 1,
245            description:
246                "Batch submission receipt with provider job ids, dry-run operations, and lifecycle state.",
247            schema_json: None,
248        },
249        SchemaEntry {
250            command: "models batch status",
251            schema_version: 1,
252            description:
253                "Provider batch status receipt with cached/dry-run validation and lifecycle counts.",
254            schema_json: None,
255        },
256        SchemaEntry {
257            command: "models batch cancel",
258            schema_version: 1,
259            description:
260                "Batch cancellation receipt with redacted cancel operations, skipped-job reasons, and lifecycle counts.",
261            schema_json: None,
262        },
263        SchemaEntry {
264            command: "models batch download",
265            schema_version: 1,
266            description:
267                "Provider result-file download receipt with artifact paths, hashes, and lifecycle counts.",
268            schema_json: None,
269        },
270        SchemaEntry {
271            command: "models lora plan",
272            schema_version: 1,
273            description: "Portable LoRA/QLoRA route plan: base model, tool-call format, trainer, data, eval, and launch contract.",
274            schema_json: None,
275        },
276        SchemaEntry {
277            command: "models lora inspect",
278            schema_version: 1,
279            description:
280                "PEFT LoRA adapter compatibility report with base-model, provider, tool-call, and launch metadata.",
281            schema_json: None,
282        },
283        SchemaEntry {
284            command: "models lora export",
285            schema_version: 1,
286            description:
287                "Trainer-ready LoRA dataset export report, including contract id, manifest paths, stats, and validation results.",
288            schema_json: None,
289        },
290        SchemaEntry {
291            command: "models lora manifest",
292            schema_version: 1,
293            description:
294                "Canonical LoRA training-run manifest with route, data, artifact, serving, and promotion contracts.",
295            schema_json: None,
296        },
297        SchemaEntry {
298            command: "models lora preflight",
299            schema_version: 1,
300            description:
301                "LoRA corpus readiness report before GPU training, including sequence-fit, tool-call shape, and threshold failures.",
302            schema_json: None,
303        },
304        SchemaEntry {
305            command: "models lora promote",
306            schema_version: 1,
307            description:
308                "LoRA promotion probe matrix receipt collected from adapter-loaded behavioral probe outputs.",
309            schema_json: None,
310        },
311        SchemaEntry {
312            command: "models lora train",
313            schema_version: 1,
314            description:
315                "LoRA trainer backend receipt with route contract, dataset hashes, backend argv, and post-training manifest commands.",
316            schema_json: None,
317        },
318        SchemaEntry {
319            command: "check connector-matrix",
320            schema_version: crate::commands::check::connector_matrix::CONNECTOR_MATRIX_SCHEMA_VERSION,
321            description: "Connector package capability matrix rows.",
322            schema_json: None,
323        },
324        SchemaEntry {
325            command: "test conformance",
326            schema_version: crate::commands::test::CONFORMANCE_TEST_SCHEMA_VERSION,
327            description:
328                "Conformance results with xfail accounting, fixture snapshot key, and duration distribution.",
329            schema_json: None,
330        },
331        SchemaEntry {
332            command: "test --json-out",
333            schema_version: crate::test_report::USER_TEST_REPORT_SCHEMA_VERSION,
334            description:
335                "User-test report with typed timeout, per-case and aggregate phases, module attribution, and duration distribution.",
336            schema_json: None,
337        },
338        SchemaEntry {
339            command: "time run",
340            schema_version: crate::commands::time::TIME_RUN_SCHEMA_VERSION,
341            description:
342                "Per-phase wall-clock + cache hit/miss + per-LLM/tool-call latency for `harn run`.",
343            schema_json: None,
344        },
345        SchemaEntry {
346            command: "fix plan",
347            schema_version: crate::commands::fix::FIX_PLAN_SCHEMA_VERSION,
348            description: "Plan repair-bearing diagnostics without editing files.",
349            schema_json: None,
350        },
351        SchemaEntry {
352            command: "fix apply",
353            schema_version: crate::commands::fix::FIX_APPLY_SCHEMA_VERSION,
354            description: "Apply clean repair edits at or below a declared safety ceiling.",
355            schema_json: None,
356        },
357        SchemaEntry {
358            command: "skills list",
359            schema_version: 1,
360            description: "Canonical Harn skill corpus, frontmatter only.",
361            schema_json: None,
362        },
363        SchemaEntry {
364            command: "skills get",
365            schema_version: 1,
366            description: "One canonical skill's frontmatter (and body with --full).",
367            schema_json: None,
368        },
369        SchemaEntry {
370            command: "pack",
371            schema_version: crate::commands::pack::PACK_SCHEMA_VERSION,
372            description: "Signed-ready .harnpack run-bundle build summary.",
373            schema_json: Some(crate::commands::pack::json_schema()),
374        },
375        SchemaEntry {
376            command: "pack verify",
377            schema_version: crate::commands::pack::PACK_VERIFY_SCHEMA_VERSION,
378            description:
379                "Result of verifying a .harnpack: bundle hash, signature, per-module hashes.",
380            schema_json: Some(crate::commands::pack::verify_json_schema()),
381        },
382        SchemaEntry {
383            command: "dev",
384            schema_version: 1,
385            description: "`harn dev --watch` incremental NDJSON event stream (ready / fingerprint_changed / rerun / diagnostics / tests).",
386            schema_json: None,
387        },
388        SchemaEntry {
389            command: "routes",
390            schema_version: 1,
391            description: "Static trigger route, budget, capability, and vendor-lock inventory.",
392            schema_json: None,
393        },
394        SchemaEntry {
395            command: "usage",
396            schema_version: crate::commands::usage::USAGE_SCHEMA_VERSION,
397            description:
398                "LLM spend/usage rollup from the event log: per-group calls, cost_usd, tokens, cache telemetry, and time-series cumulatives.",
399            schema_json: None,
400        },
401        SchemaEntry {
402            command: "graph",
403            schema_version: crate::commands::graph::GRAPH_SCHEMA_VERSION,
404            description:
405                "Static module graph with public symbols, imports, capabilities, effects, and host-call surface.",
406            schema_json: None,
407        },
408        SchemaEntry {
409            command: "lint",
410            schema_version: crate::commands::check::LINT_SCHEMA_VERSION,
411            description:
412                "Per-file lint diagnostics with severity, fixable/fixed counts, and summary.",
413            schema_json: None,
414        },
415        SchemaEntry {
416            command: "replay",
417            schema_version: crate::commands::replay::REPLAY_SCHEMA_VERSION,
418            description:
419                "Replay summary: per-stage status/outcome/branch, embedded fixture verdicts, and multi-run determinism.",
420            schema_json: None,
421        },
422        SchemaEntry {
423            command: "version",
424            schema_version: crate::VERSION_SCHEMA_VERSION,
425            description: "CLI build metadata: name, version, description.",
426            schema_json: None,
427        },
428        SchemaEntry {
429            command: "upgrade",
430            schema_version: crate::commands::upgrade::UPGRADE_SCHEMA_VERSION,
431            description:
432                "Self-update probe (`--check`) or install summary: current, target, archive URL, install outcome.",
433            schema_json: None,
434        },
435        SchemaEntry {
436            command: "explain --catalog",
437            schema_version: crate::commands::diagnostics_catalog::SCHEMA_VERSION,
438            description:
439                "Diagnostic-code catalog: per-code summary, repair, safety, related codes.",
440            schema_json: None,
441        },
442        SchemaEntry {
443            command: "mcp presets",
444            schema_version: crate::commands::mcp::presets::MCP_PRESETS_SCHEMA_VERSION,
445            description:
446                "Canonical catalog of well-known MCP server presets (Notion, Linear, GitHub, filesystem): id, transport, command/url template, auth kind, and required placeholders.",
447            schema_json: None,
448        },
449    ]
450}
451
452/// Encode an envelope as JSON. Uses pretty form so humans tailing the
453/// terminal can still read it; agents `jq`-pipe either form.
454pub fn to_string_pretty<T: Serialize>(envelope: &JsonEnvelope<T>) -> String {
455    serde_json::to_string_pretty(envelope).expect("JsonEnvelope serializes")
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461    use serde_json::json;
462
463    #[derive(Serialize)]
464    struct Payload {
465        value: u32,
466    }
467
468    #[test]
469    fn ok_envelope_round_trips() {
470        let env = JsonEnvelope::ok(7, Payload { value: 42 });
471        let v: serde_json::Value = serde_json::to_value(&env).unwrap();
472        assert_eq!(v["schemaVersion"], 7);
473        assert_eq!(v["ok"], true);
474        assert_eq!(v["data"]["value"], 42);
475        // All envelope fields are always serialized; absent payloads
476        // surface as JSON `null` / `[]`.
477        assert!(v["error"].is_null());
478        assert_eq!(v["warnings"], json!([]));
479    }
480
481    #[test]
482    fn err_envelope_carries_details() {
483        let env: JsonEnvelope<()> = JsonEnvelope::err(2, "io", "disk full")
484            .with_details(json!({ "path": "/var/log/harn" }));
485        let v: serde_json::Value = serde_json::to_value(&env).unwrap();
486        assert_eq!(v["schemaVersion"], 2);
487        assert_eq!(v["ok"], false);
488        assert_eq!(v["error"]["code"], "io");
489        assert_eq!(v["error"]["message"], "disk full");
490        assert_eq!(v["error"]["details"]["path"], "/var/log/harn");
491        assert!(v["data"].is_null());
492    }
493
494    #[test]
495    fn warnings_serialize_when_present() {
496        let env = JsonEnvelope::ok(1, Payload { value: 1 })
497            .with_warning("deprecated.flag", "--format=json is deprecated");
498        let v: serde_json::Value = serde_json::to_value(&env).unwrap();
499        assert_eq!(v["warnings"][0]["code"], "deprecated.flag");
500        assert_eq!(v["warnings"][0]["message"], "--format=json is deprecated");
501    }
502
503    #[test]
504    fn catalog_is_nonempty_and_unique() {
505        let entries = catalog();
506        assert!(!entries.is_empty(), "catalog should ship with E2.1 seeds");
507        let mut commands: Vec<_> = entries.iter().map(|e| e.command).collect();
508        commands.sort();
509        let unique_count = {
510            let mut deduped = commands.clone();
511            deduped.dedup();
512            deduped.len()
513        };
514        assert_eq!(commands.len(), unique_count, "command names must be unique");
515    }
516
517    #[test]
518    fn catalog_includes_fix_plan() {
519        let entries = catalog();
520        let entry = entries
521            .iter()
522            .find(|entry| entry.command == "fix plan")
523            .expect("fix plan schema should be registered");
524        assert_eq!(
525            entry.schema_version,
526            crate::commands::fix::FIX_PLAN_SCHEMA_VERSION
527        );
528        let entry = entries
529            .iter()
530            .find(|entry| entry.command == "fix apply")
531            .expect("fix apply schema should be registered");
532        assert_eq!(
533            entry.schema_version,
534            crate::commands::fix::FIX_APPLY_SCHEMA_VERSION
535        );
536    }
537
538    #[test]
539    fn catalog_includes_models_lora_commands() {
540        let entries = catalog();
541        for command in [
542            "models lora plan",
543            "models lora inspect",
544            "models lora export",
545            "models lora manifest",
546            "models lora preflight",
547            "models lora promote",
548            "models lora train",
549        ] {
550            let entry = entries
551                .iter()
552                .find(|entry| entry.command == command)
553                .unwrap_or_else(|| panic!("{command} schema should be registered"));
554            assert_eq!(entry.schema_version, 1);
555        }
556    }
557
558    #[test]
559    fn catalog_includes_models_batch_commands() {
560        let entries = catalog();
561        for command in [
562            "models batch plan",
563            "models batch manifest",
564            "models batch prepare",
565            "models batch submit",
566            "models batch status",
567            "models batch cancel",
568            "models batch download",
569        ] {
570            let entry = entries
571                .iter()
572                .find(|entry| entry.command == command)
573                .unwrap_or_else(|| panic!("{command} schema should be registered"));
574            assert_eq!(entry.schema_version, 1);
575        }
576    }
577
578    #[test]
579    fn schema_versions_are_positive() {
580        for entry in catalog() {
581            assert!(
582                entry.schema_version >= 1,
583                "{} should have schemaVersion >= 1",
584                entry.command
585            );
586        }
587    }
588}