cordance-cli 0.1.2

Cordance CLI — installs the `cordance` binary. The umbrella package `cordance` re-exports this entry; either install command works.
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
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
//! `cordance pack` — the core compilation pipeline.

use std::collections::HashMap;
use std::io::Read;

use anyhow::{Context, Result};
use camino::Utf8PathBuf;
use cordance_core::lock::SourceLock;
use cordance_core::pack::{CordancePack, DoctrinePin, PackTargets, ProjectIdentity};
use sha2::{Digest, Sha256};

pub struct PackConfig {
    pub target: Utf8PathBuf,
    pub output_mode: OutputMode,
    pub selected_targets: PackTargets,
    /// Override for the doctrine root. When `None`, resolved from `cordance.toml`
    /// (defaulting to `../engineering-doctrine` relative to `target`).
    pub doctrine_root: Option<Utf8PathBuf>,
    /// Optional override for the LLM provider. `None` means "fall back to
    /// `cordance.toml [llm].provider`". The string `"none"` disables LLM
    /// enrichment even when the config file enables it.
    pub llm_provider: Option<String>,
    /// Optional override for the Ollama model name. `None` means "use the
    /// adapter default" (`qwen2.5-coder:14b`). Only consulted when the resolved
    /// provider is `ollama`.
    pub ollama_model: Option<String>,
    /// When `true`, suppress human-readable progress output on stdout
    /// (e.g. "would write: AGENTS.md (2301 bytes)"). The MCP server path
    /// MUST set this — stdout is reserved for JSON-RPC frames.
    pub quiet: bool,
    /// When `true`, the pack run was initiated by `cordance cortex push`
    /// (not by an operator directly typing `cordance pack`). Suppresses the
    /// "cortex-receipt requested via --targets but pack emits no receipt"
    /// audit note that would otherwise pollute the actual receipt's
    /// `allowed_claim_language` field. Round-9 codereview #1 / regression
    /// of R8-bughunt-2: `cortex_cmd::run` builds its `PackConfig` with
    /// `cortex_receipt: true, ..Default::default()`, which makes every
    /// other target false — exactly the shape the audit-note gate fires on.
    /// This flag lets `cortex_cmd` opt out of the audit without inverting
    /// the gate logic (which would silence legitimate CLI mis-use of
    /// `--targets cortex-receipt`).
    pub from_cortex_push: bool,
    /// Whether `cortex-receipt` appeared as an explicit target token rather
    /// than coming from the ergonomic default-to-all selection.
    pub cortex_receipt_requested_explicitly: bool,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum OutputMode {
    Write,
    DryRun,
    Diff,
}

impl OutputMode {
    pub fn from_str(s: &str) -> Self {
        match s {
            "dry-run" => Self::DryRun,
            "diff" => Self::Diff,
            _ => Self::Write,
        }
    }
}

// Pack pipeline orchestrator. Round-4 codereview-8 flagged this for v1.0
// extraction into a `PackPipeline` trait; until that lands, the function is
// intentionally a sequence of well-commented steps (config → scan → doctrine
// → IR → LLM enrichment → emitters → lock → advise → evidence map) and the
// line count reflects pipeline depth, not nesting depth.
#[allow(clippy::too_many_lines)]
pub fn run(config: &PackConfig) -> Result<CordancePack> {
    // 0. Load project config. Strict: a malformed `cordance.toml` must fail
    //    the build loudly with the file path attached so the operator can
    //    fix it. Silent downgrade-to-defaults was the round-2 bughunt #3
    //    finding.
    let cfg = crate::config::Config::load_strict(&config.target)
        .with_context(|| format!("loading cordance.toml at {}", config.target))?;
    precheck_pack_metadata_destinations(config, &cfg)?;

    // 1. Detect project name + kind
    let name = detect_project_name(&config.target);
    let kind = detect_project_kind(&config.target);
    let host_os = std::env::consts::OS.to_string();
    // The axiom version is the LATEST pin cordance compiles against. We
    // capture it now so the source lock can detect axiom-algorithm drift
    // even on empty packs (see ADR 0014 / BUILD_SPEC §13).
    let axiom_pin = Some(cfg.axiom_version(&config.target));

    // 2. Scan sources. Capture any scan error so we can record it on the
    //    pack's residual_risk audit trail instead of silently degrading to
    //    an empty source list (the failure mode flagged by codereview
    //    CRITICAL — `unwrap_or_default()` makes "scan broke" look identical
    //    to "no files").
    //
    //    Round-5 bughunt CRITICAL R5-bughunt-1: drop blocked entries from the
    //    pack IR. `cordance_scan::scan_repo` surfaces blocked surfaces with
    //    `blocked: true` so `cordance scan` can render them in the operator
    //    audit report, but `pack.sources` must not contain them — otherwise
    //    every blocked file's hash would be embedded in `pack.json`, and the
    //    cordance-internal `.cordance/*` artifacts (now blocked-by-default)
    //    would create a hash self-reference loop where consecutive
    //    `cordance pack` runs produce byte-different `pack.json` outputs.
    let (sources, blocked_count, scan_error) = match cordance_scan::scan_repo(&config.target) {
        Ok(all) => {
            let total = all.len();
            let unblocked: Vec<_> = all.into_iter().filter(|r| !r.blocked).collect();
            let blocked_n = total - unblocked.len();
            if blocked_n > 0 {
                tracing::debug!(
                    blocked = blocked_n,
                    total,
                    "cordance pack: dropped blocked entries from pack.sources"
                );
            }
            (unblocked, blocked_n, None)
        }
        Err(e) => {
            tracing::warn!(error = %e, "cordance pack: source scan failed");
            (vec![], 0, Some(e.to_string()))
        }
    };
    let _ = blocked_count; // reserved for a future residual_risk note if needed

    // 3. Resolve doctrine root: explicit override wins, then config, then default.
    // Keep the configured source string (unresolved) for use in DoctrinePin.source_path
    // so that generated files don't embed absolute machine paths.
    let doctrine_source_str = config
        .doctrine_root
        .as_ref()
        .map_or_else(|| cfg.doctrine.source.clone(), |p| p.as_str().to_string());
    let doctrine_root = config
        .doctrine_root
        .clone()
        .unwrap_or_else(|| cfg.doctrine_root(&config.target));

    // 4. Load doctrine.
    //
    // Round-3 redteam #2: the previous call to `load_doctrine_or_default`
    // bypassed every hardening that lives in `load_doctrine_with_fallback`:
    //  - fallback URL validation (https-only, no userinfo, no `..`, no IP
    //    literals, no IDNA homograph silently rewriting to github.com),
    //  - SHA-keyed cache directories that defeat short-prefix collision,
    //  - explicit-pin verification against the cached HEAD,
    //  - "auto"-pin self-consistency check (round-3 bughunt #4).
    // Those were only exercised in unit tests. We now route the
    // production path through the hardened loader so a missing sibling
    // triggers a properly-validated HTTPS clone, and a tampered cache is
    // caught before any prose is read.
    //
    // A doctrine failure is non-fatal — packs still produce useful output
    // without doctrine entries — but it MUST appear on the audit trail so
    // the operator can see we silently skipped doctrine. The fallback URL
    // and the optional pin come from cordance.toml; `"auto"` is mapped to
    // `None` so `load_doctrine_with_fallback` treats it as "no pin
    // assertion" but still applies the self-consistency cross-check.
    let pin_commit: Option<&str> = if cfg.doctrine.pin_commit == "auto" {
        None
    } else {
        Some(cfg.doctrine.pin_commit.as_str())
    };
    let mut doctrine_load_warning: Option<String> = None;
    // Doctrine cache must live OUTSIDE the target tree. Round-3 scoped it to
    // `<target>/.cordance/cache/doctrine/` for per-target isolation, but that
    // exposed round-4 redteam #1: a hostile target can pre-populate that path
    // with a self-consistent fake git repo (same dirname as its HEAD commit)
    // and the auto-pin loader will load it without any network call. Moving
    // the cache to an operator-trusted location (`dirs::cache_dir()` namespace,
    // resolved by `cordance_core::paths::doctrine_cache_dir_for_url`) makes
    // it attacker-uncontrollable. Each fallback URL gets its own
    // sha256-prefixed subdirectory so different operators / forks don't
    // share cache state.
    let doctrine_cache_dir =
        cordance_core::paths::doctrine_cache_dir_for_url(&cfg.doctrine.fallback_repo);
    let doctrine_idx = match cordance_doctrine::load_doctrine_with_fallback(
        &doctrine_root,
        &cfg.doctrine.fallback_repo,
        Some(&doctrine_cache_dir),
        pin_commit,
    ) {
        Ok(idx) => idx,
        Err(err) => {
            tracing::warn!(error = %err, "doctrine load failed; using empty index");
            doctrine_load_warning = Some(format!("doctrine load failed: {err}"));
            cordance_doctrine::DoctrineIndex::empty(doctrine_root.clone())
        }
    };
    let doctrine_pins: Vec<DoctrinePin> = if let Some(commit) = &doctrine_idx.commit {
        vec![DoctrinePin {
            repo: doctrine_idx.repo.clone(),
            commit: commit.clone(),
            // Use the configured source string (relative) to avoid absolute machine paths.
            // Normalise to forward slashes so the path is portable across host OSes.
            source_path: Utf8PathBuf::from(
                format!("{doctrine_source_str}/doctrine/SEMANTIC_INDEX.md").replace('\\', "/"),
            ),
        }]
    } else {
        vec![]
    };

    // 5. Build the pack IR
    //
    // Round-8 bughunt #4 (R8-bughunt-4, four-round carryover from
    // R5-bughunt-5 / R5-bughunt-8 / R6-LOW / R7-bughunt-6): `repo_root`
    // used to be `config.target.clone()`, which on every real run is the
    // operator's host-absolute path (`C:\Users\0ryant\prj\cordance` on
    // Windows, `/home/op/projects/cordance` on Linux). That path is
    // serialised into pack.json AND mixed into `pack_id` via
    // `SourceLock::compute_from_pack` — so two operators on the same git
    // commit but different home directories produced different
    // `pack_id`s, defeating the cross-host-determinism contract the cortex
    // receipt depends on.
    //
    // The dir name itself was already captured in `pack.project.name` via
    // `detect_project_name`, so the absolute path was redundant for
    // identity purposes. Replacing it with a fixed `"."` placeholder drops
    // the host-specific bytes entirely; combined with the companion
    // placeholder mix in `compute_from_pack`, two clones of the same
    // commit now produce byte-identical `pack_id`s regardless of where
    // they live on disk.
    let mut pack = CordancePack {
        schema: cordance_core::schema::CORDANCE_PACK_V1.into(),
        project: ProjectIdentity {
            name,
            repo_root: Utf8PathBuf::from("."),
            kind,
            host_os,
            axiom_pin,
        },
        sources,
        doctrine_pins,
        targets: config.selected_targets.clone(),
        outputs: vec![],
        source_lock: SourceLock::empty(),
        advise: cordance_core::advise::AdviseReport::empty(),
        residual_risk: vec!["claim_ceiling=candidate".into()],
    };

    // 5a. If the source scan failed, surface that loudly on the audit trail.
    //     The pack still runs to completion (downstream emitters tolerate an
    //     empty source set), but the residual_risk note guarantees the
    //     condition is never silently invisible.
    if let Some(err_msg) = scan_error {
        pack.residual_risk.push(format!("scan error: {err_msg}"));
    }

    // 5a-cortex. Round-8 bughunt #2 / codereview #1: `cordance pack --targets
    //     cortex-receipt` is a no-op on the emit side (see `build_emitters`
    //     for the rationale — cortex receipts carry an attestation timestamp
    //     and break pack-level determinism if folded into pack.outputs). The
    //     flag itself is preserved because `cordance cortex push` sets it to
    //     gate target-emitter selection. But a CLI user who explicitly types
    //     `--targets cortex-receipt` and gets zero outputs deserves an
    //     operator-visible audit note instead of a silent no-op. The
    //     `cordance cortex push` callsite suppresses this note via
    //     `from_cortex_push`; direct `cordance pack --targets ...` shapes
    //     that include `cortex-receipt` get the audit note because pack
    //     itself never writes the receipt. Default-to-all selections stay
    //     quiet because the operator did not explicitly request the no-op.
    if config.selected_targets.cortex_receipt
        && config.cortex_receipt_requested_explicitly
        && !config.from_cortex_push
    {
        pack.residual_risk.push(
            "cortex-receipt requested via --targets but pack emits no receipt; \
             use `cordance cortex push` to produce the receipt"
                .into(),
        );
    }

    // 5a-bis. Same treatment for doctrine load failures (round-3 redteam #2).
    //     The pack still ships, but the operator can see we ran with an
    //     empty doctrine index and which underlying error caused it
    //     (network failure vs. pin mismatch vs. URL rejected vs. tampered
    //     cache). This is the audit-trail half of "fail loudly without
    //     aborting the pipeline".
    if let Some(warning) = doctrine_load_warning {
        pack.residual_risk.push(warning);
    }

    // 5b. Optional LLM enrichment. ADR 0002: bounded candidate prose only.
    //     This runs BEFORE emitters and writes only to `pack.residual_risk`
    //     and to a side-channel file (`.cordance/llm-candidate.json`).
    //     LLM output MUST NEVER replace emitter content.
    maybe_run_llm(config, &cfg, &mut pack);

    // 6. Collect target emitters (AGENTS.md, CLAUDE.md, .cursor/, .codex/,
    //    harness-target) and dispatch. Pack.json is dispatched separately
    //    AFTER pack.outputs is populated (round-7 codereview #1 CRITICAL).
    let emitters = build_emitters(&config.selected_targets);
    let all_outputs = dispatch_emitters(&emitters, config, &pack)?;

    pack.outputs = all_outputs;
    pack.source_lock = SourceLock::compute_from_pack(&pack);

    // 7. Persist sources.lock metadata. No-op outside Write mode.
    write_sources_lock(config, &pack)?;

    // 8. Run advise
    if let Ok(report) = cordance_advise::run_all(&pack) {
        pack.advise = report;
    }

    // 9. Emit the pack.json AND evidence map LAST so they observe the
    //    populated `pack.outputs` / `pack.source_lock` / `pack.advise`.
    //
    //    Round-7 codereview #1 CRITICAL: `PackJsonEmitter` was previously
    //    pushed into `build_emitters` and dispatched with the target emitters
    //    BEFORE `pack.outputs` and `pack.source_lock` were populated. The
    //    serialized pack.json on disk had `outputs: []` and an empty internal
    //    source_lock — silently wrong for every consumer that reads the IR.
    //    Moving pack.json into the post-emit step (parallel to the evidence
    //    map) closes that.
    //
    //    These post-step outputs are intentionally NOT folded back into
    //    `pack.outputs` (the pack and map are metadata about the pack, not
    //    target artifacts like AGENTS.md). Errors here still propagate to
    //    the CLI so the operator sees a non-zero exit code (round-7
    //    redteam #1).
    let post_emit_emitters: Vec<Box<dyn cordance_emit::TargetEmitter>> = vec![
        Box::new(cordance_emit::pack_json::PackJsonEmitter),
        Box::new(cordance_emit::evidence_map::EvidenceMapEmitter),
    ];
    let _post_outputs = dispatch_emitters(&post_emit_emitters, config, &pack)?;

    Ok(pack)
}

/// Persist `pack.source_lock` to `<target>/.cordance/sources.lock` when the
/// pack is running in Write mode. Other modes are a no-op.
///
/// Round-5 redteam #4: a hostile target can pre-plant
/// `<target>/.cordance/sources.lock` as a symlink to operator-owned files
/// (`~/.bashrc`, `~/.ssh/authorized_keys`, …). Route through
/// `safe_write_with_mkdir` so the helper refuses to follow the link.
///
/// Round-7 bughunt #3 (R7-bughunt-3): the previous shape used
/// `serde_json::to_string_pretty(...).unwrap_or_default()` and
/// `safe_write_with_mkdir(...).ok()`, which silently turned a serialise
/// failure into a 0-byte `sources.lock` (and an I/O failure into no file at
/// all). Both shapes broke the next `cordance check` with an unhelpful
/// downstream parse error rather than a real signal. Propagate both errors
/// via `?` so the operator sees the actual cause.
fn write_sources_lock(config: &PackConfig, pack: &CordancePack) -> Result<()> {
    if config.output_mode != OutputMode::Write {
        return Ok(());
    }
    let lock_path = config.target.join(".cordance").join("sources.lock");
    let lock_json =
        serde_json::to_string_pretty(&pack.source_lock).context("serialising sources.lock")?;
    cordance_core::fs::safe_write_with_mkdir(lock_path.as_std_path(), lock_json.as_bytes())
        .context("writing sources.lock")?;
    Ok(())
}

fn precheck_pack_metadata_destinations(
    config: &PackConfig,
    cfg: &crate::config::Config,
) -> Result<()> {
    if config.output_mode != OutputMode::Write {
        return Ok(());
    }

    let mut destinations = vec![
        ".cordance/sources.lock",
        ".cordance/pack.json",
        ".cordance/evidence-map.json",
    ];
    if resolve_llm_provider(config, cfg).is_some() {
        destinations.push(".cordance/llm-candidate.json");
    }

    for rel_path in destinations {
        let abs_path = config.target.join(rel_path);
        precheck_no_reparse_destination(&abs_path, rel_path, "pack metadata")?;
    }
    Ok(())
}

fn build_emitters(targets: &PackTargets) -> Vec<Box<dyn cordance_emit::TargetEmitter>> {
    let mut v: Vec<Box<dyn cordance_emit::TargetEmitter>> = vec![];
    if targets.claude_code {
        v.push(Box::new(cordance_emit::agents_md::AgentsMdEmitter));
        v.push(Box::new(cordance_emit::claude_md::ClaudeMdEmitter));
    }
    if targets.cursor {
        v.push(Box::new(cordance_emit::cursor::CursorEmitter));
    }
    if targets.codex {
        v.push(Box::new(cordance_emit::codex::CodexEmitter));
    }
    if targets.axiom_harness_target {
        v.push(Box::new(
            cordance_emit::harness_target::HarnessTargetEmitter,
        ));
    }
    // The `cortex_receipt` flag exists in `PackTargets` but is intentionally
    // NOT plumbed as a `TargetEmitter` here. Round-7 codereview #2 asked to
    // either plumb or remove. The round-7 fix lane initially plumbed it via
    // a `CortexReceiptEmitter`, but doing so broke `pack.json` determinism:
    // `cordance_cortex::build_receipt` legitimately stamps the receipt with
    // `Utc::now()` (cortex receipts are operator-initiated attestations of
    // a submission moment, NOT byte-deterministic pack artifacts), so two
    // consecutive `cordance pack` runs produced byte-different
    // `.cordance/cortex-receipt.json`, which propagated into pack.outputs
    // → pack.json → source_lock and broke runs-2-3 byte-determinism.
    //
    // The right routing is: `cordance pack` produces the deterministic
    // target outputs (AGENTS.md, CLAUDE.md, .cursor/, .codex/,
    // pai-axiom-project-harness-target.json). The cortex receipt is
    // produced by the dedicated `cordance cortex push` subcommand
    // (see `cortex_cmd.rs`), which takes the same pack as input and
    // applies a wall-clock at submission time. `cordance pack --targets
    // cortex-receipt` is therefore a no-op on the emitter side; the
    // `cortex_receipt: true` flag is preserved because `cortex_cmd::run`
    // uses it to signal "this pack run is for a cortex push" and bypass
    // unrelated target emitters.
    let _ = targets.cortex_receipt;
    // NOTE: `PackJsonEmitter` is NOT pushed here. It runs as a post-step in
    // `pack_cmd::run` AFTER `pack.outputs` / `pack.source_lock` are
    // populated, so the serialized pack.json reflects the final pack state
    // rather than an empty pre-emit snapshot. Round-7 codereview #1 CRITICAL.
    v
}

/// Round-7 redteam #1 CRITICAL: `dispatch_emitters` used to print emitter
/// failures via `eprintln!` and continue. Failed emits (including
/// `safe_write` refusals against attacker-planted symlinks/junctions) would
/// produce a "succeed-loud-but-exit-0" outcome: stderr complained about the
/// emitter but the pack reported `"N outputs written"` and the process
/// exited 0. The operator could not see the failure. Now every emitter
/// error stops dispatch and propagates as `anyhow::Error` so the CLI
/// surfaces it with a non-zero exit code.
///
/// Round-8 redteam #1 CRITICAL: the round-7 `?`-short-circuit shape closed
/// the silent-success class but opened an **atomicity gap**. If emitter 1
/// succeeded and emitter 2 refused (e.g. `CLAUDE.md` planted as a junction),
/// emitter 1's output landed on disk while `pack.json`, `sources.lock`, and
/// `evidence-map.json` never wrote — `cordance check` then reported
/// permanent drift. The fix is a 3-phase Write dispatch:
///
///   Phase 1 (render):     call `emitter.render(pack)` for every emitter,
///                         collecting `(emitter_name, rel_path, bytes)`.
///                         No I/O — pure computation. Render failures
///                         propagate before any write.
///   Phase 2 (pre-check):  scan the ancestor chain of every destination
///                         path via `precheck_no_reparse_point_ancestor`.
///                         A planted junction/symlink anywhere in the
///                         chain fails the batch before any emitter
///                         actually writes.
///   Phase 3 (commit):     run `emitter.emit(pack, repo_root)` per
///                         emitter. Most failures have been caught in
///                         Phase 2; the residual race (disk fills
///                         mid-write, permission flip between phases) is
///                         unavoidable, and the commit-phase failure
///                         logs which emitters wrote before the failure
///                         so the operator sees the partial state.
///
/// Round-8 redteam #4: refusal errors carry a `SymlinkRefusal` payload
/// whose Display includes the ancestor path. The default `anyhow::Context`
/// chain printer drops that payload in favour of the kernel
/// `(os error 5)` line; we therefore detect refusals explicitly (via
/// `extract_symlink_refusal` / direct downcast) and construct a message
/// that preserves the ancestor path for the operator's diagnostic.
///
/// `DryRun` and `Diff` modes do not write to disk, so they keep the
/// round-7 single-pass shape with `?` short-circuit on `plan()` failures.
/// Per-emitter render result captured at Phase 1. The tuple shape is
/// `(emitter_name, [(rel_path, rendered_bytes)])` — Phase 2 walks it for
/// the pre-check, Phase 3 ignores it and re-runs `emit()`.
type RenderBatch = Vec<(&'static str, Vec<(Utf8PathBuf, Vec<u8>)>)>;

fn dispatch_emitters(
    emitters: &[Box<dyn cordance_emit::TargetEmitter>],
    config: &PackConfig,
    pack: &CordancePack,
) -> Result<Vec<cordance_core::pack::PackOutput>> {
    match config.output_mode {
        OutputMode::Write => dispatch_emitters_write(emitters, config, pack),
        OutputMode::DryRun => dispatch_emitters_dry_run(emitters, config, pack),
        OutputMode::Diff => dispatch_emitters_diff(emitters, config, pack),
    }
}

/// Phase 1 + 2 + 3 dispatch for Write mode. See `dispatch_emitters`
/// docs for the round-8 redteam #1 / #4 contract.
fn dispatch_emitters_write(
    emitters: &[Box<dyn cordance_emit::TargetEmitter>],
    config: &PackConfig,
    pack: &CordancePack,
) -> Result<Vec<cordance_core::pack::PackOutput>> {
    let rendered_per_emitter = render_all(emitters, pack)?;
    precheck_all_destinations(&rendered_per_emitter, &config.target)?;
    commit_all(emitters, config, pack)
}

/// Phase 1 — RENDER. Pure compute: every emitter's `render()` is called
/// and the resulting `(rel_path, bytes)` tuples are collected. A render
/// failure aborts the batch with no I/O attempted (round-8 redteam #1).
fn render_all(
    emitters: &[Box<dyn cordance_emit::TargetEmitter>],
    pack: &CordancePack,
) -> Result<RenderBatch> {
    let mut rendered_per_emitter: RenderBatch = Vec::with_capacity(emitters.len());
    for emitter in emitters {
        let rendered = emitter
            .render(pack)
            .with_context(|| format!("emitter '{}' render failed", emitter.name()))?;
        rendered_per_emitter.push((emitter.name(), rendered));
    }
    Ok(rendered_per_emitter)
}

/// Phase 2 — PRE-CHECK. Scan every destination's ancestor chain for
/// reparse points BEFORE any emitter writes. A planted junction at
/// `<target>/.cordance/` or a symlinked `CLAUDE.md` is refused here so
/// the disk stays consistent (round-8 redteam #1). On refusal we
/// surface the structured `SymlinkRefusal` payload (round-8 redteam #4)
/// so the operator's stderr shows the ancestor path, not just
/// `(os error 5)`.
fn precheck_all_destinations(
    rendered_per_emitter: &RenderBatch,
    target: &Utf8PathBuf,
) -> Result<()> {
    for (emitter_name, rendered) in rendered_per_emitter {
        for (rel_path, _bytes) in rendered {
            let abs_path = target.join(rel_path);
            let owner = format!("emitter '{emitter_name}'");
            precheck_no_reparse_destination(&abs_path, rel_path.as_str(), &owner)?;
        }
    }
    Ok(())
}

fn precheck_no_reparse_destination(
    abs_path: &Utf8PathBuf,
    rel_path: &str,
    owner: &str,
) -> Result<()> {
    if let Err(io_err) =
        cordance_core::fs::precheck_no_reparse_point_ancestor(abs_path.as_std_path())
    {
        let refusal_path = io_err
            .get_ref()
            .and_then(|e| e.downcast_ref::<cordance_core::fs::SymlinkRefusal>())
            .map(|r| r.path.display().to_string());
        if let Some(p) = refusal_path {
            // Surface the ancestor path explicitly — anyhow's chain printer
            // drops the SymlinkRefusal Display in favour of the kernel error,
            // so we construct the message here so the operator sees the
            // junction.
            return Err(anyhow::anyhow!(
                "{owner} refused before write: \
                 refusing to write through symlink/reparse-point at {p} \
                 (destination: {rel_path})"
            ));
        }
        return Err(
            anyhow::Error::new(io_err).context(format!("{owner} pre-check failed for {rel_path}"))
        );
    }
    Ok(())
}

/// Phase 3 — COMMIT. Now run the actual `emit()`. Most refusal shapes
/// were caught in Phase 2; what remains is the unavoidable race (disk
/// fills mid-write, permission flip between Phase 2 and Phase 3) or a
/// fence-merge that reads freshly on-disk state (round-4 bughunt #3).
/// On commit-phase failure we log the partial state to stderr so the
/// operator sees which emitters succeeded before the failure (round-8
/// redteam #1 partial-state visibility).
fn commit_all(
    emitters: &[Box<dyn cordance_emit::TargetEmitter>],
    config: &PackConfig,
    pack: &CordancePack,
) -> Result<Vec<cordance_core::pack::PackOutput>> {
    let mut all_outputs = Vec::new();
    let mut succeeded: Vec<String> = Vec::with_capacity(emitters.len());
    for emitter in emitters {
        match emitter.emit(pack, &config.target) {
            Ok(outputs) => {
                succeeded.push(emitter.name().to_string());
                all_outputs.extend(outputs);
            }
            Err(err) => {
                if !succeeded.is_empty() {
                    eprintln!(
                        "cordance: commit-phase failure after {} emitter(s) wrote: {}",
                        succeeded.len(),
                        succeeded.join(", ")
                    );
                }
                // Surface the structured refusal path if the commit-
                // phase failure was nonetheless a symlink refusal
                // (e.g. attacker raced a symlink between Phase 2 and
                // Phase 3).
                if let cordance_emit::EmitError::Io(io_err) = &err {
                    if let Some(refusal) = io_err
                        .get_ref()
                        .and_then(|e| e.downcast_ref::<cordance_core::fs::SymlinkRefusal>())
                    {
                        let emitter_name = emitter.name();
                        let path_display = refusal.path.display();
                        return Err(anyhow::anyhow!(
                            "emitter '{emitter_name}' failed at commit phase: \
                             refusing to write through symlink/reparse-point at {path_display}"
                        ));
                    }
                }
                let emitter_name = emitter.name().to_string();
                return Err(anyhow::Error::new(err)
                    .context(format!("emitter '{emitter_name}' failed at commit phase")));
            }
        }
    }
    Ok(all_outputs)
}

/// `DryRun` path: `plan()` every emitter, print "would write:" lines,
/// accumulate `PackOutput` metadata. No I/O.
fn dispatch_emitters_dry_run(
    emitters: &[Box<dyn cordance_emit::TargetEmitter>],
    config: &PackConfig,
    pack: &CordancePack,
) -> Result<Vec<cordance_core::pack::PackOutput>> {
    let mut all_outputs = Vec::new();
    for emitter in emitters {
        // Round-4 bughunt #3: plan() now takes repo_root so it can
        // apply the same fence-merge logic as emit(). Otherwise the
        // sha plan records (rendered) and the sha emit writes
        // (merged) diverge, and `cordance check` reports spurious
        // drift on every fenced output after the first pack.
        let outputs = emitter
            .plan(pack, &config.target)
            .with_context(|| format!("emitter '{}' plan failed", emitter.name()))?;
        if !config.quiet {
            for o in &outputs {
                println!("would write: {} ({} bytes)", o.path, o.bytes);
            }
        }
        all_outputs.extend(outputs);
    }
    Ok(all_outputs)
}

/// Diff path: `plan()` every emitter, compare planned sha vs on-disk
/// sha, emit `unchanged:` / `changed:` / `new:` lines. No I/O writes.
fn dispatch_emitters_diff(
    emitters: &[Box<dyn cordance_emit::TargetEmitter>],
    config: &PackConfig,
    pack: &CordancePack,
) -> Result<Vec<cordance_core::pack::PackOutput>> {
    let mut all_outputs = Vec::new();
    for emitter in emitters {
        let outputs = emitter
            .plan(pack, &config.target)
            .with_context(|| format!("emitter '{}' diff-plan failed", emitter.name()))?;
        for o in &outputs {
            let abs = config.target.join(&o.path);
            let line = if abs.exists() {
                let on_disk = std::fs::read_to_string(&abs).unwrap_or_default();
                let on_disk_sha = hex::encode(Sha256::digest(on_disk.as_bytes()));
                if on_disk_sha == o.sha256 {
                    format!("unchanged: {}", o.path)
                } else {
                    format!("changed: {}", o.path)
                }
            } else {
                format!("new: {}", o.path)
            };
            if !config.quiet {
                println!("{line}");
            }
            all_outputs.push(o.clone());
        }
    }
    Ok(all_outputs)
}

/// Read `{root}/Cargo.toml` (when present) and return the project name from
/// either `[package].name` or `[workspace.package].name`. Falls back to the
/// canonicalised directory name, then the raw last path component.
///
/// Replaces the round-1/-2/-3-flagged hand-rolled line scanner. The `toml`
/// crate handles `name = "..."`, `name="..."` (no space), workspace inheritance
/// (`[workspace.package].name`), and quoting subtleties uniformly.
fn detect_project_name(root: &Utf8PathBuf) -> String {
    if let Some(name) = read_cargo_package_name(root) {
        return name;
    }
    // Fallback: canonicalize to resolve `.` and get the real directory name.
    if let Ok(canonical) = std::fs::canonicalize(root.as_std_path()) {
        if let Some(dir_name) = canonical.file_name() {
            if let Some(s) = dir_name.to_str() {
                return s.to_string();
            }
        }
    }
    root.file_name().unwrap_or("unknown").to_string()
}

/// Helper: deserialise `{root}/Cargo.toml` and pull out the project name.
///
/// Returns `None` when the file is absent, unreadable, malformed, or simply
/// declares neither `[package].name` nor `[workspace.package].name`. The
/// minimal struct shape ignores every other Cargo field so a real Cargo.toml
/// with `[dependencies]`, `[features]`, `[[bin]]`, etc. parses cleanly.
fn read_cargo_package_name(root: &Utf8PathBuf) -> Option<String> {
    #[derive(serde::Deserialize, Default)]
    struct PkgSection {
        name: Option<String>,
    }
    #[derive(serde::Deserialize, Default)]
    struct WorkspaceSection {
        package: Option<PkgSection>,
    }
    #[derive(serde::Deserialize, Default)]
    struct CargoToml {
        package: Option<PkgSection>,
        workspace: Option<WorkspaceSection>,
    }

    let cargo = root.join("Cargo.toml");
    if !cargo.exists() {
        return None;
    }
    let content = std::fs::read_to_string(&cargo).ok()?;
    let parsed: CargoToml = toml::from_str(&content).ok()?;

    if let Some(pkg) = parsed.package {
        if let Some(name) = pkg.name {
            if !name.is_empty() {
                return Some(name);
            }
        }
    }
    if let Some(ws) = parsed.workspace {
        if let Some(pkg) = ws.package {
            if let Some(name) = pkg.name {
                if !name.is_empty() {
                    return Some(name);
                }
            }
        }
    }
    None
}

fn detect_project_kind(root: &Utf8PathBuf) -> String {
    if root.join("Cargo.toml").exists() {
        return "rust-workspace".into();
    }
    if root.join("package.json").exists() {
        return "typescript-node".into();
    }
    if root.join("pyproject.toml").exists() || root.join("setup.py").exists() {
        return "python".into();
    }
    if root.join("go.mod").exists() {
        return "go".into();
    }
    "unknown".into()
}

/// Resolve the effective LLM provider from CLI override + project config.
///
/// CLI override wins over `cordance.toml`. `"none"` (explicit) and `None`
/// (absent) both disable enrichment.
fn resolve_llm_provider(config: &PackConfig, cfg: &crate::config::Config) -> Option<String> {
    config
        .llm_provider
        .clone()
        .or_else(|| Some(cfg.llm.provider.clone()))
        .filter(|p| p != "none")
}

/// Run the optional LLM enrichment pass. ADR 0002: candidate prose only.
///
/// All output flows to:
///   - `pack.residual_risk` — an audit note that a candidate was attached
///   - `{target}/.cordance/llm-candidate.json` — the raw candidate document
///
/// Emitters never see this content. Network or schema failures are downgraded
/// to a `warning` on stderr and a `residual_risk` note; they never abort `pack`.
fn maybe_run_llm(config: &PackConfig, cfg: &crate::config::Config, pack: &mut CordancePack) {
    let Some(provider) = resolve_llm_provider(config, cfg) else {
        return;
    };

    if provider != "ollama" {
        pack.residual_risk.push(format!(
            "LLM provider '{provider}' is not supported; skipping enrichment"
        ));
        return;
    }

    // ADR 0015: build the adapter from [llm.ollama] config; CLI --ollama-model
    // overrides the configured model when provided.
    let mut adapter = cordance_llm::OllamaAdapter::from_config(&cfg.llm.ollama);
    if let Some(override_model) = &config.ollama_model {
        override_model.clone_into(&mut adapter.model);
    }
    let base_url = adapter.base_url.clone();
    let model = adapter.model.clone();

    if !adapter.is_available() {
        eprintln!(
            "cordance: warning — Ollama not reachable at {base_url}, skipping LLM enrichment"
        );
        pack.residual_risk.push(format!(
            "LLM enrichment skipped: ollama/{model} at {base_url} unreachable"
        ));
        return;
    }

    // Bound the source set: take up to 20 non-blocked sources. The adapter is
    // strict about citation, so we use the same slice for both the prompt and
    // the citation allow-list.
    let sources: Vec<_> = pack
        .sources
        .iter()
        .filter(|s| !s.blocked)
        .take(20)
        .cloned()
        .collect();
    let source_ids: Vec<String> = sources.iter().map(|s| s.id.clone()).collect();

    let prompt = cordance_llm::prompt::bounded_pack_summary_prompt(
        &sources,
        &[],
        "Summarise this project's main purpose in one paragraph as a candidate observation.",
    );

    // Round-2 fix-A: wire 4-gram grounding. The validator was already in
    // place but `generate()` (no grounding) was being called, so the
    // hardening never reached production. Load the cited source bodies
    // (bounded per-file to keep memory and prompt size predictable) and
    // hand them to `generate_with_grounding`.
    let source_content_map = load_source_content_map(pack, &source_ids);

    match adapter.generate_with_grounding(&prompt, &source_ids, &source_content_map) {
        Ok(candidate) => {
            let claim_count = candidate.claims.len();
            pack.residual_risk.push(format!(
                "LLM candidate prose attached: {claim_count} claim(s) from ollama/{model}"
            ));

            let candidate_path = config.target.join(".cordance").join("llm-candidate.json");
            match serde_json::to_string_pretty(&candidate) {
                Ok(json) => {
                    // Round-5 redteam #4: route through the symlink-refusing
                    // helper so a hostile target can't redirect this write
                    // at the operator's own files. `safe_write_with_mkdir`
                    // handles parent-dir creation, so the explicit
                    // `create_dir_all` above is no longer needed.
                    if let Err(e) = cordance_core::fs::safe_write_with_mkdir(
                        candidate_path.as_std_path(),
                        json.as_bytes(),
                    ) {
                        eprintln!("cordance: warning — failed to write {candidate_path}: {e}");
                    }
                }
                Err(e) => {
                    eprintln!("cordance: warning — failed to serialise LLM candidate: {e}");
                }
            }
        }
        Err(e) => {
            eprintln!("cordance: warning — Ollama generation failed: {e}");
            pack.residual_risk
                .push(format!("LLM enrichment failed: {e}"));
        }
    }
}

/// Read the cited source files into a `{source_id → content}` map suitable
/// for [`cordance_llm::OllamaAdapter::generate_with_grounding`].
///
/// The validator only needs enough text to compare against 4-gram windows of
/// each claim, so we cap each entry at 4 KiB. This keeps the prompt-adjacent
/// memory bounded even on repos with large source files and keeps the
/// grounding check cheap.
///
/// Blocked sources are skipped (they would not have been cited anyway since
/// the prompt builder filters them out). I/O errors are silently ignored
/// because a missing file simply means the validator will not be able to
/// ground a claim against it — that is the correct behaviour, not a fatal
/// pack error.
fn load_source_content_map(pack: &CordancePack, cited_ids: &[String]) -> HashMap<String, String> {
    const MAX_PER_SOURCE: u64 = 4 * 1024;

    let mut map: HashMap<String, String> = HashMap::with_capacity(cited_ids.len());
    for id in cited_ids {
        let Some(record) = pack.sources.iter().find(|s| &s.id == id) else {
            continue;
        };
        if record.blocked {
            continue;
        }
        let abs = pack.project.repo_root.join(&record.path);
        let Ok(file) = std::fs::File::open(abs.as_std_path()) else {
            continue;
        };
        let mut buf = String::new();
        if file.take(MAX_PER_SOURCE).read_to_string(&mut buf).is_ok() {
            map.insert(id.clone(), buf);
        }
    }
    map
}

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

    fn write_cargo(content: &str) -> (tempfile::TempDir, Utf8PathBuf) {
        let dir = tempfile::tempdir().expect("tempdir");
        let target = Utf8PathBuf::from_path_buf(dir.path().to_path_buf()).expect("tempdir is utf8");
        std::fs::write(target.join("Cargo.toml"), content).expect("write Cargo.toml");
        (dir, target)
    }

    fn temp_utf8_dir() -> (tempfile::TempDir, Utf8PathBuf) {
        let dir = tempfile::tempdir().expect("tempdir");
        let target = Utf8PathBuf::from_path_buf(dir.path().to_path_buf()).expect("tempdir is utf8");
        (dir, target)
    }

    fn config_for_test(
        target: &Utf8PathBuf,
        output_mode: OutputMode,
        selected_targets: PackTargets,
        doctrine_root: &Utf8PathBuf,
        from_cortex_push: bool,
        cortex_receipt_requested_explicitly: bool,
    ) -> PackConfig {
        PackConfig {
            target: target.clone(),
            output_mode,
            selected_targets,
            doctrine_root: Some(doctrine_root.clone()),
            llm_provider: Some("none".to_string()),
            ollama_model: None,
            quiet: true,
            from_cortex_push,
            cortex_receipt_requested_explicitly,
        }
    }

    fn cortex_receipt_noop_note() -> &'static str {
        "cortex-receipt requested via --targets but pack emits no receipt"
    }

    #[test]
    fn detect_project_name_reads_package_section() {
        let (_d, target) = write_cargo("[package]\nname = \"my-crate\"\nversion = \"0.1.0\"\n");
        assert_eq!(detect_project_name(&target), "my-crate");
    }

    #[test]
    fn detect_project_name_handles_no_space_around_equals() {
        // The hand-rolled scanner used to break on `name="x"` (no whitespace).
        let (_d, target) = write_cargo("[package]\nname=\"compact\"\n");
        assert_eq!(detect_project_name(&target), "compact");
    }

    #[test]
    fn detect_project_name_reads_workspace_package_section() {
        // Cargo workspace inheritance shape that the line scanner missed.
        let (_d, target) = write_cargo(
            "[workspace]\nmembers = [\"foo\"]\n\n[workspace.package]\nname = \"ws-name\"\nversion = \"0.1.0\"\n",
        );
        assert_eq!(detect_project_name(&target), "ws-name");
    }

    #[test]
    fn detect_project_name_prefers_package_over_workspace_package() {
        // When both are present, `[package].name` wins (it's the crate-level
        // override that ws inheritance falls back from).
        let (_d, target) = write_cargo(
            "[package]\nname = \"actual\"\n\n[workspace.package]\nname = \"inherited\"\n",
        );
        assert_eq!(detect_project_name(&target), "actual");
    }

    #[test]
    fn detect_project_name_ignores_bin_name() {
        // The old scanner would match `name = "..."` inside `[[bin]]`. The
        // toml-typed parser correctly scopes to `[package]`.
        let (_d, target) = write_cargo(
            "[package]\nname = \"libname\"\n\n[[bin]]\nname = \"binname\"\npath = \"src/main.rs\"\n",
        );
        assert_eq!(detect_project_name(&target), "libname");
    }

    #[test]
    fn detect_project_name_falls_back_when_cargo_toml_absent() {
        let dir = tempfile::tempdir().expect("tempdir");
        let target = Utf8PathBuf::from_path_buf(dir.path().to_path_buf()).expect("tempdir is utf8");
        // Without Cargo.toml we expect the canonical directory name as the
        // fallback. That directory name is the tempdir's last component.
        let detected = detect_project_name(&target);
        let expected = target.file_name().unwrap_or("unknown").to_string();
        // tempdir canonicalisation can resolve the path through `/private` on
        // macOS, so allow either the raw last component or any non-empty
        // string — the contract is "non-empty, not a hand-rolled placeholder".
        assert!(!detected.is_empty());
        assert!(
            detected == expected
                || std::fs::canonicalize(target.as_std_path())
                    .ok()
                    .and_then(|p| p.file_name().map(|s| s.to_string_lossy().to_string()))
                    .is_some_and(|c| detected == c),
            "detected={detected} expected={expected}"
        );
    }

    #[test]
    fn detect_project_name_falls_back_when_cargo_toml_malformed() {
        // Unparseable TOML must not panic — fall back to the dir name.
        let (_d, target) = write_cargo("this is not = = valid toml");
        let detected = detect_project_name(&target);
        assert!(!detected.is_empty(), "must produce some non-empty fallback");
    }

    #[test]
    fn detect_project_name_falls_back_when_name_missing() {
        let (_d, target) = write_cargo("[package]\nversion = \"0.1.0\"\n");
        let detected = detect_project_name(&target);
        assert!(!detected.is_empty());
        // The result must not be `version` or any literal scraped from the toml.
        assert_ne!(detected, "0.1.0");
    }

    /// Round-7 bughunt #3 (R7-bughunt-3): the previous `write_sources_lock`
    /// shape used `unwrap_or_default()` on the serde result and `.ok()` on
    /// the write call, silently turning either failure into a 0-byte
    /// `sources.lock` (or no file at all). The fixed shape propagates both
    /// errors via `?`. This test pins the I/O-failure half of the contract:
    /// pre-plant `<target>/.cordance` as a REGULAR FILE, so the helper's
    /// `create_dir_all(<target>/.cordance)` must error (can't make a
    /// directory where a file already lives) — and `write_sources_lock`
    /// must surface that as `Err`, not `Ok(())`.
    ///
    /// The serialise-failure half cannot be exercised in a unit test today
    /// because every field of `SourceLock` is plain-JSON-friendly (`String`,
    /// `Option<String>`, `Vec<SourceLockEntry>`). The contract still
    /// matters: a future schema change that adds a non-serialisable shape
    /// (a `Map<NonSerialize, _>`, an `f64::NAN`, …) would otherwise
    /// silently land a 0-byte lock on every pack — the `?` in
    /// `to_string_pretty(...).context(...)?` is the load-bearing line.
    #[test]
    fn write_sources_lock_propagates_io_failure_instead_of_swallowing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let target = Utf8PathBuf::from_path_buf(dir.path().to_path_buf()).expect("tempdir is utf8");

        // Plant `.cordance` as a regular FILE at the target root. The
        // helper's `create_dir_all(<target>/.cordance)` cannot succeed
        // because a non-directory file already occupies that path.
        std::fs::write(target.join(".cordance"), b"blocker").expect("seed blocker file");

        let config = PackConfig {
            target: target.clone(),
            output_mode: OutputMode::Write,
            selected_targets: PackTargets::default(),
            doctrine_root: None,
            llm_provider: None,
            ollama_model: None,
            quiet: true,
            from_cortex_push: false,
            cortex_receipt_requested_explicitly: false,
        };
        let pack = CordancePack {
            schema: "test".into(),
            project: ProjectIdentity {
                name: "test".into(),
                kind: "unknown".into(),
                repo_root: target,
                host_os: "test".into(),
                axiom_pin: None,
            },
            sources: vec![],
            doctrine_pins: vec![],
            targets: PackTargets::default(),
            outputs: vec![],
            source_lock: SourceLock::empty(),
            advise: cordance_core::advise::AdviseReport::empty(),
            residual_risk: vec![],
        };

        let result = write_sources_lock(&config, &pack);
        assert!(
            result.is_err(),
            "expected write_sources_lock to surface the create_dir_all I/O failure, got Ok"
        );
        let err = result.unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("writing sources.lock"),
            "error chain must mention `writing sources.lock`; got: {msg}"
        );
    }

    #[test]
    fn cortex_push_pack_config_omits_cortex_receipt_noop_audit_note() {
        let (_target_dir, target) = temp_utf8_dir();
        let (_doctrine_dir, doctrine_root) = temp_utf8_dir();
        let config = config_for_test(
            &target,
            OutputMode::DryRun,
            PackTargets {
                cortex_receipt: true,
                ..Default::default()
            },
            &doctrine_root,
            true,
            true,
        );

        let pack = run(&config).expect("cortex-push pack run should succeed");

        assert!(
            !pack
                .residual_risk
                .iter()
                .any(|risk| risk.contains(cortex_receipt_noop_note())),
            "cordance cortex push must not pollute receipt claim language via residual_risk: {:?}",
            pack.residual_risk
        );
    }

    #[test]
    fn pack_cli_multi_target_cortex_receipt_records_noop_audit_note() {
        let (_target_dir, target) = temp_utf8_dir();
        let (_doctrine_dir, doctrine_root) = temp_utf8_dir();
        let config = config_for_test(
            &target,
            OutputMode::DryRun,
            PackTargets {
                axiom_harness_target: true,
                cortex_receipt: true,
                ..Default::default()
            },
            &doctrine_root,
            false,
            true,
        );

        let pack = run(&config).expect("pack run should succeed");

        assert!(
            pack.residual_risk
                .iter()
                .any(|risk| risk.contains(cortex_receipt_noop_note())),
            "cordance pack with cortex-receipt in any target set must record no-op audit note; got {:?}",
            pack.residual_risk
        );
    }

    #[test]
    fn default_all_targets_omits_cortex_receipt_noop_audit_note() {
        let (_target_dir, target) = temp_utf8_dir();
        let (_doctrine_dir, doctrine_root) = temp_utf8_dir();
        let config = config_for_test(
            &target,
            OutputMode::DryRun,
            PackTargets::all(),
            &doctrine_root,
            false,
            false,
        );

        let pack = run(&config).expect("default all-target pack run should succeed");

        assert!(
            !pack
                .residual_risk
                .iter()
                .any(|risk| risk.contains(cortex_receipt_noop_note())),
            "default all-target pack must not pretend --targets cortex-receipt was requested: {:?}",
            pack.residual_risk
        );
    }

    // -----------------------------------------------------------------
    // Round-8 redteam #1 (CRITICAL): `dispatch_emitters` is a 3-phase
    // render → pre-check → commit pattern. A planted symlink/junction
    // ancestor on ANY destination must fail the WHOLE batch BEFORE any
    // emitter writes. Pin the contract: no file lands on disk and no
    // file lands in the escape tree.
    // -----------------------------------------------------------------

    /// Minimal test emitter. Renders deterministic bytes at fixed
    /// repo-relative paths so the dispatcher's phase 1/2/3 surfaces
    /// can be exercised without spinning up the real emitter set.
    ///
    /// `#[cfg(unix)]`: the round-8 redteam #1 / #4 integration tests
    /// below require a planted symlink, which the test environment can
    /// only reliably create on POSIX without elevated privilege. The
    /// equivalent Windows path is covered indirectly by the
    /// `cordance-core::fs` reparse-point tests (junction-via-mklink).
    #[cfg(unix)]
    struct FakeEmitter {
        name: &'static str,
        outputs: Vec<(Utf8PathBuf, Vec<u8>)>,
    }

    #[cfg(unix)]
    impl cordance_emit::TargetEmitter for FakeEmitter {
        fn name(&self) -> &'static str {
            self.name
        }
        fn render(
            &self,
            _pack: &CordancePack,
        ) -> Result<Vec<(Utf8PathBuf, Vec<u8>)>, cordance_emit::EmitError> {
            Ok(self.outputs.clone())
        }
    }

    #[cfg(unix)]
    fn empty_pack(target: Utf8PathBuf) -> CordancePack {
        CordancePack {
            schema: "test".into(),
            project: ProjectIdentity {
                name: "test".into(),
                kind: "unknown".into(),
                repo_root: target,
                host_os: "test".into(),
                axiom_pin: None,
            },
            sources: vec![],
            doctrine_pins: vec![],
            targets: PackTargets::default(),
            outputs: vec![],
            source_lock: SourceLock::empty(),
            advise: cordance_core::advise::AdviseReport::empty(),
            residual_risk: vec![],
        }
    }

    /// Round-8 redteam #1: plant `<tempdir>/.cordance` as a symlink to
    /// an escape tree, dispatch a 2-emitter list where emitter A writes
    /// to `AGENTS.md` (root-level, clean) and emitter B writes to
    /// `.cordance/pack.json` (junction-redirected). Phase 2 pre-check
    /// must refuse the batch BEFORE phase 3 runs, so:
    ///   - `AGENTS.md` MUST NOT exist on disk (no write happened).
    ///   - The escape tree MUST be empty.
    ///   - The error must surface the SymlinkRefusal's ancestor path.
    #[cfg(unix)]
    #[test]
    fn pre_check_fails_with_planted_symlink_ancestor_before_any_write() {
        use std::os::unix::fs::symlink;

        let dir = tempfile::tempdir().expect("tempdir");
        let target = Utf8PathBuf::from_path_buf(dir.path().to_path_buf()).expect("tempdir is utf8");
        let escape = tempfile::tempdir().expect("escape tempdir");

        // Plant `<target>/.cordance` as a symlink to the escape tree.
        // Any write that resolves through `.cordance/` will land inside
        // the escape tree if the helper isn't careful — which is
        // exactly the threat model.
        let dotcordance = target.as_std_path().join(".cordance");
        symlink(escape.path(), &dotcordance).expect("plant .cordance symlink");

        let emitters: Vec<Box<dyn cordance_emit::TargetEmitter>> = vec![
            Box::new(FakeEmitter {
                name: "fake:clean",
                outputs: vec![(Utf8PathBuf::from("AGENTS.md"), b"clean-bytes".to_vec())],
            }),
            Box::new(FakeEmitter {
                name: "fake:hostile",
                outputs: vec![(
                    Utf8PathBuf::from(".cordance/pack.json"),
                    b"would-write-through-junction".to_vec(),
                )],
            }),
        ];
        let config = PackConfig {
            target: target.clone(),
            output_mode: OutputMode::Write,
            selected_targets: PackTargets::default(),
            doctrine_root: None,
            llm_provider: None,
            ollama_model: None,
            quiet: true,
            from_cortex_push: false,
            cortex_receipt_requested_explicitly: false,
        };
        let pack = empty_pack(target.clone());

        let result = dispatch_emitters(&emitters, &config, &pack);
        let err = result.expect_err("planted symlink ancestor must fail dispatch");
        let msg = format!("{err:#}");

        // The error must name the offending ancestor — the round-8
        // redteam #4 diagnostic-preservation contract. The Display impl
        // on SymlinkRefusal includes "symlink/reparse-point" so we look
        // for either that or the literal junction path.
        assert!(
            msg.contains("symlink") || msg.contains("reparse-point"),
            "error must indicate refusal class; got: {msg}"
        );
        assert!(
            msg.contains(".cordance"),
            "error must name the offending ancestor path; got: {msg}"
        );

        // No write may have happened. The clean emitter's destination
        // (AGENTS.md at the target root) must not exist.
        let agents_md = target.as_std_path().join("AGENTS.md");
        assert!(
            !agents_md.exists(),
            "Phase-2 pre-check must fail BEFORE any emitter writes; \
             AGENTS.md must not be on disk"
        );

        // The escape tree must also be empty — no bytes leaked through
        // the symlink.
        let escape_entries: Vec<_> = std::fs::read_dir(escape.path())
            .expect("read escape")
            .collect();
        assert!(
            escape_entries.is_empty(),
            "no bytes may have leaked through the symlink; escape tree \
             must be empty, found: {escape_entries:?}"
        );
    }

    /// Round-8 redteam #4: companion test. The CLI's error surface must
    /// preserve the ancestor path even when `with_context` is layered on
    /// top of the io::Error. We exercise this through `dispatch_emitters`
    /// because that's where the operator-visible diagnostic is produced.
    #[cfg(unix)]
    #[test]
    fn dispatch_error_preserves_symlink_refusal_ancestor_path() {
        use std::os::unix::fs::symlink;

        let dir = tempfile::tempdir().expect("tempdir");
        let target = Utf8PathBuf::from_path_buf(dir.path().to_path_buf()).expect("tempdir is utf8");
        let escape = tempfile::tempdir().expect("escape tempdir");

        // Plant `<target>/AGENTS.md` as a symlink — the leaf is the
        // refused ancestor in this shape.
        let agents_md = target.as_std_path().join("AGENTS.md");
        let dest = escape.path().join("operator.txt");
        std::fs::write(&dest, b"operator owned").expect("seed");
        symlink(&dest, &agents_md).expect("plant AGENTS.md symlink");

        let emitters: Vec<Box<dyn cordance_emit::TargetEmitter>> = vec![Box::new(FakeEmitter {
            name: "fake:hostile",
            outputs: vec![(Utf8PathBuf::from("AGENTS.md"), b"attacker-bytes".to_vec())],
        })];
        let config = PackConfig {
            target: target.clone(),
            output_mode: OutputMode::Write,
            selected_targets: PackTargets::default(),
            doctrine_root: None,
            llm_provider: None,
            ollama_model: None,
            quiet: true,
            from_cortex_push: false,
            cortex_receipt_requested_explicitly: false,
        };
        let pack = empty_pack(target.clone());

        let err = dispatch_emitters(&emitters, &config, &pack)
            .expect_err("symlinked leaf must be refused");
        let msg = format!("{err:#}");
        assert!(
            msg.contains("symlink") || msg.contains("reparse-point"),
            "error must indicate refusal class (round-8 redteam #4); got: {msg}"
        );
        assert!(
            msg.contains("AGENTS.md"),
            "error must name the offending leaf path; got: {msg}"
        );

        // Operator file untouched.
        assert_eq!(
            std::fs::read(&dest).expect("read operator file"),
            b"operator owned",
            "symlink target must not be overwritten"
        );
    }

    /// Windows equivalent of the round-8 redteam #1 + #4 contract: plant
    /// `<tempdir>/.cordance` as a directory junction (no privilege
    /// required via `cmd /c mklink /J`) and assert dispatch refuses
    /// before any write.
    #[cfg(windows)]
    struct FakeEmitter {
        name: &'static str,
        outputs: Vec<(Utf8PathBuf, Vec<u8>)>,
    }

    #[cfg(windows)]
    impl cordance_emit::TargetEmitter for FakeEmitter {
        fn name(&self) -> &'static str {
            self.name
        }
        fn render(
            &self,
            _pack: &CordancePack,
        ) -> Result<Vec<(Utf8PathBuf, Vec<u8>)>, cordance_emit::EmitError> {
            Ok(self.outputs.clone())
        }
    }

    #[cfg(windows)]
    fn empty_pack(target: Utf8PathBuf) -> CordancePack {
        CordancePack {
            schema: "test".into(),
            project: ProjectIdentity {
                name: "test".into(),
                kind: "unknown".into(),
                repo_root: target,
                host_os: "test".into(),
                axiom_pin: None,
            },
            sources: vec![],
            doctrine_pins: vec![],
            targets: PackTargets::default(),
            outputs: vec![],
            source_lock: SourceLock::empty(),
            advise: cordance_core::advise::AdviseReport::empty(),
            residual_risk: vec![],
        }
    }

    #[cfg(windows)]
    #[test]
    fn pre_check_fails_with_planted_junction_ancestor_before_any_write_windows() {
        use std::process::Command;

        let dir = tempfile::tempdir().expect("tempdir");
        let target = Utf8PathBuf::from_path_buf(dir.path().to_path_buf()).expect("tempdir is utf8");
        let escape = tempfile::tempdir().expect("escape tempdir");

        // Plant `<target>/.cordance` as a directory junction.
        let dotcordance = target.as_std_path().join(".cordance");
        let status = Command::new("cmd")
            .args([
                "/C",
                "mklink",
                "/J",
                dotcordance.to_str().expect("utf8 junction path"),
                escape.path().to_str().expect("utf8 escape path"),
            ])
            .status();
        let Ok(status) = status else {
            eprintln!("skipping: cmd.exe unavailable");
            return;
        };
        if !status.success() {
            eprintln!("skipping: mklink /J failed");
            return;
        }

        let emitters: Vec<Box<dyn cordance_emit::TargetEmitter>> = vec![
            Box::new(FakeEmitter {
                name: "fake:clean",
                outputs: vec![(Utf8PathBuf::from("AGENTS.md"), b"clean-bytes".to_vec())],
            }),
            Box::new(FakeEmitter {
                name: "fake:hostile",
                outputs: vec![(
                    Utf8PathBuf::from(".cordance/pack.json"),
                    b"would-write-through-junction".to_vec(),
                )],
            }),
        ];
        let config = PackConfig {
            target: target.clone(),
            output_mode: OutputMode::Write,
            selected_targets: PackTargets::default(),
            doctrine_root: None,
            llm_provider: None,
            ollama_model: None,
            quiet: true,
            from_cortex_push: false,
            cortex_receipt_requested_explicitly: false,
        };
        let pack = empty_pack(target.clone());

        let err = dispatch_emitters(&emitters, &config, &pack)
            .expect_err("planted junction ancestor must fail dispatch");
        let msg = format!("{err:#}");

        assert!(
            msg.contains("symlink") || msg.contains("reparse-point"),
            "error must indicate refusal class; got: {msg}"
        );
        assert!(
            msg.contains(".cordance"),
            "error must name the offending ancestor path; got: {msg}"
        );

        // No write may have happened.
        let agents_md = target.as_std_path().join("AGENTS.md");
        assert!(
            !agents_md.exists(),
            "Phase-2 pre-check must fail BEFORE any emitter writes; \
             AGENTS.md must not be on disk"
        );

        // The escape tree must also be empty.
        let escape_entries: Vec<_> = std::fs::read_dir(escape.path())
            .expect("read escape")
            .collect();
        assert!(
            escape_entries.is_empty(),
            "no bytes may have leaked through the junction; escape tree \
             must be empty, found: {escape_entries:?}"
        );
    }

    /// R9-bughunt-1: pack metadata (`.cordance/sources.lock`,
    /// `.cordance/pack.json`, `.cordance/evidence-map.json`) must be part of
    /// the same preflight envelope as target emitters. This exercises the full
    /// `run` pipeline with only root-level target outputs selected: if the
    /// metadata preflight is missing, `AGENTS.md` lands before the later
    /// `.cordance` write refuses the junction.
    #[cfg(windows)]
    #[test]
    fn pack_run_prechecks_metadata_junction_before_root_outputs_windows() {
        use std::process::Command;

        let (_target_dir, target) = temp_utf8_dir();
        let (_doctrine_dir, doctrine_root) = temp_utf8_dir();
        let escape = tempfile::tempdir().expect("escape tempdir");

        let dotcordance = target.as_std_path().join(".cordance");
        let status = Command::new("cmd")
            .args([
                "/C",
                "mklink",
                "/J",
                dotcordance.to_str().expect("utf8 junction path"),
                escape.path().to_str().expect("utf8 escape path"),
            ])
            .status()
            .expect("cmd.exe must be available for junction regression");
        assert!(
            status.success(),
            "mklink /J must succeed for regression test"
        );

        let config = config_for_test(
            &target,
            OutputMode::Write,
            PackTargets {
                claude_code: true,
                ..Default::default()
            },
            &doctrine_root,
            false,
            false,
        );

        let err = run(&config).expect_err("planted .cordance junction must abort pack");
        let msg = format!("{err:#}");
        assert!(
            msg.contains(".cordance"),
            "error must name the refused metadata ancestor; got: {msg}"
        );
        assert!(
            !target.join("AGENTS.md").exists(),
            "metadata preflight must fail before root target output AGENTS.md lands"
        );
        let escape_entries: Vec<_> = std::fs::read_dir(escape.path())
            .expect("read escape")
            .collect();
        assert!(
            escape_entries.is_empty(),
            "metadata bytes must not leak through the junction; found {escape_entries:?}"
        );
    }

    /// POSIX companion to the Windows junction regression above.
    #[cfg(unix)]
    #[test]
    fn pack_run_prechecks_metadata_symlink_before_root_outputs_unix() {
        use std::os::unix::fs::symlink;

        let (_target_dir, target) = temp_utf8_dir();
        let (_doctrine_dir, doctrine_root) = temp_utf8_dir();
        let escape = tempfile::tempdir().expect("escape tempdir");

        let dotcordance = target.as_std_path().join(".cordance");
        symlink(escape.path(), &dotcordance).expect("plant .cordance symlink");

        let config = config_for_test(
            &target,
            OutputMode::Write,
            PackTargets {
                claude_code: true,
                ..Default::default()
            },
            &doctrine_root,
            false,
            false,
        );

        let err = run(&config).expect_err("planted .cordance symlink must abort pack");
        let msg = format!("{err:#}");
        assert!(
            msg.contains(".cordance"),
            "error must name the refused metadata ancestor; got: {msg}"
        );
        assert!(
            !target.join("AGENTS.md").exists(),
            "metadata preflight must fail before root target output AGENTS.md lands"
        );
        let escape_entries: Vec<_> = std::fs::read_dir(escape.path())
            .expect("read escape")
            .collect();
        assert!(
            escape_entries.is_empty(),
            "metadata bytes must not leak through the symlink; found {escape_entries:?}"
        );
    }
}