heddle-cli 0.15.0

An AI-native version control system
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
// SPDX-License-Identifier: Apache-2.0
//! `--output json-compact` projects the decision surface only.
//!
//! heddle#470: `--output json` is the full machine contract — great for
//! machines, but extremely noisy for an agent driving Heddle, where the
//! actionable surface is just `output_kind`, `status`/`coordination_status`,
//! `blockers`, `next_action`, `changed_paths`/`changed_path_count`, and
//! `conflicts`/`conflict_count`. `--output json-compact` emits ONLY those
//! fields; the full `--output json` contract is unchanged.

use std::str;

use serde_json::Value;
use tempfile::TempDir;

use super::{heddle, heddle_output};

/// Every key the compact decision surface is allowed to emit. Any key
/// outside this set leaking into a compact payload is a regression —
/// the whole point of the mode is that the surface stays small as the
/// full envelope grows.
const COMPACT_ALLOWED_KEYS: &[&str] = &[
    "output_kind",
    "status",
    "coordination_status",
    "blockers",
    "next_action",
    "next_action_template",
    "changed_paths",
    "changed_path_count",
    "conflicts",
    "conflict_count",
    "state_id",
];

fn assert_only_compact_keys(value: &Value, context: &str) {
    let obj = value
        .as_object()
        .unwrap_or_else(|| panic!("{context}: compact payload must be a JSON object: {value}"));
    for key in obj.keys() {
        assert!(
            COMPACT_ALLOWED_KEYS.contains(&key.as_str()),
            "{context}: compact payload leaked non-decision-surface key `{key}`: {value}"
        );
    }
}

fn compact_json(args: &[&str], temp: &TempDir) -> Value {
    let mut argv: Vec<&str> = vec!["--output", "json-compact"];
    argv.extend(args.iter().copied());
    let out =
        heddle_output(&argv, Some(temp.path())).unwrap_or_else(|err| panic!("spawn failed: {err}"));
    assert!(
        out.status.success(),
        "heddle {argv:?} should succeed; stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = str::from_utf8(&out.stdout).expect("stdout utf8");
    let line = stdout.lines().next().unwrap_or_else(|| {
        panic!(
            "heddle {argv:?} produced no stdout; stderr={}",
            String::from_utf8_lossy(&out.stderr)
        )
    });
    serde_json::from_str(line)
        .unwrap_or_else(|err| panic!("heddle {argv:?} stdout not JSON: {err}\n  line: {line}"))
}

fn compact_json_output(args: &[&str], temp: &TempDir) -> Value {
    let out =
        heddle_output(args, Some(temp.path())).unwrap_or_else(|err| panic!("spawn failed: {err}"));
    assert!(
        out.status.success(),
        "heddle {args:?} should succeed; stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = str::from_utf8(&out.stdout).expect("stdout utf8");
    let line = stdout
        .lines()
        .next()
        .unwrap_or_else(|| panic!("heddle {args:?} produced no stdout"));
    serde_json::from_str(line)
        .unwrap_or_else(|err| panic!("heddle {args:?} stdout not JSON: {err}\n  line: {line}"))
}

fn assert_compact_op_id_error_envelope(args: &[&str], temp: &TempDir, context: &str) -> Value {
    let out =
        heddle_output(args, Some(temp.path())).unwrap_or_else(|err| panic!("spawn failed: {err}"));
    assert!(
        !out.status.success(),
        "{context}: heddle {args:?} should fail; stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        out.stdout.is_empty(),
        "{context}: failed compact op-id command should not emit stdout: {}",
        String::from_utf8_lossy(&out.stdout)
    );
    let stderr = str::from_utf8(&out.stderr).expect("stderr utf8");
    let envelope: Value = serde_json::from_str(stderr.trim())
        .unwrap_or_else(|err| panic!("{context}: stderr not JSON: {err}\n  stderr: {stderr}"));
    // `kind` (not the dropped `code` duplicate) is the envelope's
    // discriminator (HeddleCo/heddle#647).
    for key in ["kind", "error", "exit_code", "hint"] {
        assert!(
            envelope.get(key).is_some(),
            "{context}: compact op-id failure stripped `{key}` from error envelope: {envelope}"
        );
    }
    envelope
}

fn full_json(args: &[&str], temp: &TempDir) -> Value {
    let mut argv: Vec<&str> = vec!["--output", "json"];
    argv.extend(args.iter().copied());
    let stdout = heddle(&argv, Some(temp.path()))
        .unwrap_or_else(|err| panic!("heddle {argv:?} failed: {err}"));
    let line = stdout.lines().next().expect("full json stdout");
    serde_json::from_str(line).expect("full json parses")
}

#[test]
fn capture_op_id_compact_failure_preserves_error_envelope() {
    let temp = TempDir::new().unwrap();
    heddle(&["init"], Some(temp.path())).expect("init");
    let op_id = "550e8400-e29b-41d4-a716-446655440471";
    let args = ["--output", "json-compact", "--op-id", op_id, "capture"];

    let first = assert_compact_op_id_error_envelope(&args, &temp, "capture op-id failure");
    let replayed =
        assert_compact_op_id_error_envelope(&args, &temp, "capture op-id failure replay");
    assert_eq!(
        replayed, first,
        "compact op-id replay should preserve the cached error envelope verbatim"
    );
}

#[test]
fn status_compact_emits_only_decision_surface() {
    let temp = TempDir::new().unwrap();
    heddle(&["init"], Some(temp.path())).expect("init");

    let compact = compact_json(&["status"], &temp);
    assert_eq!(
        compact["output_kind"].as_str(),
        Some("status"),
        "compact status must carry output_kind: {compact}"
    );
    assert!(
        compact.get("coordination_status").is_some(),
        "compact status must carry coordination_status: {compact}"
    );
    assert!(
        compact.get("changed_path_count").is_some(),
        "compact status must carry changed_path_count: {compact}"
    );
    assert!(
        compact.get("changed_paths").is_some(),
        "compact status must carry changed_paths: {compact}"
    );
    assert_only_compact_keys(&compact, "status");

    // Contrast: the full contract still carries verification metadata the
    // compact projection drops.
    let full = full_json(&["status"], &temp);
    assert!(
        full.get("git_overlay_health").is_none() && full.get("verification").is_some(),
        "full status must expose verification without the legacy git_overlay_health alias: {full}"
    );
    assert!(
        compact.get("git_overlay_health").is_none() && compact.get("verification").is_none(),
        "compact status must drop git_overlay_health/verification: {compact}"
    );
}

#[test]
fn status_compact_keeps_uncaptured_changed_path_count_consistent() {
    let temp = TempDir::new().unwrap();
    heddle(&["init"], Some(temp.path())).expect("init");
    std::fs::write(temp.path().join("work.txt"), "pending\n").unwrap();

    let compact = compact_json(&["status"], &temp);
    let changed_paths = compact["changed_paths"]
        .as_array()
        .unwrap_or_else(|| panic!("compact status must carry changed_paths: {compact}"));
    assert_eq!(
        compact["changed_path_count"].as_u64(),
        Some(changed_paths.len() as u64),
        "compact status count must match changed_paths in a dirty uncaptured repo: {compact}"
    );
    assert_eq!(
        changed_paths.as_slice(),
        [Value::String("work.txt".to_string())],
        "dirty uncaptured repo should report the pending worktree path: {compact}"
    );
    assert_only_compact_keys(&compact, "dirty uncaptured status");
}

#[test]
fn capture_op_id_compact_replay_emits_only_decision_surface() {
    let temp = TempDir::new().unwrap();
    heddle(&["init"], Some(temp.path())).expect("init");
    std::fs::write(temp.path().join("work.txt"), "pending\n").unwrap();
    let op_id = "550e8400-e29b-41d4-a716-446655440470";
    let args = [
        "--output",
        "json-compact",
        "--op-id",
        op_id,
        "capture",
        "-m",
        "compact op-id capture",
    ];

    let first = compact_json_output(&args, &temp);
    assert_only_compact_keys(&first, "capture op-id executed");
    assert!(
        first.get("operation_record").is_none()
            && first.get("op_id").is_none()
            && first.get("idempotency_status").is_none()
            && first.get("replayed").is_none(),
        "compact executed op-id output must not leak idempotency fields: {first}"
    );

    let replayed = compact_json_output(&args, &temp);
    assert_only_compact_keys(&replayed, "capture op-id replayed");
    assert_eq!(
        replayed, first,
        "compact op-id replay should return the cached compact payload without wrapper decoration"
    );
    assert!(
        replayed.get("operation_record").is_none()
            && replayed.get("op_id").is_none()
            && replayed.get("idempotency_status").is_none()
            && replayed.get("replayed").is_none(),
        "compact replayed op-id output must not leak idempotency fields: {replayed}"
    );
}

#[test]
fn continue_compact_drops_operator_metadata() {
    let temp = TempDir::new().unwrap();
    heddle(&["init"], Some(temp.path())).expect("init");

    let compact = compact_json(&["continue"], &temp);
    assert_eq!(compact["output_kind"].as_str(), Some("continue"));
    assert_eq!(compact["status"].as_str(), Some("noop"));
    assert_only_compact_keys(&compact, "continue");

    // The full operator envelope carries `message`, `action`, and
    // `recommended_action`; compact keeps only `next_action`.
    let full = full_json(&["continue"], &temp);
    assert!(full.get("message").is_some() && full.get("action").is_some());
    assert!(
        compact.get("message").is_none()
            && compact.get("action").is_none()
            && compact.get("recommended_action").is_none(),
        "compact continue must drop message/action/recommended_action: {compact}"
    );
}

#[test]
fn json_compact_is_a_valid_output_value() {
    let temp = TempDir::new().unwrap();
    heddle(&["init"], Some(temp.path())).expect("init");
    let out =
        heddle_output(&["--output", "json-compact", "status"], Some(temp.path())).expect("spawn");
    assert!(
        out.status.success(),
        "--output json-compact must parse and run: stderr={}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn json_compact_rejects_commands_without_projection() {
    let temp = TempDir::new().unwrap();
    heddle(&["init"], Some(temp.path())).expect("init");

    let out =
        heddle_output(&["--output", "json-compact", "help"], Some(temp.path())).expect("spawn");
    assert!(
        !out.status.success(),
        "compact-less command must reject json-compact"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("json-compact is not supported"),
        "rejection should explain unsupported compact mode: {stderr}"
    );
}

fn compact_error_envelope(args: &[&str], cwd: Option<&std::path::Path>) -> Value {
    let out = heddle_output(args, cwd).unwrap_or_else(|err| panic!("spawn failed: {err}"));
    assert!(
        !out.status.success(),
        "heddle {args:?} should fail; stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = str::from_utf8(&out.stderr).expect("stderr utf8");
    serde_json::from_str(stderr.trim())
        .unwrap_or_else(|err| panic!("stderr not JSON: {err}\n  stderr: {stderr}"))
}

const COMPACT_ERROR_KEYS: &[&str] = &["kind", "error", "exit_code", "hint", "primary_command"];

fn assert_only_compact_error_keys(value: &Value, context: &str) {
    let obj = value
        .as_object()
        .unwrap_or_else(|| panic!("{context}: compact error must be a JSON object: {value}"));
    for key in obj.keys() {
        assert!(
            COMPACT_ERROR_KEYS.contains(&key.as_str()),
            "{context}: compact error leaked non-decision-surface key `{key}`: {value}"
        );
    }
    for key in COMPACT_ERROR_KEYS {
        assert!(
            obj.contains_key(*key),
            "{context}: compact error missing `{key}`: {value}"
        );
    }
}

#[test]
fn field_study_everyday_verbs_accept_json_compact() {
    let temp = TempDir::new().unwrap();
    heddle(&["init"], Some(temp.path())).expect("init");
    std::fs::write(temp.path().join("main.rs"), "fn main() {}\n").unwrap();
    heddle(&["capture", "-m", "seed"], Some(temp.path())).expect("seed");

    for args in [
        &["log"][..],
        &["diff"][..],
        &["verify"][..],
        &[
            "context",
            "set",
            "--path",
            "main.rs",
            "--scope",
            "file",
            "--kind",
            "rationale",
            "-m",
            "entry point",
        ][..],
        &["discuss", "open", "main.rs", "main", "first turn"][..],
    ] {
        let compact = compact_json(args, &temp);
        assert!(
            compact.get("output_kind").and_then(Value::as_str).is_some(),
            "heddle {args:?} --output json-compact must emit output_kind: {compact}"
        );
        assert_only_compact_keys(&compact, &format!("field-study {}", args.join(" ")));
        assert!(
            compact.get("verification").is_none()
                && compact.get("machine_contract_coverage").is_none(),
            "compact {args:?} must not embed machine-contract self-noise: {compact}"
        );
    }

    let checkout = TempDir::new().unwrap();
    let checkout_arg = checkout.path().join("work");
    let started = compact_json(
        &[
            "start",
            "feature/search",
            "--path",
            checkout_arg.to_str().unwrap(),
        ],
        &temp,
    );
    assert_eq!(started["output_kind"].as_str(), Some("thread_start"));
    assert_only_compact_keys(&started, "field-study start");
}

#[test]
fn capture_compact_includes_state_id() {
    let temp = TempDir::new().unwrap();
    heddle(&["init"], Some(temp.path())).expect("init");
    std::fs::write(temp.path().join("work.txt"), "pending\n").unwrap();

    let compact = compact_json(&["capture", "-m", "compact state_id"], &temp);
    assert_eq!(compact["output_kind"].as_str(), Some("capture"));
    let state_id = compact["state_id"]
        .as_str()
        .unwrap_or_else(|| panic!("capture compact must include state_id: {compact}"));
    assert!(
        !state_id.is_empty(),
        "capture compact state_id must be non-empty: {compact}"
    );
    assert_only_compact_keys(&compact, "capture state_id");

    let full = full_json(&["log", "--limit", "1"], &temp);
    assert_eq!(
        full["states"][0]["state_id"].as_str(),
        Some(state_id),
        "compact capture state_id must match the tip state"
    );
}

#[test]
fn status_compact_after_ready_has_land_next_action() {
    let temp = TempDir::new().unwrap();
    heddle(&["init"], Some(temp.path())).expect("init");
    std::fs::write(temp.path().join("base.txt"), "base\n").unwrap();
    heddle(&["capture", "-m", "base"], Some(temp.path())).expect("base");

    let checkout = TempDir::new().unwrap();
    let checkout_arg = checkout.path().join("work");
    let started = full_json(
        &[
            "start",
            "feature/search",
            "--path",
            checkout_arg.to_str().unwrap(),
        ],
        &temp,
    );
    let execution_path = started["execution_path"]
        .as_str()
        .expect("start should report execution_path");
    let checkout_path = std::path::Path::new(execution_path);
    std::fs::write(checkout_path.join("feature.txt"), "feature\n").unwrap();
    heddle(&["capture", "-m", "feature"], Some(checkout_path)).expect("feature");
    heddle(&["ready"], Some(checkout_path)).expect("ready");

    let status_out = heddle_output(&["--output", "json-compact", "status"], Some(checkout_path))
        .expect("status compact after ready");
    assert!(
        status_out.status.success(),
        "compact status after ready should succeed; stderr={}",
        String::from_utf8_lossy(&status_out.stderr)
    );
    let compact: Value = serde_json::from_str(
        str::from_utf8(&status_out.stdout)
            .expect("stdout utf8")
            .lines()
            .next()
            .expect("status compact stdout"),
    )
    .expect("status compact JSON");
    let next_action = compact["next_action"]
        .as_str()
        .unwrap_or_else(|| panic!("compact status after ready must have next_action: {compact}"));
    assert!(
        next_action.contains("land --thread feature/search"),
        "compact status after ready must recommend land: {compact}"
    );
    assert_only_compact_keys(&compact, "status after ready");
    assert!(
        compact.get("verification").is_none(),
        "compact status must drop the coverage report: {compact}"
    );
}

#[test]
fn status_compact_before_init_stays_compact() {
    let temp = TempDir::new().unwrap();
    let envelope =
        compact_error_envelope(&["--output", "json-compact", "status"], Some(temp.path()));
    assert_eq!(envelope["kind"], "repository_not_found");
    assert_only_compact_error_keys(&envelope, "status compact before init");
    let primary = envelope["primary_command"]
        .as_str()
        .unwrap_or_else(|| panic!("compact pre-init error must keep primary_command: {envelope}"));
    assert!(
        primary.contains("heddle init"),
        "compact pre-init next step must be init: {envelope}"
    );
    assert!(
        envelope.get("advice_contract_valid").is_none()
            && envelope.get("recovery_commands").is_none()
            && envelope.get("unsafe_condition").is_none(),
        "compact pre-init must not dump the full recovery envelope: {envelope}"
    );
}