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,1189 @@
1
+ """The curation handler (A5, ADR 0028): `curate`, and the session-start curation decisions (`_decisions`, the passes and marks files, the pair and note queues) with the logic only they use."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import collections
7
+ import contextlib
8
+ import dataclasses
9
+ import datetime
10
+ import hashlib
11
+ import io
12
+ import json
13
+ import os
14
+ import sys
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import TYPE_CHECKING, TypedDict, Unpack
18
+
19
+ from memory_cli.commands import common, edit, memory
20
+ from memory_cli.core import auto_state, safe_io, store_git
21
+ from memory_cli.corroborate import decide as corroborate_decide
22
+ from memory_cli.integrate.log import log_entries
23
+ from memory_cli.memories import records, rules
24
+ from memory_cli.notes import fields as note_fields
25
+ from memory_cli.notes import note as note_files
26
+ from memory_cli.notes import split_candidates
27
+ from memory_cli.syntheses import document, units
28
+ from memory_cli.syntheses import project as project_syntheses
29
+
30
+ if TYPE_CHECKING:
31
+ from collections.abc import Collection, Mapping, Sequence
32
+
33
+
34
+ _CURATE_LINE_WORDS = 3 # `merge m:<keep> m:<drop>` and `attach <note> s:<h>#<section>`
35
+
36
+
37
+ def _got_worse(
38
+ project: Sequence[records.Memory],
39
+ global_: Sequence[records.Memory],
40
+ today: datetime.date,
41
+ choice: rules.Choice | None = None,
42
+ ) -> list[tuple[records.Memory, bool]]:
43
+ """The lessons whose present version got worse (records.got_worse) and that the rules block loads or leaves out
44
+ over the cap; the flag says "loaded". `choose` gets both scopes so that the cap is the one of session start."""
45
+ choice = choice if choice is not None else rules.choose(project, global_, today)
46
+ found = [(m, True) for m in choice.loaded] + [
47
+ (m, False) for m, why in choice.left if why == rules.OVER
48
+ ]
49
+ return [(m, loaded) for m, loaded in found if records.got_worse(m)]
50
+
51
+
52
+ _STALE_DAYS = 90
53
+
54
+
55
+ _FREQUENT = 3
56
+
57
+
58
+ _STANDING_KINDS = (
59
+ "constraint",
60
+ "decision",
61
+ "state",
62
+ ) # no date makes them stale: only a refutation retires them
63
+
64
+
65
+ def _passes_file(env: Mapping[str, str]) -> Path | None:
66
+ folder = common.data_dir(env)
67
+ return folder / "curated.json" if folder is not None else None
68
+
69
+
70
+ def read_passes(env: Mapping[str, str]) -> dict[str, datetime.date]:
71
+ """Date of the last pass per memory folder (resolved path), from the data folder; {} when unknown."""
72
+ path = _passes_file(env)
73
+ try:
74
+ raw = json.loads(path.read_text(encoding="utf-8")) if path is not None else {}
75
+ return {k: datetime.date.fromisoformat(v) for k, v in raw.items()}
76
+ except (OSError, ValueError, AttributeError, TypeError):
77
+ return {}
78
+
79
+
80
+ def _write_passes(env: Mapping[str, str], covered: Sequence[Path], today: datetime.date) -> None:
81
+ path = _passes_file(env)
82
+ if path is None:
83
+ raise OSError("no data folder: set MEM_DATA or HOME")
84
+ known = {k: v.isoformat() for k, v in read_passes(env).items()}
85
+ known.update({str(f.resolve()): today.isoformat() for f in covered})
86
+ path.parent.mkdir(parents=True, exist_ok=True)
87
+ safe_io.replace_file(path, (json.dumps(known, indent=2, sort_keys=True) + "\n").encode("utf-8"))
88
+
89
+
90
+ def _marks_file(env: Mapping[str, str]) -> Path | None:
91
+ folder = common.data_dir(env)
92
+ return folder / "curated-items.json" if folder is not None else None
93
+
94
+
95
+ def _parse_marks(text: str) -> dict[str, frozenset[str]]:
96
+ try:
97
+ return {
98
+ k: frozenset(v)
99
+ for k, v in json.loads(text).items()
100
+ if isinstance(k, str) and isinstance(v, list) and all(isinstance(x, str) for x in v)
101
+ }
102
+ except (ValueError, AttributeError, TypeError):
103
+ return {}
104
+
105
+
106
+ def read_marks(env: Mapping[str, str]) -> dict[str, frozenset[str]]:
107
+ """Decision keys recorded by the last pass per memory folder (resolved path); anything unreadable reads as none."""
108
+ path = _marks_file(env)
109
+ try:
110
+ return _parse_marks(path.read_text(encoding="utf-8")) if path is not None else {}
111
+ except (OSError, ValueError): # ValueError: not UTF-8
112
+ return {}
113
+
114
+
115
+ def _write_marks(env: Mapping[str, str], covered: Mapping[Path, Collection[str]]) -> None:
116
+ """Replace the keys of the covered folders only; `curated.json` is not touched (C100)."""
117
+ path = _marks_file(env)
118
+ if path is None:
119
+ raise OSError("no data folder: set MEM_DATA or HOME")
120
+ # a missing or malformed file starts empty; one that exists but cannot be read raises, so no key is dropped
121
+ try:
122
+ text = path.read_text(encoding="utf-8") if path.exists() else ""
123
+ except UnicodeDecodeError: # malformed, not unreadable
124
+ text = ""
125
+ known = {k: sorted(v) for k, v in _parse_marks(text).items()}
126
+ known.update({str(f.resolve()): sorted(keys) for f, keys in covered.items()})
127
+ path.parent.mkdir(parents=True, exist_ok=True)
128
+ safe_io.replace_file(path, (json.dumps(known, indent=2, sort_keys=True) + "\n").encode("utf-8"))
129
+
130
+
131
+ def _tagged(m: records.Memory, extra: str = "") -> str:
132
+ created = m.created.isoformat() if m.created else "undated"
133
+ return f" m:{m.handle} [{m.kind}, {created}{extra}] {memory._flat(m.claim)}"
134
+
135
+
136
+ def _differ_in(a: str, b: str) -> str:
137
+ words = records.differing_words(a, b)
138
+ return f"differ in: {', '.join(words)}" if words else "differ in: wording only"
139
+
140
+
141
+ _DECISION_LABELS = {
142
+ "refuted": "refuted again",
143
+ "pair": "same or opposite",
144
+ "state": "newer state",
145
+ "expired": "expired",
146
+ "seen": "seen often",
147
+ "stale": f"not confirmed in {_STALE_DAYS} days",
148
+ "nofill": "no short form",
149
+ }
150
+
151
+
152
+ @dataclass(frozen=True)
153
+ class Decisions:
154
+ """The decision items of one folder's curation queue (C98): `mem curate` prints them, the count counts them."""
155
+
156
+ refuted: list[tuple[records.Memory, records.Memory]] # (live, refuted)
157
+ same: list[tuple[records.Memory, records.Memory]]
158
+ state: list[tuple[records.Memory, records.Memory]] # (old, new)
159
+ expired: list[records.Memory]
160
+ seen: list[records.Memory]
161
+ stale: list[records.Memory]
162
+ nofill: list[
163
+ records.Memory
164
+ ] # established lessons the automatic short-form fill will not write (`fill_wont_write`)
165
+ pairs_checked: bool
166
+
167
+ def keys(self) -> dict[str, str]:
168
+ """Each item's key (C100) with the label of its part."""
169
+ found: dict[str, str] = {}
170
+ for a, r in self.refuted:
171
+ found[f"refuted:{a.handle}|{r.handle}"] = _DECISION_LABELS["refuted"]
172
+ for a, b in self.same:
173
+ found[f"pair:{'|'.join(sorted((a.handle, b.handle)))}"] = _DECISION_LABELS["pair"]
174
+ for old, new in self.state:
175
+ found[f"state:{old.handle}|{new.handle}"] = _DECISION_LABELS["state"]
176
+ for name, items in (
177
+ ("expired", self.expired),
178
+ ("seen", self.seen),
179
+ ("stale", self.stale),
180
+ ("nofill", self.nofill),
181
+ ):
182
+ for m in items:
183
+ found[f"{name}:{m.handle}"] = _DECISION_LABELS[name]
184
+ return found
185
+
186
+
187
+ def _unconfirmed_handles(memories: Sequence[records.Memory]) -> set[str]:
188
+ """Handles of the unconfirmed memories: they have their own category, so the other blocks skip them."""
189
+ return {m.handle for m in memories if records.standing(m) == "unconfirmed"}
190
+
191
+
192
+ def _changed_since(live: Sequence[records.Memory], since: datetime.date) -> list[str]:
193
+ """Handles of the memories changed on or after `since`, newest change first: created then, or its file written
194
+ then (local time), or no `created`, or the file cannot be read."""
195
+ found = []
196
+ for m in live:
197
+ try:
198
+ written: datetime.date | None = datetime.date.fromtimestamp(m.path.stat().st_mtime)
199
+ except OSError:
200
+ written = None
201
+ if m.created is not None and written is not None and m.created < since and written < since:
202
+ continue
203
+ found.append((
204
+ max(m.created, written)
205
+ if m.created is not None and written is not None
206
+ else datetime.date.max,
207
+ m.handle,
208
+ ))
209
+ found.sort(key=lambda t: (-t[0].toordinal(), t[1]))
210
+ return [h for _, h in found]
211
+
212
+
213
+ class _DecisionOptions(TypedDict, total=False):
214
+ """The keyword options of `_decisions`."""
215
+
216
+ since: datetime.date | None
217
+ budget: records.Budget | None
218
+ attempts: dict | None
219
+ root: Path | None
220
+ tracked: frozenset[str] | None
221
+
222
+
223
+ def _decision_pairs(
224
+ kept: list[records.Memory],
225
+ today: datetime.date,
226
+ among: list[str] | None,
227
+ budget: records.Budget | None,
228
+ ) -> tuple[
229
+ list[tuple[records.Memory, records.Memory]], list[tuple[records.Memory, records.Memory]]
230
+ ]:
231
+ """The pairs of memories that may say the same: the ordinary ones, and the project `state` ones (oldest first)."""
232
+ same: list[tuple[records.Memory, records.Memory]] = []
233
+ state: list[tuple[records.Memory, records.Memory]] = []
234
+ for a, b, _ in records.pairs(
235
+ kept, today, tokenize=records.tokenize, among=among, budget=budget
236
+ ):
237
+ if (
238
+ a.kind == "state" and b.kind == "state" and a.scope == b.scope == "project"
239
+ ): # C103: a project matter
240
+ old, new = sorted((a, b), key=lambda m: (m.created or datetime.date.min, m.handle))
241
+ state.append((old, new))
242
+ else:
243
+ same.append((a, b))
244
+ return same, state
245
+
246
+
247
+ def _decision_stale(
248
+ live: list[records.Memory], today: datetime.date, unconfirmed: set[str]
249
+ ) -> list[records.Memory]:
250
+ """The live memories nobody observed for `_STALE_DAYS` days; the standing kinds and unconfirmed ones never go stale."""
251
+ cutoff = today - datetime.timedelta(days=_STALE_DAYS)
252
+ return [
253
+ m
254
+ for m in live
255
+ if m.kind not in _STANDING_KINDS
256
+ and m.created is not None
257
+ and m.handle not in unconfirmed
258
+ and max(m.created, m.last_observed or m.created) <= cutoff
259
+ ]
260
+
261
+
262
+ def _decision_nofill(
263
+ kept: list[records.Memory],
264
+ today: datetime.date,
265
+ attempts: dict | None,
266
+ root: Path | None,
267
+ tracked: frozenset[str] | None,
268
+ ) -> list[records.Memory]:
269
+ """The memories the automatic short-form fill will not write; none unless `attempts` turns the kind on."""
270
+ return [
271
+ m
272
+ for m in (records.mark_repository(kept, tracked) if root else kept)
273
+ if attempts is not None and corroborate_decide.fill_wont_write(m, root, attempts, today)
274
+ ]
275
+
276
+
277
+ def _decisions(
278
+ loaded: Sequence[records.Memory],
279
+ today: datetime.date,
280
+ **options: Unpack[_DecisionOptions],
281
+ ) -> Decisions:
282
+ """The decision items of one folder from what `records.load_memories` returned: superseded memories and
283
+ unreadable files are left out. With `since` the pair kinds compare only pairs with a memory changed since then;
284
+ `budget` is spent by those comparisons. `attempts` (`_fill_attempts`) turns on the "no short form" kind; `root` is
285
+ the project root of a project folder, None for the global one, and `tracked` its `records.tracked_memories`."""
286
+ since = options.get("since")
287
+ budget = options.get("budget")
288
+ kept = [m for m in loaded if m.error is None and m.superseded_by is None]
289
+ live = [m for m in kept if records.is_live(m, today)]
290
+ among = _changed_since(live, since) if since is not None else None
291
+ again = [
292
+ (a, r)
293
+ for a, r, _ in records.refuted_pairs(
294
+ kept, today, tokenize=records.tokenize, among=among, budget=budget
295
+ )
296
+ ]
297
+ same, state = _decision_pairs(kept, today, among, budget)
298
+ unconfirmed = _unconfirmed_handles(kept)
299
+ expired = [
300
+ m
301
+ for m in kept
302
+ if m.status == "active"
303
+ and m.valid_until is not None
304
+ and m.valid_until < today
305
+ and m.handle not in unconfirmed
306
+ ]
307
+ seen = [
308
+ m for m in live if m.scope == "project" and m.observed >= _FREQUENT and not m.promote
309
+ ] # a global one cannot be promoted
310
+ stale = _decision_stale(live, today, unconfirmed)
311
+ nofill = _decision_nofill(
312
+ kept,
313
+ today,
314
+ options.get("attempts"),
315
+ options.get("root"),
316
+ options.get("tracked", frozenset()),
317
+ )
318
+ return Decisions(
319
+ again, same, state, expired, seen, stale, nofill, budget is None or not budget.exhausted
320
+ )
321
+
322
+
323
+ type _MemoryPairs = Sequence[tuple[records.Memory, records.Memory]]
324
+
325
+
326
+ def _most_paired(pairs: _MemoryPairs) -> tuple[str, str]:
327
+ """The (scope, handle) of the memory in the most pairs (ties by handle)."""
328
+ count: collections.Counter = collections.Counter()
329
+ for a, b in pairs:
330
+ count.update([(a.scope, a.handle), (b.scope, b.handle)])
331
+ return min(count, key=lambda k: (-count[k], k[1], k[0]))
332
+
333
+
334
+ def _pairs_of_member(
335
+ left: _MemoryPairs, top: tuple[str, str]
336
+ ) -> tuple[records.Memory, list[tuple[str, str, str]], list[tuple[records.Memory, records.Memory]]]:
337
+ """The memory `top`, the lines of its partners (handle, tag and claim, differ line) and the pairs that do not hold it."""
338
+ rest = []
339
+ head = left[0][0] # overwritten: `top` is a member of some pair
340
+ lines = []
341
+ for a, b in left:
342
+ if (a.scope, a.handle) == top:
343
+ head, other = a, b
344
+ elif (b.scope, b.handle) == top:
345
+ head, other = b, a
346
+ else:
347
+ rest.append((a, b))
348
+ continue
349
+ lines.append((
350
+ other.handle,
351
+ f" {_tagged(other)}",
352
+ f" {_differ_in(head.claim, other.claim)}",
353
+ ))
354
+ return head, lines, rest
355
+
356
+
357
+ def _grouped_pairs(pairs: _MemoryPairs) -> list[str]:
358
+ """C102: the memory in the most remaining pairs first (ties by handle) with its line, then one indented line per
359
+ partner (its tag and claim, two spaces deeper) with its `differ in` below; each pair once."""
360
+ left = list(pairs)
361
+ out: list[str] = []
362
+ while left:
363
+ head, lines, left = _pairs_of_member(left, _most_paired(left))
364
+ out.append(_tagged(head))
365
+ for _, line, differ in sorted(lines):
366
+ out += [line, differ]
367
+ return out
368
+
369
+
370
+ TOPIC_CROWD = 8
371
+
372
+
373
+ TOPIC_LOOSE = 5 # of them, knowledge notes not yet part of any synthesis
374
+
375
+
376
+ def _note_line(note: note_files.Note) -> str:
377
+ return (
378
+ f" {note_files._handle(note.rel)} [{note.meta.get('confidence', '')}, {note.meta.get('updated', '')}] "
379
+ f"{memory._flat(str(note.meta.get('claim', '')))}"
380
+ )
381
+
382
+
383
+ def _note_pairs(notes: Sequence[note_files.Note]) -> list[tuple[note_files.Note, note_files.Note]]:
384
+ """Pairs of notes that share a topic and whose claims contain each other with at least `records.STRONG`,
385
+ unless one names the other in `distinct_from`; the closest pair first."""
386
+ notes = sorted(notes, key=lambda n: note_files._handle(n.rel))
387
+ tokens = [set(records.tokenize(str(n.meta.get("claim", "")))) for n in notes]
388
+ found = []
389
+ for i, a in enumerate(notes):
390
+ for j in range(i + 1, len(notes)):
391
+ b = notes[j]
392
+ if not set(a.meta.get("topics") or []) & set(b.meta.get("topics") or []):
393
+ continue
394
+ if note_files._handle(b.rel) in (
395
+ a.meta.get("distinct_from") or []
396
+ ) or note_files._handle(a.rel) in (b.meta.get("distinct_from") or []):
397
+ continue
398
+ score = max(
399
+ records.containment(tokens[i], tokens[j]), records.containment(tokens[j], tokens[i])
400
+ )
401
+ if score >= records.STRONG:
402
+ found.append((score, a, b))
403
+ found.sort(key=lambda t: (-t[0], note_files._handle(t[1].rel), note_files._handle(t[2].rel)))
404
+ return [(a, b) for _, a, b in found]
405
+
406
+
407
+ @dataclass(frozen=True)
408
+ class _NoteQueues:
409
+ """The lines of the three note blocks of `mem curate --notes` that come from reading each note."""
410
+
411
+ unattached: list[str] = dataclasses.field(default_factory=list)
412
+ stale: list[str] = dataclasses.field(default_factory=list)
413
+ disputed: list[str] = dataclasses.field(default_factory=list)
414
+
415
+
416
+ def _curate_notes_unattached(
417
+ note: note_files.Note, name: str, synths: list[document.Synthesis], known: dict
418
+ ) -> str | None:
419
+ """The line of a note that is part of no synthesis though a synthesis covers its topic; None when none does."""
420
+ topics = [t for t in note.meta.get("topics", []) if isinstance(t, str)]
421
+ own = set(edit._own_topics(known, topics))
422
+ covering = [x for x in synths if own & set(x.topics)]
423
+ if not covering:
424
+ return None
425
+ return (
426
+ f" {name} \u2192 {', '.join('s:' + x.handle for x in covering)} "
427
+ f"{memory._flat(str(note.meta.get('claim', '')))}"
428
+ )
429
+
430
+
431
+ def _curate_notes_stale(
432
+ note: note_files.Note, name: str, part: str, synths: list[document.Synthesis]
433
+ ) -> str | None:
434
+ """The line of a note older than the synthesis section it is part of; None when it is current."""
435
+ handle, _, section = part.partition("#")
436
+ syn = next((x for x in synths if x.handle == handle), None)
437
+ sec = next((x for x in syn.sections if x.handle == section), None) if syn else None
438
+ if sec is not None and not units.is_current(
439
+ note.meta.get("part_of_hash"), sec.text, common._note_target(note.rel)
440
+ ):
441
+ return f" {name} s:{handle}#{section}"
442
+ return None
443
+
444
+
445
+ def _curate_notes_file(
446
+ note: note_files.Note, synths: list[document.Synthesis], known: dict, queues: _NoteQueues
447
+ ) -> None:
448
+ """Sort one knowledge note into the queues (disputed, not yet part of a synthesis, older than its section)."""
449
+ if note.type != "knowledge" or note.error is not None or not isinstance(note.meta, dict):
450
+ return
451
+ if note_fields._disputed(note.meta.get("disputed")) is None:
452
+ queues.disputed.append(
453
+ f" {note_files._handle(note.rel)} {memory._flat(str(note.meta.get('claim', '')))} "
454
+ f"(source: {note.meta['disputed'][0]['source']})"
455
+ )
456
+ part = note.meta.get("part_of")
457
+ name = note_files._handle(note.rel)
458
+ if not isinstance(part, str):
459
+ line = _curate_notes_unattached(note, name, synths, known)
460
+ if line is not None:
461
+ queues.unattached.append(line)
462
+ return
463
+ line = _curate_notes_stale(note, name, part, synths)
464
+ if line is not None:
465
+ queues.stale.append(line)
466
+
467
+
468
+ def _curate_notes_blocks(queues: _NoteQueues) -> list[str]:
469
+ """The disputed, unattached and stale blocks: a heading with the decision to take, then the lines."""
470
+ out: list[str] = []
471
+ if queues.disputed:
472
+ out.append(
473
+ "notes disputed by a source (decide: correct the note with mem note edit, "
474
+ "or mem note dispute <note> --clear)"
475
+ )
476
+ out += queues.disputed
477
+ if queues.unattached:
478
+ out.append(
479
+ "notes on a topic that has a synthesis, not yet part of it (add what the note says to a part with "
480
+ "mem synthesis append or add, then: mem synthesis attach <note> s:<h>#<section>)"
481
+ )
482
+ out += queues.unattached
483
+ if queues.stale:
484
+ out.append(
485
+ "notes older than their section (rewrite the note from the section: mem show s:<h>#<section>)"
486
+ )
487
+ out += queues.stale
488
+ return out
489
+
490
+
491
+ def _curate_notes_same(live: list[note_files.Note]) -> list[str]:
492
+ """The block of knowledge notes that may say the same or the opposite."""
493
+ same = _note_pairs([n for n in live if n.type == "knowledge"])
494
+ if not same:
495
+ return []
496
+ out = [
497
+ (
498
+ "notes that say the same or the opposite? (decide: mem unify <keep> <other> --body-file \u2026, "
499
+ "mem distinct <a> <b>, or leave)"
500
+ )
501
+ ]
502
+ for a, b in same:
503
+ out += [
504
+ _note_line(a),
505
+ _note_line(b),
506
+ f" {_differ_in(str(a.meta.get('claim', '')), str(b.meta.get('claim', '')))}",
507
+ ]
508
+ return out
509
+
510
+
511
+ def _curate_notes_crowded(
512
+ live: list[note_files.Note], synths: list[document.Synthesis], known: dict
513
+ ) -> list[str]:
514
+ """The block of topics with many notes and no synthesis."""
515
+ covered = {t for x in synths for t in x.topics}
516
+ counts: collections.Counter = collections.Counter()
517
+ loose: collections.Counter = (
518
+ collections.Counter()
519
+ ) # knowledge notes that are part of no synthesis
520
+ for n in live:
521
+ if n.type in {"knowledge", "literature"}:
522
+ own = edit._own_topics(
523
+ known, [t for t in n.meta.get("topics", []) if isinstance(t, str)]
524
+ )
525
+ counts.update(own)
526
+ if n.type == "knowledge" and not n.meta.get("part_of"):
527
+ loose.update(own)
528
+ # A topic whose notes already sit in other syntheses is not worth a document of its own.
529
+ crowded = sorted(
530
+ (
531
+ (t, c)
532
+ for t, c in counts.items()
533
+ if c >= TOPIC_CROWD and t not in covered and loose[t] >= TOPIC_LOOSE
534
+ ),
535
+ key=lambda tc: (-tc[1], tc[0]),
536
+ )
537
+ if not crowded:
538
+ return []
539
+ return [
540
+ f"topics with {TOPIC_CROWD} notes or more and no synthesis (mem synthesis new)",
541
+ *(f" {t} {c} notes" for t, c in crowded),
542
+ ]
543
+
544
+
545
+ def _curate_notes(args: argparse.Namespace) -> int:
546
+ root = args.root
547
+ if root is None:
548
+ print("mem: curate --notes needs a store", file=sys.stderr)
549
+ return 2
550
+ synths = [x for x in document.load(root / document.SYNTHESES_DIR) if x.error is None]
551
+ try:
552
+ known = note_files.load_topics(root)
553
+ except note_files.FrontmatterError:
554
+ known = {}
555
+ queues = _NoteQueues()
556
+ for note in note_files.discover_notes(root):
557
+ _curate_notes_file(note, synths, known, queues)
558
+ out = _curate_notes_blocks(queues)
559
+ live = [
560
+ n
561
+ for n in note_files.discover_notes(root)
562
+ if n.error is None and isinstance(n.meta, dict) and n.meta.get("superseded_by") is None
563
+ ]
564
+ out += _curate_notes_same(live)
565
+ out += _curate_notes_crowded(live, synths, known)
566
+ candidates = split_candidates.find_candidates(live, synths, known)
567
+ if candidates:
568
+ out.append("synthesis split candidates")
569
+ out.extend(f" s:{c.part} {c.topic} {len(c.notes)} notes" for c in candidates)
570
+ if out:
571
+ print("\n".join(out))
572
+ return 0
573
+
574
+
575
+ _PROJECT_SYNTHESIS_MIN_MEMORIES = 5
576
+
577
+
578
+ def _curate_project_syntheses(
579
+ scopes: Sequence[tuple[str, Path | None, list[records.Memory]]], today: datetime.date
580
+ ) -> list[str]:
581
+ """The two project synthesis blocks of `mem curate`: parts possibly stale, and none written yet."""
582
+ context = _project_synthesis_context_quiet()
583
+ if context is None:
584
+ return []
585
+ memory_dir, tree = context
586
+ found, broken = project_syntheses.load_each(memory_dir)
587
+ out: list[str] = []
588
+ if broken:
589
+ out.append("-- project syntheses: unreadable --")
590
+ out += [f"{path}\t{error}" for path, error in broken]
591
+ states = [
592
+ (name, part, project_syntheses.freshness(tree, part.stamp))
593
+ for name, parts in found.items()
594
+ for part in parts
595
+ ]
596
+ stale = [
597
+ (name, part, state) for name, part, state in states if state != project_syntheses.FRESH
598
+ ]
599
+ if stale:
600
+ out.append("-- project syntheses: possibly stale --")
601
+ out += [
602
+ f"p:{name}#{part.handle}\t{project_syntheses.describe(state)}"
603
+ for name, part, state in stale
604
+ ]
605
+ active = sum(
606
+ 1
607
+ for scope, _, loaded in scopes
608
+ if scope == "project"
609
+ for m in loaded
610
+ if m.error is None and records.is_live(m, today)
611
+ )
612
+ if not found and not broken and active >= _PROJECT_SYNTHESIS_MIN_MEMORIES:
613
+ out += [
614
+ "-- project syntheses: none yet --",
615
+ f"{active} active memories and no project synthesis: organize them (see the memory-curation skill).",
616
+ ]
617
+ return out
618
+
619
+
620
+ def _project_synthesis_context_quiet() -> tuple[Path, Path] | None:
621
+ """(memory folder, working tree) of the project the session is in; None outside a project, silently."""
622
+ try:
623
+ root = records.project_root(Path.cwd(), os.environ)
624
+ except OSError:
625
+ return None
626
+ if root is None:
627
+ return None
628
+ return records.project_dir(root), project_syntheses.worktree(Path.cwd(), root, os.environ)
629
+
630
+
631
+ def _claim_key(claim: str) -> str:
632
+ """A claim for the safe-merge test: case, whitespace and trailing punctuation do not count."""
633
+ return " ".join(claim.lower().split()).rstrip(" .,;:!?")
634
+
635
+
636
+ def _parse_actions(text: str) -> list[tuple[str, list[str]]]:
637
+ """(raw line, words) of each action line; blank lines and `#` comments dropped. ValueError on a known verb
638
+ with the wrong number of arguments, so a malformed file applies nothing."""
639
+ out = []
640
+ for raw in text.splitlines():
641
+ line = raw.strip()
642
+ if not line or line.startswith("#"):
643
+ continue
644
+ words = line.split()
645
+ if words[0] == "merge" and len(words) != _CURATE_LINE_WORDS:
646
+ raise ValueError(f"malformed line (merge m:<keep> m:<drop>): {line}")
647
+ if words[0] == "attach" and len(words) != _CURATE_LINE_WORDS:
648
+ raise ValueError(f"malformed line (attach <note> s:<h>#<section>): {line}")
649
+ out.append((" ".join(words), words))
650
+ return out
651
+
652
+
653
+ def _last_error(buf: io.StringIO, default: str) -> str:
654
+ lines = [ln.removeprefix("mem: ").strip() for ln in buf.getvalue().splitlines() if ln.strip()]
655
+ return lines[-1] if lines else default
656
+
657
+
658
+ def _curate_merge_refusal(a: records.Memory, b: records.Memory) -> str | None:
659
+ """Why two memories must not be merged automatically; None when they are the same claim, both active, in one
660
+ scope."""
661
+ if a.handle == b.handle:
662
+ return "the same memory twice"
663
+ if a.scope != b.scope:
664
+ return "different scopes"
665
+ for m in (a, b):
666
+ if m.status != "active" or m.superseded_by is not None:
667
+ return f"m:{m.handle} is {m.status}"
668
+ if _claim_key(a.claim) != _claim_key(b.claim):
669
+ return "the claims are not equal"
670
+ return None
671
+
672
+
673
+ def _safe_merge(args: argparse.Namespace, keep: str, drop: str) -> str | None:
674
+ """None after the merge ran; else why it was left. Only equal claims, both active, in one scope; never --force."""
675
+ err = io.StringIO()
676
+ with contextlib.redirect_stderr(err):
677
+ found = memory._memory_of(args, [keep, drop])
678
+ if found is None:
679
+ return _last_error(err, "memories not found")
680
+ refusal = _curate_merge_refusal(*found)
681
+ if refusal is not None:
682
+ return refusal
683
+ ns = argparse.Namespace(**{**vars(args), "keep": keep, "drop": drop, "force": False})
684
+ out, err = io.StringIO(), io.StringIO()
685
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
686
+ code = memory.cmd_merge(ns)
687
+ return None if code == 0 else _last_error(err, "the merge was refused")
688
+
689
+
690
+ def _curate_attach_refusal(root: Path, found: Path, target: str) -> str | None:
691
+ """Why the note must not be attached automatically to `target`; None when the part's `Sources:` line links it and
692
+ it is not part of a synthesis yet."""
693
+ try:
694
+ syn, sec = common._section_ref(root, target)
695
+ part = note_files.split_frontmatter(note_files._read_text(found))[0].get("part_of")
696
+ except (ValueError, OSError, note_files.FrontmatterError) as exc:
697
+ return str(exc)
698
+ if part:
699
+ return f"the note is already part of s:{part}"
700
+ cited = {(syn.path.parent / s).resolve() for s in sec.sources}
701
+ if found.resolve() not in cited:
702
+ return "the part's Sources line does not link the note"
703
+ return None
704
+
705
+
706
+ def _safe_attach(args: argparse.Namespace, note: str, target: str) -> str | None:
707
+ """None after the attach ran; else why it was left. Only when the part's `Sources:` line links the note and the
708
+ note is not part of a synthesis yet."""
709
+ root = args.root
710
+ if not isinstance(root, Path) or not root.is_dir() or not records.store_is_writable(root):
711
+ return "no writable store"
712
+ found = common.resolve_note(root, note)
713
+ if isinstance(found, list):
714
+ return "the note name is ambiguous"
715
+ if found is None:
716
+ return "no such note"
717
+ refusal = _curate_attach_refusal(root, found, target)
718
+ if refusal is not None:
719
+ return refusal
720
+ ns = argparse.Namespace(root=root, note=note, target=target)
721
+ out, err = io.StringIO(), io.StringIO()
722
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
723
+ code = edit._attach(ns)
724
+ return None if code == 0 else _last_error(err, "the attach was refused")
725
+
726
+
727
+ def _curate_run_action(args: argparse.Namespace, words: list[str]) -> str | None:
728
+ """None after the action ran; else why it was left."""
729
+ if words[0] == "merge":
730
+ return _safe_merge(args, words[1], words[2])
731
+ if words[0] == "attach":
732
+ return _safe_attach(args, words[1], words[2])
733
+ return f"not a safe action ({words[0]})"
734
+
735
+
736
+ def _curate_apply(args: argparse.Namespace) -> int:
737
+ """`mem curate apply --safe`: action lines from a file or stdin; only what the code can prove safe runs."""
738
+ if not args.safe:
739
+ print("mem: curate apply runs only with --safe: there is no unsafe mode.", file=sys.stderr)
740
+ return 2
741
+ try:
742
+ text = (
743
+ sys.stdin.read()
744
+ if args.from_file in {None, "-"}
745
+ else Path(args.from_file).read_text(encoding="utf-8")
746
+ )
747
+ actions = _parse_actions(text)
748
+ except (OSError, UnicodeDecodeError, ValueError) as exc:
749
+ print(f"mem: {exc}", file=sys.stderr)
750
+ return 2
751
+ applied = left = 0
752
+ for line, words in actions:
753
+ why = _curate_run_action(args, words)
754
+ if why is None:
755
+ applied += 1
756
+ print(f"applied\t{line}")
757
+ else:
758
+ left += 1
759
+ print(f"left\t{line}\t{why}")
760
+ print(f"applied {applied}, left {left}")
761
+ return 0
762
+
763
+
764
+ def _integrate_stamps(store: Path) -> dict[str, str]:
765
+ """`{hub-relative path: digest}` of the text of each file that `mem synthesis integrate` left, or an undo of it
766
+ put back, per the curation log read as a stack: the digest is the `after` of the file's newest live entry when
767
+ that is an `integrate` entry, or that of the `before` text when the file's newest entry is a restore marker
768
+ cancelling an `integrate` entry."""
769
+ entries = log_entries(store)
770
+ by_line = {e["line"]: e for _, e in entries}
771
+ newest_live: dict[str, dict] = {}
772
+ newest_any: dict[str, dict] = {}
773
+ for gone, entry in entries:
774
+ newest_any[entry["handle"]] = entry
775
+ if entry.get("action") != "restore" and not gone:
776
+ newest_live[entry["handle"]] = entry
777
+ stamps = {
778
+ handle: str(entry.get("after"))
779
+ for handle, entry in newest_live.items()
780
+ if entry.get("action") == "integrate"
781
+ }
782
+ for handle, marker in newest_any.items():
783
+ undone = by_line.get(marker.get("undone")) if marker.get("action") == "restore" else None
784
+ if (
785
+ undone is not None
786
+ and undone.get("action") == "integrate"
787
+ and isinstance(undone.get("before"), str)
788
+ ):
789
+ stamps[handle] = hashlib.sha256(undone["before"].encode("utf-8")).hexdigest()
790
+ return stamps
791
+
792
+
793
+ def _written_by_integrate(path: Path, store: Path, stamps: dict[str, str]) -> bool:
794
+ """True when `mem synthesis integrate` wrote the file's current text: its mtime says nothing new."""
795
+ if not path.is_relative_to(store):
796
+ return False
797
+ after = stamps.get(path.relative_to(store).as_posix())
798
+ return after is not None and hashlib.sha256(path.read_bytes()).hexdigest() == after
799
+
800
+
801
+ def _curate_new_since(args: argparse.Namespace) -> int:
802
+ """Print how many global memories and notes of the store were written after `--new-since` (epoch seconds) and
803
+ after the last curation pass of the global memories (its day counts as passed). File times: an edit counts as new,
804
+ except a note whose current text is what `mem synthesis integrate` last wrote. The trigger of `mem-auto`."""
805
+ store = args.root
806
+ cutoff = float(args.new_since)
807
+ memories = records.memories_root(
808
+ os.environ, store if store is not None and store.is_dir() else None
809
+ )
810
+ paths: list[Path] = []
811
+ if memories is not None and memories.is_dir():
812
+ last = read_passes(os.environ).get(str(memories.resolve()))
813
+ if last is not None:
814
+ cutoff = max(
815
+ cutoff,
816
+ datetime.datetime.combine(
817
+ last + datetime.timedelta(days=1), datetime.time.min
818
+ ).timestamp(),
819
+ )
820
+ today = datetime.date.today()
821
+ paths += [
822
+ m.path
823
+ for m in records.load_memories(memories, "global")
824
+ if m.error is None and records.is_live(m, today) and m.origin is None
825
+ ] # a pipeline's own writes must not start the next run
826
+ stamps: dict[str, str] = {}
827
+ if store is not None and store.is_dir():
828
+ paths += [store / n.rel for n in note_files.discover_notes(store) if n.error is None]
829
+ stamps = _integrate_stamps(store)
830
+ count = 0
831
+ for path in paths:
832
+ try:
833
+ newer = path.stat().st_mtime > cutoff
834
+ count += newer and not (
835
+ store is not None and _written_by_integrate(path, store, stamps)
836
+ )
837
+ except OSError:
838
+ continue
839
+ print(count)
840
+ return 0
841
+
842
+
843
+ type _CurateScopes = Sequence[tuple[str, Path | None, list[records.Memory]]]
844
+
845
+
846
+ @dataclass(frozen=True)
847
+ class _CuratePass:
848
+ """The folders a `mem curate done` pass covers, with the decision keys and the scope label of each."""
849
+
850
+ covered: list[Path]
851
+ keys: dict[Path, set[str]]
852
+ labels: dict[Path, str]
853
+
854
+
855
+ def _curate_pass_keys(folder: Path, scope: str, attempts: dict, today: datetime.date) -> set[str]:
856
+ """The decision keys of one folder's queue, as `mem curate done` records them."""
857
+ root = folder.parent if scope == "project" else None
858
+ return set(
859
+ _decisions(
860
+ records.load_memories(folder, scope),
861
+ today,
862
+ attempts=attempts,
863
+ root=root,
864
+ tracked=records.tracked_memories(root) if root else frozenset(),
865
+ ).keys()
866
+ )
867
+
868
+
869
+ def _curate_pass_of(
870
+ store: Path | None, scopes: _CurateScopes, attempts: dict, today: datetime.date
871
+ ) -> _CuratePass | None:
872
+ """The folders a pass covers; None after a message on stderr when one of them is read-only."""
873
+ covered = []
874
+ keys: dict[Path, set[str]] = {}
875
+ labels: dict[Path, str] = {}
876
+ for scope, folder, _ in scopes:
877
+ if folder is None or not folder.is_dir():
878
+ continue
879
+ if common._read_only_store(store, folder.resolve()):
880
+ print(
881
+ common._READ_ONLY_PROJECT if scope == "project" else common._READ_ONLY_MEMORIES,
882
+ file=sys.stderr,
883
+ )
884
+ return None
885
+ covered.append(folder)
886
+ keys[folder] = _curate_pass_keys(folder, scope, attempts, today)
887
+ labels[folder] = scope
888
+ return _CuratePass(covered, keys, labels)
889
+
890
+
891
+ def _curate_record_pass(passed: _CuratePass, today: datetime.date) -> int:
892
+ """Write the marks and the pass dates of the covered folders and say how many items each held; 2 when the write
893
+ fails."""
894
+ if not passed.covered:
895
+ return 0
896
+ try:
897
+ _write_marks(
898
+ os.environ, passed.keys
899
+ ) # first: a failed write leaves the pass date where it was
900
+ _write_passes(os.environ, passed.covered, today)
901
+ except OSError as exc:
902
+ print(f"mem: {exc}", file=sys.stderr)
903
+ return 2
904
+ for folder in sorted(passed.covered, key=lambda f: passed.labels[f] != "global"):
905
+ n = len(passed.keys[folder])
906
+ print(f"recorded {n} {'item' if n == 1 else 'items'} ({passed.labels[folder]})")
907
+ return 0
908
+
909
+
910
+ def _curate_commit_pass(store: Path | None, today: datetime.date) -> None:
911
+ """Commit the store after a pass and trim its logs."""
912
+ if store is not None and store_git.is_repo(store):
913
+ _, failed = common._commit_points(
914
+ store, lambda n: f"curation pass {today.isoformat()}: {n} files"
915
+ )
916
+ # git holds the older states now: the logs keep 30 days. Not while an automatic run may be appending
917
+ # to them, and under the commit lock so a commit never sees a half-written log.
918
+ if not failed and not auto_state.run_lock_held(common.data_dir(os.environ), store):
919
+ store_git.trim_logs_locked(store)
920
+
921
+
922
+ def _curate_done(
923
+ args: argparse.Namespace, scopes: _CurateScopes, attempts: dict, today: datetime.date
924
+ ) -> int:
925
+ """`mem curate --done`: record the pass over the folders loaded."""
926
+ store = common._optional_store(args)
927
+ passed = _curate_pass_of(store, scopes, attempts, today)
928
+ if passed is None:
929
+ return 2
930
+ code = _curate_record_pass(passed, today)
931
+ if code != 0:
932
+ return code
933
+ _curate_commit_pass(store, today)
934
+ return 0
935
+
936
+
937
+ def _curate_decisions(
938
+ scopes: _CurateScopes, attempts: dict, today: datetime.date
939
+ ) -> list[Decisions]:
940
+ """The decision items of each scope, in order."""
941
+ roots = [
942
+ folder.parent if scope == "project" and folder else None for scope, folder, _ in scopes
943
+ ]
944
+ return [
945
+ _decisions(
946
+ loaded,
947
+ today,
948
+ attempts=attempts,
949
+ root=root,
950
+ tracked=records.tracked_memories(root) if root else frozenset(),
951
+ )
952
+ for root, (_, _, loaded) in zip(roots, scopes, strict=False)
953
+ ]
954
+
955
+
956
+ def _curate_refuted_lines(found: Sequence[Decisions]) -> list[str]:
957
+ again = [pair for d in found for pair in d.refuted]
958
+ if not again:
959
+ return []
960
+ out = [
961
+ (
962
+ "written again after being refuted (decide: mem refute <h>, or mem distinct <a> <b> if it is a "
963
+ "different claim)"
964
+ )
965
+ ]
966
+ for a, r in again:
967
+ out += [_tagged(a), _tagged(r, ", refuted")]
968
+ return out
969
+
970
+
971
+ def _curate_same_lines(found: Sequence[Decisions]) -> list[str]:
972
+ same = [pair for d in found for pair in d.same]
973
+ if not same:
974
+ return []
975
+ header = (
976
+ "same or opposite? (decide: mem merge <keep> <drop>, or keep both and say so in the body)"
977
+ )
978
+ return [header, *_grouped_pairs(same)]
979
+
980
+
981
+ def _curate_state_lines(found: Sequence[Decisions]) -> list[str]:
982
+ state = [pair for d in found for pair in d.state]
983
+ if not state:
984
+ return []
985
+ out = [
986
+ "newer state of the same project? (decide: mem supersede <old> <new>, or mem distinct <a> <b>)"
987
+ ]
988
+ for old, new in state:
989
+ out += [_tagged(old), f" -> {_tagged(new).lstrip()}"]
990
+ return out
991
+
992
+
993
+ def _curate_expired_lines(found: Sequence[Decisions]) -> list[str]:
994
+ expired = [m for d in found for m in d.expired]
995
+ if not expired:
996
+ return []
997
+ out = ["expired (decide: mem forget <h>, or mem confirm <h> --until <date> if it still holds)"]
998
+ out += [
999
+ f" m:{m.handle} valid until {m.valid_until.isoformat()} {memory._flat(m.claim)}"
1000
+ for m in expired
1001
+ if m.valid_until is not None
1002
+ ]
1003
+ return out
1004
+
1005
+
1006
+ def _curate_seen_lines(found: Sequence[Decisions]) -> list[str]:
1007
+ frequent = [m for d in found for m in d.seen]
1008
+ if not frequent:
1009
+ return []
1010
+ out = [f"seen {_FREQUENT} times or more: general enough for a global lesson? (mem promote <h>)"]
1011
+ out += [f" m:{m.handle} observed {m.observed} {memory._flat(m.claim)}" for m in frequent]
1012
+ return out
1013
+
1014
+
1015
+ def _curate_stale_lines(found: Sequence[Decisions]) -> list[str]:
1016
+ stale = [m for d in found for m in d.stale]
1017
+ if not stale:
1018
+ return []
1019
+ out = [f"not confirmed in {_STALE_DAYS} days (decide: mem confirm <h> or mem forget <h>)"]
1020
+ out += [
1021
+ f" m:{m.handle} {m.created.isoformat()} {memory._flat(m.claim)}"
1022
+ for m in stale
1023
+ if m.created is not None
1024
+ ]
1025
+ return out
1026
+
1027
+
1028
+ def _curate_awaiting_lines(live: Sequence[records.Memory]) -> list[str]:
1029
+ awaiting = [m for m in live if m.triage == "pending"]
1030
+ if not awaiting:
1031
+ return []
1032
+ out = [
1033
+ (
1034
+ "general lesson, out of quarantine, awaiting triage (decide: mem triage accept <h>, mem triage "
1035
+ "reject <h>, or reword it with mem memory edit <h> --global and then accept)"
1036
+ )
1037
+ ]
1038
+ for m in awaiting:
1039
+ n, p = len(records.sessions(m)), len(records.projects(m))
1040
+ out.append(
1041
+ f" m:{m.handle} {n} session{'' if n == 1 else 's'}, {p} project{'' if p == 1 else 's'} "
1042
+ f"{memory._flat(m.claim)}"
1043
+ )
1044
+ if m.triage_reason:
1045
+ out.append(f" held: {m.triage_reason}")
1046
+ return out
1047
+
1048
+
1049
+ def _curate_worse_lines(
1050
+ args: argparse.Namespace,
1051
+ raw: dict[str, list[records.Memory]],
1052
+ scopes: _CurateScopes,
1053
+ today: datetime.date,
1054
+ ) -> list[str]:
1055
+ """The lessons whose balance got worse after loading; `raw` gets the scope not asked for, loaded quietly."""
1056
+ asked = {scope for scope, _, _ in scopes}
1057
+ for scope, folder in common._memory_folders(
1058
+ args
1059
+ ): # the scope not asked for still counts toward the cap; loaded quietly
1060
+ if scope not in raw:
1061
+ raw[scope] = records.load_memories(folder, scope)
1062
+ worse = [
1063
+ (m, loaded)
1064
+ for m, loaded in _got_worse(raw.get("project", []), raw.get("global", []), today)
1065
+ if m.scope in asked and m.superseded_by is None
1066
+ ]
1067
+ if not worse:
1068
+ return []
1069
+ out = [
1070
+ (
1071
+ "balance got worse after loading (decide: reword it or go back with mem memory edit <h> --short, "
1072
+ "drop it with mem forget <h>, or keep the wording with mem triage accept <h>)"
1073
+ )
1074
+ ]
1075
+ for m, loaded in worse:
1076
+ state = (
1077
+ "rules off" if common._rules_off() else "loaded" if loaded else "left out by the cap"
1078
+ )
1079
+ note = records.reword_note(m)
1080
+ out.append(f" m:{m.handle} {state}{'; ' + note if note else ''} {memory._flat(m.claim)}")
1081
+ found = records.tallies(m)[-2:]
1082
+ ends = [t.since for t in found[1:]] + [today]
1083
+ out += [f" {common._tally_line(t, end)}" for t, end in zip(found, ends, strict=False)]
1084
+ return out
1085
+
1086
+
1087
+ def _curate_quarantine_lines(every: Sequence[records.Memory]) -> list[str]:
1088
+ held = sum(
1089
+ 1 for m in every if m.status == "active" and records.quarantined(m)
1090
+ ) # a lapsed one is still stored
1091
+ if not held:
1092
+ return []
1093
+ return [
1094
+ (
1095
+ f"in quarantine: {held} general lesson{'' if held == 1 else 's'}, not shown to a reader until corroborated "
1096
+ "(mem memories --global --quarantine)"
1097
+ )
1098
+ ]
1099
+
1100
+
1101
+ def _curate_unconfirmed_lines(live: Sequence[records.Memory], unconfirmed: set[str]) -> list[str]:
1102
+ waiting = [m for m in live if m.handle in unconfirmed and not records.quarantined(m)]
1103
+ if not waiting:
1104
+ return []
1105
+ out = [
1106
+ (
1107
+ "from a transcript, not confirmed yet (decide: mem forget <h>, or leave it; it is confirmed only "
1108
+ "when another session shows it)"
1109
+ )
1110
+ ]
1111
+ for m in waiting:
1112
+ n = len(records.sessions(m))
1113
+ out.append(
1114
+ f" m:{m.handle} {m.weight or 'medium'}, {n} session{'' if n == 1 else 's'} {memory._flat(m.claim)}"
1115
+ )
1116
+ return out
1117
+
1118
+
1119
+ def _curate_unread_lines(live: Sequence[records.Memory]) -> list[str]:
1120
+ unread = [m for m in live if m.short_by == "model" and m.short]
1121
+ return [f"short forms nobody read: {len(unread)} (mem rules --unread)"] if unread else []
1122
+
1123
+
1124
+ def _curate_nofill_lines(found: Sequence[Decisions]) -> list[str]:
1125
+ nofill = [m for d in found for m in d.nofill]
1126
+ if not nofill:
1127
+ return []
1128
+ out = [
1129
+ (
1130
+ "established, but the automatic fill will not write its short form (it gave up, or never "
1131
+ f"tries a repository-tracked or strong unconfirmed project lesson); write one of at most "
1132
+ f"{records.SHORT_LIMIT} characters and pick a topic: mem memory edit m:<h> --short '<text>' "
1133
+ "--topic <t>, with --global for a global lesson; add --user-read only when the owner wrote or read the text)"
1134
+ )
1135
+ ]
1136
+ out += [f" m:{m.handle} {memory._flat(m.claim)}" for m in nofill]
1137
+ return out
1138
+
1139
+
1140
+ def _curate_report(
1141
+ args: argparse.Namespace,
1142
+ scopes: _CurateScopes,
1143
+ attempts: dict,
1144
+ today: datetime.date,
1145
+ ) -> int:
1146
+ """Print the curation queue: every decision the owner or the pipeline has to take."""
1147
+ raw = {scope: loaded for scope, _, loaded in scopes}
1148
+ scopes = [(s, f, [m for m in loaded if m.superseded_by is None]) for s, f, loaded in scopes]
1149
+ every = [m for _, _, loaded in scopes for m in loaded if m.error is None]
1150
+ live = [m for m in every if records.is_live(m, today)]
1151
+ found = _curate_decisions(scopes, attempts, today)
1152
+ unconfirmed = _unconfirmed_handles(every) # their own category below
1153
+ out = [
1154
+ *_curate_refuted_lines(found),
1155
+ *_curate_same_lines(found),
1156
+ *_curate_state_lines(found),
1157
+ *_curate_expired_lines(found),
1158
+ *_curate_seen_lines(found),
1159
+ *_curate_stale_lines(found),
1160
+ *_curate_awaiting_lines(live),
1161
+ *_curate_worse_lines(args, raw, scopes, today),
1162
+ *_curate_quarantine_lines(every),
1163
+ *_curate_unconfirmed_lines(live, unconfirmed),
1164
+ *_curate_unread_lines(live),
1165
+ *_curate_nofill_lines(found),
1166
+ ]
1167
+ if not args.is_global:
1168
+ out += _curate_project_syntheses(scopes, today)
1169
+ if out:
1170
+ print("\n".join(out))
1171
+ return 0
1172
+
1173
+
1174
+ def cmd_curate(args: argparse.Namespace) -> int:
1175
+ if args.action == "apply":
1176
+ return _curate_apply(args)
1177
+ if args.new_since is not None:
1178
+ return _curate_new_since(args)
1179
+ if args.notes:
1180
+ return _curate_notes(args)
1181
+ today = datetime.date.today()
1182
+ folders = common._memory_folders(args)
1183
+ if args.is_project or args.is_global:
1184
+ folders = [f for f in folders if (f[0] == "global") == args.is_global]
1185
+ scopes = memory._loaded(folders)
1186
+ attempts = common._fill_attempts(os.environ)
1187
+ if args.done:
1188
+ return _curate_done(args, scopes, attempts, today)
1189
+ return _curate_report(args, scopes, attempts, today)