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