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.
- memory_cli/__init__.py +1 -0
- memory_cli/__main__.py +49 -0
- memory_cli/capture/__init__.py +7 -0
- memory_cli/capture/codex_rollout.py +164 -0
- memory_cli/capture/event_lines.py +66 -0
- memory_cli/capture/extract.py +458 -0
- memory_cli/capture/state.py +183 -0
- memory_cli/commands/__init__.py +21 -0
- memory_cli/commands/admin.py +363 -0
- memory_cli/commands/common.py +609 -0
- memory_cli/commands/curate.py +1189 -0
- memory_cli/commands/diagnostics.py +126 -0
- memory_cli/commands/edit.py +1282 -0
- memory_cli/commands/hooks.py +730 -0
- memory_cli/commands/import_recovery.py +45 -0
- memory_cli/commands/install.py +152 -0
- memory_cli/commands/integrate.py +480 -0
- memory_cli/commands/memory.py +2152 -0
- memory_cli/commands/read.py +1290 -0
- memory_cli/commands/sources.py +766 -0
- memory_cli/commands/split.py +97 -0
- memory_cli/commands/split_plan.py +196 -0
- memory_cli/commands/split_transaction.py +230 -0
- memory_cli/commands/synthesis.py +1122 -0
- memory_cli/core/__init__.py +16 -0
- memory_cli/core/auto_state.py +30 -0
- memory_cli/core/codex_pass.py +109 -0
- memory_cli/core/config.py +87 -0
- memory_cli/core/file_journal.py +163 -0
- memory_cli/core/headless.py +130 -0
- memory_cli/core/jobs.py +130 -0
- memory_cli/core/resources.py +57 -0
- memory_cli/core/runner.py +398 -0
- memory_cli/core/safe_io.py +155 -0
- memory_cli/core/store_git.py +407 -0
- memory_cli/core/yaml_load.py +14 -0
- memory_cli/corroborate/__init__.py +11 -0
- memory_cli/corroborate/cli.py +267 -0
- memory_cli/corroborate/decide.py +893 -0
- memory_cli/corroborate/digest.py +425 -0
- memory_cli/corroborate/fill.py +744 -0
- memory_cli/corroborate/job.py +15 -0
- memory_cli/corroborate/reword.py +446 -0
- memory_cli/corroborate/run.py +1142 -0
- memory_cli/corroborate/state.py +300 -0
- memory_cli/digest/__init__.py +4 -0
- memory_cli/digest/lessons.py +483 -0
- memory_cli/entry/__init__.py +12 -0
- memory_cli/entry/auto.py +660 -0
- memory_cli/entry/capture.py +1403 -0
- memory_cli/entry/corroborate.py +214 -0
- memory_cli/entry/integrate.py +684 -0
- memory_cli/entry/integrate_self_check.py +203 -0
- memory_cli/entry/research.py +9 -0
- memory_cli/entry/settle.py +614 -0
- memory_cli/entry/split_auto.py +460 -0
- memory_cli/entry/synthesize.py +22 -0
- memory_cli/integrate/__init__.py +9 -0
- memory_cli/integrate/answers.py +42 -0
- memory_cli/integrate/briefs/check-brief.md +16 -0
- memory_cli/integrate/briefs/place-brief.md +26 -0
- memory_cli/integrate/log.py +43 -0
- memory_cli/integrate/plan.py +125 -0
- memory_cli/integrate/rows.py +99 -0
- memory_cli/integrate/state.py +158 -0
- memory_cli/integrate/undo.py +143 -0
- memory_cli/mem.py +1180 -0
- memory_cli/memories/__init__.py +16 -0
- memory_cli/memories/fingerprints.py +51 -0
- memory_cli/memories/journal.py +93 -0
- memory_cli/memories/locations.py +282 -0
- memory_cli/memories/matching.py +451 -0
- memory_cli/memories/model.py +205 -0
- memory_cli/memories/parse.py +237 -0
- memory_cli/memories/records.py +266 -0
- memory_cli/memories/rules.py +291 -0
- memory_cli/memories/sightings.py +314 -0
- memory_cli/memories/terms.py +148 -0
- memory_cli/memories/write.py +358 -0
- memory_cli/notes/__init__.py +13 -0
- memory_cli/notes/check.py +806 -0
- memory_cli/notes/due.py +260 -0
- memory_cli/notes/fields.py +217 -0
- memory_cli/notes/index.py +230 -0
- memory_cli/notes/links.py +170 -0
- memory_cli/notes/note.py +222 -0
- memory_cli/notes/search.py +391 -0
- memory_cli/notes/split_candidates.py +72 -0
- memory_cli/research/__init__.py +5 -0
- memory_cli/research/checks.py +1065 -0
- memory_cli/research/pipeline.py +952 -0
- memory_cli/session/__init__.py +5 -0
- memory_cli/session/handoff.py +139 -0
- memory_cli/session/notices.py +111 -0
- memory_cli/settle/__init__.py +5 -0
- memory_cli/settle/state.py +111 -0
- memory_cli/settle/verdicts.py +693 -0
- memory_cli/split/briefs/checker-brief.md +5 -0
- memory_cli/split/briefs/editor-brief.md +20 -0
- memory_cli/syntheses/__init__.py +8 -0
- memory_cli/syntheses/document.py +400 -0
- memory_cli/syntheses/edit.py +581 -0
- memory_cli/syntheses/project.py +384 -0
- memory_cli/syntheses/split_conservation.py +50 -0
- memory_cli/syntheses/units.py +427 -0
- memory_cli/synthesize/__init__.py +9 -0
- memory_cli/synthesize/backfill.py +431 -0
- memory_cli/synthesize/briefs/backfill-brief.md +26 -0
- memory_cli/synthesize/briefs/checker-brief.md +13 -0
- memory_cli/synthesize/briefs/fixer-brief.md +19 -0
- memory_cli/synthesize/briefs/memory-brief.md +30 -0
- memory_cli/synthesize/briefs/settle-brief.md +32 -0
- memory_cli/synthesize/briefs/verdict-brief.md +50 -0
- memory_cli/synthesize/briefs/web-brief.md +33 -0
- memory_cli/synthesize/cli.py +311 -0
- memory_cli/synthesize/pipeline.py +764 -0
- memory_cli/synthesize/references.py +164 -0
- memory_cli/synthesize/run.py +150 -0
- memory_cli/synthesize/topics.py +528 -0
- memory_cli/templates/knowledge.md +23 -0
- memory_cli/templates/literature.md +25 -0
- memory_cli/templates/research.md +23 -0
- memory_cli/templates/synthesis.md +6 -0
- memory_cli-0.1.0.dist-info/METADATA +102 -0
- memory_cli-0.1.0.dist-info/RECORD +128 -0
- memory_cli-0.1.0.dist-info/WHEEL +4 -0
- memory_cli-0.1.0.dist-info/entry_points.txt +9 -0
- memory_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
"""mem-corroborate: the state folder, the journal and undo, and the commands that need nothing else (stdlib, `jobs`, `safe_io`; no yaml)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from memory_cli.core import jobs, safe_io
|
|
15
|
+
|
|
16
|
+
DEFAULT_BUDGET = 0.25 # USD per session
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
STAMP_RE = re.compile(r"[A-Za-z0-9._-]+")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
# `CURATION_LOG`, repeated so this module needs no yaml: `auto` and `undo` must work when the engine cannot load
|
|
23
|
+
CURATION_LOG = ".curation-log"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
data_dir = jobs.state_dir
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def corroborate_dir(data: Path) -> Path:
|
|
30
|
+
return Path(data) / "corroborate"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def budget_of(value) -> float:
|
|
34
|
+
try:
|
|
35
|
+
number = float(value)
|
|
36
|
+
except (TypeError, ValueError):
|
|
37
|
+
return DEFAULT_BUDGET
|
|
38
|
+
return number if math.isfinite(number) and number > 0 else DEFAULT_BUDGET
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def save_status(cdir: Path, **changes) -> dict:
|
|
42
|
+
jobs.private_dir(cdir)
|
|
43
|
+
data = {**jobs.read_json(cdir / jobs.STATUS_NAME), **changes}
|
|
44
|
+
for key in [k for k, v in data.items() if k == "failure" and v is None]:
|
|
45
|
+
del data[key]
|
|
46
|
+
jobs.write_json(cdir / jobs.STATUS_NAME, data)
|
|
47
|
+
return data
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
append_log = jobs.append_log
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def write_private(path: Path, text: str) -> None:
|
|
54
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
|
55
|
+
with os.fdopen(fd, "w", encoding="utf-8", errors="replace") as f:
|
|
56
|
+
os.fchmod(f.fileno(), 0o600)
|
|
57
|
+
f.write(text)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def digest(data: bytes | None) -> str | None:
|
|
61
|
+
return hashlib.sha256(data).hexdigest() if data is not None else None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def read_bytes(path: Path) -> bytes | None:
|
|
65
|
+
try:
|
|
66
|
+
return path.read_bytes()
|
|
67
|
+
except OSError:
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
FILL_NEWS = (
|
|
72
|
+
"written",
|
|
73
|
+
"refused_code",
|
|
74
|
+
"refused_check",
|
|
75
|
+
"to_triage",
|
|
76
|
+
"stopped",
|
|
77
|
+
) # the counts `status` reports
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class Journal:
|
|
81
|
+
"""The undo record of one run: `commit` after an action compares each watched file with its text before."""
|
|
82
|
+
|
|
83
|
+
def __init__(self, run: Path):
|
|
84
|
+
self.run = run
|
|
85
|
+
self.seen: dict[str, bool] = {} # file -> created by this run
|
|
86
|
+
|
|
87
|
+
@staticmethod
|
|
88
|
+
def before_name(path: Path) -> str:
|
|
89
|
+
return hashlib.sha1(str(path).encode()).hexdigest()[:16]
|
|
90
|
+
|
|
91
|
+
@staticmethod
|
|
92
|
+
def watch(paths) -> dict[Path, bytes | None]:
|
|
93
|
+
"""The files and the curation log beside each (an action may log the text it replaces)."""
|
|
94
|
+
out = {Path(p): read_bytes(Path(p)) for p in paths}
|
|
95
|
+
for p in list(out):
|
|
96
|
+
log = p.parent / CURATION_LOG
|
|
97
|
+
out.setdefault(log, read_bytes(log))
|
|
98
|
+
return out
|
|
99
|
+
|
|
100
|
+
def watch_folder(self, folder: Path) -> dict[Path, bytes | None]:
|
|
101
|
+
found = self.watch(sorted(folder.glob("*.md"))) if folder.is_dir() else {}
|
|
102
|
+
log = folder / CURATION_LOG
|
|
103
|
+
found.setdefault(log, read_bytes(log))
|
|
104
|
+
return found
|
|
105
|
+
|
|
106
|
+
def commit(
|
|
107
|
+
self, action: str, before: dict[Path, bytes | None], folder: Path | None = None
|
|
108
|
+
) -> None:
|
|
109
|
+
"""Journal every watched file that changed; with `folder`, files that appeared in it count as created."""
|
|
110
|
+
paths = dict(before)
|
|
111
|
+
if folder is not None and folder.is_dir():
|
|
112
|
+
for p in folder.glob("*.md"):
|
|
113
|
+
paths.setdefault(p, None)
|
|
114
|
+
for path, old in paths.items():
|
|
115
|
+
now = read_bytes(path)
|
|
116
|
+
if now != old:
|
|
117
|
+
self._record(action, path, old, now)
|
|
118
|
+
|
|
119
|
+
def _record(self, action: str, path: Path, old: bytes | None, now: bytes | None) -> None:
|
|
120
|
+
"""Journal one changed file; the first change to it also saves its text before the run."""
|
|
121
|
+
key = str(path)
|
|
122
|
+
if key not in self.seen:
|
|
123
|
+
self.seen[key] = old is None
|
|
124
|
+
if old is not None:
|
|
125
|
+
folder_b = self.run / "before"
|
|
126
|
+
jobs.private_dir(folder_b)
|
|
127
|
+
write_private_bytes(folder_b / self.before_name(path), old)
|
|
128
|
+
row = {"action": action, "file": key, "created": self.seen[key], "hash": digest(now)}
|
|
129
|
+
fd = os.open(self.run / "journal.jsonl", os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
|
|
130
|
+
with os.fdopen(fd, "a", encoding="utf-8") as f:
|
|
131
|
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def write_private_bytes(path: Path, data: bytes) -> None:
|
|
135
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
|
136
|
+
with os.fdopen(fd, "wb") as f:
|
|
137
|
+
os.fchmod(f.fileno(), 0o600)
|
|
138
|
+
f.write(data)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class UndoRefusedError(Exception):
|
|
142
|
+
"""An undo that must change nothing; the message says why."""
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _journal_rows(run: Path) -> dict[str, dict]:
|
|
146
|
+
"""The last journal row of each file the run changed."""
|
|
147
|
+
journal = run / "journal.jsonl"
|
|
148
|
+
if not journal.is_file():
|
|
149
|
+
raise UndoRefusedError("this run has no journal: nothing to undo")
|
|
150
|
+
last: dict[str, dict] = {}
|
|
151
|
+
for text in journal.read_text(encoding="utf-8").splitlines():
|
|
152
|
+
try:
|
|
153
|
+
row = json.loads(text)
|
|
154
|
+
except ValueError:
|
|
155
|
+
raise UndoRefusedError("the journal cannot be read: nothing was changed") from None
|
|
156
|
+
if isinstance(row, dict) and isinstance(row.get("file"), str):
|
|
157
|
+
last[row["file"]] = row
|
|
158
|
+
return last
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _to_restore(run: Path, file: str, row: dict) -> tuple[Path, bytes | None] | None:
|
|
162
|
+
"""What to put back at `file` (None means remove it), or None when it is restored already."""
|
|
163
|
+
path, now = Path(file), read_bytes(Path(file))
|
|
164
|
+
if row.get("created"):
|
|
165
|
+
saved = None
|
|
166
|
+
if now is None:
|
|
167
|
+
return None
|
|
168
|
+
else:
|
|
169
|
+
saved = read_bytes(run / "before" / Journal.before_name(path))
|
|
170
|
+
if saved is None:
|
|
171
|
+
raise UndoRefusedError(f"the saved copy of {file} is missing: nothing was changed")
|
|
172
|
+
if now == saved:
|
|
173
|
+
return None
|
|
174
|
+
if digest(now) != row.get("hash"):
|
|
175
|
+
raise UndoRefusedError(
|
|
176
|
+
f"{file} changed since the run: nothing was changed. Undo the later change first "
|
|
177
|
+
"(mem restore for a memory), or leave the pass applied"
|
|
178
|
+
)
|
|
179
|
+
return path, saved
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _restore(todo: list[tuple[Path, bytes | None]]) -> str | None:
|
|
183
|
+
"""Put the files back; the message of the first failure, None when all are restored."""
|
|
184
|
+
for path, saved in todo:
|
|
185
|
+
try:
|
|
186
|
+
if saved is None:
|
|
187
|
+
path.unlink(missing_ok=True)
|
|
188
|
+
else:
|
|
189
|
+
safe_io.replace_file(path, saved, mode=0o600)
|
|
190
|
+
except OSError as exc:
|
|
191
|
+
return f"cannot restore {path}: {exc.strerror or type(exc).__name__}; run undo again to finish"
|
|
192
|
+
return None
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def undo_run(run: Path) -> tuple[bool, str]:
|
|
196
|
+
"""(done, message). Changes nothing unless every journaled file that is not restored yet still holds what the run
|
|
197
|
+
left in it; a file already equal to its saved copy (or a created one already gone) counts as restored, so an
|
|
198
|
+
interrupted undo can be run again."""
|
|
199
|
+
if (run / "undone").exists():
|
|
200
|
+
return True, f"run {run.name} was already undone"
|
|
201
|
+
try:
|
|
202
|
+
todo = [
|
|
203
|
+
step
|
|
204
|
+
for file, row in _journal_rows(run).items()
|
|
205
|
+
if (step := _to_restore(run, file, row))
|
|
206
|
+
]
|
|
207
|
+
except UndoRefusedError as exc:
|
|
208
|
+
return False, str(exc)
|
|
209
|
+
failure = _restore(todo)
|
|
210
|
+
if failure:
|
|
211
|
+
return False, failure
|
|
212
|
+
write_private(run / "undone", "")
|
|
213
|
+
return True, f"undone: {len(todo)} files"
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def forget_run(cdir: Path, run: Path) -> None:
|
|
217
|
+
"""After an undo: the next run does the work again, so drop the saved fingerprint and the marks this run added."""
|
|
218
|
+
seen = jobs.read_json(cdir / "seen.json")
|
|
219
|
+
if not seen:
|
|
220
|
+
return
|
|
221
|
+
added = jobs.read_json(run / "seen-added.json").get("marked")
|
|
222
|
+
marks = seen.get("refused")
|
|
223
|
+
seen.pop("fingerprint", None)
|
|
224
|
+
seen.pop("retry", None)
|
|
225
|
+
if isinstance(marks, dict) and isinstance(added, list):
|
|
226
|
+
seen["refused"] = {k: v for k, v in marks.items() if k not in added}
|
|
227
|
+
jobs.write_json(cdir / "seen.json", seen)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def cmd_undo(args) -> int:
|
|
231
|
+
if not STAMP_RE.fullmatch(args.stamp) or args.stamp in {".", ".."}:
|
|
232
|
+
print("mem-corroborate: not a run stamp", file=sys.stderr)
|
|
233
|
+
return 2
|
|
234
|
+
cdir = corroborate_dir(data_dir())
|
|
235
|
+
run = cdir / "runs" / args.stamp
|
|
236
|
+
if not run.is_dir():
|
|
237
|
+
print(f"mem-corroborate: no run {args.stamp}", file=sys.stderr)
|
|
238
|
+
return 2
|
|
239
|
+
lock = jobs.take_run_lock(cdir)
|
|
240
|
+
if lock is None:
|
|
241
|
+
print("mem-corroborate: a run is going: try again later", file=sys.stderr)
|
|
242
|
+
return 1
|
|
243
|
+
try:
|
|
244
|
+
if (run / "undone").exists():
|
|
245
|
+
done, message = True, f"run {args.stamp} was already undone"
|
|
246
|
+
else:
|
|
247
|
+
done, message = undo_run(run)
|
|
248
|
+
if (
|
|
249
|
+
done and not (run / "fill").exists()
|
|
250
|
+
): # a fill run never touched the pass's `seen.json`
|
|
251
|
+
forget_run(cdir, run)
|
|
252
|
+
finally:
|
|
253
|
+
os.close(lock)
|
|
254
|
+
print(f"mem-corroborate: {message}", file=sys.stdout if done else sys.stderr)
|
|
255
|
+
return 0 if done else 1
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def cmd_status() -> int:
|
|
259
|
+
data = jobs.read_json(corroborate_dir(data_dir()) / jobs.STATUS_NAME)
|
|
260
|
+
if not data:
|
|
261
|
+
print("no corroboration run yet")
|
|
262
|
+
return 0
|
|
263
|
+
shown = data.get("state", "?")
|
|
264
|
+
started = data.get("started")
|
|
265
|
+
if (
|
|
266
|
+
shown == "running"
|
|
267
|
+
and isinstance(started, (int, float))
|
|
268
|
+
and time.time() - started > jobs.STALE_RUNNING_SECONDS
|
|
269
|
+
):
|
|
270
|
+
shown = "failed (a run that did not finish)"
|
|
271
|
+
print(f"last run: state {shown}, cost {float(data.get('cost') or 0):.3f} USD")
|
|
272
|
+
failure = jobs.failure(data, time.time())
|
|
273
|
+
if failure:
|
|
274
|
+
print(f"unacknowledged failure: {failure.get('reason')} (mem-corroborate ack clears it)")
|
|
275
|
+
fill = data.get("fill")
|
|
276
|
+
if isinstance(fill, dict) and any(fill.get(k) for k in FILL_NEWS):
|
|
277
|
+
refused = (fill.get("refused_code") or 0) + (fill.get("refused_check") or 0)
|
|
278
|
+
stopped = f", stopped: {fill['stopped']}" if fill.get("stopped") else ""
|
|
279
|
+
print(
|
|
280
|
+
f"last fill: {fill.get('written') or 0} written, {refused} refused, {fill.get('to_triage') or 0} to triage{stopped}"
|
|
281
|
+
)
|
|
282
|
+
print(f"log: {data.get('log') or '(none)'}")
|
|
283
|
+
return 0
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def cmd_ack() -> int:
|
|
287
|
+
cdir = corroborate_dir(data_dir())
|
|
288
|
+
current = jobs.read_json(cdir / jobs.STATUS_NAME)
|
|
289
|
+
if current:
|
|
290
|
+
changes: dict = {"failure": None}
|
|
291
|
+
started = current.get("started")
|
|
292
|
+
if (
|
|
293
|
+
current.get("state") == "running"
|
|
294
|
+
and isinstance(started, (int, float))
|
|
295
|
+
and time.time() - started > jobs.STALE_RUNNING_SECONDS
|
|
296
|
+
):
|
|
297
|
+
changes["state"] = "failed"
|
|
298
|
+
save_status(cdir, **changes)
|
|
299
|
+
print("acknowledged: the failure line is cleared")
|
|
300
|
+
return 0
|