patchloom 0.25.0

Structured file editing library and CLI for AI agents: parser-backed JSON/YAML/TOML edits, AST-aware code operations, multi-file batching, markdown operations, and MCP server
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
//! size-waiver: accepted single-domain bulk (policy #1408). Tx JSON output
//! assembly and match honesty aggregation for plan/CLI/MCP is one unit; do not
//! split for LOC alone.

use crate::exit;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

/// Structured report from `execute_plan` (and the `tx` command).
///
/// Library users can deserialize the JSON string returned by `execute_plan`
/// into this type for typed access instead of string parsing.
/// See #805 and the embedding docs.
///
/// Marked `non_exhaustive` so new honesty fields can land in minor releases
/// without breaking external struct literals. Serde deserialization is
/// unaffected (`#[serde(default)]` on optional fields).
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct TxOutput {
    pub ok: bool,
    pub status: String,
    /// Whether bytes were written to disk for this report (#1808 parity for
    /// plan/batch/tx). True after successful apply or post-commit lifecycle
    /// errors; false for preview/check and pure failures.
    #[serde(default)]
    pub applied: bool,
    pub files_changed: usize,
    pub files_created: usize,
    pub files_deleted: usize,
    /// Number of `file.rename` pairs reported as a single `action: "renamed"`
    /// change (not double-counted as create+delete). Fixrealloop 2026-07-20.
    /// Omitted when zero so agents without renames keep the prior JSON shape.
    #[serde(default, skip_serializing_if = "is_zero_usize")]
    pub files_renamed: usize,
    pub changes: Vec<TxChange>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub reads: Vec<TxReadResult>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub searches: Vec<TxSearchResult>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub lints: Vec<TxLintResult>,
    /// Per-op doc delete / delete-where summaries (#1439). Empty when the plan
    /// had no such ops. Prefer this for multi-op plans; top-level `changed` /
    /// `removed` are aggregates when present.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub mutations: Vec<TxDocMutation>,
    /// Aggregate of [`TxDocMutation::changed`] when `mutations` is non-empty.
    /// Mirrors CLI doc write JSON so agents can treat exit 0 + `removed: 0`
    /// as an idempotent no-op without re-reading the file.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub changed: Option<bool>,
    /// Sum of [`TxDocMutation::removed`] when `mutations` is non-empty.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub removed: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub error_kind: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub error: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub backup_session: Option<String>,
    /// Aggregate replace match honesty when every replace-backed change agrees
    /// (or worst-case: fuzzy > anchored > exact). See #1674.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub match_mode: Option<String>,
    /// Similarity score when aggregate [`Self::match_mode`] is fuzzy.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub match_score: Option<f64>,
    /// Sum of per-path replace match counts when any replace meta was recorded.
    /// Lets MCP/CLI agents read honesty without a second content pass.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub match_count: Option<usize>,
    /// Widest fuzzy/anchored matched span across replace paths (Unicode chars),
    /// same worst-case rollup as multi-op content_edits (#1736 / #2007).
    /// Aggregate [`Self::match_score`] is min and may come from a different path;
    /// use `changes[].matched_text` / plan `old` for refuse pairing.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub matched_text: Option<String>,
    /// Soft-refuse / soft-skip replace paths that did not write. Includes
    /// fuzzy fail-closed (`exact_old_absent`) and exact soft no-match
    /// (`no_matches`) so multi-op success does not hide a silent miss
    /// (fixrealloop 2026-07-16). Parity with CLI `replace` `refused[]`.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub refused: Vec<TxRefused>,
}

/// One soft-refuse path in a plan/tx report (fuzzy fail-closed without a write).
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TxRefused {
    pub path: String,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub match_mode: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub match_score: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub matched_text: Option<String>,
    /// Machine-readable reason (`exact_old_absent` or `no_write`).
    pub reason: String,
}

/// One doc delete / delete-where outcome inside a plan/tx report (#1439).
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TxDocMutation {
    pub path: String,
    /// Plan op name, e.g. `doc.delete` or `doc.delete_where`.
    pub op: String,
    pub changed: bool,
    pub removed: usize,
}

/// A single file change in a plan/tx report.
///
/// Marked `non_exhaustive` so new honesty fields can land in minor releases
/// without breaking external struct literals.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct TxChange {
    pub path: String,
    pub action: String,
    /// Source path when [`Self::action`] is `renamed` (display-relative).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub from: Option<String>,
    /// Destination path when [`Self::action`] is `renamed` (display-relative).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub to: Option<String>,
    /// Replace match honesty for this path (`exact` / `fuzzy` / `anchored`).
    /// Omitted for non-replace changes. See #1674 / #1669.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub match_mode: Option<String>,
    /// Similarity score when [`Self::match_mode`] is fuzzy.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub match_score: Option<f64>,
    /// Number of replace matches for this path (from engine meta). Omitted for
    /// non-replace changes. Prefer this over re-deriving after Apply.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub match_count: Option<usize>,
    /// Text actually matched for fuzzy/anchored replace on this path (#1736).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub matched_text: Option<String>,
    /// YAML presentation style shifted (e.g. block-sequence indent collapse)
    /// while values may still be correct (#2070). Omitted when false.
    #[serde(skip_serializing_if = "std::ops::Not::not", default)]
    pub style_changed: bool,
}

/// Presentation honesty for a path write (#2070 / single helper in ops::doc).
fn path_style_changed(path: &Path, original: &str, new_text: &str) -> bool {
    crate::ops::doc::style_changed_for_path(&path.to_string_lossy(), original, new_text)
}

/// A search match in the tx output.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TxSearchMatch {
    pub line: usize,
    pub column: usize,
    pub text: String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub context_before: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub context_after: Vec<String>,
}

/// A search result in the tx output.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TxSearchResult {
    pub path: String,
    pub pattern: String,
    pub match_count: usize,
    pub matches: Vec<TxSearchMatch>,
    /// True when `matches` was capped by `max_results` while `match_count` is
    /// the full total (same honesty as CLI `search --json` truncated).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub truncated: bool,
}

/// A file read result in the tx output.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TxReadResult {
    pub path: String,
    pub content: String,
    pub start_line: usize,
    pub end_line: usize,
    pub total_lines: usize,
}

/// A lint result in the tx output.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TxLintResult {
    pub path: String,
    pub issue_count: usize,
    pub issues: Vec<crate::ops::md::LintIssue>,
}

/// Intermediate result from executing all operations in a plan and applying
/// write policy. Contains everything needed for callers to decide on output
/// mode, commit changes, and run lifecycle steps.
pub(crate) struct TxExecResult {
    pub(crate) changes: Vec<(PathBuf, String, String)>,
    pub(crate) deletions: HashSet<PathBuf>,
    pub(crate) existed_before: HashSet<PathBuf>,
    /// Original pending map, retained for `rollback_strict`.
    pub(crate) pending: HashMap<PathBuf, (String, String)>,
    pub(crate) tx_reads: Vec<TxReadResult>,
    pub(crate) tx_searches: Vec<TxSearchResult>,
    pub(crate) tx_lints: Vec<TxLintResult>,
    pub(crate) tx_mutations: Vec<TxDocMutation>,
    pub(crate) no_effective_changes: bool,
    pub(crate) replace_no_matches: bool,
    /// "Did you mean?" hints when a replace found zero matches.
    pub(crate) replace_hint: Option<String>,
    /// Per-path replace match honesty recorded during plan execution (#1674).
    pub(crate) replace_match_meta: HashMap<PathBuf, ReplaceMatchMeta>,
    /// Explicit `file.rename` pairs `(from, to)` for hardlink-preserving
    /// commit via `fs::rename` (including rename-then-edit in one plan).
    pub(crate) renames: Vec<(PathBuf, PathBuf)>,
}

/// Per-path replace match honesty recorded during plan execution.
#[derive(Debug, Clone)]
pub(crate) struct ReplaceMatchMeta {
    pub mode: crate::api::MatchMode,
    pub score: Option<f64>,
    pub match_count: usize,
    /// Fuzzy/anchored span text actually matched (may differ from plan `old`). #1736
    pub matched_text: Option<String>,
    /// Soft-no-write reason when `match_count` is 0 (`exact_old_absent`,
    /// `below_min_fuzzy_score`, `no_matches`). Used for CLI/tx `refused[]`
    /// honesty.
    pub refuse_reason: Option<&'static str>,
}

/// Apply mutation summaries onto a [`TxOutput`] (aggregates + list).
pub(crate) fn attach_mutations(output: &mut TxOutput, mutations: Vec<TxDocMutation>) {
    if mutations.is_empty() {
        return;
    }
    let changed = mutations.iter().any(|m| m.changed);
    let removed = mutations.iter().map(|m| m.removed).sum();
    output.changed = Some(changed);
    output.removed = Some(removed);
    output.mutations = mutations;
}

/// JSON label for [`crate::api::MatchMode`] (CLI/MCP parity: snake_case strings).
pub(crate) fn match_mode_label(mode: crate::api::MatchMode) -> &'static str {
    match mode {
        crate::api::MatchMode::Exact => "exact",
        crate::api::MatchMode::Fuzzy => "fuzzy",
        crate::api::MatchMode::Anchored => "anchored",
    }
}

/// Worst-case rollup: fuzzy > anchored > exact (#1674 / #1673).
///
/// Thin re-export of [`crate::api::merge_match_modes`] so `tx::replace_op`
/// and callers keep a stable import path.
pub(crate) use crate::api::merge_match_modes;

fn match_meta_for_path(
    path: &Path,
    meta: &HashMap<PathBuf, ReplaceMatchMeta>,
) -> (Option<String>, Option<f64>, Option<usize>, Option<String>) {
    match meta.get(path) {
        Some(m) => (
            Some(match_mode_label(m.mode).to_string()),
            m.score,
            Some(m.match_count),
            m.matched_text.clone(),
        ),
        None => (None, None, None, None),
    }
}

fn is_zero_usize(n: &usize) -> bool {
    *n == 0
}

/// Staged path/meta inputs for [`build_tx_output_with_meta`] (keeps arg count low).
pub(crate) struct TxOutputMetaInputs<'a> {
    pub changes: &'a [(PathBuf, String, String)],
    pub deletions: &'a HashSet<PathBuf>,
    pub existed_before: &'a HashSet<PathBuf>,
    pub replace_match_meta: &'a HashMap<PathBuf, ReplaceMatchMeta>,
    pub renames: &'a [(PathBuf, PathBuf)],
}

pub(crate) fn build_tx_output_with_meta(
    status: &'static str,
    ok: bool,
    cwd: &Path,
    inputs: TxOutputMetaInputs<'_>,
) -> TxOutput {
    let TxOutputMetaInputs {
        changes,
        deletions,
        existed_before,
        replace_match_meta,
        renames,
    } = inputs;
    let mut tx_changes = Vec::new();
    let mut created = 0usize;
    let mut deleted_count = 0usize;
    let mut modified = 0usize;
    let mut renamed_count = 0usize;
    let mut agg_mode: Option<crate::api::MatchMode> = None;
    let mut agg_score: Option<f64> = None;
    let mut agg_count: usize = 0;
    let mut any_replace_meta = false;
    let mut top_matched_text: Option<String> = None;

    let display_path = |p: &Path| -> String {
        crate::files::relative_display(p, cwd)
            .to_string_lossy()
            .into_owned()
    };

    // Explicit file.rename pairs: one "renamed" row (not create+delete).
    let mut rename_from: HashSet<PathBuf> = HashSet::new();
    let mut rename_to: HashSet<PathBuf> = HashSet::new();
    for (from, to) in renames {
        rename_from.insert(from.clone());
        rename_to.insert(to.clone());
        let (match_mode, match_score, match_count, matched_text) =
            match_meta_for_path(to, replace_match_meta);
        if let Some(m) = replace_match_meta.get(to) {
            any_replace_meta = true;
            agg_mode = Some(merge_match_modes(agg_mode, m.mode));
            if matches!(m.mode, crate::api::MatchMode::Fuzzy)
                && let Some(s) = m.score
            {
                agg_score = Some(agg_score.map_or(s, |prev| prev.min(s)));
            }
            agg_count = agg_count.saturating_add(m.match_count);
            top_matched_text =
                crate::api::prefer_widest_matched_text(top_matched_text, m.matched_text.clone());
        }
        let from_str = display_path(from);
        let to_str = display_path(to);
        tx_changes.push(TxChange {
            // Destination is the surviving path agents care about.
            path: to_str.clone(),
            action: "renamed".to_string(),
            from: Some(from_str),
            to: Some(to_str),
            match_mode,
            match_score,
            match_count,
            matched_text,
            style_changed: false,
        });
        renamed_count += 1;
    }

    // O(1) membership for deletion/refuse loops (AI finding + large-tx scale).
    let change_paths: HashSet<&std::path::Path> =
        changes.iter().map(|(c, _, _)| c.as_path()).collect();

    for (path, original, new_content) in changes {
        // Covered by a renamed entry (source deleted / dest created).
        if rename_from.contains(path) || rename_to.contains(path) {
            continue;
        }
        let path_str = display_path(path);
        let (match_mode, match_score, match_count, matched_text) =
            match_meta_for_path(path, replace_match_meta);
        if let Some(m) = replace_match_meta.get(path) {
            any_replace_meta = true;
            agg_mode = Some(merge_match_modes(agg_mode, m.mode));
            if matches!(m.mode, crate::api::MatchMode::Fuzzy)
                && let Some(s) = m.score
            {
                // Worst-case confidence: keep the lowest fuzzy score across paths.
                agg_score = Some(agg_score.map_or(s, |prev| prev.min(s)));
            }
            agg_count = agg_count.saturating_add(m.match_count);
            top_matched_text =
                crate::api::prefer_widest_matched_text(top_matched_text, m.matched_text.clone());
        }
        let style_changed = path_style_changed(path, original, new_content);
        if deletions.contains(path) {
            tx_changes.push(TxChange {
                path: path_str,
                action: "deleted".to_string(),
                from: None,
                to: None,
                match_mode,
                match_score,
                match_count,
                matched_text,
                style_changed: false,
            });
            deleted_count += 1;
        } else if !existed_before.contains(path) {
            tx_changes.push(TxChange {
                path: path_str,
                action: "created".to_string(),
                from: None,
                to: None,
                match_mode,
                match_score,
                match_count,
                matched_text,
                style_changed: false,
            });
            created += 1;
        } else {
            tx_changes.push(TxChange {
                path: path_str,
                action: "modified".to_string(),
                from: None,
                to: None,
                match_mode,
                match_score,
                match_count,
                matched_text,
                style_changed,
            });
            modified += 1;
        }
    }
    // Deletions not captured in changes (empty files).
    for path in deletions {
        if rename_from.contains(path) {
            continue;
        }
        if !change_paths.contains(path.as_path()) {
            let (match_mode, match_score, match_count, matched_text) =
                match_meta_for_path(path, replace_match_meta);
            if let Some(m) = replace_match_meta.get(path) {
                any_replace_meta = true;
                agg_mode = Some(merge_match_modes(agg_mode, m.mode));
                if matches!(m.mode, crate::api::MatchMode::Fuzzy)
                    && let Some(s) = m.score
                {
                    agg_score = Some(agg_score.map_or(s, |prev| prev.min(s)));
                }
                agg_count = agg_count.saturating_add(m.match_count);
                top_matched_text = crate::api::prefer_widest_matched_text(
                    top_matched_text,
                    m.matched_text.clone(),
                );
            }
            tx_changes.push(TxChange {
                path: display_path(path),
                action: "deleted".to_string(),
                from: None,
                to: None,
                match_mode,
                match_score,
                match_count,
                matched_text,
                style_changed: false,
            });
            deleted_count += 1;
        }
    }

    // Soft full refuses (fuzzy fail-closed #1758) store honesty without a write.
    // Fold only when there is no write surface: otherwise refuse meta would poison
    // success aggregates (e.g. exact multi-file apply + one soft refuse → match_mode
    // "fuzzy"). Partial refuses are listed in `refused[]` instead.
    if changes.is_empty() && deletions.is_empty() {
        for m in replace_match_meta.values() {
            any_replace_meta = true;
            agg_mode = Some(merge_match_modes(agg_mode, m.mode));
            if matches!(m.mode, crate::api::MatchMode::Fuzzy)
                && let Some(s) = m.score
            {
                agg_score = Some(agg_score.map_or(s, |prev| prev.min(s)));
            }
            agg_count = agg_count.saturating_add(m.match_count);
            top_matched_text =
                crate::api::prefer_widest_matched_text(top_matched_text, m.matched_text.clone());
        }
    }

    // Paths with recorded meta but no write (fuzzy refuse / floor skip /
    // exact soft no-match). Multi-op success must still list these so agents
    // do not treat overall ok as "every replace applied".
    let mut refused = Vec::new();
    for (path, m) in replace_match_meta {
        if change_paths.contains(path.as_path()) || deletions.contains(path) {
            continue;
        }
        // Only surface zero-match soft skips (writes already listed in changes).
        if m.match_count != 0 {
            continue;
        }
        // Fuzzy/anchored candidates carry matched_text; exact soft no-match
        // carries refuse_reason "no_matches" without a candidate span.
        if m.matched_text.is_none() && m.refuse_reason != Some("no_matches") {
            continue;
        }
        let reason = m
            .refuse_reason
            .unwrap_or(if m.mode == crate::api::MatchMode::Fuzzy {
                "exact_old_absent"
            } else {
                "no_write"
            });
        refused.push(TxRefused {
            path: display_path(path),
            match_mode: Some(match_mode_label(m.mode).to_string()),
            match_score: m.score,
            matched_text: m.matched_text.clone(),
            reason: reason.to_string(),
        });
    }
    refused.sort_by(|a, b| a.path.cmp(&b.path));

    let (top_mode, top_score) = match agg_mode {
        Some(m) => (
            Some(match_mode_label(m).to_string()),
            if matches!(m, crate::api::MatchMode::Fuzzy) {
                agg_score
            } else {
                None
            },
        ),
        None => (None, None),
    };

    TxOutput {
        ok,
        status: status.to_string(),
        // Only claim applied when a real commit mutated files. Status
        // "success" is also used for dry-run no-ops and lint-only clean
        // plans; agents branch on applied for undo.
        applied: status == "success" && (modified + created + deleted_count + renamed_count > 0),
        files_changed: modified,
        files_created: created,
        files_deleted: deleted_count,
        files_renamed: renamed_count,
        changes: tx_changes,
        reads: Vec::new(),
        searches: Vec::new(),
        lints: Vec::new(),
        mutations: Vec::new(),
        changed: None,
        removed: None,
        error_kind: None,
        error: None,
        backup_session: None,
        match_mode: top_mode,
        match_score: top_score,
        match_count: if any_replace_meta {
            Some(agg_count)
        } else {
            None
        },
        // Worst-case (widest) span across replace paths (#2007), same as
        // content_edits multi-op rollup. Hosts that need per-path pairing use
        // `changes[].matched_text` / `old` at the plan layer.
        matched_text: top_matched_text,
        refused,
    }
}

pub(crate) fn build_full_tx_output(
    status: &'static str,
    result: &mut TxExecResult,
    cwd: &Path,
) -> TxOutput {
    let mut output = build_tx_output_with_meta(
        status,
        true,
        cwd,
        TxOutputMetaInputs {
            changes: &result.changes,
            deletions: &result.deletions,
            existed_before: &result.existed_before,
            replace_match_meta: &result.replace_match_meta,
            renames: &result.renames,
        },
    );
    output.reads = std::mem::take(&mut result.tx_reads);
    output.searches = std::mem::take(&mut result.tx_searches);
    output.lints = std::mem::take(&mut result.tx_lints);
    attach_mutations(&mut output, std::mem::take(&mut result.tx_mutations));
    // Soft no-match replaces: status=no_matches, exit 3. Agents and MCP hosts
    // branch on `ok` first (#1791); keep ok:false so MCP is_error and body agree
    // with CLI --json replace. Still surface error_kind + replace_hint (#1753).
    if status == "no_matches" {
        output.ok = false;
        output.error_kind = Some("no_matches".to_string());
        let detail = result
            .replace_hint
            .as_deref()
            .filter(|h| !h.is_empty())
            .unwrap_or("no matches");
        output.error = Some(detail.to_string());
    }
    // Lint-only (or any plan with lint issues): match CLI md lint-agents
    // exit 2 / ok:false so agents branching on ok/exit do not treat dirty
    // AGENTS.md as clean. Clear applied: lint never writes.
    if matches!(status, "success" | "changes_detected") {
        let lint_issues: usize = output.lints.iter().map(|l| l.issue_count).sum();
        if lint_issues > 0 {
            output.ok = false;
            output.status = "changes_detected".to_string();
            output.error_kind = Some("changes_detected".to_string());
            output.error = Some(format!(
                "lint found {lint_issues} issue(s); see lints[] for details"
            ));
            // Lint does not mutate files; never claim applied.
            if output.files_changed
                + output.files_created
                + output.files_deleted
                + output.files_renamed
                == 0
            {
                output.applied = false;
            }
        }
    }
    output
}

pub(crate) fn describe_exit_status(status: std::process::ExitStatus) -> String {
    match status.code() {
        Some(code) => format!("exit code {code}"),
        None => "terminated by signal".to_string(),
    }
}

pub(crate) fn describe_lifecycle_cwd(base_cwd: &Path, cwd: &Path) -> String {
    if cwd == base_cwd {
        ".".to_string()
    } else {
        crate::files::relative_display(cwd, base_cwd)
            .display()
            .to_string()
    }
}

pub(crate) fn format_error_with_backup_hint(error: &str, backup_session: Option<&str>) -> String {
    match backup_session {
        Some(ts) => format!("{error} (backup session {ts}; run `patchloom undo` to restore)"),
        None => error.to_string(),
    }
}

/// Prefix `error` with `error_kind:` unless it already starts with that kind
/// (EditError Display is already `{kind}: {message}`).
fn format_error_with_kind(error_kind: &str, error: &str) -> String {
    let prefix = format!("{error_kind}: ");
    if error.starts_with(&prefix) || error.starts_with(&format!("{error_kind}:")) {
        error.to_string()
    } else {
        format!("{prefix}{error}")
    }
}

pub(crate) fn build_error_output(
    error_kind: &str,
    error: &str,
    backup_session: Option<&str>,
) -> TxOutput {
    let body = format_error_with_backup_hint(error, backup_session);
    TxOutput {
        ok: false,
        status: "error".to_string(),
        applied: false,
        files_changed: 0,
        files_created: 0,
        files_deleted: 0,
        files_renamed: 0,
        changes: Vec::new(),
        reads: Vec::new(),
        searches: Vec::new(),
        lints: Vec::new(),
        mutations: Vec::new(),
        changed: None,
        removed: None,
        error_kind: Some(error_kind.to_string()),
        error: Some(format_error_with_kind(error_kind, &body)),
        backup_session: backup_session.map(str::to_string),
        match_mode: None,
        match_score: None,
        match_count: None,
        matched_text: None,
        refused: Vec::new(),
    }
}

/// Non-strict lifecycle failure after commit: files are already on disk.
///
/// Agents must see `files_changed` / `changes` / `backup_session` so they do
/// not treat `ok: false` as "nothing wrote" (fixrealloop 2026-07-16).
pub(crate) fn build_applied_with_error_output(
    error_kind: &str,
    error: &str,
    result: &mut TxExecResult,
    cwd: &Path,
    backup_session: Option<&str>,
) -> TxOutput {
    let mut output = build_full_tx_output("error", result, cwd);
    output.ok = false;
    // Writes already committed before this error path.
    output.applied = true;
    output.error_kind = Some(error_kind.to_string());
    let body = format_error_with_backup_hint(error, backup_session);
    output.error = Some(format_error_with_kind(error_kind, &body));
    if output.backup_session.is_none() {
        output.backup_session = backup_session.map(str::to_string);
    }
    output
}

/// Map a `TxOutput` (PlanReport) to the traditional exit code for CLI/MCP compat.
pub fn exit_code_from_tx_output(report: &TxOutput) -> u8 {
    if report.ok {
        // Preview/check with mutations keeps ok:true (not an error) but exit 2.
        // Lint issues force ok:false + error_kind=changes_detected (handled below).
        match report.status.as_str() {
            "no_matches" => exit::NO_MATCHES,
            "changes_detected" => exit::CHANGES_DETECTED,
            _ => exit::SUCCESS,
        }
    } else {
        match report.error_kind.as_deref() {
            Some("no_matches") => exit::NO_MATCHES,
            Some("parse_error") => exit::PARSE_ERROR,
            Some("ambiguous") => exit::AMBIGUOUS,
            Some("rollback") => exit::ROLLBACK,
            Some("rollback_failed") => exit::FAILURE,
            Some("validation_failed") | Some("format_failed") | Some("verification_failed") => {
                exit::VALIDATION_FAILED
            }
            Some("operation_failed") => exit::OPERATION_FAILED,
            Some("conflicts") => exit::CONFLICTS,
            Some("changes_detected") => exit::CHANGES_DETECTED,
            // parse_error already handled above; keep exhaustive for clarity
            _ => exit::FAILURE,
        }
    }
}

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

    // ---- describe_exit_status ----

    /// Spawn a process that exits with the given code on both Unix and Windows.
    fn command_for_exit_code(code: i32) -> std::process::Command {
        #[cfg(windows)]
        {
            let mut cmd = std::process::Command::new("cmd");
            cmd.args(["/C", &format!("exit {code}")]);
            cmd
        }
        #[cfg(not(windows))]
        {
            if code == 0 {
                std::process::Command::new("true")
            } else {
                std::process::Command::new("false")
            }
        }
    }

    #[test]
    fn describe_exit_status_code_zero() {
        let status = command_for_exit_code(0).status().unwrap();
        assert_eq!(describe_exit_status(status), "exit code 0");
    }

    #[test]
    fn describe_exit_status_code_nonzero() {
        let status = command_for_exit_code(1).status().unwrap();
        assert_eq!(describe_exit_status(status), "exit code 1");
    }

    // ---- describe_lifecycle_cwd ----

    #[test]
    fn describe_lifecycle_cwd_same() {
        let cwd = Path::new("/tmp/project");
        assert_eq!(describe_lifecycle_cwd(cwd, cwd), ".");
    }

    #[test]
    fn describe_lifecycle_cwd_subdir() {
        let base = Path::new("/tmp/project");
        let sub = Path::new("/tmp/project/src/lib");
        assert_eq!(describe_lifecycle_cwd(base, sub), "src/lib");
    }

    // ---- format_error_with_backup_hint ----

    #[test]
    fn format_error_without_backup() {
        assert_eq!(format_error_with_backup_hint("oops", None), "oops");
    }

    #[test]
    fn format_error_with_backup() {
        let msg = format_error_with_backup_hint("oops", Some("20260101T120000"));
        assert!(msg.contains("backup session 20260101T120000"));
        assert!(msg.contains("patchloom undo"));
    }

    // ---- build_error_output ----

    #[test]
    fn build_error_output_fields() {
        let out = build_error_output("parse_error", "bad plan", None);
        assert!(!out.ok);
        assert_eq!(out.status, "error");
        assert_eq!(out.error_kind.as_deref(), Some("parse_error"));
        assert!(out.error.as_ref().unwrap().contains("bad plan"));
        assert_eq!(out.files_changed, 0);
        assert!(out.backup_session.is_none());
    }

    #[test]
    fn format_error_with_kind_skips_duplicate_prefix() {
        let already = "guard_rejected: path rejected by workspace guard: escapes";
        assert_eq!(
            format_error_with_kind("guard_rejected", already),
            already,
            "must not double-prefix EditError Display"
        );
        assert_eq!(
            format_error_with_kind("parse_error", "bad plan"),
            "parse_error: bad plan"
        );
    }

    #[test]
    fn build_error_output_with_backup() {
        let out = build_error_output("rollback", "fail", Some("ts123"));
        assert_eq!(out.backup_session.as_deref(), Some("ts123"));
        assert!(out.error.as_ref().unwrap().contains("patchloom undo"));
    }

    // ---- exit_code_from_tx_output ----

    fn ok_output(status: &str) -> TxOutput {
        TxOutput {
            ok: true,
            status: status.to_string(),
            applied: status == "success",
            files_changed: 0,
            files_created: 0,
            files_deleted: 0,
            files_renamed: 0,
            changes: Vec::new(),
            reads: Vec::new(),
            searches: Vec::new(),
            lints: Vec::new(),
            mutations: Vec::new(),
            changed: None,
            removed: None,
            error_kind: None,
            error: None,
            backup_session: None,
            match_mode: None,
            match_score: None,
            match_count: None,
            matched_text: None,
            refused: Vec::new(),
        }
    }

    fn err_output(kind: &str) -> TxOutput {
        TxOutput {
            ok: false,
            status: "error".to_string(),
            applied: false,
            files_changed: 0,
            files_created: 0,
            files_deleted: 0,
            files_renamed: 0,
            changes: Vec::new(),
            reads: Vec::new(),
            searches: Vec::new(),
            lints: Vec::new(),
            mutations: Vec::new(),
            changed: None,
            removed: None,
            error_kind: Some(kind.to_string()),
            error: Some("test error".to_string()),
            backup_session: None,
            match_mode: None,
            match_score: None,
            match_count: None,
            matched_text: None,
            refused: Vec::new(),
        }
    }

    #[test]
    fn attach_mutations_sets_aggregates() {
        let mut out = ok_output("success");
        attach_mutations(
            &mut out,
            vec![
                TxDocMutation {
                    path: "a.json".into(),
                    op: "doc.delete_where".into(),
                    changed: true,
                    removed: 2,
                },
                TxDocMutation {
                    path: "b.json".into(),
                    op: "doc.delete".into(),
                    changed: false,
                    removed: 0,
                },
            ],
        );
        assert_eq!(out.changed, Some(true));
        assert_eq!(out.removed, Some(2));
        assert_eq!(out.mutations.len(), 2);
        assert_eq!(out.mutations[0].removed, 2);
    }

    #[test]
    fn attach_mutations_empty_is_noop() {
        let mut out = ok_output("success");
        attach_mutations(&mut out, Vec::new());
        assert_eq!(out.changed, None);
        assert_eq!(out.removed, None);
        assert!(out.mutations.is_empty());
    }

    #[test]
    fn exit_code_success() {
        assert_eq!(
            exit_code_from_tx_output(&ok_output("success")),
            exit::SUCCESS
        );
    }

    #[test]
    fn exit_code_ok_changes_detected() {
        // Dry-run/check with file changes: ok:true, status changes_detected, exit 2.
        assert_eq!(
            exit_code_from_tx_output(&ok_output("changes_detected")),
            exit::CHANGES_DETECTED
        );
    }

    #[test]
    fn exit_code_ok_no_matches() {
        assert_eq!(
            exit_code_from_tx_output(&ok_output("no_matches")),
            exit::NO_MATCHES
        );
    }

    #[test]
    fn exit_code_error_kinds() {
        assert_eq!(
            exit_code_from_tx_output(&err_output("no_matches")),
            exit::NO_MATCHES
        );
        assert_eq!(
            exit_code_from_tx_output(&err_output("parse_error")),
            exit::PARSE_ERROR
        );
        assert_eq!(
            exit_code_from_tx_output(&err_output("rollback")),
            exit::ROLLBACK
        );
        assert_eq!(
            exit_code_from_tx_output(&err_output("rollback_failed")),
            exit::FAILURE
        );
        assert_eq!(
            exit_code_from_tx_output(&err_output("validation_failed")),
            exit::VALIDATION_FAILED
        );
        assert_eq!(
            exit_code_from_tx_output(&err_output("format_failed")),
            exit::VALIDATION_FAILED
        );
        assert_eq!(
            exit_code_from_tx_output(&err_output("verification_failed")),
            exit::VALIDATION_FAILED
        );
        assert_eq!(
            exit_code_from_tx_output(&err_output("operation_failed")),
            exit::OPERATION_FAILED
        );
        assert_eq!(
            exit_code_from_tx_output(&err_output("ambiguous")),
            exit::AMBIGUOUS
        );
        assert_eq!(
            exit_code_from_tx_output(&err_output("unknown_kind")),
            exit::FAILURE
        );
    }

    // ---- build_tx_output ----

    #[test]
    fn build_tx_output_classifies_changes() {
        let cwd = Path::new("/project");
        let existed = HashSet::from([PathBuf::from("/project/existing.txt")]);
        let deletions = HashSet::from([PathBuf::from("/project/removed.txt")]);
        let changes = vec![
            (
                PathBuf::from("/project/existing.txt"),
                "old".to_string(),
                "new".to_string(),
            ),
            (
                PathBuf::from("/project/brand_new.txt"),
                String::new(),
                "content".to_string(),
            ),
            (
                PathBuf::from("/project/removed.txt"),
                "was here".to_string(),
                String::new(),
            ),
        ];

        let out = build_tx_output_with_meta(
            "success",
            true,
            cwd,
            TxOutputMetaInputs {
                changes: &changes,
                deletions: &deletions,
                existed_before: &existed,
                replace_match_meta: &HashMap::new(),
                renames: &[],
            },
        );
        assert!(out.ok);
        assert_eq!(out.files_changed, 1); // existing.txt modified
        assert_eq!(out.files_created, 1); // brand_new.txt
        assert_eq!(out.files_deleted, 1); // removed.txt
        assert_eq!(out.changes.len(), 3);

        let actions: Vec<&str> = out.changes.iter().map(|c| c.action.as_str()).collect();
        assert!(actions.contains(&"modified"));
        assert!(actions.contains(&"created"));
        assert!(actions.contains(&"deleted"));
    }

    /// Explicit file.rename must surface as one `renamed` change, not create+delete.
    #[test]
    fn build_tx_output_classifies_file_rename() {
        let cwd = Path::new("/project");
        let from = PathBuf::from("/project/old.txt");
        let to = PathBuf::from("/project/new.txt");
        let changes = vec![
            (to.clone(), String::new(), "body\n".to_string()),
            (from.clone(), "body\n".to_string(), String::new()),
        ];
        let deletions = HashSet::from([from.clone()]);
        let renames = vec![(from, to)];
        let out = build_tx_output_with_meta(
            "success",
            true,
            cwd,
            TxOutputMetaInputs {
                changes: &changes,
                deletions: &deletions,
                existed_before: &HashSet::new(),
                replace_match_meta: &HashMap::new(),
                renames: &renames,
            },
        );
        assert_eq!(out.files_renamed, 1);
        assert_eq!(out.files_created, 0);
        assert_eq!(out.files_deleted, 0);
        assert_eq!(out.files_changed, 0);
        assert_eq!(out.changes.len(), 1);
        assert_eq!(out.changes[0].action, "renamed");
        assert_eq!(out.changes[0].path, "new.txt");
        assert_eq!(out.changes[0].from.as_deref(), Some("old.txt"));
        assert_eq!(out.changes[0].to.as_deref(), Some("new.txt"));
    }

    #[test]
    fn build_tx_output_empty_changes() {
        let cwd = Path::new("/project");
        let out = build_tx_output_with_meta(
            "success",
            true,
            cwd,
            TxOutputMetaInputs {
                changes: &[],
                deletions: &HashSet::new(),
                existed_before: &HashSet::new(),
                replace_match_meta: &HashMap::new(),
                renames: &[],
            },
        );
        assert_eq!(out.files_changed, 0);
        assert_eq!(out.files_created, 0);
        assert_eq!(out.files_deleted, 0);
        assert!(out.changes.is_empty());
    }

    #[test]
    fn build_tx_output_includes_replace_match_mode() {
        let cwd = Path::new("/project");
        let path = PathBuf::from("/project/a.txt");
        let existed = HashSet::from([path.clone()]);
        let changes = vec![(path.clone(), "old".into(), "new".into())];
        let mut meta = HashMap::new();
        meta.insert(
            path,
            ReplaceMatchMeta {
                mode: crate::api::MatchMode::Fuzzy,
                score: Some(0.91),
                match_count: 1,
                matched_text: Some("proccess".into()),
                refuse_reason: None,
            },
        );
        let out = build_tx_output_with_meta(
            "success",
            true,
            cwd,
            TxOutputMetaInputs {
                changes: &changes,
                deletions: &HashSet::new(),
                existed_before: &existed,
                replace_match_meta: &meta,
                renames: &[],
            },
        );
        assert_eq!(out.match_mode.as_deref(), Some("fuzzy"));
        assert_eq!(out.match_score, Some(0.91));
        assert_eq!(out.match_count, Some(1));
        assert_eq!(out.changes.len(), 1);
        assert_eq!(out.changes[0].match_mode.as_deref(), Some("fuzzy"));
        assert_eq!(out.changes[0].match_score, Some(0.91));
        assert_eq!(out.changes[0].match_count, Some(1));
        assert_eq!(out.matched_text.as_deref(), Some("proccess"));
        assert_eq!(out.changes[0].matched_text.as_deref(), Some("proccess"));
        let json = serde_json::to_string(&out).unwrap();
        assert!(json.contains("\"match_mode\":\"fuzzy\""), "{json}");
        assert!(json.contains("\"match_count\":1"), "{json}");
        assert!(json.contains("\"matched_text\":\"proccess\""), "{json}");
    }

    /// Multi-path fuzzy aggregate must report the minimum score (worst case).
    #[test]
    fn build_tx_output_fuzzy_agg_score_is_minimum() {
        let cwd = Path::new("/project");
        let a = PathBuf::from("/project/a.txt");
        let b = PathBuf::from("/project/b.txt");
        let existed = HashSet::from([a.clone(), b.clone()]);
        let changes = vec![
            (a.clone(), "old".into(), "new".into()),
            (b.clone(), "old".into(), "new".into()),
        ];
        let mut meta = HashMap::new();
        meta.insert(
            a,
            ReplaceMatchMeta {
                mode: crate::api::MatchMode::Fuzzy,
                score: Some(0.95),
                match_count: 1,
                matched_text: Some("short".into()),
                refuse_reason: None,
            },
        );
        meta.insert(
            b,
            ReplaceMatchMeta {
                mode: crate::api::MatchMode::Fuzzy,
                score: Some(0.80),
                match_count: 1,
                matched_text: Some("much_wider_matched_span".into()),
                refuse_reason: None,
            },
        );
        let out = build_tx_output_with_meta(
            "success",
            true,
            cwd,
            TxOutputMetaInputs {
                changes: &changes,
                deletions: &HashSet::new(),
                existed_before: &existed,
                replace_match_meta: &meta,
                renames: &[],
            },
        );
        assert_eq!(out.match_mode.as_deref(), Some("fuzzy"));
        assert_eq!(
            out.match_score,
            Some(0.80),
            "worst-case aggregate score must be the min fuzzy score"
        );
        assert_eq!(
            out.matched_text.as_deref(),
            Some("much_wider_matched_span"),
            "multi-path top-level matched_text must be widest span (#2007)"
        );
        assert_eq!(out.match_count, Some(2));
    }

    /// Single replace path still surfaces top-level matched_text among other
    /// non-replace changes (#2007 multi-path widest still covers the lone span).
    #[test]
    fn build_tx_output_matched_text_when_single_replace_among_other_changes() {
        let cwd = Path::new("/project");
        let replaced = PathBuf::from("/project/a.txt");
        let other = PathBuf::from("/project/b.txt");
        let existed = HashSet::from([replaced.clone(), other.clone()]);
        let changes = vec![
            (replaced.clone(), "old".into(), "new".into()),
            (other, "x".into(), "y".into()),
        ];
        let mut meta = HashMap::new();
        meta.insert(
            replaced,
            ReplaceMatchMeta {
                mode: crate::api::MatchMode::Fuzzy,
                score: Some(0.88),
                match_count: 1,
                matched_text: Some("live_span".into()),
                refuse_reason: None,
            },
        );
        let out = build_tx_output_with_meta(
            "success",
            true,
            cwd,
            TxOutputMetaInputs {
                changes: &changes,
                deletions: &HashSet::new(),
                existed_before: &existed,
                replace_match_meta: &meta,
                renames: &[],
            },
        );
        assert_eq!(
            out.matched_text.as_deref(),
            Some("live_span"),
            "single replace path must surface matched_text even when other files changed"
        );
        assert_eq!(out.match_score, Some(0.88));
    }

    #[test]
    fn applied_true_on_success_status_false_on_preview() {
        let preview = build_tx_output_with_meta(
            "changes_detected",
            true,
            Path::new("/tmp"),
            TxOutputMetaInputs {
                changes: &[],
                deletions: &Default::default(),
                existed_before: &Default::default(),
                replace_match_meta: &Default::default(),
                renames: &[],
            },
        );
        assert!(!preview.applied, "preview must set applied=false");
        // success with zero mutations is a no-op / dry-run identity: applied=false
        let noop = build_tx_output_with_meta(
            "success",
            true,
            Path::new("/tmp"),
            TxOutputMetaInputs {
                changes: &[],
                deletions: &Default::default(),
                existed_before: &Default::default(),
                replace_match_meta: &Default::default(),
                renames: &[],
            },
        );
        assert!(
            !noop.applied,
            "success with no file mutations must set applied=false"
        );
        let mut existed = HashSet::new();
        existed.insert(PathBuf::from("/tmp/a.txt"));
        let changes = vec![(
            PathBuf::from("/tmp/a.txt"),
            "old".to_string(),
            "new".to_string(),
        )];
        let applied = build_tx_output_with_meta(
            "success",
            true,
            Path::new("/tmp"),
            TxOutputMetaInputs {
                changes: &changes,
                deletions: &Default::default(),
                existed_before: &existed,
                replace_match_meta: &Default::default(),
                renames: &[],
            },
        );
        assert!(
            applied.applied,
            "success with real file mutations must set applied=true"
        );
        let err = build_error_output("invalid_input", "nope", None);
        assert!(!err.applied, "pure error must set applied=false");
    }

    // ---- TxOutput serde round-trip ----

    #[test]
    fn tx_output_serde_round_trip() {
        let out = ok_output("success");
        let json = serde_json::to_string(&out).unwrap();
        let parsed: TxOutput = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.ok, out.ok);
        assert_eq!(parsed.status, out.status);
    }

    #[test]
    fn tx_output_skips_empty_optional_fields() {
        let out = ok_output("success");
        let json = serde_json::to_string(&out).unwrap();
        // Empty reads/searches/lints should be omitted
        assert!(!json.contains("\"reads\""));
        assert!(!json.contains("\"searches\""));
        assert!(!json.contains("\"lints\""));
        assert!(!json.contains("\"error\""));
    }

    /// Soft no_matches reports must carry error_kind + replace_hint for agents.
    #[test]
    fn build_full_tx_output_no_matches_includes_hint() {
        use std::collections::HashMap;
        let cwd = Path::new("/project");
        let mut result = TxExecResult {
            changes: vec![],
            deletions: HashSet::new(),
            existed_before: HashSet::new(),
            pending: HashMap::new(),
            tx_reads: vec![],
            tx_searches: vec![],
            tx_lints: vec![],
            tx_mutations: vec![],
            no_effective_changes: true,
            replace_no_matches: true,
            replace_hint: Some(
                "fuzzy match score 0.900 below min_fuzzy_score 1 for \"proccess\"".into(),
            ),
            replace_match_meta: HashMap::new(),
            renames: vec![],
        };
        let out = build_full_tx_output("no_matches", &mut result, cwd);
        assert_eq!(out.status, "no_matches");
        assert!(
            !out.ok,
            "no_matches must set ok:false so MCP/CLI agents agree (#1791)"
        );
        assert_eq!(out.error_kind.as_deref(), Some("no_matches"));
        assert!(
            out.error
                .as_deref()
                .is_some_and(|e| e.contains("min_fuzzy_score")),
            "hint must appear in error: {:?}",
            out.error
        );
        assert_eq!(exit_code_from_tx_output(&out), exit::NO_MATCHES);
    }

    /// Soft refuse (#1758) records replace_match_meta without a write; no_matches
    /// JSON must still expose match_mode / match_score / matched_text.
    #[test]
    fn build_full_tx_output_no_matches_includes_refuse_match_meta() {
        use std::collections::HashMap;
        let cwd = Path::new("/project");
        let mut meta = HashMap::new();
        meta.insert(
            PathBuf::from("/project/app.py"),
            ReplaceMatchMeta {
                mode: crate::api::MatchMode::Fuzzy,
                score: Some(0.987),
                match_count: 0,
                matched_text: Some("compute_checksum".into()),
                refuse_reason: None,
            },
        );
        let mut result = TxExecResult {
            changes: vec![],
            deletions: HashSet::new(),
            existed_before: HashSet::new(),
            pending: HashMap::new(),
            tx_reads: vec![],
            tx_searches: vec![],
            tx_lints: vec![],
            tx_mutations: vec![],
            no_effective_changes: true,
            replace_no_matches: true,
            replace_hint: Some("exact old absent; best fuzzy candidate".into()),
            replace_match_meta: meta,
            renames: vec![],
        };
        let out = build_full_tx_output("no_matches", &mut result, cwd);
        assert_eq!(out.status, "no_matches");
        assert_eq!(out.match_mode.as_deref(), Some("fuzzy"));
        assert_eq!(out.match_score, Some(0.987));
        assert_eq!(out.matched_text.as_deref(), Some("compute_checksum"));
        assert_eq!(out.match_count, Some(0));
    }

    /// Partial apply + soft refuse must not report aggregate match_mode=fuzzy.
    #[test]
    fn build_full_tx_output_partial_success_ignores_refuse_meta_in_aggregate() {
        use std::collections::HashMap;
        let cwd = Path::new("/project");
        let changed = PathBuf::from("/project/a.txt");
        let refused = PathBuf::from("/project/b.txt");
        let mut meta = HashMap::new();
        meta.insert(
            changed.clone(),
            ReplaceMatchMeta {
                mode: crate::api::MatchMode::Exact,
                score: None,
                match_count: 1,
                matched_text: None,
                refuse_reason: None,
            },
        );
        meta.insert(
            refused,
            ReplaceMatchMeta {
                mode: crate::api::MatchMode::Fuzzy,
                score: Some(0.97),
                match_count: 0,
                matched_text: Some("helo world".into()),
                refuse_reason: Some("exact_old_absent"),
            },
        );
        let mut result = TxExecResult {
            changes: vec![(changed, "hello world\n".into(), "hi\n".into())],
            deletions: HashSet::new(),
            existed_before: {
                let mut s = HashSet::new();
                s.insert(PathBuf::from("/project/a.txt"));
                s
            },
            pending: HashMap::new(),
            tx_reads: vec![],
            tx_searches: vec![],
            tx_lints: vec![],
            tx_mutations: vec![],
            no_effective_changes: false,
            replace_no_matches: false,
            replace_hint: Some("exact old absent".into()),
            replace_match_meta: meta,
            renames: vec![],
        };
        let out = build_full_tx_output("success", &mut result, cwd);
        assert_eq!(out.status, "success");
        assert_eq!(out.match_mode.as_deref(), Some("exact"));
        assert!(out.match_score.is_none());
        assert_eq!(out.match_count, Some(1));
        assert_eq!(out.refused.len(), 1);
        assert_eq!(out.refused[0].path, "b.txt");
        assert_eq!(out.refused[0].match_mode.as_deref(), Some("fuzzy"));
        assert_eq!(out.refused[0].reason, "exact_old_absent");
        assert_eq!(out.refused[0].matched_text.as_deref(), Some("helo world"));
    }

    /// Non-strict format/validation failure after commit must list applied
    /// changes (not empty files_changed=0).
    #[test]
    fn build_applied_with_error_output_includes_changes_and_backup() {
        use std::collections::HashMap;
        let cwd = Path::new("/project");
        let path = PathBuf::from("/project/a.txt");
        let mut meta = HashMap::new();
        meta.insert(
            path.clone(),
            ReplaceMatchMeta {
                mode: crate::api::MatchMode::Exact,
                score: None,
                match_count: 1,
                matched_text: None,
                refuse_reason: None,
            },
        );
        let mut result = TxExecResult {
            changes: vec![(path, "hello\n".into(), "world\n".into())],
            deletions: HashSet::new(),
            existed_before: {
                let mut s = HashSet::new();
                s.insert(PathBuf::from("/project/a.txt"));
                s
            },
            pending: HashMap::new(),
            tx_reads: vec![],
            tx_searches: vec![],
            tx_lints: vec![],
            tx_mutations: vec![],
            no_effective_changes: false,
            replace_no_matches: false,
            replace_hint: None,
            replace_match_meta: meta,
            renames: vec![],
        };
        let out = build_applied_with_error_output(
            "format_failed",
            "format step failed (step 1, exit code 1, cwd: .)",
            &mut result,
            cwd,
            Some("123_0"),
        );
        assert!(!out.ok);
        assert_eq!(out.error_kind.as_deref(), Some("format_failed"));
        assert_eq!(out.files_changed, 1);
        assert_eq!(out.changes.len(), 1);
        assert_eq!(out.backup_session.as_deref(), Some("123_0"));
        assert!(
            out.error
                .as_deref()
                .is_some_and(|e| e.contains("backup session") && e.contains("undo")),
            "{:?}",
            out.error
        );
    }

    /// Multi-op success with an exact soft no-match must list refused[] so
    /// agents do not treat overall ok as every replace having applied
    /// (fixrealloop 2026-07-16).
    #[test]
    fn build_full_tx_output_partial_success_surfaces_exact_soft_no_match() {
        use std::collections::HashMap;
        let cwd = Path::new("/project");
        let created = PathBuf::from("/project/g.txt");
        let missed = PathBuf::from("/project/f.txt");
        let mut meta = HashMap::new();
        meta.insert(
            missed,
            ReplaceMatchMeta {
                mode: crate::api::MatchMode::Exact,
                score: None,
                match_count: 0,
                matched_text: None,
                refuse_reason: Some("no_matches"),
            },
        );
        let mut result = TxExecResult {
            changes: vec![(created, String::new(), "hi\n".into())],
            deletions: HashSet::new(),
            existed_before: HashSet::new(),
            pending: HashMap::new(),
            tx_reads: vec![],
            tx_searches: vec![],
            tx_lints: vec![],
            tx_mutations: vec![],
            no_effective_changes: false,
            replace_no_matches: false,
            replace_hint: Some("no matches for 'missing' in f.txt".into()),
            replace_match_meta: meta,
            renames: vec![],
        };
        let out = build_full_tx_output("success", &mut result, cwd);
        assert_eq!(out.status, "success");
        assert_eq!(out.files_created, 1);
        assert_eq!(
            out.refused.len(),
            1,
            "exact soft miss must surface: {out:?}"
        );
        assert_eq!(out.refused[0].path, "f.txt");
        assert_eq!(out.refused[0].reason, "no_matches");
        assert_eq!(out.refused[0].match_mode.as_deref(), Some("exact"));
        assert!(out.refused[0].matched_text.is_none());
    }

    /// Hosts may deserialize older plan/tx JSON that never had match honesty
    /// fields. Missing keys must default to None (parity with TxChange).
    #[test]
    fn tx_output_deserializes_minimal_json_without_match_fields() {
        let json = r#"{"ok":true,"status":"success","files_changed":0,"files_created":0,"files_deleted":0,"changes":[]}"#;
        let parsed: TxOutput = serde_json::from_str(json).expect("minimal TxOutput JSON");
        assert!(parsed.ok);
        assert!(parsed.match_mode.is_none());
        assert!(parsed.match_score.is_none());
        assert!(parsed.match_count.is_none());
        assert!(parsed.matched_text.is_none());
        assert!(parsed.backup_session.is_none());
        assert!(parsed.error_kind.is_none());
    }
}