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,458 @@
1
+ """Reduce a Claude Code session transcript to a compact extract and validate
2
+ the memory candidates a model proposes from it.
3
+
4
+ Pure; standard library and `records` only. The transcript is read line by line and the
5
+ extract is bounded while reading, because transcripts reach hundreds of
6
+ megabytes. Who is the owner is decided by `origin.kind`, not by the entry
7
+ type: most string user entries are subagent reports.
8
+ """
9
+
10
+ import json
11
+ import logging
12
+ import re
13
+ from collections import deque
14
+ from collections.abc import Mapping, Sequence
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from memory_cli.capture import codex_rollout
19
+ from memory_cli.capture.event_lines import (
20
+ AGENT_LIMIT,
21
+ HUMAN_LIMIT,
22
+ REPORT_LIMIT,
23
+ flat,
24
+ result_event,
25
+ text_of,
26
+ tool_use_line,
27
+ )
28
+ from memory_cli.memories import records
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ SIGNALS: tuple[str, ...] = (
33
+ "owner_correction",
34
+ "failed_then_passed",
35
+ "verified_review_finding",
36
+ "plan_changed_by_review",
37
+ "delegation_failed",
38
+ "rework",
39
+ "repeated_tool_error",
40
+ "decision_with_reason",
41
+ "owner_approval",
42
+ "owner_request_paid_off",
43
+ "effective_practice",
44
+ )
45
+ # What a signal says about the lesson (C65): a failure, a thing that worked, or only that it was seen.
46
+ _FAILED = (
47
+ "owner_correction",
48
+ "failed_then_passed",
49
+ "verified_review_finding",
50
+ "delegation_failed",
51
+ "rework",
52
+ "repeated_tool_error",
53
+ )
54
+ _WORKED = ("owner_approval", "owner_request_paid_off", "effective_practice")
55
+
56
+
57
+ def outcome(signal: str) -> str:
58
+ """The case outcome a capture signal records; an unknown signal is `seen`."""
59
+ return "failed" if signal in _FAILED else "worked" if signal in _WORKED else "seen"
60
+
61
+
62
+ REACHES = records.REACHES
63
+ FORMS: tuple[str, ...] = ("suggestion", "recommendation")
64
+ SAME_AS_MIN = 0.3 # the larger share of one claim's terms found in the other, in either direction
65
+ KINDS: tuple[str, ...] = ("lesson", "pitfall", "decision")
66
+ EXTRACT_LIMIT = 80_000
67
+ PART_SIZE = 40_000
68
+ MAX_CANDIDATES = 5
69
+ CLAIM_MIN = 20
70
+ CLAIM_MAX = 400
71
+ EVIDENCE_MIN = 15
72
+ CONTEXT_LIMIT = 300
73
+
74
+ _OWNER_SIGNALS = (
75
+ "owner_correction",
76
+ "decision_with_reason",
77
+ "owner_approval",
78
+ "owner_request_paid_off",
79
+ )
80
+ _LINE_KINDS = ("OWNER", "OWNER ANSWER", "REPORT", "AGENT", "TOOL", "TOOL ERROR", "TOOL OK")
81
+ _MARKER = "[...] earlier lines left out"
82
+ LEFT_OUT_MARKER = _MARKER
83
+ last_skipped = 0 # lines the last extract() could not process, for the caller to report
84
+ last_more = False # forward mode: lines remain after the window the last extract() returned
85
+ _KIND_RE = re.compile(r"^\[\d+\] (OWNER ANSWER|OWNER|REPORT|AGENT|TOOL ERROR|TOOL OK|TOOL)\b")
86
+ _BODY_RE = re.compile(r"^\[\d+\] (OWNER ANSWER|OWNER|REPORT|AGENT|TOOL ERROR \S+|TOOL \S+): (.*)$")
87
+
88
+
89
+ def _blocks(content: object) -> list[dict]:
90
+ return [b for b in content if isinstance(b, dict)] if isinstance(content, list) else []
91
+
92
+
93
+ def _is_human(origin: object) -> bool:
94
+ return isinstance(origin, dict) and origin.get("kind") == "human"
95
+
96
+
97
+ def _queued_prompt(entry: dict) -> dict | None:
98
+ att = entry.get("attachment")
99
+ if (
100
+ isinstance(att, dict)
101
+ and att.get("type") == "queued_command"
102
+ and att.get("commandMode") == "prompt"
103
+ and not att.get("isMeta")
104
+ and not entry.get("isMeta")
105
+ ):
106
+ return att
107
+ return None
108
+
109
+
110
+ def _attachment_events(entry: dict) -> list[str]:
111
+ att = _queued_prompt(entry)
112
+ if att is None:
113
+ return []
114
+ origin = att.get(
115
+ "origin", entry.get("origin")
116
+ ) # the origin of a queued command sits on the attachment
117
+ human = origin is None or _is_human(origin)
118
+ text = flat(text_of(att.get("prompt")), HUMAN_LIMIT if human else REPORT_LIMIT)
119
+ if not text:
120
+ return []
121
+ return [f"OWNER: {text}" if human else f"REPORT: {text}"]
122
+
123
+
124
+ def _assistant_events(content: object, names: dict) -> list[str]:
125
+ out: list[str] = []
126
+ blocks: list[dict] = (
127
+ [{"type": "text", "text": content}] if isinstance(content, str) else _blocks(content)
128
+ )
129
+ for b in blocks:
130
+ if b.get("type") == "text" and isinstance(b.get("text"), str):
131
+ text = flat(b["text"], AGENT_LIMIT)
132
+ if text:
133
+ out.append(f"AGENT: {text}")
134
+ elif b.get("type") == "tool_use":
135
+ out.append(tool_use_line(b, names))
136
+ return out
137
+
138
+
139
+ def _result_events(content: object, names: dict, state: dict) -> list[str]:
140
+ out: list[str] = []
141
+ for b in _blocks(content):
142
+ if b.get("type") != "tool_result":
143
+ continue
144
+ event = result_event(b, names.get(b.get("tool_use_id"), "?"), state)
145
+ if event is not None:
146
+ out.append(event)
147
+ return out
148
+
149
+
150
+ def _user_text_events(entry: dict, content: object) -> list[str]:
151
+ if entry.get("isMeta") or entry.get("isCompactSummary"):
152
+ return []
153
+ text = text_of(content)
154
+ if not text.strip():
155
+ return []
156
+ origin = entry.get("origin")
157
+ human = _is_human(origin) or (origin is None and not text.lstrip().startswith("<"))
158
+ body = flat(text, HUMAN_LIMIT if human else REPORT_LIMIT)
159
+ if body and human:
160
+ return [f"OWNER: {body}"]
161
+ if body and origin is not None:
162
+ return [f"REPORT: {body}"]
163
+ return []
164
+
165
+
166
+ def _events(entry: dict, names: dict, state: dict) -> list[str]:
167
+ """Extract lines (without the line number prefix) of one transcript entry."""
168
+ kind = entry.get("type")
169
+ if kind == "attachment":
170
+ return _attachment_events(entry)
171
+ msg = entry.get("message")
172
+ content = msg.get("content") if isinstance(msg, dict) else None
173
+ if kind == "assistant":
174
+ return _assistant_events(content, names)
175
+ if kind != "user":
176
+ return []
177
+ return _result_events(content, names, state) + _user_text_events(entry, content)
178
+
179
+
180
+ def _decode(raw: str, names: dict, state: dict, decoder: Any = _events) -> list[str]:
181
+ entry = json.loads(raw)
182
+ return decoder(entry, names, state) if isinstance(entry, dict) else []
183
+
184
+
185
+ class _Window:
186
+ """The kept lines of an extract, bounded to the budget."""
187
+
188
+ def __init__(self, forward: bool) -> None:
189
+ self.forward = forward
190
+ self.budget = EXTRACT_LIMIT - len(_MARKER) - 1
191
+ self.lines: deque[str] = deque()
192
+ self.size = 0 # characters of the kept lines, one newline each
193
+ self.left_out = False
194
+
195
+ def overflows(self, n: int, events: list[str]) -> bool:
196
+ if not (self.forward and self.lines):
197
+ return False
198
+ return self.size + sum(len(f"[{n}] {ev}") + 1 for ev in events) > self.budget
199
+
200
+ def add(self, n: int, events: list[str]) -> None:
201
+ for ev in events:
202
+ line = f"[{n}] {ev}"
203
+ self.lines.append(line)
204
+ self.size += len(line) + 1
205
+ while not self.forward and self.size > self.budget and self.lines:
206
+ self.size -= len(self.lines.popleft()) + 1
207
+ self.left_out = True
208
+
209
+ def text(self) -> str:
210
+ if self.left_out:
211
+ self.lines.appendleft(_MARKER)
212
+ return "\n".join(self.lines)
213
+
214
+
215
+ class _Scan:
216
+ """One pass over a transcript: the window plus what `extract` reports about it."""
217
+
218
+ def __init__(self, since_line: int, forward: bool) -> None:
219
+ self.forward = forward
220
+ self.window = _Window(forward)
221
+ self.names: dict = {}
222
+ self.state: dict = {}
223
+ self.last = since_line
224
+ self.skipped = 0
225
+ self.more = False
226
+ self.decoder: Any = _events
227
+ self.prime_marks = ("tool_use", "tool_result")
228
+
229
+ def choose(self, first_line: str) -> None:
230
+ """Pick the decoder once per file from its first line: a Codex rollout or a Claude transcript."""
231
+ if codex_rollout.is_rollout(first_line):
232
+ self.decoder = codex_rollout.events
233
+ self.prime_marks = ("_call", "session_meta")
234
+
235
+ def prime(self, raw: str) -> None:
236
+ """Learn tool names and failure state from a line before the window; nothing else matters."""
237
+ if not any(mark in raw for mark in self.prime_marks):
238
+ return
239
+ try:
240
+ _decode(raw, self.names, self.state, self.decoder)
241
+ except Exception:
242
+ # not counted: the earlier window already reported it
243
+ logger.debug("capture: unreadable line before the window", exc_info=True)
244
+
245
+ def read(self, n: int, raw: str) -> bool:
246
+ """Take line `n` into the window; False when the window is done."""
247
+ if self.forward and not raw.endswith("\n"):
248
+ return False # a line still being written is read once it is finished
249
+ self.last = n
250
+ try: # no line of any content may stop the extract
251
+ events = _decode(raw, self.names, self.state, self.decoder)
252
+ except json.JSONDecodeError:
253
+ return True # a line that is not JSON is ordinary
254
+ except Exception:
255
+ # anything else may be a defect here: counted, so an emptied extract is noticed
256
+ logger.debug("capture: line %d could not be processed", n, exc_info=True)
257
+ self.skipped += 1
258
+ return True
259
+ if self.window.overflows(n, events):
260
+ self.last, self.more = n - 1, True
261
+ return False
262
+ self.window.add(n, events)
263
+ return True
264
+
265
+
266
+ def extract(transcript: Path, since_line: int = 0, forward: bool = False) -> tuple[str, int]:
267
+ """Extract text and number of the last line read (1-based).
268
+
269
+ By default the newest lines are kept and the oldest left out. With `forward` the window starts at
270
+ `since_line` and stops before the first line that would overflow it (`last_more` is then True); a first
271
+ line larger than the budget is kept, so every call advances, and an unterminated last line is left for the
272
+ next call. Lines up to `since_line` are parsed only to know the tool names and failures a result refers to."""
273
+ scan = _Scan(since_line, forward)
274
+ with open(transcript, encoding="utf-8", errors="replace") as f:
275
+ for n, raw in enumerate(f, 1):
276
+ if n == 1:
277
+ scan.choose(raw)
278
+ if n <= since_line:
279
+ scan.prime(raw)
280
+ elif not scan.read(n, raw):
281
+ break
282
+ global last_skipped, last_more
283
+ last_skipped, last_more = scan.skipped, scan.more
284
+ return scan.window.text(), scan.last
285
+
286
+
287
+ def parts(text: str, size: int = PART_SIZE) -> list[str]:
288
+ """Split at line boundaries into pieces of at most `size` characters."""
289
+ pieces: list[str] = []
290
+ cur: list[str] = []
291
+ cur_len = 0
292
+ for line in text.split("\n"):
293
+ if cur and cur_len + 1 + len(line) > size:
294
+ pieces.append("\n".join(cur))
295
+ cur, cur_len = [], 0
296
+ cur_len += len(line) + (1 if cur else 0)
297
+ cur.append(line)
298
+ pieces.append("\n".join(cur))
299
+ return pieces
300
+
301
+
302
+ def counts(extract_text: str) -> dict[str, int]:
303
+ result: dict[str, int] = dict.fromkeys(_LINE_KINDS, 0)
304
+ for line in extract_text.split("\n"):
305
+ m = _KIND_RE.match(line)
306
+ if m:
307
+ result[m.group(1)] += 1
308
+ return result
309
+
310
+
311
+ def _squash(s: str) -> str:
312
+ return " ".join(s.split())
313
+
314
+
315
+ def _norm(s: str) -> str:
316
+ return " ".join(s.split()).lower()
317
+
318
+
319
+ _ENUM_FIELDS = (
320
+ ("kind", None, KINDS),
321
+ ("signal", None, SIGNALS),
322
+ ("reach", "project", REACHES),
323
+ ("weight", "medium", records.WEIGHTS),
324
+ ("form", "recommendation", FORMS),
325
+ )
326
+
327
+
328
+ def _field_reason(item: dict) -> str:
329
+ for key, default, allowed in _ENUM_FIELDS:
330
+ if item.get(key, default) not in allowed:
331
+ return key
332
+ if item["kind"] == "decision" and item.get("reach", "project") == "general":
333
+ return "a decision is a project record"
334
+ return ""
335
+
336
+
337
+ def _link_reason(item: dict, handles: Mapping[str, str]) -> str:
338
+ same_as = item.get("same_as")
339
+ if same_as is not None and (not isinstance(same_as, str) or same_as not in handles):
340
+ return "same_as"
341
+ claim = item.get("claim")
342
+ if not isinstance(claim, str) or not CLAIM_MIN <= len(_squash(claim)) <= CLAIM_MAX:
343
+ return "claim length"
344
+ if same_as is not None and _overlap(claim, handles[same_as]) < SAME_AS_MIN:
345
+ return "same_as mismatch"
346
+ return ""
347
+
348
+
349
+ def _evidence_reason(item: dict, bodies: list[tuple[str, str]]) -> str:
350
+ evidence = item.get("evidence")
351
+ ev = " ".join(evidence.split()) if isinstance(evidence, str) else ""
352
+ hits = [k for k, body in bodies if ev in body] if len(ev) >= EVIDENCE_MIN else []
353
+ if not hits:
354
+ return "evidence not in the transcript"
355
+ if item["signal"] in _OWNER_SIGNALS and not any(k.startswith("OWNER") for k in hits):
356
+ return "evidence is not the owner's words"
357
+ return ""
358
+
359
+
360
+ def _repeat_reason(item: dict, recorded: set[str], sighted: set[str]) -> str:
361
+ same_as = item.get("same_as")
362
+ if same_as is not None:
363
+ return "same_as repeated" if same_as in sighted else ""
364
+ return "already recorded" if _norm(item["claim"]) in recorded else ""
365
+
366
+
367
+ def _reason(
368
+ item: object,
369
+ bodies: list[tuple[str, str]],
370
+ recorded: set[str],
371
+ handles: Mapping[str, str],
372
+ sighted: set[str],
373
+ ) -> str:
374
+ if not isinstance(item, dict):
375
+ return "not an object"
376
+ return (
377
+ _field_reason(item)
378
+ or _link_reason(item, handles)
379
+ or _evidence_reason(item, bodies)
380
+ or _repeat_reason(item, recorded, sighted)
381
+ )
382
+
383
+
384
+ def _overlap(claim: str, other: str) -> float:
385
+ """How much two claims share, from either side: a hedged candidate is longer than the record it repeats."""
386
+ a, b = records.tokenize(claim), records.tokenize(other)
387
+ return max(records.containment(a, set(b)), records.containment(b, set(a)))
388
+
389
+
390
+ def _bodies(extract_text: str) -> list[tuple[str, str]]:
391
+ bodies = []
392
+ for line in extract_text.split("\n"):
393
+ m = _BODY_RE.match(line)
394
+ if m:
395
+ bodies.append((m.group(1), " ".join(m.group(2).split())))
396
+ return bodies
397
+
398
+
399
+ def _by_claim(handles: Mapping[str, str]) -> dict[str, str]:
400
+ by_claim: dict[str, str] = {}
401
+ for h, c in handles.items():
402
+ # the same claim in a project record and a global one links to the global one: sightings are counted there
403
+ if _norm(c) not in by_claim or h.startswith("g:"):
404
+ by_claim[_norm(c)] = h
405
+ return by_claim
406
+
407
+
408
+ def _link_identical(item: Any, by_claim: Mapping[str, str]) -> Any:
409
+ """An identical claim is one more sighting of the project's record, not a new one."""
410
+ if (
411
+ isinstance(item, dict)
412
+ and item.get("same_as") is None
413
+ and isinstance(item.get("claim"), str)
414
+ and _norm(item["claim"]) in by_claim
415
+ ):
416
+ return {**item, "same_as": by_claim[_norm(item["claim"])]}
417
+ return item
418
+
419
+
420
+ def _kept_entry(item: dict) -> dict:
421
+ context = item.get("context")
422
+ return {
423
+ "kind": item["kind"],
424
+ "signal": item["signal"],
425
+ "reach": item.get("reach", "project"),
426
+ "weight": item.get("weight", "medium"),
427
+ "form": item.get("form", "recommendation"),
428
+ "claim": _squash(item["claim"]),
429
+ "context": _squash(context)[:CONTEXT_LIMIT] if isinstance(context, str) else "",
430
+ "evidence": _squash(item["evidence"]),
431
+ "same_as": item.get("same_as"),
432
+ }
433
+
434
+
435
+ def validate(
436
+ candidates: object, extract_text: str, recorded: Sequence[str], handles: Mapping[str, str] = {}
437
+ ) -> tuple[list[dict], list[dict]]:
438
+ """Split candidates into kept and dropped ({"candidate", "reason"}). `handles` maps "m:<handle>" to the claim
439
+ of a memory of this project that a candidate may name in `same_as` as one more sighting."""
440
+ if not isinstance(candidates, list):
441
+ return [], [{"candidate": candidates, "reason": "not a list"}]
442
+ bodies = _bodies(extract_text)
443
+ done = {_norm(r) for r in recorded}
444
+ by_claim = _by_claim(handles)
445
+ kept: list[dict] = []
446
+ dropped: list[dict] = []
447
+ sighted: set[str] = set()
448
+ for candidate in candidates:
449
+ item = _link_identical(candidate, by_claim)
450
+ over = len(kept) >= MAX_CANDIDATES
451
+ reason = "over the limit" if over else _reason(item, bodies, done, handles, sighted)
452
+ if reason:
453
+ dropped.append({"candidate": item, "reason": reason})
454
+ continue
455
+ if item.get("same_as") is not None:
456
+ sighted.add(item["same_as"])
457
+ kept.append(_kept_entry(item))
458
+ return kept, dropped
@@ -0,0 +1,183 @@
1
+ """State of the background transcript capture (`bin/mem-capture auto`), kept outside the store.
2
+
3
+ Layout: `<data folder>/capture/` (mode 0700) holds `status.json`, `sessions/<hash>.json` (how far each session was read)
4
+ and `runs/<stamp>/` (logs and results). Standard library only, and no import of `records`, `capture` or `yaml`: the
5
+ caller loads this module first, so a missing dependency can still be reported through it."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import datetime
10
+ import hashlib
11
+ import json
12
+ import shutil
13
+ import time
14
+ from pathlib import Path
15
+
16
+ from memory_cli.core import jobs
17
+
18
+ MAX_WINDOWS = 3 # windows read in one trigger
19
+ MAX_NEW_PER_TRIGGER = 5 # new memories one trigger may write
20
+ MAX_ATTEMPTS = 2 # tries of one window before its offset moves on
21
+ LOCK_WAIT_SECONDS = 900
22
+ PRE_COMPACT_DELAY_SECONDS = 300
23
+ KEEP_RUNS = 20
24
+ KEEP_RUN_DAYS = 14
25
+ SWEEP_IDLE_SECONDS = 6 * 3600 # a session this recently changed may still be open and live
26
+ SWEEP_MAX_AGE_DAYS = 7
27
+ SWEEP_MAX_SESSIONS = 2 # runs that start a model session at one start
28
+ SWEEP_MAX_EXAMINED = 10 # candidate files one start may examine, newest first
29
+ SWEEP_LOCK_WAIT_SECONDS = 30 # a sweep gives up on a held capture lock sooner than a hook does
30
+ SWEEP_MAX_PER_DAY = 4 # sessions swept per UTC day for one data folder
31
+ SWEEP_DAY_NAME = "sweep-day.json"
32
+ OPTION = "CLAUDE_PLUGIN_OPTION_AUTO_CAPTURE"
33
+ BUDGET_OPTION = "CLAUDE_PLUGIN_OPTION_AUTO_CAPTURE_BUDGET"
34
+
35
+
36
+ def capture_dir(data: Path) -> Path:
37
+ return Path(data) / "capture"
38
+
39
+
40
+ def _transcript_key(transcript: Path) -> str:
41
+ return hashlib.sha256(str(transcript.expanduser().resolve()).encode()).hexdigest()
42
+
43
+
44
+ class ExclusionRegistryError(ValueError):
45
+ """Unreadable or malformed automatic capture exclusions."""
46
+
47
+
48
+ def _read_exclusions(data: Path) -> set[str]:
49
+ """Read the exclusion registry, failing closed if it cannot be decoded or read."""
50
+ try:
51
+ contents = (capture_dir(data) / "excluded.json").read_text(encoding="utf-8")
52
+ except FileNotFoundError:
53
+ return set()
54
+ value = json.loads(contents)
55
+ if not isinstance(value, dict) or not isinstance(value.get("transcripts"), list):
56
+ raise TypeError("invalid capture exclusion registry")
57
+ items = value["transcripts"]
58
+ if any(not isinstance(item, str) for item in items):
59
+ raise TypeError("invalid capture exclusion registry")
60
+ return set(items)
61
+
62
+
63
+ def exclusions(data: Path) -> set[str]:
64
+ try:
65
+ return _read_exclusions(data)
66
+ except (OSError, ValueError, TypeError, RecursionError) as exc:
67
+ raise ExclusionRegistryError("capture exclusion registry is unreadable or invalid") from exc
68
+
69
+
70
+ def is_excluded(data: Path, transcript: Path) -> bool:
71
+ return _transcript_key(transcript) in exclusions(data)
72
+
73
+
74
+ def exclude(data: Path, transcript: Path) -> None:
75
+ """Add an exclusion while the caller holds the capture lock."""
76
+ values = exclusions(data)
77
+ values.add(_transcript_key(transcript))
78
+ jobs.write_json(capture_dir(data) / "excluded.json", {"transcripts": sorted(values)})
79
+
80
+
81
+ def session_path(data: Path, session: str) -> Path:
82
+ """The state file of one session; the name is a hash, so no session string becomes a file name."""
83
+ return (
84
+ capture_dir(data)
85
+ / "sessions"
86
+ / (hashlib.sha1(session.encode("utf-8", "replace")).hexdigest()[:16] + ".json")
87
+ )
88
+
89
+
90
+ def _count(value) -> int:
91
+ """A stored counter: a non-negative int (a JSON boolean is not one), else 0."""
92
+ return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else 0
93
+
94
+
95
+ def read_session(data: Path, session: str) -> dict:
96
+ found = jobs.read_json(session_path(data, session))
97
+ offset, attempts = found.get("offset"), found.get("attempts")
98
+ return {"offset": _count(offset), "attempts": _count(attempts)}
99
+
100
+
101
+ def swept_size(data: Path, session: str) -> int | None:
102
+ """The file's size at its last sweep, None when it was never swept."""
103
+ found = jobs.read_json(session_path(data, session)).get("swept_size")
104
+ return _count(found) if found is not None else None
105
+
106
+
107
+ def save_session(data: Path, session: str, offset: int, attempts: int) -> None:
108
+ path = session_path(data, session)
109
+ jobs.private_dir(path.parent)
110
+ state = {"session": session, "offset": offset, "attempts": attempts, "updated": time.time()}
111
+ swept = swept_size(data, session)
112
+ if swept is not None:
113
+ state["swept_size"] = swept # a capture keeps what the last sweep saw
114
+ jobs.write_json(path, state)
115
+
116
+
117
+ def save_swept_size(data: Path, session: str, size: int) -> None:
118
+ """Remember the file's size at its sweep, next to the offset, so an unchanged file is not swept again."""
119
+ path = session_path(data, session)
120
+ jobs.private_dir(path.parent)
121
+ found = read_session(data, session)
122
+ jobs.write_json(
123
+ path,
124
+ {
125
+ "session": session,
126
+ "offset": found["offset"],
127
+ "attempts": found["attempts"],
128
+ "swept_size": size,
129
+ "updated": time.time(),
130
+ },
131
+ )
132
+
133
+
134
+ def _utc_day(now: float) -> str:
135
+ return datetime.datetime.fromtimestamp(now, datetime.UTC).date().isoformat()
136
+
137
+
138
+ def sweeps_today(data: Path, now: float) -> int:
139
+ found = jobs.read_json(capture_dir(data) / SWEEP_DAY_NAME)
140
+ return _count(found.get("count")) if found.get("day") == _utc_day(now) else 0
141
+
142
+
143
+ def note_sweep(data: Path, now: float) -> None:
144
+ """Count one swept session against today's cap."""
145
+ jobs.private_dir(capture_dir(data))
146
+ jobs.write_json(
147
+ capture_dir(data) / SWEEP_DAY_NAME,
148
+ {"day": _utc_day(now), "count": sweeps_today(data, now) + 1},
149
+ )
150
+
151
+
152
+ def failure_line(data: Path | None, now: float) -> str | None:
153
+ """The one line `mem session-index` adds after a failed capture; None when there is nothing to show."""
154
+ if data is None:
155
+ return None
156
+ found = jobs.failure(jobs.read_json(capture_dir(data) / jobs.STATUS_NAME), now)
157
+ if found is None:
158
+ return None
159
+ try:
160
+ when = datetime.datetime.fromtimestamp(float(found.get("at") or now)).date().isoformat()
161
+ except (TypeError, ValueError, OverflowError, OSError):
162
+ when = datetime.datetime.fromtimestamp(now).date().isoformat()
163
+ reason = " ".join(str(found["reason"]).split())[:200]
164
+ return (
165
+ f"Automatic capture failed on {when}: {reason}; log: {found.get('log') or '(none)'} "
166
+ "(mem-capture ack clears this)."
167
+ )
168
+
169
+
170
+ def prune_runs(runs: Path, keep: int, max_age_days: int, now: float) -> None:
171
+ """Delete run folders beyond the newest `keep` and any older than `max_age_days`."""
172
+ try:
173
+ folders = [
174
+ (p.stat().st_mtime, p)
175
+ for p in Path(runs).iterdir()
176
+ if p.is_dir() and not p.is_symlink()
177
+ ]
178
+ except OSError:
179
+ return
180
+ folders.sort(key=lambda item: item[0], reverse=True)
181
+ for index, (mtime, folder) in enumerate(folders):
182
+ if index >= keep or now - mtime > max_age_days * 86400:
183
+ shutil.rmtree(folder, ignore_errors=True)
@@ -0,0 +1,21 @@
1
+ """The `mem` command handlers (A5, ADR 0028), a top layer like `entry`: it may import every package and only `mem` imports it.
2
+
3
+ Modules:
4
+
5
+ `common`: helpers shared by the handlers and the dispatch (store resolution, logs, note resolution, guards, `UsageError`)
6
+ `admin`: `terms`, `projects`, `init`, `history`
7
+ `read`: `check`, `index`, `find`, `topics`, `show`, `search`, `passages`, `related`, `search-eval`, `stats`, `review`
8
+ `edit`: `new`, `note` (edit and marks), `rename`, `unify`; `new_note` and the attach-to-section helpers
9
+ `import_recovery`: write-ahead rollback journal for interrupted imports
10
+ `sources`: `fetch-sources` and `import`; download, HTML and PDF text extraction, and the store import
11
+ `memory`: `remember`, `confirm` (and `observe`), `refute`, `forget`, `triage`, `supersede`, `merge`, `distinct`, `restore`, `promote`, `memories`, `rules`, `memory` (edit) and `settle`
12
+ `curate`: `curate`, and the session-start curation decisions (passes, marks, pair and note queues)
13
+ `hooks`: `session-index`, `compact-log` and `signal`, with the session start text and the logic only they use
14
+ `diagnostics`: read-only report of local plugin, store, roles and hooks
15
+ `install`: `install-command`, which puts a `mem` launcher on PATH, and the plugin-root record the launcher follows
16
+ `synthesis`: `synthesis` (list, new, add, append, edit, attach, rename, remove, detach, topics, refs) and `project-synthesis`, with the logic only they use
17
+ `split`: CLI for split proposals, preview, apply, status, recovery and undo
18
+ `split_plan`: read-only synthesis split proposals and previews
19
+ `split_transaction`: recoverable split groups and exact undo
20
+ `integrate`: `synthesis integrate`, which joins knowledge notes to parts of a synthesis (registered by `mem`, not by the synthesis dispatch, because it imports `synthesis`)
21
+ """