gwm-cli 1.4.0

git worktree manager — TUI + CLI, native libgit2, per-repo bootstrap
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
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
//! Contract freeze tests for the 1.0 machine surface (issue #317).
//!
//! These pin the three machine-readable contracts so a rename or removal
//! of a *stable* field fails CI and becomes a conscious breaking decision
//! (a `contract::SCHEMA_VERSION` bump) rather than an accident:
//!
//! 1. **JSON output schemas** — `docs/schema/*.json` vs the live output: the
//!    [`gwm::json_api`] DTOs (`list`/`doctor`/`path`) and the hand-built
//!    `gwm status --json` payload ([`build_status_json`]).
//! 2. **Daemon JSON-RPC protocol** — method/notification names, error
//!    codes, and the `schema_version` carried in `worktrees.changed`.
//! 3. **`.gwm.toml` config schema** — the top-level section set.
//!
//! Sections 5–7 add baselines independent of both DTO and schema so a
//! *coordinated* rename, a type drift, or a re-tightened `additionalProperties`
//! is caught too — not just a one-sided DTO-vs-schema divergence.
//!
//! Anchor choice: the committed `docs/schema/*.json` files are the source
//! of truth (they are what external consumers fetch), so the parity tests
//! read them off disk and compare against the live serialized DTOs. The
//! relation is deliberately a **subset** check, not exact equality — the
//! `repo` field is workspace-only and present in `properties` but not in
//! `required`, so `required ⊆ serialized ⊆ properties` is the correct shape
//! (an `assert_eq!` would false-fail on it).
//!
//! Proven to bite: temporarily renaming a `JsonWorktree` field, or dropping
//! a `required` entry from a schema file, turns the relevant parity test
//! red (verified during development of #317).

use clap::Parser;
use gwm::cli::{build_status_json, Cli, Command};
use gwm::contract;
use gwm::github::{BranchLink, CiState, IssueState, IssueStatus, LinkSource, PrState, PrStatus};
use gwm::json_api::{JsonCheck, JsonDoctorReport, JsonPath, JsonStatus, JsonWorktree};
use serde_json::Value;
use std::collections::BTreeSet;
use std::path::PathBuf;

// --- helpers ---------------------------------------------------------------

fn schema_dir() -> PathBuf {
  PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("docs/schema")
}

fn read_schema(name: &str) -> Value {
  let path = schema_dir().join(name);
  let raw = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
  serde_json::from_str(&raw).unwrap_or_else(|e| panic!("parse {}: {e}", path.display()))
}

/// Keys of the JSON object at `pointer` within `schema`.
fn object_keys(schema: &Value, pointer: &str) -> BTreeSet<String> {
  schema
    .pointer(pointer)
    .unwrap_or_else(|| panic!("schema has no object at {pointer}"))
    .as_object()
    .unwrap_or_else(|| panic!("{pointer} is not an object"))
    .keys()
    .cloned()
    .collect()
}

/// Entries of the `required` string array at `pointer` within `schema`.
fn required_set(schema: &Value, pointer: &str) -> BTreeSet<String> {
  schema
    .pointer(pointer)
    .unwrap_or_else(|| panic!("schema has no `required` at {pointer}"))
    .as_array()
    .unwrap_or_else(|| panic!("{pointer} is not an array"))
    .iter()
    .map(|v| v.as_str().expect("required entry must be a string").to_string())
    .collect()
}

/// Top-level keys of a serialized value (must serialize to an object).
fn serialized_keys<T: serde::Serialize>(value: &T) -> BTreeSet<String> {
  serde_json::to_value(value)
    .expect("serialize")
    .as_object()
    .expect("DTO must serialize to an object")
    .keys()
    .cloned()
    .collect()
}

/// `required ⊆ serialized ⊆ properties` — the field-set contract between a
/// schema object and the DTO it documents. `what` labels failures.
fn assert_field_contract(
  what: &str,
  required: &BTreeSet<String>,
  serialized: &BTreeSet<String>,
  properties: &BTreeSet<String>,
) {
  let missing_required: Vec<_> = required.difference(serialized).collect();
  assert!(
    missing_required.is_empty(),
    "{what}: stable field(s) {missing_required:?} are `required` in the schema but no longer serialized — a rename/removal that breaks the contract"
  );
  let undocumented: Vec<_> = serialized.difference(properties).collect();
  assert!(
    undocumented.is_empty(),
    "{what}: serialized field(s) {undocumented:?} are not in the schema `properties` — an undocumented field leaking into the frozen output"
  );
}

fn sample_worktree() -> JsonWorktree {
  JsonWorktree {
    name: "feat-317".into(),
    id: "feat-317".into(),
    path: "/wt/feat-317".into(),
    branch: Some("feat/#317-freeze-machine-contracts".into()),
    head: Some("a".repeat(40)),
    is_main: false,
    is_locked: false,
    is_prunable: false,
    status: JsonStatus {
      is_dirty: true,
      has_upstream: true,
      ahead: 1,
      behind: 0,
      unknown: false,
    },
    age_seconds: Some(10),
    issue: Some(317),
    pr: Some(318),
    agents: None,
  }
}

// --- 1. JSON output schema parity ------------------------------------------

#[test]
fn worktree_list_schema_matches_the_dto() {
  let schema = read_schema("worktree-list.schema.json");
  let required = required_set(&schema, "/$defs/worktree/required");
  let properties = object_keys(&schema, "/$defs/worktree/properties");
  let serialized = serialized_keys(&sample_worktree());
  assert_field_contract("worktree-list row", &required, &serialized, &properties);
}

#[test]
fn worktree_status_schema_matches_the_dto() {
  let schema = read_schema("worktree-list.schema.json");
  let required = required_set(&schema, "/$defs/status/required");
  let properties = object_keys(&schema, "/$defs/status/properties");
  let serialized = serialized_keys(&sample_worktree().status);
  assert_field_contract("worktree status", &required, &serialized, &properties);
}

#[test]
fn workspace_repo_field_is_in_properties_but_not_required() {
  // The workspace `--workspace ... list --format=json` row flattens a
  // `JsonWorktree` and prepends `repo` (cli.rs `WorkspaceJsonWorktree`).
  // The schema must allow that extra field (it's in `properties`) without
  // demanding it for single-repo rows (it's NOT in `required`).
  let schema = read_schema("worktree-list.schema.json");
  let required = required_set(&schema, "/$defs/worktree/required");
  let properties = object_keys(&schema, "/$defs/worktree/properties");
  assert!(
    properties.contains("repo"),
    "workspace-mode `repo` must be a documented property"
  );
  assert!(
    !required.contains("repo"),
    "`repo` is workspace-only — requiring it would break single-repo rows"
  );

  // Replicate the workspace wire shape: flattened worktree + `repo`.
  let mut row = serde_json::to_value(sample_worktree()).unwrap();
  row
    .as_object_mut()
    .unwrap()
    .insert("repo".into(), Value::String("gwm-cli".into()));
  let serialized: BTreeSet<String> = row.as_object().unwrap().keys().cloned().collect();
  assert_field_contract("workspace worktree row", &required, &serialized, &properties);
}

#[test]
fn doctor_schema_matches_the_dtos() {
  let schema = read_schema("doctor.schema.json");

  let report = JsonDoctorReport {
    checks: vec![JsonCheck {
      name: "config".into(),
      status: "ok".into(),
      detail: "found .gwm.toml".into(),
      fix_hint: None,
    }],
    severity: "ok".into(),
    exit_code: 0,
  };
  let required = required_set(&schema, "/required");
  let properties = object_keys(&schema, "/properties");
  assert_field_contract("doctor report", &required, &serialized_keys(&report), &properties);

  let check_required = required_set(&schema, "/$defs/check/required");
  let check_properties = object_keys(&schema, "/$defs/check/properties");
  assert_field_contract(
    "doctor check",
    &check_required,
    &serialized_keys(&report.checks[0]),
    &check_properties,
  );
}

#[test]
fn path_schema_matches_the_dto() {
  let schema = read_schema("path.schema.json");
  let required = required_set(&schema, "/required");
  let properties = object_keys(&schema, "/properties");
  let dto = JsonPath {
    name: "feat-317".into(),
    path: "/wt/feat-317".into(),
    branch: Some("feat/#317-freeze-machine-contracts".into()),
  };
  assert_field_contract("path result", &required, &serialized_keys(&dto), &properties);
}

// --- 2. Schema version freeze ----------------------------------------------

#[test]
fn schema_version_baseline_is_one() {
  // The 1.0 baseline. Bumping this is a deliberate breaking decision; this
  // test flags the bump so it can't happen by accident.
  assert_eq!(contract::SCHEMA_VERSION, 1);
}

#[test]
fn every_schema_file_declares_the_contract_version() {
  for file in [
    "worktree-list.schema.json",
    "doctor.schema.json",
    "path.schema.json",
    "status.schema.json",
  ] {
    let schema = read_schema(file);
    let v = schema
      .get("version")
      .unwrap_or_else(|| panic!("{file} must declare a `version`"))
      .as_u64()
      .unwrap_or_else(|| panic!("{file} `version` must be an integer"));
    assert_eq!(
      v as u32,
      contract::SCHEMA_VERSION,
      "{file} version drifted from contract::SCHEMA_VERSION"
    );
  }
}

// --- 3. Daemon protocol freeze ---------------------------------------------

#[test]
fn daemon_notification_carries_the_schema_version() {
  // The runtime drift signal for a long-lived `subscribe` client.
  let note = gwm::daemon::worktrees_changed_notification(&[]);
  assert_eq!(note["method"], Value::String("worktrees.changed".into()));
  assert_eq!(
    note["params"]["schema_version"]
      .as_u64()
      .expect("schema_version present"),
    contract::SCHEMA_VERSION as u64
  );
  // The frozen payload field is still there alongside the version.
  assert!(note["params"]["worktrees"].is_array());
}

#[test]
fn daemon_method_and_notification_names_are_frozen() {
  assert_eq!(contract::DAEMON_METHODS, &["list", "doctor", "path", "subscribe"]);
  assert_eq!(contract::DAEMON_NOTIFICATIONS, &["worktrees.changed"]);
}

#[test]
fn daemon_jsonrpc_error_codes_are_the_standard_values() {
  // Frozen to the JSON-RPC 2.0 standard codes — a client maps on these.
  assert_eq!(gwm::daemon::PARSE_ERROR, -32700);
  assert_eq!(gwm::daemon::INVALID_REQUEST, -32600);
  assert_eq!(gwm::daemon::METHOD_NOT_FOUND, -32601);
  assert_eq!(gwm::daemon::INVALID_PARAMS, -32602);
  assert_eq!(gwm::daemon::INTERNAL_ERROR, -32603);
}

// --- 4. Config schema freeze -----------------------------------------------

#[test]
fn config_top_level_sections_are_frozen() {
  // The serialized top-level keys of a default Config ARE the `.gwm.toml`
  // section set. Pinning them against `contract::CONFIG_SECTIONS` makes a
  // renamed/added/removed section a conscious edit in two places.
  let serialized = serialized_keys(&gwm::config::Config::default());
  let frozen: BTreeSet<String> = contract::CONFIG_SECTIONS.iter().map(|s| s.to_string()).collect();
  assert_eq!(
    serialized, frozen,
    "the `.gwm.toml` top-level section set drifted from contract::CONFIG_SECTIONS"
  );
}

#[test]
fn a_config_with_every_frozen_section_round_trips() {
  // Each frozen section must still parse — `deny_unknown_fields` means a
  // renamed section would make this fail, a second guard on the set above.
  let toml = "\
[worktree]
[bootstrap]
[hooks]
[doctor]
[tui]
[theme]
[git_tui]
[review]
[issue_template]
[pr_template]
[aliases]
[gitmoji]
[exec]
[clean]
";
  let cfg: gwm::config::Config = toml::from_str(toml).expect("frozen sections must parse");
  // Array-of-table and list sections default to empty without a block.
  let _ = serde_json::to_value(&cfg).unwrap();
}

// --- 5. Frozen field + type baseline ---------------------------------------
//
// The parity tests above compare the live DTO to the live schema file, so
// they catch a DTO field renamed *without* the schema following. They do NOT
// catch two cases the 1.0 pledge cares about (raised in #317 review):
//
//   1. a coordinated rename — DTO field AND its schema entry renamed in the
//      same commit — leaves `required ⊆ serialized ⊆ properties` still true;
//   2. a *type* change with the same name (e.g. `head: String` -> `head: u64`)
//      is invisible to a name-only set comparison.
//
// This baseline is a third, independent anchor: a hardcoded `(field, type)`
// map per surface. A rename now needs THREE coordinated edits (DTO, schema,
// baseline) and a type change is caught outright — turning an accidental
// break into a deliberate one that must also bump `SCHEMA_VERSION`. Editing
// the maps below is the conscious act the freeze exists to force.

/// Coarse JSON type tag of a value, with integers split out from floats so a
/// `u64 -> f64` drift is caught. A `null` reports `"null"`, but the baseline
/// is asserted against samples whose nullable fields are populated, so the
/// *non-null* type is what gets pinned (null is always permitted on a
/// nullable field).
fn json_type(v: &Value) -> &'static str {
  match v {
    Value::Null => "null",
    Value::Bool(_) => "bool",
    Value::Number(n) if n.is_i64() || n.is_u64() => "integer",
    Value::Number(_) => "number",
    Value::String(_) => "string",
    Value::Array(_) => "array",
    Value::Object(_) => "object",
  }
}

/// Assert every `(field, expected_type)` in `baseline` is present in the
/// serialized object with the matching JSON type. `what` labels failures.
fn assert_type_baseline<T: serde::Serialize>(what: &str, value: &T, baseline: &[(&str, &str)]) {
  let v = serde_json::to_value(value).expect("serialize");
  let obj = v.as_object().expect("DTO must serialize to an object");
  for (field, expected) in baseline {
    let actual = obj
      .get(*field)
      .unwrap_or_else(|| panic!("{what}: stable field `{field}` is gone from the serialized output (rename/removal?)"));
    assert_eq!(
      json_type(actual),
      *expected,
      "{what}: stable field `{field}` changed type — was `{expected}`, now `{}`",
      json_type(actual)
    );
  }
}

#[test]
fn worktree_field_types_are_frozen() {
  assert_type_baseline(
    "worktree-list row",
    &sample_worktree(),
    &[
      ("name", "string"),
      ("id", "string"),
      ("path", "string"),
      ("branch", "string"),
      ("head", "string"),
      ("is_main", "bool"),
      ("is_locked", "bool"),
      ("is_prunable", "bool"),
      ("status", "object"),
      ("age_seconds", "integer"),
      ("issue", "integer"),
      ("pr", "integer"),
    ],
  );
  assert_type_baseline(
    "worktree status",
    &sample_worktree().status,
    &[
      ("is_dirty", "bool"),
      ("has_upstream", "bool"),
      ("ahead", "integer"),
      ("behind", "integer"),
      ("unknown", "bool"),
    ],
  );
}

#[test]
fn path_field_types_are_frozen() {
  let dto = JsonPath {
    name: "feat-317".into(),
    path: "/wt/feat-317".into(),
    branch: Some("feat/#317-freeze-machine-contracts".into()),
  };
  assert_type_baseline(
    "path result",
    &dto,
    &[("name", "string"), ("path", "string"), ("branch", "string")],
  );
}

#[test]
fn doctor_field_types_are_frozen() {
  let report = JsonDoctorReport {
    checks: vec![JsonCheck {
      name: "config".into(),
      status: "ok".into(),
      detail: "found .gwm.toml".into(),
      fix_hint: Some("run gwm init".into()),
    }],
    severity: "ok".into(),
    exit_code: 0,
  };
  assert_type_baseline(
    "doctor report",
    &report,
    &[("checks", "array"), ("severity", "string"), ("exit_code", "integer")],
  );
  assert_type_baseline(
    "doctor check",
    &report.checks[0],
    &[
      ("name", "string"),
      ("status", "string"),
      ("detail", "string"),
      ("fix_hint", "string"),
    ],
  );
}

// --- 6. Frozen *schema-side* baseline --------------------------------------
//
// Section 5 freezes the DTO side (what gwm emits). The committed schema
// files are themselves a published artifact external validators consume, so
// they need the symmetric freeze (raised in #317 review):
//
//   1. a schema edit that DROPS a stable field from `required` (makes it
//      optional) while the DTO still emits it leaves the parity check green
//      (`required` only shrinks, `serialized ⊆ properties` still holds) —
//      silently weakening the published contract;
//   2. a schema-only TYPE drift (e.g. `head`'s declared type flipped to
//      `integer` while the output stays a string) is invisible to a baseline
//      that only inspects the serialized DTO.
//
// So pin the schema's own `required` set and per-field declared `type`/`$ref`
// against an explicit frozen baseline, independent of the DTO. Experimental
// fields (`repo`) are deliberately excluded — they may move without a bump.

/// Normalized descriptor of a schema property's declared type: the `$ref`
/// target verbatim (prefixed), or the `type` keyword with a multi-type
/// array sorted+joined so `["string","null"]` is stable regardless of order.
fn schema_type_descriptor(prop: &Value) -> String {
  if let Some(r) = prop.get("$ref").and_then(|v| v.as_str()) {
    return format!("$ref:{r}");
  }
  match prop.get("type") {
    Some(Value::String(s)) => s.clone(),
    Some(Value::Array(a)) => {
      let mut parts: Vec<String> = a.iter().filter_map(|x| x.as_str().map(String::from)).collect();
      parts.sort();
      parts.join("|")
    }
    _ => panic!("schema property has neither `$ref` nor `type`"),
  }
}

/// Assert the schema object at `base_ptr` has exactly `frozen_required` as
/// its stable required set (experimental fields excluded by construction),
/// and that each `(field, descriptor)` in `frozen_types` matches the
/// property's declared `type`/`$ref`.
fn assert_schema_baseline(
  what: &str,
  schema: &Value,
  base_ptr: &str,
  frozen_required: &[&str],
  frozen_types: &[(&str, &str)],
) {
  let required = required_set(schema, &format!("{base_ptr}/required"));
  let frozen: BTreeSet<String> = frozen_required.iter().map(|s| s.to_string()).collect();
  assert_eq!(
    required, frozen,
    "{what}: schema `required` set drifted from the frozen stable baseline — a dropped/added required field is a contract change"
  );
  let props = schema
    .pointer(&format!("{base_ptr}/properties"))
    .unwrap_or_else(|| panic!("{what}: no properties at {base_ptr}"));
  for (field, expected) in frozen_types {
    let prop = props
      .get(*field)
      .unwrap_or_else(|| panic!("{what}: stable field `{field}` missing from schema properties"));
    assert_eq!(
      &schema_type_descriptor(prop),
      expected,
      "{what}: schema-declared type of `{field}` drifted from the frozen contract"
    );
  }
}

#[test]
fn worktree_schema_required_and_types_are_frozen() {
  let schema = read_schema("worktree-list.schema.json");
  assert_schema_baseline(
    "worktree-list row",
    &schema,
    "/$defs/worktree",
    // `repo` is experimental — intentionally NOT in the frozen required set.
    &[
      "name",
      "id",
      "path",
      "branch",
      "head",
      "is_main",
      "is_locked",
      "is_prunable",
      "status",
      "age_seconds",
      "issue",
      "pr",
    ],
    &[
      ("name", "string"),
      ("id", "string"),
      ("path", "string"),
      ("branch", "null|string"),
      ("head", "null|string"),
      ("is_main", "boolean"),
      ("is_locked", "boolean"),
      ("is_prunable", "boolean"),
      ("status", "$ref:#/$defs/status"),
      ("age_seconds", "integer|null"),
      ("issue", "integer|null"),
      ("pr", "integer|null"),
    ],
  );
  assert_schema_baseline(
    "worktree status",
    &schema,
    "/$defs/status",
    &["is_dirty", "has_upstream", "ahead", "behind", "unknown"],
    &[
      ("is_dirty", "boolean"),
      ("has_upstream", "boolean"),
      ("ahead", "integer"),
      ("behind", "integer"),
      ("unknown", "boolean"),
    ],
  );
}

#[test]
fn doctor_schema_required_and_types_are_frozen() {
  let schema = read_schema("doctor.schema.json");
  assert_schema_baseline(
    "doctor report",
    &schema,
    "",
    &["checks", "severity", "exit_code"],
    &[
      ("checks", "array"),
      ("severity", "$ref:#/$defs/status"),
      ("exit_code", "integer"),
    ],
  );
  assert_schema_baseline(
    "doctor check",
    &schema,
    "/$defs/check",
    &["name", "status", "detail", "fix_hint"],
    &[
      ("name", "string"),
      ("status", "$ref:#/$defs/status"),
      ("detail", "string"),
      ("fix_hint", "null|string"),
    ],
  );
}

#[test]
fn path_schema_required_and_types_are_frozen() {
  let schema = read_schema("path.schema.json");
  assert_schema_baseline(
    "path result",
    &schema,
    "",
    &["name", "path", "branch"],
    &[("name", "string"), ("path", "string"), ("branch", "null|string")],
  );
}

#[test]
fn output_schemas_tolerate_additive_fields() {
  // The versioning policy promises additive fields are backward-compatible
  // and consumers ignore unknowns (#317 review). For a schema-validating
  // consumer that's only true if the object schemas don't set
  // `additionalProperties: false` — otherwise a v1 validator would reject
  // an output carrying a new optional field. Freeze that: nobody may
  // re-tighten these without consciously breaking the documented policy.
  // (The producer-side guard `serialized ⊆ properties` still catches an
  // accidental leaked field at our own CI.)
  let cases: &[(&str, &[&str])] = &[
    ("worktree-list.schema.json", &["/$defs/worktree", "/$defs/status"]),
    ("doctor.schema.json", &["", "/$defs/check"]),
    ("path.schema.json", &[""]),
    ("status.schema.json", &["", "/$defs/issue_link", "/$defs/pr_link"]),
  ];
  for (file, pointers) in cases {
    let schema = read_schema(file);
    for ptr in *pointers {
      let obj = schema
        .pointer(ptr)
        .unwrap_or_else(|| panic!("{file}: no object at '{ptr}'"));
      assert_ne!(
        obj.get("additionalProperties"),
        Some(&Value::Bool(false)),
        "{file} at '{ptr}': additionalProperties:false breaks the additive-compatibility policy"
      );
    }
  }
}

// --- 7. `gwm status --json` freeze -----------------------------------------
//
// The fourth JSON output surface (#317 review): a hand-built, nested payload
// documented as "a stable schema for scripting" (cli.rs). It's not a serde
// DTO, so `build_status_json` was made pure (returns the value) to pin it
// here without spawning the binary or hitting GitHub. Frozen against
// `docs/schema/status.schema.json`.

/// A fully-populated status value: a remote slug, a linked issue and PR with
/// live `gh` state. Exercises every optional nested field so the freeze
/// covers the widest shape the surface emits.
fn populated_status() -> Value {
  let mut link = BranchLink::empty();
  link.issue = Some(317);
  link.pr = Some(322);
  link.issue_source = LinkSource::Explicit;
  link.pr_source = LinkSource::Detected;
  let issue = Some(IssueStatus {
    number: 317,
    title: "freeze the contracts".into(),
    state: IssueState::Open,
    url: "https://example/317".into(),
    labels: vec!["enhancement".into()],
    updated_at: "2026-06-17T00:00:00Z".into(),
  });
  let pr = Some(PrStatus {
    number: 322,
    title: "freeze & version".into(),
    state: PrState::Open,
    url: "https://example/322".into(),
    updated_at: "2026-06-17T00:00:00Z".into(),
    checks_passed: 3,
    checks_total: 4,
    ci: CiState::Running,
    checks: vec![],
  });
  build_status_json(
    "feat/#317-freeze-machine-contracts",
    Some("kbrdn1/gwm-cli"),
    &link,
    &issue,
    &pr,
  )
}

#[test]
fn status_json_matches_the_schema() {
  let schema = read_schema("status.schema.json");
  let top_required = required_set(&schema, "/required");
  let top_props = object_keys(&schema, "/properties");
  let v = populated_status();

  let top: BTreeSet<String> = v.as_object().unwrap().keys().cloned().collect();
  assert_field_contract("status result", &top_required, &top, &top_props);

  let issue_required = required_set(&schema, "/$defs/issue_link/required");
  let issue_props = object_keys(&schema, "/$defs/issue_link/properties");
  let issue: BTreeSet<String> = v["issue"].as_object().unwrap().keys().cloned().collect();
  assert_field_contract("status issue link", &issue_required, &issue, &issue_props);

  let pr_required = required_set(&schema, "/$defs/pr_link/required");
  let pr_props = object_keys(&schema, "/$defs/pr_link/properties");
  let pr: BTreeSet<String> = v["pr"].as_object().unwrap().keys().cloned().collect();
  assert_field_contract("status pr link", &pr_required, &pr, &pr_props);
}

#[test]
fn status_json_null_link_still_carries_required_keys() {
  // No remote, no link: `branch` plus explicit `issue:null` / `pr:null`. The
  // required keys must be present so a scripting consumer can always read
  // them; `repo` is absent (it's optional, only with a slug).
  let v = build_status_json("dev", None, &BranchLink::empty(), &None, &None);
  let obj = v.as_object().unwrap();
  assert_eq!(obj["branch"], Value::String("dev".into()));
  assert_eq!(obj["issue"], Value::Null);
  assert_eq!(obj["pr"], Value::Null);
  assert!(!obj.contains_key("repo"), "repo must be absent without a remote slug");
}

#[test]
fn status_json_field_types_are_frozen() {
  let v = populated_status();
  assert_type_baseline(
    "status result",
    &v,
    &[
      ("branch", "string"),
      ("repo", "string"),
      ("issue", "object"),
      ("pr", "object"),
    ],
  );
  assert_type_baseline(
    "status issue link",
    &v["issue"],
    &[
      ("number", "integer"),
      ("source", "string"),
      ("state", "string"),
      ("title", "string"),
      ("labels", "array"),
      ("url", "string"),
    ],
  );
  assert_type_baseline(
    "status pr link",
    &v["pr"],
    &[
      ("number", "integer"),
      ("source", "string"),
      ("state", "string"),
      ("title", "string"),
      ("checks_passed", "integer"),
      ("checks_total", "integer"),
      ("url", "string"),
    ],
  );
}

#[test]
fn status_schema_required_and_types_are_frozen() {
  let schema = read_schema("status.schema.json");

  // Top object: `branch`/`repo` are plain types; `issue`/`pr` are
  // `oneOf[null, $ref]`, asserted structurally below.
  assert_eq!(
    required_set(&schema, "/required"),
    ["branch", "issue", "pr"]
      .iter()
      .map(|s| s.to_string())
      .collect::<BTreeSet<_>>(),
    "status top-level required set drifted"
  );
  assert_eq!(schema_type_descriptor(&schema["properties"]["branch"]), "string");
  assert_eq!(schema_type_descriptor(&schema["properties"]["repo"]), "string");
  for field in ["issue", "pr"] {
    let one_of = schema["properties"][field]["oneOf"]
      .as_array()
      .unwrap_or_else(|| panic!("status `{field}` must be a oneOf[null, link]"));
    let descriptors: BTreeSet<String> = one_of.iter().map(schema_type_descriptor).collect();
    let expected_ref = format!("$ref:#/$defs/{}_link", field);
    assert!(descriptors.contains("null"), "status `{field}` must permit null");
    assert!(
      descriptors.contains(&expected_ref),
      "status `{field}` must reference its link definition"
    );
  }

  assert_schema_baseline(
    "status issue link",
    &schema,
    "/$defs/issue_link",
    &["number", "source"],
    &[
      ("number", "integer"),
      ("source", "$ref:#/$defs/link_source"),
      ("state", "string"),
      ("title", "string"),
      ("labels", "array"),
      ("url", "string"),
    ],
  );
  assert_schema_baseline(
    "status pr link",
    &schema,
    "/$defs/pr_link",
    &["number", "source"],
    &[
      ("number", "integer"),
      ("source", "$ref:#/$defs/link_source"),
      ("state", "string"),
      ("title", "string"),
      ("checks_passed", "integer"),
      ("checks_total", "integer"),
      ("url", "string"),
    ],
  );
}

// --- 8. exec / clean CLI flag freeze (issue #344) --------------------------
// `help_prints_subcommands` (cli_binary.rs) pins the subcommand *names*; it
// does not see flags. The 1.0 exec/clean surface froze `--profile` / `--jobs`
// (#324) and the global `--workspace` (#36 / #326) as part of the stable CLI
// contract, so a rename, a removal, or a change to whether a flag takes a value
// must be a conscious breaking decision, not a silent clap edit. These parse a
// full invocation and assert each flag lands on the right field with the right
// arity — renaming `--jobs`, dropping `--profile`, or making `--yes` take a
// value turns one of them red.

#[test]
fn exec_flag_surface_is_frozen() {
  // `--workspace` is a global flag (on `Cli`); `--profile` / `--jobs` are on
  // the subcommand; the command follows `--`.
  let cli = Cli::try_parse_from([
    "gwm",
    "--workspace",
    "/tmp/ws",
    "exec",
    "--profile",
    "ci",
    "--jobs",
    "4",
    "--",
    "cargo",
    "test",
  ])
  .expect("frozen exec flags must still parse");

  assert_eq!(
    cli.workspace.as_deref(),
    Some(std::path::Path::new("/tmp/ws")),
    "`--workspace <DIR>` is a frozen global flag that takes a value"
  );
  match cli.command {
    Some(Command::Exec {
      profile,
      jobs,
      command,
      slugs,
    }) => {
      assert!(slugs.is_empty(), "no slugs before `--`");
      assert_eq!(
        profile.as_deref(),
        Some("ci"),
        "`--profile <NAME>` frozen, takes a value"
      );
      assert_eq!(jobs, Some(4), "`--jobs <N>` frozen, takes an integer value");
      assert_eq!(
        command,
        vec!["cargo".to_string(), "test".to_string()],
        "`-- <cmd>` forwarded verbatim"
      );
    }
    other => panic!("expected Command::Exec, got {other:?}"),
  }
}

#[test]
fn clean_flag_surface_is_frozen() {
  let cli = Cli::try_parse_from([
    "gwm",
    "--workspace",
    "/tmp/ws",
    "clean",
    "feat-1",
    "--profile",
    "rust",
    "--yes",
  ])
  .expect("frozen clean flags must still parse");

  assert_eq!(
    cli.workspace.as_deref(),
    Some(std::path::Path::new("/tmp/ws")),
    "`--workspace <DIR>` is a frozen global flag that takes a value"
  );
  match cli.command {
    Some(Command::Clean { slugs, profile, yes }) => {
      assert_eq!(slugs, vec!["feat-1".to_string()], "positional slug still accepted");
      assert_eq!(
        profile.as_deref(),
        Some("rust"),
        "`--profile <NAME>` frozen, takes a value"
      );
      assert!(yes, "`--yes` frozen as a boolean flag (no value)");
    }
    other => panic!("expected Command::Clean, got {other:?}"),
  }
}

#[test]
fn clean_yes_flag_takes_no_value() {
  // Guards the arity of `--yes` specifically. With `--yes` as a bool, a
  // following bare token is NOT consumed as its value — it lands in `slugs`.
  // If `--yes` were ever changed to take a value, clap would swallow the token
  // and `slugs` would be empty, turning this red.
  let cli = Cli::try_parse_from(["gwm", "clean", "--yes", "trailing-token"]).expect("parses with --yes as a boolean");
  match cli.command {
    Some(Command::Clean { slugs, yes, .. }) => {
      assert!(yes, "--yes set");
      assert_eq!(
        slugs,
        vec!["trailing-token".to_string()],
        "the trailing token is a slug, not a value consumed by --yes"
      );
    }
    other => panic!("expected Command::Clean, got {other:?}"),
  }
}

// --- 8. Agent sessions field (issue #408) ----------------------------------
//
// `agents` is an ADDITIVE, experimental-tier field on the list row (same
// route the workspace `repo` field took): present in `properties`, never in
// `required`, omitted (not null) when no session matched, ignored cleanly by
// pre-#408 consumers. SCHEMA_VERSION stays 1.

mod agent_sessions_field {
  use super::*;
  use gwm::json_api::{JsonAgentSession, JsonWorktreeAgents};

  fn sample_agents() -> JsonWorktreeAgents {
    let s = |kind: &str, freshness: &str, ts: u64, id: &str| JsonAgentSession {
      kind: kind.into(),
      freshness: freshness.into(),
      last_activity: ts,
      id: id.into(),
      name: Some("fix the login flow".into()),
    };
    JsonWorktreeAgents {
      top: s("claude", "active", 1_784_480_000, "a7820111"),
      sessions: vec![
        s("claude", "active", 1_784_480_000, "a7820111"),
        s("codex", "idle", 1_784_470_000, "019f6b95"),
      ],
    }
  }

  fn sample_worktree_with_agents() -> JsonWorktree {
    let mut w = sample_worktree();
    w.agents = Some(sample_agents());
    w
  }

  #[test]
  fn agents_is_documented_but_never_required() {
    let schema = read_schema("worktree-list.schema.json");
    let required = required_set(&schema, "/$defs/worktree/required");
    let properties = object_keys(&schema, "/$defs/worktree/properties");
    assert!(properties.contains("agents"), "`agents` must be a documented property");
    assert!(
      !required.contains("agents"),
      "`agents` is additive/experimental — requiring it would break the additive policy"
    );
  }

  #[test]
  fn worktree_with_agents_still_matches_the_schema() {
    let schema = read_schema("worktree-list.schema.json");
    let required = required_set(&schema, "/$defs/worktree/required");
    let properties = object_keys(&schema, "/$defs/worktree/properties");
    let serialized = serialized_keys(&sample_worktree_with_agents());
    assert_field_contract("worktree row with agents", &required, &serialized, &properties);
  }

  #[test]
  fn agents_shape_and_types_are_frozen() {
    assert_type_baseline(
      "worktree agents",
      &sample_agents(),
      &[("top", "object"), ("sessions", "array")],
    );
    assert_type_baseline(
      "agent session",
      &sample_agents().top,
      &[
        ("kind", "string"),
        ("freshness", "string"),
        ("last_activity", "integer"),
        ("id", "string"),
        ("name", "string"),
      ],
    );
  }

  #[test]
  fn agents_is_omitted_not_null_when_absent() {
    let v = serde_json::to_value(sample_worktree()).unwrap();
    assert!(
      !v.as_object().unwrap().contains_key("agents"),
      "a session-less row must omit `agents` entirely (skip_serializing_if), not carry null"
    );
  }

  #[test]
  fn a_pre_408_consumer_parses_a_payload_carrying_agents() {
    // Minimal stand-in for a consumer compiled against the pre-#408 shape:
    // serde ignores unknown fields by default, so `agents` passes through.
    #[derive(serde::Deserialize)]
    struct OldRow {
      name: String,
      path: String,
    }
    let payload = serde_json::to_string(&sample_worktree_with_agents()).unwrap();
    let old: OldRow = serde_json::from_str(&payload).expect("old consumer must keep working");
    assert_eq!(old.name, "feat-317");
    assert_eq!(old.path, "/wt/feat-317");
  }
}