harn-cli 0.8.29

CLI for the Harn programming language — run, test, REPL, format, and lint
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Canonical JSON envelope for `harn` CLI commands.
//!
//! Every `--json` mode returns a [`JsonEnvelope<T>`] — a versioned
//! wrapper that exposes `schemaVersion`, `ok`, and either `data` or
//! `error`. Soft signals attach as `warnings` so `ok: true` stays
//! stable as long as the command succeeds.
//!
//! Schema versions are per-command and monotonically increasing.
//! [`catalog`] returns the registry consumed by `harn --json-schemas`.
//! New commands extend the catalog (and bump their own
//! [`JsonOutput::SCHEMA_VERSION`]) when their JSON shape changes in a
//! way agents need to detect.
//!
//! See epic #1753 (`--json` everywhere) for the broader contract.

use serde::{Deserialize, Serialize};

/// Schema version of the `harn --json-schemas` catalog itself. Bump
/// when the shape of [`SchemaEntry`] or the catalog envelope changes.
pub const CATALOG_SCHEMA_VERSION: u32 = 1;

/// Versioned wrapper for every `--json` CLI output. All five fields
/// are always serialized so consumers can rely on a flat shape:
/// missing payloads surface as `null` and the empty `warnings` array
/// is `[]` rather than absent.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonEnvelope<T: Serialize> {
    #[serde(rename = "schemaVersion")]
    pub schema_version: u32,
    pub ok: bool,
    pub data: Option<T>,
    pub error: Option<JsonError>,
    #[serde(default)]
    pub warnings: Vec<JsonWarning>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonError {
    pub code: String,
    pub message: String,
    /// Free-form structured context. `null` when the error has no
    /// structured payload — the field is always present so consumers
    /// can read `error.details` without an existence check.
    #[serde(default)]
    pub details: serde_json::Value,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonWarning {
    pub code: String,
    pub message: String,
}

/// Implemented by every CLI command that exposes a `--json` mode. The
/// associated `SCHEMA_VERSION` is also surfaced in [`catalog`] so
/// agents can negotiate per-command compatibility without parsing
/// every payload.
pub trait JsonOutput {
    const SCHEMA_VERSION: u32;
    type Data: Serialize;
    fn into_envelope(self) -> JsonEnvelope<Self::Data>;
}

impl<T: Serialize> JsonEnvelope<T> {
    pub fn ok(schema_version: u32, data: T) -> Self {
        Self {
            schema_version,
            ok: true,
            data: Some(data),
            error: None,
            warnings: Vec::new(),
        }
    }

    pub fn err(
        schema_version: u32,
        code: impl Into<String>,
        message: impl Into<String>,
    ) -> JsonEnvelope<T> {
        Self {
            schema_version,
            ok: false,
            data: None,
            error: Some(JsonError {
                code: code.into(),
                message: message.into(),
                details: serde_json::Value::Null,
            }),
            warnings: Vec::new(),
        }
    }

    pub fn with_details(mut self, details: serde_json::Value) -> Self {
        if let Some(err) = self.error.as_mut() {
            err.details = details;
        }
        self
    }

    pub fn with_warning(mut self, code: impl Into<String>, message: impl Into<String>) -> Self {
        self.warnings.push(JsonWarning {
            code: code.into(),
            message: message.into(),
        });
        self
    }
}

/// One row of the `harn --json-schemas` catalog. `schema_json` is
/// inline when small; richer schemas live behind a future
/// `schema_url` field documented per-command.
#[derive(Debug, Clone, Serialize)]
pub struct SchemaEntry {
    pub command: &'static str,
    #[serde(rename = "schemaVersion")]
    pub schema_version: u32,
    pub description: &'static str,
    #[serde(skip_serializing_if = "Option::is_none", rename = "schemaJson")]
    pub schema_json: Option<serde_json::Value>,
}

/// Static catalog of commands that already emit a stable JSON shape.
///
/// E2.1 seeds the commands that ship a `schema_version` today (doctor,
/// session export, the provider catalog). New commands register here as
/// they migrate to [`JsonEnvelope`] — for example, the `skills` family
/// added in E3.2.
pub fn catalog() -> Vec<SchemaEntry> {
    vec![
        SchemaEntry {
            command: "doctor",
            schema_version: crate::commands::doctor::DOCTOR_SCHEMA_VERSION,
            description: "Capability matrix: host, per-target buildability, per-provider reachability, per-stdlib-effect availability.",
            schema_json: None,
        },
        SchemaEntry {
            command: "session export",
            schema_version: 1,
            description: "Portable Harn session bundle export.",
            schema_json: None,
        },
        SchemaEntry {
            command: "provider-catalog",
            schema_version: 1,
            description: "Resolved provider/model catalog snapshot.",
            schema_json: None,
        },
        SchemaEntry {
            command: "connect status",
            schema_version: 1,
            description: "Outbound-connector readiness report.",
            schema_json: None,
        },
        SchemaEntry {
            command: "connect setup-plan",
            schema_version: 1,
            description: "Step-by-step plan to bring a connector online.",
            schema_json: None,
        },
        SchemaEntry {
            command: "run",
            schema_version: crate::commands::run::json_events::RUN_JSON_SCHEMA_VERSION,
            description: "Pipeline-run NDJSON event stream (stdout, stderr, transcript, tool, hook, persona, result, error).",
            schema_json: None,
        },
        SchemaEntry {
            command: "parse",
            schema_version: crate::commands::parse_tokens::PARSE_JSON_SCHEMA_VERSION,
            description: "Tagged Harn AST tree with byte spans for parser tooling.",
            schema_json: None,
        },
        SchemaEntry {
            command: "tokens",
            schema_version: crate::commands::parse_tokens::TOKENS_JSON_SCHEMA_VERSION,
            description: "Lexer token stream with source lexemes and byte spans.",
            schema_json: None,
        },
        SchemaEntry {
            command: "check",
            schema_version: crate::commands::check::CHECK_SCHEMA_VERSION,
            description: "Per-file static check results with diagnostics and summary counts.",
            schema_json: None,
        },
        SchemaEntry {
            command: "fmt",
            schema_version: crate::commands::check::FMT_SCHEMA_VERSION,
            description: "Per-file formatting result report for write and check modes.",
            schema_json: None,
        },
        SchemaEntry {
            command: "check provider-matrix",
            schema_version: crate::commands::check::provider_matrix::PROVIDER_MATRIX_SCHEMA_VERSION,
            description: "Provider/model capability matrix rows.",
            schema_json: None,
        },
        SchemaEntry {
            command: "check connector-matrix",
            schema_version: crate::commands::check::connector_matrix::CONNECTOR_MATRIX_SCHEMA_VERSION,
            description: "Connector package capability matrix rows.",
            schema_json: None,
        },
        SchemaEntry {
            command: "test conformance",
            schema_version: crate::commands::test::CONFORMANCE_TEST_SCHEMA_VERSION,
            description:
                "Conformance test results with xfail accounting and a stable fixture snapshot key.",
            schema_json: None,
        },
        SchemaEntry {
            command: "time run",
            schema_version: crate::commands::time::TIME_RUN_SCHEMA_VERSION,
            description:
                "Per-phase wall-clock + cache hit/miss + per-LLM/tool-call latency for `harn run`.",
            schema_json: None,
        },
        SchemaEntry {
            command: "fix plan",
            schema_version: crate::commands::fix::FIX_PLAN_SCHEMA_VERSION,
            description: "Plan repair-bearing diagnostics without editing files.",
            schema_json: None,
        },
        SchemaEntry {
            command: "fix apply",
            schema_version: crate::commands::fix::FIX_APPLY_SCHEMA_VERSION,
            description: "Apply clean repair edits at or below a declared safety ceiling.",
            schema_json: None,
        },
        SchemaEntry {
            command: "skills list",
            schema_version: 1,
            description: "Canonical Harn skill corpus, frontmatter only.",
            schema_json: None,
        },
        SchemaEntry {
            command: "skills get",
            schema_version: 1,
            description: "One canonical skill's frontmatter (and body with --full).",
            schema_json: None,
        },
        SchemaEntry {
            command: "pack",
            schema_version: crate::commands::pack::PACK_SCHEMA_VERSION,
            description: "Signed-ready .harnpack run-bundle build summary.",
            schema_json: Some(crate::commands::pack::json_schema()),
        },
        SchemaEntry {
            command: "pack verify",
            schema_version: crate::commands::pack::PACK_VERIFY_SCHEMA_VERSION,
            description:
                "Result of verifying a .harnpack: bundle hash, signature, per-module hashes.",
            schema_json: Some(crate::commands::pack::verify_json_schema()),
        },
        SchemaEntry {
            command: "dev",
            schema_version: 1,
            description: "`harn dev --watch` incremental NDJSON event stream (ready / fingerprint_changed / rerun / diagnostics / tests).",
            schema_json: None,
        },
        SchemaEntry {
            command: "routes",
            schema_version: 1,
            description: "Static trigger route, budget, capability, and vendor-lock inventory.",
            schema_json: None,
        },
        SchemaEntry {
            command: "graph",
            schema_version: crate::commands::graph::GRAPH_SCHEMA_VERSION,
            description:
                "Static module graph with public symbols, imports, capabilities, effects, and host-call surface.",
            schema_json: None,
        },
        SchemaEntry {
            command: "lint",
            schema_version: crate::commands::check::LINT_SCHEMA_VERSION,
            description:
                "Per-file lint diagnostics with severity, fixable/fixed counts, and summary.",
            schema_json: None,
        },
        SchemaEntry {
            command: "replay",
            schema_version: crate::commands::replay::REPLAY_SCHEMA_VERSION,
            description:
                "Replay summary: per-stage status/outcome/branch plus the embedded replay-fixture verdict.",
            schema_json: None,
        },
        SchemaEntry {
            command: "version",
            schema_version: crate::VERSION_SCHEMA_VERSION,
            description: "CLI build metadata: name, version, description.",
            schema_json: None,
        },
        SchemaEntry {
            command: "upgrade",
            schema_version: crate::commands::upgrade::UPGRADE_SCHEMA_VERSION,
            description:
                "Self-update probe (`--check`) or install summary: current, target, archive URL, install outcome.",
            schema_json: None,
        },
        SchemaEntry {
            command: "explain --catalog",
            schema_version: crate::commands::diagnostics_catalog::SCHEMA_VERSION,
            description:
                "Diagnostic-code catalog: per-code summary, repair, safety, related codes.",
            schema_json: None,
        },
    ]
}

/// Encode an envelope as JSON. Uses pretty form so humans tailing the
/// terminal can still read it; agents `jq`-pipe either form.
pub fn to_string_pretty<T: Serialize>(envelope: &JsonEnvelope<T>) -> String {
    serde_json::to_string_pretty(envelope).expect("JsonEnvelope serializes")
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[derive(Serialize)]
    struct Payload {
        value: u32,
    }

    #[test]
    fn ok_envelope_round_trips() {
        let env = JsonEnvelope::ok(7, Payload { value: 42 });
        let v: serde_json::Value = serde_json::to_value(&env).unwrap();
        assert_eq!(v["schemaVersion"], 7);
        assert_eq!(v["ok"], true);
        assert_eq!(v["data"]["value"], 42);
        // All envelope fields are always serialized; absent payloads
        // surface as JSON `null` / `[]`.
        assert!(v["error"].is_null());
        assert_eq!(v["warnings"], json!([]));
    }

    #[test]
    fn err_envelope_carries_details() {
        let env: JsonEnvelope<()> = JsonEnvelope::err(2, "io", "disk full")
            .with_details(json!({ "path": "/var/log/harn" }));
        let v: serde_json::Value = serde_json::to_value(&env).unwrap();
        assert_eq!(v["schemaVersion"], 2);
        assert_eq!(v["ok"], false);
        assert_eq!(v["error"]["code"], "io");
        assert_eq!(v["error"]["message"], "disk full");
        assert_eq!(v["error"]["details"]["path"], "/var/log/harn");
        assert!(v["data"].is_null());
    }

    #[test]
    fn warnings_serialize_when_present() {
        let env = JsonEnvelope::ok(1, Payload { value: 1 })
            .with_warning("deprecated.flag", "--format=json is deprecated");
        let v: serde_json::Value = serde_json::to_value(&env).unwrap();
        assert_eq!(v["warnings"][0]["code"], "deprecated.flag");
        assert_eq!(v["warnings"][0]["message"], "--format=json is deprecated");
    }

    #[test]
    fn catalog_is_nonempty_and_unique() {
        let entries = catalog();
        assert!(!entries.is_empty(), "catalog should ship with E2.1 seeds");
        let mut commands: Vec<_> = entries.iter().map(|e| e.command).collect();
        commands.sort();
        let unique_count = {
            let mut deduped = commands.clone();
            deduped.dedup();
            deduped.len()
        };
        assert_eq!(commands.len(), unique_count, "command names must be unique");
    }

    #[test]
    fn catalog_includes_fix_plan() {
        let entries = catalog();
        let entry = entries
            .iter()
            .find(|entry| entry.command == "fix plan")
            .expect("fix plan schema should be registered");
        assert_eq!(
            entry.schema_version,
            crate::commands::fix::FIX_PLAN_SCHEMA_VERSION
        );
        let entry = entries
            .iter()
            .find(|entry| entry.command == "fix apply")
            .expect("fix apply schema should be registered");
        assert_eq!(
            entry.schema_version,
            crate::commands::fix::FIX_APPLY_SCHEMA_VERSION
        );
    }

    #[test]
    fn schema_versions_are_positive() {
        for entry in catalog() {
            assert!(
                entry.schema_version >= 1,
                "{} should have schemaVersion >= 1",
                entry.command
            );
        }
    }
}