memory-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. memory_cli/__init__.py +1 -0
  2. memory_cli/__main__.py +49 -0
  3. memory_cli/capture/__init__.py +7 -0
  4. memory_cli/capture/codex_rollout.py +164 -0
  5. memory_cli/capture/event_lines.py +66 -0
  6. memory_cli/capture/extract.py +458 -0
  7. memory_cli/capture/state.py +183 -0
  8. memory_cli/commands/__init__.py +21 -0
  9. memory_cli/commands/admin.py +363 -0
  10. memory_cli/commands/common.py +609 -0
  11. memory_cli/commands/curate.py +1189 -0
  12. memory_cli/commands/diagnostics.py +126 -0
  13. memory_cli/commands/edit.py +1282 -0
  14. memory_cli/commands/hooks.py +730 -0
  15. memory_cli/commands/import_recovery.py +45 -0
  16. memory_cli/commands/install.py +152 -0
  17. memory_cli/commands/integrate.py +480 -0
  18. memory_cli/commands/memory.py +2152 -0
  19. memory_cli/commands/read.py +1290 -0
  20. memory_cli/commands/sources.py +766 -0
  21. memory_cli/commands/split.py +97 -0
  22. memory_cli/commands/split_plan.py +196 -0
  23. memory_cli/commands/split_transaction.py +230 -0
  24. memory_cli/commands/synthesis.py +1122 -0
  25. memory_cli/core/__init__.py +16 -0
  26. memory_cli/core/auto_state.py +30 -0
  27. memory_cli/core/codex_pass.py +109 -0
  28. memory_cli/core/config.py +87 -0
  29. memory_cli/core/file_journal.py +163 -0
  30. memory_cli/core/headless.py +130 -0
  31. memory_cli/core/jobs.py +130 -0
  32. memory_cli/core/resources.py +57 -0
  33. memory_cli/core/runner.py +398 -0
  34. memory_cli/core/safe_io.py +155 -0
  35. memory_cli/core/store_git.py +407 -0
  36. memory_cli/core/yaml_load.py +14 -0
  37. memory_cli/corroborate/__init__.py +11 -0
  38. memory_cli/corroborate/cli.py +267 -0
  39. memory_cli/corroborate/decide.py +893 -0
  40. memory_cli/corroborate/digest.py +425 -0
  41. memory_cli/corroborate/fill.py +744 -0
  42. memory_cli/corroborate/job.py +15 -0
  43. memory_cli/corroborate/reword.py +446 -0
  44. memory_cli/corroborate/run.py +1142 -0
  45. memory_cli/corroborate/state.py +300 -0
  46. memory_cli/digest/__init__.py +4 -0
  47. memory_cli/digest/lessons.py +483 -0
  48. memory_cli/entry/__init__.py +12 -0
  49. memory_cli/entry/auto.py +660 -0
  50. memory_cli/entry/capture.py +1403 -0
  51. memory_cli/entry/corroborate.py +214 -0
  52. memory_cli/entry/integrate.py +684 -0
  53. memory_cli/entry/integrate_self_check.py +203 -0
  54. memory_cli/entry/research.py +9 -0
  55. memory_cli/entry/settle.py +614 -0
  56. memory_cli/entry/split_auto.py +460 -0
  57. memory_cli/entry/synthesize.py +22 -0
  58. memory_cli/integrate/__init__.py +9 -0
  59. memory_cli/integrate/answers.py +42 -0
  60. memory_cli/integrate/briefs/check-brief.md +16 -0
  61. memory_cli/integrate/briefs/place-brief.md +26 -0
  62. memory_cli/integrate/log.py +43 -0
  63. memory_cli/integrate/plan.py +125 -0
  64. memory_cli/integrate/rows.py +99 -0
  65. memory_cli/integrate/state.py +158 -0
  66. memory_cli/integrate/undo.py +143 -0
  67. memory_cli/mem.py +1180 -0
  68. memory_cli/memories/__init__.py +16 -0
  69. memory_cli/memories/fingerprints.py +51 -0
  70. memory_cli/memories/journal.py +93 -0
  71. memory_cli/memories/locations.py +282 -0
  72. memory_cli/memories/matching.py +451 -0
  73. memory_cli/memories/model.py +205 -0
  74. memory_cli/memories/parse.py +237 -0
  75. memory_cli/memories/records.py +266 -0
  76. memory_cli/memories/rules.py +291 -0
  77. memory_cli/memories/sightings.py +314 -0
  78. memory_cli/memories/terms.py +148 -0
  79. memory_cli/memories/write.py +358 -0
  80. memory_cli/notes/__init__.py +13 -0
  81. memory_cli/notes/check.py +806 -0
  82. memory_cli/notes/due.py +260 -0
  83. memory_cli/notes/fields.py +217 -0
  84. memory_cli/notes/index.py +230 -0
  85. memory_cli/notes/links.py +170 -0
  86. memory_cli/notes/note.py +222 -0
  87. memory_cli/notes/search.py +391 -0
  88. memory_cli/notes/split_candidates.py +72 -0
  89. memory_cli/research/__init__.py +5 -0
  90. memory_cli/research/checks.py +1065 -0
  91. memory_cli/research/pipeline.py +952 -0
  92. memory_cli/session/__init__.py +5 -0
  93. memory_cli/session/handoff.py +139 -0
  94. memory_cli/session/notices.py +111 -0
  95. memory_cli/settle/__init__.py +5 -0
  96. memory_cli/settle/state.py +111 -0
  97. memory_cli/settle/verdicts.py +693 -0
  98. memory_cli/split/briefs/checker-brief.md +5 -0
  99. memory_cli/split/briefs/editor-brief.md +20 -0
  100. memory_cli/syntheses/__init__.py +8 -0
  101. memory_cli/syntheses/document.py +400 -0
  102. memory_cli/syntheses/edit.py +581 -0
  103. memory_cli/syntheses/project.py +384 -0
  104. memory_cli/syntheses/split_conservation.py +50 -0
  105. memory_cli/syntheses/units.py +427 -0
  106. memory_cli/synthesize/__init__.py +9 -0
  107. memory_cli/synthesize/backfill.py +431 -0
  108. memory_cli/synthesize/briefs/backfill-brief.md +26 -0
  109. memory_cli/synthesize/briefs/checker-brief.md +13 -0
  110. memory_cli/synthesize/briefs/fixer-brief.md +19 -0
  111. memory_cli/synthesize/briefs/memory-brief.md +30 -0
  112. memory_cli/synthesize/briefs/settle-brief.md +32 -0
  113. memory_cli/synthesize/briefs/verdict-brief.md +50 -0
  114. memory_cli/synthesize/briefs/web-brief.md +33 -0
  115. memory_cli/synthesize/cli.py +311 -0
  116. memory_cli/synthesize/pipeline.py +764 -0
  117. memory_cli/synthesize/references.py +164 -0
  118. memory_cli/synthesize/run.py +150 -0
  119. memory_cli/synthesize/topics.py +528 -0
  120. memory_cli/templates/knowledge.md +23 -0
  121. memory_cli/templates/literature.md +25 -0
  122. memory_cli/templates/research.md +23 -0
  123. memory_cli/templates/synthesis.md +6 -0
  124. memory_cli-0.1.0.dist-info/METADATA +102 -0
  125. memory_cli-0.1.0.dist-info/RECORD +128 -0
  126. memory_cli-0.1.0.dist-info/WHEEL +4 -0
  127. memory_cli-0.1.0.dist-info/entry_points.txt +9 -0
  128. memory_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,806 @@
1
+ """The check rule catalog and `check()`. Pure: no git, environment or writes; never mem."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import collections
6
+ import os
7
+ import re
8
+ from pathlib import Path
9
+ from typing import TYPE_CHECKING
10
+
11
+ from memory_cli.notes import index as index_mod
12
+ from memory_cli.notes import note as notes_mod
13
+ from memory_cli.notes.due import rule_requirements
14
+ from memory_cli.notes.fields import (
15
+ _INSTRUCTION_FIX,
16
+ _PART_OF,
17
+ OPTIONAL_FIELDS,
18
+ SCHEMAS,
19
+ Problem,
20
+ _authors,
21
+ instruction_word,
22
+ )
23
+ from memory_cli.notes.index import INDEX_START, index_targets
24
+ from memory_cli.notes.links import rule_links
25
+ from memory_cli.notes.note import (
26
+ FrontmatterError,
27
+ ancestors,
28
+ discover_notes,
29
+ key_line,
30
+ load_topics,
31
+ root_of,
32
+ root_topics,
33
+ slugify,
34
+ )
35
+ from memory_cli.syntheses import document
36
+
37
+ if TYPE_CHECKING:
38
+ from collections.abc import Callable
39
+
40
+ from memory_cli.notes.note import Note
41
+ from memory_cli.syntheses.document import Section, Synthesis
42
+
43
+
44
+ NAME_PATTERNS: dict[str, re.Pattern] = {
45
+ "literature": re.compile(r"[0-9]{4}-[a-z0-9]+-[a-z0-9]+(-[a-z0-9]+)*\.md"),
46
+ "knowledge": re.compile(r"[a-z][a-z0-9]*(-[a-z0-9]+)*\.md"),
47
+ "research": re.compile(r"[0-9]{4}-(0[1-9]|1[0-2])-[a-z0-9]+(-[a-z0-9]+)*"),
48
+ }
49
+ RESERVED_TOPIC = "general"
50
+ _TOPIC_ID = re.compile(r"[a-z][a-z0-9]*(-[a-z0-9]+)*")
51
+ _NAME_FIX = {
52
+ "literature": "rename to year-firstauthor-slug.md",
53
+ "knowledge": "rename to lowercase-words-with-hyphens.md, starting with a letter",
54
+ "research": "rename the folder to YYYY-MM-slug",
55
+ }
56
+
57
+
58
+ REQUIRED_HEADINGS: dict[str, list[str]] = {
59
+ "literature": ["TL;DR", "What the source says", "Our interpretation", "Relevance"],
60
+ "knowledge": ["Claim", "Evidence", "Applies when", "Does not apply when"],
61
+ "research": ["Question", "Status", "Findings", "Contents"],
62
+ }
63
+ # An investigation with its own experiments (spec 5.5, ADR 0008) also states what it improves on.
64
+ BASELINE_HEADING = "Baseline and contribution"
65
+ EXPERIMENT_DIRS = ("code", "results")
66
+
67
+
68
+ def _visible(directory: Path, root: Path) -> list[Path]:
69
+ if not directory.is_dir():
70
+ return []
71
+ return sorted(p for p in directory.iterdir() if not notes_mod._is_hidden(p, root))
72
+
73
+
74
+ def _has_committable_file(folder: Path) -> bool:
75
+ """Whether git would store anything from an investigation folder.
76
+
77
+ Its `data/` and the folders `.gitignore` names stay local, so a folder holding only those (left
78
+ behind when its branch was checked out here) is not an investigation on this branch."""
79
+ for dirpath, dirnames, filenames in os.walk(folder):
80
+ local = _LOCAL_DIRS | ({"data"} if Path(dirpath) == folder else set())
81
+ dirnames[:] = [d for d in dirnames if d not in local]
82
+ if filenames:
83
+ return True
84
+ return False
85
+
86
+
87
+ # Longest knowledge filename stem (characters); longer claims belong in `claim`, not the name (C-10).
88
+ MAX_KNOWLEDGE_NAME = 80
89
+ _LONG_NAME_FIX = (
90
+ f"shorten the filename to at most {MAX_KNOWLEDGE_NAME} characters (keep the full sentence "
91
+ "in `claim`) and update links"
92
+ )
93
+
94
+
95
+ def rule_names(root: Path, notes: list[Note], topics: dict | None) -> list[Problem]:
96
+ """Rule 1: filenames and research folder names; research/ holds only README.md and <id>/."""
97
+ problems = []
98
+ for kind in ("literature", "knowledge"):
99
+ problems += _note_name_problems(root, kind)
100
+ for p in _visible(root / "research", root):
101
+ rel = p.relative_to(root).as_posix()
102
+ if p.is_dir():
103
+ problems += _research_folder_problems(p, rel)
104
+ elif p.name != "README.md":
105
+ problems.append(
106
+ Problem(
107
+ rel,
108
+ 1,
109
+ "not allowed here: research/ holds only README.md and "
110
+ "<id>/ folders; move the file into a research folder",
111
+ )
112
+ )
113
+ return problems
114
+
115
+
116
+ def _name_message(kind: str, p: Path) -> str | None:
117
+ """What is wrong with the file name of a literature or knowledge note, else None."""
118
+ if not NAME_PATTERNS[kind].fullmatch(p.name):
119
+ return f"invalid name: {_NAME_FIX[kind]}"
120
+ if kind != "knowledge":
121
+ return None
122
+ if word := instruction_word(p.stem):
123
+ return f'knowledge name reads as an instruction ("{word}-..."): {_INSTRUCTION_FIX}'
124
+ if len(p.stem) > MAX_KNOWLEDGE_NAME:
125
+ return f"knowledge name too long ({len(p.stem)} characters): {_LONG_NAME_FIX}"
126
+ return None
127
+
128
+
129
+ def _note_name_problems(root: Path, kind: str) -> list[Problem]:
130
+ problems = []
131
+ for domain in _visible(root / kind, root):
132
+ if not domain.is_dir():
133
+ continue
134
+ for p in _visible(domain, root):
135
+ if p.is_file() and p.suffix == ".md" and p.name != "README.md":
136
+ message = _name_message(kind, p)
137
+ if message is not None:
138
+ problems.append(Problem(p.relative_to(root).as_posix(), 1, message))
139
+ return problems
140
+
141
+
142
+ def _research_folder_problems(p: Path, rel: str) -> list[Problem]:
143
+ problems = []
144
+ if not NAME_PATTERNS["research"].fullmatch(p.name):
145
+ problems.append(Problem(rel, 1, f"invalid name: {_NAME_FIX['research']}"))
146
+ if not (p / "README.md").is_file() and _has_committable_file(p):
147
+ problems.append(
148
+ Problem(
149
+ rel,
150
+ 1,
151
+ f"missing readme: create {rel}/README.md "
152
+ "by copying templates/research.md and filling it",
153
+ )
154
+ )
155
+ return problems
156
+
157
+
158
+ def rule_flat(root: Path, notes: list[Note], topics: dict | None) -> list[Problem]:
159
+ """Rule 7: literature/ and knowledge/ hold README.md and domain folders; those hold only .md files."""
160
+ problems = []
161
+ domains = set(root_topics(topics)) if topics is not None else None
162
+ for kind in ("literature", "knowledge"):
163
+ for p in _visible(root / kind, root):
164
+ rel = p.relative_to(root).as_posix()
165
+ if p.is_dir():
166
+ problems += _flat_folder_problems(root, kind, p, domains)
167
+ elif p.name != "README.md":
168
+ problems.append(
169
+ Problem(
170
+ rel,
171
+ 1,
172
+ f"not allowed here: {kind}/ holds only README.md and "
173
+ f"domain folders; move the file into {kind}/<domain>/",
174
+ )
175
+ )
176
+ return problems
177
+
178
+
179
+ def _flat_folder_problems(
180
+ root: Path, kind: str, p: Path, domains: set[str] | None
181
+ ) -> list[Problem]:
182
+ problems = []
183
+ if domains is not None and p.name not in domains:
184
+ problems.append(
185
+ Problem(
186
+ p.relative_to(root).as_posix(),
187
+ 1,
188
+ f"not allowed here: {kind}/ holds only README.md "
189
+ "and folders named after root topics of "
190
+ "topics.yaml; rename or remove it",
191
+ )
192
+ )
193
+ problems.extend(
194
+ Problem(
195
+ q.relative_to(root).as_posix(),
196
+ 1,
197
+ f"not allowed here: {kind}/{p.name}/ holds only .md notes; move or remove it",
198
+ )
199
+ for q in _visible(p, root)
200
+ if q.is_dir() or q.suffix != ".md"
201
+ )
202
+ return problems
203
+
204
+
205
+ def rule_domain(root: Path, notes: list[Note], topics: dict | None) -> list[Problem]:
206
+ """Rule 8: a literature or knowledge note lives under the root of at least one of its topics."""
207
+ if topics is None:
208
+ return []
209
+ problems = []
210
+ for note in notes:
211
+ listed = note.meta.get("topics") if isinstance(note.meta, dict) else None
212
+ if note.type == "research" or not isinstance(listed, list):
213
+ continue
214
+ domains = set(root_topics(topics))
215
+ roots = list(
216
+ dict.fromkeys(root_of(topics, t) for t in listed if isinstance(t, str) and t in topics)
217
+ )
218
+ roots = [r for r in roots if r in domains]
219
+ if roots and note.path.parent.name not in roots:
220
+ fix = " or ".join(f"{note.type}/{r}/" for r in roots)
221
+ problems.append(
222
+ Problem(note.rel, key_line(note.text, "topics"), f"wrong domain: move to {fix}")
223
+ )
224
+ return problems
225
+
226
+
227
+ def _nonempty_dir(path: Path) -> bool:
228
+ """An empty folder does not count: git does not store it, so the staged snapshot would not see it."""
229
+ return path.is_dir() and any(path.iterdir())
230
+
231
+
232
+ def _heading_problems(note: Note) -> list[Problem]:
233
+ lines = [ln.rstrip() for ln in note.body.split("\n")]
234
+ pos = 0
235
+ problems = []
236
+ for heading in REQUIRED_HEADINGS[note.type]:
237
+ try:
238
+ pos = lines.index(f"## {heading}", pos) + 1
239
+ except ValueError:
240
+ problems.append(
241
+ Problem(
242
+ note.rel,
243
+ note.body_line,
244
+ f"missing heading '## {heading}': add it in the order of the template",
245
+ )
246
+ )
247
+ if (
248
+ note.type == "research"
249
+ and f"## {BASELINE_HEADING}" not in lines
250
+ and any(_nonempty_dir(note.path.parent / d) for d in EXPERIMENT_DIRS)
251
+ ):
252
+ problems.append(
253
+ Problem(
254
+ note.rel,
255
+ note.body_line,
256
+ f"missing heading '## {BASELINE_HEADING}' (required once code/ or results/ exists, "
257
+ "spec 5.5): add it, naming the strongest published method that fits our constraints, "
258
+ "the change tested against it and the result",
259
+ )
260
+ )
261
+ return problems
262
+
263
+
264
+ def rule_schema(root: Path, notes: list[Note], topics: dict | None) -> list[Problem]:
265
+ """Rule 2: frontmatter present, closed schema, typed values, required headings."""
266
+ problems = []
267
+ for note in notes:
268
+ shape = _frontmatter_shape_problem(note)
269
+ if shape is not None:
270
+ problems.append(shape)
271
+ continue
272
+ problems += _field_problems(note)
273
+ problems += _heading_problems(note)
274
+ return problems
275
+
276
+
277
+ def _frontmatter_shape_problem(note: Note) -> Problem | None:
278
+ if note.error is not None:
279
+ return Problem(
280
+ note.rel,
281
+ note.error_line,
282
+ f"invalid frontmatter ({note.error}): fix the block at the top of the file",
283
+ )
284
+ if not isinstance(note.meta, dict):
285
+ return Problem(
286
+ note.rel,
287
+ 1,
288
+ "invalid frontmatter (it must be a mapping of fields): rewrite it as key: value lines",
289
+ )
290
+ return None
291
+
292
+
293
+ def _field_problems(note: Note) -> list[Problem]:
294
+ schema = SCHEMAS[note.type]
295
+ problems = [
296
+ Problem(note.rel, 1, f"missing field '{field}': add it to the frontmatter")
297
+ for field in schema
298
+ if field not in note.meta and field not in OPTIONAL_FIELDS
299
+ ]
300
+ for field, value in note.meta.items():
301
+ line = key_line(note.text, str(field))
302
+ if field not in schema:
303
+ problems.append(
304
+ Problem(
305
+ note.rel, line, f"unknown field '{field}': remove it (the schema is closed)"
306
+ )
307
+ )
308
+ elif (fix := schema[field](value)) is not None:
309
+ problems.append(Problem(note.rel, line, f"invalid value for '{field}': {fix}"))
310
+ return problems
311
+
312
+
313
+ def _starts_with_author(tokens: list[str], first: str) -> bool:
314
+ """True when the slug's first tokens spell the author again ("ethereum-org" for "ethereumorg")."""
315
+ return any("".join(tokens[:k]) == first for k in range(1, len(tokens) + 1))
316
+
317
+
318
+ def rule_consistency(root: Path, notes: list[Note], topics: dict | None) -> list[Problem]:
319
+ """Rule 3: literature year/author and research started match the file name."""
320
+ problems = []
321
+ for note in notes:
322
+ if not isinstance(note.meta, dict) or note.error is not None:
323
+ continue
324
+ if note.type == "literature":
325
+ problems += _literature_consistency(note)
326
+ elif note.type == "research":
327
+ problems += _started_consistency(note)
328
+ return problems
329
+
330
+
331
+ def _repeat_problem(note: Note, first: str, rest: list[str]) -> Problem | None:
332
+ name = note.path.name
333
+ if rest and _starts_with_author(rest, first):
334
+ kind = "author"
335
+ elif rest and rest[0] == name[:4]:
336
+ kind = "year"
337
+ else:
338
+ return None
339
+ return Problem(
340
+ note.rel, 1, f"{kind} repeated in filename: rename to {name[:4]}-{first}-<rest>.md"
341
+ )
342
+
343
+
344
+ def _literature_consistency(note: Note) -> list[Problem]:
345
+ name = note.path.name
346
+ if not NAME_PATTERNS["literature"].fullmatch(name):
347
+ return []
348
+ _, first, *rest = name.removesuffix(".md").split("-")
349
+ problems = []
350
+ if (repeat := _repeat_problem(note, first, rest)) is not None:
351
+ problems.append(repeat)
352
+ year = note.meta.get("year")
353
+ if isinstance(year, int) and str(year) != name[:4]:
354
+ problems.append(
355
+ Problem(
356
+ note.rel,
357
+ key_line(note.text, "year"),
358
+ f"year mismatch: set year to {name[:4]} or rename the file",
359
+ )
360
+ )
361
+ authors = note.meta.get("authors")
362
+ if isinstance(authors, list) and _authors(authors) is None and slugify(authors[0]) != first:
363
+ problems.append(
364
+ Problem(
365
+ note.rel,
366
+ key_line(note.text, "authors"),
367
+ f"author mismatch: first author must slugify to '{first}'; "
368
+ "fix authors or rename the file",
369
+ )
370
+ )
371
+ return problems
372
+
373
+
374
+ def _started_consistency(note: Note) -> list[Problem]:
375
+ folder = note.path.parent.name
376
+ started = note.meta.get("started")
377
+ if (
378
+ NAME_PATTERNS["research"].fullmatch(folder)
379
+ and isinstance(started, str)
380
+ and started != folder[:7]
381
+ ):
382
+ return [
383
+ Problem(
384
+ note.rel,
385
+ key_line(note.text, "started"),
386
+ f'started mismatch: set started to "{folder[:7]}" or rename the folder',
387
+ )
388
+ ]
389
+ return []
390
+
391
+
392
+ def rule_topics_used(root: Path, notes: list[Note], topics: dict | None) -> list[Problem]:
393
+ """Rule 4: topics exist, are listed with every ancestor, and are not empty."""
394
+ if topics is None:
395
+ return []
396
+ problems = []
397
+ for note in notes:
398
+ listed = note.meta.get("topics") if isinstance(note.meta, dict) else None
399
+ if not isinstance(listed, list):
400
+ continue
401
+ problems += _note_topic_problems(note, listed, topics)
402
+ return problems
403
+
404
+
405
+ def _note_topic_problems(note: Note, listed: list, topics: dict) -> list[Problem]:
406
+ line = key_line(note.text, "topics")
407
+ problems = []
408
+ if not listed:
409
+ problems.append(
410
+ Problem(
411
+ note.rel, line, "at least one topic is required: list a topic id from topics.yaml"
412
+ )
413
+ )
414
+ names = [t for t in listed if isinstance(t, str)]
415
+ for t in names:
416
+ if t not in topics:
417
+ problems.append(
418
+ Problem(
419
+ note.rel,
420
+ line,
421
+ f"unknown topic '{t}': use an id from topics.yaml or add it there",
422
+ )
423
+ )
424
+ continue
425
+ problems.extend(
426
+ Problem(note.rel, line, f"missing ancestor '{a}' of '{t}': add '{a}' to topics")
427
+ for a in ancestors(topics, t)
428
+ if a not in names
429
+ )
430
+ return problems
431
+
432
+
433
+ def _topic_line(text: str, tid: object) -> int:
434
+ for i, ln in enumerate(text.split("\n"), 1):
435
+ if re.match(rf"{re.escape(str(tid))}[ \t]*:", ln):
436
+ return i
437
+ return 1
438
+
439
+
440
+ def rule_topics_file(root: Path, notes: list[Note], topics: dict | None) -> list[Problem]:
441
+ """Rule 5: topics.yaml follows 5.6."""
442
+ if topics is None:
443
+ return []
444
+ text = notes_mod._read_text(root / "topics.yaml")
445
+ problems = []
446
+ for tid, entry in topics.items():
447
+ problems += _topic_entry_problems(tid, entry, topics, text)
448
+ problems += _topic_cycle_problems(topics, text)
449
+ return problems
450
+
451
+
452
+ def _bad_topic(text: str, tid: object, why: str, fix: str) -> Problem:
453
+ return Problem(
454
+ "topics.yaml", _topic_line(text, tid), f"invalid topics file entry '{tid}' ({why}): {fix}"
455
+ )
456
+
457
+
458
+ def _topic_entry_problems(tid: object, entry: object, topics: dict, text: str) -> list[Problem]:
459
+ if not isinstance(tid, str) or not _TOPIC_ID.fullmatch(tid):
460
+ return [
461
+ _bad_topic(
462
+ text,
463
+ tid,
464
+ "not a valid id",
465
+ "use lowercase words with hyphens, starting with a letter",
466
+ )
467
+ ]
468
+ if tid == RESERVED_TOPIC:
469
+ return [
470
+ Problem(
471
+ "topics.yaml",
472
+ _topic_line(text, tid),
473
+ f"topic id '{tid}' is reserved (it is the fallback heading of "
474
+ "domain indexes): rename it",
475
+ )
476
+ ]
477
+ if not isinstance(entry, dict):
478
+ return [
479
+ _bad_topic(
480
+ text, tid, "not a mapping", "write it as {parent: ..., description: ...} or {}"
481
+ )
482
+ ]
483
+ return _topic_field_problems(tid, entry, topics, text)
484
+
485
+
486
+ def _topic_field_problems(tid: str, entry: dict, topics: dict, text: str) -> list[Problem]:
487
+ problems = [
488
+ _bad_topic(text, tid, f"unknown field '{key}'", "keep only parent and description")
489
+ for key in entry
490
+ if key not in {"parent", "description"}
491
+ ]
492
+ if "description" in entry and not isinstance(entry["description"], str):
493
+ problems.append(
494
+ _bad_topic(text, tid, "description is not a string", "write a one-line description")
495
+ )
496
+ parent = entry.get("parent")
497
+ if "parent" in entry and not isinstance(parent, str):
498
+ problems.append(
499
+ _bad_topic(text, tid, "parent is not a string", "set parent to an existing topic id")
500
+ )
501
+ elif isinstance(parent, str) and parent not in topics:
502
+ problems.append(
503
+ Problem(
504
+ "topics.yaml",
505
+ _topic_line(text, tid),
506
+ f"unknown parent '{parent}' of '{tid}': add '{parent}' "
507
+ "or point parent at an existing topic",
508
+ )
509
+ )
510
+ return problems
511
+
512
+
513
+ def _topic_cycle_problems(topics: dict, text: str) -> list[Problem]:
514
+ problems = []
515
+ for tid in topics:
516
+ seen, current = set(), notes_mod._parent(topics, tid) if isinstance(tid, str) else None
517
+ while isinstance(current, str) and current not in seen:
518
+ if current == tid:
519
+ problems.append(
520
+ Problem(
521
+ "topics.yaml",
522
+ _topic_line(text, tid),
523
+ f"cycle through '{tid}': break the parent chain",
524
+ )
525
+ )
526
+ break
527
+ seen.add(current)
528
+ current = notes_mod._parent(topics, current)
529
+ return problems
530
+
531
+
532
+ def rule_placeholders(root: Path, notes: list[Note], topics: dict | None) -> list[Problem]:
533
+ """Rule 10: no TODO(hub): lines left in typed notes."""
534
+ return [
535
+ Problem(note.rel, i, "placeholder left from the template: replace the TODO(hub): text")
536
+ for note in notes
537
+ for i, line in enumerate(note.text.split("\n"), 1)
538
+ if line.startswith("TODO(hub):")
539
+ ]
540
+
541
+
542
+ MAX_FILE_BYTES = 5 * 1024 * 1024
543
+ _UNTRACKED_DIRS = frozenset({
544
+ "__pycache__",
545
+ ".venv",
546
+ "target",
547
+ "node_modules",
548
+ }) # .gitignore entries; hidden ones (.sources/) are skipped as hidden
549
+ _LOCAL_DIRS = _UNTRACKED_DIRS | {
550
+ ".pytest_cache",
551
+ ".sources",
552
+ ".playwright-mcp",
553
+ } # every folder name .gitignore keeps out of git
554
+
555
+
556
+ def rule_file_size(root: Path, notes: list[Note], topics: dict | None) -> list[Problem]:
557
+ """Rule 13: no file over 5 MB (sizes only; contents are never read)."""
558
+ problems = []
559
+ for dirpath, dirnames, filenames in os.walk(root):
560
+ local_data = (
561
+ {"data"} if Path(dirpath).parent == root / "research" else set()
562
+ ) # research/*/data/ never reaches git
563
+ dirnames[:] = sorted(
564
+ d
565
+ for d in dirnames
566
+ if not d.startswith(".") and d not in _UNTRACKED_DIRS and d not in local_data
567
+ )
568
+ for name in sorted(filenames):
569
+ path = Path(dirpath) / name
570
+ if name.startswith("."):
571
+ continue
572
+ try: # lstat: git stores a symlink, not its target; a broken or vanished file is not an error
573
+ size = path.lstat().st_size
574
+ except OSError:
575
+ continue
576
+ if size > MAX_FILE_BYTES:
577
+ problems.append(
578
+ Problem(
579
+ path.relative_to(root).as_posix(),
580
+ 1,
581
+ "file over 5 MB: keep it out of git and link it by https:// URL (spec 5.1)",
582
+ )
583
+ )
584
+ return problems
585
+
586
+
587
+ def rule_handles(root: Path, notes: list[Note], topics: dict | None) -> list[Problem]:
588
+ """Rule 14: no two typed notes share a handle (`_handle`), so a handle names one note."""
589
+ groups: dict[str, list[str]] = collections.defaultdict(list)
590
+ for note in notes:
591
+ groups[notes_mod._handle(note.rel)].append(note.rel)
592
+ return [
593
+ Problem(
594
+ rel,
595
+ 1,
596
+ f'handle "{h}" is also used by {", ".join(r for r in rels if r != rel)}: '
597
+ "rename one so a handle names one note",
598
+ )
599
+ for h, rels in groups.items()
600
+ if len(rels) > 1
601
+ for rel in rels
602
+ ]
603
+
604
+
605
+ def rule_syntheses(root: Path, notes: list[Note], topics: dict | None) -> list[Problem]:
606
+ """Rule 15: each synthesis parses, repeats no section handle, uses known topics and ends every part with a
607
+ valid `Sources:` line; a reference names a source and has a sentence before it, and no reference or source
608
+ names a superseded note."""
609
+ loaded = document.load(root / document.SYNTHESES_DIR)
610
+ superseded = {
611
+ (root / n.rel).resolve(): n.meta["superseded_by"]
612
+ for n in notes
613
+ if n.error is None
614
+ and isinstance(n.meta, dict)
615
+ and isinstance(n.meta.get("superseded_by"), str)
616
+ }
617
+ problems = []
618
+ for note in notes:
619
+ problem = _part_of_problem(note, loaded)
620
+ if problem is not None:
621
+ problems.append(problem)
622
+ for syn in loaded:
623
+ problems += _synthesis_problems(syn, root, topics, superseded)
624
+ return problems
625
+
626
+
627
+ def _part_of_problem(note: Note, loaded: list[Synthesis]) -> Problem | None:
628
+ part = note.meta.get("part_of") if note.error is None and isinstance(note.meta, dict) else None
629
+ if not isinstance(part, str) or not _PART_OF.fullmatch(part):
630
+ return None
631
+ handle, _, section = part.partition("#")
632
+ syn = next((x for x in loaded if x.handle == handle and x.error is None), None)
633
+ if syn is None:
634
+ return Problem(
635
+ note.rel,
636
+ key_line(note.text, "part_of"),
637
+ f"part_of names s:{handle}, which does not exist: fix or remove part_of",
638
+ )
639
+ if not any(sec.handle == section for sec in syn.sections):
640
+ return Problem(
641
+ note.rel,
642
+ key_line(note.text, "part_of"),
643
+ f"part_of names the section {section} of s:{handle}, which does not exist: "
644
+ "fix or remove part_of",
645
+ )
646
+ return None
647
+
648
+
649
+ def _section_messages(sec: Section, root: Path, superseded: dict) -> list[str]:
650
+ if sec.handle == document.SUMMARY:
651
+ return document.summary_problems(sec.text)
652
+ msgs = document.validate_section(sec.text, root)
653
+ base = (root / document.SYNTHESES_DIR).resolve()
654
+ cited = [("reference", t) for t in dict.fromkeys(document.references(sec.text))]
655
+ cited += [("source", t) for t in sec.sources]
656
+ for kind, target in cited:
657
+ successor = superseded.get(document._resolved(base, target))
658
+ if successor:
659
+ msgs.append(f"{kind} {target} is superseded by {successor}: point to it")
660
+ return msgs
661
+
662
+
663
+ def _synthesis_problems(
664
+ syn: Synthesis, root: Path, topics: dict | None, superseded: dict
665
+ ) -> list[Problem]:
666
+ rel = syn.path.relative_to(root).as_posix()
667
+ if syn.error:
668
+ return [
669
+ Problem(
670
+ rel,
671
+ 1,
672
+ f"synthesis cannot be parsed ({syn.error}): fix the frontmatter "
673
+ "and start the body with `## Summary`",
674
+ )
675
+ ]
676
+ problems = [
677
+ Problem(rel, 1, f"unknown topic '{t}': use an id from topics.yaml or add it there")
678
+ for t in syn.topics
679
+ if topics is not None and t not in topics
680
+ ]
681
+ seen: set[str] = set()
682
+ for sec in syn.sections:
683
+ if sec.handle in seen:
684
+ problems.append(
685
+ Problem(
686
+ rel, sec.line, f'repeated section handle "{sec.handle}": rename one heading'
687
+ )
688
+ )
689
+ seen.add(sec.handle)
690
+ problems.extend(
691
+ Problem(rel, sec.line, f'section "{sec.heading}": {msg}')
692
+ for msg in _section_messages(sec, root, superseded)
693
+ )
694
+ return problems
695
+
696
+
697
+ def rule_supersession(root: Path, notes: list[Note], topics: dict | None) -> list[Problem]:
698
+ """Rule 16: `superseded_by` and `distinct_from` name notes that exist."""
699
+ handles = {notes_mod._handle(n.rel) for n in notes}
700
+ problems = []
701
+ for note in notes:
702
+ if note.error is not None or not isinstance(note.meta, dict):
703
+ continue
704
+ named = [("superseded_by", note.meta.get("superseded_by"))]
705
+ named += (
706
+ [
707
+ ("distinct_from", h)
708
+ for h in (note.meta.get("distinct_from") or [])
709
+ if isinstance(h, str)
710
+ ]
711
+ if isinstance(note.meta.get("distinct_from"), list)
712
+ else []
713
+ )
714
+ for field, value in named:
715
+ if isinstance(value, str) and value not in handles:
716
+ problems.append(
717
+ Problem(
718
+ note.rel,
719
+ key_line(note.text, field),
720
+ f"{field} names {value}, which is not a note: fix or remove {field}",
721
+ )
722
+ )
723
+ return problems
724
+
725
+
726
+ def rule_index_fresh(root: Path, notes: list[Note], topics: dict | None) -> list[Problem]:
727
+ """Rule 9: generated index blocks are current."""
728
+ if topics is None:
729
+ return []
730
+ problems = []
731
+ for path, block, default in index_targets(root, notes, topics):
732
+ problem = _index_problem(path.relative_to(root).as_posix(), path, block, default)
733
+ if problem is not None:
734
+ problems.append(problem)
735
+ return problems
736
+
737
+
738
+ def _index_start_line(text: str) -> int:
739
+ start = text.find(INDEX_START)
740
+ return text.count("\n", 0, start) + 1 if start >= 0 else 1
741
+
742
+
743
+ def _index_problem(rel: str, path: Path, block: str, default: object) -> Problem | None:
744
+ if not path.is_file():
745
+ return Problem(rel, 1, "missing readme: run mem index") if default is not None else None
746
+ try:
747
+ text = notes_mod._read_text(path)
748
+ except FrontmatterError as exc:
749
+ return Problem(rel, 1, f"unreadable index README ({exc}): save it as UTF-8 text")
750
+ try:
751
+ current = index_mod._with_index(text, block) == text
752
+ except FrontmatterError as exc:
753
+ return Problem(rel, _index_start_line(text), str(exc))
754
+ return None if current else Problem(rel, _index_start_line(text), "index stale: run mem index")
755
+
756
+
757
+ RULES = [
758
+ rule_names,
759
+ rule_flat,
760
+ rule_domain,
761
+ rule_schema,
762
+ rule_consistency,
763
+ rule_topics_used,
764
+ rule_topics_file,
765
+ rule_links,
766
+ rule_index_fresh,
767
+ rule_placeholders,
768
+ rule_requirements,
769
+ rule_file_size,
770
+ rule_handles,
771
+ rule_syntheses,
772
+ rule_supersession,
773
+ ]
774
+
775
+
776
+ def check(root: Path) -> list[Problem]:
777
+ problems: list[Problem] = []
778
+ try:
779
+ topics: dict | None = load_topics(root)
780
+ except FrontmatterError as exc:
781
+ topics = None
782
+ problems.append(
783
+ Problem(
784
+ "topics.yaml",
785
+ exc.line,
786
+ f"topics file unusable ({exc}): restore topics.yaml as a mapping of topic ids",
787
+ )
788
+ )
789
+ notes = discover_notes(root)
790
+ for rule in RULES:
791
+ problems += rule(root, notes, topics)
792
+ return sorted(set(problems))
793
+
794
+
795
+ def invalid_changed(store: Path) -> Callable[[list[str]], list[str]]:
796
+ """A validator for `store_git.commit_if_changed`: runs `check` once, on the working tree, and returns the given
797
+ paths that have a problem. The working tree is checked, not the committed snapshot: a committed note may link to a
798
+ held-back one."""
799
+
800
+ def validate(paths: list[str]) -> list[str]:
801
+ bad = {p.path for p in check(store)}
802
+ return [
803
+ p for p in paths if p in bad or any(p.startswith(b + "/") for b in bad)
804
+ ] # a problem may name a folder
805
+
806
+ return validate