memstead-cli 0.3.0

Command-line interface for Memstead — query and mutate typed entity graphs from the shell. Default build produces the full `memstead` binary (multi-mem, git-backed); `--no-default-features` builds the lean folder-only surface.
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
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
//! `memstead projection` — the binding (projection-promotion) command tree.
//!
//! The projection is the unit: one versioned binding per source→mem obligation
//! (bundle plan `03-projection-promotion`). The tree ships five leaves —
//! `brief`, `init`, `migrate`, `advance`, `enable`:
//!
//! - `brief` renders a binding's run-brief — the Markdown prompt an agent
//!   consumes — for a canonical binding id `<mem>/<stem>` (D3/D9), or the next
//!   due binding under `--all` (round-robin + backoff selection).
//! - `init` scaffolds a fresh v1 binding non-interactively (D8).
//! - `migrate` promotes both legacy generations into v1 bindings (D10): the
//!   root-folder `scopes|projections|ingests/` layout (gen-1) and the gen-2
//!   four-primitive store (`Projection` + flat `Ingest`).
//! - `advance` records disposition-gated sync-baseline advances (D7).
//! - `enable` adds a missing `build` / `sync` / `verify` operation block to an
//!   existing binding (D6 — the remedy a refused mutating op cites).
//!
//! This tree is the sole binding surface: the retired `ingest` and `pipeline`
//! command trees folded in here (`ingest brief` → `projection brief`,
//! `pipeline migrate` → `projection migrate`'s gen-1 path).
//!
//! Errors carry `PROJECTION_*` wire tokens (D12); the missing-workspace path is
//! single-sourced through [`crate::setup::workspace_not_initialised_error`].

use clap::{Args as ClapArgs, Subcommand, ValueEnum};
use serde_json::json;

use memstead_base::binding::{
    BINDING_VERSION, BindingV1, BuildMode, BuildOperation, CapabilityError, CoverageSemantics,
    DEFAULT_ADJUDICATION_CAP, DEFAULT_FULL_RESYNC_EVERY, Operations, PruneConfig, ResolvedBinding,
    SyncOperation, VerifyOperation, prune_guarantee_for_medium, validate_binding,
};
use memstead_base::binding_migrate::{
    BindingMigrateError, migrate_gen2_bindings, resolve_migrated_binding,
};
use memstead_base::ingest::advance::{
    AdvanceError, DispositionInput, ExcludeError, advance_baseline, record_exclusions,
};
use memstead_base::ingest::findings::{FullResyncDecision, verify_binding};
use memstead_base::ingest::report::{
    DEFAULT_REPORT_BUDGET, compute_fidelity_report, render_fidelity_report,
};
use memstead_base::ingest::resolve::{
    ResolveError, ResolvedPrimarySource, ResolvedSource, resolve_binding, resolve_binding_run,
};
use memstead_base::ingest::{
    RenderBriefError, render_ingest_brief, render_sync_brief_for, render_verify_brief_for,
    select_next_due,
};
use memstead_base::pipeline::{
    Facet, IngestTrigger, Medium, MediumType, PatternEntry, PatternMode,
};
use memstead_base::pipeline_store::{
    delete_ingest, load_legacy_pipeline_configs, load_pipeline_configs, read_binding,
    write_binding, write_facet, write_medium,
};
use memstead_base::workspace_store::StoreError;
use memstead_base::{migrate_legacy_pipeline, read_legacy_pipeline_configs};

use crate::CliError;
use crate::output::{ExitKind, print_json, print_markdown};
use crate::setup::{CliContext, CliEngine, workspace_not_initialised_error};

#[derive(ClapArgs, Debug)]
pub struct Args {
    #[command(subcommand)]
    pub command: ProjectionCommand,
}

#[derive(Subcommand, Debug)]
pub enum ProjectionCommand {
    /// Render a binding's run-brief — the Markdown prompt an agent consumes —
    /// on stdout. Takes the canonical binding id `<mem>/<stem>` (D3), e.g.
    /// `engine/graph`. Omit the id (or pass `--all`) to select the next due
    /// binding by round-robin + backoff and render its build brief. Reads the v1
    /// binding store and the destination mem's schema / writing guidance; the
    /// assembly is shared with the UniFFI surface, so CLI and app briefs are
    /// byte-identical by construction.
    ///
    /// `--verify` renders the **verify brief** (group C) for the named binding:
    /// measurement + capped-adjudication instructions only, with no
    /// destination-mutation instruction. `--sync` renders the **sync brief** —
    /// the sole maintenance-writer prompt, carrying both the cursor slice and the
    /// open verify findings in one brief with the absorbed reconcile
    /// conservatism. Both are read-only on the mem; the sync brief's repairs
    /// reach the mem only when an agent acts on it through the MCP mutation
    /// surface.
    Brief(BriefArgs),
    /// Scaffold a fresh v1 binding non-interactively: a `Medium`, a `Facet`,
    /// and a v1 binding under `.memstead/{mediums,facets,projections}/<mem>/`.
    /// All inputs are flags — no prompts ever (parity across callers). The
    /// default binding declares build+sync+verify where the medium permits:
    /// a `web` source scaffolds build-only, with the deferral named in
    /// `warnings[]`. A `prune` block is scaffolded wherever sync survived,
    /// with the strongest guarantee the medium supports (never-clobber for a
    /// git-backed source). Refuses `PROJECTION_EXISTS` (without touching disk)
    /// when a binding of the same id already exists — never overwrites.
    Init(InitArgs),
    /// Migrate both legacy generations into v1 bindings (D10). Gen-1 — the
    /// root-folder `scopes|projections|ingests/` JSON layout the retired
    /// `pipeline migrate` command handled — is first materialized into the
    /// gen-2 `.memstead/` store, then promoted. Gen-2 — the four-primitive
    /// store (per-mem `Projection` + flat `Ingest`) — merges each ingest into
    /// the projection its `projection` ref names; the binding takes the
    /// projection's file identity (`.memstead/projections/<mem>/<stem>.json`)
    /// and the merged ingest is removed. `refinement` mode and dangling
    /// projection refs refuse with a typed error. Use `--dry-run` to preview
    /// without writing.
    Migrate(MigrateArgs),
    /// Enable a `build` / `sync` / `verify` operation on an existing binding by
    /// adding its block (with sensible defaults) if absent. This is the remedy
    /// a refused *mutating* operation cites (D6): `projection enable sync
    /// <binding>`. Before writing, the operation is checked against the
    /// medium-capability matrix (D6) — enabling `sync`/`verify` over a medium
    /// that cannot support it (e.g. a `web` source) refuses with the capability
    /// gap and writes nothing. Enabling an already-present operation refuses
    /// `PROJECTION_OP_ALREADY_ENABLED`; a missing binding refuses
    /// `PROJECTION_NOT_FOUND`.
    Enable(EnableArgs),
    /// Advance a binding's sync baseline by recording per-artifact
    /// dispositions (D7). The engine freezes the presented changed slice,
    /// subtracts already-disposed artifacts on re-presentation, appends
    /// new-HEAD deltas when the source moves mid-pass, and — when the
    /// remainder empties — advances the destination mem's `#synced` token via
    /// the sync-state writer (provenance piggybacks that commit). Dispositions
    /// are durable (`.memstead/state/advance/`), so a partial pass resumes
    /// across process restarts. The gate accepts **only** artifact ids the
    /// engine presented — an unknown id refuses the whole call atomically
    /// (`PROJECTION_ADVANCE_UNKNOWN_ARTIFACT`). In this cycle the agent supplies
    /// a disposition for **every** artifact explicitly (auto-derivation lands
    /// later).
    Advance(AdvanceArgs),
    /// Declare authored **exclusions** for in-scope source artifacts. Unlike
    /// `advance` (whose gate accepts only artifacts in the changed slice), this
    /// gates on enumerable `S(D)` membership, so a stable, unchanged artifact can
    /// be recorded as deliberately not-modeled with a rationale. Each accepted
    /// `(artifact, rationale)` lands in the durable exclusion ledger the fidelity
    /// report consults, so the artifact stops re-surfacing as `uncovered` under
    /// exhaustive coverage and keeps its reasoning. An artifact outside `S(D)`
    /// refuses the whole call atomically (`PROJECTION_EXCLUDE_NOT_SOURCE_MEMBER`);
    /// re-declaring merges into the ledger. The write path for the option-(a)
    /// process-mem judgment migration, and the general "this in-scope artifact is
    /// mined and warrants no destination entity, because …" capability.
    Exclude(ExcludeArgs),
    /// Measure a binding's fidelity and record durable findings (E3b, group A).
    /// Read-only on the destination mem: verify adjudicates the mem's anchors
    /// against the live source and samples in-scope artifacts, writing findings
    /// keyed `(hash(D), source_head)` into the engine-owned findings store
    /// (`.memstead/state/findings/`). A binding-declaration edit or a source-head
    /// move partitions the keyspace, so prior findings are segregated as
    /// superseded, never presented as current. Verify never mutates the mem —
    /// any repair routes through the (later) sync brief. It then renders the
    /// deterministic, token-budgeted **tier-1 fidelity report** (group B) over
    /// the findings just recorded: grain-classed coverage with tree-anchor
    /// fan-out on its own axis, anchor-resolution %, freshness vs. both
    /// `sync_state` tokens (`signal: none` → freshness unknowable), the
    /// capability-matrix block, and the tier-3 backlog depth — aggregates always
    /// ship; heavy per-artifact lists greedy-fill under `--budget` and drop to
    /// hints (forced back in with `--include`).
    Verify(VerifyArgs),
}

/// The medium type flag for `projection init` — the CLI-facing mirror of
/// [`MediumType`] (which carries serde, not clap, derives). Decides the
/// capability matrix (D6) that filters the default binding's operations.
#[derive(Clone, Copy, Debug, ValueEnum)]
pub enum MediumTypeArg {
    /// A source tree of code.
    Codebase,
    /// A directory of files (non-code).
    Filesystem,
    /// A git history.
    Git,
    /// Another mem's graph.
    Graph,
    /// Web sources (build-only this cycle — no change signal).
    Web,
}

impl MediumTypeArg {
    fn to_medium_type(self) -> MediumType {
        match self {
            MediumTypeArg::Codebase => MediumType::Codebase,
            MediumTypeArg::Filesystem => MediumType::Filesystem,
            MediumTypeArg::Git => MediumType::Git,
            MediumTypeArg::Graph => MediumType::Graph,
            MediumTypeArg::Web => MediumType::Web,
        }
    }
}

#[derive(ClapArgs, Debug)]
pub struct BriefArgs {
    /// The canonical binding id `<mem>/<stem>` (D3) — e.g. `engine/graph`.
    /// Omit (or pass `--all`) to select the next due binding by round-robin +
    /// backoff. Required with `--verify` / `--sync` (those operate on one
    /// binding's live findings/cursor, never a rotation).
    pub binding: Option<String>,
    /// Select the next due binding across all bindings (round-robin + backoff)
    /// and render its (build) brief, instead of naming one. Ignored with
    /// `--verify` / `--sync`.
    #[arg(long)]
    pub all: bool,
    /// Render the **verify brief** (group C) for the named binding instead of
    /// the build brief: measurement + capped-adjudication instructions only.
    /// It carries no destination-mutation instruction — repairs route through
    /// the sync brief. Read-only on the mem. Mutually exclusive with `--sync`.
    #[arg(long, conflicts_with = "sync")]
    pub verify: bool,
    /// Render the **sync brief** (group C) for the named binding instead of the
    /// build brief: the sole maintenance-writer prompt, carrying both the cursor
    /// slice and the open verify findings in one brief, with the absorbed
    /// reconcile conservatism. Read-only on the mem (the agent's writes route
    /// through MCP). Mutually exclusive with `--verify`.
    #[arg(long, conflicts_with = "verify")]
    pub sync: bool,
}

#[derive(ClapArgs, Debug)]
pub struct InitArgs {
    /// Destination mem the binding writes into — the `<mem>` half of the
    /// binding id `<mem>/<stem>` and the per-mem tier the three files live under.
    #[arg(long)]
    pub mem: String,
    /// The medium pointer — a path (codebase / filesystem / git) or a mem id /
    /// URL (graph / web). Becomes the scaffolded medium's `pointer`.
    #[arg(long)]
    pub source: String,
    /// The medium type — decides the capability matrix (D6) that filters which
    /// operations the default binding declares.
    #[arg(long = "medium-type", value_enum)]
    pub medium_type: MediumTypeArg,
    /// Intent prose for the agent (the binding's `intent`). Optional.
    #[arg(long)]
    pub intent: Option<String>,
    /// Binding stem — the `<stem>` half of the binding id and the shared file
    /// name of the scaffolded medium / facet / binding. Defaults to the final
    /// path component of `--source`.
    #[arg(long)]
    pub name: Option<String>,
}

#[derive(ClapArgs, Debug)]
pub struct MigrateArgs {
    /// Preview the produced bindings (and any warnings) without writing them
    /// to disk or removing the merged ingest files.
    #[arg(long)]
    pub dry_run: bool,
}

/// The operation `projection enable` adds to a binding. Mirror of the binding's
/// operations block: `build` is always present (required), so enabling it
/// always refuses as already-enabled; `sync` / `verify` are the enableable
/// blocks.
#[derive(Clone, Copy, Debug, ValueEnum, PartialEq, Eq)]
pub enum EnableOperationArg {
    /// The build operation (always present — enabling refuses as already-enabled).
    Build,
    /// The sync (maintenance-write) operation.
    Sync,
    /// The verify (measurement) operation.
    Verify,
}

impl EnableOperationArg {
    fn name(self) -> &'static str {
        match self {
            EnableOperationArg::Build => "build",
            EnableOperationArg::Sync => "sync",
            EnableOperationArg::Verify => "verify",
        }
    }
}

#[derive(ClapArgs, Debug)]
pub struct EnableArgs {
    /// The operation to enable: `build` | `sync` | `verify`.
    #[arg(value_enum)]
    pub operation: EnableOperationArg,
    /// The binding id `<mem>/<stem>` (D3) — e.g. `engine/graph`.
    pub binding: String,
}

#[derive(ClapArgs, Debug)]
pub struct AdvanceArgs {
    /// The binding id `<mem>/<stem>` (D3) — e.g. `engine/graph`.
    pub binding: String,
    /// A JSON object mapping each judged artifact id to its disposition, e.g.
    /// `'{"src/lib.rs": "worked", "src/old.rs": "irrelevant"}'`. A value may
    /// instead be an object carrying an authored rationale —
    /// `'{"src/gen.rs": {"disposition": "excluded", "rationale": "generated, no entity"}}'`
    /// — and an `excluded` verdict with a rationale is retained in the durable
    /// exclusion ledger so the artifact stops re-surfacing as `uncovered` and
    /// keeps its reasoning. Only ids the engine presented in the brief's changed
    /// slice are accepted — an unknown id refuses the whole call. Pass `'{}'` to
    /// re-present the remainder without recording anything.
    #[arg(long)]
    pub dispositions: String,
}

#[derive(ClapArgs, Debug)]
pub struct ExcludeArgs {
    /// The binding id `<mem>/<stem>` (D3) — e.g. `project/graph`.
    pub binding: String,
    /// A JSON object mapping each in-scope source artifact id to the authored
    /// rationale for excluding it, e.g.
    /// `'{"docs/legacy.md": "superseded; no entity", "vendor/x.rs": "generated"}'`.
    /// Every id must be a member of the binding's enumerable source `S(D)` — an
    /// id outside scope refuses the whole call.
    #[arg(long)]
    pub exclusions: String,
}

#[derive(ClapArgs, Debug)]
pub struct VerifyArgs {
    /// The binding id `<mem>/<stem>` (D3) — e.g. `engine/graph`.
    pub binding: String,
    /// Token budget for the tier-1 fidelity report's **heavy** content
    /// (per-artifact lists). Aggregated counts always ship in addition; heavy
    /// lists greedy-fill and drop to `## Hints` when they do not fit. Defaults
    /// to the house envelope budget.
    #[arg(long)]
    pub budget: Option<usize>,
    /// Force a heavy report section in past the budget (repeatable):
    /// `uncovered_artifacts` | `tree_fanout` | `superseded_findings`.
    #[arg(long = "include")]
    pub include: Vec<String>,
}

pub fn run(ctx: &CliContext, args: Args) -> anyhow::Result<()> {
    match args.command {
        ProjectionCommand::Brief(a) => brief(ctx, a),
        ProjectionCommand::Init(a) => init(ctx, a),
        ProjectionCommand::Migrate(a) => migrate(ctx, a),
        ProjectionCommand::Enable(a) => enable(ctx, a),
        ProjectionCommand::Advance(a) => advance(ctx, a),
        ProjectionCommand::Exclude(a) => exclude(ctx, a),
        ProjectionCommand::Verify(a) => verify(ctx, a),
    }
}

/// Map a [`RenderBriefError`] to a typed CLI error (D12). Not-found bindings /
/// facets / mediums exit `NotFound`; a malformed id is a `Validation` name
/// error; config-load and mode-unsupported failures are generic. Codes are
/// spelled as literals at each construction site so the generated error index
/// (xtask) picks them up.
fn map_brief_err(binding_id: &str, err: RenderBriefError) -> CliError {
    let message = err.to_string();
    let mapped = match &err {
        RenderBriefError::ConfigLoad(_) => {
            CliError::new(ExitKind::Generic, "PROJECTION_LOAD_FAILED", message)
        }
        // D6/AC4: the binding declares no build op — refuse with the
        // `projection enable build` remedy the error message already carries.
        RenderBriefError::BuildOperationAbsent { .. } => CliError::new(
            ExitKind::Validation,
            "PROJECTION_BUILD_NOT_ENABLED",
            message,
        ),
        // A malformed findings store while rendering a verify / sync brief.
        RenderBriefError::FindingsRead { .. } => CliError::new(
            ExitKind::Generic,
            "PROJECTION_FINDINGS_READ_FAILED",
            message,
        ),
        RenderBriefError::Resolve(inner) => match inner {
            ResolveError::BindingNotFound { .. } => {
                CliError::new(ExitKind::NotFound, "PROJECTION_NOT_FOUND", message)
            }
            ResolveError::FacetNotFound { .. } => {
                CliError::new(ExitKind::NotFound, "PROJECTION_FACET_NOT_FOUND", message)
            }
            ResolveError::MediumNotFound { .. } => {
                CliError::new(ExitKind::NotFound, "PROJECTION_MEDIUM_NOT_FOUND", message)
            }
            ResolveError::MalformedProjectionRef { .. } => {
                CliError::new(ExitKind::Validation, "PROJECTION_INVALID_NAME", message)
            }
        },
    };
    mapped.with_details(json!({ "binding": binding_id }))
}

fn brief(ctx: &CliContext, args: BriefArgs) -> anyhow::Result<()> {
    let (_shape, root) = ctx.workspace_shape().ok_or_else(|| {
        workspace_not_initialised_error(
            "not inside a Memstead workspace (no `.memstead/workspace.toml` in any ancestor)",
        )
    })?;

    let cli_engine = ctx.cli_engine_at(&root)?;
    let engine = match &cli_engine {
        #[cfg(feature = "mem-repo")]
        CliEngine::MemRepo(e) => e,
        CliEngine::Filesystem(e) => e,
    };

    // Group-C briefs: verify / sync render for one named binding (no rotation).
    // Both are read-only on the destination mem — the sync brief's repairs reach
    // the mem only when an agent acts on it through the MCP mutation surface.
    if args.verify || args.sync {
        let binding_id = args.binding.ok_or_else(|| {
            CliError::new(
                ExitKind::Validation,
                "PROJECTION_BRIEF_BINDING_REQUIRED",
                format!(
                    "`projection brief --{}` needs a binding id `<mem>/<stem>` — it renders one \
                     binding's brief, not an `--all` rotation",
                    if args.verify { "verify" } else { "sync" }
                ),
            )
        })?;
        let rendered = if args.verify {
            render_verify_brief_for(engine, &root, &binding_id)
        } else {
            render_sync_brief_for(engine, &root, &binding_id)
        }
        .map_err(|e| map_brief_err(&binding_id, e))?;

        if ctx.json {
            print_json(&json!({ "brief": rendered }))?;
        } else {
            print!("{rendered}");
        }
        return Ok(());
    }

    // Resolve which binding to render: a named one (canonical `<mem>/<stem>`),
    // or the next due binding in a round-robin `--all` rotation (which advances
    // the cursor + backoff state).
    let selected = match args.binding {
        Some(binding) if !args.all => Some(binding),
        _ => {
            let configs = load_pipeline_configs(&root).map_err(|e| {
                CliError::new(
                    ExitKind::Generic,
                    "PROJECTION_LOAD_FAILED",
                    format!("could not load binding store: {e}"),
                )
                .with_details(json!({ "error": e.to_string() }))
            })?;
            // Distinguish "nothing is configured" from "everything is backing
            // off". Both otherwise collapse into the same `None` from
            // `select_next_due`, but the two outcomes want different caller
            // responses: an empty store is a setup prompt, a backing-off pass
            // is a no-op retry. Emit the empty-store signal explicitly so a
            // caller (the plugin router, a status display) can branch on it.
            if configs.bindings.is_empty() {
                if ctx.json {
                    print_json(&json!({ "no_bindings": true }))?;
                } else {
                    println!("> **[projection] No bindings configured in this workspace yet.**");
                }
                return Ok(());
            }
            select_next_due(engine, &root, &configs)
        }
    };

    let Some(binding_id) = selected else {
        // Every eligible binding is backing off this pass — a valid outcome.
        if ctx.json {
            print_json(&json!({ "skipped": true }))?;
        } else {
            println!(
                "> **[projection] Skipped — every eligible binding is backing off this pass.**"
            );
        }
        return Ok(());
    };

    let rendered = render_ingest_brief(engine, &root, &binding_id)
        .map_err(|e| map_brief_err(&binding_id, e))?;

    if ctx.json {
        print_json(&json!({ "brief": rendered }))?;
    } else {
        // The brief *is* the stdout content (the skill pipes it as the agent
        // prompt) — write it verbatim, no added trailing newline.
        print!("{rendered}");
    }
    Ok(())
}

/// Is `value` a single, plain path component — safe to use verbatim as a `<mem>`
/// or `<stem>` dir/file segment and as half of the binding id? Mirrors
/// `pipeline_store`'s internal component guard so `init` refuses with a clear
/// typed code up front rather than surfacing a store IO error mid-scaffold.
fn is_single_component(value: &str) -> bool {
    !value.is_empty()
        && value != "."
        && value != ".."
        && !value.contains('/')
        && !value.contains('\\')
        && !value.contains(':')
        && !value.contains('\0')
}

/// Derive a binding stem from a `--source` pointer: its final path component
/// (trailing slashes trimmed). `../public` → `public`; `home` → `home`;
/// `https://example.com/manual` → `manual`.
fn derive_stem(source: &str) -> String {
    source
        .trim_end_matches('/')
        .rsplit('/')
        .next()
        .unwrap_or(source)
        .to_string()
}

/// Map a store write failure during scaffolding to a typed CLI error.
fn init_write_error(binding_id: &str, err: StoreError) -> CliError {
    CliError::new(
        ExitKind::Generic,
        "PROJECTION_INIT_FAILED",
        format!("could not scaffold binding `{binding_id}`: {err}"),
    )
    .with_details(json!({ "binding": binding_id, "error": err.to_string() }))
}

fn init(ctx: &CliContext, args: InitArgs) -> anyhow::Result<()> {
    let (_shape, root) = ctx.workspace_shape().ok_or_else(|| {
        workspace_not_initialised_error(
            "not inside a Memstead workspace (no `.memstead/workspace.toml` in any ancestor)",
        )
    })?;

    let mem = args.mem;
    let stem = args
        .name
        .clone()
        .unwrap_or_else(|| derive_stem(&args.source));

    // `mem` and `stem` become three file-path components and the binding id —
    // refuse anything that is not a single plain component before touching disk.
    for (kind, value) in [("mem", mem.as_str()), ("name", stem.as_str())] {
        if !is_single_component(value) {
            return Err(CliError::new(
                ExitKind::Validation,
                "PROJECTION_INVALID_NAME",
                format!(
                    "invalid {kind} '{}': must be a single path component (no separators, \
                     traversal segments, ':' or NUL) — pass an explicit --name",
                    value.escape_default()
                ),
            )
            .with_details(json!({ "kind": kind, "value": value }))
            .into());
        }
    }

    let binding_id = format!("{mem}/{stem}");
    let medium_type = args.medium_type.to_medium_type();

    // Refuse — without touching disk — when a binding of this id already exists
    // (D8: `init` never overwrites). The binding occupies the per-mem
    // projections tier; its presence is the id-collision signal.
    let binding_path = root
        .join(".memstead")
        .join("projections")
        .join(&mem)
        .join(format!("{stem}.json"));
    if binding_path.exists() {
        return Err(CliError::new(
            ExitKind::Validation,
            "PROJECTION_EXISTS",
            format!(
                "a binding `{binding_id}` already exists at \
                 .memstead/projections/{mem}/{stem}.json — `projection init` never overwrites; \
                 choose a different --name or edit the existing binding"
            ),
        )
        .with_details(json!({ "binding": binding_id }))
        .into());
    }

    // The scaffolded triple. The medium and facet share the binding stem as
    // their file identity — one tidy `mediums`/`facets`/`projections` triple per
    // obligation. The facet is scoped `**/*` (a scoped default: an unscoped
    // facet — no allow patterns — would refuse at run time).
    let medium = Medium {
        name: stem.clone(),
        medium_type,
        pointer: args.source.clone(),
        change_detection: None,
    };
    let scope = vec![PatternEntry {
        path: "**/*".to_string(),
        mode: PatternMode::Allow,
    }];
    let facet = Facet {
        name: stem.clone(),
        medium: stem.clone(),
        scope: scope.clone(),
        engagement: None,
        preparation: None,
    };

    // Matrix-filtered defaults (D6): declare build+sync+verify, then let the
    // capability matrix strip any operation the medium cannot support. A `web`
    // source has no change signal this cycle, so sync/verify are stripped and
    // the deferral is named in `warnings[]` (operator decision 7). Every other
    // medium keeps build+sync+verify.
    let mut binding = BindingV1 {
        version: BINDING_VERSION,
        intent: args.intent.clone(),
        source_facets: vec![stem.clone()],
        reference_mems: Vec::new(),
        destination_mem: mem.clone(),
        deny_paths: Vec::new(),
        coverage_semantics: CoverageSemantics::Exhaustive,
        rules: None,
        prune: None,
        operations: Operations {
            build: Some(BuildOperation {
                mode: BuildMode::Discovery,
                trigger: IngestTrigger::Loop,
                batch_size: 20,
                post_actions: None,
            }),
            sync: Some(SyncOperation {
                trigger: IngestTrigger::Manual,
                batch_size: 20,
            }),
            verify: Some(VerifyOperation {
                trigger: IngestTrigger::Manual,
                batch_size: 20,
                adjudication_cap: DEFAULT_ADJUDICATION_CAP,
                full_resync_every: DEFAULT_FULL_RESYNC_EVERY,
            }),
        },
    };

    let resolved = ResolvedBinding {
        binding: binding.clone(),
        primary_sources: vec![ResolvedPrimarySource {
            facet_ref: stem.clone(),
            medium: stem.clone(),
            medium_type,
            medium_pointer: args.source.clone(),
            declared_change_detection: None,
            scope,
            preparation: None,
        }],
    };

    let mut warnings: Vec<String> = Vec::new();
    if let Err(refusals) = validate_binding(&resolved) {
        for r in &refusals {
            if let CapabilityError::OperationOutOfScope { operation, .. } = r {
                match *operation {
                    "sync" => binding.operations.sync = None,
                    "verify" => binding.operations.verify = None,
                    _ => {}
                }
            }
            warnings.push(r.to_string());
        }
    }

    // Prune (F1) rides the sync path — scaffold it wherever sync survived the
    // matrix filter, with the strongest guarantee the medium supports (a
    // base-retrievable / git-backed medium gets never-clobber; every
    // sync-capable medium is also base-retrievable, so this never refuses). A
    // `web` binding (sync stripped) gets no prune block.
    if binding.operations.sync.is_some() {
        binding.prune = Some(PruneConfig {
            guarantee: prune_guarantee_for_medium(medium_type),
        });
    }

    let mut operations: Vec<&str> = vec!["build"];
    if binding.operations.sync.is_some() {
        operations.push("sync");
    }
    if binding.operations.verify.is_some() {
        operations.push("verify");
    }

    // Write the triple. The id-collision refusal above already guaranteed a
    // fresh binding, so this path only runs on a clean scaffold; a store IO
    // failure surfaces the typed `PROJECTION_INIT_FAILED`.
    write_medium(&root, &mem, &stem, &medium).map_err(|e| init_write_error(&binding_id, e))?;
    write_facet(&root, &mem, &stem, &facet).map_err(|e| init_write_error(&binding_id, e))?;
    write_binding(&root, &mem, &stem, &binding).map_err(|e| init_write_error(&binding_id, e))?;

    let created = vec![
        format!(".memstead/mediums/{mem}/{stem}.json"),
        format!(".memstead/facets/{mem}/{stem}.json"),
        format!(".memstead/projections/{mem}/{stem}.json"),
    ];

    if ctx.json {
        // D8's pinned skill contract: { binding, created, operations, warnings }.
        print_json(&json!({
            "binding": binding_id,
            "created": created,
            "operations": operations,
            "warnings": warnings,
        }))?;
    } else {
        let mut out = format!("# Projection init\n\nScaffolded binding `{binding_id}`:\n");
        for c in &created {
            out.push_str(&format!("- `{c}`\n"));
        }
        out.push_str(&format!("\nOperations: {}\n", operations.join(", ")));
        if !warnings.is_empty() {
            out.push_str("\n## Warnings\n\n");
            for w in &warnings {
                out.push_str(&format!("- {w}\n"));
            }
        }
        print_markdown(&out);
    }
    Ok(())
}

fn map_migrate_err(err: BindingMigrateError) -> CliError {
    // Spell each `PROJECTION_*` token as a literal at its own construction site
    // so the generated error index (xtask) picks them up — a variable `code`
    // is invisible to the string-literal scanner.
    let message = err.to_string();
    match &err {
        BindingMigrateError::RefinementModeDeleted { .. } => CliError::new(
            ExitKind::Validation,
            "PROJECTION_MIGRATE_REFINEMENT",
            message,
        ),
        BindingMigrateError::MalformedProjectionRef { .. } => CliError::new(
            ExitKind::Validation,
            "PROJECTION_MIGRATE_MALFORMED_REF",
            message,
        ),
        BindingMigrateError::DanglingProjectionRef { .. } => CliError::new(
            ExitKind::Validation,
            "PROJECTION_MIGRATE_DANGLING_REF",
            message,
        ),
    }
}

/// Does the workspace root carry a gen-1 legacy pipeline layout — the
/// pre-four-primitive `scopes|projections|ingests/` JSON folders at the root
/// (not under `.memstead/`)? Presence of any of the three marks it. This is the
/// trigger for folding the retired `pipeline migrate` conversion into
/// `projection migrate` (D10, gen-1 path).
fn has_legacy_root_layout(root: &std::path::Path) -> bool {
    ["scopes", "projections", "ingests"]
        .iter()
        .any(|d| root.join(d).is_dir())
}

/// Map a store load failure during migrate to the typed generic code.
fn migrate_load_err(err: StoreError) -> CliError {
    CliError::new(
        ExitKind::Generic,
        "PROJECTION_MIGRATE_FAILED",
        format!("could not load pipeline config: {err}"),
    )
    .with_details(json!({ "error": err.to_string() }))
}

/// Does the binding's `medium_pointer` (resolved against the workspace root)
/// point at the same location as a `reconcile-cursors.json` absolute key? Uses
/// canonicalization where both paths exist, else a lexical comparison (D10 —
/// "the binding whose medium pointer resolves to that path").
fn pointer_resolves_to(root: &std::path::Path, medium_pointer: &str, abs_path: &str) -> bool {
    let resolved = if medium_pointer.is_empty() {
        root.to_path_buf()
    } else {
        root.join(medium_pointer)
    };
    match (
        std::fs::canonicalize(&resolved),
        std::fs::canonicalize(abs_path),
    ) {
        (Ok(a), Ok(b)) => a == b,
        _ => resolved == std::path::Path::new(abs_path),
    }
}

/// Scan `workspace.toml` for retired pipeline/cursor vocabulary. `projection
/// migrate` **never** writes `workspace.toml` (D10) — if it finds a stale
/// reference it returns a proposal block for the operator (or the migrating
/// session) to apply and commit explicitly, rather than rewriting it.
fn propose_workspace_toml(root: &std::path::Path) -> Option<String> {
    let path = root.join(".memstead").join("workspace.toml");
    let content = std::fs::read_to_string(path).ok()?;
    let hits: Vec<(usize, &str)> = content
        .lines()
        .enumerate()
        .filter(|(_, l)| {
            let low = l.to_lowercase();
            low.contains("reconcile-cursors") || low.contains("ingests/") || low.contains("ingest ")
        })
        .collect();
    if hits.is_empty() {
        return None;
    }
    let mut block = String::from(
        "## Proposal: workspace.toml (NOT applied)\n\n`projection migrate` never edits \
         `workspace.toml`. It found references to retired pipeline vocabulary — review and \
         update these lines by hand, then commit:\n\n",
    );
    for (i, line) in hits {
        block.push_str(&format!("- L{}: `{}`\n", i + 1, line.trim()));
    }
    Some(block)
}

/// Consume a skill-written `reconcile-cursors.json` (D10/AC12): each
/// machine-absolute `"<mem>:<abs-path>": <sha>` entry seeds the `#synced`
/// baseline of every binding whose medium pointer resolves to that path (via
/// the engine's `set_mem_sync_state` writer — the engine owns mem-repo state),
/// then the file is **deleted** regardless of whether anything matched
/// (cursorless / unmatched bindings stay never-synced). Returns the seeded keys.
fn consume_reconcile_cursors(
    ctx: &CliContext,
    root: &std::path::Path,
) -> anyhow::Result<Vec<String>> {
    let cursor_path = root.join(".memstead").join("reconcile-cursors.json");
    if !cursor_path.exists() {
        return Ok(Vec::new());
    }
    let cursors: std::collections::BTreeMap<String, String> = std::fs::read(&cursor_path)
        .ok()
        .and_then(|b| serde_json::from_slice(&b).ok())
        .unwrap_or_default();

    let mut seeded: Vec<String> = Vec::new();
    if !cursors.is_empty() {
        let configs = load_pipeline_configs(root).map_err(migrate_load_err)?;
        let mut cli_engine = ctx.cli_engine_at(root)?;
        let engine = match &mut cli_engine {
            #[cfg(feature = "mem-repo")]
            CliEngine::MemRepo(e) => e,
            CliEngine::Filesystem(e) => e,
        };
        for (cursor_key, sha) in &cursors {
            // Key is `"<mem>:<abs-path>"` — split on the first ':'.
            let Some((_cursor_mem, abs_path)) = cursor_key.split_once(':') else {
                continue;
            };
            for record in &configs.bindings {
                let binding_id = format!("{}/{}", record.mem, record.name);
                let Ok(resolved) = resolve_binding_run(&configs, &binding_id, &record.config)
                else {
                    continue;
                };
                for source in &resolved.sources {
                    if let ResolvedSource::Primary(p) = source
                        && pointer_resolves_to(root, &p.medium_pointer, abs_path)
                    {
                        let key = format!("{binding_id}/{}#synced", p.facet_ref);
                        if engine
                            .set_mem_sync_state(
                                &resolved.destination_mem,
                                &key,
                                sha,
                                Some("projection migrate: seeded from reconcile-cursors.json"),
                            )
                            .is_ok()
                        {
                            seeded.push(key);
                        }
                    }
                }
            }
        }
    }
    // Consumed — delete regardless of matches (D10: the file is retired here).
    let _ = std::fs::remove_file(&cursor_path);
    Ok(seeded)
}

fn migrate(ctx: &CliContext, args: MigrateArgs) -> anyhow::Result<()> {
    let (_shape, root) = ctx.workspace_shape().ok_or_else(|| {
        workspace_not_initialised_error(
            "not inside a Memstead workspace (no `.memstead/workspace.toml` in any ancestor)",
        )
    })?;

    // Gen-1 root-folder layout (`scopes|projections|ingests/` at the workspace
    // root) — the pre-four-primitive generation the retired `pipeline migrate`
    // command handled. Fold it in (D10, gen-1 path): materialize it into the
    // gen-2 `.memstead/` store first (mediums + facets + projections + ingests),
    // then promote to v1 below in the same pass. `--dry-run` reads the
    // root-folder configs directly without writing anything.
    let gen1 = has_legacy_root_layout(&root);
    if gen1 && !args.dry_run {
        migrate_legacy_pipeline(&root).map_err(|e| {
            CliError::new(
                ExitKind::Generic,
                "PROJECTION_MIGRATE_FAILED",
                format!("could not convert root-folder (gen-1) pipeline layout: {e}"),
            )
            .with_details(json!({ "error": e.to_string() }))
        })?;
    }

    let configs = if gen1 && args.dry_run {
        read_legacy_pipeline_configs(&root).map_err(migrate_load_err)?
    } else {
        load_legacy_pipeline_configs(&root).map_err(migrate_load_err)?
    };

    // Pure transform first: any refusal (refinement / dangling / malformed)
    // aborts before a single file is touched — the migration is all-or-nothing.
    let migrated = migrate_gen2_bindings(&configs).map_err(map_migrate_err)?;

    // Validate each produced binding against the D6 capability matrix. A
    // capability refusal reflects a pre-existing config problem the binding
    // faithfully carries; surface it as a per-binding warning rather than
    // aborting the promotion.
    let mut warnings: Vec<serde_json::Value> = Vec::new();
    for m in &migrated {
        match resolve_migrated_binding(&configs, &m.id, m.binding.clone()) {
            Ok(resolved) => {
                if let Err(refusals) = validate_binding(&resolved) {
                    for r in refusals {
                        warnings.push(json!({
                            "binding": m.id,
                            "kind": "capability",
                            "message": r.to_string(),
                        }));
                    }
                }
            }
            Err(e) => warnings.push(json!({
                "binding": m.id,
                "kind": "resolve",
                "message": e.to_string(),
            })),
        }
        for note in &m.notes {
            warnings.push(json!({
                "binding": m.id,
                "kind": "note",
                "message": note,
            }));
        }
    }

    // Emit to disk unless previewing: promote each projection file to its v1
    // binding in place, then remove the consumed flat ingest.
    if !args.dry_run {
        for m in &migrated {
            write_binding(&root, &m.mem, &m.name, &m.binding).map_err(|e| {
                CliError::new(
                    ExitKind::Generic,
                    "PROJECTION_MIGRATE_FAILED",
                    format!("could not write binding `{}`: {e}", m.id),
                )
                .with_details(json!({ "binding": m.id, "error": e.to_string() }))
            })?;
            delete_ingest(&root, &m.ingest_name).map_err(|e| {
                CliError::new(
                    ExitKind::Generic,
                    "PROJECTION_MIGRATE_FAILED",
                    format!("could not remove merged ingest `{}`: {e}", m.ingest_name),
                )
                .with_details(json!({ "ingest": m.ingest_name, "error": e.to_string() }))
            })?;
        }
    }

    // AC12/D10: consume `reconcile-cursors.json` (seed `#synced` baselines, then
    // delete it) and surface a `workspace.toml` proposal for any retired-vocab
    // references — never rewriting workspace.toml. Both are no-ops in `--dry-run`.
    let (seeded, proposal) = if args.dry_run {
        (Vec::new(), None)
    } else {
        (
            consume_reconcile_cursors(ctx, &root)?,
            propose_workspace_toml(&root),
        )
    };

    let bindings: Vec<&str> = migrated.iter().map(|m| m.id.as_str()).collect();
    if ctx.json {
        print_json(&json!({
            "ok": true,
            "dry_run": args.dry_run,
            "migrated": migrated.len(),
            "bindings": bindings,
            "warnings": warnings,
            "cursors_seeded": seeded,
            "workspace_toml_proposal": proposal,
        }))?;
    } else {
        let verb = if args.dry_run {
            "Would migrate"
        } else {
            "Migrated"
        };
        let mut out = format!(
            "# Projection migration\n\n{verb} {} binding(s) to v1:\n",
            migrated.len()
        );
        for id in &bindings {
            out.push_str(&format!("- `{id}`\n"));
        }
        if !warnings.is_empty() {
            out.push_str("\n## Warnings\n\n");
            for w in &warnings {
                out.push_str(&format!(
                    "- [{}] `{}`: {}\n",
                    w["kind"].as_str().unwrap_or(""),
                    w["binding"].as_str().unwrap_or(""),
                    w["message"].as_str().unwrap_or(""),
                ));
            }
        }
        if !seeded.is_empty() {
            out.push_str("\n## Baselines seeded from reconcile-cursors.json\n\n");
            for key in &seeded {
                out.push_str(&format!("- `{key}`\n"));
            }
        }
        if let Some(block) = &proposal {
            out.push('\n');
            out.push_str(block);
        }
        if !args.dry_run {
            out.push_str(
                "\nEach projection file was promoted to a v1 binding in place and its merged \
                 ingest removed.\n",
            );
        }
        print_markdown(&out);
    }
    Ok(())
}

/// A malformed binding id (not `<mem>/<stem>`, or a half that is not a single
/// plain path component) — the same shape guard `init` applies to its
/// scaffolded id, spelled here so the failure is typed before any disk touch.
fn invalid_binding_id(binding_id: &str) -> CliError {
    CliError::new(
        ExitKind::Validation,
        "PROJECTION_INVALID_NAME",
        format!(
            "invalid binding id '{}': expected `<mem>/<stem>` with each half a single path \
             component (no extra separators, traversal segments, ':' or NUL)",
            binding_id.escape_default()
        ),
    )
    .with_details(json!({ "binding": binding_id }))
}

/// Map a store IO/parse failure while enabling to a typed CLI error. The
/// missing-binding case is handled separately (existence pre-check →
/// `PROJECTION_NOT_FOUND`); this covers a present-but-unreadable/unparseable
/// binding file and write failures.
fn enable_failed(binding_id: &str, err: StoreError) -> CliError {
    CliError::new(
        ExitKind::Generic,
        "PROJECTION_ENABLE_FAILED",
        format!("could not enable operation on binding `{binding_id}`: {err}"),
    )
    .with_details(json!({ "binding": binding_id, "error": err.to_string() }))
}

fn enable(ctx: &CliContext, args: EnableArgs) -> anyhow::Result<()> {
    let (_shape, root) = ctx.workspace_shape().ok_or_else(|| {
        workspace_not_initialised_error(
            "not inside a Memstead workspace (no `.memstead/workspace.toml` in any ancestor)",
        )
    })?;

    let binding_id = args.binding;
    let op = args.operation;

    // Parse the binding id `<mem>/<stem>`; refuse a malformed shape (or a half
    // that is not a single plain path component) before touching disk. Own the
    // halves so `binding_id` is free to move into JSON payloads later.
    let (mem, stem) = binding_id
        .split_once('/')
        .filter(|(m, n)| !m.is_empty() && !n.is_empty())
        .filter(|(m, n)| is_single_component(m) && is_single_component(n))
        .ok_or_else(|| invalid_binding_id(&binding_id))?;
    let mem = mem.to_string();
    let stem = stem.to_string();

    // Missing binding file → PROJECTION_NOT_FOUND (NotFound exit). A present-
    // but-unparseable file is kept apart (→ PROJECTION_ENABLE_FAILED) by this
    // existence pre-check.
    let binding_path = root
        .join(".memstead")
        .join("projections")
        .join(&mem)
        .join(format!("{stem}.json"));
    if !binding_path.exists() {
        return Err(CliError::new(
            ExitKind::NotFound,
            "PROJECTION_NOT_FOUND",
            format!(
                "no binding `{binding_id}` at .memstead/projections/{mem}/{stem}.json — \
                 scaffold one with `projection init` or migrate a legacy workspace with \
                 `projection migrate`"
            ),
        )
        .with_details(json!({ "binding": binding_id }))
        .into());
    }
    let mut binding =
        read_binding(&root, &mem, &stem).map_err(|e| enable_failed(&binding_id, e))?;

    // Already present? Refuse without a partial write. Every operation block is
    // optional now (D1/AC4), so `build` is enableable too (the remedy a
    // build-less binding's brief refusal cites).
    let already = match op {
        EnableOperationArg::Build => binding.operations.build.is_some(),
        EnableOperationArg::Sync => binding.operations.sync.is_some(),
        EnableOperationArg::Verify => binding.operations.verify.is_some(),
    };
    if already {
        return Err(CliError::new(
            ExitKind::Validation,
            "PROJECTION_OP_ALREADY_ENABLED",
            format!(
                "operation `{}` is already enabled on binding `{binding_id}` — nothing to do",
                op.name()
            ),
        )
        .with_details(json!({ "binding": binding_id, "operation": op.name() }))
        .into());
    }

    // Add the operation block with sensible defaults: `batch_size` mirrors the
    // build op's when present, else 20. Sync/verify default `trigger: manual`;
    // build defaults to a discovery/loop schedule (the common obligation shape).
    let batch_size = binding
        .operations
        .build
        .as_ref()
        .map_or(20, |b| b.batch_size);
    match op {
        EnableOperationArg::Build => {
            binding.operations.build = Some(BuildOperation {
                mode: BuildMode::Discovery,
                trigger: IngestTrigger::Loop,
                batch_size,
                post_actions: None,
            });
        }
        EnableOperationArg::Sync => {
            binding.operations.sync = Some(SyncOperation {
                trigger: IngestTrigger::Manual,
                batch_size,
            });
        }
        EnableOperationArg::Verify => {
            binding.operations.verify = Some(VerifyOperation {
                trigger: IngestTrigger::Manual,
                batch_size,
                adjudication_cap: DEFAULT_ADJUDICATION_CAP,
                full_resync_every: DEFAULT_FULL_RESYNC_EVERY,
            });
        }
    }

    // Matrix validation (D6): resolve the candidate binding (facets → mediums,
    // in the binding-id's `<mem>` tier) and refuse if the medium cannot support
    // the operation being enabled — e.g. `sync`/`verify` over a `web` source.
    // Refusals about *other* operations reflect pre-existing config and do not
    // block this enable (mirrors `migrate`'s treat-as-warning posture). No write
    // on refusal — the file stays byte-identical.
    let configs = load_legacy_pipeline_configs(&root).map_err(|e| enable_failed(&binding_id, e))?;
    let resolved = resolve_binding(&configs, &binding_id, &binding).map_err(|e| {
        CliError::new(
            ExitKind::Generic,
            "PROJECTION_ENABLE_FAILED",
            format!("could not resolve binding `{binding_id}` for validation: {e}"),
        )
        .with_details(json!({ "binding": binding_id, "error": e.to_string() }))
    })?;
    if let Err(refusals) = validate_binding(&resolved)
        && let Some(err) = refusals.iter().find(|r| {
            matches!(
                r,
                CapabilityError::OperationOutOfScope { operation, .. } if *operation == op.name()
            )
        })
    {
        return Err(CliError::new(
            ExitKind::Validation,
            "PROJECTION_CAPABILITY_UNSUPPORTED",
            err.to_string(),
        )
        .with_details(json!({ "binding": binding_id, "operation": op.name() }))
        .into());
    }

    write_binding(&root, &mem, &stem, &binding).map_err(|e| enable_failed(&binding_id, e))?;

    let mut operations: Vec<&str> = Vec::new();
    if binding.operations.build.is_some() {
        operations.push("build");
    }
    if binding.operations.sync.is_some() {
        operations.push("sync");
    }
    if binding.operations.verify.is_some() {
        operations.push("verify");
    }

    if ctx.json {
        print_json(&json!({
            "binding": binding_id,
            "enabled": op.name(),
            "operations": operations,
        }))?;
    } else {
        print_markdown(&format!(
            "# Projection enable\n\nEnabled `{}` on binding `{binding_id}`.\n\nOperations: {}\n",
            op.name(),
            operations.join(", ")
        ));
    }
    Ok(())
}

/// Map a `resolve_binding_run` failure (dangling facet/medium, malformed id)
/// to a typed CLI error. `BindingNotFound` cannot arise from the binding
/// resolver (the binding *is* the declaration), so it falls through to the
/// generic advance-failure code.
fn map_resolve_err(binding_id: &str, err: ResolveError) -> CliError {
    let message = err.to_string();
    let mapped = match err {
        ResolveError::FacetNotFound { .. } => {
            CliError::new(ExitKind::NotFound, "PROJECTION_FACET_NOT_FOUND", message)
        }
        ResolveError::MediumNotFound { .. } => {
            CliError::new(ExitKind::NotFound, "PROJECTION_MEDIUM_NOT_FOUND", message)
        }
        ResolveError::MalformedProjectionRef { .. } => {
            CliError::new(ExitKind::Validation, "PROJECTION_INVALID_NAME", message)
        }
        _ => CliError::new(ExitKind::Generic, "PROJECTION_ADVANCE_FAILED", message),
    };
    mapped.with_details(json!({ "binding": binding_id }))
}

/// Map an [`AdvanceError`] to a typed CLI error. The unknown-artifact refusal
/// is the D7 gate (Validation); a malformed id is a Validation-shaped name
/// error; store / engine failures are generic. Codes are spelled as literals at
/// each site so the generated error index picks them up.
fn map_advance_err(binding_id: &str, err: AdvanceError) -> CliError {
    let message = err.to_string();
    match &err {
        AdvanceError::MalformedId(_) => {
            CliError::new(ExitKind::Validation, "PROJECTION_INVALID_NAME", message)
                .with_details(json!({ "binding": binding_id }))
        }
        AdvanceError::UnknownArtifact { artifacts, .. } => CliError::new(
            ExitKind::Validation,
            "PROJECTION_ADVANCE_UNKNOWN_ARTIFACT",
            message,
        )
        .with_details(json!({ "binding": binding_id, "unknown_artifacts": artifacts })),
        AdvanceError::Store(_) | AdvanceError::Engine(_) => {
            CliError::new(ExitKind::Generic, "PROJECTION_ADVANCE_FAILED", message)
                .with_details(json!({ "binding": binding_id }))
        }
    }
}

fn advance(ctx: &CliContext, args: AdvanceArgs) -> anyhow::Result<()> {
    let (_shape, root) = ctx.workspace_shape().ok_or_else(|| {
        workspace_not_initialised_error(
            "not inside a Memstead workspace (no `.memstead/workspace.toml` in any ancestor)",
        )
    })?;

    let binding_id = args.binding;

    // Parse the dispositions payload up front — a malformed `--dispositions`
    // refuses cheaply (before loading configs or an engine) with a typed code.
    let dispositions: std::collections::BTreeMap<String, DispositionInput> =
        serde_json::from_str(&args.dispositions).map_err(|e| {
            CliError::new(
                ExitKind::Validation,
                "PROJECTION_INVALID_DISPOSITIONS",
                format!(
                    "--dispositions must be a JSON object mapping artifact id → either a \
                     disposition string (e.g. \"worked\") or an object \
                     {{\"disposition\": \"excluded\", \"rationale\": \"...\"}}: {e}"
                ),
            )
            .with_details(json!({ "error": e.to_string() }))
        })?;

    // Find the binding by canonical id in the v1 store.
    let configs = load_pipeline_configs(&root).map_err(|e| {
        CliError::new(
            ExitKind::Generic,
            "PROJECTION_ADVANCE_FAILED",
            format!("could not load pipeline config: {e}"),
        )
        .with_details(json!({ "error": e.to_string() }))
    })?;
    let record = configs
        .bindings
        .iter()
        .find(|r| format!("{}/{}", r.mem, r.name) == binding_id)
        .ok_or_else(|| {
            CliError::new(
                ExitKind::NotFound,
                "PROJECTION_NOT_FOUND",
                format!(
                    "no binding `{binding_id}` in this workspace — scaffold one with \
                     `projection init` or migrate a legacy workspace with `projection migrate`"
                ),
            )
            .with_details(json!({ "binding": binding_id }))
        })?;

    // D6/AC4: advance is the sync (maintenance-write) path — refuse when the
    // binding declares no `sync` operation, carrying the one-command remedy
    // `projection enable sync <binding>` (which, run verbatim, makes it succeed).
    if record.config.operations.sync.is_none() {
        return Err(CliError::new(
            ExitKind::Validation,
            "PROJECTION_SYNC_NOT_ENABLED",
            format!(
                "binding `{binding_id}` has no sync operation — enable it with \
                 `memstead projection enable sync {binding_id}`"
            ),
        )
        .with_details(json!({ "binding": binding_id }))
        .into());
    }

    let resolved = resolve_binding_run(&configs, &binding_id, &record.config)
        .map_err(|e| map_resolve_err(&binding_id, e))?;

    // The engine is mutable — a completing advance writes the `#synced`
    // baseline token through the sync-state writer.
    let mut cli_engine = ctx.cli_engine_at(&root)?;
    let engine = match &mut cli_engine {
        #[cfg(feature = "mem-repo")]
        CliEngine::MemRepo(e) => e,
        CliEngine::Filesystem(e) => e,
    };

    let outcome = advance_baseline(engine, &root, &resolved, &dispositions)
        .map_err(|e| map_advance_err(&binding_id, e))?;

    if ctx.json {
        print_json(&json!({
            "binding": outcome.binding,
            "completed": outcome.completed,
            "disposed": outcome.disposed,
            "pending": outcome.pending,
            "remainder": outcome.remainder,
            "tokens_written": outcome.tokens_written,
            "warnings": outcome.warnings,
        }))?;
    } else {
        let mut out = format!(
            "# Projection advance\n\nBinding `{}`: {} artifact(s) disposed, {} remaining.\n",
            outcome.binding, outcome.disposed, outcome.pending
        );
        if outcome.completed {
            out.push_str("\nEvery presented artifact is disposed — the sync baseline advanced.\n");
            if !outcome.tokens_written.is_empty() {
                out.push_str("\nBaseline tokens written:\n");
                for key in &outcome.tokens_written {
                    out.push_str(&format!("- `{key}`\n"));
                }
            }
        } else {
            out.push_str(
                "\nRemainder still pending — re-run `projection advance` after judging the rest \
                 (a brief re-render shows what is left).\n",
            );
        }
        if !outcome.warnings.is_empty() {
            out.push_str("\n## Warnings\n\n");
            for w in &outcome.warnings {
                out.push_str(&format!("- {w}\n"));
            }
        }
        print_markdown(&out);
    }
    Ok(())
}

/// Map an [`ExcludeError`] to a typed CLI error. The non-member refusal is the
/// S(D)-membership gate (Validation); a malformed id is a Validation-shaped name
/// error; store failures are generic. Codes are spelled as literals at each site
/// so the generated error index picks them up.
fn map_exclude_err(binding_id: &str, err: ExcludeError) -> CliError {
    let message = err.to_string();
    match &err {
        ExcludeError::MalformedId(_) => {
            CliError::new(ExitKind::Validation, "PROJECTION_INVALID_NAME", message)
                .with_details(json!({ "binding": binding_id }))
        }
        ExcludeError::NotSourceMember { artifacts, .. } => CliError::new(
            ExitKind::Validation,
            "PROJECTION_EXCLUDE_NOT_SOURCE_MEMBER",
            message,
        )
        .with_details(json!({ "binding": binding_id, "not_source_members": artifacts })),
        ExcludeError::Store(_) => {
            CliError::new(ExitKind::Generic, "PROJECTION_EXCLUDE_FAILED", message)
                .with_details(json!({ "binding": binding_id }))
        }
    }
}

fn exclude(ctx: &CliContext, args: ExcludeArgs) -> anyhow::Result<()> {
    let (_shape, root) = ctx.workspace_shape().ok_or_else(|| {
        workspace_not_initialised_error(
            "not inside a Memstead workspace (no `.memstead/workspace.toml` in any ancestor)",
        )
    })?;

    let binding_id = args.binding;

    // Parse the exclusions payload up front — a malformed `--exclusions` refuses
    // cheaply (before loading configs) with a typed code.
    let exclusions: std::collections::BTreeMap<String, String> =
        serde_json::from_str(&args.exclusions).map_err(|e| {
            CliError::new(
                ExitKind::Validation,
                "PROJECTION_INVALID_EXCLUSIONS",
                format!(
                    "--exclusions must be a JSON object mapping in-scope artifact id → \
                     rationale string: {e}"
                ),
            )
            .with_details(json!({ "error": e.to_string() }))
        })?;

    // Find the binding by canonical id in the v1 store.
    let configs = load_pipeline_configs(&root).map_err(|e| {
        CliError::new(
            ExitKind::Generic,
            "PROJECTION_EXCLUDE_FAILED",
            format!("could not load pipeline config: {e}"),
        )
        .with_details(json!({ "error": e.to_string() }))
    })?;
    let record = configs
        .bindings
        .iter()
        .find(|r| format!("{}/{}", r.mem, r.name) == binding_id)
        .ok_or_else(|| {
            CliError::new(
                ExitKind::NotFound,
                "PROJECTION_NOT_FOUND",
                format!(
                    "no binding `{binding_id}` in this workspace — scaffold one with \
                     `projection init` or migrate a legacy workspace with `projection migrate`"
                ),
            )
            .with_details(json!({ "binding": binding_id }))
        })?;

    let resolved = resolve_binding_run(&configs, &binding_id, &record.config)
        .map_err(|e| map_resolve_err(&binding_id, e))?;

    let outcome = record_exclusions(&root, &resolved, &exclusions)
        .map_err(|e| map_exclude_err(&binding_id, e))?;

    if ctx.json {
        print_json(&json!({
            "binding": outcome.binding,
            "excluded": outcome.excluded,
            "added": outcome.added,
        }))?;
    } else {
        print_markdown(&format!(
            "# Projection exclude\n\nBinding `{}`: {} artifact(s) newly excluded, \
             {} in the ledger.\n",
            outcome.binding, outcome.added, outcome.excluded
        ));
    }
    Ok(())
}

/// Render a one-block human note for the full-enumeration scheduling decision
/// (D3), prepended to the verify report so the typed signal is never silent: a
/// scheduled full walk that fired, a not-yet-due countdown, disabled scheduling,
/// and — critically — any non-enumerable refusal. Empty for the quiet cases
/// keeps a rotating-sample run byte-clean.
fn render_full_resync_note(decision: &FullResyncDecision) -> String {
    match decision {
        FullResyncDecision::Disabled => String::new(),
        FullResyncDecision::NotDue { .. } => String::new(),
        FullResyncDecision::Due {
            walked_facets,
            refused,
            ..
        } => {
            let mut s = String::from("> **Scheduled full resync (D3)** — ");
            if walked_facets.is_empty() {
                s.push_str("no enumerable facet to walk this run.");
            } else {
                s.push_str(&format!(
                    "full-enumeration coverage walk fired for: {}.",
                    walked_facets.join(", ")
                ));
            }
            for r in refused {
                s.push_str(&format!(
                    "\n> **Refused (non-enumerable):** `{}` ({}) — {}",
                    r.facet, r.medium_type, r.reason
                ));
            }
            s.push_str("\n\n");
            s
        }
    }
}

/// `projection verify <binding>` — measure fidelity and record durable findings
/// (group A). Read-only on the destination mem.
fn verify(ctx: &CliContext, args: VerifyArgs) -> anyhow::Result<()> {
    let (_shape, root) = ctx.workspace_shape().ok_or_else(|| {
        workspace_not_initialised_error(
            "not inside a Memstead workspace (no `.memstead/workspace.toml` in any ancestor)",
        )
    })?;

    let binding_id = args.binding;

    let configs = load_pipeline_configs(&root).map_err(|e| {
        CliError::new(
            ExitKind::Generic,
            "PROJECTION_VERIFY_FAILED",
            format!("could not load pipeline config: {e}"),
        )
        .with_details(json!({ "error": e.to_string() }))
    })?;
    let record = configs
        .bindings
        .iter()
        .find(|r| format!("{}/{}", r.mem, r.name) == binding_id)
        .ok_or_else(|| {
            CliError::new(
                ExitKind::NotFound,
                "PROJECTION_NOT_FOUND",
                format!(
                    "no binding `{binding_id}` in this workspace — scaffold one with \
                     `projection init` or migrate a legacy workspace with `projection migrate`"
                ),
            )
            .with_details(json!({ "binding": binding_id }))
        })?;

    let resolved = resolve_binding_run(&configs, &binding_id, &record.config)
        .map_err(|e| map_resolve_err(&binding_id, e))?;

    // Verify is read-only — a shared engine borrow makes a mem mutation
    // structurally impossible (A5).
    let cli_engine = ctx.cli_engine_at(&root)?;
    let engine = match &cli_engine {
        #[cfg(feature = "mem-repo")]
        CliEngine::MemRepo(e) => e,
        CliEngine::Filesystem(e) => e,
    };

    let outcome = verify_binding(engine, &root, &record.config, &resolved).map_err(|e| {
        CliError::new(
            ExitKind::Generic,
            "PROJECTION_VERIFY_FAILED",
            format!("verify failed for `{binding_id}`: {e}"),
        )
        .with_details(json!({ "binding": binding_id, "error": e.to_string() }))
    })?;

    // Assemble + render the tier-1 fidelity report (group B) over the findings
    // the pass just recorded. Read-only — no destination-mem mutation.
    let budget = args.budget.unwrap_or(DEFAULT_REPORT_BUDGET);
    let report = compute_fidelity_report(engine, &root, &record.config, &resolved, &outcome.key);
    let rendered = render_fidelity_report(&report, budget, &args.include);

    if ctx.json {
        print_json(&json!({
            "binding": outcome.binding,
            "key": {
                "binding_hash": outcome.key.binding_hash,
                "source_head": outcome.key.source_head,
            },
            "recorded": outcome.recorded,
            "superseded": outcome.superseded,
            "backlog": outcome.backlog,
            // The tier-3 full-enumeration scheduling decision (D3) — surfaced
            // (never a silent skip): whether a scheduled full walk fired, is not
            // yet due, is disabled, and any typed non-enumerable refusals.
            "full_resync": outcome.full_resync,
            "report": report,
            "report_mode": rendered.mode,
            "report_markdown": rendered.markdown,
        }))?;
    } else {
        // The rendered report IS the stdout content (agent-consumable brief);
        // prepend the scheduled full-walk decision so D3's typed signal (a full
        // sweep, or a non-enumerable refusal) is never silent in human mode.
        print_markdown(&format!(
            "{}{}",
            render_full_resync_note(&outcome.full_resync),
            rendered.markdown
        ));
    }
    Ok(())
}