1use serde::{Deserialize, Serialize};
17
18pub const CATALOG_SCHEMA_VERSION: u32 = 1;
21
22#[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 #[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
54pub 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#[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
122pub 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
471pub 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 fn catalog_command_paths(command: &str) -> (Vec<Vec<String>>, Vec<String>) {
493 let tokens: Vec<&str> = command.split_whitespace().collect();
494 let split = tokens
495 .iter()
496 .position(|token| token.starts_with('-'))
497 .unwrap_or(tokens.len());
498 let (subcommands, flags) = tokens.split_at(split);
499 let flags = flags.iter().map(|f| f.to_string()).collect();
500 let Some((leaves, prefix)) = subcommands.split_last() else {
501 return (Vec::new(), flags);
502 };
503 let paths = leaves
504 .split('|')
505 .map(|leaf| {
506 let mut path: Vec<String> = prefix.iter().map(|s| (*s).to_string()).collect();
507 path.push(leaf.to_string());
508 path
509 })
510 .collect();
511 (paths, flags)
512 }
513
514 fn resolve_command<'a>(root: &'a clap::Command, path: &[String]) -> Option<&'a clap::Command> {
515 let mut current = root;
516 for segment in path {
517 current = current.get_subcommands().find(|sub| {
518 sub.get_name() == segment || sub.get_all_aliases().any(|alias| alias == segment)
519 })?;
520 }
521 Some(current)
522 }
523
524 #[test]
532 fn catalog_commands_exist_in_the_cli() {
533 use clap::CommandFactory;
534 let root = crate::cli::Cli::command();
535 const POSITIONAL_VALUE_ROWS: &[&str] = &["test conformance"];
544
545 let mut drift = Vec::new();
546 for entry in catalog() {
547 if POSITIONAL_VALUE_ROWS.contains(&entry.command) {
548 continue;
549 }
550 let (paths, flags) = catalog_command_paths(entry.command);
551 for path in paths {
552 let Some(command) = resolve_command(&root, &path) else {
553 drift.push(format!(
554 "`{}` names no such command (row: `{}`)",
555 path.join(" "),
556 entry.command
557 ));
558 continue;
559 };
560 for flag in &flags {
561 let long = flag.trim_start_matches('-');
562 if !command
563 .get_arguments()
564 .any(|arg| arg.get_long() == Some(long))
565 {
566 drift.push(format!(
567 "`{}` takes no `{flag}` (row: `{}`)",
568 path.join(" "),
569 entry.command
570 ));
571 }
572 }
573 }
574 }
575 assert!(
576 drift.is_empty(),
577 "`--json-schemas` advertises {} command(s) the CLI does not expose:\n {}",
578 drift.len(),
579 drift.join("\n ")
580 );
581 }
582
583 #[test]
584 fn ok_envelope_round_trips() {
585 let env = JsonEnvelope::ok(7, Payload { value: 42 });
586 let v: serde_json::Value = serde_json::to_value(&env).unwrap();
587 assert_eq!(v["schemaVersion"], 7);
588 assert_eq!(v["ok"], true);
589 assert_eq!(v["data"]["value"], 42);
590 assert!(v["error"].is_null());
593 assert_eq!(v["warnings"], json!([]));
594 }
595
596 #[test]
597 fn err_envelope_carries_details() {
598 let env: JsonEnvelope<()> = JsonEnvelope::err(2, "io", "disk full")
599 .with_details(json!({ "path": "/var/log/harn" }));
600 let v: serde_json::Value = serde_json::to_value(&env).unwrap();
601 assert_eq!(v["schemaVersion"], 2);
602 assert_eq!(v["ok"], false);
603 assert_eq!(v["error"]["code"], "io");
604 assert_eq!(v["error"]["message"], "disk full");
605 assert_eq!(v["error"]["details"]["path"], "/var/log/harn");
606 assert!(v["data"].is_null());
607 }
608
609 #[test]
610 fn warnings_serialize_when_present() {
611 let env = JsonEnvelope::ok(1, Payload { value: 1 })
612 .with_warning("deprecated.flag", "--format=json is deprecated");
613 let v: serde_json::Value = serde_json::to_value(&env).unwrap();
614 assert_eq!(v["warnings"][0]["code"], "deprecated.flag");
615 assert_eq!(v["warnings"][0]["message"], "--format=json is deprecated");
616 }
617
618 #[test]
619 fn catalog_is_nonempty_and_unique() {
620 let entries = catalog();
621 assert!(!entries.is_empty(), "catalog should ship with E2.1 seeds");
622 let mut commands: Vec<_> = entries.iter().map(|e| e.command).collect();
623 commands.sort();
624 let unique_count = {
625 let mut deduped = commands.clone();
626 deduped.dedup();
627 deduped.len()
628 };
629 assert_eq!(commands.len(), unique_count, "command names must be unique");
630 }
631
632 #[test]
633 fn catalog_includes_fix_plan() {
634 let entries = catalog();
635 let entry = entries
636 .iter()
637 .find(|entry| entry.command == "fix --plan")
638 .expect("fix --plan schema should be registered");
639 assert_eq!(
640 entry.schema_version,
641 crate::commands::fix::FIX_PLAN_SCHEMA_VERSION
642 );
643 let entry = entries
644 .iter()
645 .find(|entry| entry.command == "fix --apply")
646 .expect("fix apply schema should be registered");
647 assert_eq!(
648 entry.schema_version,
649 crate::commands::fix::FIX_APPLY_SCHEMA_VERSION
650 );
651 }
652
653 #[test]
654 fn catalog_includes_models_lora_commands() {
655 let entries = catalog();
656 for command in [
657 "models lora plan",
658 "models lora inspect",
659 "models lora export",
660 "models lora manifest",
661 "models lora preflight",
662 "models lora promote",
663 "models lora train",
664 ] {
665 let entry = entries
666 .iter()
667 .find(|entry| entry.command == command)
668 .unwrap_or_else(|| panic!("{command} schema should be registered"));
669 assert_eq!(entry.schema_version, 1);
670 }
671 }
672
673 #[test]
674 fn catalog_includes_models_batch_commands() {
675 let entries = catalog();
676 for command in [
677 "models batch plan",
678 "models batch manifest",
679 "models batch prepare",
680 "models batch submit",
681 "models batch status",
682 "models batch cancel",
683 "models batch download",
684 ] {
685 let entry = entries
686 .iter()
687 .find(|entry| entry.command == command)
688 .unwrap_or_else(|| panic!("{command} schema should be registered"));
689 assert_eq!(entry.schema_version, 1);
690 }
691 }
692
693 #[test]
694 fn schema_versions_are_positive() {
695 for entry in catalog() {
696 assert!(
697 entry.schema_version >= 1,
698 "{} should have schemaVersion >= 1",
699 entry.command
700 );
701 }
702 }
703
704 #[test]
705 fn catalog_lint_publishes_schema_json() {
706 let entry = catalog()
707 .into_iter()
708 .find(|entry| entry.command == "lint")
709 .expect("lint schema should be registered");
710 assert_eq!(
711 entry.schema_version,
712 crate::commands::check::LINT_SCHEMA_VERSION
713 );
714 let schema = entry.schema_json.expect("lint schemaJson must be present");
715 assert_eq!(schema["title"], "harn lint --json");
716 assert_eq!(schema["properties"]["schemaVersion"]["const"], 1);
717 jsonschema::draft202012::meta::validate(&schema).expect("lint schema meta-valid");
718 }
719}