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,164 @@
1
+ """The backfill of inline references for existing syntheses (`mem-synthesize --backfill`).
2
+
3
+ A cheap session reads one synthesis's units and its source notes and answers `<part> | <number> | <path or none>`
4
+ lines; this module selects the parts, builds the session's input and command, parses the answer and keeps the done
5
+ list. The session never writes: Python turns its lines into `mem synthesis refs` proposals, so a wrong answer can be
6
+ a wrong reference, never a changed sentence."""
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import re
13
+ import time
14
+ from typing import TYPE_CHECKING, NamedTuple, TypedDict, Unpack
15
+
16
+ from memory_cli.core import headless
17
+ from memory_cli.syntheses import document
18
+ from memory_cli.syntheses import units as synthesis_units
19
+ from memory_cli.synthesize import pipeline as sp
20
+
21
+ if TYPE_CHECKING:
22
+ from pathlib import Path
23
+
24
+ ANSWER_LINE = re.compile(
25
+ r"^\s*`?\s*(?P<part>[^|\s`]+)\s*\|\s*(?P<n>\d+)\s*\|\s*`?(?P<target>[^|`\s]+)`?\s*$"
26
+ )
27
+ FENCE_LINE = re.compile(r"^\s*(```|~~~)")
28
+ TIMEOUT = 900
29
+
30
+
31
+ def select(path: Path, done: dict[str, str]) -> list[dict]:
32
+ """The parts of the synthesis file that the backfill sends: at least one note source, a unit without
33
+ reference, and no done entry equal to the part's fingerprint (`done`: section handle -> fingerprint).
34
+
35
+ Each: `handle`, `units` (all its units), `bare` (those without reference), `sources` (note targets, as on its
36
+ `Sources:` line), `fingerprint`."""
37
+ chosen = []
38
+ for section in document.load_one(path).parts:
39
+ sources = [t for t in section.sources if synthesis_units._is_ref(t)]
40
+ found, _ = synthesis_units.units(section.text)
41
+ bare = [u for u in found if not u.refs]
42
+ fingerprint = synthesis_units.fingerprint(section.text)
43
+ if sources and bare and done.get(section.handle) != fingerprint:
44
+ chosen.append({
45
+ "handle": section.handle,
46
+ "units": found,
47
+ "bare": bare,
48
+ "sources": sources,
49
+ "fingerprint": fingerprint,
50
+ })
51
+ return chosen
52
+
53
+
54
+ def write_input(path: Path, parts: list[dict], work: Path) -> tuple[Path, Path]:
55
+ """The units file restricted to `parts`, and the `target -> absolute path` list of their source notes."""
56
+ keep = {p["handle"] for p in parts}
57
+ lines, inside = [], False
58
+ for line in sp.units_text(path).splitlines():
59
+ if line.startswith("## "):
60
+ inside = line[3:] in keep
61
+ if inside:
62
+ lines.append(line)
63
+ units, notes = work / "units-backfill.md", work / "notes-backfill.md"
64
+ units.write_text("\n".join(lines) + "\n", encoding="utf-8")
65
+ seen = dict.fromkeys(t for p in parts for t in p["sources"])
66
+ notes.write_text(
67
+ "".join(f"{t} -> {document._resolved(path.parent, t)}\n" for t in seen), encoding="utf-8"
68
+ )
69
+ return units, notes
70
+
71
+
72
+ class SessionOptions(TypedDict):
73
+ settings: Path
74
+ max_budget: float | None
75
+
76
+
77
+ def session_cmd(
78
+ claude: str, prompt: str, work: Path, store: Path, **options: Unpack[SessionOptions]
79
+ ) -> list[str]:
80
+ """Only Read exists (`--tools`, no MCP server) and the rules allow it inside the work folder and the store
81
+ (`//` is an absolute path in a permission rule): no shell, no web, no write."""
82
+ return headless.command(
83
+ headless.Session(
84
+ claude=claude,
85
+ prompt=prompt,
86
+ model="haiku",
87
+ effort=sp.CHEAP,
88
+ settings=options["settings"],
89
+ tools=("Read",),
90
+ # --tools says which tools exist; a headless session still needs the permission to call them
91
+ allowed=(f"Read(/{work}/**)", f"Read(/{store}/**)"),
92
+ max_budget=options["max_budget"],
93
+ )
94
+ )
95
+
96
+
97
+ def run_session(cmd: list[str], work: Path, env: dict, log: Path) -> dict:
98
+ start = time.monotonic()
99
+ raw = headless.run_raw(cmd, cwd=work, env=env, timeout=TIMEOUT).stdout
100
+ log.write_text(raw, encoding="utf-8")
101
+ result = sp.parse(raw)
102
+ result["wall"] = time.monotonic() - start
103
+ return result
104
+
105
+
106
+ class Answer(NamedTuple):
107
+ found: list[tuple[str, int, str]] # (part, number, target or "none") in order without repeats
108
+ unreadable: int
109
+ repeated: int # readable lines dropped as repeats: found + unreadable + repeated = the non-blank, non-fence lines
110
+ nothing: bool # the answer is exactly the word `nothing`: an explicit empty result
111
+
112
+
113
+ def parse_answer(answer: str) -> Answer:
114
+ """Blank lines and code fence lines are ignored; `None`/`NONE` mean `none`; backticks, angle brackets and a
115
+ trailing full stop around a target are stripped."""
116
+ if re.fullmatch(r"\s*nothing\.?\s*", answer, re.IGNORECASE):
117
+ return Answer([], 0, 0, True)
118
+ found, unreadable, lines = [], 0, 0
119
+ for line in answer.splitlines():
120
+ if not line.strip() or FENCE_LINE.match(line):
121
+ continue
122
+ lines += 1
123
+ m = ANSWER_LINE.match(line)
124
+ if not m:
125
+ unreadable += 1
126
+ continue
127
+ target = m["target"].strip("`<>").removesuffix(".").strip("`<>")
128
+ if target.lower() == "none":
129
+ target = "none"
130
+ found.append((m["part"].removeprefix("s:").split("#")[-1], int(m["n"]), target))
131
+ unique = list(dict.fromkeys(found))
132
+ return Answer(unique, unreadable, len(found) - len(unique), False)
133
+
134
+
135
+ def load_done(path: Path) -> tuple[dict, bool]:
136
+ """(store -> synthesis handle -> section handle -> fingerprint, readable). A missing file is `({}, True)`; a file
137
+ that exists but is not that shape is `({}, False)`, so the caller can refuse to go on."""
138
+ try:
139
+ data = json.loads(path.read_text(encoding="utf-8"))
140
+ except FileNotFoundError:
141
+ return {}, True
142
+ except (OSError, ValueError):
143
+ return {}, False
144
+ ok = isinstance(data, dict) and all(
145
+ isinstance(syns, dict)
146
+ and all(
147
+ isinstance(parts, dict) and all(isinstance(fp, str) for fp in parts.values())
148
+ for parts in syns.values()
149
+ )
150
+ for syns in data.values()
151
+ )
152
+ return (data, True) if ok else ({}, False)
153
+
154
+
155
+ def save_done(path: Path, store: str, handle: str, entries: dict[str, str]) -> None:
156
+ """Merge one synthesis's part entries into the file as it is now, so a run on another synthesis keeps its own."""
157
+ path.parent.mkdir(parents=True, exist_ok=True)
158
+ data, ok = load_done(path)
159
+ if not ok:
160
+ raise ValueError(f"{path} is not a readable done list")
161
+ data.setdefault(store, {}).setdefault(handle, {}).update(entries)
162
+ tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
163
+ tmp.write_text(json.dumps(data, indent=1, sort_keys=True) + "\n", encoding="utf-8")
164
+ tmp.replace(path)
@@ -0,0 +1,150 @@
1
+ """Shared pieces of `mem-synthesize`: constants, the store and session environment, the table helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import time
8
+ from typing import TYPE_CHECKING
9
+
10
+ from memory_cli.core import config, jobs
11
+ from memory_cli.synthesize import pipeline as sp
12
+
13
+ if TYPE_CHECKING:
14
+ from collections.abc import Callable
15
+ from pathlib import Path
16
+
17
+
18
+ AGENT = "memory:memory-synthesizer"
19
+
20
+
21
+ ESTIMATE_PER_TOPIC = (
22
+ 0.5 # USD: 0.25 measured at medium effort, doubled for the owner's high setting
23
+ )
24
+
25
+
26
+ TOPIC_LINE = re.compile(r"^ (\S+) (\d+) notes\s*$")
27
+
28
+
29
+ ATTACH_LINE = re.compile(r"^(knowledge/\S+\.md)\t(s:[^\s#]+#[^\s#]+)\s*$")
30
+
31
+
32
+ ESTIMATE_PER_BACKFILL = (
33
+ 0.05 # USD per synthesis session: measured 0.035 to 0.053 (trial of 2026-11-18)
34
+ )
35
+
36
+
37
+ FAILED_WORDS_PER_FAKE_ROW = (
38
+ 2 # the self-check's fake claude: "failed" appears in the status and in the table row
39
+ )
40
+
41
+
42
+ BACKFILL_HEADER = (
43
+ "synthesis",
44
+ "parts",
45
+ "units",
46
+ "proposed",
47
+ "applied",
48
+ "refused",
49
+ "none",
50
+ "unreadable",
51
+ "repeated",
52
+ "mem check",
53
+ "cost USD",
54
+ "status",
55
+ )
56
+
57
+
58
+ HEADER = (
59
+ "topic",
60
+ "parts",
61
+ "attached",
62
+ "fixed",
63
+ "deleted",
64
+ "reverted",
65
+ "refs",
66
+ "refused",
67
+ "none",
68
+ "mem check",
69
+ "cost USD",
70
+ "status",
71
+ )
72
+
73
+
74
+ def default_store() -> Path | None:
75
+ """The store `mem` falls back to: MEM_STORE, the config file, else the marked default store."""
76
+ return config.resolve_store(None, os.environ)
77
+
78
+
79
+ state_dir = jobs.state_dir
80
+
81
+
82
+ def session_env(store: Path) -> dict:
83
+ """The environment of the headless sessions and of the `mem` calls: aimed at `store` only; the installed
84
+ plugin's `bin/` is dropped from PATH so the sessions run this plugin's `mem`."""
85
+ env = {
86
+ k: v
87
+ for k, v in os.environ.items()
88
+ if k not in {"MEM_STORE", "MEM_MEMORIES", "MEM_PROJECT"}
89
+ and not k.startswith("CLAUDE_PLUGIN_OPTION_")
90
+ }
91
+ env["PATH"] = os.pathsep.join(
92
+ p for p in env.get("PATH", "").split(os.pathsep) if "/plugins/cache/" not in p
93
+ )
94
+ env["MEM_STORE"] = str(store)
95
+ return env
96
+
97
+
98
+ def topics_without_synthesis(curate_output: str) -> list[str]:
99
+ """Topic ids listed under "no synthesis" in the output of `mem curate --notes`."""
100
+ topics, inside = [], False
101
+ for line in curate_output.splitlines():
102
+ if line and not line.startswith(" "):
103
+ inside = "no synthesis" in line
104
+ elif inside and (found := TOPIC_LINE.match(line)):
105
+ topics.append(found.group(1))
106
+ return topics
107
+
108
+
109
+ def attach_lines(answer: str) -> list[tuple[str, str]]:
110
+ return [(m[1], m[2]) for m in map(ATTACH_LINE.match, answer.splitlines()) if m]
111
+
112
+
113
+ def part_of(note: Path) -> str | None:
114
+ head = re.match(r"---\n(.*?)\n---\n", note.read_text(encoding="utf-8"), re.DOTALL)
115
+ found = re.search(r'^part_of: "?([^"\n]+)"?$', head.group(1), re.MULTILINE) if head else None
116
+ return found.group(1) if found else None
117
+
118
+
119
+ def history_commit(store: Path, env: dict, message: str, log) -> None:
120
+ if not (store / ".git").exists():
121
+ return
122
+ done = sp.mem(store, env, "history", "commit", "-m", message)
123
+ log(
124
+ f"history commit ({message}): exit {done.returncode} {done.stdout.strip()} {done.stderr.strip()}"
125
+ )
126
+
127
+
128
+ def _file_logger(log_file: Path) -> Callable[[str], None]:
129
+ def log(text: str) -> None:
130
+ with log_file.open("a", encoding="utf-8") as f:
131
+ f.write(f"{time.strftime('%H:%M:%S')} {text}\n")
132
+
133
+ return log
134
+
135
+
136
+ def _aligned(lines: list[tuple]) -> str:
137
+ """`lines` as columns padded to the widest cell; the first line is the header."""
138
+ widths = [max(len(str(line[i])) for line in lines) for i in range(len(lines[0]))]
139
+ return "\n".join(
140
+ " ".join(str(c).ljust(w) for c, w in zip(line, widths, strict=True)).rstrip()
141
+ for line in lines
142
+ )
143
+
144
+
145
+ def count_parts(synthesis: Path) -> int:
146
+ return len(re.findall(r"^## (?!Summary$)", synthesis.read_text(encoding="utf-8"), re.MULTILINE))
147
+
148
+
149
+ def say(text: str) -> None:
150
+ print(text, flush=True)