miwa-cli 0.7.0

doc / req / test の3層の仕様乖離(ドリフト)を検知する CLI
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
//! `reconcile`: record the current state of one or more edges into the lock.

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReconcileTarget {
    All,
    Edges(Vec<String>),
}

#[derive(Debug, thiserror::Error)]
pub enum ReconcileError {
    #[error("unknown edge: {0}")]
    UnknownEdge(String),
    #[error("edge {0} has structural problems")]
    Blocked(String),
    #[error("graph has broken references or invalid nodes")]
    GraphNotClean,
}

pub fn reconcile(
    graph: &crate::model::Graph,
    lock: &crate::lock::Lock,
    target: ReconcileTarget,
    reason: Option<String>,
    now: &str,
) -> Result<crate::lock::Lock, ReconcileError> {
    use crate::lock::{Lock, LockEntry};

    match target {
        ReconcileTarget::All => {
            if !graph.invalid.is_empty() || !graph.broken.is_empty() {
                return Err(ReconcileError::GraphNotClean);
            }
            let mut new_lock = Lock::default();
            for (edge_id, edge) in &graph.edges {
                let (from_hash, to_hash) = crate::model::edge_hashes(graph, edge);
                let entry = match lock.edges.get(edge_id) {
                    Some(existing) if existing.from == from_hash && existing.to == to_hash => {
                        existing.clone()
                    }
                    _ => LockEntry {
                        from: from_hash,
                        to: to_hash,
                        by: "human".to_string(),
                        reason: reason.clone(),
                        score: None,
                        at: now.to_string(),
                    },
                };
                new_lock.edges.insert(edge_id.clone(), entry);
            }
            Ok(new_lock)
        }
        ReconcileTarget::Edges(ids) => {
            let mut new_lock = lock.clone();
            for id in ids {
                if let Some(edge) = graph.edges.get(&id) {
                    let blocked = graph
                        .invalid
                        .iter()
                        .any(|inv| inv.target == edge.from.id || inv.target == edge.to.id)
                        || graph.broken.iter().any(|b| b.from == edge.from);
                    if blocked {
                        return Err(ReconcileError::Blocked(id));
                    }
                    let (from_hash, to_hash) = crate::model::edge_hashes(graph, edge);
                    new_lock.edges.insert(
                        id,
                        LockEntry {
                            from: from_hash,
                            to: to_hash,
                            by: "human".to_string(),
                            reason: reason.clone(),
                            score: None,
                            at: now.to_string(),
                        },
                    );
                } else if new_lock.edges.contains_key(&id) {
                    // The edge only exists in the lock (it was removed from
                    // the source). Deleting it is normally fine, but if its
                    // endpoints are currently invalid/broken (e.g. the req it
                    // pointed to now has a duplicate id, or the test file it
                    // lived in now fails to parse), removing the record could
                    // hide that problem, so reject it instead.
                    if let Some((kind_prefix, from_id, to_id)) = parse_edge_id(&id) {
                        let mut blocked = graph
                            .invalid
                            .iter()
                            .any(|inv| inv.target == from_id || inv.target == to_id)
                            || graph.broken.iter().any(|b| b.from.id == from_id);
                        if !blocked && kind_prefix == "test-req" {
                            blocked = test_source_has_parse_error(&graph.invalid, from_id);
                        }
                        if blocked {
                            return Err(ReconcileError::Blocked(id));
                        }
                    }
                    new_lock.edges.remove(&id);
                } else {
                    return Err(ReconcileError::UnknownEdge(id));
                }
            }
            Ok(new_lock)
        }
    }
}

/// Splits an edge id (`"doc-req:<from>:<to>"` / `"test-req:<from>:<to>"` /
/// `"desc:doc:<id>"` / `"desc:req:<id>"`) into `(kind_prefix, from_id, to_id)`.
/// A `desc` edge yields `("desc", <id>, <id>)` (a self-loop; the node kind is
/// only part of the edge id). For the other kinds, `to` (a req id) never contains `:`
/// (doc/req ids are restricted to `[A-Za-z0-9._-]`), so it is always the
/// last `:`-separated segment; `from` is everything between the kind prefix
/// and that segment (and may itself contain `:` for Rust test ids).
fn parse_edge_id(id: &str) -> Option<(&str, &str, &str)> {
    if let Some(node_id) = id
        .strip_prefix("desc:doc:")
        .or_else(|| id.strip_prefix("desc:req:"))
    {
        return Some(("desc", node_id, node_id));
    }
    let (rest, to_id) = id.rsplit_once(':')?;
    let (kind_prefix, from_id) = rest.split_once(':')?;
    Some((kind_prefix, from_id, to_id))
}

/// Whether `invalid` contains a `ParseError` whose target (a file path)
/// looks like the source file that test id `test_id` lives in. The "source
/// prefix" is the part of the test id before its first `:` (e.g. Rust
/// `tests/sample::t` -> `tests/sample`, Go `internal/auth:TestX` ->
/// `internal/auth`, Go at the repo root `.:TestX` -> `.`). The match is
/// deliberately conservative (a false positive only blocks a removal, it
/// never silently drops information):
/// - Rust / C# / Java / Kotlin / Dart / TypeScript / JavaScript: the target equals
///   `<prefix>.rs` / `<prefix>.cs` / `<prefix>.java` / `<prefix>.kt` / `<prefix>.dart` /
///   `<prefix>.<ext>` exactly, `<ext>` being one of
///   `TYPESCRIPT_TEST_EXTENSIONS` (TS / JS prefixes keep `.test` / `.spec`).
/// - Go (non-root): the target starts with `<prefix>/`.
/// - Go (repo root, `prefix == "."`): the target contains no `/`.
fn test_source_has_parse_error(invalid: &[crate::model::Invalid], test_id: &str) -> bool {
    let prefix = test_id.split_once(':').map_or(test_id, |(p, _)| p);
    invalid.iter().any(|inv| {
        if inv.reason != crate::model::ReasonCode::ParseError {
            return false;
        }
        let target = inv.target.as_str();
        if target == format!("{prefix}.rs")
            || target == format!("{prefix}.cs")
            || target == format!("{prefix}.java")
            || target == format!("{prefix}.kt")
            || target == format!("{prefix}.dart")
            || crate::extract::TYPESCRIPT_TEST_EXTENSIONS
                .iter()
                .any(|ext| target == format!("{prefix}.{ext}"))
        {
            return true;
        }
        if prefix == "." {
            !target.contains('/')
        } else {
            target.starts_with(&format!("{prefix}/"))
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lock::{Lock, LockEntry};
    use crate::model::{
        Edge, EdgeKind, Graph, Invalid, Node, NodeKey, NodeKind, ReasonCode, TargetKind,
    };

    fn node(kind: NodeKind, id: &str, hash: &str) -> Node {
        Node {
            key: NodeKey {
                kind,
                id: id.to_string(),
            },
            path: format!("{id}.md"),
            content: String::new(),
            hash: hash.to_string(),
            description: None,
        }
    }

    fn lock_entry(from: &str, to: &str, at: &str) -> LockEntry {
        LockEntry {
            from: from.to_string(),
            to: to.to_string(),
            by: "human".to_string(),
            reason: None,
            score: None,
            at: at.to_string(),
        }
    }

    /// A clean graph with a single doc-req edge, no broken/invalid entries.
    fn clean_graph() -> Graph {
        let mut graph = Graph::default();
        let doc_key = NodeKey {
            kind: NodeKind::Doc,
            id: "DOC-A".to_string(),
        };
        let req_key = NodeKey {
            kind: NodeKind::Req,
            id: "FR-001".to_string(),
        };
        graph.nodes.insert(
            doc_key.clone(),
            node(NodeKind::Doc, "DOC-A", "sha256:doc-current"),
        );
        graph.nodes.insert(
            req_key.clone(),
            node(NodeKind::Req, "FR-001", "sha256:req-current"),
        );
        let edge_id = "doc-req:DOC-A:FR-001".to_string();
        graph.edges.insert(
            edge_id.clone(),
            Edge {
                id: edge_id,
                kind: EdgeKind::DocReq,
                from: doc_key,
                to: req_key,
            },
        );
        graph
    }

    // [FR-033]
    #[test]
    fn edgeを指定すると現在の両端のハッシュがロックに記録される() {
        let graph = clean_graph();
        let lock = Lock::default();
        let result = reconcile(
            &graph,
            &lock,
            ReconcileTarget::Edges(vec!["doc-req:DOC-A:FR-001".to_string()]),
            None,
            "2026-01-01T00:00:00Z",
        )
        .unwrap();
        let entry = result
            .edges
            .get("doc-req:DOC-A:FR-001")
            .expect("edge should be recorded");
        assert_eq!(entry.from, "sha256:doc-current");
        assert_eq!(entry.to, "sha256:req-current");
        assert_eq!(entry.by, "human");
    }

    // [FR-034]
    #[test]
    fn ロックにのみ存在するエッジを指定するとロックから削除される() {
        let graph = Graph::default(); // グラフには存在しない
        let mut lock = Lock::default();
        lock.edges.insert(
            "doc-req:DOC-A:FR-001".to_string(),
            lock_entry("sha256:old-doc", "sha256:old-req", "2025-01-01T00:00:00Z"),
        );
        let result = reconcile(
            &graph,
            &lock,
            ReconcileTarget::Edges(vec!["doc-req:DOC-A:FR-001".to_string()]),
            None,
            "2026-01-01T00:00:00Z",
        )
        .unwrap();
        assert!(!result.edges.contains_key("doc-req:DOC-A:FR-001"));
    }

    // [FR-035]
    #[test]
    fn ロックにのみ存在するエッジの終端がinvalidな場合はblockedとして拒否される() {
        let graph = {
            let mut graph = Graph::default(); // FR-001 は重複idによりグラフから消えている
            graph.invalid.push(Invalid {
                target_kind: TargetKind::Req,
                target: "FR-001".to_string(),
                reason: ReasonCode::DuplicateId,
                detail: "duplicate id".to_string(),
            });
            graph
        };
        let mut lock = Lock::default();
        lock.edges.insert(
            "doc-req:DOC-A:FR-001".to_string(),
            lock_entry("sha256:old-doc", "sha256:old-req", "2025-01-01T00:00:00Z"),
        );
        let before = lock.clone();

        let result = reconcile(
            &graph,
            &lock,
            ReconcileTarget::Edges(vec!["doc-req:DOC-A:FR-001".to_string()]),
            None,
            "2026-01-01T00:00:00Z",
        );
        assert!(matches!(result, Err(ReconcileError::Blocked(_))));
        assert_eq!(lock, before);
    }

    // [FR-035]
    #[test]
    fn ロックにのみ存在するrustのtest_reqエッジは所在ファイルが構文エラーだとblockedになる() {
        let mut graph = Graph::default(); // テストは構文エラーによりグラフから消えている
        graph.invalid.push(Invalid {
            target_kind: TargetKind::File,
            target: "tests/sample.rs".to_string(),
            reason: ReasonCode::ParseError,
            detail: "parse error".to_string(),
        });
        let mut lock = Lock::default();
        lock.edges.insert(
            "test-req:tests/sample::t:FR-001".to_string(),
            lock_entry("sha256:old-test", "sha256:old-req", "2025-01-01T00:00:00Z"),
        );
        let before = lock.clone();

        let result = reconcile(
            &graph,
            &lock,
            ReconcileTarget::Edges(vec!["test-req:tests/sample::t:FR-001".to_string()]),
            None,
            "2026-01-01T00:00:00Z",
        );
        assert!(matches!(result, Err(ReconcileError::Blocked(_))));
        assert_eq!(lock, before);
    }

    // [FR-035]
    #[test]
    fn ロックにのみ存在するgoのtest_reqエッジは所在ファイルが構文エラーだとblockedになる() {
        let mut graph = Graph::default(); // テストは構文エラーによりグラフから消えている
        graph.invalid.push(Invalid {
            target_kind: TargetKind::File,
            target: "internal/auth/login_test.go".to_string(),
            reason: ReasonCode::ParseError,
            detail: "parse error".to_string(),
        });
        let mut lock = Lock::default();
        lock.edges.insert(
            "test-req:internal/auth:TestX:FR-001".to_string(),
            lock_entry("sha256:old-test", "sha256:old-req", "2025-01-01T00:00:00Z"),
        );
        let before = lock.clone();

        let result = reconcile(
            &graph,
            &lock,
            ReconcileTarget::Edges(vec!["test-req:internal/auth:TestX:FR-001".to_string()]),
            None,
            "2026-01-01T00:00:00Z",
        );
        assert!(matches!(result, Err(ReconcileError::Blocked(_))));
        assert_eq!(lock, before);
    }

    // [FR-034]
    #[test]
    fn ロックにもグラフにも存在しないエッジを指定するとエラーになる() {
        let graph = Graph::default();
        let lock = Lock::default();
        let result = reconcile(
            &graph,
            &lock,
            ReconcileTarget::Edges(vec!["doc-req:NOWHERE:FR-999".to_string()]),
            None,
            "2026-01-01T00:00:00Z",
        );
        assert!(matches!(result, Err(ReconcileError::UnknownEdge(_))));
    }

    // [FR-035]
    #[test]
    fn 対象reqがinvalidに関わるエッジはreconcileを拒否される() {
        let mut graph = clean_graph();
        // FR-001 は id が重複しており invalid として報告されている
        graph.invalid.push(Invalid {
            target_kind: TargetKind::Req,
            target: "FR-001".to_string(),
            reason: ReasonCode::DuplicateId,
            detail: "duplicate id".to_string(),
        });
        let lock = Lock::default();
        let result = reconcile(
            &graph,
            &lock,
            ReconcileTarget::Edges(vec!["doc-req:DOC-A:FR-001".to_string()]),
            None,
            "2026-01-01T00:00:00Z",
        );
        assert!(matches!(result, Err(ReconcileError::Blocked(_))));
        // ロックは変更されていないはず(今回は空のロックのまま)
    }

    // [FR-036]
    #[test]
    fn allは変更のないエッジを据え置き_新規を追加し_消えたエッジを削除する() {
        let mut graph = clean_graph();
        // 現在のグラフに存在する新規エッジ(reqにのみ紐づくtest-reqエッジ)
        let test_key = NodeKey {
            kind: NodeKind::Test,
            id: "src/foo::bar".to_string(),
        };
        graph.nodes.insert(
            test_key.clone(),
            node(NodeKind::Test, "src/foo::bar", "sha256:test-current"),
        );
        let req_key = NodeKey {
            kind: NodeKind::Req,
            id: "FR-001".to_string(),
        };
        let new_edge_id = "test-req:src/foo::bar:FR-001".to_string();
        graph.edges.insert(
            new_edge_id.clone(),
            Edge {
                id: new_edge_id.clone(),
                kind: EdgeKind::TestReq,
                from: test_key,
                to: req_key,
            },
        );

        let mut lock = Lock::default();
        // 既に合意済みで、ハッシュが変化していないエッジ(据え置かれるはず)
        lock.edges.insert(
            "doc-req:DOC-A:FR-001".to_string(),
            lock_entry(
                "sha256:doc-current",
                "sha256:req-current",
                "2020-01-01T00:00:00Z",
            ),
        );
        // ソースからは既に消えたエッジ(削除されるはず)
        lock.edges.insert(
            "doc-req:DOC-STALE:FR-999".to_string(),
            lock_entry(
                "sha256:stale-doc",
                "sha256:stale-req",
                "2020-01-01T00:00:00Z",
            ),
        );

        let result = reconcile(
            &graph,
            &lock,
            ReconcileTarget::All,
            None,
            "2026-01-01T00:00:00Z",
        )
        .unwrap();

        // 据え置き: 変更なしのエッジは元のエントリのまま(at が上書きされない)
        let kept = result.edges.get("doc-req:DOC-A:FR-001").unwrap();
        assert_eq!(kept.at, "2020-01-01T00:00:00Z");

        // 削除: ソースから消えたエッジはロックに残らない
        assert!(!result.edges.contains_key("doc-req:DOC-STALE:FR-999"));

        // 追加: 新規エッジが記録される
        let added = result.edges.get("test-req:src/foo::bar:FR-001").unwrap();
        assert_eq!(added.from, "sha256:test-current");
        assert_eq!(added.to, "sha256:req-current");
        assert_eq!(added.by, "human");
    }

    // [FR-036]
    #[test]
    fn 対象にbrokenまたはinvalidが1件でもあればallは全く変更せず失敗する() {
        let mut graph = clean_graph();
        graph.invalid.push(Invalid {
            target_kind: TargetKind::Req,
            target: "FR-999".to_string(),
            reason: ReasonCode::MissingId,
            detail: "missing id".to_string(),
        });
        let mut lock = Lock::default();
        lock.edges.insert(
            "doc-req:DOC-A:FR-001".to_string(),
            lock_entry(
                "sha256:doc-current",
                "sha256:req-current",
                "2020-01-01T00:00:00Z",
            ),
        );
        let before = lock.clone();

        let result = reconcile(
            &graph,
            &lock,
            ReconcileTarget::All,
            None,
            "2026-01-01T00:00:00Z",
        );
        assert!(matches!(result, Err(ReconcileError::GraphNotClean)));
        // 呼び出し元のロックは reconcile によって書き換えられていない(純粋関数なので当然だが明示する)
        assert_eq!(lock, before);
    }

    // [FR-037]
    #[test]
    fn reasonを指定した場合はエントリに記録される() {
        let graph = clean_graph();
        let result = reconcile(
            &graph,
            &Lock::default(),
            ReconcileTarget::Edges(vec!["doc-req:DOC-A:FR-001".to_string()]),
            Some("最小長の記述が一致".to_string()),
            "2026-01-01T00:00:00Z",
        )
        .unwrap();
        let entry = result.edges.get("doc-req:DOC-A:FR-001").unwrap();
        assert_eq!(entry.by, "human");
        assert_eq!(entry.reason, Some("最小長の記述が一致".to_string()));
    }

    // [FR-037]
    #[test]
    fn reasonを指定しない場合は記録されない() {
        let graph = clean_graph();
        let result = reconcile(
            &graph,
            &Lock::default(),
            ReconcileTarget::Edges(vec!["doc-req:DOC-A:FR-001".to_string()]),
            None,
            "2026-01-01T00:00:00Z",
        )
        .unwrap();
        let entry = result.edges.get("doc-req:DOC-A:FR-001").unwrap();
        assert_eq!(entry.by, "human");
        assert_eq!(entry.reason, None);
    }

    fn assert_blocked_by_parse_error(file: &str, edge: &str) {
        let mut graph = Graph::default();
        graph.invalid.push(Invalid {
            target_kind: TargetKind::File,
            target: file.to_string(),
            reason: ReasonCode::ParseError,
            detail: "parse error".to_string(),
        });
        let mut lock = Lock::default();
        lock.edges.insert(
            edge.to_string(),
            lock_entry("sha256:old-test", "sha256:old-req", "2025-01-01T00:00:00Z"),
        );
        let before = lock.clone();

        let result = reconcile(
            &graph,
            &lock,
            ReconcileTarget::Edges(vec![edge.to_string()]),
            None,
            "2026-01-01T00:00:00Z",
        );
        assert!(matches!(result, Err(ReconcileError::Blocked(_))), "{edge}");
        assert_eq!(lock, before);
    }

    // [FR-035]
    #[test]
    fn ロックにのみ存在するcsharpのtest_reqエッジは所在ファイルが構文エラーだとblockedになる() {
        assert_blocked_by_parse_error(
            "tests/AuthTests.cs",
            "test-req:tests/AuthTests:AuthTests:T:FR-001",
        );
    }

    // [FR-035]
    #[test]
    fn ロックにのみ存在するjavaのtest_reqエッジは所在ファイルが構文エラーだとblockedになる() {
        assert_blocked_by_parse_error(
            "tests/AuthTests.java",
            "test-req:tests/AuthTests:AuthTests:t:FR-001",
        );
    }

    // [FR-035]
    #[test]
    fn ロックにのみ存在するkotlinのtest_reqエッジは所在ファイルが構文エラーだとblockedになる() {
        assert_blocked_by_parse_error(
            "tests/AuthTest.kt",
            "test-req:tests/AuthTest:AuthTest:一覧 取得:FR-001",
        );
    }

    // [FR-035]
    #[test]
    fn ロックにのみ存在するtypescriptのtest_reqエッジは所在ファイルが構文エラーだとblockedになる() {
        assert_blocked_by_parse_error("src/a.test.ts", "test-req:src/a.test:d:t:FR-001");
        assert_blocked_by_parse_error("src/a.spec.ts", "test-req:src/a.spec:d:t:FR-001");
    }

    // [FR-035]
    #[test]
    fn ロックにのみ存在するdartのtest_reqエッジは所在ファイルが構文エラーだとblockedになる() {
        assert_blocked_by_parse_error("test/a_test.dart", "test-req:test/a_test:g:t:FR-001");
    }

    // [FR-035]
    #[test]
    fn ロックにのみ存在するtsxのtest_reqエッジは所在ファイルが構文エラーだとblockedになる() {
        assert_blocked_by_parse_error("src/a.test.tsx", "test-req:src/a.test:d:t:FR-001");
        assert_blocked_by_parse_error("src/a.spec.tsx", "test-req:src/a.spec::t:FR-001");
    }

    // [FR-035]
    #[test]
    fn ロックにのみ存在するjsのtest_reqエッジは所在ファイルが構文エラーだとblockedになる() {
        assert_blocked_by_parse_error("src/a.test.js", "test-req:src/a.test:d:t:FR-001");
        assert_blocked_by_parse_error("src/a.test.mjs", "test-req:src/a.test:d:t:FR-001");
        assert_blocked_by_parse_error("src/a.spec.cjs", "test-req:src/a.spec:d:t:FR-001");
        assert_blocked_by_parse_error("src/a.spec.mts", "test-req:src/a.spec:d:t:FR-001");
        assert_blocked_by_parse_error("src/a.test.cts", "test-req:src/a.test:d:t:FR-001");
        assert_blocked_by_parse_error("src/a.spec.jsx", "test-req:src/a.spec:d:t:FR-001");
    }

    /// `clean_graph` plus `desc:doc:DOC-A` for the doc (with a description).
    fn desc_graph() -> Graph {
        let mut graph = clean_graph();
        let key = NodeKey {
            kind: NodeKind::Doc,
            id: "DOC-A".to_string(),
        };
        graph.nodes.get_mut(&key).unwrap().description = Some("要約A".to_string());
        graph.edges.insert(
            "desc:doc:DOC-A".to_string(),
            Edge {
                id: "desc:doc:DOC-A".to_string(),
                kind: EdgeKind::Desc,
                from: key.clone(),
                to: key,
            },
        );
        graph
    }

    // [FR-033]
    #[test]
    fn descエッジを指定すると現在の要約と本文のハッシュが記録される() {
        let graph = desc_graph();
        let result = reconcile(
            &graph,
            &Lock::default(),
            ReconcileTarget::Edges(vec!["desc:doc:DOC-A".to_string()]),
            None,
            "2026-01-01T00:00:00Z",
        )
        .unwrap();
        let entry = result.edges.get("desc:doc:DOC-A").expect("recorded");
        assert_eq!(entry.from, crate::hash::content_hash("要約A"));
        assert_eq!(entry.to, "sha256:doc-current");
        assert_eq!(entry.by, "human");
        assert!(!result.edges.contains_key("doc-req:DOC-A:FR-001"));
    }

    // [FR-087]
    #[test]
    fn descエッジは要約が無ければ空文字列のハッシュを記録する() {
        let mut graph = desc_graph();
        let key = NodeKey {
            kind: NodeKind::Doc,
            id: "DOC-A".to_string(),
        };
        graph.nodes.get_mut(&key).unwrap().description = None;
        let result = reconcile(
            &graph,
            &Lock::default(),
            ReconcileTarget::Edges(vec!["desc:doc:DOC-A".to_string()]),
            None,
            "2026-01-01T00:00:00Z",
        )
        .unwrap();
        assert_eq!(
            result.edges["desc:doc:DOC-A"].from,
            crate::hash::content_hash("")
        );
    }

    // [FR-036]
    #[test]
    fn allはdescエッジも記録し変更のないdescは据え置く() {
        let graph = desc_graph();
        let mut lock = Lock::default();
        lock.edges.insert(
            "desc:doc:DOC-A".to_string(),
            lock_entry(
                &crate::hash::content_hash("要約A"),
                "sha256:doc-current",
                "2025-01-01T00:00:00Z",
            ),
        );
        let before = lock.edges["desc:doc:DOC-A"].clone();
        let result = reconcile(
            &graph,
            &lock,
            ReconcileTarget::All,
            None,
            "2026-01-01T00:00:00Z",
        )
        .unwrap();
        assert!(result.edges.contains_key("doc-req:DOC-A:FR-001"));
        assert_eq!(result.edges["desc:doc:DOC-A"], before);
    }

    // [FR-036]
    #[test]
    fn allはロックにないdescエッジを新規に記録する() {
        let result = reconcile(
            &desc_graph(),
            &Lock::default(),
            ReconcileTarget::All,
            None,
            "2026-01-01T00:00:00Z",
        )
        .unwrap();
        let entry = result.edges.get("desc:doc:DOC-A").expect("desc recorded");
        assert_eq!(entry.from, crate::hash::content_hash("要約A"));
        assert_eq!(entry.to, "sha256:doc-current");
        assert_eq!(entry.at, "2026-01-01T00:00:00Z");
    }

    // [FR-034]
    #[test]
    fn ロックにのみ存在するdescエッジを指定するとロックから削除される() {
        let mut lock = Lock::default();
        lock.edges.insert(
            "desc:doc:DOC-GONE".to_string(),
            lock_entry("sha256:old", "sha256:old", "2025-01-01T00:00:00Z"),
        );
        let result = reconcile(
            &Graph::default(),
            &lock,
            ReconcileTarget::Edges(vec!["desc:doc:DOC-GONE".to_string()]),
            None,
            "2026-01-01T00:00:00Z",
        )
        .unwrap();
        assert!(!result.edges.contains_key("desc:doc:DOC-GONE"));
    }

    // [FR-035]
    #[test]
    fn ロックにのみ存在するdescエッジのノードがinvalidならblockedになる() {
        let mut graph = Graph::default();
        graph.invalid.push(Invalid {
            target_kind: TargetKind::Doc,
            target: "DOC-A".to_string(),
            reason: ReasonCode::DuplicateId,
            detail: "duplicate id".to_string(),
        });
        let mut lock = Lock::default();
        lock.edges.insert(
            "desc:doc:DOC-A".to_string(),
            lock_entry("sha256:old", "sha256:old", "2025-01-01T00:00:00Z"),
        );
        let before = lock.clone();
        let result = reconcile(
            &graph,
            &lock,
            ReconcileTarget::Edges(vec!["desc:doc:DOC-A".to_string()]),
            None,
            "2026-01-01T00:00:00Z",
        );
        assert!(matches!(result, Err(ReconcileError::Blocked(_))));
        assert_eq!(lock, before);
    }

    // [FR-035]
    #[test]
    fn invalidなdocのdescエッジを指定するとblockedになる() {
        let mut graph = desc_graph();
        graph.invalid.push(Invalid {
            target_kind: TargetKind::Doc,
            target: "DOC-A".to_string(),
            reason: ReasonCode::DuplicateId,
            detail: "duplicate id".to_string(),
        });
        let result = reconcile(
            &graph,
            &Lock::default(),
            ReconcileTarget::Edges(vec!["desc:doc:DOC-A".to_string()]),
            None,
            "2026-01-01T00:00:00Z",
        );
        assert!(matches!(result, Err(ReconcileError::Blocked(_))));
    }

    // [FR-035]
    #[test]
    fn リンク切れを持つdocのdescエッジを指定するとblockedになる() {
        let mut graph = desc_graph();
        graph.broken.push(crate::model::Broken {
            from: NodeKey {
                kind: NodeKind::Doc,
                id: "DOC-A".to_string(),
            },
            target: "../req/missing.md".to_string(),
            reason: ReasonCode::MissingReq,
            detail: "missing".to_string(),
        });
        let result = reconcile(
            &graph,
            &Lock::default(),
            ReconcileTarget::Edges(vec!["desc:doc:DOC-A".to_string()]),
            None,
            "2026-01-01T00:00:00Z",
        );
        assert!(matches!(result, Err(ReconcileError::Blocked(_))));
    }

    // [FR-023]
    #[test]
    fn parse_edge_idはdescエッジを種別とidに分解する() {
        assert_eq!(
            parse_edge_id("desc:doc:DOC-A"),
            Some(("desc", "DOC-A", "DOC-A"))
        );
        assert_eq!(
            parse_edge_id("doc-req:DOC-A:FR-001"),
            Some(("doc-req", "DOC-A", "FR-001"))
        );
    }
}