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,427 @@
1
+ """The units of a part: sentences and list items with the references on them, and the fingerprints of a part's text.
2
+
3
+ A leaf below `document` and `edit`: `Unit` and its parser, `fingerprint` and friends, and the few link and fence helpers
4
+ that both of them share. Imports nothing from mem.py.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import posixpath
11
+ import re
12
+ import urllib.parse
13
+ from dataclasses import dataclass
14
+ from typing import TYPE_CHECKING
15
+
16
+ if TYPE_CHECKING:
17
+ from collections.abc import Sequence
18
+
19
+ NOTE_FOLDERS = ("literature", "knowledge", "research") # where a Sources link may point
20
+ MIN_NOTE_PARTS = 2
21
+ _FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})")
22
+ _SCHEME = re.compile(r"[a-zA-Z][a-zA-Z0-9+.-]*:")
23
+
24
+
25
+ def _next_fence(fence: str | None, marker: str) -> str | None:
26
+ """The fence state after a line that opens or closes with `marker` (its first character)."""
27
+ return None if fence and marker == fence else (fence or marker)
28
+
29
+
30
+ def _relative(target: str) -> bool:
31
+ return not target.startswith(("#", "mailto:")) and not _SCHEME.match(target)
32
+
33
+
34
+ def _file_part(target: str) -> str:
35
+ return urllib.parse.unquote(target.split("#", 1)[0])
36
+
37
+
38
+ def _note_key(target: str) -> str:
39
+ return posixpath.normpath(urllib.parse.unquote(_file_part(target)))
40
+
41
+
42
+ _REF_LINK = re.compile(r"\[([^\]]*)\]\(([^)\s]+)\)")
43
+ _INTRO_ITEM = re.compile(
44
+ r"[ \t]*(?:[-*+]|\d+[.)])[ \t]+"
45
+ ) # a list item a colon-final line may introduce
46
+ _LIST_MARK = re.compile(r"(?:>\s*)*(?:(?:[-*+]|\d+[.)])[ \t]+|#{1,6}[ \t]+)?")
47
+ _BOLD_LABEL = re.compile(r"\*\*[^*\n]*[.!?:]\*\*(?=\s|$)")
48
+ _TABLE_SEP = re.compile(r"\s*\|?\s*:?-+:?\s*(?:\|\s*:?-+:?\s*)*\|?\s*")
49
+ _ABBREVIATION = re.compile(r"(?:^|[\s(\[])(?:e\.g|i\.e|et al|vs|cf)$", re.IGNORECASE)
50
+ _CLOSERS = "\"'\u201d\u2019)]\u00bb"
51
+ _GAP = " \t,;"
52
+ _FRONTMATTER_SLOT = "{frontmatter}"
53
+ _SUMMARY_SLOT = "{summary}"
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class Unit:
58
+ """One sentence or table row of a part's body."""
59
+
60
+ n: int # 1-based
61
+ text: str # as stored, including the references that follow the sentence
62
+ plain: str # without references: trailing ones dropped, inline ones reduced to their label
63
+ refs: list[str] # targets (file part), in order
64
+ span: tuple[int, int] # character offsets in the part text, [start, end)
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class _Ref:
69
+ start: int
70
+ end: int
71
+ label: str
72
+ target: str
73
+ trailing: (
74
+ bool # follows the closing punctuation of its sentence: dropped, not reduced to its label
75
+ )
76
+
77
+
78
+ def _is_ref(target: str) -> bool:
79
+ """A relative link into a note folder (the folders may be reached through leading `..`)."""
80
+ if not _relative(target) or target.startswith("/"):
81
+ return False
82
+ parts = [p for p in posixpath.normpath(_file_part(target)).split("/") if p not in {"", "."}]
83
+ while parts and parts[0] == "..":
84
+ parts.pop(0)
85
+ return len(parts) >= MIN_NOTE_PARTS and parts[0] in NOTE_FOLDERS and parts[-1].endswith(".md")
86
+
87
+
88
+ def _inline(raw: str) -> list[tuple[int, int, str, re.Match[str] | None]]:
89
+ """Code spans and links of a line, as (start, end, kind, match); nothing inside them splits or links."""
90
+ found, i = [], 0
91
+ while i < len(raw):
92
+ if raw[i] == "`":
93
+ n = len(raw[i:]) - len(raw[i:].lstrip("`"))
94
+ j = i + n
95
+ while (j := raw.find("`" * n, j)) != -1 and raw[j : j + n + 1] == "`" * (n + 1):
96
+ j += len(raw[j:]) - len(raw[j:].lstrip("`"))
97
+ if j != -1:
98
+ found.append((i, j + n, "code", None))
99
+ i = j + n
100
+ continue
101
+ i += n
102
+ elif raw[i] == "[" and (m := _REF_LINK.match(raw, i)):
103
+ found.append((i, m.end(), "link", m))
104
+ i = m.end()
105
+ else:
106
+ i += 1
107
+ return found
108
+
109
+
110
+ def _remove(text: str, lo: int, hi: int, refs: Sequence[_Ref]) -> str:
111
+ out, pos = [], lo
112
+ for r in refs:
113
+ if r.trailing:
114
+ s = r.start
115
+ while s > pos and text[s - 1] in _GAP:
116
+ s -= 1
117
+ out.append(text[pos:s])
118
+ else:
119
+ out.append(text[pos : r.start] + r.label)
120
+ pos = r.end
121
+ return "".join(out) + text[pos:hi]
122
+
123
+
124
+ def _last_content(lines: list[str]) -> int | None:
125
+ """Index of the last line that is not blank."""
126
+ return next((i for i in range(len(lines) - 1, -1, -1) if lines[i].strip()), None)
127
+
128
+
129
+ def _ref_of(m: re.Match[str], base: int, trailing: bool) -> _Ref:
130
+ return _Ref(base + m.start(), base + m.end(), m.group(1), m.group(2), trailing)
131
+
132
+
133
+ def _list_mark_end(raw: str) -> int:
134
+ m = _LIST_MARK.match(raw)
135
+ return m.end() if m else 0
136
+
137
+
138
+ class _Line:
139
+ """One prose or table line of a body: its links into notes and the scans that look at them."""
140
+
141
+ def __init__(self, raw: str, base: int) -> None:
142
+ self.raw, self.base = raw, base
143
+ spans = _inline(raw)
144
+ self.links = {
145
+ s: (e, m)
146
+ for s, e, kind, m in spans
147
+ if kind == "link" and m is not None and _is_ref(m.group(2))
148
+ }
149
+ self.starts = {s: e for s, e, _, _ in spans}
150
+ self.ce = len(raw.rstrip())
151
+ self.indent = len(raw) - len(raw.lstrip())
152
+
153
+ def ref(self, m: re.Match[str], trailing: bool) -> _Ref:
154
+ return _ref_of(m, self.base, trailing)
155
+
156
+ def skip_gap(self, p: int, chars: str = " \t") -> int:
157
+ while p < self.ce and self.raw[p] in chars:
158
+ p += 1
159
+ return p
160
+
161
+ def only_refs_follow(self, p: int) -> bool:
162
+ # `et al.` ends a unit when only references follow it on the line: the abbreviation stops splitting
163
+ # mid-sentence, but a reference added after it must not merge the unit into its own label.
164
+ p = self.skip_gap(p, _GAP)
165
+ if p >= self.ce or p not in self.links:
166
+ return False
167
+ while p in self.links:
168
+ p = self.skip_gap(self.links[p][0], _GAP)
169
+ return p >= self.ce
170
+
171
+ def colon_intro_head(self, lo: int) -> int | None:
172
+ """Where the references start when the rest of the line is `words:` plus only references."""
173
+ for s0 in sorted(self.links):
174
+ if s0 < lo:
175
+ continue
176
+ p = s0
177
+ while p > lo and self.raw[p - 1] in _GAP:
178
+ p -= 1
179
+ if (
180
+ p > lo
181
+ and self.raw[p - 1] == ":"
182
+ and self.only_refs_follow(s0)
183
+ and re.search(r"\w", self.raw[lo:p])
184
+ ):
185
+ return s0
186
+ break
187
+ return None
188
+
189
+ def table_refs(self) -> list[_Ref]:
190
+ refs = []
191
+ for s, (_, m) in self.links.items():
192
+ k = s
193
+ while k > self.indent and self.raw[k - 1] in _GAP:
194
+ k -= 1
195
+ refs.append(self.ref(m, k > self.indent and self.raw[k - 1] in ".!?" + _CLOSERS))
196
+ return refs
197
+
198
+ def punct_end(self, k: int) -> tuple[int, int]:
199
+ """(end of the run of `.!?` at `k`, end of the closing quotes and brackets after it)."""
200
+ j = k + 1
201
+ while j < self.ce and self.raw[j] in ".!?":
202
+ j += 1
203
+ t = j
204
+ while t < self.ce and self.raw[t] in _CLOSERS:
205
+ t += 1
206
+ return j, t
207
+
208
+ def ends_unit(self, k: int, j: int, t: int, ustart: int) -> bool:
209
+ """Whether the punctuation at `k` (run to `j`, closers to `t`) ends the unit that began at `ustart`."""
210
+ if not (t >= self.ce or self.raw[t].isspace() or t in self.links):
211
+ return False
212
+ abbreviation = (
213
+ self.raw[k] == "."
214
+ and j == k + 1
215
+ and _ABBREVIATION.search(self.raw[ustart:k])
216
+ and not self.only_refs_follow(t)
217
+ )
218
+ return not abbreviation
219
+
220
+ def unit_end(self, t: int) -> int:
221
+ """The end of a unit whose punctuation ends at `t`: the references that follow it belong to it."""
222
+ end = t
223
+ while (p := self.skip_gap(end, _GAP)) in self.links:
224
+ end = self.links[p][0]
225
+ return end
226
+
227
+
228
+ class _Parser:
229
+ """Walks the lines of a body and collects the units (as character spans with their references) and orphans."""
230
+
231
+ def __init__(self, lines: list[str], offsets: list[int], count: int) -> None:
232
+ self.lines, self.offsets, self.count = lines, offsets, count
233
+ self.found: list[tuple[int, int, list[_Ref]]] = []
234
+ self.orphans: list[_Ref] = []
235
+ self.fence: str | None = None
236
+ self.prev_blank = True
237
+
238
+ def run(self) -> None:
239
+ for i in range(self.count):
240
+ self.feed(i)
241
+
242
+ def feed(self, i: int) -> None:
243
+ raw = self.lines[i].rstrip("\r")
244
+ if f := _FENCE.match(raw):
245
+ self.fence = _next_fence(self.fence, f.group(1)[0])
246
+ self.prev_blank = False
247
+ return
248
+ if self.fence:
249
+ return
250
+ if not raw.strip():
251
+ self.prev_blank = True
252
+ return
253
+ was_blank, self.prev_blank = self.prev_blank, False
254
+ line = _Line(raw, self.offsets[i])
255
+ if raw.lstrip().startswith("|"):
256
+ self.table(line)
257
+ else:
258
+ self.prose(i, line, was_blank)
259
+
260
+ def table(self, line: _Line) -> None:
261
+ if _TABLE_SEP.fullmatch(line.raw) and "-" in line.raw:
262
+ return
263
+ self.found.append((line.base + line.indent, line.base + line.ce, line.table_refs()))
264
+
265
+ def introduces_block(self, n: int) -> bool:
266
+ nxt = next(
267
+ (self.lines[j].rstrip("\r") for j in range(n + 1, self.count) if self.lines[j].strip()),
268
+ None,
269
+ )
270
+ # a table row or a list item only: a heading or a quote after a colon introduces no block of this unit
271
+ return nxt is not None and (nxt.lstrip().startswith("|") or bool(_INTRO_ITEM.match(nxt)))
272
+
273
+ def prose(self, i: int, line: _Line, was_blank: bool) -> None:
274
+ cs = _list_mark_end(line.raw)
275
+ if (was_blank or cs > 0) and (m := _BOLD_LABEL.match(line.raw, cs, line.ce)):
276
+ # A reference inside a label supports no sentence: it has no owner.
277
+ self.orphans.extend(
278
+ line.ref(lm, False) for s, (_, lm) in line.links.items() if cs <= s < m.end()
279
+ )
280
+ cs = m.end()
281
+ pos = line.skip_gap(cs)
282
+ while pos in line.links: # a reference with no sentence before it
283
+ end, m = line.links[pos]
284
+ self.orphans.append(line.ref(m, False))
285
+ pos = line.skip_gap(end, _GAP)
286
+ self.tail(i, line, self.sentences(line, pos))
287
+
288
+ def sentences(self, line: _Line, pos: int) -> int:
289
+ """Record the units that end before the end of the line; return where the unfinished one starts."""
290
+ ustart, k = pos, pos
291
+ while k < line.ce:
292
+ if k in line.starts:
293
+ k = line.starts[k]
294
+ elif line.raw[k] not in ".!?":
295
+ k += 1
296
+ else:
297
+ k, ustart = self.sentence(line, k, ustart)
298
+ return ustart
299
+
300
+ def sentence(self, line: _Line, k: int, ustart: int) -> tuple[int, int]:
301
+ """The punctuation at `k`: (where to scan on, where the next unit starts)."""
302
+ j, t = line.punct_end(k)
303
+ if not line.ends_unit(k, j, t, ustart):
304
+ return j, ustart
305
+ if not re.search(r"\w", line.raw[ustart:k]):
306
+ nxt = line.skip_gap(t)
307
+ return nxt, nxt
308
+ end = line.unit_end(t)
309
+ refs = [line.ref(m, s >= t) for s, (_, m) in line.links.items() if ustart <= s < end]
310
+ self.found.append((line.base + ustart, line.base + end, refs))
311
+ nxt = line.skip_gap(end)
312
+ return nxt, nxt
313
+
314
+ def tail(self, i: int, line: _Line, ustart: int) -> None:
315
+ """The unit that runs to the end of the line, if it has any word."""
316
+ if ustart >= line.ce or not re.search(r"\w", line.raw[ustart : line.ce]):
317
+ return
318
+ head = line.colon_intro_head(ustart)
319
+ # A unit that ends in `:` before a table or list closes there: a reference added after the colon
320
+ # must not merge into the unit's own words.
321
+ split = head if head is not None and self.introduces_block(i) else None
322
+ refs = [
323
+ line.ref(m, split is not None and s >= split)
324
+ for s, (_, m) in line.links.items()
325
+ if ustart <= s < line.ce
326
+ ]
327
+ self.found.append((line.base + ustart, line.base + line.ce, refs))
328
+
329
+
330
+ def _parse(text: str) -> tuple[list[Unit], list[_Ref], list[_Ref], int]:
331
+ """(units, every reference of the body in order, the references without an owner, end of the body)."""
332
+ lines = text.split("\n")
333
+ offsets, o = [], 0
334
+ for ln in lines:
335
+ offsets.append(o)
336
+ o += len(ln) + 1
337
+ last = _last_content(lines)
338
+ count, body_end = len(lines), len(text)
339
+ if last is not None and lines[last].startswith("Sources:"):
340
+ count, body_end = last, offsets[last]
341
+ parser = _Parser(lines, offsets, count)
342
+ parser.run()
343
+ units = [
344
+ Unit(n, text[a:b], _remove(text, a, b, refs), [_file_part(r.target) for r in refs], (a, b))
345
+ for n, (a, b, refs) in enumerate(parser.found, 1)
346
+ ]
347
+ every = sorted(
348
+ [r for _, _, refs in parser.found for r in refs] + parser.orphans, key=lambda r: r.start
349
+ )
350
+ return units, every, parser.orphans, body_end
351
+
352
+
353
+ def units(text: str) -> tuple[list[Unit], list[str]]:
354
+ """A part's body (everything but the closing `Sources:` line) as numbered units, and the targets of the
355
+ references that have no owner.
356
+
357
+ A unit is a sentence or a table row. A reference is a relative link into a note folder; one that follows a
358
+ sentence's closing punctuation (white space, `,` or `;` between) belongs to that sentence, and so does one
359
+ inside it. A bold label that opens a paragraph or list item (`**What it is.**`) belongs to no unit."""
360
+ found, _, orphans, _ = _parse(text)
361
+ return found, [_file_part(r.target) for r in orphans]
362
+
363
+
364
+ def _body_without_references(text: str) -> tuple[str, int]:
365
+ _, every, _, body_end = _parse(text)
366
+ return _remove(text, 0, body_end, every), body_end
367
+
368
+
369
+ def without_references(text: str) -> str:
370
+ """The part's text with the references of its body removed (the `Sources:` line stays as it is)."""
371
+ body, body_end = _body_without_references(text)
372
+ return body + text[body_end:]
373
+
374
+
375
+ def fingerprint(text: str) -> str:
376
+ """A short hash of a section's text without its `Sources:` line, its references and surrounding whitespace."""
377
+ return _hash(_body_without_references(text)[0])
378
+
379
+
380
+ def _hash(body: str) -> str:
381
+ return hashlib.sha256(body.strip().encode("utf-8")).hexdigest()[:10]
382
+
383
+
384
+ def fingerprint_legacy(text: str) -> str:
385
+ """The fingerprint before references existed: stored by notes stamped earlier, still accepted."""
386
+ lines = text.split("\n")
387
+ last = _last_content(lines)
388
+ if last is not None and lines[last].startswith("Sources:"):
389
+ lines = lines[:last]
390
+ return _hash("\n".join(lines))
391
+
392
+
393
+ def note_fingerprint(text: str, target: str) -> str:
394
+ """The stamp of one note in a part: `u:` plus a hash of the sorted multiset of the units that cite the note and
395
+ the part's table rows (they cannot carry a reference), each as plain text with white space collapsed. A note
396
+ that no unit cites gets `fingerprint(text)`, the whole-part rule.
397
+
398
+ `target` is the note as a reference names it: the relative link from the synthesis folder, `../knowledge/<d>/<f>.md`
399
+ (the entries of `Unit.refs`); spelling variants (`./`, `%20`, `#fragment`) compare equal."""
400
+ key = _note_key(target)
401
+ found = units(text)[0]
402
+ if not any(key in {_note_key(r) for r in u.refs} for u in found):
403
+ return fingerprint(text)
404
+ picked = [
405
+ " ".join(u.plain.split())
406
+ for u in found
407
+ if key in {_note_key(r) for r in u.refs} or u.text.lstrip().startswith("|")
408
+ ]
409
+ return "u:" + _hash("\n".join(sorted(picked)))
410
+
411
+
412
+ def is_current(stored: object, text: str, target: str | None = None) -> bool:
413
+ """Whether a note's `part_of_hash` matches the part's text. A `u:` stamp compares with `note_fingerprint`
414
+ (never current without a `target`); any other stamp is the whole part, by the current or the legacy fingerprint."""
415
+ if isinstance(stored, str) and stored.startswith("u:"):
416
+ return target is not None and stored == note_fingerprint(text, target)
417
+ return isinstance(stored, str) and stored in {fingerprint(text), fingerprint_legacy(text)}
418
+
419
+
420
+ def word_count(text: str) -> int:
421
+ return len(text.split())
422
+
423
+
424
+ def first_paragraph(text: str) -> str:
425
+ """The text up to the first blank line; empty when that paragraph is the `Sources:` line."""
426
+ para = re.split(r"\n\s*\n", text.strip(), maxsplit=1)[0]
427
+ return "" if para.startswith("Sources:") else para
@@ -0,0 +1,9 @@
1
+ """The synthesis job: topic pipeline, reference backfill and the brief files.
2
+
3
+ `backfill`: the `--backfill` driver: runs the reference sessions over the syntheses (one, the batch, a dry run) and prints the table
4
+ `cli`: command line of `mem-synthesize`, `main`, self-check
5
+ `pipeline`: the lean pipeline shared with `evals/synthesis/run_trials.py`
6
+ `references`: the steps of one reference session: select the parts, write the input, build and run the command, parse the answer
7
+ `run`: shared constants, session environment, table helpers
8
+ `topics`: topics without a synthesis: pipeline per topic, then references
9
+ """