memory-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. memory_cli/__init__.py +1 -0
  2. memory_cli/__main__.py +49 -0
  3. memory_cli/capture/__init__.py +7 -0
  4. memory_cli/capture/codex_rollout.py +164 -0
  5. memory_cli/capture/event_lines.py +66 -0
  6. memory_cli/capture/extract.py +458 -0
  7. memory_cli/capture/state.py +183 -0
  8. memory_cli/commands/__init__.py +21 -0
  9. memory_cli/commands/admin.py +363 -0
  10. memory_cli/commands/common.py +609 -0
  11. memory_cli/commands/curate.py +1189 -0
  12. memory_cli/commands/diagnostics.py +126 -0
  13. memory_cli/commands/edit.py +1282 -0
  14. memory_cli/commands/hooks.py +730 -0
  15. memory_cli/commands/import_recovery.py +45 -0
  16. memory_cli/commands/install.py +152 -0
  17. memory_cli/commands/integrate.py +480 -0
  18. memory_cli/commands/memory.py +2152 -0
  19. memory_cli/commands/read.py +1290 -0
  20. memory_cli/commands/sources.py +766 -0
  21. memory_cli/commands/split.py +97 -0
  22. memory_cli/commands/split_plan.py +196 -0
  23. memory_cli/commands/split_transaction.py +230 -0
  24. memory_cli/commands/synthesis.py +1122 -0
  25. memory_cli/core/__init__.py +16 -0
  26. memory_cli/core/auto_state.py +30 -0
  27. memory_cli/core/codex_pass.py +109 -0
  28. memory_cli/core/config.py +87 -0
  29. memory_cli/core/file_journal.py +163 -0
  30. memory_cli/core/headless.py +130 -0
  31. memory_cli/core/jobs.py +130 -0
  32. memory_cli/core/resources.py +57 -0
  33. memory_cli/core/runner.py +398 -0
  34. memory_cli/core/safe_io.py +155 -0
  35. memory_cli/core/store_git.py +407 -0
  36. memory_cli/core/yaml_load.py +14 -0
  37. memory_cli/corroborate/__init__.py +11 -0
  38. memory_cli/corroborate/cli.py +267 -0
  39. memory_cli/corroborate/decide.py +893 -0
  40. memory_cli/corroborate/digest.py +425 -0
  41. memory_cli/corroborate/fill.py +744 -0
  42. memory_cli/corroborate/job.py +15 -0
  43. memory_cli/corroborate/reword.py +446 -0
  44. memory_cli/corroborate/run.py +1142 -0
  45. memory_cli/corroborate/state.py +300 -0
  46. memory_cli/digest/__init__.py +4 -0
  47. memory_cli/digest/lessons.py +483 -0
  48. memory_cli/entry/__init__.py +12 -0
  49. memory_cli/entry/auto.py +660 -0
  50. memory_cli/entry/capture.py +1403 -0
  51. memory_cli/entry/corroborate.py +214 -0
  52. memory_cli/entry/integrate.py +684 -0
  53. memory_cli/entry/integrate_self_check.py +203 -0
  54. memory_cli/entry/research.py +9 -0
  55. memory_cli/entry/settle.py +614 -0
  56. memory_cli/entry/split_auto.py +460 -0
  57. memory_cli/entry/synthesize.py +22 -0
  58. memory_cli/integrate/__init__.py +9 -0
  59. memory_cli/integrate/answers.py +42 -0
  60. memory_cli/integrate/briefs/check-brief.md +16 -0
  61. memory_cli/integrate/briefs/place-brief.md +26 -0
  62. memory_cli/integrate/log.py +43 -0
  63. memory_cli/integrate/plan.py +125 -0
  64. memory_cli/integrate/rows.py +99 -0
  65. memory_cli/integrate/state.py +158 -0
  66. memory_cli/integrate/undo.py +143 -0
  67. memory_cli/mem.py +1180 -0
  68. memory_cli/memories/__init__.py +16 -0
  69. memory_cli/memories/fingerprints.py +51 -0
  70. memory_cli/memories/journal.py +93 -0
  71. memory_cli/memories/locations.py +282 -0
  72. memory_cli/memories/matching.py +451 -0
  73. memory_cli/memories/model.py +205 -0
  74. memory_cli/memories/parse.py +237 -0
  75. memory_cli/memories/records.py +266 -0
  76. memory_cli/memories/rules.py +291 -0
  77. memory_cli/memories/sightings.py +314 -0
  78. memory_cli/memories/terms.py +148 -0
  79. memory_cli/memories/write.py +358 -0
  80. memory_cli/notes/__init__.py +13 -0
  81. memory_cli/notes/check.py +806 -0
  82. memory_cli/notes/due.py +260 -0
  83. memory_cli/notes/fields.py +217 -0
  84. memory_cli/notes/index.py +230 -0
  85. memory_cli/notes/links.py +170 -0
  86. memory_cli/notes/note.py +222 -0
  87. memory_cli/notes/search.py +391 -0
  88. memory_cli/notes/split_candidates.py +72 -0
  89. memory_cli/research/__init__.py +5 -0
  90. memory_cli/research/checks.py +1065 -0
  91. memory_cli/research/pipeline.py +952 -0
  92. memory_cli/session/__init__.py +5 -0
  93. memory_cli/session/handoff.py +139 -0
  94. memory_cli/session/notices.py +111 -0
  95. memory_cli/settle/__init__.py +5 -0
  96. memory_cli/settle/state.py +111 -0
  97. memory_cli/settle/verdicts.py +693 -0
  98. memory_cli/split/briefs/checker-brief.md +5 -0
  99. memory_cli/split/briefs/editor-brief.md +20 -0
  100. memory_cli/syntheses/__init__.py +8 -0
  101. memory_cli/syntheses/document.py +400 -0
  102. memory_cli/syntheses/edit.py +581 -0
  103. memory_cli/syntheses/project.py +384 -0
  104. memory_cli/syntheses/split_conservation.py +50 -0
  105. memory_cli/syntheses/units.py +427 -0
  106. memory_cli/synthesize/__init__.py +9 -0
  107. memory_cli/synthesize/backfill.py +431 -0
  108. memory_cli/synthesize/briefs/backfill-brief.md +26 -0
  109. memory_cli/synthesize/briefs/checker-brief.md +13 -0
  110. memory_cli/synthesize/briefs/fixer-brief.md +19 -0
  111. memory_cli/synthesize/briefs/memory-brief.md +30 -0
  112. memory_cli/synthesize/briefs/settle-brief.md +32 -0
  113. memory_cli/synthesize/briefs/verdict-brief.md +50 -0
  114. memory_cli/synthesize/briefs/web-brief.md +33 -0
  115. memory_cli/synthesize/cli.py +311 -0
  116. memory_cli/synthesize/pipeline.py +764 -0
  117. memory_cli/synthesize/references.py +164 -0
  118. memory_cli/synthesize/run.py +150 -0
  119. memory_cli/synthesize/topics.py +528 -0
  120. memory_cli/templates/knowledge.md +23 -0
  121. memory_cli/templates/literature.md +25 -0
  122. memory_cli/templates/research.md +23 -0
  123. memory_cli/templates/synthesis.md +6 -0
  124. memory_cli-0.1.0.dist-info/METADATA +102 -0
  125. memory_cli-0.1.0.dist-info/RECORD +128 -0
  126. memory_cli-0.1.0.dist-info/WHEEL +4 -0
  127. memory_cli-0.1.0.dist-info/entry_points.txt +9 -0
  128. memory_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,16 @@
1
+ """Infrastructure of the background jobs: config, safe writes, the `claude -p` launcher, job lifecycle and state.
2
+
3
+ `auto_state`: `mem-auto` state, run lock, failure line
4
+ `config`: store resolution for every entry point
5
+ `headless`: spec and runner of `claude -p` sessions
6
+ `resources`: package data, the plugin folder when there is one, and the command that starts a child entry point
7
+ `runner`: the `claude` or `codex` runner of a pass: resolution, Codex argv and environment, one `Outcome`
8
+ `codex_pass`: one Codex session of a pass in the shape the builders read, the token cap, the refusal text
9
+ `file_journal`: private rollback journals for file operations
10
+ `jobs`: generic job pieces: status and lock files, run lock, private JSON
11
+ `safe_io`: writes into memory folders that never follow a symlink
12
+ `store_git`: a store that is a git repository: commits at curation points
13
+ `yaml_load`: the engine's YAML parser and plain `safe_load`
14
+
15
+ Imports stdlib and `core` only.
16
+ """
@@ -0,0 +1,30 @@
1
+ """State of the automatic curation run (`bin/mem-auto`), shared with `mem`: where it lives, the store-wide run lock
2
+ and the failure line of the session text. Standard library and `jobs` only.
3
+
4
+ Layout, per store: `<data folder>/auto/<id>/` (mode 0700) holds `run.lock`, `status.json` and `runs/<stamp>/` (logs and
5
+ transcripts, kept 30 days)."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ from pathlib import Path
11
+
12
+ from memory_cli.core import jobs
13
+
14
+
15
+ def auto_dir(data: Path, store: Path) -> Path:
16
+ return Path(data) / "auto" / hashlib.sha1(str(Path(store).resolve()).encode()).hexdigest()[:12]
17
+
18
+
19
+ def run_lock_held(data: Path | None, store: Path) -> bool:
20
+ """True while a run holds the lock. Reads only: no folder is made; any doubt answers False."""
21
+ if data is None:
22
+ return False
23
+ return jobs.lock_held(auto_dir(data, store))
24
+
25
+
26
+ def failure_line(data: Path | None, store: Path | None, now: float) -> str | None:
27
+ """The one line `mem session-index` adds after a failed run; None when there is nothing to show."""
28
+ if data is None or store is None:
29
+ return None
30
+ return jobs.failure_line(auto_dir(data, store), "curation", "mem-auto", now)
@@ -0,0 +1,109 @@
1
+ """One Codex session of a background pass, in the shape the builders already read (ADR 0037).
2
+
3
+ `ask` runs a `headless.Session` through `codex exec` and returns a dict with the keys of `synthesize.pipeline.parse`
4
+ that the builders use (`has_result`, `error`, `answer`, `cost`), plus `tokens` and `raw`. The token cap is the budget
5
+ of a Codex pass (Codex reports tokens, not money); `refusal` is the message of a pass that stays on Claude.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import sys
12
+ from typing import TYPE_CHECKING
13
+
14
+ from memory_cli.core import runner
15
+
16
+ if TYPE_CHECKING:
17
+ from collections.abc import Mapping
18
+ from pathlib import Path
19
+
20
+ from memory_cli.core import headless
21
+
22
+ DEFAULT_TOKEN_CAP = (
23
+ 500_000 # about 44k input tokens of Codex's own prompt per call, observed 2026-11-27
24
+ )
25
+ NO_CODEX = "no codex binary (MEM_CODEX, PATH or the VS Code extension)"
26
+ PRIVATE_MODE = runner.PRIVATE_MODE
27
+ REFUSED_EXIT = 2
28
+
29
+
30
+ def token_cap(env: Mapping[str, str] | None = None) -> int:
31
+ """`MEM_CODEX_TOKENS` when it is a positive integer, else `DEFAULT_TOKEN_CAP`."""
32
+ env = os.environ if env is None else env
33
+ try:
34
+ value = int(env.get("MEM_CODEX_TOKENS", ""))
35
+ except ValueError:
36
+ return DEFAULT_TOKEN_CAP
37
+ return value if value > 0 else DEFAULT_TOKEN_CAP
38
+
39
+
40
+ def over_cap(tokens: int) -> bool:
41
+ return tokens >= token_cap()
42
+
43
+
44
+ def reason(done: dict) -> str:
45
+ """`: <why>` for a failed Codex session (exit code, timeout, stderr presence), else ''; a Claude dict has no `failure`."""
46
+ return f": {done['failure']}" if done.get("failure") else ""
47
+
48
+
49
+ WHY_SHELL = "Codex cannot remove the shell from this step"
50
+ WHY_INTEGRATE = "Codex placed 0 of 17 appends in 4 runs, trial 2026-11-27"
51
+
52
+
53
+ def refusal(pass_name: str, why: str = WHY_SHELL) -> str:
54
+ return (
55
+ f"{pass_name}: runs on Claude only (ADR 0037: {why}); "
56
+ "set runner=claude or pass --runner claude"
57
+ )
58
+
59
+
60
+ def refuse_codex(
61
+ pass_name: str, explicit: str | None = None, *, why: str = WHY_SHELL
62
+ ) -> int | None:
63
+ """For a pass that stays on Claude. An `explicit` request for `codex` (the pass's own `--runner`) prints
64
+ `refusal` to stderr and returns the exit code to end with; an explicit `claude` ends the question. A `codex` that only comes from a default
65
+ (`MEM_RUNNER`, the config file, `MEM_RUNNER_OPTION`) never disables the pass: one line on stderr says the
66
+ default is ignored, the pass runs on Claude, and None is returned. A malformed setting is ignored silently."""
67
+ if explicit == "codex":
68
+ print(refusal(pass_name, why), file=sys.stderr)
69
+ return REFUSED_EXIT
70
+ if explicit == "claude":
71
+ return None
72
+ try:
73
+ chosen = runner.resolve_runner(None)
74
+ except ValueError:
75
+ return None
76
+ if chosen == "codex":
77
+ print(
78
+ f"{pass_name}: the default runner codex is ignored for this pass; it runs on Claude (ADR 0037)",
79
+ file=sys.stderr,
80
+ )
81
+ return None
82
+
83
+
84
+ def ask(session: headless.Session, work: Path, *, writes: bool, timeout: float) -> dict:
85
+ """Runs `session` with Codex in `work`, which is also its sandbox root and holds its HOME. `writes`: the step
86
+ writes a file there (`workspace-write`), else the sandbox is read-only. `FileNotFoundError` when no binary."""
87
+ codex = runner.find_codex()
88
+ if codex is None:
89
+ raise FileNotFoundError(NO_CODEX)
90
+ for sub in ("home", "xdg"):
91
+ (work / sub).mkdir(mode=PRIVATE_MODE, exist_ok=True)
92
+ cmd = runner.codex_command(session, codex, work, writes=writes)
93
+ try:
94
+ raw = runner.run_codex(
95
+ cmd, session.prompt, cwd=work, env=runner.codex_env(work), timeout=timeout
96
+ )
97
+ finally:
98
+ runner.sync_auth(work) # a refreshed token must not be lost, success or not
99
+ runner.drop_codex_home(work) # no credential copy outlives the run
100
+ out = runner.parse_codex(raw.stdout, raw.returncode, raw.stderr, raw.timed_out)
101
+ return {
102
+ "has_result": out.has_result,
103
+ "error": not out.has_result,
104
+ "answer": out.text,
105
+ "cost": 0.0,
106
+ "tokens": out.tokens,
107
+ "raw": raw.stdout,
108
+ "failure": out.error,
109
+ }
@@ -0,0 +1,87 @@
1
+ """Where the note store is: one resolution for every entry point.
2
+
3
+ Precedence, highest first: `--root`/`--store`, `MEM_STORE` (empty counts as unset), the first line of
4
+ `agent-memory/store` under the config folder (stripped), then the default store. Owner rulings 2026-11-26:
5
+ the config file is honoured by every entry point, and the default store counts only when it holds
6
+ `mem-store.yaml`; with neither `HOME` nor `XDG_DATA_HOME` there is no default store.
7
+
8
+ Pure: every function takes the environment as a mapping and imports no engine module. The one exception is
9
+ `~` in a configured path, expanded with `Path.expanduser()` (it reads the process `HOME`) as `mem` always did.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from pathlib import Path
15
+ from typing import TYPE_CHECKING, Literal
16
+
17
+ if TYPE_CHECKING:
18
+ from collections.abc import Mapping
19
+
20
+ STORE_MARKER = "mem-store.yaml"
21
+ APP_DIR = "agent-memory"
22
+
23
+ StoreSource = Literal["--root", "MEM_STORE", "config file", "default"]
24
+
25
+
26
+ def config_dir(env: Mapping[str, str]) -> Path | None:
27
+ """`agent-memory` under XDG_CONFIG_HOME, else under ~/.config; None without either variable."""
28
+ if env.get("XDG_CONFIG_HOME"):
29
+ return Path(env["XDG_CONFIG_HOME"]) / APP_DIR
30
+ if env.get("HOME"):
31
+ return Path(env["HOME"]) / ".config" / APP_DIR
32
+ return None
33
+
34
+
35
+ def config_lines(env: Mapping[str, str], name: str) -> list[str]:
36
+ """The lines of the config file `name`; empty when it is missing or unreadable."""
37
+ base = config_dir(env)
38
+ if base is None:
39
+ return []
40
+ try:
41
+ return (base / name).read_text(encoding="utf-8").splitlines()
42
+ except (OSError, UnicodeDecodeError):
43
+ return []
44
+
45
+
46
+ def default_store_path(env: Mapping[str, str]) -> Path | None:
47
+ """Where the default store lives (`mem init` creates it there), whether or not it exists."""
48
+ if env.get("XDG_DATA_HOME"):
49
+ return Path(env["XDG_DATA_HOME"]) / APP_DIR / "store"
50
+ if env.get("HOME"):
51
+ return Path(env["HOME"]) / ".local" / "share" / APP_DIR / "store"
52
+ return None
53
+
54
+
55
+ def default_store(env: Mapping[str, str]) -> Path | None:
56
+ """The default store when it holds the marker; a folder without it is not ours to write to."""
57
+ path = default_store_path(env)
58
+ return path if path is not None and (path / STORE_MARKER).is_file() else None
59
+
60
+
61
+ def _config_store(env: Mapping[str, str]) -> str:
62
+ lines = config_lines(env, "store")
63
+ return lines[0].strip() if lines else ""
64
+
65
+
66
+ def store_source(arg: str | None, env: Mapping[str, str]) -> StoreSource | None:
67
+ """Which rung of the precedence names the store; None when none does."""
68
+ if arg:
69
+ return "--root"
70
+ if env.get("MEM_STORE"):
71
+ return "MEM_STORE"
72
+ if _config_store(env):
73
+ return "config file"
74
+ if default_store(env) is not None:
75
+ return "default"
76
+ return None
77
+
78
+
79
+ def resolve_store(arg: str | None, env: Mapping[str, str]) -> Path | None:
80
+ """The store folder by the precedence above; a named folder is not checked for existence."""
81
+ source = store_source(arg, env)
82
+ if source is None:
83
+ return None
84
+ if source == "default":
85
+ return default_store(env)
86
+ raw = {"--root": arg, "MEM_STORE": env.get("MEM_STORE")}.get(source) or _config_store(env)
87
+ return Path(raw).expanduser()
@@ -0,0 +1,163 @@
1
+ """Private write-ahead rollback journals for interrupted file operations.
2
+
3
+ Callers hold locked() for the whole operation. Concurrent writers that do not
4
+ use the lock and power loss are outside the journal's guarantees.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import contextlib
11
+ import hashlib
12
+ import json
13
+ import os
14
+ from pathlib import Path
15
+ from typing import TYPE_CHECKING
16
+
17
+ from memory_cli.core import jobs, safe_io
18
+
19
+ if TYPE_CHECKING:
20
+ from collections.abc import Generator, Mapping
21
+
22
+
23
+ SPLIT_VERSION = 2
24
+
25
+
26
+ class DivergedError(OSError):
27
+ """A file differs from both its original and replacement contents."""
28
+
29
+
30
+ class FileJournal:
31
+ def __init__(self, root: Path, directory: str, version: int = 2):
32
+ if not root.is_absolute() or ".." in root.parts:
33
+ raise ValueError("journal root must be absolute and contained")
34
+ if not directory or directory in {".", ".."} or Path(directory).name != directory:
35
+ raise ValueError("invalid journal directory")
36
+ if version not in {1, 2}:
37
+ raise ValueError("invalid journal version")
38
+ self.root = root
39
+ self.directory = directory
40
+ self.version = version
41
+ self.label = "import recovery" if version == 1 else "file recovery"
42
+ self.folder = root / directory
43
+ self.journal = self.folder / "journal.json"
44
+
45
+ def _check_journal(self) -> None:
46
+ safe_io.refuse_symlink_chain(self.root, self.journal)
47
+ safe_io.refuse_symlink_chain(self.root, self.folder / jobs.LOCK_NAME)
48
+
49
+ @contextlib.contextmanager
50
+ def locked(self) -> Generator[None, None, None]:
51
+ self._check_journal()
52
+ fd = jobs.take_run_lock(self.folder)
53
+ if fd is None:
54
+ message = (
55
+ "another import or recovery is running"
56
+ if self.version == 1
57
+ else "another file operation or recovery is running"
58
+ )
59
+ raise BlockingIOError(message)
60
+ try:
61
+ yield
62
+ finally:
63
+ os.close(fd)
64
+
65
+ def pending(self) -> bool:
66
+ self._check_journal()
67
+ return self.journal.exists()
68
+
69
+ def _target(self, path: Path) -> tuple[Path, str]:
70
+ if not path.is_absolute():
71
+ raise ValueError(
72
+ "import path must be absolute"
73
+ if self.version == 1
74
+ else "file path must be absolute"
75
+ )
76
+ relative = path.relative_to(self.root)
77
+ if not relative.parts or ".." in relative.parts or relative.parts[0] == self.directory:
78
+ raise ValueError("invalid import path" if self.version == 1 else "invalid file path")
79
+ target = self.root / relative
80
+ safe_io.refuse_symlink_chain(self.root, target)
81
+ return target, relative.as_posix()
82
+
83
+ def read_original(self, path: Path) -> bytes | None:
84
+ target, _ = self._target(path)
85
+ try:
86
+ return target.read_bytes()
87
+ except FileNotFoundError:
88
+ return None
89
+
90
+ def publish(self, changes: Mapping[Path, tuple[bytes | None, bytes | None]]) -> None: # ruff: ignore[complex-structure]
91
+ if self.pending():
92
+ raise FileExistsError(f"an {self.label} journal already exists")
93
+ entries = []
94
+ for path, (original, after) in changes.items():
95
+ target, relative = self._target(path)
96
+ if original is not None and not isinstance(original, bytes):
97
+ raise TypeError("invalid original contents")
98
+ if after is not None and not isinstance(after, bytes):
99
+ raise TypeError("invalid replacement contents")
100
+ if self.version == 1 and after is None:
101
+ raise ValueError("invalid import recovery digest")
102
+ if self.read_original(target) != original:
103
+ raise ValueError(f"file changed before journal publication: {relative}")
104
+ entries.append({
105
+ "path": relative,
106
+ "original": base64.b64encode(original).decode("ascii")
107
+ if original is not None
108
+ else None,
109
+ "after": hashlib.sha256(after).hexdigest() if after is not None else None,
110
+ })
111
+ self._check_journal()
112
+ jobs.write_json(self.journal, {"version": self.version, "entries": entries})
113
+
114
+ def rollback(self) -> None: # ruff: ignore[complex-structure]
115
+ self._check_journal()
116
+ data = json.loads(self.journal.read_text(encoding="utf-8"))
117
+ if (
118
+ not isinstance(data, dict)
119
+ or data.get("version") != self.version
120
+ or not isinstance(data.get("entries"), list)
121
+ ):
122
+ raise ValueError(f"invalid {self.label} journal")
123
+ restore = []
124
+ diverged = []
125
+ seen = set()
126
+ for row in data["entries"]:
127
+ if not isinstance(row, dict) or not isinstance(row.get("path"), str):
128
+ raise TypeError(f"invalid {self.label} entry")
129
+ target, relative = self._target(self.root / row["path"])
130
+ if self.version == SPLIT_VERSION and ("original" not in row or relative in seen):
131
+ raise ValueError(f"invalid {self.label} entry")
132
+ seen.add(relative)
133
+ original = row.get("original")
134
+ if original is not None:
135
+ original = base64.b64decode(original, validate=True)
136
+ after = row.get("after")
137
+ if not (self.version == SPLIT_VERSION and "after" in row and after is None) and (
138
+ not isinstance(after, str) or len(after) != hashlib.sha256().digest_size * 2
139
+ ):
140
+ raise ValueError(f"invalid {self.label} digest")
141
+ current = self.read_original(target)
142
+ replacement_matches = (
143
+ current is None
144
+ if after is None
145
+ else current is not None and hashlib.sha256(current).hexdigest() == after
146
+ )
147
+ if current != original and not replacement_matches:
148
+ diverged.append(relative)
149
+ restore.append((target, original, current))
150
+ if diverged:
151
+ raise DivergedError(f"{self.label} refused changed files: " + ", ".join(diverged))
152
+ for target, original, current in restore:
153
+ if current == original:
154
+ continue
155
+ safe_io.refuse_symlink_chain(self.root, target)
156
+ if original is None:
157
+ target.unlink()
158
+ else:
159
+ safe_io.replace_file(target, original)
160
+
161
+ def clear(self) -> None:
162
+ self._check_journal()
163
+ self.journal.unlink()
@@ -0,0 +1,130 @@
1
+ """The spec and the runner of `claude -p` sessions, shared by every builder that starts one.
2
+
3
+ Standard library only; it imports no plugin module."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import codecs
8
+ import os
9
+ import subprocess
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any, NamedTuple
13
+
14
+ SESSION_VARS = (
15
+ "CLAUDE_ENV_FILE",
16
+ "CLAUDE_PID",
17
+ "CLAUDE_PROJECT_DIR",
18
+ "CLAUDE_CODE_SESSION_ID",
19
+ "CLAUDE_CODE_MESSAGING_SOCKET",
20
+ "CLAUDE_CODE_MESSAGING_TOKEN",
21
+ )
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Session:
26
+ claude: str
27
+ prompt: str
28
+ model: str
29
+ settings: Path
30
+ effort: str | None = None
31
+ plugin_dir: Path | None = None
32
+ tools: tuple[str, ...] | None = None
33
+ allowed: tuple[str, ...] = ()
34
+ disallowed: tuple[str, ...] = ()
35
+ max_budget: float | None = None
36
+ agent: str | None = None
37
+
38
+
39
+ class Raw(NamedTuple):
40
+ stdout: str
41
+ timed_out: bool
42
+
43
+
44
+ def _flag(name: str, value: object | None) -> list[str]:
45
+ return [] if value is None else [name, str(value)]
46
+
47
+
48
+ def _values(name: str, values: tuple[str, ...]) -> list[str]:
49
+ return [name, *values] if values else []
50
+
51
+
52
+ def command(session: Session) -> list[str]:
53
+ """The argv of a session. The CLI reads flags by name, so the order is canonical, not any builder's old one."""
54
+ tools = None if session.tools is None else ",".join(session.tools)
55
+ budget = None if session.max_budget is None else f"{session.max_budget:.4f}"
56
+ return [
57
+ session.claude,
58
+ "-p",
59
+ session.prompt,
60
+ "--model",
61
+ session.model,
62
+ *_flag("--effort", session.effort),
63
+ *_flag("--plugin-dir", session.plugin_dir),
64
+ "--settings",
65
+ str(session.settings),
66
+ "--setting-sources",
67
+ "project",
68
+ *_flag("--tools", tools),
69
+ "--strict-mcp-config",
70
+ *_values("--allowedTools", session.allowed),
71
+ *_values("--disallowedTools", session.disallowed),
72
+ "--output-format",
73
+ "stream-json",
74
+ "--verbose",
75
+ "--no-session-persistence",
76
+ *_flag("--max-budget-usd", budget),
77
+ *_flag("--agent", session.agent),
78
+ ]
79
+
80
+
81
+ def run_raw(
82
+ cmd: list[str],
83
+ *,
84
+ cwd: Path,
85
+ env: dict[str, str],
86
+ timeout: float,
87
+ errors: str | None = None,
88
+ ) -> Raw:
89
+ """Run a session; a timeout returns the partial stdout with `timed_out=True`, an `OSError` propagates."""
90
+ kwargs: dict[str, Any] = {
91
+ "cwd": cwd,
92
+ "env": env,
93
+ "stdin": subprocess.DEVNULL,
94
+ "capture_output": True,
95
+ "text": True,
96
+ "timeout": timeout,
97
+ }
98
+ if errors is not None:
99
+ kwargs["errors"] = errors
100
+ try:
101
+ done = subprocess.run(cmd, check=False, **kwargs)
102
+ except subprocess.TimeoutExpired as exc:
103
+ partial = exc.stdout
104
+ if isinstance(partial, bytes):
105
+ # A cut inside a multibyte character drops that fragment only; other invalid bytes keep `errors`.
106
+ decoder = codecs.getincrementaldecoder("utf-8")(errors=errors or "strict")
107
+ partial = decoder.decode(partial, final=False)
108
+ return Raw(partial or "", True)
109
+ return Raw(done.stdout, False)
110
+
111
+
112
+ def has_mem(folder: str) -> bool:
113
+ try:
114
+ return os.access(Path(folder) / "mem", os.X_OK) and (Path(folder) / "mem").is_file()
115
+ except OSError:
116
+ return False
117
+
118
+
119
+ def session_env() -> dict[str, str]:
120
+ """The environment of every model session: no `MEM_*`, no `CLAUDE_PLUGIN_*`, no session variable of the process
121
+ that started this one, and a PATH without any folder that holds `mem`."""
122
+ env = {
123
+ k: v
124
+ for k, v in os.environ.items()
125
+ if not k.startswith(("MEM_", "CLAUDE_PLUGIN")) and k not in SESSION_VARS
126
+ }
127
+ env["PATH"] = os.pathsep.join(
128
+ p for p in env.get("PATH", "").split(os.pathsep) if p and not has_mem(p)
129
+ )
130
+ return env
@@ -0,0 +1,130 @@
1
+ """Generic pieces of the background jobs (`bin/mem-auto`, `bin/mem-settle`, `bin/mem-integrate`, capture, corroborate): the status and lock
2
+ file names, the private state folder, the run lock, private JSON files and the failure of the last runs. Standard
3
+ library and `safe_io` only."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import datetime
8
+ import fcntl
9
+ import json
10
+ import os
11
+ import shutil
12
+ from pathlib import Path
13
+
14
+ from memory_cli.core import safe_io
15
+
16
+ STALE_RUNNING_SECONDS = 3600 # a `running` status older than this is a run that was killed
17
+ LOCK_NAME = "run.lock"
18
+ STATUS_NAME = "status.json"
19
+
20
+
21
+ def state_dir() -> Path:
22
+ """The data folder: MEM_DATA, else `$XDG_STATE_HOME/agent-memory` (default `~/.local/state`); empty values count as unset."""
23
+ if os.environ.get("MEM_DATA"):
24
+ return Path(os.environ["MEM_DATA"])
25
+ state = os.environ.get("XDG_STATE_HOME") or str(Path.home() / ".local" / "state")
26
+ return Path(state) / "agent-memory"
27
+
28
+
29
+ def private_dir(path: Path) -> None:
30
+ """Create `path` with every missing parent at mode 0700 (the umask would give 0755)."""
31
+ missing = []
32
+ while not path.exists():
33
+ missing.append(path)
34
+ path = path.parent
35
+ for folder in reversed(missing):
36
+ try:
37
+ folder.mkdir(mode=0o700)
38
+ except FileExistsError:
39
+ continue
40
+ os.chmod(folder, 0o700)
41
+
42
+
43
+ def take_run_lock(adir: Path) -> int | None:
44
+ """The store-wide run lock as an open descriptor (closing it releases it), or None when a run holds it."""
45
+ private_dir(adir)
46
+ fd = os.open(adir / LOCK_NAME, os.O_RDWR | os.O_CREAT, 0o600)
47
+ try:
48
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
49
+ except BlockingIOError:
50
+ os.close(fd)
51
+ return None
52
+ return fd
53
+
54
+
55
+ def lock_held(folder: Path) -> bool:
56
+ """True while a run holds the lock in `folder`. Reads only: no folder is made; any doubt answers False."""
57
+ path = folder / LOCK_NAME
58
+ try:
59
+ fd = os.open(path, os.O_RDWR)
60
+ except OSError:
61
+ return False
62
+ try:
63
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
64
+ except BlockingIOError:
65
+ return True
66
+ except OSError:
67
+ return False
68
+ finally:
69
+ os.close(fd)
70
+ return False
71
+
72
+
73
+ def read_json(path: Path) -> dict:
74
+ try:
75
+ data = json.loads(path.read_text(encoding="utf-8"))
76
+ except (OSError, ValueError):
77
+ return {}
78
+ return data if isinstance(data, dict) else {}
79
+
80
+
81
+ def write_json(path: Path, data: dict) -> None:
82
+ safe_io.replace_file(path, json.dumps(data).encode("utf-8"), mode=0o600)
83
+
84
+
85
+ def failure(status: dict, now: float) -> dict | None:
86
+ """The unacknowledged failure of the last runs: `{at, reason, log}`, or None."""
87
+ found = status.get("failure")
88
+ if isinstance(found, dict) and found.get("reason"):
89
+ return found
90
+ started = status.get("started")
91
+ if (
92
+ status.get("state") == "running"
93
+ and isinstance(started, (int, float))
94
+ and now - started > STALE_RUNNING_SECONDS
95
+ ):
96
+ return {"at": started, "reason": "the run did not finish", "log": status.get("log", "")}
97
+ return None
98
+
99
+
100
+ def append_log(cdir: Path, line: dict) -> None:
101
+ """Append `line` as one JSON line to `cdir/log.jsonl` (private folder, file mode 0600)."""
102
+ private_dir(cdir)
103
+ fd = os.open(cdir / "log.jsonl", os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
104
+ with os.fdopen(fd, "a", encoding="utf-8") as f:
105
+ f.write(json.dumps(line, ensure_ascii=False) + "\n")
106
+
107
+
108
+ def prune_runs_older(runs: Path, now: float, keep_seconds: float) -> None:
109
+ """Remove the entries of `runs` last modified more than `keep_seconds` before `now`; no folder is made."""
110
+ if not runs.is_dir():
111
+ return
112
+ for folder in runs.iterdir():
113
+ try:
114
+ if now - folder.stat().st_mtime > keep_seconds:
115
+ shutil.rmtree(folder, ignore_errors=True)
116
+ except OSError:
117
+ continue
118
+
119
+
120
+ def failure_line(folder: Path, kind: str, ack: str, now: float) -> str | None:
121
+ """The one line `mem session-index` adds after a failed `kind` run of the job whose status is in `folder`."""
122
+ found = failure(read_json(folder / STATUS_NAME), now)
123
+ if found is None:
124
+ return None
125
+ when = datetime.datetime.fromtimestamp(float(found.get("at") or now)).date().isoformat()
126
+ reason = " ".join(str(found["reason"]).split())[:200]
127
+ return (
128
+ f"Automatic {kind} failed on {when}: {reason}; log: {found.get('log') or '(none)'} "
129
+ f"({ack} ack clears this)."
130
+ )