gobby-wiki 0.8.0

Gobby wiki CLI shell
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
use super::*;
use gobby_core::ai_types::TokenUsage;

use crate::explainer::{ExplainerPrompt, ExplainerResponse};
use crate::provenance::ProvenanceGraph;
use crate::session::{AcceptedResearchNote, ResearchScope, ResearchSession};
use crate::sources::{SourceDraft, SourceKind, SourceManifest};

fn session_with_note(scope: &ResearchScope, title: &str, relative_path: &str) -> ResearchSession {
    ResearchSession {
        session_id: "research-compile-test".to_string(),
        question: "How should compile handoff work?".to_string(),
        prompt: "Compile source-grounded research".to_string(),
        scope: scope.clone(),
        source_constraints: vec!["accepted notes only".to_string()],
        agent_count: 1,
        dispatch_task_id: Some("#302".to_string()),
        dispatch: None,
        accepted_notes: vec![AcceptedResearchNote {
            title: title.to_string(),
            path: scope.root().join(relative_path),
            code_citations: Vec::new(),
            degradation: None,
        }],
        compile_state: None,
    }
}

#[test]
fn compile_bundle_contains_required_sections() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let note_path = scope.root().join("raw/research/compile.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(
        &note_path,
        "---\ntitle: Compile behavior\nsource: daemon notes\n---\n\nCitation: Example Docs, Compile API\nConflict: Workers disagree about overwrite behavior.\nGap: Missing benchmark evidence.\nAccepted chunk about durable synthesis handoff.",
    )
    .expect("note written");
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");

    let outcome = prepare_handoff(
        &mut session,
        CompileRequest {
            topic: "Compile behavior".to_string(),
            outline: vec![
                "Durable handoff".to_string(),
                "Synthesis inputs".to_string(),
            ],
            target_page: Some(PathBuf::from("compile-behavior.md")),
            write_intent: false,
        },
    )
    .expect("compile handoff prepared");

    assert_eq!(outcome.bundle.outline.len(), 2);
    assert_eq!(outcome.bundle.accepted_sources.len(), 1);
    assert_eq!(outcome.bundle.citations, vec!["Example Docs, Compile API"]);
    assert_eq!(
        outcome.bundle.conflicting_claims,
        vec!["Workers disagree about overwrite behavior."]
    );
    assert_eq!(
        outcome.bundle.missing_evidence,
        vec!["Missing benchmark evidence."]
    );

    let rendered = std::fs::read_to_string(&outcome.bundle.path).expect("bundle written");
    assert!(rendered.contains("## Topic outline"));
    assert!(rendered.contains("## Accepted sources"));
    assert!(rendered.contains("## Citations"));
    assert!(rendered.contains("## Conflicting claims"));
    assert!(rendered.contains("## Missing evidence"));
}

#[test]
fn compile_handoff_is_non_destructive_by_default() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let page_path = scope.root().join("compile-behavior.md");
    std::fs::write(&page_path, "human-authored wiki page").expect("page written");
    let note_path = scope.root().join("raw/research/compile.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&note_path, "Citation: Example Docs").expect("note written");
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");

    let outcome = prepare_handoff(
        &mut session,
        CompileRequest {
            topic: "Compile behavior".to_string(),
            outline: vec!["Durable handoff".to_string()],
            target_page: Some(PathBuf::from("compile-behavior.md")),
            write_intent: false,
        },
    )
    .expect("compile handoff prepared");

    assert_eq!(
        std::fs::read_to_string(&page_path).expect("page retained"),
        "human-authored wiki page"
    );
    assert_ne!(outcome.bundle.path, page_path);
    assert!(!outcome.state.write_intent);
}

#[test]
fn prepare_handoff_does_not_write_target_page() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let page_path = scope.root().join("compile-behavior.md");
    std::fs::write(&page_path, "human-authored wiki page").expect("page written");
    let note_path = scope.root().join("raw/research/compile.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&note_path, "Citation: Example Docs").expect("note written");
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");

    let outcome = prepare_handoff(
        &mut session,
        CompileRequest {
            topic: "Compile behavior".to_string(),
            outline: vec!["Durable handoff".to_string()],
            target_page: Some(PathBuf::from("compile-behavior.md")),
            write_intent: true,
        },
    )
    .expect("compile handoff prepared");

    assert_eq!(
        std::fs::read_to_string(&page_path).expect("page retained"),
        "human-authored wiki page"
    );
    assert!(outcome.state.write_intent);
}

#[test]
fn compile_fails_on_out_of_scope_accepted_note() {
    let in_scope = tempfile::tempdir().expect("in scope tempdir");
    let out_of_scope = tempfile::tempdir().expect("out of scope tempdir");
    let scope = ResearchScope::project_for_id("project-1", in_scope.path());
    let in_scope_path = scope.root().join("raw/research/in-scope.md");
    std::fs::create_dir_all(in_scope_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&in_scope_path, "Citation: In-scope citation").expect("note written");
    let mut session = session_with_note(&scope, "In scope", "raw/research/in-scope.md");
    session.accepted_notes.push(AcceptedResearchNote {
        title: "Out of scope".to_string(),
        path: out_of_scope.path().join("raw/research/out-of-scope.md"),
        code_citations: Vec::new(),
        degradation: None,
    });
    let out_path = out_of_scope.path().join("raw/research/out-of-scope.md");
    std::fs::create_dir_all(out_path.parent().expect("out parent")).expect("out raw dir");
    std::fs::write(&out_path, "Out of scope citation").expect("out note written");

    let err = prepare_handoff(
        &mut session,
        CompileRequest {
            topic: "Scoped compile".to_string(),
            outline: vec!["Scoped sources".to_string()],
            target_page: None,
            write_intent: false,
        },
    )
    .expect_err("out-of-scope accepted note must fail fast");

    assert!(matches!(
        err,
        WikiError::InvalidInput {
            field: "accepted_note",
            ..
        }
    ));
}

#[test]
fn compile_rejects_absolute_or_escaping_target_pages() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let note_path = scope.root().join("raw/research/compile.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&note_path, "Citation: Example Docs").expect("note written");
    let mut absolute_session =
        session_with_note(&scope, "Compile behavior", "raw/research/compile.md");

    let absolute = prepare_handoff(
        &mut absolute_session,
        CompileRequest {
            topic: "Compile behavior".to_string(),
            outline: vec!["Overview".to_string()],
            target_page: Some(scope.root().join("absolute.md")),
            write_intent: false,
        },
    )
    .expect_err("absolute target page must be rejected");
    assert!(matches!(
        absolute,
        WikiError::InvalidInput {
            field: "target_page",
            ..
        }
    ));

    let mut escaping_session =
        session_with_note(&scope, "Compile behavior", "raw/research/compile.md");
    let escaping = prepare_handoff(
        &mut escaping_session,
        CompileRequest {
            topic: "Compile behavior".to_string(),
            outline: vec!["Overview".to_string()],
            target_page: Some(PathBuf::from("../outside.md")),
            write_intent: false,
        },
    )
    .expect_err("escaping target page must be rejected");
    assert!(matches!(
        escaping,
        WikiError::InvalidInput {
            field: "target_page",
            ..
        }
    ));
}

#[cfg(unix)]
#[test]
fn compile_rejects_target_page_through_symlinked_parent() {
    let vault = tempfile::tempdir().expect("vault tempdir");
    let outside = tempfile::tempdir().expect("outside tempdir");
    std::os::unix::fs::symlink(outside.path(), vault.path().join("linked"))
        .expect("symlink outside");

    let error = write_target_page(
        vault.path(),
        &vault.path().join("linked/outside.md"),
        "# Outside\n",
    )
    .expect_err("symlinked target parent rejected");

    assert!(matches!(
        error,
        WikiError::InvalidInput {
            field: "target_page",
            ..
        }
    ));
}

#[cfg(windows)]
#[test]
fn compile_rejects_target_page_through_symlinked_parent() {
    let vault = tempfile::tempdir().expect("vault tempdir");
    let outside = tempfile::tempdir().expect("outside tempdir");
    if let Err(error) =
        std::os::windows::fs::symlink_dir(outside.path(), vault.path().join("linked"))
    {
        if matches!(
            error.kind(),
            std::io::ErrorKind::PermissionDenied | std::io::ErrorKind::Unsupported
        ) {
            eprintln!("skipping Windows symlink assertion: {error}");
            return;
        }
        panic!("symlink outside: {error}");
    }

    let error = write_target_page(
        vault.path(),
        &vault.path().join("linked/outside.md"),
        "# Outside\n",
    )
    .expect_err("symlinked target parent rejected");

    assert!(matches!(
        error,
        WikiError::InvalidInput {
            field: "target_page",
            ..
        }
    ));
}

#[test]
fn compile_writes_obsidian_markdown() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let note_path = scope.root().join("raw/research/compile.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(
        &note_path,
        concat!(
            "---\n",
            "title: Compile behavior\n",
            "source: daemon notes\n",
            "---\n\n",
            "Citation: Example Docs, Compile API\n",
            "Compile turns accepted notes into source-grounded wiki articles.\n",
            "Evidence sections keep claims traceable to their matching outline entries."
        ),
    )
    .expect("note written");
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");

    let outcome = compile_to_wiki(
        &mut session,
        CompileRequest {
            topic: "Durable Compile".to_string(),
            outline: vec!["Overview".to_string(), "Evidence".to_string()],
            target_page: None,
            write_intent: false,
        },
    )
    .expect("wiki articles compiled");

    let page = std::fs::read_to_string(&outcome.article_path).expect("article written");
    assert!(
        outcome
            .article_path
            .ends_with("knowledge/topics/durable-compile.md")
    );
    assert!(page.starts_with("---\n"));
    assert!(page.contains("title: \"Durable Compile\""));
    assert!(page.contains("source_kind: \"topic\""));
    assert!(page.contains("[[knowledge/sources/compile-behavior|Compile behavior]]"));
    assert!(page.contains("Example Docs, Compile API"));

    let source_page = scope.root().join("knowledge/sources/compile-behavior.md");
    assert!(source_page.exists());
    let provenance =
        std::fs::read_to_string(scope.root().join("meta/provenance.json")).expect("provenance");
    assert!(provenance.contains("knowledge/topics/durable-compile.md"));
    assert!(provenance.contains("raw/research/compile.md"));
    let provenance = ProvenanceGraph::load_from_vault(scope.root()).expect("load provenance graph");
    let links = provenance.links();
    assert_eq!(links.len(), 2);
    assert_eq!(links[0].section.section_id, "durable-compile");
    assert_eq!(links[1].section.section_id, "evidence");
    let article_page = std::path::Path::new("knowledge/topics/durable-compile.md");
    assert_eq!(
        provenance
            .links_for_page_section(article_page, "durable-compile")
            .len(),
        1
    );
    assert_eq!(
        provenance
            .links_for_page_section(article_page, "evidence")
            .len(),
        1
    );
    let source = &provenance.links()[0].source;
    assert!(source.byte_end > source.byte_start);
}

#[test]
fn compile_reuses_existing_source_digest_pages() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let note_body = "Compile turns accepted notes into source-grounded wiki articles.\n";
    let note_path = scope.root().join("raw/research/compile.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&note_path, note_body).expect("note written");
    // Register the note as a manifest source and materialize its digest page,
    // the way session/document ingest does.
    let record = SourceManifest::register(
        scope.root(),
        SourceDraft::new(
            "raw/research/compile.md",
            SourceKind::Text,
            "2026-07-05T00:00:00Z",
            note_body.as_bytes().to_vec(),
        ),
    )
    .expect("source registered");
    let digest_path = scope
        .root()
        .join("knowledge/sources")
        .join(format!("{}.md", record.id));
    std::fs::create_dir_all(digest_path.parent().expect("digest parent")).expect("sources dir");
    std::fs::write(
        &digest_path,
        "---\ntitle: Compile behavior\n---\n\nRich digest body.\n",
    )
    .expect("digest written");
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");

    let outcome = compile_to_wiki(
        &mut session,
        CompileRequest {
            topic: "Durable Compile".to_string(),
            outline: vec!["Overview".to_string()],
            target_page: None,
            write_intent: false,
        },
    )
    .expect("wiki articles compiled");

    // The digest is the only page under knowledge/sources/ — no duplicate stub.
    let entries: Vec<String> = std::fs::read_dir(scope.root().join("knowledge/sources"))
        .expect("sources dir listed")
        .filter_map(Result::ok)
        .map(|entry| entry.file_name().to_string_lossy().into_owned())
        .collect();
    assert_eq!(entries, vec![format!("{}.md", record.id)]);
    assert!(outcome.source_paths.is_empty());
    let article = std::fs::read_to_string(&outcome.article_path).expect("article written");
    assert!(
        article.contains(&format!(
            "[[knowledge/sources/{}|Compile behavior]]",
            record.id
        )),
        "{article}"
    );
    assert_eq!(
        std::fs::read_to_string(&digest_path).expect("digest retained"),
        "---\ntitle: Compile behavior\n---\n\nRich digest body.\n"
    );
}

#[test]
fn recompile_updates_source_stub_pages_in_place() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let note_path = scope.root().join("raw/research/compile.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&note_path, "First compile evidence.\n").expect("note written");
    let request = || CompileRequest {
        topic: "Durable Compile".to_string(),
        outline: vec!["Overview".to_string()],
        target_page: Some(PathBuf::from("knowledge/topics/durable-compile.md")),
        write_intent: true,
    };
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");
    compile_to_wiki(&mut session, request()).expect("first compile succeeded");

    std::fs::write(&note_path, "Recompiled evidence.\n").expect("note rewritten");
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");
    let outcome = compile_to_wiki(&mut session, request()).expect("recompile succeeded");

    // The recompile resolves the stub written by the first compile and
    // updates it in place — no slug-suffixed sibling pages (#17596).
    let entries: Vec<String> = std::fs::read_dir(scope.root().join("knowledge/sources"))
        .expect("sources dir listed")
        .filter_map(Result::ok)
        .map(|entry| entry.file_name().to_string_lossy().into_owned())
        .collect();
    assert_eq!(entries, vec!["compile-behavior.md".to_string()]);
    assert_eq!(
        outcome.source_paths,
        vec![scope.root().join("knowledge/sources/compile-behavior.md")]
    );
    let stub = std::fs::read_to_string(scope.root().join("knowledge/sources/compile-behavior.md"))
        .expect("stub read");
    assert!(stub.contains("Recompiled evidence."), "{stub}");
    assert!(
        stub.contains("source_path: \"raw/research/compile.md\""),
        "{stub}"
    );
}

#[test]
fn recompile_overwrites_source_stub_without_write_intent() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let note_path = scope.root().join("raw/research/shared.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&note_path, "Shared source evidence.\n").expect("note written");

    // A first topic compiles the source, minting its derived stub page.
    let mut first = session_with_note(&scope, "Shared Source", "raw/research/shared.md");
    compile_to_wiki(
        &mut first,
        CompileRequest {
            topic: "First Topic".to_string(),
            outline: vec!["Overview".to_string()],
            target_page: Some(PathBuf::from("knowledge/topics/first-topic.md")),
            write_intent: true,
        },
    )
    .expect("first compile succeeded");

    // A second, brand-new topic references the SAME source with no write
    // intent. Its article is create-only, but the shared source stub already
    // exists — the stub is a deterministic machine digest, so it must overwrite
    // in place rather than fail loud or mint a slug-suffixed sibling (#17707).
    let mut second = session_with_note(&scope, "Shared Source", "raw/research/shared.md");
    let outcome = compile_to_wiki(
        &mut second,
        CompileRequest {
            topic: "Second Topic".to_string(),
            outline: vec!["Overview".to_string()],
            target_page: Some(PathBuf::from("knowledge/topics/second-topic.md")),
            write_intent: false,
        },
    )
    .expect("second compile overwrites shared stub without write intent");

    let entries: Vec<String> = std::fs::read_dir(scope.root().join("knowledge/sources"))
        .expect("sources dir listed")
        .filter_map(Result::ok)
        .map(|entry| entry.file_name().to_string_lossy().into_owned())
        .collect();
    assert_eq!(entries, vec!["shared-source.md".to_string()]);
    assert_eq!(
        outcome.source_paths,
        vec![scope.root().join("knowledge/sources/shared-source.md")]
    );
}

#[test]
fn recompile_without_target_page_updates_article_in_place() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let note_path = scope.root().join("raw/research/compile.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&note_path, "First compile evidence.\n").expect("note written");
    let request = || CompileRequest {
        topic: "Durable Compile".to_string(),
        outline: vec!["Overview".to_string()],
        target_page: None,
        write_intent: true,
    };
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");
    let first = compile_to_wiki(&mut session, request()).expect("first compile succeeded");
    assert_eq!(
        first.article_path,
        scope.root().join("knowledge/topics/durable-compile.md")
    );

    std::fs::write(&note_path, "Recompiled evidence.\n").expect("note rewritten");
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");
    let outcome = compile_to_wiki(&mut session, request()).expect("recompile succeeded");

    // The recompile resolves the article written by the first compile and
    // updates it in place — no -2 suffixed sibling article (#17635).
    assert_eq!(outcome.article_path, first.article_path);
    let entries: Vec<String> = std::fs::read_dir(scope.root().join("knowledge/topics"))
        .expect("topics dir listed")
        .filter_map(Result::ok)
        .map(|entry| entry.file_name().to_string_lossy().into_owned())
        .collect();
    assert_eq!(entries, vec!["durable-compile.md".to_string()]);
    // Resolving the existing page also feeds its body into the synthesis
    // prompt as update-over-create context.
    assert!(
        outcome
            .prompt
            .user
            .contains("update it rather than starting over"),
        "{}",
        outcome.prompt.user
    );
}

#[test]
fn compile_after_recapture_emits_single_digest_without_suffix() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let vault_root = scope.root().to_path_buf();
    let source_path = vault_root.join("recaptured-note.md");

    let mut ai_source = gobby_core::config::EnvOnlySource;
    let mut ai_context = gobby_core::ai_context::AiContext::resolve(None, &mut ai_source);
    let options = crate::api::IngestFileOptions {
        no_ai: true,
        ..crate::api::IngestFileOptions::default()
    };
    options.apply_to_ai_context(&mut ai_context);

    let scope_identity = scope.identity();
    for (body, fetched_at) in [
        ("# Note\n\nFirst capture body.\n", "2026-07-01T00:00:00Z"),
        (
            "# Note\n\nSecond capture body, changed.\n",
            "2026-07-02T00:00:00Z",
        ),
    ] {
        std::fs::write(&source_path, body).expect("write source");
        let mut store = crate::store::MemoryWikiStore::default();
        crate::ingest::file::ingest_path(
            &vault_root,
            &mut store,
            &scope_identity,
            &ai_context,
            &options,
            crate::ingest::file::LocalFileSnapshot {
                path: &source_path,
                fetched_at,
            },
            &mut crate::progress::ProgressOptions::default(),
        )
        .expect("ingest capture");
    }

    // Re-capturing the changed file supersedes the first record (#17644), so
    // the compile input holds a single raw capture for the location.
    let raw_notes: Vec<PathBuf> = std::fs::read_dir(vault_root.join("raw"))
        .expect("raw dir")
        .filter_map(Result::ok)
        .map(|entry| entry.path())
        .filter(|path| {
            path.extension().is_some_and(|ext| ext == "md")
                && path.file_name().is_some_and(|name| name != "INDEX.md")
        })
        .collect();
    assert_eq!(raw_notes.len(), 1, "re-capture keeps a single raw source");

    let mut session = session_with_note(&scope, "Recaptured note", "raw/research/unused.md");
    session.accepted_notes = raw_notes
        .iter()
        .map(|path| AcceptedResearchNote {
            title: "Recaptured note".to_string(),
            path: path.clone(),
            code_citations: Vec::new(),
            degradation: None,
        })
        .collect();

    compile_to_wiki(
        &mut session,
        CompileRequest {
            topic: "Recaptured Note Topic".to_string(),
            outline: vec!["Overview".to_string()],
            target_page: Some(PathBuf::from("knowledge/topics/recaptured-note.md")),
            write_intent: true,
        },
    )
    .expect("compile succeeded");

    let digests: Vec<String> = std::fs::read_dir(vault_root.join("knowledge/sources"))
        .expect("sources dir listed")
        .filter_map(Result::ok)
        .map(|entry| entry.file_name().to_string_lossy().into_owned())
        .collect();
    assert_eq!(
        digests.len(),
        1,
        "single digest page, no -2 sibling: {digests:?}"
    );
    assert!(!digests[0].ends_with("-2.md"), "{digests:?}");
}

#[test]
fn recompile_of_machine_page_overwrites_without_write_intent() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let note_path = scope.root().join("raw/research/compile.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&note_path, "First compile evidence.\n").expect("note written");
    let request = |write_intent: bool| CompileRequest {
        topic: "Durable Compile".to_string(),
        outline: vec!["Overview".to_string()],
        target_page: None,
        write_intent,
    };

    // The first compile authors the machine article; it carries `synthesis_mode`.
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");
    let first = compile_to_wiki(&mut session, request(true)).expect("first compile succeeded");
    assert!(
        std::fs::read_to_string(&first.article_path)
            .expect("article written")
            .contains("synthesis_mode:"),
        "first compile marks the page machine-owned"
    );

    // A recompile with no write intent now refreshes the machine-owned page in
    // place: the page's `synthesis_mode` provenance authorizes the overwrite, so
    // an automated recompile can self-drain re-fetched sources instead of failing
    // loud or minting a slug-suffixed sibling (#17708; supersedes the blanket
    // #17635 fail-loud for machine-owned pages).
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");
    let second = compile_to_wiki(&mut session, request(false))
        .expect("recompile of a machine-owned page overwrites without write intent");
    assert_eq!(second.article_path, first.article_path);

    let articles: Vec<String> =
        std::fs::read_dir(first.article_path.parent().expect("article parent"))
            .expect("article dir listed")
            .filter_map(Result::ok)
            .map(|entry| entry.file_name().to_string_lossy().into_owned())
            .filter(|name| name.ends_with(".md"))
            .collect();
    assert_eq!(articles.len(), 1, "no slug-suffixed sibling: {articles:?}");
}

#[test]
fn recompile_over_hand_authored_page_requires_write_intent() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let note_path = scope.root().join("raw/research/compile.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&note_path, "First compile evidence.\n").expect("note written");
    let target = PathBuf::from("knowledge/topics/hand-authored.md");
    let page_path = scope.root().join(&target);
    std::fs::create_dir_all(page_path.parent().expect("target parent")).expect("target dir");
    let curated = "# Hand authored\n\nCurated by a human; no synthesis_mode.\n";
    std::fs::write(&page_path, curated).expect("page written");

    // A page without `synthesis_mode` provenance is not machine-owned, so the
    // #17635 anti-clobber guard still fails an intent-less recompile loud and
    // never clobbers the human page.
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");
    let error = compile_to_wiki(
        &mut session,
        CompileRequest {
            topic: "Hand Authored".to_string(),
            outline: vec!["Overview".to_string()],
            target_page: Some(target.clone()),
            write_intent: false,
        },
    )
    .expect_err("recompile over a hand-authored page fails loud without write intent");
    assert_eq!(error.code(), "invalid_input");
    assert_eq!(
        std::fs::read_to_string(&page_path).expect("page retained"),
        curated,
        "the human page is never clobbered"
    );
}

#[test]
fn recompile_carries_existing_target_body_into_prompt() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let note_path = scope.root().join("raw/research/compile.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&note_path, "Compile evidence.\n").expect("note written");
    let target_path = scope.root().join("knowledge/topics/durable-compile.md");
    std::fs::create_dir_all(target_path.parent().expect("target parent")).expect("topics dir");
    std::fs::write(
        &target_path,
        "---\ntitle: Stale Title\n---\n\n## Overview\n\nPreviously compiled claim.\n",
    )
    .expect("target written");
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");

    let outcome = compile_to_wiki_with_options(
        &mut session,
        CompileRequest {
            topic: "Durable Compile".to_string(),
            outline: vec!["Overview".to_string()],
            target_page: Some(PathBuf::from("knowledge/topics/durable-compile.md")),
            write_intent: true,
        },
        WikiCompileOptions::default(),
        None,
    )
    .expect("recompile succeeded");

    assert!(
        outcome.prompt.user.contains("Current page content"),
        "{}",
        outcome.prompt.user
    );
    assert!(outcome.prompt.user.contains("Previously compiled claim."));
    // Frontmatter is stripped before the body enters the prompt.
    assert!(!outcome.prompt.user.contains("Stale Title"));
}

#[test]
fn compile_regenerates_index_catalog_from_vault_state() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let topics_dir = scope.root().join("knowledge/topics");
    std::fs::create_dir_all(&topics_dir).expect("topics dir");
    std::fs::write(
        topics_dir.join("existing.md"),
        "---\ntitle: \"Existing Entry\"\n---\n\nAlready compiled body.\n",
    )
    .expect("existing page written");
    let note_path = scope.root().join("raw/research/index.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&note_path, "Index updates keep unrelated entries.").expect("note written");
    let mut session = session_with_note(&scope, "Index behavior", "raw/research/index.md");

    compile_to_wiki(
        &mut session,
        CompileRequest {
            topic: "Index Preservation".to_string(),
            outline: vec!["Overview".to_string()],
            target_page: None,
            write_intent: false,
        },
    )
    .expect("wiki article compiled");

    let index = std::fs::read_to_string(scope.root().join("_index.md")).expect("index read");
    assert!(index.contains("## Overview"), "{index}");
    assert!(
        index.contains("[[knowledge/topics/existing|Existing Entry]]"),
        "{index}"
    );
    assert!(
        index.contains("[[knowledge/topics/index-preservation|Index Preservation]]"),
        "{index}"
    );
    let knowledge = std::fs::read_to_string(scope.root().join("knowledge/INDEX.md"))
        .expect("knowledge index read");
    assert!(
        knowledge.contains("[[knowledge/topics/index-preservation|Index Preservation]]"),
        "{knowledge}"
    );
}

#[test]
fn compile_without_checkpoint_persistence_leaves_research_session_untouched() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let note_path = scope.root().join("raw/research/ephemeral.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&note_path, "Ephemeral compile evidence.").expect("note written");
    let mut session = session_with_note(&scope, "Ephemeral", "raw/research/ephemeral.md");

    compile_to_wiki_with_options(
        &mut session,
        CompileRequest {
            topic: "Ephemeral Compile".to_string(),
            outline: vec!["Overview".to_string()],
            target_page: None,
            write_intent: false,
        },
        WikiCompileOptions {
            persist_checkpoint: false,
            ..WikiCompileOptions::default()
        },
        None,
    )
    .expect("wiki article compiled");

    // Compile state is recorded in memory for the caller...
    assert!(session.compile_state.is_some());
    // ...but the on-disk research checkpoint is never written.
    let checkpoint = ResearchSession::checkpoint_path(scope.root());
    assert!(
        !checkpoint.exists(),
        "persist_checkpoint=false must not write {}",
        checkpoint.display()
    );
}

#[test]
fn compile_appends_page_write_log_entries() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let note_path = scope.root().join("raw/research/logged.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&note_path, "Compile writes go to the log.").expect("note written");
    let mut session = session_with_note(&scope, "Logged compile", "raw/research/logged.md");

    compile_to_wiki(
        &mut session,
        CompileRequest {
            topic: "Logged Compile".to_string(),
            outline: vec!["Overview".to_string()],
            target_page: None,
            write_intent: false,
        },
    )
    .expect("wiki article compiled");

    let log = std::fs::read_to_string(scope.root().join("log.md")).expect("log read");
    let article_line = log
        .lines()
        .find(|line| line.contains("knowledge/topics/logged-compile.md"))
        .expect("article write logged");
    assert!(article_line.starts_with("- "), "{article_line}");
    assert!(article_line.contains("page_created:"), "{article_line}");
    assert!(article_line.contains("Logged Compile"), "{article_line}");
}

#[test]
fn write_target_page_rejects_existing_page_without_overwrite_race() {
    let vault = tempfile::tempdir().expect("vault tempdir");
    let target = vault.path().join("existing.md");
    std::fs::write(&target, "human-authored wiki page").expect("existing page");

    let error = write_target_page(vault.path(), &target, "# Replacement\n")
        .expect_err("existing target rejected");

    assert!(matches!(
        error,
        WikiError::InvalidInput {
            field: "write_intent",
            ..
        }
    ));
    assert_eq!(
        std::fs::read_to_string(&target).expect("existing page retained"),
        "human-authored wiki page"
    );
}

#[test]
fn compile_explainer_generates_grounded_prose_sections() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let note_path = scope.root().join("raw/research/compile.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(
        &note_path,
        "---\ntitle: Compile behavior\n---\n\nCompile turns accepted notes into grounded articles.",
    )
    .expect("note written");
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");

    let mut prompts = Vec::new();
    let outcome = {
        let mut generator = |prompt: &ExplainerPrompt| {
            prompts.push(prompt.user.clone());
            Ok(ExplainerResponse {
                text: "## Overview\nCompile grounds articles in accepted notes \
                       [source: raw/research/compile.md]. It never keeps invented citations \
                       [source: raw/research/invented.md].\n"
                    .to_string(),
                model: Some("mock-model".to_string()),
                route: "daemon",
                tool_use_count: Some(4),
                turns: Some(3),
                usage: Some(TokenUsage {
                    input_tokens: Some(120),
                    output_tokens: Some(45),
                    total_tokens: Some(165),
                }),
            })
        };
        compile_to_wiki_with_options(
            &mut session,
            CompileRequest {
                topic: "Durable Compile".to_string(),
                outline: vec!["Overview".to_string()],
                target_page: None,
                write_intent: false,
            },
            WikiCompileOptions::default(),
            Some(&mut generator),
        )
        .expect("wiki article compiled")
    };

    let page = std::fs::read_to_string(&outcome.article_path).expect("article written");
    assert!(page.contains("synthesis_mode: \"daemon\""), "{page}");
    assert!(!page.contains("degraded:"), "{page}");
    assert!(page.contains("## Overview"), "{page}");
    assert!(
        page.contains("accepted notes [[knowledge/sources/compile-behavior|Compile behavior]]."),
        "{page}"
    );
    assert!(!page.contains("[source:"), "{page}");
    assert!(!page.contains("invented.md"), "{page}");

    let report = outcome.explainer.expect("explainer report");
    assert_eq!(report.status, "generated");
    assert_eq!(report.route, Some("daemon"));
    assert_eq!(report.model.as_deref(), Some("mock-model"));
    assert_eq!(report.tool_use_count, Some(4));
    assert_eq!(report.turns, Some(3));
    assert_eq!(
        report.usage.as_ref().and_then(TokenUsage::token_count),
        Some(165)
    );
    assert_eq!(report.citations_kept, 1);
    assert_eq!(report.citations_stripped, 1);

    assert!(outcome.prompt.tokens_estimated > 0);
    assert_eq!(outcome.prompt.truncated_sources, 0);
    let prompt_user = prompts.first().expect("explainer prompt captured");
    assert!(
        prompt_user.contains("[source: raw/research/compile.md]"),
        "{prompt_user}"
    );
    assert!(
        prompt_user.contains("Compile turns accepted notes"),
        "{prompt_user}"
    );
}

#[test]
fn compile_explainer_failure_degrades_and_keeps_structural_skeleton() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let note_path = scope.root().join("raw/research/compile.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&note_path, "Accepted compile evidence.").expect("note written");
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");

    let mut generator = |_prompt: &ExplainerPrompt| {
        Err::<ExplainerResponse, _>("text lane unavailable".to_string())
    };
    let outcome = compile_to_wiki_with_options(
        &mut session,
        CompileRequest {
            topic: "Degraded Compile".to_string(),
            outline: vec!["Overview".to_string()],
            target_page: None,
            write_intent: false,
        },
        WikiCompileOptions::default(),
        Some(&mut generator),
    )
    .expect("wiki article compiled despite explainer failure");

    let page = std::fs::read_to_string(&outcome.article_path).expect("article written");
    assert!(page.contains("synthesis_mode: \"fallback\""), "{page}");
    assert!(page.contains("degraded: true"), "{page}");
    assert!(page.contains("degraded_sources:"), "{page}");
    assert!(page.contains("  - model_provider_unavailable"), "{page}");
    assert!(page.contains("## Overview"), "{page}");

    let report = outcome.explainer.expect("explainer report");
    assert_eq!(report.status, "failed");
    assert_eq!(report.error.as_deref(), Some("text lane unavailable"));
    assert_eq!(report.citations_kept, 0);
}

#[test]
fn compile_lane_b_failure_hard_fails_without_skeleton() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let note_path = scope.root().join("raw/research/compile.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&note_path, "Accepted compile evidence.").expect("note written");
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");

    let mut generator = |_prompt: &ExplainerPrompt| {
        Err::<ExplainerResponse, _>("tool loop unavailable".to_string())
    };
    // With hard-fail set (Lane B), a generation failure must NOT write a skeleton
    // article — it hard-fails with a distinct error (#982, matching codewiki #978).
    let error = compile_to_wiki_with_options(
        &mut session,
        CompileRequest {
            topic: "Hard Fail Compile".to_string(),
            outline: vec!["Overview".to_string()],
            target_page: Some(PathBuf::from("hard-fail-compile.md")),
            write_intent: true,
        },
        WikiCompileOptions {
            hard_fail_on_generation_failure: true,
            ..WikiCompileOptions::default()
        },
        Some(&mut generator),
    )
    .expect_err("Lane B failure hard-fails");

    assert!(
        matches!(error, crate::WikiError::Generation { .. }),
        "expected a generation error, got: {error}"
    );
    let message = error.to_string();
    assert!(
        message.contains("Lane B compile generation failed"),
        "{message}"
    );
    assert!(message.contains("no skeleton"), "{message}");

    // No synthesized article was written under the vault's knowledge tree.
    assert!(
        !scope.root().join("knowledge").exists(),
        "no skeleton article should be written on Lane B hard-fail"
    );
    assert!(
        !scope.root().join("hard-fail-compile.md").exists(),
        "write-intent target handoff should not be written on Lane B hard-fail"
    );
}

#[test]
fn compile_drops_alias_equal_to_title_and_keeps_case_variants() {
    // Observed case variants become frontmatter aliases, but the variant
    // identical to the page title is pure redundancy — the title is already a
    // resolution key — and every upkeep pass would rewrite it (#17642).
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let note_path = scope.root().join("raw/research/compile.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&note_path, "Accepted compile evidence.").expect("note written");
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");

    let outcome = compile_to_wiki_with_options(
        &mut session,
        CompileRequest {
            topic: "Gcode".to_string(),
            outline: vec!["Overview".to_string()],
            target_page: None,
            write_intent: false,
        },
        WikiCompileOptions {
            target_kind: ArticleKind::Concept,
            aliases: vec!["Gcode".to_string(), "gcode".to_string()],
            ..WikiCompileOptions::default()
        },
        None,
    )
    .expect("wiki article compiled");

    let page = std::fs::read_to_string(&outcome.article_path).expect("article written");
    let parsed = crate::frontmatter::parse_frontmatter(&page).expect("frontmatter parses");
    assert_eq!(parsed.metadata.title.as_deref(), Some("Gcode"));
    assert_eq!(parsed.metadata.aliases, vec!["gcode"]);
}

#[test]
fn compile_without_generator_stays_structural_without_degradation() {
    let temp = tempfile::tempdir().expect("tempdir");
    let scope = ResearchScope::project_for_id("project-1", temp.path());
    let note_path = scope.root().join("raw/research/compile.md");
    std::fs::create_dir_all(note_path.parent().expect("note parent")).expect("raw dir");
    std::fs::write(&note_path, "Accepted compile evidence.").expect("note written");
    let mut session = session_with_note(&scope, "Compile behavior", "raw/research/compile.md");

    let outcome = compile_to_wiki_with_options(
        &mut session,
        CompileRequest {
            topic: "Structural Compile".to_string(),
            outline: vec!["Overview".to_string()],
            target_page: None,
            write_intent: false,
        },
        WikiCompileOptions::default(),
        None,
    )
    .expect("wiki article compiled");

    let page = std::fs::read_to_string(&outcome.article_path).expect("article written");
    assert!(page.contains("synthesis_mode: \"fallback\""), "{page}");
    assert!(!page.contains("degraded:"), "{page}");
    assert!(page.contains("## Overview"), "{page}");

    let report = outcome.explainer.expect("explainer report");
    assert_eq!(report.status, "skipped");
}