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,407 @@
|
|
|
1
|
+
"""A store that is a git repository: `mem` commits at the end of a curation pass, at session end and by hand
|
|
2
|
+
(plan 2026-11-17-memory-store-git); no other command runs git.
|
|
3
|
+
|
|
4
|
+
A git failure never fails a command: `commit_if_changed` reports one line and returns None.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import datetime
|
|
10
|
+
import fcntl
|
|
11
|
+
import fnmatch
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
import os
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
import tempfile
|
|
18
|
+
import time
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import TYPE_CHECKING, TypedDict, Unpack
|
|
21
|
+
|
|
22
|
+
from memory_cli.core import safe_io
|
|
23
|
+
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
from collections.abc import Callable
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
# Same values as mem.py (_LOCAL_DIRS, MAX_FILE_BYTES); mem.py cannot be imported from here (it imports this module, and `engine/run.py` runs it)
|
|
30
|
+
# and a test keeps both copies equal.
|
|
31
|
+
LOCAL_DIRS = frozenset({
|
|
32
|
+
"__pycache__",
|
|
33
|
+
".venv",
|
|
34
|
+
"target",
|
|
35
|
+
"node_modules",
|
|
36
|
+
".pytest_cache",
|
|
37
|
+
".sources",
|
|
38
|
+
".playwright-mcp",
|
|
39
|
+
})
|
|
40
|
+
MAX_FILE_BYTES = 5 * 1024 * 1024
|
|
41
|
+
SETTLE_FILES = (".settle-log", ".settle-state.json", ".settle-lock")
|
|
42
|
+
IGNORED_FILES = (
|
|
43
|
+
"research/*/data/",
|
|
44
|
+
".*.tmp",
|
|
45
|
+
".curation-log",
|
|
46
|
+
*SETTLE_FILES,
|
|
47
|
+
) # logs: git holds every earlier state already; settle state is per machine
|
|
48
|
+
|
|
49
|
+
TIMEOUT = 10
|
|
50
|
+
LOCK_WAIT = 10
|
|
51
|
+
STALE_LOCK_SECONDS = 600 # mem's own git calls time out at 10 s: a lock this old is left over
|
|
52
|
+
LOCK_NAME = "mem-commit.lock"
|
|
53
|
+
_GIT_FLAGS = [
|
|
54
|
+
"-c",
|
|
55
|
+
"commit.gpgsign=false",
|
|
56
|
+
"-c",
|
|
57
|
+
"core.hooksPath=",
|
|
58
|
+
] # a user's signing or hooks cannot hang a commit
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class GitError(Exception):
|
|
62
|
+
pass
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _env() -> dict[str, str]:
|
|
66
|
+
"""The environment without any GIT_* variable that could redirect the repository, index or work tree."""
|
|
67
|
+
env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
|
|
68
|
+
for keep in (
|
|
69
|
+
"GIT_CONFIG_GLOBAL",
|
|
70
|
+
"GIT_CONFIG_SYSTEM",
|
|
71
|
+
): # the user's config choice, as the plan keeps it
|
|
72
|
+
if keep in os.environ:
|
|
73
|
+
env[keep] = os.environ[keep]
|
|
74
|
+
return env
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _git(store: Path, *args: str) -> str:
|
|
78
|
+
try:
|
|
79
|
+
done = subprocess.run(
|
|
80
|
+
["git", "-C", str(store), *_GIT_FLAGS, *args],
|
|
81
|
+
capture_output=True,
|
|
82
|
+
text=True,
|
|
83
|
+
check=False,
|
|
84
|
+
timeout=TIMEOUT,
|
|
85
|
+
env=_env(),
|
|
86
|
+
)
|
|
87
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
88
|
+
raise GitError(f"git {args[0]}: {exc}") from exc
|
|
89
|
+
if done.returncode != 0:
|
|
90
|
+
detail = (done.stderr or done.stdout).strip().splitlines()
|
|
91
|
+
raise GitError(f"git {args[0]} failed" + (f": {detail[-1]}" if detail else ""))
|
|
92
|
+
return done.stdout
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def is_repo(store: Path) -> bool:
|
|
96
|
+
return (Path(store) / ".git").exists()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _oversized(store: Path) -> list[str]:
|
|
100
|
+
"""Files over MAX_FILE_BYTES outside the ignored folders; they are never staged."""
|
|
101
|
+
found = []
|
|
102
|
+
for dirpath, dirnames, filenames in os.walk(store):
|
|
103
|
+
in_research = Path(dirpath).parent == store / "research"
|
|
104
|
+
dirnames[:] = [
|
|
105
|
+
d
|
|
106
|
+
for d in dirnames
|
|
107
|
+
if d != ".git" and d not in LOCAL_DIRS and not (in_research and d == "data")
|
|
108
|
+
]
|
|
109
|
+
for name in filenames:
|
|
110
|
+
if name == ".curation-log" or fnmatch.fnmatch(name, ".*.tmp"):
|
|
111
|
+
continue # ignored already; git add fails when an exclude pathspec names an ignored file
|
|
112
|
+
path = Path(dirpath) / name
|
|
113
|
+
try:
|
|
114
|
+
if path.lstat().st_size > MAX_FILE_BYTES:
|
|
115
|
+
found.append(path.relative_to(store).as_posix())
|
|
116
|
+
except OSError:
|
|
117
|
+
continue
|
|
118
|
+
return found
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _lock(store: Path):
|
|
122
|
+
fd = os.open(store / ".git" / LOCK_NAME, os.O_RDWR | os.O_CREAT, 0o644)
|
|
123
|
+
deadline = time.monotonic() + LOCK_WAIT
|
|
124
|
+
while True:
|
|
125
|
+
try:
|
|
126
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
127
|
+
return fd
|
|
128
|
+
except BlockingIOError:
|
|
129
|
+
if time.monotonic() >= deadline:
|
|
130
|
+
os.close(fd)
|
|
131
|
+
raise GitError("the commit lock stayed busy for 10 s") from None
|
|
132
|
+
time.sleep(0.05)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _drop_stale_index_lock(store: Path) -> None:
|
|
136
|
+
lock = store / ".git" / "index.lock"
|
|
137
|
+
try:
|
|
138
|
+
if time.time() - lock.stat().st_mtime > STALE_LOCK_SECONDS:
|
|
139
|
+
lock.unlink()
|
|
140
|
+
except OSError:
|
|
141
|
+
pass
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
HELD_NAME = "mem-held-back"
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def held_back(store: Path) -> list[str]:
|
|
148
|
+
"""The paths the last commit held back because they fail `mem check`; empty when none or no repository."""
|
|
149
|
+
try:
|
|
150
|
+
text = (Path(store) / ".git" / HELD_NAME).read_text(encoding="utf-8")
|
|
151
|
+
except (OSError, UnicodeDecodeError):
|
|
152
|
+
return []
|
|
153
|
+
return [ln for ln in text.split("\n") if ln]
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _replace_held(path: Path, held: list[str]) -> None:
|
|
157
|
+
if not held:
|
|
158
|
+
path.unlink(missing_ok=True)
|
|
159
|
+
return
|
|
160
|
+
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=HELD_NAME + ".")
|
|
161
|
+
try:
|
|
162
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
163
|
+
handle.write("".join(f"{p}\n" for p in held))
|
|
164
|
+
os.replace(tmp, path)
|
|
165
|
+
except OSError:
|
|
166
|
+
Path(tmp).unlink(missing_ok=True)
|
|
167
|
+
raise
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _write_held(store: Path, held: list[str]) -> None:
|
|
171
|
+
"""Replace the list in one step: a reader sees the old list or the new one, never half of one."""
|
|
172
|
+
try:
|
|
173
|
+
_replace_held(store / ".git" / HELD_NAME, held)
|
|
174
|
+
except OSError as exc:
|
|
175
|
+
raise GitError(f"held-back list: {exc}") from exc
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _staged_paths(store: Path) -> list[str]:
|
|
179
|
+
out = _git(store, "diff", "--cached", "--name-only", "-z", "--diff-filter=d")
|
|
180
|
+
return [p for p in out.split("\0") if p]
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _rename_sources(store: Path, held: list[str]) -> list[str]:
|
|
184
|
+
"""The old paths of the staged renames whose new path is held: resetting only the new side would commit the deletion.
|
|
185
|
+
|
|
186
|
+
Only renames git detects by similarity are paired; a rename whose text changed almost entirely stages as an
|
|
187
|
+
unrelated deletion and addition, so the deletion is committed (the old text stays in earlier commits)."""
|
|
188
|
+
fields = _git(store, "diff", "--cached", "-M", "--name-status", "-z").split("\0")
|
|
189
|
+
sources, i = [], 0
|
|
190
|
+
while i < len(fields) and fields[i]:
|
|
191
|
+
status = fields[i]
|
|
192
|
+
width = 3 if status[0] in "RC" else 2
|
|
193
|
+
if status[0] == "R" and fields[i + 2] in held:
|
|
194
|
+
sources.append(fields[i + 1])
|
|
195
|
+
i += width
|
|
196
|
+
return sources
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _hold_back(
|
|
200
|
+
store: Path, validate: Callable[[list[str]], list[str]], warn: Callable[[str], None]
|
|
201
|
+
) -> list[str]:
|
|
202
|
+
"""Unstage the changed files that fail `validate` (returned) and, silently, any that a writer changed while it ran."""
|
|
203
|
+
paths = _staged_paths(store)
|
|
204
|
+
if not paths:
|
|
205
|
+
return []
|
|
206
|
+
try:
|
|
207
|
+
bad = list(validate(paths))
|
|
208
|
+
except (
|
|
209
|
+
Exception
|
|
210
|
+
) as exc: # a broken validator must not stop history: commit everything and say so
|
|
211
|
+
logger.debug("validator raised", exc_info=True)
|
|
212
|
+
warn(f"check failed, nothing held back: {exc}")
|
|
213
|
+
return []
|
|
214
|
+
# writers do not take the commit lock: a file that differs from the index now changed after it was staged
|
|
215
|
+
changed = _git(store, "diff", "--name-only", "-z", "--", *paths).split("\0")
|
|
216
|
+
held = sorted(set(bad) | {p for p in changed if p})
|
|
217
|
+
if held:
|
|
218
|
+
_git(store, "reset", "-q", "--", *held, *_rename_sources(store, held))
|
|
219
|
+
return sorted(set(bad))
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _stage(
|
|
223
|
+
store: Path,
|
|
224
|
+
validate: Callable[[list[str]], list[str]] | None,
|
|
225
|
+
warn: Callable[[str], None],
|
|
226
|
+
on_held: Callable[[list[str]], None],
|
|
227
|
+
) -> None:
|
|
228
|
+
_drop_stale_index_lock(store)
|
|
229
|
+
_git(store, "add", "-A", "--", ".", *(f":(exclude,literal){rel}" for rel in _oversized(store)))
|
|
230
|
+
if validate is None:
|
|
231
|
+
return
|
|
232
|
+
held = _hold_back(store, validate, warn)
|
|
233
|
+
on_held(held)
|
|
234
|
+
try: # only after the gate ran, so a reader never sees a list this run has not decided yet
|
|
235
|
+
_write_held(store, held)
|
|
236
|
+
except GitError as exc: # the list is a convenience: the commit must not be lost for it
|
|
237
|
+
warn(str(exc))
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _commit_staged(store: Path, message: str | Callable[[int], str]) -> str | None:
|
|
241
|
+
staged = subprocess.run(
|
|
242
|
+
["git", "-C", str(store), *_GIT_FLAGS, "diff", "--cached", "--quiet"],
|
|
243
|
+
capture_output=True,
|
|
244
|
+
text=True,
|
|
245
|
+
check=False,
|
|
246
|
+
timeout=TIMEOUT,
|
|
247
|
+
env=_env(),
|
|
248
|
+
)
|
|
249
|
+
if staged.returncode == 0:
|
|
250
|
+
return None
|
|
251
|
+
if staged.returncode != 1:
|
|
252
|
+
raise GitError("git diff failed: " + (staged.stderr.strip() or f"exit {staged.returncode}"))
|
|
253
|
+
if callable(message):
|
|
254
|
+
message = message(len(_git(store, "diff", "--cached", "--name-only").splitlines()))
|
|
255
|
+
_git(store, "commit", "-q", "-m", message)
|
|
256
|
+
return _git(store, "rev-parse", "--short", "HEAD").strip()
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _commit(
|
|
260
|
+
store: Path,
|
|
261
|
+
message: str | Callable[[int], str],
|
|
262
|
+
validate: Callable[[list[str]], list[str]] | None = None,
|
|
263
|
+
warn: Callable[[str], None] = lambda reason: None,
|
|
264
|
+
on_held: Callable[[list[str]], None] = lambda held: None,
|
|
265
|
+
) -> str | None:
|
|
266
|
+
try:
|
|
267
|
+
fd = _lock(store)
|
|
268
|
+
except (OSError, GitError) as exc:
|
|
269
|
+
raise (exc if isinstance(exc, GitError) else GitError(f"lock: {exc}")) from None
|
|
270
|
+
try:
|
|
271
|
+
_stage(store, validate, warn, on_held)
|
|
272
|
+
return _commit_staged(store, message)
|
|
273
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
274
|
+
raise GitError(str(exc)) from exc
|
|
275
|
+
finally:
|
|
276
|
+
os.close(fd) # closing releases the flock
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _print_reason(reason: str) -> None:
|
|
280
|
+
print(f"mem: history: {reason}", file=sys.stderr)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
class _CommitOptions(TypedDict, total=False):
|
|
284
|
+
report: Callable[[str], None]
|
|
285
|
+
warn: Callable[[str], None]
|
|
286
|
+
validate: Callable[[list[str]], list[str]] | None
|
|
287
|
+
on_held: Callable[[list[str]], None]
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def commit_if_changed(
|
|
291
|
+
store: Path, message: str | Callable[[int], str], **options: Unpack[_CommitOptions]
|
|
292
|
+
) -> str | None:
|
|
293
|
+
"""Stage everything and commit (keyword options: `report`, `warn`, `validate`, `on_held`); the short commit id, or None when nothing changed or git failed (reported).
|
|
294
|
+
|
|
295
|
+
`message` may be a function of the number of files the commit holds. `validate` gets the changed paths (deletions
|
|
296
|
+
excluded) and returns those to hold back: they stay in the working tree, listed by `held_back`. When it raises,
|
|
297
|
+
everything is committed and `warn` says so (it is not a git failure). `on_held` gets the paths this run held back
|
|
298
|
+
for failing `validate` (not those a writer changed meanwhile), once the gate has run."""
|
|
299
|
+
try:
|
|
300
|
+
return _commit(
|
|
301
|
+
Path(store),
|
|
302
|
+
message,
|
|
303
|
+
options.get("validate"),
|
|
304
|
+
options.get("warn", _print_reason),
|
|
305
|
+
options.get("on_held", lambda held: None),
|
|
306
|
+
)
|
|
307
|
+
except GitError as exc:
|
|
308
|
+
options.get("report", _print_reason)(str(exc))
|
|
309
|
+
return None
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _ignore_lines(store: Path, lines: list[str]) -> None:
|
|
313
|
+
ignore = store / ".gitignore"
|
|
314
|
+
have = ignore.read_text(encoding="utf-8").splitlines() if ignore.exists() else []
|
|
315
|
+
missing = [ln for ln in lines if ln not in have]
|
|
316
|
+
if missing or not ignore.exists():
|
|
317
|
+
prefix = "\n" if have and not ignore.read_text(encoding="utf-8").endswith("\n") else ""
|
|
318
|
+
safe_io.append_text(ignore, prefix + "".join(ln + "\n" for ln in missing))
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def ensure_ignored(store: Path) -> None:
|
|
322
|
+
"""Add the settle files to the .gitignore of a store that is a repository already (`init` writes them for new ones)."""
|
|
323
|
+
if is_repo(store):
|
|
324
|
+
_ignore_lines(Path(store), list(SETTLE_FILES))
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def init(store: Path) -> str | None:
|
|
328
|
+
"""Make the store a repository: local identity, .gitignore, a first commit of everything present."""
|
|
329
|
+
store = Path(store)
|
|
330
|
+
_git(store, "init", "-q")
|
|
331
|
+
_git(store, "config", "user.name", "mem")
|
|
332
|
+
_git(store, "config", "user.email", "mem@localhost")
|
|
333
|
+
_ignore_lines(store, [f"{name}/" for name in sorted(LOCAL_DIRS)] + list(IGNORED_FILES))
|
|
334
|
+
return _commit(store, "mem history init")
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def log(store: Path, count: int) -> list[str]:
|
|
338
|
+
"""The last `count` commits, one line each: `<id> <date> <message>`."""
|
|
339
|
+
out = _git(Path(store), "log", f"-n{max(count, 1)}", "--date=short", "--format=%h %ad %s")
|
|
340
|
+
return out.splitlines()
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
TRIM_DAYS = 30
|
|
344
|
+
_LOG_FOLDERS = (
|
|
345
|
+
"",
|
|
346
|
+
"syntheses",
|
|
347
|
+
"memories",
|
|
348
|
+
) # the store's own curation logs; a project's .memory/ is never one of them
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _entry_time(line: str) -> datetime.datetime | None:
|
|
352
|
+
try:
|
|
353
|
+
if not line.strip():
|
|
354
|
+
return None
|
|
355
|
+
entry = json.loads(line)
|
|
356
|
+
return datetime.datetime.strptime(entry["t"], "%Y-%m-%dT%H:%M:%SZ").replace(
|
|
357
|
+
tzinfo=datetime.UTC
|
|
358
|
+
)
|
|
359
|
+
except (ValueError, TypeError, KeyError):
|
|
360
|
+
return None # unreadable or undated lines stay
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _blank_old(lines: list[str], cutoff: datetime.datetime) -> int:
|
|
364
|
+
changed = 0
|
|
365
|
+
for number, line in enumerate(lines):
|
|
366
|
+
when = _entry_time(line)
|
|
367
|
+
if when is not None and when < cutoff:
|
|
368
|
+
lines[number] = ""
|
|
369
|
+
changed += 1
|
|
370
|
+
return changed
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def trim_logs(store: Path, now: datetime.datetime | None = None) -> int:
|
|
374
|
+
"""Blank the `.curation-log` entries older than TRIM_DAYS; the number of entries removed.
|
|
375
|
+
|
|
376
|
+
A removed entry becomes an empty line, not a missing one: `mem restore` marks an undone entry by its line number.
|
|
377
|
+
Call it only for a store whose git history is intact."""
|
|
378
|
+
now = now or datetime.datetime.now(datetime.UTC)
|
|
379
|
+
cutoff = now - datetime.timedelta(days=TRIM_DAYS)
|
|
380
|
+
removed = 0
|
|
381
|
+
for folder in _LOG_FOLDERS:
|
|
382
|
+
path = Path(store) / folder / ".curation-log"
|
|
383
|
+
try:
|
|
384
|
+
lines = path.read_text(encoding="utf-8").split("\n")
|
|
385
|
+
except (OSError, UnicodeDecodeError):
|
|
386
|
+
continue
|
|
387
|
+
changed = _blank_old(lines, cutoff)
|
|
388
|
+
if not changed:
|
|
389
|
+
continue
|
|
390
|
+
try:
|
|
391
|
+
safe_io.replace_file(path, "\n".join(lines).encode("utf-8"))
|
|
392
|
+
except OSError:
|
|
393
|
+
continue
|
|
394
|
+
removed += changed
|
|
395
|
+
return removed
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def trim_logs_locked(store: Path) -> int:
|
|
399
|
+
"""`trim_logs` under the commit lock; 0 when the lock stays busy (the next pass trims)."""
|
|
400
|
+
try:
|
|
401
|
+
fd = _lock(Path(store))
|
|
402
|
+
except (OSError, GitError):
|
|
403
|
+
return 0
|
|
404
|
+
try:
|
|
405
|
+
return trim_logs(store)
|
|
406
|
+
finally:
|
|
407
|
+
os.close(fd)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""The YAML parser the engine uses and the plain `safe_load` built on it. Imports only the standard library and PyYAML."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import yaml
|
|
6
|
+
|
|
7
|
+
# The C parser is several times faster; searching reads every note. libyaml accepts a tab after a colon
|
|
8
|
+
# (`a:\tb`) and words parse errors differently. This is the one place that picks it.
|
|
9
|
+
BaseLoader: type[yaml.SafeLoader] = getattr(yaml, "CSafeLoader", yaml.SafeLoader)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def safe_load(text: str):
|
|
13
|
+
"""Plain SafeLoader values (dates stay dates) from the same C parser; HubLoader's rules do not apply."""
|
|
14
|
+
return yaml.load(text, Loader=BaseLoader)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""The corroboration pass: matches lessons by meaning and keeps one general record of each (`bin/mem-corroborate`).
|
|
2
|
+
|
|
3
|
+
`cli`: commands that need the whole engine, self-check
|
|
4
|
+
`decide`: what the pass reads and does with the groups a model returns; pure
|
|
5
|
+
`digest`: heading per topic and line per lesson for session start
|
|
6
|
+
`job`: shared background-job result and table formatting
|
|
7
|
+
`fill`: short form and topic of lessons that lack them
|
|
8
|
+
`reword`: new short form for loaded lessons that got worse
|
|
9
|
+
`run`: model sessions, briefs, applier, `execute` (one run)
|
|
10
|
+
`state`: state folder, journal and undo, commands needing nothing else
|
|
11
|
+
"""
|