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,16 @@
|
|
|
1
|
+
"""Memories: the record model, parsing and writing, matching, terms, locations, sightings, rules and fingerprints.
|
|
2
|
+
|
|
3
|
+
`fingerprints`: lookups of the digest: fingerprints, stored heading or line of a lesson
|
|
4
|
+
`journal`: curation log: record text before an action, and undo
|
|
5
|
+
`locations`: git roots, project registry, memories folders, project key
|
|
6
|
+
`matching`: term matching, containment, related records, duplicate and refuting pairs
|
|
7
|
+
`model`: the `Memory` record, its vocabularies, one-line checks, `short_problems`
|
|
8
|
+
`parse`: a Markdown file with YAML frontmatter becomes a `Memory`
|
|
9
|
+
`records`: facade re-exporting names as `records.<name>`; no logic
|
|
10
|
+
`rules`: which lessons load as rules at session start, order, text
|
|
11
|
+
`sightings`: sightings, cases and versions of a memory
|
|
12
|
+
`terms`: forbidden terms, secret patterns, global-scope checks
|
|
13
|
+
`write`: render a memory file, new memories, field updates
|
|
14
|
+
|
|
15
|
+
A base layer like `core`: imports stdlib, `core` and `memories` only (never `notes`).
|
|
16
|
+
"""
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""The lookups of the digest: the fingerprints and the stored heading or line of a lesson, if still fresh.
|
|
2
|
+
|
|
3
|
+
Both `digest` and `rules` import this module, so neither imports the other back. `digest` re-exports the four public
|
|
4
|
+
names, so `digest.heading` and the others keep working."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
from typing import TYPE_CHECKING
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from collections.abc import Sequence
|
|
13
|
+
|
|
14
|
+
from memory_cli.memories.model import Memory
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _print(*parts: str) -> str:
|
|
18
|
+
"""The first 16 hexadecimal characters of the SHA-256 of the parts, each with whitespace collapsed, joined by NUL."""
|
|
19
|
+
text = "\0".join(" ".join((p or "").split()) for p in parts)
|
|
20
|
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def line_print(m: Memory) -> str:
|
|
24
|
+
"""Hashes the claim and the short form of the lesson; nothing else (not log, versions or topic)."""
|
|
25
|
+
return _print(m.claim, m.short or "")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def heading_print(lessons: Sequence[Memory]) -> str:
|
|
29
|
+
"""Hashes the lessons' handles and claims, sorted by handle, so the order of the lessons does not matter."""
|
|
30
|
+
return _print(
|
|
31
|
+
*(part for m in sorted(lessons, key=lambda m: m.handle) for part in (m.handle, m.claim))
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def heading(digest: dict, topic: str, lessons: Sequence[Memory]) -> str | None:
|
|
36
|
+
"""The stored heading when it was written for exactly these lessons and claims, else None."""
|
|
37
|
+
entry = digest.get("topics", {}).get(topic)
|
|
38
|
+
return entry["heading"] if entry and entry["of"] == heading_print(lessons) else None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def line(digest: dict, topic: str, m: Memory, lessons: Sequence[Memory]) -> str | None:
|
|
42
|
+
"""The stored text when it matches the lesson, was written under the stored heading, and that heading is fresh."""
|
|
43
|
+
if heading(digest, topic, lessons) is None:
|
|
44
|
+
return None
|
|
45
|
+
entry = digest["topics"][topic]
|
|
46
|
+
stored = entry["lines"].get(m.handle)
|
|
47
|
+
return (
|
|
48
|
+
stored["text"]
|
|
49
|
+
if stored and stored["of"] == line_print(m) and stored["under"] == entry["of"]
|
|
50
|
+
else None
|
|
51
|
+
)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""The curation log: each record file's text before an action changes it, and the undo that puts it back."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime
|
|
6
|
+
import json
|
|
7
|
+
from typing import TYPE_CHECKING, Protocol
|
|
8
|
+
|
|
9
|
+
from memory_cli.core import safe_io
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from collections.abc import Sequence
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
CURATION_LOG = ".curation-log"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Logged(Protocol):
|
|
19
|
+
"""What the curation log needs of a record: a file and a handle (a memory or a synthesis)."""
|
|
20
|
+
|
|
21
|
+
path: Path
|
|
22
|
+
handle: str
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def log_before(memory: Logged, action: str) -> None:
|
|
26
|
+
"""Append the file's whole current text to the `.curation-log` beside it, before an action changes the file."""
|
|
27
|
+
entry = {
|
|
28
|
+
"t": datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
29
|
+
"action": action,
|
|
30
|
+
"handle": memory.handle,
|
|
31
|
+
"before": memory.path.read_bytes().decode("utf-8"),
|
|
32
|
+
}
|
|
33
|
+
safe_io.append_text(
|
|
34
|
+
memory.path.parent / CURATION_LOG, json.dumps(entry, ensure_ascii=False) + "\n"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _log_lines(memory: Logged) -> list[str] | None:
|
|
39
|
+
try:
|
|
40
|
+
# split on "\n" only: splitlines() would also cut at U+0085 or U+2028 inside a JSON string
|
|
41
|
+
return (memory.path.parent / CURATION_LOG).read_text(encoding="utf-8").split("\n")
|
|
42
|
+
except OSError:
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _parsed_log(lines: Sequence[str], handle: str) -> tuple[list[dict | None], int]:
|
|
47
|
+
"""The entries of the memory's handle, None for every other line, and the count of unreadable lines."""
|
|
48
|
+
parsed: list[dict | None] = []
|
|
49
|
+
skipped = 0
|
|
50
|
+
for line in lines:
|
|
51
|
+
entry = None
|
|
52
|
+
if line.strip():
|
|
53
|
+
try:
|
|
54
|
+
entry = json.loads(line)
|
|
55
|
+
except ValueError:
|
|
56
|
+
skipped += 1
|
|
57
|
+
parsed.append(entry if isinstance(entry, dict) and entry.get("handle") == handle else None)
|
|
58
|
+
return parsed, skipped
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def last_log_entry(memory: Logged) -> dict | None:
|
|
62
|
+
"""The newest `.curation-log` entry for the memory's handle that no restore has used yet, or None.
|
|
63
|
+
|
|
64
|
+
Undo is a stack over an append-only log: a restore appends a marker naming the entry (by line number) it used.
|
|
65
|
+
The entry returned gains `line` (its number) and `skipped` (the unreadable lines of the log)."""
|
|
66
|
+
lines = _log_lines(memory)
|
|
67
|
+
if lines is None:
|
|
68
|
+
return None
|
|
69
|
+
parsed, skipped = _parsed_log(lines, memory.handle)
|
|
70
|
+
undone = {
|
|
71
|
+
e["undone"]
|
|
72
|
+
for e in parsed
|
|
73
|
+
if e and e.get("action") == "restore" and isinstance(e.get("undone"), int)
|
|
74
|
+
}
|
|
75
|
+
for number in range(len(parsed) - 1, -1, -1):
|
|
76
|
+
entry = parsed[number]
|
|
77
|
+
if entry and isinstance(entry.get("before"), str) and number not in undone:
|
|
78
|
+
return {**entry, "line": number, "skipped": skipped}
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def restore(memory: Logged, entry: dict) -> None:
|
|
83
|
+
"""Put back the text a log entry holds, byte for byte, through a temporary file, then log that it was used."""
|
|
84
|
+
safe_io.replace_file(memory.path, entry["before"].encode("utf-8"))
|
|
85
|
+
marker = {
|
|
86
|
+
"t": datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
87
|
+
"action": "restore",
|
|
88
|
+
"handle": memory.handle,
|
|
89
|
+
"undone": entry["line"],
|
|
90
|
+
}
|
|
91
|
+
safe_io.append_text(
|
|
92
|
+
memory.path.parent / CURATION_LOG, json.dumps(marker, ensure_ascii=False) + "\n"
|
|
93
|
+
)
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
"""Where things live: git roots, the project registry, the memories folders and the project key."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import subprocess
|
|
9
|
+
import tempfile
|
|
10
|
+
from dataclasses import replace
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import TYPE_CHECKING
|
|
13
|
+
|
|
14
|
+
from memory_cli.core import config
|
|
15
|
+
from memory_cli.memories.model import GLOBAL_DIR, PROJECT_DIR, PROJECT_KEY_LEN
|
|
16
|
+
from memory_cli.memories.terms import store_is_writable
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
import datetime
|
|
20
|
+
from collections.abc import Mapping, Sequence
|
|
21
|
+
|
|
22
|
+
from memory_cli.memories.model import Memory
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _git_common_dir(cwd: Path) -> Path | None:
|
|
26
|
+
try:
|
|
27
|
+
out = subprocess.run(
|
|
28
|
+
["git", "-C", str(cwd), "rev-parse", "--path-format=absolute", "--git-common-dir"],
|
|
29
|
+
capture_output=True,
|
|
30
|
+
text=True,
|
|
31
|
+
check=False,
|
|
32
|
+
)
|
|
33
|
+
except (OSError, ValueError):
|
|
34
|
+
return None
|
|
35
|
+
line = out.stdout.strip()
|
|
36
|
+
if out.returncode != 0 or not line:
|
|
37
|
+
return None
|
|
38
|
+
return Path(line)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _main_worktree(cwd: Path) -> Path | None:
|
|
42
|
+
try:
|
|
43
|
+
out = subprocess.run(
|
|
44
|
+
["git", "-C", str(cwd), "worktree", "list", "--porcelain"],
|
|
45
|
+
capture_output=True,
|
|
46
|
+
text=True,
|
|
47
|
+
check=False,
|
|
48
|
+
)
|
|
49
|
+
except (OSError, ValueError):
|
|
50
|
+
return None
|
|
51
|
+
if out.returncode != 0:
|
|
52
|
+
return None
|
|
53
|
+
for line in out.stdout.splitlines():
|
|
54
|
+
if line.startswith("worktree "):
|
|
55
|
+
first = Path(line[len("worktree ") :])
|
|
56
|
+
# A submodule lists its git directory (under .git/modules), not its folder: ask for the folder.
|
|
57
|
+
if (first / ".git").exists():
|
|
58
|
+
return first
|
|
59
|
+
return _toplevel(cwd)
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _toplevel(cwd: Path) -> Path | None:
|
|
64
|
+
try:
|
|
65
|
+
out = subprocess.run(
|
|
66
|
+
["git", "-C", str(cwd), "rev-parse", "--show-toplevel"],
|
|
67
|
+
capture_output=True,
|
|
68
|
+
text=True,
|
|
69
|
+
check=False,
|
|
70
|
+
)
|
|
71
|
+
except (OSError, ValueError):
|
|
72
|
+
return None
|
|
73
|
+
line = out.stdout.strip()
|
|
74
|
+
return Path(line) if out.returncode == 0 and line else None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def project_root(cwd: Path, env: Mapping[str, str]) -> Path | None:
|
|
78
|
+
override = env.get("MEM_PROJECT")
|
|
79
|
+
if override:
|
|
80
|
+
return Path(override).expanduser().resolve()
|
|
81
|
+
return _main_worktree(cwd)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def project_dir(project: Path) -> Path:
|
|
85
|
+
return project / PROJECT_DIR
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
REGISTRY_FILE = "projects.json"
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def read_registry(data: Path | None) -> dict[str, dict[str, str]]:
|
|
92
|
+
"""The registry of projects in the data folder: name -> {path, seen}. Empty when there is no file;
|
|
93
|
+
ValueError when the file cannot be read or is not that shape."""
|
|
94
|
+
if data is None:
|
|
95
|
+
return {}
|
|
96
|
+
try:
|
|
97
|
+
text = (data / REGISTRY_FILE).read_text(encoding="utf-8")
|
|
98
|
+
except FileNotFoundError:
|
|
99
|
+
return {}
|
|
100
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
101
|
+
raise ValueError(f"the registry of projects cannot be read: {exc}") from exc
|
|
102
|
+
try:
|
|
103
|
+
reg = json.loads(text)
|
|
104
|
+
except ValueError as exc:
|
|
105
|
+
raise ValueError(f"the registry of projects is not valid JSON: {exc}") from exc
|
|
106
|
+
if not isinstance(reg, dict) or not all(
|
|
107
|
+
isinstance(v, dict) and isinstance(v.get("path"), str) for v in reg.values()
|
|
108
|
+
):
|
|
109
|
+
raise ValueError("the registry of projects has an unexpected shape")
|
|
110
|
+
return reg
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _registry_name(
|
|
114
|
+
reg: dict[str, dict[str, str]], project: Path, held: str | None, name: str | None
|
|
115
|
+
) -> str:
|
|
116
|
+
"""The name `project` takes in the registry: `name` when free or its own, else the one it holds, else its folder's."""
|
|
117
|
+
if name is not None:
|
|
118
|
+
if held != name and name in reg:
|
|
119
|
+
raise ValueError(f"the name {name} is taken by {reg[name]['path']}")
|
|
120
|
+
return name
|
|
121
|
+
if held is not None:
|
|
122
|
+
return held
|
|
123
|
+
base = project.resolve().name or "project"
|
|
124
|
+
name, n = base, 2
|
|
125
|
+
while name in reg:
|
|
126
|
+
name, n = f"{base}-{n}", n + 1
|
|
127
|
+
return name
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _write_registry(data: Path, reg: dict[str, dict[str, str]]) -> None:
|
|
131
|
+
tmp = data / f"{REGISTRY_FILE}.{os.getpid()}.tmp"
|
|
132
|
+
try:
|
|
133
|
+
tmp.write_text(json.dumps(reg, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
134
|
+
os.replace(tmp, data / REGISTRY_FILE)
|
|
135
|
+
finally:
|
|
136
|
+
tmp.unlink(missing_ok=True)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def register_project(
|
|
140
|
+
data: Path | None, project: Path, today: datetime.date, name: str | None = None
|
|
141
|
+
) -> str | None:
|
|
142
|
+
"""Register `project` (or refresh its `seen` date) in the data folder; its name, None without a data folder.
|
|
143
|
+
|
|
144
|
+
The name is the folder's name, with -2, -3 ... when another path holds it; an explicit `name` held by another
|
|
145
|
+
path is a ValueError. The file is replaced whole, so a failure leaves the old one."""
|
|
146
|
+
if data is None:
|
|
147
|
+
return None
|
|
148
|
+
reg = read_registry(data)
|
|
149
|
+
path = str(project.resolve())
|
|
150
|
+
held = next((n for n, v in reg.items() if v["path"] == path), None)
|
|
151
|
+
name = _registry_name(reg, project, held, name)
|
|
152
|
+
if held is not None and held != name:
|
|
153
|
+
del reg[held]
|
|
154
|
+
reg[name] = {"path": path, "seen": today.isoformat()}
|
|
155
|
+
data.mkdir(parents=True, exist_ok=True)
|
|
156
|
+
_write_registry(data, reg)
|
|
157
|
+
return name
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def forget_project(data: Path | None, name: str) -> bool:
|
|
161
|
+
"""Remove a project from the registry; False when the name is unknown."""
|
|
162
|
+
reg = read_registry(data)
|
|
163
|
+
if data is None or name not in reg:
|
|
164
|
+
return False
|
|
165
|
+
del reg[name]
|
|
166
|
+
_write_registry(data, reg)
|
|
167
|
+
return True
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _configured_memories(env: Mapping[str, str]) -> str:
|
|
171
|
+
"""The first non-blank line of agent-memory/memories under the config folder, else an empty string."""
|
|
172
|
+
lines = config.config_lines(env, "memories")
|
|
173
|
+
return next((ln.strip() for ln in lines if ln.strip()), "")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def memories_root(env: Mapping[str, str], store: Path | None) -> Path | None:
|
|
177
|
+
"""Folder of global memories: MEM_MEMORIES, else the first line of agent-memory/memories, else the writable store's."""
|
|
178
|
+
named = env.get("MEM_MEMORIES") or _configured_memories(env)
|
|
179
|
+
if named:
|
|
180
|
+
if named == "~" or named.startswith("~/"):
|
|
181
|
+
named = (
|
|
182
|
+
str(Path(env["HOME"]) / named[2:]) if env.get("HOME") else os.path.expanduser(named)
|
|
183
|
+
)
|
|
184
|
+
return Path(named)
|
|
185
|
+
if store is not None and store_is_writable(store):
|
|
186
|
+
return store / GLOBAL_DIR
|
|
187
|
+
return None
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def global_memories_root(env: Mapping[str, str]) -> Path | None:
|
|
191
|
+
"""The folder of global memories for a command that takes no store argument (the background commands):
|
|
192
|
+
`memories_root` with the store that MEM_STORE names, else the default store. Without this a background run
|
|
193
|
+
that is given only MEM_STORE, as the hooks give it, finds no global memory."""
|
|
194
|
+
store = config.resolve_store(None, env)
|
|
195
|
+
return memories_root(env, store if store is not None and store.is_dir() else None)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def project_key(project: Path) -> str:
|
|
199
|
+
"""The first 12 hex characters of the SHA-1 of the resolved path: counts projects without naming them."""
|
|
200
|
+
return hashlib.sha1(str(project.resolve()).encode("utf-8")).hexdigest()[:PROJECT_KEY_LEN]
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def under_temp(path: Path) -> bool:
|
|
204
|
+
"""True when `path` is under a temporary folder: a trial copy of a project there is not a second project.
|
|
205
|
+
Always false when MEM_COUNT_TEMP_PROJECTS is "1" (the tests, which run under a temporary folder)."""
|
|
206
|
+
if os.environ.get("MEM_COUNT_TEMP_PROJECTS") == "1":
|
|
207
|
+
return False
|
|
208
|
+
resolved = path.resolve()
|
|
209
|
+
roots = {
|
|
210
|
+
Path(tempfile.gettempdir()).resolve(),
|
|
211
|
+
Path("/tmp").resolve(),
|
|
212
|
+
Path("/var/tmp").resolve(),
|
|
213
|
+
}
|
|
214
|
+
return any(resolved == r or r in resolved.parents for r in roots)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def tracked_memories(project: Path) -> frozenset[str] | None:
|
|
218
|
+
"""Handles of the `.memory/*.md` files git tracks in `project`; None when `.memory` holds its own `.git` or is
|
|
219
|
+
listed as a gitlink (every handle counts as tracked); empty when git is missing, fails or times out."""
|
|
220
|
+
folder = project / PROJECT_DIR
|
|
221
|
+
try:
|
|
222
|
+
if (folder / ".git").exists():
|
|
223
|
+
return None
|
|
224
|
+
run = subprocess.run(
|
|
225
|
+
[
|
|
226
|
+
"git",
|
|
227
|
+
"-C",
|
|
228
|
+
str(project),
|
|
229
|
+
"ls-files",
|
|
230
|
+
"-z",
|
|
231
|
+
"--recurse-submodules",
|
|
232
|
+
"--",
|
|
233
|
+
f"{PROJECT_DIR}/",
|
|
234
|
+
],
|
|
235
|
+
capture_output=True,
|
|
236
|
+
timeout=2,
|
|
237
|
+
check=False,
|
|
238
|
+
)
|
|
239
|
+
except (OSError, subprocess.SubprocessError):
|
|
240
|
+
return frozenset()
|
|
241
|
+
if run.returncode != 0:
|
|
242
|
+
return frozenset()
|
|
243
|
+
names = [Path(n.decode("utf-8", "replace")) for n in run.stdout.split(b"\0") if n]
|
|
244
|
+
if any(n.as_posix() == PROJECT_DIR for n in names): # a gitlink lists as the folder itself
|
|
245
|
+
return None
|
|
246
|
+
return frozenset(
|
|
247
|
+
n.stem for n in names if n.suffix == ".md" and n.parent.as_posix() == PROJECT_DIR
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def mark_repository(memories: Sequence[Memory], tracked: frozenset[str] | None) -> list[Memory]:
|
|
252
|
+
"""Copies of the tracked memories with `from_repository` set and the owner confirmation in the file dropped: a
|
|
253
|
+
repository's author is not the reader. Sightings still count. `tracked` None marks them all."""
|
|
254
|
+
return [
|
|
255
|
+
replace(m, from_repository=True, owner_confirmed=None)
|
|
256
|
+
if tracked is None or m.handle in tracked
|
|
257
|
+
else m
|
|
258
|
+
for m in memories
|
|
259
|
+
]
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def ensure_excluded(project: Path) -> bool:
|
|
263
|
+
"""Add `.memory/` to the repository's .git/info/exclude; raises OSError when the line should be written and cannot."""
|
|
264
|
+
if (project / PROJECT_DIR).exists():
|
|
265
|
+
return False
|
|
266
|
+
common = _git_common_dir(project)
|
|
267
|
+
if common is None:
|
|
268
|
+
return False
|
|
269
|
+
exclude = common / "info" / "exclude"
|
|
270
|
+
existing = exclude.read_text(encoding="utf-8") if exclude.exists() else ""
|
|
271
|
+
lines = {ln.strip() for ln in existing.splitlines()}
|
|
272
|
+
if lines & {".memory/", ".memory", "/.memory/", "/.memory"}:
|
|
273
|
+
return False
|
|
274
|
+
exclude.parent.mkdir(parents=True, exist_ok=True)
|
|
275
|
+
sep = "" if not existing or existing.endswith("\n") else "\n"
|
|
276
|
+
exclude.write_text(f"{existing}{sep}{PROJECT_DIR}/\n", encoding="utf-8")
|
|
277
|
+
return True
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def default_store(env: Mapping[str, str]) -> Path | None:
|
|
281
|
+
"""The store used when none is named: the path only, `mem init` creates it (see `config.default_store`)."""
|
|
282
|
+
return config.default_store_path(env)
|