Repository navigation
Expand file tree
/
Copy pathtest_compiler.py
More file actions
2832 lines (2489 loc) · 113 KB
/
Copy pathtest_compiler.py
File metadata and controls
2832 lines (2489 loc) · 113 KB
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
"""Tests for openkb.agent.compiler pipeline."""
from __future__ import annotations
import json
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from openkb.agent.compiler import (
_ENTITY_TYPE_LIST,
_add_related_link,
_backlink_concepts,
_backlink_entities,
_backlink_summary,
_backlink_summary_entities,
_compile_concepts,
_filter_entity_items,
_parse_entities_plan,
_parse_json,
_prepend_source_to_frontmatter,
8
_read_concept_briefs,
_read_entity_briefs,
_read_wiki_context,
_remove_source_from_frontmatter,
_sanitize_concept_name,
_update_index,
_write_concept,
_write_entity,
_write_summary,
compile_long_doc,
compile_short_doc,
remove_doc_from_entity_pages,
)
from openkb.config import resolve_entity_types
from openkb.schema import AGENTS_MD
class TestFrontmatterSourceMutation:
"""``_prepend_source_to_frontmatter``/``_remove_source_from_frontmatter`` must preserve existing
frontmatter even when the page ends at the closing ``---`` with no trailing
newline — ``frontmatter.split`` then returns a block ending in a bare
``\\n---`` rather than ``\\n---\\n``.
"""
def test_prepend_preserves_keys_without_trailing_newline(self):
text = '---\nsources: ["summaries/p1.md"]\ntype: "Concept"\ndescription: "Focus"\n---'
out = _prepend_source_to_frontmatter(text, "summaries/p2.md")
assert out.startswith("---\n") # opening delimiter kept
assert 'type: "Concept"' in out # other keys kept
assert 'description: "Focus"' in out
assert "summaries/p1.md" in out # existing source kept
assert "summaries/p2.md" in out # new source prepended
def test_remove_preserves_keys_without_trailing_newline(self):
text = '---\ntype: "Organization"\nsources: ["summaries/doc.md"]\n---'
out, now_empty = _remove_source_from_frontmatter(text, "summaries/doc.md")
assert now_empty is True # it was the only source
assert 'type: "Organization"' in out # other key preserved
assert "summaries/doc.md" not in out # source removed
def test_prepend_with_body_is_unchanged(self):
text = '---\nsources: ["a.md"]\ntype: "Concept"\n---\n\nBody.\n'
out = _prepend_source_to_frontmatter(text, "b.md")
assert out.startswith("---\n")
assert "b.md" in out and "a.md" in out
assert out.endswith("\n\nBody.\n") # body + closing untouched
class TestParseJson:
def test_plain_json(self):
assert _parse_json('[{"name": "foo"}]') == [{"name": "foo"}]
def test_fenced_json(self):
text = '```json\n[{"name": "bar"}]\n```'
assert _parse_json(text) == [{"name": "bar"}]
def test_invalid_json(self):
with pytest.raises((json.JSONDecodeError, ValueError)):
_parse_json("not json")
class TestParseConceptsPlan:
def test_dict_format(self):
text = json.dumps(
{
"create": [{"name": "foo", "title": "Foo"}],
"update": [{"name": "bar", "title": "Bar"}],
"related": ["baz"],
}
)
parsed = _parse_json(text)
assert isinstance(parsed, dict)
assert len(parsed["create"]) == 1
assert len(parsed["update"]) == 1
assert parsed["related"] == ["baz"]
def test_fallback_list_format(self):
text = json.dumps([{"name": "foo", "title": "Foo"}])
parsed = _parse_json(text)
assert isinstance(parsed, list)
def test_fenced_dict(self):
text = '```json\n{"create": [], "update": [], "related": []}\n```'
parsed = _parse_json(text)
assert isinstance(parsed, dict)
assert parsed["create"] == []
class TestParseEntitiesPlan:
def test_extracts_entities_group(self):
parsed = {
"concepts": {"create": [{"name": "x", "title": "X"}], "update": [], "related": []},
"entities": {
"create": [{"name": "anthropic", "title": "Anthropic", "type": "organization"}],
"update": [],
"related": ["nvidia"],
},
}
ents = _parse_entities_plan(parsed)
assert ents["create"] == [
{"name": "anthropic", "title": "Anthropic", "type": "organization"}
]
assert ents["related"] == ["nvidia"]
def test_missing_entities_key_is_empty(self):
ents = _parse_entities_plan({"create": [], "update": [], "related": []})
assert ents == {"create": [], "update": [], "related": []}
def test_bad_type_falls_back_to_other(self):
parsed = {
"entities": {
"create": [{"name": "x", "title": "X", "type": "alien"}],
"update": [],
"related": [],
}
}
ents = _parse_entities_plan(parsed)
assert ents["create"][0]["type"] == "other"
class TestResolveEntityTypes:
def test_default_when_key_absent(self):
assert resolve_entity_types({}) == list(_ENTITY_TYPE_LIST)
def test_custom_list_is_used_and_normalized(self):
out = resolve_entity_types({"entity_types": ["Person", " Dataset ", "MODEL"]})
assert out == ["person", "dataset", "model", "other"]
def test_always_includes_other(self):
out = resolve_entity_types({"entity_types": ["person", "dataset"]})
assert "other" in out
# already-present "other" is not duplicated
out2 = resolve_entity_types({"entity_types": ["dataset", "other"]})
assert out2.count("other") == 1
def test_dedupes_preserving_order(self):
out = resolve_entity_types({"entity_types": ["a", "a", "b"]})
assert out == ["a", "b", "other"]
def test_malformed_string_falls_back_to_default(self):
assert resolve_entity_types({"entity_types": "person"}) == list(_ENTITY_TYPE_LIST)
def test_empty_list_falls_back_to_default(self):
assert resolve_entity_types({"entity_types": []}) == list(_ENTITY_TYPE_LIST)
def test_all_empty_strings_falls_back_to_default(self):
assert resolve_entity_types({"entity_types": ["", " "]}) == list(_ENTITY_TYPE_LIST)
def test_sanitizes_punctuation_and_skips_non_strings(self):
# '{'/'}' and other punctuation are stripped (so they can't leak into a
# prompt template's .format()); non-string items (YAML null, ints) are
# skipped (str(None) must NOT become the type "none").
out = resolve_entity_types({"entity_types": ["Per{son}", None, 123, "data set!"]})
assert out == ["person", "data set", "other"]
class TestFilterEntityItemsCustomTypes:
def test_custom_type_in_valid_types_is_kept(self):
valid = frozenset({"person", "dataset", "other"})
items = [{"name": "imagenet", "title": "ImageNet", "type": "dataset"}]
out = _filter_entity_items(items, valid)
assert out == [{"name": "imagenet", "title": "ImageNet", "type": "dataset"}]
def test_type_not_in_valid_types_is_coerced_to_other(self):
valid = frozenset({"person", "dataset", "other"})
items = [{"name": "x", "title": "X", "type": "organization"}]
out = _filter_entity_items(items, valid)
assert out[0]["type"] == "other"
def test_default_valid_types_backward_compat(self):
# No valid_types arg → module default enum is used.
items = [{"name": "x", "title": "X", "type": "organization"}]
out = _filter_entity_items(items)
assert out[0]["type"] == "organization"
class TestParseBriefContent:
def test_dict_with_brief_and_content(self):
text = json.dumps({"brief": "A short desc", "content": "# Full page\n\nDetails."})
parsed = _parse_json(text)
assert parsed["brief"] == "A short desc"
assert "# Full page" in parsed["content"]
def test_plain_text_fallback(self):
"""If LLM returns plain text, _parse_json raises — caller handles fallback."""
with pytest.raises((json.JSONDecodeError, ValueError)):
_parse_json("Just plain markdown text without JSON")
class TestSanitizeConceptName:
def test_ascii_passthrough(self):
assert _sanitize_concept_name("hello-world") == "hello-world"
def test_spaces_replaced(self):
assert _sanitize_concept_name("hello world") == "hello-world"
def test_chinese(self):
result = _sanitize_concept_name("注意力机制")
assert result == "注意力机制"
def test_japanese(self):
result = _sanitize_concept_name("トランスフォーマー")
assert result == "トランスフォーマー"
def test_french_accents(self):
result = _sanitize_concept_name("réseau neuronal")
assert "r" in result
assert result != "r-seau-neuronal" # accented chars preserved, not stripped
def test_distinct_chinese_names_no_collision(self):
a = _sanitize_concept_name("注意力机制")
b = _sanitize_concept_name("变压器模型")
assert a != b
def test_empty_fallback(self):
assert _sanitize_concept_name("!!!") == "unnamed-concept"
def test_nfkc_normalization(self):
# U+FF21 (fullwidth A) should normalize to regular A
assert _sanitize_concept_name("\uff21\uff22") == "AB"
class TestWriteSummary:
def test_writes_type_and_description(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
_write_summary(wiki, "my-doc", "# Summary\n\nContent.", description="A one-line summary.")
text = (wiki / "summaries" / "my-doc.md").read_text()
assert 'type: "Summary"' in text
assert 'description: "A one-line summary."' in text
assert "doc_type: short" in text
assert 'full_text: "sources/my-doc.md"' in text
assert "# Summary" in text
def test_omits_description_when_empty(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
_write_summary(wiki, "my-doc", "# Summary\n\nContent.")
text = (wiki / "summaries" / "my-doc.md").read_text()
assert 'type: "Summary"' in text
assert "description:" not in text
class TestWriteConcept:
def test_new_concept_with_brief(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
_write_concept(
wiki,
"attention",
"# Attention\n\nDetails.",
"paper.pdf",
False,
brief="Mechanism for selective focus",
)
path = wiki / "concepts" / "attention.md"
assert path.exists()
text = path.read_text()
assert 'sources: ["paper.pdf"]' in text
assert 'description: "Mechanism for selective focus"' in text
assert "# Attention" in text
def test_new_concept_without_brief(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
_write_concept(wiki, "attention", "# Attention\n\nDetails.", "paper.pdf", False)
path = wiki / "concepts" / "attention.md"
assert path.exists()
text = path.read_text()
assert 'sources: ["paper.pdf"]' in text
assert "brief:" not in text
def test_update_concept_updates_brief(self, tmp_path):
wiki = tmp_path / "wiki"
concepts = wiki / "concepts"
concepts.mkdir(parents=True)
(concepts / "attention.md").write_text(
"---\nsources: [paper1.pdf]\nbrief: Old brief\n---\n\n# Attention\n\nOld content.",
encoding="utf-8",
)
_write_concept(wiki, "attention", "New info.", "paper2.pdf", True, brief="Updated brief")
text = (concepts / "attention.md").read_text()
assert "paper2.pdf" in text
assert "paper1.pdf" in text
assert 'description: "Updated brief"' in text
assert "Old brief" not in text
def test_update_concept_appends_source(self, tmp_path):
wiki = tmp_path / "wiki"
concepts = wiki / "concepts"
concepts.mkdir(parents=True)
(concepts / "attention.md").write_text(
"---\nsources: [paper1.pdf]\n---\n\n# Attention\n\nOld content.",
encoding="utf-8",
)
_write_concept(wiki, "attention", "New info from paper2.", "paper2.pdf", True)
text = (concepts / "attention.md").read_text()
assert "paper2.pdf" in text
assert "paper1.pdf" in text
assert "New info from paper2." in text
def test_update_concept_merges_into_non_canonical_sources(self, tmp_path):
"""sources:[a] (no space after colon) must still get paper2 prepended,
matching the helper's behavior in _add_related_link."""
wiki = tmp_path / "wiki"
concepts = wiki / "concepts"
concepts.mkdir(parents=True)
(concepts / "attention.md").write_text(
"---\nsources:[paper1.pdf]\n---\n\n# Attention\n\nOld content.",
encoding="utf-8",
)
_write_concept(wiki, "attention", "New info from paper2.", "paper2.pdf", True)
text = (concepts / "attention.md").read_text()
assert "paper1.pdf" in text
assert "paper2.pdf" in text
assert "New info from paper2." in text
def test_new_concept_has_type_and_description(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
_write_concept(
wiki,
"attention",
"# Attention\n\nDetails.",
"summaries/p.md",
False,
brief="Mechanism for selective focus",
)
text = (wiki / "concepts" / "attention.md").read_text()
assert 'type: "Concept"' in text
assert 'description: "Mechanism for selective focus"' in text
assert "brief:" not in text
def test_new_concept_without_description_still_has_type(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
_write_concept(wiki, "attention", "# Attention\n\nDetails.", "summaries/p.md", False)
text = (wiki / "concepts" / "attention.md").read_text()
assert 'type: "Concept"' in text
assert "description:" not in text
def test_update_concept_sets_type_and_description(self, tmp_path):
wiki = tmp_path / "wiki"
concepts = wiki / "concepts"
concepts.mkdir(parents=True)
(concepts / "attention.md").write_text(
'---\nsources: ["p1.pdf"]\ndescription: "Old"\n---\n\n# Attention\n\nOld.',
encoding="utf-8",
)
_write_concept(wiki, "attention", "New.", "summaries/p2.md", True, brief="New one")
text = (concepts / "attention.md").read_text()
assert 'type: "Concept"' in text
assert 'description: "New one"' in text
assert "Old" not in text
class TestUpdateIndex:
def test_appends_entries_with_briefs(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
(wiki / "index.md").write_text(
"# Index\n\n## Documents\n\n## Concepts\n\n## Explorations\n",
encoding="utf-8",
)
_update_index(
wiki,
"my-doc",
["attention", "transformer"],
doc_brief="Introduces transformers",
concept_briefs={"attention": "Focus mechanism", "transformer": "NN architecture"},
)
text = (wiki / "index.md").read_text()
assert "[[summaries/my-doc]] (short) — Introduces transformers" in text
assert "[[concepts/attention]] — Focus mechanism" in text
assert "[[concepts/transformer]] — NN architecture" in text
def test_updates_only_exact_concept_row(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
(wiki / "index.md").write_text(
"# Index\n\n## Documents\n\n## Concepts\n"
"- [[concepts/transformer]] — Uses [[concepts/attention]] internally\n"
"- [[concepts/attention]] — Old brief\n\n## Explorations\n",
encoding="utf-8",
)
_update_index(
wiki,
"my-doc",
["attention"],
concept_briefs={"attention": "New brief"},
)
text = (wiki / "index.md").read_text()
assert "- [[concepts/transformer]] — Uses [[concepts/attention]] internally" in text
assert "- [[concepts/attention]] — New brief" in text
assert text.count("[[concepts/attention]] — New brief") == 1
def test_no_duplicates(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
(wiki / "index.md").write_text(
"# Index\n\n## Documents\n- [[summaries/my-doc]] — Old brief\n\n## Concepts\n",
encoding="utf-8",
)
_update_index(wiki, "my-doc", [], doc_brief="New brief")
text = (wiki / "index.md").read_text()
assert text.count("[[summaries/my-doc]]") == 1
def test_backwards_compat_no_briefs(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
(wiki / "index.md").write_text(
"# Index\n\n## Documents\n\n## Concepts\n\n## Explorations\n",
encoding="utf-8",
)
_update_index(wiki, "my-doc", ["attention"])
text = (wiki / "index.md").read_text()
assert "[[summaries/my-doc]]" in text
assert "[[concepts/attention]]" in text
def test_updates_concept_brief_only_inside_concepts_section(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
(wiki / "index.md").write_text(
"# Index\n\n"
"## Documents\n"
"- [[summaries/my-doc]] (short) — Mentions [[concepts/attention]] here\n\n"
"## Concepts\n"
"- [[concepts/attention]] — Old brief\n\n"
"## Explorations\n",
encoding="utf-8",
)
_update_index(
wiki,
"my-doc",
["attention"],
concept_briefs={"attention": "New brief"},
)
text = (wiki / "index.md").read_text()
assert "- [[summaries/my-doc]] (short) — Mentions [[concepts/attention]] here" in text
assert "- [[concepts/attention]] — New brief" in text
assert "- [[concepts/attention]] — Old brief" not in text
def test_adds_concept_entry_when_link_exists_outside_concepts_section(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
(wiki / "index.md").write_text(
"# Index\n\n"
"## Documents\n"
"- [[summaries/my-doc]] (short) — Mentions [[concepts/attention]] here\n\n"
"## Concepts\n\n"
"## Explorations\n",
encoding="utf-8",
)
_update_index(
wiki,
"my-doc",
["attention"],
concept_briefs={"attention": "New brief"},
)
text = (wiki / "index.md").read_text()
assert "- [[summaries/my-doc]] (short) — Mentions [[concepts/attention]] here" in text
assert "- [[concepts/attention]] — New brief" in text
def test_recovers_when_documents_section_missing(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
(wiki / "index.md").write_text(
"# Index\n\n## Concepts\n\n## Explorations\n",
encoding="utf-8",
)
_update_index(wiki, "my-doc", [], doc_brief="Brief")
text = (wiki / "index.md").read_text()
assert "## Documents" in text
assert "[[summaries/my-doc]] (short) — Brief" in text
def test_recovers_when_concepts_section_missing(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
(wiki / "index.md").write_text(
"# Index\n\n## Documents\n\n## Explorations\n",
encoding="utf-8",
)
_update_index(wiki, "my-doc", ["attention"], concept_briefs={"attention": "Focus"})
text = (wiki / "index.md").read_text()
assert "## Concepts" in text
assert "[[concepts/attention]] — Focus" in text
assert "[[summaries/my-doc]]" in text
def test_entities_inserted_before_explorations(self, tmp_path):
"""#8: an old index.md predating ## Entities must get it inserted
before ## Explorations, not appended after it (canonical order)."""
wiki = tmp_path / "wiki"
wiki.mkdir()
# Old order: no ## Entities section yet.
(wiki / "index.md").write_text(
"# Index\n\n## Documents\n\n## Concepts\n\n## Explorations\n",
encoding="utf-8",
)
_update_index(
wiki,
"my-doc",
[],
entity_names=["anthropic"],
entity_meta={"anthropic": ("organization", "AI lab.")},
)
text = (wiki / "index.md").read_text()
assert "## Entities" in text
# Canonical order: Entities before Explorations.
assert text.index("## Entities") < text.index("## Explorations")
assert "[[entities/anthropic]] (organization) — AI lab." in text
class TestReadWikiContext:
def test_empty_wiki(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
index, concepts = _read_wiki_context(wiki)
assert index == ""
assert concepts == []
def test_with_content(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
(wiki / "index.md").write_text("# Index\n", encoding="utf-8")
concepts_dir = wiki / "concepts"
concepts_dir.mkdir()
(concepts_dir / "attention.md").write_text("# Attention", encoding="utf-8")
(concepts_dir / "transformer.md").write_text("# Transformer", encoding="utf-8")
index, concepts = _read_wiki_context(wiki)
assert "# Index" in index
assert concepts == ["attention", "transformer"]
class TestReadConceptBriefs:
def test_empty_wiki(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
(wiki / "concepts").mkdir()
assert _read_concept_briefs(wiki) == "(none yet)"
def test_no_concepts_dir(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
assert _read_concept_briefs(wiki) == "(none yet)"
def test_reads_briefs_with_frontmatter(self, tmp_path):
wiki = tmp_path / "wiki"
concepts = wiki / "concepts"
concepts.mkdir(parents=True)
(concepts / "attention.md").write_text(
"---\nsources: [paper.pdf]\n---\n\nAttention is a mechanism that allows models to focus on relevant parts.",
encoding="utf-8",
)
result = _read_concept_briefs(wiki)
assert "- attention:" in result
assert "Attention is a mechanism" in result
assert "sources" not in result
assert "---" not in result
def test_reads_briefs_without_frontmatter(self, tmp_path):
wiki = tmp_path / "wiki"
concepts = wiki / "concepts"
concepts.mkdir(parents=True)
(concepts / "transformer.md").write_text(
"Transformer is a neural network architecture based on attention.",
encoding="utf-8",
)
result = _read_concept_briefs(wiki)
assert "- transformer:" in result
assert "Transformer is a neural network" in result
def test_truncates_long_content(self, tmp_path):
wiki = tmp_path / "wiki"
concepts = wiki / "concepts"
concepts.mkdir(parents=True)
long_body = "A" * 300
(concepts / "longconcept.md").write_text(long_body, encoding="utf-8")
result = _read_concept_briefs(wiki)
# The brief part should be truncated at 150 chars
brief = result.split("- longconcept: ", 1)[1]
assert len(brief) == 150
assert brief == "A" * 150
def test_sorted_alphabetically(self, tmp_path):
wiki = tmp_path / "wiki"
concepts = wiki / "concepts"
concepts.mkdir(parents=True)
(concepts / "zebra.md").write_text("Zebra concept.", encoding="utf-8")
(concepts / "apple.md").write_text("Apple concept.", encoding="utf-8")
(concepts / "mango.md").write_text("Mango concept.", encoding="utf-8")
result = _read_concept_briefs(wiki)
lines = result.strip().splitlines()
slugs = [line.split(":")[0].lstrip("- ") for line in lines]
assert slugs == ["apple", "mango", "zebra"]
def test_reads_brief_from_frontmatter(self, tmp_path):
wiki = tmp_path / "wiki"
concepts = wiki / "concepts"
concepts.mkdir(parents=True)
(concepts / "attention.md").write_text(
"---\nsources: [paper.pdf]\nbrief: Selective focus mechanism\n---\n\n# Attention\n\nLong content...",
encoding="utf-8",
)
result = _read_concept_briefs(wiki)
assert "- attention: Selective focus mechanism" in result
def test_falls_back_to_body_truncation(self, tmp_path):
wiki = tmp_path / "wiki"
concepts = wiki / "concepts"
concepts.mkdir(parents=True)
(concepts / "old.md").write_text(
"---\nsources: [paper.pdf]\n---\n\nOld concept without brief field.",
encoding="utf-8",
)
result = _read_concept_briefs(wiki)
assert "- old: Old concept without brief field." in result
def test_reads_description_field(self, tmp_path):
wiki = tmp_path / "wiki"
concepts = wiki / "concepts"
concepts.mkdir(parents=True)
(concepts / "attention.md").write_text(
'---\nsources: ["p.pdf"]\ndescription: "Selective focus"\n---\n\n# A\n',
encoding="utf-8",
)
assert "- attention: Selective focus" in _read_concept_briefs(wiki)
class TestReadEntityBriefs:
def test_none_when_missing(self, tmp_path):
assert _read_entity_briefs(tmp_path) == "(none yet)"
def test_brief_type_and_source_count(self, tmp_path):
ent = tmp_path / "entities"
ent.mkdir()
(ent / "anthropic.md").write_text(
"---\n"
"sources: [summaries/a.md, summaries/b.md]\n"
"type: organization\n"
"brief: AI lab behind Claude.\n"
"---\n\n# Anthropic\n",
encoding="utf-8",
)
out = _read_entity_briefs(tmp_path)
assert out == "- anthropic (organization, 2 sources) — AI lab behind Claude."
def test_empty_dir_returns_none(self, tmp_path):
ent = tmp_path / "entities"
ent.mkdir()
assert _read_entity_briefs(tmp_path) == "(none yet)"
def test_falls_back_to_body_when_no_brief(self, tmp_path):
ent = tmp_path / "entities"
ent.mkdir()
body_text = "OpenAI is a research lab focused on artificial general intelligence."
(ent / "openai.md").write_text(
"---\n"
"type: organization\n"
"sources: [summaries/a.md, summaries/b.md, summaries/c.md]\n"
"---\n\n" + body_text,
encoding="utf-8",
)
out = _read_entity_briefs(tmp_path)
# Should use truncated body (first 150 chars) as the brief
expected_brief = body_text[:150]
assert f" — {expected_brief}" in out
# Should still include type and source count
assert "(organization, 3 sources)" in out
def test_sorted_alphabetically(self, tmp_path):
ent = tmp_path / "entities"
ent.mkdir()
(ent / "zeta.md").write_text(
"---\ntype: person\nsources: [summaries/a.md]\nbrief: Last letter of Greek alphabet.\n---\n",
encoding="utf-8",
)
(ent / "alpha.md").write_text(
"---\ntype: concept\nsources: [summaries/b.md]\nbrief: First letter of Greek alphabet.\n---\n",
encoding="utf-8",
)
out = _read_entity_briefs(tmp_path)
lines = out.strip().splitlines()
assert lines[0].startswith("- alpha ")
assert lines[1].startswith("- zeta ")
def test_reads_description_and_lowercases_type(self, tmp_path):
ent = tmp_path / "entities"
ent.mkdir()
(ent / "anthropic.md").write_text(
"---\n"
'sources: ["summaries/a.md", "summaries/b.md"]\n'
'type: "Organization"\n'
'description: "AI lab behind Claude."\n'
"---\n\n# Anthropic\n",
encoding="utf-8",
)
out = _read_entity_briefs(tmp_path)
assert out == "- anthropic (organization, 2 sources) — AI lab behind Claude."
def test_reads_legacy_brief_when_no_description(self, tmp_path):
ent = tmp_path / "entities"
ent.mkdir()
(ent / "openai.md").write_text(
"---\ntype: organization\nsources: [summaries/a.md]\n"
"brief: Legacy one-liner.\n---\n\n# OpenAI\n",
encoding="utf-8",
)
out = _read_entity_briefs(tmp_path)
assert "— Legacy one-liner." in out
class TestWriteEntity:
def test_new_entity_frontmatter(self, tmp_path):
_write_entity(
tmp_path,
"anthropic",
"# Anthropic\n\nAI lab.",
"summaries/a.md",
is_update=False,
brief="AI lab behind Claude.",
type_="organization",
aliases=["Anthropic PBC"],
)
text = (tmp_path / "entities" / "anthropic.md").read_text(encoding="utf-8")
assert 'type: "Organization"' in text
assert 'description: "AI lab behind Claude."' in text
assert "sources:" in text and "summaries/a.md" in text
assert "Anthropic PBC" in text
assert text.count("---") == 2 # exactly one frontmatter block
def test_update_prepends_source_keeps_type(self, tmp_path):
_write_entity(
tmp_path,
"anthropic",
"# Anthropic\n\nv1.",
"summaries/a.md",
is_update=False,
brief="b1",
type_="organization",
aliases=None,
)
_write_entity(
tmp_path,
"anthropic",
"# Anthropic\n\nv2 richer.",
"summaries/b.md",
is_update=True,
brief="b2",
type_="organization",
aliases=None,
)
text = (tmp_path / "entities" / "anthropic.md").read_text(encoding="utf-8")
assert "summaries/b.md" in text and "summaries/a.md" in text
# _yaml_list_line uses json.dumps: b prepended before a, double-quoted
assert '"summaries/b.md", "summaries/a.md"' in text
assert 'type: "Organization"' in text
assert "v2 richer." in text
assert "v1." not in text
assert 'descr
10BC8
iption: "b2"' in text
def test_update_rebuilds_frontmatter_when_no_closing_delim(self, tmp_path):
"""#11: malformed existing file (opening --- but no closing ---) must
not drop frontmatter; rebuild valid sources/type/brief on update."""
entities = tmp_path / "entities"
entities.mkdir(parents=True)
# Opening delimiter, NO closing delimiter — find("---", 3) == -1.
(entities / "anthropic.md").write_text(
'---\nsources: ["summaries/a.md"]\ntype: organization\n'
"# Anthropic (no closing fence)\n\nOld body.",
encoding="utf-8",
)
_write_entity(
tmp_path,
"anthropic",
"# Anthropic\n\nv2 rewritten.",
"summaries/b.md",
is_update=True,
brief="AI lab.",
type_="organization",
aliases=None,
)
text = (entities / "anthropic.md").read_text(encoding="utf-8")
# Frontmatter rebuilt with a proper closing delimiter, not body-only.
assert text.startswith("---\n")
assert text.count("---") == 2
assert "sources:" in text and "summaries/b.md" in text
# The PRE-EXISTING source must be preserved, not dropped when rebuilding.
assert "summaries/a.md" in text
assert 'type: "Organization"' in text
assert 'description: "AI lab."' in text
assert "v2 rewritten." in text
def test_new_entity_type_capitalized_and_description(self, tmp_path):
_write_entity(
tmp_path,
"anthropic",
"# Anthropic\n\nAI lab.",
"summaries/a.md",
is_update=False,
brief="AI lab behind Claude.",
type_="organization",
)
text = (tmp_path / "entities" / "anthropic.md").read_text(encoding="utf-8")
assert 'type: "Organization"' in text # capitalized
assert 'description: "AI lab behind Claude."' in text
assert "brief:" not in text # renamed, not duplicated
def test_update_entity_capitalizes_type_and_writes_description(self, tmp_path):
_write_entity(
tmp_path,
"anthropic",
"# A\n\nv1.",
"summaries/a.md",
is_update=False,
brief="b1",
type_="organization",
)
_write_entity(
tmp_path,
"anthropic",
"# A\n\nv2.",
"summaries/b.md",
is_update=True,
brief="b2",
type_="organization",
)
text = (tmp_path / "entities" / "anthropic.md").read_text(encoding="utf-8")
assert 'type: "Organization"' in text
assert 'description: "b2"' in text
assert "brief:" not in text
def test_update_entity_strips_legacy_brief(self, tmp_path):
entities = tmp_path / "entities"
entities.mkdir(parents=True)
(entities / "anthropic.md").write_text(
'---\nsources: ["summaries/a.md"]\ntype: organization\n'
"brief: Old brief.\n---\n\n# Anthropic\n\nOld.",
encoding="utf-8",
)
_write_entity(
tmp_path,
"anthropic",
"# Anthropic\n\nv2.",
"summaries/b.md",
is_update=True,
brief="New desc.",
type_="organization",
)
text = (entities / "anthropic.md").read_text(encoding="utf-8")
assert "brief:" not in text
assert "Old brief." not in text
assert 'description: "New desc."' in text
def test_entity_type_multiword_title_cased(self, tmp_path):
_write_entity(
tmp_path,
"acme",
"# Acme\n\nx.",
"summaries/a.md",
is_update=False,
brief="b",
type_="real estate",
)
text = (tmp_path / "entities" / "acme.md").read_text(encoding="utf-8")
assert 'type: "Real Estate"' in text
def test_update_keeps_single_blank_line_after_frontmatter(tmp_path):
"""Regression: the update path must not accumulate a 3rd newline after ---."""
wiki = tmp_path / "wiki"
(wiki / "concepts").mkdir(parents=True)
(wiki / "concepts" / "x.md").write_text(
'---\ntype: "Concept"\nsources: ["a"]\ndescription: "old"\n---\n\n# X\n', encoding="utf-8"
)
_write_concept(wiki, "x", "# X\n\nNew.", "summaries/b.md", True, brief="new")
ctext = (wiki / "concepts" / "x.md").read_text(encoding="utf-8")
assert "---\n\n\n" not in ctext and "---\n\n" in ctext
(wiki / "entities").mkdir(parents=True)
(wiki / "entities" / "e.md").write_text(
'---\nsources: ["a"]\ntype: "Person"\ndescription: "old"\n---\n\n# E\n', encoding="utf-8"
)
_write_entity(wiki, "e", "# E\n\nNew.", "summaries/b.md", True, brief="new", type_="person")
etext = (wiki / "entities" / "e.md").read_text(encoding="utf-8")
assert "---\n\n\n" not in etext and "---\n\n" in etext
class TestBacklinkSummary:
def test_adds_missing_concept_links(self, tmp_path):
wiki = tmp_path / "wiki"
summaries = wiki / "summaries"
summaries.mkdir(parents=True)
(summaries / "paper.md").write_text(
"---\nsources: [paper.pdf]\n---\n\n# Summary\n\nContent about attention.",
encoding="utf-8",
)
_backlink_summary(wiki, "paper", ["attention", "transformer"])
text = (summaries / "paper.md").read_text()
assert "[[concepts/attention]]" in text
assert "[[concepts/transformer]]" in text
def test_skips_already_linked(self, tmp_path):
wiki = tmp_path / "wiki"
summaries = wiki / "summaries"
summaries.mkdir(parents=True)
(summaries / "paper.md").write_text(
"---\nsources: [paper.pdf]\n---\n\n# Summary\n\nSee [[concepts/attention]].",
encoding="utf-8",
)
_backlink_summary(wiki, "paper", ["attention", "transformer"])
text = (summaries / "paper.md").read_text()
# attention already linked, should not duplicate
assert text.count("[[concepts/attention]]") == 1
# transformer should be added
assert "[[concepts/transformer]]" in text
def test_no_op_when_all_linked(self, tmp_path):
wiki = tmp_path / "wiki"
summaries = wiki / "summaries"
summaries.mkdir(parents=True)
original = "# Summary\n\n[[concepts/attention]] and [[concepts/transformer]]"
(summaries / "paper.md").write_text(original, encoding="utf-8")
_backlink_summary(wiki, "paper", ["attention", "transformer"])
assert (summaries / "paper.md").read_text() == original
def test_skips_if_file_missing(self, tmp_path):
wiki = tmp_path / "wiki"
wiki.mkdir()
# Should not raise
_backlink_summary(wiki, "nonexistent", ["attention"])
def test_merges_into_existing_section(self, tmp_path):
"""Second add should merge into existing ## Related Concepts, not duplicate."""
wiki = tmp_path / "wiki"
summaries = wiki / "summaries"
summaries.mkdir(parents=True)
(summaries / "paper.md").write_text(
"# Summary\n\nContent.\n\n## Related Concepts\n- [[concepts/attention]]\n",
encoding="utf-8",
)
_backlink_summary(wiki, "paper", ["attention", "transformer"])
text = (summaries / "paper.md").read_text()
assert text.count("## Related Concepts") == 1
assert "[[concepts/transformer]]" in text
assert text.count("[[concepts/attention]]") == 1
def test_section_with_trailing_whitespace_still_merges(self, tmp_path):
"""Heading with trailing space must merge into the existing section,
not append a duplicate H2."""
wiki = tmp_path / "wiki"
summaries = wiki / "summaries"
summaries.mkdir(parents=True)
(summaries / "paper.md").write_text(
"# Summary\n\nContent.\n\n## Related Concepts \n- [[concepts/attention]]\n",
encoding="utf-8",
)
_backlink_summary(wiki, "paper", ["attention", "transformer"])
text = (summaries / "paper.md").read_text()
assert "[[concepts/transformer]]" in text
assert text.count("## Related Concepts") == 1
class TestBacklinkConcepts:
def test_adds_summary_link_to_concept(self, tmp_path):
wiki = tmp_path / "wiki"
concepts = wiki / "concepts"
concepts.mkdir(parents=True)
(concepts / "attention.md").write_text(
"---\nsources: [paper.pdf]\n---\n\n# Attention\n\nContent.",
encoding="utf-8",
)
_backlink_concepts(wiki, "paper", ["attention"])
text = (concepts / "attention.md").read_text()
assert "[[summaries/paper]]" in text
assert "## Related Documents" in text