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: "portable compile|start|resume",
187            schema_version: crate::commands::portable::PORTABLE_CLI_SCHEMA_VERSION,
188            description: "Portable artifact compilation and deterministic execute/resume terminal states.",
189            schema_json: None,
190        },
191        SchemaEntry {
192            command: "parse",
193            schema_version: crate::commands::parse_tokens::PARSE_JSON_SCHEMA_VERSION,
194            description: "Tagged Harn AST tree with byte spans for parser tooling.",
195            schema_json: None,
196        },
197        SchemaEntry {
198            command: "tokens",
199            schema_version: crate::commands::parse_tokens::TOKENS_JSON_SCHEMA_VERSION,
200            description: "Lexer token stream with source lexemes and byte spans.",
201            schema_json: None,
202        },
203        SchemaEntry {
204            command: "check",
205            schema_version: crate::commands::check::CHECK_SCHEMA_VERSION,
206            description: "Per-file static check results with diagnostics and summary counts.",
207            schema_json: None,
208        },
209        SchemaEntry {
210            command: "package verify",
211            schema_version:
212                crate::commands::package_verify::PACKAGE_VERIFY_SCHEMA_VERSION,
213            description: "Complete package verification receipt with inferred package kinds and per-gate applicability, reachability, and results.",
214            schema_json: None,
215        },
216        SchemaEntry {
217            command: "skill list",
218            schema_version: crate::commands::skills::SKILLS_LIST_SCHEMA_VERSION,
219            description: "Canonical embedded or disk-backed Harn skill catalog.",
220            schema_json: None,
221        },
222        SchemaEntry {
223            command: "skill get",
224            schema_version: crate::commands::skills::SKILLS_GET_SCHEMA_VERSION,
225            description: "One canonical skill card with an optional full SKILL.md body.",
226            schema_json: None,
227        },
228        SchemaEntry {
229            command: "skill validate",
230            schema_version: crate::commands::skills::SKILLS_VALIDATE_SCHEMA_VERSION,
231            description: "Skill bundle validation result from the runtime's canonical parser.",
232            schema_json: None,
233        },
234        SchemaEntry {
235            command: "fmt",
236            schema_version: crate::commands::check::FMT_SCHEMA_VERSION,
237            description: "Per-file formatting result report for write and check modes.",
238            schema_json: None,
239        },
240        SchemaEntry {
241            command: "check provider-matrix",
242            schema_version: crate::commands::check::provider_matrix::PROVIDER_MATRIX_SCHEMA_VERSION,
243            description: "Provider/model capability matrix rows.",
244            schema_json: None,
245        },
246        SchemaEntry {
247            command: "provider catalog support",
248            schema_version: crate::commands::provider_support::PROVIDER_SUPPORT_SCHEMA_VERSION,
249            description: "Generated provider recommendation and support matrix.",
250            schema_json: None,
251        },
252        SchemaEntry {
253            command: "models batch plan",
254            schema_version: 1,
255            description:
256                "Provider Batch API candidates plus Harn live-adapter support for offline workloads.",
257            schema_json: None,
258        },
259        SchemaEntry {
260            command: "models batch manifest",
261            schema_version: 1,
262            description:
263                "Provider-neutral offline batch manifest summary and request groups.",
264            schema_json: None,
265        },
266        SchemaEntry {
267            command: "models batch prepare",
268            schema_version: 1,
269            description:
270                "Provider-native batch request files, deterministic prepare receipt, and lifecycle state.",
271            schema_json: None,
272        },
273        SchemaEntry {
274            command: "models batch submit",
275            schema_version: 1,
276            description:
277                "Batch submission receipt with provider job ids, dry-run operations, and lifecycle state.",
278            schema_json: None,
279        },
280        SchemaEntry {
281            command: "models batch status",
282            schema_version: 1,
283            description:
284                "Provider batch status receipt with cached/dry-run validation and lifecycle counts.",
285            schema_json: None,
286        },
287        SchemaEntry {
288            command: "models batch cancel",
289            schema_version: 1,
290            description:
291                "Batch cancellation receipt with redacted cancel operations, skipped-job reasons, and lifecycle counts.",
292            schema_json: None,
293        },
294        SchemaEntry {
295            command: "models batch download",
296            schema_version: 1,
297            description:
298                "Provider result-file download receipt with artifact paths, hashes, and lifecycle counts.",
299            schema_json: None,
300        },
301        SchemaEntry {
302            command: "models lora plan",
303            schema_version: 1,
304            description: "Portable LoRA/QLoRA route plan: base model, tool-call format, trainer, data, eval, and launch contract.",
305            schema_json: None,
306        },
307        SchemaEntry {
308            command: "models lora inspect",
309            schema_version: 1,
310            description:
311                "PEFT LoRA adapter compatibility report with base-model, provider, tool-call, and launch metadata.",
312            schema_json: None,
313        },
314        SchemaEntry {
315            command: "models lora export",
316            schema_version: 1,
317            description:
318                "Trainer-ready LoRA dataset export report, including contract id, manifest paths, stats, and validation results.",
319            schema_json: None,
320        },
321        SchemaEntry {
322            command: "models lora manifest",
323            schema_version: 1,
324            description:
325                "Canonical LoRA training-run manifest with route, data, artifact, serving, and promotion contracts.",
326            schema_json: None,
327        },
328        SchemaEntry {
329            command: "models lora preflight",
330            schema_version: 1,
331            description:
332                "LoRA corpus readiness report before GPU training, including sequence-fit, tool-call shape, and threshold failures.",
333            schema_json: None,
334        },
335        SchemaEntry {
336            command: "models lora promote",
337            schema_version: 1,
338            description:
339                "LoRA promotion probe matrix receipt collected from adapter-loaded behavioral probe outputs.",
340            schema_json: None,
341        },
342        SchemaEntry {
343            command: "models lora train",
344            schema_version: 1,
345            description:
346                "LoRA trainer backend receipt with route contract, dataset hashes, backend argv, and post-training manifest commands.",
347            schema_json: None,
348        },
349        SchemaEntry {
350            command: "check connector-matrix",
351            schema_version: crate::commands::check::connector_matrix::CONNECTOR_MATRIX_SCHEMA_VERSION,
352            description: "Connector package capability matrix rows.",
353            schema_json: None,
354        },
355        SchemaEntry {
356            command: "test conformance",
357            schema_version: crate::commands::test::CONFORMANCE_TEST_SCHEMA_VERSION,
358            description:
359                "Conformance results with xfail accounting, fixture snapshot key, and duration distribution.",
360            schema_json: None,
361        },
362        SchemaEntry {
363            command: "test --json-out",
364            schema_version: crate::test_report::USER_TEST_REPORT_SCHEMA_VERSION,
365            description:
366                "User-test report with typed timeout, per-case and aggregate phases, module attribution, and duration distribution.",
367            schema_json: None,
368        },
369        SchemaEntry {
370            command: "time run",
371            schema_version: crate::commands::time::TIME_RUN_SCHEMA_VERSION,
372            description:
373                "Per-phase wall-clock + cache hit/miss + per-LLM/tool-call latency for `harn run`.",
374            schema_json: None,
375        },
376        SchemaEntry {
377            command: "fix plan",
378            schema_version: crate::commands::fix::FIX_PLAN_SCHEMA_VERSION,
379            description: "Plan repair-bearing diagnostics without editing files.",
380            schema_json: None,
381        },
382        SchemaEntry {
383            command: "fix apply",
384            schema_version: crate::commands::fix::FIX_APPLY_SCHEMA_VERSION,
385            description: "Apply clean repair edits at or below a declared safety ceiling.",
386            schema_json: None,
387        },
388        SchemaEntry {
389            command: "pack",
390            schema_version: crate::commands::pack::PACK_SCHEMA_VERSION,
391            description: "Signed-ready .harnpack run-bundle build summary.",
392            schema_json: Some(crate::commands::pack::json_schema()),
393        },
394        SchemaEntry {
395            command: "pack verify",
396            schema_version: crate::commands::pack::PACK_VERIFY_SCHEMA_VERSION,
397            description:
398                "Result of verifying a .harnpack: bundle hash, signature, per-module hashes.",
399            schema_json: Some(crate::commands::pack::verify_json_schema()),
400        },
401        SchemaEntry {
402            command: "dev",
403            schema_version: 1,
404            description: "`harn dev --watch` incremental NDJSON event stream (ready / fingerprint_changed / rerun / diagnostics / tests).",
405            schema_json: None,
406        },
407        SchemaEntry {
408            command: "routes",
409            schema_version: 1,
410            description: "Static trigger route, budget, capability, and vendor-lock inventory.",
411            schema_json: None,
412        },
413        SchemaEntry {
414            command: "usage",
415            schema_version: crate::commands::usage::USAGE_SCHEMA_VERSION,
416            description:
417                "LLM spend/usage rollup from the event log: per-group calls, cost_usd, tokens, cache telemetry, and time-series cumulatives.",
418            schema_json: None,
419        },
420        SchemaEntry {
421            command: "graph",
422            schema_version: crate::commands::graph::GRAPH_SCHEMA_VERSION,
423            description:
424                "Static module graph with public symbols, imports, capabilities, effects, and host-call surface.",
425            schema_json: None,
426        },
427        SchemaEntry {
428            command: "lint",
429            schema_version: crate::commands::check::LINT_SCHEMA_VERSION,
430            description:
431                "Per-file lint diagnostics with severity, fixable/fixed counts, and summary.",
432            schema_json: Some(crate::commands::check::lint_json_schema()),
433        },
434        SchemaEntry {
435            command: "replay",
436            schema_version: crate::commands::replay::REPLAY_SCHEMA_VERSION,
437            description:
438                "Replay summary: per-stage status/outcome/branch, embedded fixture verdicts, and multi-run determinism.",
439            schema_json: None,
440        },
441        SchemaEntry {
442            command: "version",
443            schema_version: crate::VERSION_SCHEMA_VERSION,
444            description: "CLI build metadata: name, version, description.",
445            schema_json: None,
446        },
447        SchemaEntry {
448            command: "upgrade",
449            schema_version: crate::commands::upgrade::UPGRADE_SCHEMA_VERSION,
450            description:
451                "Self-update probe (`--check`) or install summary: current, target, archive URL, install outcome.",
452            schema_json: None,
453        },
454        SchemaEntry {
455            command: "explain --catalog",
456            schema_version: crate::commands::diagnostics_catalog::SCHEMA_VERSION,
457            description:
458                "Diagnostic-code catalog: per-code summary, repair, safety, related codes.",
459            schema_json: None,
460        },
461        SchemaEntry {
462            command: "mcp presets",
463            schema_version: crate::commands::mcp::presets::MCP_PRESETS_SCHEMA_VERSION,
464            description:
465                "Canonical catalog of well-known MCP server presets (Notion, Linear, GitHub, filesystem): id, transport, command/url template, auth kind, and required placeholders.",
466            schema_json: None,
467        },
468    ]
469}
470
471/// Encode an envelope as JSON. Uses pretty form so humans tailing the
472/// terminal can still read it; agents `jq`-pipe either form.
473pub fn to_string_pretty<T: Serialize>(envelope: &JsonEnvelope<T>) -> String {
474    serde_json::to_string_pretty(envelope).expect("JsonEnvelope serializes")
475}
476
477#[cfg(test)]
478mod tests {
479    use super::*;
480    use serde_json::json;
481
482    #[derive(Serialize)]
483    struct Payload {
484        value: u32,
485    }
486
487    #[test]
488    fn ok_envelope_round_trips() {
489        let env = JsonEnvelope::ok(7, Payload { value: 42 });
490        let v: serde_json::Value = serde_json::to_value(&env).unwrap();
491        assert_eq!(v["schemaVersion"], 7);
492        assert_eq!(v["ok"], true);
493        assert_eq!(v["data"]["value"], 42);
494        // All envelope fields are always serialized; absent payloads
495        // surface as JSON `null` / `[]`.
496        assert!(v["error"].is_null());
497        assert_eq!(v["warnings"], json!([]));
498    }
499
500    #[test]
501    fn err_envelope_carries_details() {
502        let env: JsonEnvelope<()> = JsonEnvelope::err(2, "io", "disk full")
503            .with_details(json!({ "path": "/var/log/harn" }));
504        let v: serde_json::Value = serde_json::to_value(&env).unwrap();
505        assert_eq!(v["schemaVersion"], 2);
506        assert_eq!(v["ok"], false);
507        assert_eq!(v["error"]["code"], "io");
508        assert_eq!(v["error"]["message"], "disk full");
509        assert_eq!(v["error"]["details"]["path"], "/var/log/harn");
510        assert!(v["data"].is_null());
511    }
512
513    #[test]
514    fn warnings_serialize_when_present() {
515        let env = JsonEnvelope::ok(1, Payload { value: 1 })
516            .with_warning("deprecated.flag", "--format=json is deprecated");
517        let v: serde_json::Value = serde_json::to_value(&env).unwrap();
518        assert_eq!(v["warnings"][0]["code"], "deprecated.flag");
519        assert_eq!(v["warnings"][0]["message"], "--format=json is deprecated");
520    }
521
522    #[test]
523    fn catalog_is_nonempty_and_unique() {
524        let entries = catalog();
525        assert!(!entries.is_empty(), "catalog should ship with E2.1 seeds");
526        let mut commands: Vec<_> = entries.iter().map(|e| e.command).collect();
527        commands.sort();
528        let unique_count = {
529            let mut deduped = commands.clone();
530            deduped.dedup();
531            deduped.len()
532        };
533        assert_eq!(commands.len(), unique_count, "command names must be unique");
534    }
535
536    #[test]
537    fn catalog_includes_fix_plan() {
538        let entries = catalog();
539        let entry = entries
540            .iter()
541            .find(|entry| entry.command == "fix plan")
542            .expect("fix plan schema should be registered");
543        assert_eq!(
544            entry.schema_version,
545            crate::commands::fix::FIX_PLAN_SCHEMA_VERSION
546        );
547        let entry = entries
548            .iter()
549            .find(|entry| entry.command == "fix apply")
550            .expect("fix apply schema should be registered");
551        assert_eq!(
552            entry.schema_version,
553            crate::commands::fix::FIX_APPLY_SCHEMA_VERSION
554        );
555    }
556
557    #[test]
558    fn catalog_includes_models_lora_commands() {
559        let entries = catalog();
560        for command in [
561            "models lora plan",
562            "models lora inspect",
563            "models lora export",
564            "models lora manifest",
565            "models lora preflight",
566            "models lora promote",
567            "models lora train",
568        ] {
569            let entry = entries
570                .iter()
571                .find(|entry| entry.command == command)
572                .unwrap_or_else(|| panic!("{command} schema should be registered"));
573            assert_eq!(entry.schema_version, 1);
574        }
575    }
576
577    #[test]
578    fn catalog_includes_models_batch_commands() {
579        let entries = catalog();
580        for command in [
581            "models batch plan",
582            "models batch manifest",
583            "models batch prepare",
584            "models batch submit",
585            "models batch status",
586            "models batch cancel",
587            "models batch download",
588        ] {
589            let entry = entries
590                .iter()
591                .find(|entry| entry.command == command)
592                .unwrap_or_else(|| panic!("{command} schema should be registered"));
593            assert_eq!(entry.schema_version, 1);
594        }
595    }
596
597    #[test]
598    fn schema_versions_are_positive() {
599        for entry in catalog() {
600            assert!(
601                entry.schema_version >= 1,
602                "{} should have schemaVersion >= 1",
603                entry.command
604            );
605        }
606    }
607
608    #[test]
609    fn catalog_lint_publishes_schema_json() {
610        let entry = catalog()
611            .into_iter()
612            .find(|entry| entry.command == "lint")
613            .expect("lint schema should be registered");
614        assert_eq!(
615            entry.schema_version,
616            crate::commands::check::LINT_SCHEMA_VERSION
617        );
618        let schema = entry.schema_json.expect("lint schemaJson must be present");
619        assert_eq!(schema["title"], "harn lint --json");
620        assert_eq!(schema["properties"]["schemaVersion"]["const"], 1);
621        jsonschema::draft202012::meta::validate(&schema).expect("lint schema meta-valid");
622    }
623}