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,609 @@
|
|
|
1
|
+
"""Helpers shared by the `mem` command handlers and the dispatch (A5, ADR 0028): store resolution, the usage and hook logs, note resolution, the secret and term checks, read-only guards, field and file swaps, history commit points and the project-synthesis context."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import datetime
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import sys
|
|
13
|
+
import uuid
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import TYPE_CHECKING, Any
|
|
16
|
+
|
|
17
|
+
import yaml
|
|
18
|
+
|
|
19
|
+
from memory_cli.core import config, jobs, resources, safe_io, store_git
|
|
20
|
+
from memory_cli.digest import lessons as digest_lessons
|
|
21
|
+
from memory_cli.memories import records
|
|
22
|
+
from memory_cli.notes import check as check_rules
|
|
23
|
+
from memory_cli.notes import note as note_files
|
|
24
|
+
from memory_cli.syntheses import document
|
|
25
|
+
from memory_cli.syntheses import project as project_syntheses
|
|
26
|
+
|
|
27
|
+
if TYPE_CHECKING:
|
|
28
|
+
import argparse
|
|
29
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class UsageError(Exception):
|
|
36
|
+
"""The options of a command contradict each other: the dispatch prints the message as the parser's error (exit 2)."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _env_value(env: Mapping[str, str], key: str) -> str:
|
|
40
|
+
return env.get(key) or ""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
NO_STORE = (
|
|
44
|
+
'mem: no store is set. Run "mem init" to create the default store, or set the plugin\'s "store" option, '
|
|
45
|
+
"or pass --root <folder>, or set MEM_STORE."
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def no_store_message(env: Mapping[str, str]) -> str:
|
|
50
|
+
"""NO_STORE, plus a line when the default folder exists without its marker (it is not used, and why)."""
|
|
51
|
+
folder = config.default_store_path(env)
|
|
52
|
+
if folder is None or not folder.is_dir() or (folder / config.STORE_MARKER).is_file():
|
|
53
|
+
return NO_STORE
|
|
54
|
+
return (
|
|
55
|
+
f"{NO_STORE}\nmem: {folder} has no {config.STORE_MARKER}, so it is not used; "
|
|
56
|
+
"add the file by hand only if you own that folder and mean to write to it."
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def resolve_root(cli_root: str | None, env: Mapping[str, str]) -> Path | None:
|
|
61
|
+
"""The store folder by precedence --root, MEM_STORE, config file, default store; not checked for existence."""
|
|
62
|
+
return config.resolve_store(cli_root, env)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def data_dir(env: Mapping[str, str]) -> Path | None:
|
|
66
|
+
"""Folder for the usage log and other state, outside the store; None when no variable locates it."""
|
|
67
|
+
if _env_value(env, "MEM_DATA"):
|
|
68
|
+
return Path(env["MEM_DATA"])
|
|
69
|
+
state = _env_value(env, "XDG_STATE_HOME")
|
|
70
|
+
if state:
|
|
71
|
+
return Path(state) / "agent-memory"
|
|
72
|
+
home = _env_value(env, "HOME")
|
|
73
|
+
return Path(home) / ".local" / "state" / "agent-memory" if home else None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def resolve_note(root: Path, arg: str, *, prefix: bool = True) -> Path | list[str] | None:
|
|
77
|
+
"""The `.md` file `arg` names inside the hub, as a resolved absolute Path.
|
|
78
|
+
|
|
79
|
+
`arg` is a path (hub-relative or absolute), else a handle (`_handle`, with or without `.md`), else (when
|
|
80
|
+
`prefix`, and `arg` does not end in `.md`) a unique prefix of a handle or of a hub-relative path; an exact
|
|
81
|
+
handle or path wins over prefixes. Several matches return their hub-relative paths, sorted; no match
|
|
82
|
+
returns None. Handles come from file names alone: no note is parsed."""
|
|
83
|
+
root = root.resolve()
|
|
84
|
+
path = Path(arg)
|
|
85
|
+
path = (path if path.is_absolute() else root / path).resolve()
|
|
86
|
+
if path.suffix == ".md" and path.is_file() and path.is_relative_to(root):
|
|
87
|
+
return path
|
|
88
|
+
name = arg.removesuffix(".md")
|
|
89
|
+
if not name:
|
|
90
|
+
return None
|
|
91
|
+
rels = sorted(p.relative_to(root).as_posix() for _, p in note_files._note_files(root))
|
|
92
|
+
for found in (
|
|
93
|
+
[r for r in rels if note_files._handle(r) == name or r.removesuffix(".md") == name],
|
|
94
|
+
[r for r in rels if note_files._handle(r).startswith(name) or r.startswith(name)]
|
|
95
|
+
if prefix and name == arg
|
|
96
|
+
else [],
|
|
97
|
+
):
|
|
98
|
+
if found:
|
|
99
|
+
return root / found[0] if len(found) == 1 else found
|
|
100
|
+
return None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _ambiguous(arg: str, found: list[str]) -> None:
|
|
104
|
+
print(f"ambiguous: {arg} matches {len(found)} notes:", *found[:10], sep="\n", file=sys.stderr)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _split_frontmatter_block(text: str) -> re.Match | None:
|
|
108
|
+
return re.match(r"---\n(.*?)\n---[ \t]*(?:\n|$)", text, re.DOTALL)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _set_field(text: str, key: str, value: Any) -> str:
|
|
112
|
+
"""`text` with the frontmatter field `key` set (in place when present, else last) or, for None, removed;
|
|
113
|
+
every other byte stays."""
|
|
114
|
+
m = _split_frontmatter_block(text)
|
|
115
|
+
if m is None:
|
|
116
|
+
raise ValueError("the note has no frontmatter")
|
|
117
|
+
lines = m.group(1).split("\n")
|
|
118
|
+
start = next((i for i, ln in enumerate(lines) if re.match(rf"{re.escape(key)}:", ln)), None)
|
|
119
|
+
end = start
|
|
120
|
+
if start is not None:
|
|
121
|
+
end = start + 1
|
|
122
|
+
while end < len(lines) and re.match(r"(\s|- )", lines[end]):
|
|
123
|
+
end += 1
|
|
124
|
+
rendered = (
|
|
125
|
+
""
|
|
126
|
+
if value is None
|
|
127
|
+
else yaml.safe_dump(
|
|
128
|
+
value, allow_unicode=True, default_flow_style=True, width=float("inf")
|
|
129
|
+
).split("\n")[0]
|
|
130
|
+
)
|
|
131
|
+
new = [] if value is None else [f"{key}: {rendered}"]
|
|
132
|
+
new_lines = lines[:start] + new + lines[end:] if start is not None else lines + new
|
|
133
|
+
return "---\n" + "\n".join(new_lines) + "\n---\n" + text[m.end() :]
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _usage_log(env: Mapping[str, str]) -> Path | None:
|
|
137
|
+
data = data_dir(env)
|
|
138
|
+
return None if data is None else data / "usage" / "log.jsonl"
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _is_outside(root: Path, cwd: Path | None) -> bool:
|
|
142
|
+
try:
|
|
143
|
+
here = (cwd if cwd is not None else Path.cwd()).resolve()
|
|
144
|
+
return not here.is_relative_to(root.resolve())
|
|
145
|
+
except OSError:
|
|
146
|
+
return True
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _append_usage(
|
|
150
|
+
root: Path | None, entry: dict[str, Any], env: Mapping[str, str], cwd: Path | None
|
|
151
|
+
) -> None:
|
|
152
|
+
"""Write one usage entry as a line of the log file, unless the log would sit inside the store."""
|
|
153
|
+
log_path = _usage_log(env)
|
|
154
|
+
if root is not None:
|
|
155
|
+
entry["outside"] = _is_outside(root, cwd)
|
|
156
|
+
# the store is never written by the log
|
|
157
|
+
if log_path is not None and log_path.resolve().is_relative_to(root.resolve()):
|
|
158
|
+
return
|
|
159
|
+
if log_path is None:
|
|
160
|
+
return
|
|
161
|
+
# ASCII escapes keep one entry on one line and survive argv that is not valid UTF-8
|
|
162
|
+
line = (json.dumps(entry) + "\n").encode("ascii")
|
|
163
|
+
log_path.parent.mkdir(parents=True, exist_ok=True)
|
|
164
|
+
fd = os.open(log_path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o644)
|
|
165
|
+
try:
|
|
166
|
+
os.write(fd, line) # one write: parallel processes cannot interleave lines
|
|
167
|
+
finally:
|
|
168
|
+
os.close(fd)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def log_usage(
|
|
172
|
+
root: Path | None,
|
|
173
|
+
entry: dict[str, Any],
|
|
174
|
+
*,
|
|
175
|
+
env: Mapping[str, str] | None = None,
|
|
176
|
+
cwd: Path | None = None,
|
|
177
|
+
) -> None:
|
|
178
|
+
"""Append one JSON line to the usage log in the data folder; never raises, never changes output."""
|
|
179
|
+
env = os.environ if env is None else env
|
|
180
|
+
if env.get("MEM_USAGE_LOG") == "0":
|
|
181
|
+
return
|
|
182
|
+
entry = {"t": datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), **entry}
|
|
183
|
+
with contextlib.suppress(OSError, ValueError, TypeError):
|
|
184
|
+
_append_usage(root, entry, env, cwd)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _project_synthesis_context() -> tuple[Path, Path, Path] | None:
|
|
188
|
+
"""(memory folder, working tree, project root) of the project the session is in; None after saying so."""
|
|
189
|
+
root = records.project_root(Path.cwd(), os.environ)
|
|
190
|
+
if root is None:
|
|
191
|
+
print("mem: not inside a project", file=sys.stderr)
|
|
192
|
+
return None
|
|
193
|
+
return records.project_dir(root), project_syntheses.worktree(Path.cwd(), root, os.environ), root
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _split_part_ref(ref: str) -> tuple[str, str | None]:
|
|
197
|
+
name, sep, handle = ref.removeprefix("p:").partition("#")
|
|
198
|
+
if sep and not handle:
|
|
199
|
+
raise project_syntheses.ProjectSynthesisError(f"{ref!r} has an empty part handle after `#`")
|
|
200
|
+
return name, handle or None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _existing_parts(found: dict[str, list[project_syntheses.Part]]) -> str:
|
|
204
|
+
return "; ".join(f"p:{n}#{p.handle}" for n, parts in found.items() for p in parts) or "none yet"
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _part_line(name: str, part: project_syntheses.Part, tree: Path) -> str:
|
|
208
|
+
return (
|
|
209
|
+
f"p:{name}#{part.handle}\t{project_syntheses.freshness(tree, part.stamp)}\t{part.heading}"
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _load_project_syntheses(
|
|
214
|
+
memory_dir: Path, name: str | None = None
|
|
215
|
+
) -> dict[str, list[project_syntheses.Part]]:
|
|
216
|
+
"""The files that load; a broken one does not hide the others, but asking for it by name raises its error."""
|
|
217
|
+
found, broken = project_syntheses.load_each(memory_dir)
|
|
218
|
+
for path, error in broken:
|
|
219
|
+
if name is not None and path == f"{project_syntheses.folder(Path()).as_posix()}/{name}.md":
|
|
220
|
+
raise project_syntheses.Unavailable(f"{path} cannot be read: {error}")
|
|
221
|
+
return found
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _optional_store(args: argparse.Namespace) -> Path | None:
|
|
225
|
+
return args.root if isinstance(args.root, Path) and args.root.is_dir() else None
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
_READ_ONLY_PROJECT = (
|
|
229
|
+
"mem: this project is the store, which is read-only: it has no mem-store.yaml; "
|
|
230
|
+
"a memory cannot be written here."
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
_READ_ONLY_MEMORIES = (
|
|
235
|
+
"mem: the memories folder is inside the store, which is read-only: it has no mem-store.yaml."
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _read_only_store(store: Path | None, path: Path) -> bool:
|
|
240
|
+
return (
|
|
241
|
+
store is not None and not records.store_is_writable(store) and records.inside(path, store)
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _append_hook_log(entry: dict[str, Any]) -> None:
|
|
246
|
+
folder = data_dir(os.environ)
|
|
247
|
+
if folder is None:
|
|
248
|
+
return
|
|
249
|
+
log_path = folder / "hooks" / "log.jsonl"
|
|
250
|
+
log_path.parent.mkdir(parents=True, exist_ok=True)
|
|
251
|
+
fd = os.open(log_path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o644)
|
|
252
|
+
try:
|
|
253
|
+
os.write(fd, (json.dumps(entry) + "\n").encode("ascii"))
|
|
254
|
+
finally:
|
|
255
|
+
os.close(fd)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _log_hook(entry: dict[str, Any]) -> None:
|
|
259
|
+
"""Append one line to the hook log in the data folder; never raises. Holds no text and no path."""
|
|
260
|
+
entry = {"t": datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), **entry}
|
|
261
|
+
with contextlib.suppress(OSError, ValueError, TypeError):
|
|
262
|
+
_append_hook_log(entry)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _check_terms(texts: Sequence[str], kind: str, approved: bool) -> int:
|
|
266
|
+
"""0 when a write to the global scope may go on, else its exit code after a message on stderr: 4 for a hard
|
|
267
|
+
term, 5 for a soft one the owner has not approved, 2 when the list cannot be read, created or located (no HOME and
|
|
268
|
+
no XDG_CONFIG_HOME). A missing list is created, so it never blocks."""
|
|
269
|
+
if records.forbidden_file(os.environ) is None:
|
|
270
|
+
print(
|
|
271
|
+
"mem: the forbidden-terms list has no place: neither XDG_CONFIG_HOME nor HOME is set; nothing was written.",
|
|
272
|
+
file=sys.stderr,
|
|
273
|
+
)
|
|
274
|
+
return 2
|
|
275
|
+
try:
|
|
276
|
+
records.ensure_terms_file(os.environ)
|
|
277
|
+
hits = records.term_hits(texts, os.environ, kind)
|
|
278
|
+
except records.ForbiddenListError as exc:
|
|
279
|
+
print(
|
|
280
|
+
f"mem: the forbidden-terms list cannot be read ({exc}); nothing was written.",
|
|
281
|
+
file=sys.stderr,
|
|
282
|
+
)
|
|
283
|
+
return 2
|
|
284
|
+
except OSError as exc:
|
|
285
|
+
print(
|
|
286
|
+
f"mem: the forbidden-terms list cannot be created ({exc}); nothing was written.",
|
|
287
|
+
file=sys.stderr,
|
|
288
|
+
)
|
|
289
|
+
return 2
|
|
290
|
+
hard = next((t for t in hits if not t.soft), None)
|
|
291
|
+
if hard is not None:
|
|
292
|
+
print(
|
|
293
|
+
f"mem: the text contains a forbidden term (line {hard.line} of the forbidden-terms list); "
|
|
294
|
+
"nothing was written.",
|
|
295
|
+
file=sys.stderr,
|
|
296
|
+
)
|
|
297
|
+
return 4
|
|
298
|
+
soft = next((t for t in hits), None)
|
|
299
|
+
if soft is not None and not approved:
|
|
300
|
+
print(
|
|
301
|
+
f'mem: the text mentions "{soft.text}" (a soft term): ask the owner whether this may be written to the '
|
|
302
|
+
"global scope; if they agree, repeat with --owner-approved.",
|
|
303
|
+
file=sys.stderr,
|
|
304
|
+
)
|
|
305
|
+
return 5
|
|
306
|
+
return 0
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _refuse_secret(texts: Sequence[str]) -> bool:
|
|
310
|
+
"""Say so on stderr and return True when a text looks like it holds a secret."""
|
|
311
|
+
name = records.secret_in(texts)
|
|
312
|
+
if name is None:
|
|
313
|
+
return False
|
|
314
|
+
print(
|
|
315
|
+
f"mem: the text looks like it contains a secret ({name}); nothing was written.",
|
|
316
|
+
file=sys.stderr,
|
|
317
|
+
)
|
|
318
|
+
return True
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
_TEMPLATES = resources.TEMPLATES
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _commit_points(
|
|
325
|
+
store: Path,
|
|
326
|
+
message: str | Callable[[int], str],
|
|
327
|
+
*,
|
|
328
|
+
quiet: bool = False,
|
|
329
|
+
held: list[str] | None = None,
|
|
330
|
+
) -> tuple[str | None, bool]:
|
|
331
|
+
"""Commit the store; (commit id or None, whether git failed). The failure is reported and logged.
|
|
332
|
+
|
|
333
|
+
`held` receives the paths this run held back, so a caller never reads an older run's list."""
|
|
334
|
+
failed: list[str] = []
|
|
335
|
+
|
|
336
|
+
def report(reason: str) -> None:
|
|
337
|
+
failed.append(reason)
|
|
338
|
+
if not quiet:
|
|
339
|
+
print(f"mem: history: {reason}", file=sys.stderr)
|
|
340
|
+
log_usage(store, {"cmd": "history", "error": reason})
|
|
341
|
+
|
|
342
|
+
def warn(
|
|
343
|
+
reason: str,
|
|
344
|
+
) -> None: # not a git failure: it must not make `mem history commit` exit 1
|
|
345
|
+
if not quiet:
|
|
346
|
+
print(f"mem: history: {reason}", file=sys.stderr)
|
|
347
|
+
log_usage(store, {"cmd": "history", "warning": reason})
|
|
348
|
+
|
|
349
|
+
commit = store_git.commit_if_changed(
|
|
350
|
+
store,
|
|
351
|
+
message,
|
|
352
|
+
report=report,
|
|
353
|
+
warn=warn,
|
|
354
|
+
validate=check_rules.invalid_changed(store),
|
|
355
|
+
on_held=lambda paths: held.extend(paths) if held is not None else None,
|
|
356
|
+
)
|
|
357
|
+
return commit, bool(failed)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _swap_file(path: Path, data: bytes) -> None:
|
|
361
|
+
safe_io.replace_file(path, data)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
SOURCES_DIR = ".sources"
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _memory_folders(args: argparse.Namespace) -> list[tuple[str, Path | None]]:
|
|
368
|
+
try:
|
|
369
|
+
project = records.project_root(Path.cwd(), os.environ)
|
|
370
|
+
except OSError:
|
|
371
|
+
project = None
|
|
372
|
+
return [
|
|
373
|
+
("project", records.project_dir(project) if project else None),
|
|
374
|
+
("global", records.memories_root(os.environ, _optional_store(args))),
|
|
375
|
+
]
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _named_folder(name: str) -> Path | None:
|
|
379
|
+
"""The memory folder of a registered project; None when the name is unknown or the registry unreadable."""
|
|
380
|
+
try:
|
|
381
|
+
entry = records.read_registry(data_dir(os.environ)).get(name)
|
|
382
|
+
except ValueError:
|
|
383
|
+
return None
|
|
384
|
+
return records.project_dir(Path(entry["path"])) if entry else None
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _other_projects(names: Sequence[str], every: bool) -> list[tuple[str, Path]] | None:
|
|
388
|
+
"""The folders of the projects asked for, without the current one; None after a message on stderr."""
|
|
389
|
+
try:
|
|
390
|
+
reg = records.read_registry(data_dir(os.environ))
|
|
391
|
+
except ValueError as exc:
|
|
392
|
+
print(f"mem: {exc}", file=sys.stderr)
|
|
393
|
+
return None
|
|
394
|
+
for name in names:
|
|
395
|
+
if name not in reg:
|
|
396
|
+
print(f"mem: no project named {name} (see mem projects list)", file=sys.stderr)
|
|
397
|
+
return None
|
|
398
|
+
try:
|
|
399
|
+
current = records.project_root(Path.cwd(), os.environ)
|
|
400
|
+
current = current.resolve() if current else None
|
|
401
|
+
except OSError:
|
|
402
|
+
current = None
|
|
403
|
+
chosen = list(dict.fromkeys([*(reg if every else ()), *names]))
|
|
404
|
+
return [
|
|
405
|
+
(n, records.project_dir(Path(reg[n]["path"])))
|
|
406
|
+
for n in chosen
|
|
407
|
+
if current is None or Path(reg[n]["path"]) != current
|
|
408
|
+
]
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _memory_status(m: records.Memory, today: datetime.date) -> str | None:
|
|
412
|
+
if m.status != "active":
|
|
413
|
+
return m.status
|
|
414
|
+
return "expired" if m.valid_until is not None and m.valid_until < today else None
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _unconfirmed(m: records.Memory) -> str:
|
|
418
|
+
"""A web finding is unchecked until a second source confirms it; a transcript memory until another session shows it."""
|
|
419
|
+
if m.origin == "transcript":
|
|
420
|
+
return (
|
|
421
|
+
", from transcript, unconfirmed"
|
|
422
|
+
if records.standing(m) == "unconfirmed"
|
|
423
|
+
else ", from transcript"
|
|
424
|
+
)
|
|
425
|
+
return ", web, unconfirmed" if m.origin == "web" else ""
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _tally_line(tally: records.Tally, until: datetime.date) -> str:
|
|
429
|
+
"""The `mem show` line of one version; `until` is the date of the next version, or today for the last."""
|
|
430
|
+
days = (until - tally.since).days
|
|
431
|
+
return (
|
|
432
|
+
f"version {tally.number} since {tally.since.isoformat()} ({days} day{'' if days == 1 else 's'}): "
|
|
433
|
+
f"worked {tally.worked}, failed {tally.failed}: {tally.text}"
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _find_memory(args: argparse.Namespace, handle: str) -> records.Memory | None:
|
|
438
|
+
"""An exact handle: the project scope wins over the global one."""
|
|
439
|
+
named = getattr(args, "project", None)
|
|
440
|
+
if named: # an explicit, read-only look at another project
|
|
441
|
+
return next(
|
|
442
|
+
(
|
|
443
|
+
m
|
|
444
|
+
for m in records.load_memories(_named_folder(named), "project")
|
|
445
|
+
if m.handle == handle
|
|
446
|
+
),
|
|
447
|
+
None,
|
|
448
|
+
)
|
|
449
|
+
project = records.project_root(Path.cwd(), os.environ)
|
|
450
|
+
folders = [
|
|
451
|
+
("project", records.project_dir(project) if project else None),
|
|
452
|
+
("global", records.memories_root(os.environ, _optional_store(args))),
|
|
453
|
+
]
|
|
454
|
+
for scope, folder in folders:
|
|
455
|
+
for m in records.load_memories(folder, scope):
|
|
456
|
+
if m.handle == handle:
|
|
457
|
+
return m
|
|
458
|
+
return None
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
class NewNoteError(Exception):
|
|
462
|
+
pass
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def _sha(data: bytes) -> str:
|
|
466
|
+
return hashlib.sha256(data).hexdigest()
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _log_group(
|
|
470
|
+
root: Path,
|
|
471
|
+
originals: Mapping[Path, bytes],
|
|
472
|
+
action: str,
|
|
473
|
+
moved: Mapping[Path, Path] | None = None,
|
|
474
|
+
group: str | None = None,
|
|
475
|
+
) -> None:
|
|
476
|
+
"""One `.curation-log` entry per changed file, sharing a `group` id and holding the file's text before the action
|
|
477
|
+
and a digest of its text after it, so `mem restore` can undo them together and refuse when one changed since.
|
|
478
|
+
`moved` names, for a file that was renamed, the path it had before (`from`, hub-relative)."""
|
|
479
|
+
changes = {path: (before, _sha(path.read_bytes())) for path, before in originals.items()}
|
|
480
|
+
safe_io.append_text(
|
|
481
|
+
root / records.CURATION_LOG, _group_entries(root, changes, action, moved, group)
|
|
482
|
+
)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def _group_entries(
|
|
486
|
+
root: Path,
|
|
487
|
+
changes: Mapping[Path, tuple[bytes, str]],
|
|
488
|
+
action: str,
|
|
489
|
+
moved: Mapping[Path, Path] | None = None,
|
|
490
|
+
group: str | None = None,
|
|
491
|
+
) -> str:
|
|
492
|
+
"""Serialize a group from original bytes and replacement digests."""
|
|
493
|
+
group = group or uuid.uuid4().hex
|
|
494
|
+
stamp = datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
495
|
+
out = []
|
|
496
|
+
for path, (before, after) in changes.items():
|
|
497
|
+
entry = {
|
|
498
|
+
"t": stamp,
|
|
499
|
+
"action": action,
|
|
500
|
+
"handle": path.relative_to(root).as_posix(),
|
|
501
|
+
"group": group,
|
|
502
|
+
"before": before.decode("utf-8"),
|
|
503
|
+
"after": after,
|
|
504
|
+
}
|
|
505
|
+
if moved and path in moved:
|
|
506
|
+
entry["from"] = moved[path].relative_to(root).as_posix()
|
|
507
|
+
out.append(json.dumps(entry, ensure_ascii=False) + "\n")
|
|
508
|
+
return "".join(out)
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def _read_body_text(source: str) -> str:
|
|
512
|
+
"""The text of the file, or of standard input for `-`, before any check of its content."""
|
|
513
|
+
if source == "-":
|
|
514
|
+
if sys.stdin.isatty():
|
|
515
|
+
raise NewNoteError("--body-file - needs the body on standard input, not a terminal")
|
|
516
|
+
return sys.stdin.read().removeprefix("\ufeff").replace("\r\n", "\n")
|
|
517
|
+
return note_files._read_text(Path(source))
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def _read_body(source: str) -> str:
|
|
521
|
+
"""The text of a `--body-file` (`-` is standard input); NewNoteError when it cannot be a body."""
|
|
522
|
+
try:
|
|
523
|
+
body = _read_body_text(source)
|
|
524
|
+
except (OSError, UnicodeDecodeError, note_files.FrontmatterError) as exc:
|
|
525
|
+
raise NewNoteError(f"cannot read the body: {exc}") from exc
|
|
526
|
+
if not body.strip():
|
|
527
|
+
raise NewNoteError("the body is empty")
|
|
528
|
+
if body.split("\n", 1)[0].strip() == "---":
|
|
529
|
+
raise NewNoteError(
|
|
530
|
+
"the body starts with a frontmatter fence: pass the text after the frontmatter"
|
|
531
|
+
)
|
|
532
|
+
return body if body.endswith("\n") else body + "\n"
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def _section_ref(root: Path, ref: str) -> tuple[document.Synthesis, document.Section]:
|
|
536
|
+
"""`s:<h>#<section>` as the synthesis and section it names; ValueError when either is missing."""
|
|
537
|
+
handle, section = document.split_ref(ref)
|
|
538
|
+
path = document.path_of(root / document.SYNTHESES_DIR, handle)
|
|
539
|
+
if section is None or path is None or not path.is_file():
|
|
540
|
+
raise ValueError(
|
|
541
|
+
f"{ref} must name an existing synthesis section: s:<handle>#<section handle>"
|
|
542
|
+
)
|
|
543
|
+
syn = document.load_one(path)
|
|
544
|
+
if syn.error:
|
|
545
|
+
raise ValueError(f"{path.name}: {syn.error}")
|
|
546
|
+
found = next((x for x in syn.sections if x.handle == section), None)
|
|
547
|
+
if found is None:
|
|
548
|
+
raise ValueError(f"no section {section} in s:{handle}")
|
|
549
|
+
return syn, found
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _note_target(rel: str) -> str:
|
|
553
|
+
"""How a synthesis part refers to the note stored at `rel` (a store-relative path)."""
|
|
554
|
+
return "../" + rel
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def _memory_body(source: str | None) -> str:
|
|
558
|
+
"""The text of `--body-file` (`-` is standard input); absent or empty gives an empty body."""
|
|
559
|
+
if not source:
|
|
560
|
+
return ""
|
|
561
|
+
if source == "-":
|
|
562
|
+
if sys.stdin.isatty():
|
|
563
|
+
raise OSError("--body-file - needs the body on standard input, not a terminal")
|
|
564
|
+
return sys.stdin.read().removeprefix("\ufeff").replace("\r\n", "\n")
|
|
565
|
+
return Path(source).read_text(encoding="utf-8").replace("\r\n", "\n")
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _readable(memories: Sequence[records.Memory], today: datetime.date) -> list[records.Memory]:
|
|
569
|
+
"""What a reader may be shown: live, and not a global lesson still in quarantine. The tools that corroborate or
|
|
570
|
+
look a record up (the identical-claim check, handles, curate, the capture list) load unfiltered. `cmd_search`,
|
|
571
|
+
`cmd_memories` and `cmd_signal` filter `records.quarantined` directly: the first two because `--all-memories` and
|
|
572
|
+
`--dead` still show dead records, the third because it reads the folders itself and shows no liveness."""
|
|
573
|
+
return [m for m in memories if records.is_live(m, today) and not records.quarantined(m)]
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def _rules_layout(arg: str | None = None) -> str:
|
|
577
|
+
"""`--layout` wins, then MEM_RULES_LAYOUT (set by the hooks from the option rules_layout); only `grouped` and `digest` switch."""
|
|
578
|
+
env = os.environ.get("MEM_RULES_LAYOUT")
|
|
579
|
+
return arg or (env if env in {"grouped", "digest"} else "flat")
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def _rules_digest(
|
|
583
|
+
global_lessons: list[records.Memory], today: datetime.date
|
|
584
|
+
) -> tuple[dict | None, dict | None]:
|
|
585
|
+
"""The digest file and the topics it may speak for, (None, None) when either cannot be read: callers then print without it."""
|
|
586
|
+
try:
|
|
587
|
+
data = digest_lessons.read(data_dir(os.environ))
|
|
588
|
+
return (
|
|
589
|
+
(data, digest_lessons.topics_of(global_lessons, today))
|
|
590
|
+
if data["topics"]
|
|
591
|
+
else (None, None)
|
|
592
|
+
)
|
|
593
|
+
except Exception:
|
|
594
|
+
logger.debug("reading the rules digest failed", exc_info=True)
|
|
595
|
+
return None, None
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def _rules_off() -> bool:
|
|
599
|
+
return os.environ.get("MEM_LOADED_RULES") == "off"
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def _fill_attempts(env: Mapping[str, str]) -> dict:
|
|
603
|
+
"""The automatic short-form fill's attempts (`fill_key` -> entry), read defensively: a missing, unreadable or
|
|
604
|
+
malformed state reads as no attempts, so curation never fails on it."""
|
|
605
|
+
data = data_dir(env)
|
|
606
|
+
lessons = (
|
|
607
|
+
jobs.read_json(data / "corroborate" / "fill-attempts.json").get("lessons") if data else None
|
|
608
|
+
)
|
|
609
|
+
return lessons if isinstance(lessons, dict) else {}
|