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,57 @@
|
|
|
1
|
+
"""The only module that derives a path from `__file__`: package data, the plugin folder and the child-process command.
|
|
2
|
+
|
|
3
|
+
Three kinds of lookup, so a caller names its need and never counts `parents[N]`:
|
|
4
|
+
|
|
5
|
+
- package data (`TEMPLATES`, the `*_BRIEFS` folders) ships inside the wheel and is always there;
|
|
6
|
+
- the plugin folder (`plugin_root`) exists only while the engine runs from the plugin's source tree (`engine/..`
|
|
7
|
+
holding `hooks/`); an installed `memory-cli` has none;
|
|
8
|
+
- a child entry point (`mem_command`, `child_env`) always starts from the running installation: its interpreter and
|
|
9
|
+
`-m memory_cli`, never a `mem` found on `PATH`, which may be an older copy.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import shutil
|
|
14
|
+
import sys
|
|
15
|
+
from collections.abc import Mapping
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
PACKAGE_DIR = Path(__file__).resolve().parents[1]
|
|
19
|
+
TEMPLATES = PACKAGE_DIR / "templates"
|
|
20
|
+
MEM_PY = PACKAGE_DIR / "mem.py" # `mem stats` counts this file by name
|
|
21
|
+
INTEGRATE_BRIEFS = PACKAGE_DIR / "integrate" / "briefs"
|
|
22
|
+
SPLIT_BRIEFS = PACKAGE_DIR / "split" / "briefs"
|
|
23
|
+
SYNTHESIZE_BRIEFS = PACKAGE_DIR / "synthesize" / "briefs"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def plugin_root() -> Path | None:
|
|
27
|
+
"""The plugin folder this source tree sits in (`engine/..` when it holds `hooks/`), else None."""
|
|
28
|
+
root = PACKAGE_DIR.parent.parent
|
|
29
|
+
return root if (root / "hooks").is_dir() else None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def mem_command(entry: str | None = None) -> list[str]:
|
|
33
|
+
"""argv prefix that runs `mem`, or the console script `entry` (`mem-settle`, ...), from this installation.
|
|
34
|
+
|
|
35
|
+
`-P` keeps the working folder (a project or store) off `sys.path`, so a stray `yaml.py` there cannot shadow
|
|
36
|
+
a dependency."""
|
|
37
|
+
return [sys.executable, "-P", "-m", "memory_cli", *(["--bin", entry] if entry else [])]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def child_env(env: Mapping[str, str] | None = None) -> dict[str, str]:
|
|
41
|
+
"""`env` (the current one when None) with the folder that holds `memory_cli` first on `PYTHONPATH`.
|
|
42
|
+
|
|
43
|
+
Harmless once installed; it is what lets `-m memory_cli` find the package when the plugin runs from source."""
|
|
44
|
+
result = dict(os.environ if env is None else env)
|
|
45
|
+
parts = [str(PACKAGE_DIR.parent), *filter(None, result.get("PYTHONPATH", "").split(os.pathsep))]
|
|
46
|
+
result["PYTHONPATH"] = os.pathsep.join(parts)
|
|
47
|
+
return result
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def shell_mem() -> str:
|
|
51
|
+
"""The `mem` a host agent or a shell should run: the plugin's `bin/mem`, else the console script that sits next
|
|
52
|
+
to the running interpreter, else the bare name."""
|
|
53
|
+
root = plugin_root()
|
|
54
|
+
if root is not None:
|
|
55
|
+
return str(root / "bin" / "mem")
|
|
56
|
+
beside = Path(sys.executable).parent / "mem"
|
|
57
|
+
return str(beside) if beside.is_file() else shutil.which("mem") or "mem"
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
"""The runner of a background pass: `claude` or `codex` (ADR 0037).
|
|
2
|
+
|
|
3
|
+
Resolution, the Codex binary, its argv and environment, its JSON-lines output, and one normalized `Outcome` for
|
|
4
|
+
both runners. Standard library plus `core`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import codecs
|
|
10
|
+
import contextlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import shutil
|
|
15
|
+
import signal
|
|
16
|
+
import subprocess
|
|
17
|
+
import tempfile
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import TYPE_CHECKING, Any, NamedTuple
|
|
21
|
+
|
|
22
|
+
from memory_cli.core import config, headless
|
|
23
|
+
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
import argparse
|
|
26
|
+
from collections.abc import Mapping
|
|
27
|
+
|
|
28
|
+
RUNNERS = ("claude", "codex")
|
|
29
|
+
PRIVATE_MODE = 0o700
|
|
30
|
+
|
|
31
|
+
# (claude tier, effort) -> (codex model, codex effort). A copy of what `scripts/port.py` derives from
|
|
32
|
+
# `shared/models.toml` (the installed plugin has no `shared/`); `scripts/tests/test_runner_models.py` keeps them equal.
|
|
33
|
+
CODEX_MODELS: dict[tuple[str, str], tuple[str, str]] = {
|
|
34
|
+
("haiku", "low"): ("gpt-6-luna", "low"),
|
|
35
|
+
("haiku", "medium"): ("gpt-6-luna", "low"),
|
|
36
|
+
("haiku", "high"): ("gpt-6-luna", "medium"),
|
|
37
|
+
("sonnet", "low"): ("gpt-6-luna", "high"),
|
|
38
|
+
("sonnet", "medium"): ("gpt-6.1-terra", "low"),
|
|
39
|
+
("sonnet", "high"): ("gpt-6.1-terra", "medium"),
|
|
40
|
+
("opus", "low"): ("gpt-6.2-sol", "low"),
|
|
41
|
+
("opus", "medium"): ("gpt-6.2-sol", "low"),
|
|
42
|
+
("opus", "high"): ("gpt-6.2-sol", "medium"),
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _choice(value: str, source: str) -> str:
|
|
47
|
+
if value not in RUNNERS:
|
|
48
|
+
raise ValueError(f"{source}: runner {value!r} is not one of {', '.join(RUNNERS)}")
|
|
49
|
+
return value
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def resolve_runner(flag: str | None, env: Mapping[str, str] | None = None) -> str:
|
|
53
|
+
"""The first set of `--runner`, `MEM_RUNNER`, the `runner` config file (first line), `MEM_RUNNER_OPTION`
|
|
54
|
+
(the plugin setting), then `claude`; an empty value counts as unset, an invalid one raises naming its source."""
|
|
55
|
+
env = os.environ if env is None else env
|
|
56
|
+
lines = config.config_lines(env, "runner")
|
|
57
|
+
sources = (
|
|
58
|
+
("--runner", flag or ""),
|
|
59
|
+
("MEM_RUNNER", env.get("MEM_RUNNER", "")),
|
|
60
|
+
("the runner config file", lines[0].strip() if lines else ""),
|
|
61
|
+
("MEM_RUNNER_OPTION", env.get("MEM_RUNNER_OPTION", "")),
|
|
62
|
+
)
|
|
63
|
+
for source, value in sources:
|
|
64
|
+
if value.strip():
|
|
65
|
+
return _choice(value.strip(), source)
|
|
66
|
+
return "claude"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def add_flag(parser: argparse.ArgumentParser) -> None:
|
|
70
|
+
"""`--runner` for a pass command; `pin_flag(args.runner)` applies it."""
|
|
71
|
+
parser.add_argument(
|
|
72
|
+
"--runner",
|
|
73
|
+
choices=RUNNERS,
|
|
74
|
+
help="claude or codex; outranks MEM_RUNNER, the runner config file and the plugin option (default claude)",
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def pin_flag(flag: str | None) -> None:
|
|
79
|
+
"""Make `--runner` outrank every other source for the rest of the process: `resolve_runner` reads `MEM_RUNNER`
|
|
80
|
+
right after the flag, so setting it once at the entry reaches every call site."""
|
|
81
|
+
if flag:
|
|
82
|
+
os.environ["MEM_RUNNER"] = flag
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _extension_version(binary: Path) -> tuple[int, ...]:
|
|
86
|
+
"""`openai.chatgpt-26.1120.41243-linux-x64` -> (26, 1120, 41243)."""
|
|
87
|
+
found = re.search(r"openai\.chatgpt-([\d.]+)", binary.parent.parent.parent.name)
|
|
88
|
+
return tuple(int(n) for n in found.group(1).split(".") if n) if found else ()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def find_codex(env: Mapping[str, str] | None = None) -> str | None:
|
|
92
|
+
"""`MEM_CODEX` (when it is an executable file), then `codex` on PATH, then the newest VS Code extension's binary.
|
|
93
|
+
Found at run time, never stored; a `MEM_CODEX` that is missing or not executable falls through."""
|
|
94
|
+
env = os.environ if env is None else env
|
|
95
|
+
chosen = env.get("MEM_CODEX")
|
|
96
|
+
if chosen and Path(chosen).is_file() and os.access(chosen, os.X_OK):
|
|
97
|
+
return chosen
|
|
98
|
+
on_path = shutil.which("codex", path=env.get("PATH"))
|
|
99
|
+
if on_path:
|
|
100
|
+
return on_path
|
|
101
|
+
home = Path(env["HOME"]) if env.get("HOME") else Path.home()
|
|
102
|
+
found = [
|
|
103
|
+
p
|
|
104
|
+
for p in home.glob(".vscode*/extensions/openai.chatgpt-*/bin/*/codex")
|
|
105
|
+
if p.is_file() and os.access(p, os.X_OK)
|
|
106
|
+
]
|
|
107
|
+
return str(max(found, key=_extension_version)) if found else None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def codex_model(session: headless.Session) -> tuple[str, str]:
|
|
111
|
+
"""The Codex (model, effort) of a session; no effort counts as `medium`. `ValueError` names an unmapped pair."""
|
|
112
|
+
pair = (session.model, session.effort or "medium")
|
|
113
|
+
try:
|
|
114
|
+
return CODEX_MODELS[pair]
|
|
115
|
+
except KeyError:
|
|
116
|
+
raise ValueError(f"no Codex model for (model, effort) = {pair!r}") from None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def codex_command(
|
|
120
|
+
session: headless.Session, codex: str, run_dir: Path, *, writes: bool
|
|
121
|
+
) -> list[str]:
|
|
122
|
+
"""The argv of a Codex session, prompt on stdin (`-`).
|
|
123
|
+
|
|
124
|
+
The Session's `tools`, `allowed`, `disallowed`, `agent`, `plugin_dir`, `max_budget` and `settings` have no Codex
|
|
125
|
+
equivalent and are ignored: the sandbox (`read-only` or `workspace-write` limited to `run_dir`) and the
|
|
126
|
+
environment from `codex_env` are the isolation, and the token cap is enforced by the caller from `Outcome.tokens`.
|
|
127
|
+
"""
|
|
128
|
+
model, effort = codex_model(session)
|
|
129
|
+
return [
|
|
130
|
+
codex,
|
|
131
|
+
"exec",
|
|
132
|
+
"--json",
|
|
133
|
+
"--ephemeral",
|
|
134
|
+
"--ignore-user-config",
|
|
135
|
+
"--disable",
|
|
136
|
+
"hooks",
|
|
137
|
+
"--skip-git-repo-check",
|
|
138
|
+
"-s",
|
|
139
|
+
"workspace-write" if writes else "read-only",
|
|
140
|
+
"-C",
|
|
141
|
+
str(run_dir),
|
|
142
|
+
"-m",
|
|
143
|
+
model,
|
|
144
|
+
"-c",
|
|
145
|
+
f"model_reasoning_effort={effort}",
|
|
146
|
+
"-",
|
|
147
|
+
]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _real_codex_home() -> Path:
|
|
151
|
+
return Path(
|
|
152
|
+
os.environ.get("CODEX_HOME") or Path(os.environ.get("HOME") or Path.home()) / ".codex"
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _tokens(auth: object) -> dict:
|
|
157
|
+
"""The `tokens` object of a parsed `auth.json`, or `{}` for any other shape."""
|
|
158
|
+
tokens = auth.get("tokens") if isinstance(auth, dict) else None
|
|
159
|
+
return tokens if isinstance(tokens, dict) else {}
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _same_account(content: str, real: Path) -> bool:
|
|
163
|
+
"""The per-run file is a refresh of the real login: same `tokens.account_id`, non-empty tokens. The run folder
|
|
164
|
+
is the sandbox's writable root, so a model could plant any file there; this keeps it from logging the owner
|
|
165
|
+
out or swapping in another account. No real file means no login to refresh: `OSError`, so no sync. Raises
|
|
166
|
+
`ValueError` or `OSError` on unreadable input."""
|
|
167
|
+
fresh_tokens = _tokens(json.loads(content))
|
|
168
|
+
real_tokens = _tokens(json.loads(real.read_text(encoding="utf-8")))
|
|
169
|
+
return bool(
|
|
170
|
+
real_tokens.get("account_id")
|
|
171
|
+
and fresh_tokens.get("account_id") == real_tokens.get("account_id")
|
|
172
|
+
and fresh_tokens.get("access_token")
|
|
173
|
+
and fresh_tokens.get("refresh_token")
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def sync_auth(run_dir: Path) -> bool:
|
|
178
|
+
"""After a Codex run: when Codex replaced the `auth.json` symlink of `codex_env` with a regular file (write a
|
|
179
|
+
temp file, rename it over), that file holds the token Codex refreshed and the real one may hold a rotated-out
|
|
180
|
+
refresh token. A regular, newer file of the same account (`_same_account`) replaces the real `auth.json`
|
|
181
|
+
atomically (mode 0600, same folder); a real path that is a symlink is left alone. An in-place write needs
|
|
182
|
+
nothing: it went through the link. Never logs the token. True when it synced."""
|
|
183
|
+
fresh = run_dir / "codex-home" / "auth.json"
|
|
184
|
+
real = _real_codex_home() / "auth.json"
|
|
185
|
+
try:
|
|
186
|
+
if fresh.is_symlink() or not fresh.is_file() or real.is_symlink():
|
|
187
|
+
return False
|
|
188
|
+
if real.exists() and fresh.stat().st_mtime <= real.stat().st_mtime:
|
|
189
|
+
return False
|
|
190
|
+
content = fresh.read_text(encoding="utf-8")
|
|
191
|
+
if not _same_account(content, real):
|
|
192
|
+
return False
|
|
193
|
+
fd, tmp = tempfile.mkstemp(dir=real.parent, prefix=".auth-")
|
|
194
|
+
except (OSError, ValueError):
|
|
195
|
+
return False
|
|
196
|
+
try:
|
|
197
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
198
|
+
handle.write(content)
|
|
199
|
+
Path(tmp).chmod(0o600)
|
|
200
|
+
Path(tmp).replace(real)
|
|
201
|
+
except OSError:
|
|
202
|
+
Path(tmp).unlink(missing_ok=True)
|
|
203
|
+
return False
|
|
204
|
+
return True
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def drop_codex_home(run_dir: Path) -> None:
|
|
208
|
+
"""After `sync_auth`: remove the run's `codex-home`, so no copy of a credential outlives the run (run folders
|
|
209
|
+
are kept until pruned). Kept only when it holds a refreshed token that could not be synced because the real
|
|
210
|
+
`auth.json` is a symlink: deleting it would lose that token."""
|
|
211
|
+
home = run_dir / "codex-home"
|
|
212
|
+
fresh = home / "auth.json"
|
|
213
|
+
real = _real_codex_home() / "auth.json"
|
|
214
|
+
with contextlib.suppress(OSError):
|
|
215
|
+
if fresh.is_file() and not fresh.is_symlink() and real.is_symlink():
|
|
216
|
+
return
|
|
217
|
+
shutil.rmtree(home)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def codex_env(run_dir: Path) -> dict[str, str]:
|
|
221
|
+
"""`session_env()` with HOME and the XDG folders inside `run_dir`, and a clean `CODEX_HOME` there.
|
|
222
|
+
|
|
223
|
+
Codex's model shell is a login shell that re-sources `~/.profile`, which would put `mem` back on PATH
|
|
224
|
+
(observed 2026-11-27); with HOME in the run folder it finds nothing. The real `CODEX_HOME` would also load the
|
|
225
|
+
owner's `AGENTS.md` and plugins into the prompt (`project_doc_max_bytes=0` does not drop them), so
|
|
226
|
+
`<run_dir>/codex-home` (mode 0700) holds only a symlink to the real `auth.json`; the credential is never
|
|
227
|
+
copied, and without a real `auth.json` the link is left out and Codex reports the missing login itself."""
|
|
228
|
+
env = headless.session_env()
|
|
229
|
+
real_codex = _real_codex_home()
|
|
230
|
+
clean = run_dir / "codex-home"
|
|
231
|
+
clean.mkdir(mode=PRIVATE_MODE, parents=True, exist_ok=True)
|
|
232
|
+
link = clean / "auth.json"
|
|
233
|
+
if (real_codex / "auth.json").is_file() and not link.is_symlink():
|
|
234
|
+
link.symlink_to(real_codex / "auth.json")
|
|
235
|
+
env["CODEX_HOME"] = str(clean)
|
|
236
|
+
env["HOME"] = str(run_dir / "home")
|
|
237
|
+
for var, sub in (
|
|
238
|
+
("XDG_CONFIG_HOME", "config"),
|
|
239
|
+
("XDG_STATE_HOME", "state"),
|
|
240
|
+
("XDG_DATA_HOME", "data"),
|
|
241
|
+
("XDG_CACHE_HOME", "cache"),
|
|
242
|
+
):
|
|
243
|
+
env[var] = str(run_dir / "xdg" / sub)
|
|
244
|
+
return env
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
class CodexRaw(NamedTuple):
|
|
248
|
+
stdout: str
|
|
249
|
+
timed_out: bool
|
|
250
|
+
returncode: int | None
|
|
251
|
+
stderr: str = ""
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _text(data: str | bytes | None) -> str:
|
|
255
|
+
if isinstance(data, bytes):
|
|
256
|
+
return codecs.getincrementaldecoder("utf-8")(errors="replace").decode(data, final=False)
|
|
257
|
+
return data or ""
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def run_codex(
|
|
261
|
+
cmd: list[str], prompt: str, *, cwd: Path, env: dict[str, str], timeout: float
|
|
262
|
+
) -> CodexRaw:
|
|
263
|
+
"""Run a Codex session with the prompt on stdin (closed after it); output decoded as UTF-8 with replacement. A
|
|
264
|
+
timeout returns the partial output with `timed_out=True` and no return code, an `OSError` propagates."""
|
|
265
|
+
process = subprocess.Popen(
|
|
266
|
+
cmd,
|
|
267
|
+
cwd=cwd,
|
|
268
|
+
env=env,
|
|
269
|
+
stdin=subprocess.PIPE,
|
|
270
|
+
stdout=subprocess.PIPE,
|
|
271
|
+
stderr=subprocess.PIPE,
|
|
272
|
+
start_new_session=True,
|
|
273
|
+
)
|
|
274
|
+
try:
|
|
275
|
+
stdout, stderr = process.communicate(prompt.encode("utf-8"), timeout=timeout)
|
|
276
|
+
except subprocess.TimeoutExpired as exc:
|
|
277
|
+
with contextlib.suppress(ProcessLookupError):
|
|
278
|
+
os.killpg(process.pid, signal.SIGKILL)
|
|
279
|
+
for pipe in (process.stdin, process.stdout, process.stderr):
|
|
280
|
+
if pipe is not None:
|
|
281
|
+
pipe.close()
|
|
282
|
+
process.wait()
|
|
283
|
+
return CodexRaw(_text(exc.stdout), True, None, _text(exc.stderr))
|
|
284
|
+
return CodexRaw(_text(stdout), False, process.returncode, _text(stderr))
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
@dataclass(frozen=True)
|
|
288
|
+
class Outcome:
|
|
289
|
+
"""What a builder needs from one session, whichever runner ran it.
|
|
290
|
+
|
|
291
|
+
`has_result`: a usable final answer exists (Claude: a `result` event that is not an error; Codex: also a
|
|
292
|
+
completed turn and exit 0). `error`: why the run failed, non-empty exactly when `has_result` is False, for both
|
|
293
|
+
runners. `text`: the final answer (Claude: also the error text of a failed run). `tokens`: Codex: input (cached
|
|
294
|
+
included) plus output, so the cap of a Codex pass counts Codex's own ~44k-token prompt on every call; Claude:
|
|
295
|
+
informational only (Claude budgets stay in USD). `cost_usd`: Claude's reported cost, 0.0 for Codex. `commands`:
|
|
296
|
+
(command, exit code or None) the session ran, Codex only (Claude's tool calls are tallied by the
|
|
297
|
+
synthesizer)."""
|
|
298
|
+
|
|
299
|
+
has_result: bool
|
|
300
|
+
text: str = ""
|
|
301
|
+
tokens: int = 0
|
|
302
|
+
cost_usd: float = 0.0
|
|
303
|
+
commands: list[tuple[str, int | None]] = field(default_factory=list)
|
|
304
|
+
error: str = ""
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _events(stdout: str) -> list[dict[str, Any]]:
|
|
308
|
+
events = []
|
|
309
|
+
for line in stdout.splitlines():
|
|
310
|
+
try:
|
|
311
|
+
event = json.loads(line)
|
|
312
|
+
except ValueError:
|
|
313
|
+
continue
|
|
314
|
+
if isinstance(event, dict):
|
|
315
|
+
events.append(event)
|
|
316
|
+
return events
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _count(usage: Any, *names: str) -> int:
|
|
320
|
+
if not isinstance(usage, dict):
|
|
321
|
+
return 0
|
|
322
|
+
return sum(v for n in names if isinstance(v := usage.get(n), int))
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def claude_outcome(stdout: str) -> Outcome:
|
|
326
|
+
"""Normalize a `stream-json` session: the last `result` event gives text, cost, usage and `is_error`."""
|
|
327
|
+
final = next((e for e in reversed(_events(stdout)) if e.get("type") == "result"), None)
|
|
328
|
+
if final is None:
|
|
329
|
+
return Outcome(False, error="no result event")
|
|
330
|
+
text = final.get("result") or ""
|
|
331
|
+
failed = bool(final.get("is_error"))
|
|
332
|
+
return Outcome(
|
|
333
|
+
not failed,
|
|
334
|
+
text=text,
|
|
335
|
+
tokens=_count(
|
|
336
|
+
final.get("usage"), "input_tokens", "cache_creation_input_tokens", "output_tokens"
|
|
337
|
+
),
|
|
338
|
+
cost_usd=float(final.get("total_cost_usd") or 0.0),
|
|
339
|
+
error=(text or "the session reported an error") if failed else "",
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _item(event: dict[str, Any]) -> dict[str, Any]:
|
|
344
|
+
item = event.get("item")
|
|
345
|
+
return item if isinstance(item, dict) else {}
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
@dataclass
|
|
349
|
+
class _Tally:
|
|
350
|
+
text: str = ""
|
|
351
|
+
tokens: int = 0
|
|
352
|
+
completed: bool = False
|
|
353
|
+
commands: list[tuple[str, int | None]] = field(default_factory=list)
|
|
354
|
+
errors: list[str] = field(default_factory=list)
|
|
355
|
+
|
|
356
|
+
def add(self, event: dict[str, Any]) -> None:
|
|
357
|
+
kind = event.get("type")
|
|
358
|
+
item = _item(event)
|
|
359
|
+
if kind == "item.completed":
|
|
360
|
+
self._item(item)
|
|
361
|
+
elif kind == "turn.completed":
|
|
362
|
+
self.completed = True
|
|
363
|
+
self.tokens += _count(event.get("usage"), "input_tokens", "output_tokens")
|
|
364
|
+
elif kind in {"turn.failed", "error"}:
|
|
365
|
+
self.errors.append(str(kind))
|
|
366
|
+
|
|
367
|
+
def _item(self, item: dict[str, Any]) -> None:
|
|
368
|
+
if item.get("type") == "agent_message":
|
|
369
|
+
self.text = item.get("text") or ""
|
|
370
|
+
elif item.get("type") == "command_execution":
|
|
371
|
+
self.commands.append((item.get("command") or "", item.get("exit_code")))
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _failure(tally: _Tally, returncode: int | None, stderr: str, timed_out: bool) -> str:
|
|
375
|
+
reasons = list(tally.errors)
|
|
376
|
+
if timed_out:
|
|
377
|
+
reasons.append("the session timed out")
|
|
378
|
+
elif not reasons:
|
|
379
|
+
reasons.append("no final message" if tally.completed else "the session did not complete")
|
|
380
|
+
if returncode not in {0, None}:
|
|
381
|
+
reasons.append(f"exit {returncode}")
|
|
382
|
+
if stderr:
|
|
383
|
+
reasons.append("stderr present")
|
|
384
|
+
return "; ".join(reasons)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def parse_codex(
|
|
388
|
+
stdout: str, returncode: int | None, stderr: str = "", timed_out: bool = False
|
|
389
|
+
) -> Outcome:
|
|
390
|
+
"""Normalize `codex exec --json` events. `has_result` needs a `turn.completed`, an agent message and exit 0;
|
|
391
|
+
`error` is empty then, else event types, a timeout, exit code and whether stderr was present.
|
|
392
|
+
`tokens` sums `input_tokens` and `output_tokens` (cached and reasoning tokens are parts of those)."""
|
|
393
|
+
tally = _Tally()
|
|
394
|
+
for event in _events(stdout):
|
|
395
|
+
tally.add(event)
|
|
396
|
+
has_result = tally.completed and bool(tally.text) and returncode == 0 and not timed_out
|
|
397
|
+
error = "" if has_result else _failure(tally, returncode, stderr, timed_out)
|
|
398
|
+
return Outcome(has_result, tally.text, tally.tokens, 0.0, tally.commands, error)
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Writes into memory folders that never follow a symlink.
|
|
2
|
+
|
|
3
|
+
A cloned repository can ship a `.memory/` folder with planted symlinks; a write that follows one would
|
|
4
|
+
overwrite a file elsewhere. Files are replaced through an unpredictable temporary name (`os.replace` swaps a
|
|
5
|
+
symlink at the target itself, never what it points to) and logs are appended with `O_NOFOLLOW`."""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
import os
|
|
11
|
+
import stat
|
|
12
|
+
import tempfile
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import TYPE_CHECKING
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from collections.abc import Mapping
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class UnsafePathError(OSError):
|
|
21
|
+
"""A path that is, or sits under, a symlink where the caller refuses one."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
UnsafePath = UnsafePathError # public name kept for callers
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _umask() -> int:
|
|
28
|
+
mask = os.umask(0)
|
|
29
|
+
os.umask(mask)
|
|
30
|
+
return mask
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _close_quietly(fd: int) -> None:
|
|
34
|
+
with contextlib.suppress(OSError): # fdopen may already have closed it; keep the original error
|
|
35
|
+
os.close(fd)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _default_mode(path: Path) -> int:
|
|
39
|
+
"""The mode of `path` when it is a regular file, else `0o666 & ~umask`."""
|
|
40
|
+
try:
|
|
41
|
+
st = os.lstat(path)
|
|
42
|
+
except FileNotFoundError:
|
|
43
|
+
return 0o666 & ~_umask()
|
|
44
|
+
return stat.S_IMODE(st.st_mode) if stat.S_ISREG(st.st_mode) else 0o666 & ~_umask()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _write_fd(fd: int, data: bytes) -> None:
|
|
48
|
+
try:
|
|
49
|
+
f = os.fdopen(fd, "wb")
|
|
50
|
+
except BaseException:
|
|
51
|
+
_close_quietly(fd)
|
|
52
|
+
raise
|
|
53
|
+
with f:
|
|
54
|
+
f.write(data)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def replace_file(path: Path, data: bytes, mode: int | None = None) -> None:
|
|
58
|
+
"""Write `data` to a fresh temporary file beside `path`, then move it over `path`.
|
|
59
|
+
|
|
60
|
+
The mode is `mode` when given, else the one `path` has when it is a regular file, else `0o666 & ~umask`."""
|
|
61
|
+
if mode is None:
|
|
62
|
+
mode = _default_mode(path)
|
|
63
|
+
fd, name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
|
|
64
|
+
try:
|
|
65
|
+
_write_fd(fd, data)
|
|
66
|
+
os.chmod(name, mode)
|
|
67
|
+
os.replace(name, path)
|
|
68
|
+
except BaseException:
|
|
69
|
+
with contextlib.suppress(OSError):
|
|
70
|
+
os.unlink(name)
|
|
71
|
+
raise
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def append_text(path: Path, text: str) -> None:
|
|
75
|
+
"""Append `text` to `path`, creating it; a symlink at `path` raises OSError."""
|
|
76
|
+
fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o644)
|
|
77
|
+
try:
|
|
78
|
+
f = os.fdopen(fd, "w", encoding="utf-8", newline="")
|
|
79
|
+
except BaseException:
|
|
80
|
+
_close_quietly(fd)
|
|
81
|
+
raise
|
|
82
|
+
with f:
|
|
83
|
+
f.write(text)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def refuse_symlink_chain(root: Path, path: Path) -> None:
|
|
87
|
+
"""Raise UnsafePath when `root` or any component of `path` below `root` is a symlink."""
|
|
88
|
+
if root.is_symlink():
|
|
89
|
+
raise UnsafePathError(f"{root} is a symlink")
|
|
90
|
+
current = root
|
|
91
|
+
try:
|
|
92
|
+
parts = path.relative_to(root).parts
|
|
93
|
+
except ValueError:
|
|
94
|
+
raise UnsafePathError(f"{path} is not under {root}") from None
|
|
95
|
+
for part in parts:
|
|
96
|
+
current /= part
|
|
97
|
+
if current.is_symlink():
|
|
98
|
+
raise UnsafePathError(f"{current} is a symlink")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# Sandbox of the background sessions (`mem-auto`, `mem-synthesize`): their text may come from injected notes, so a
|
|
102
|
+
# session started with MEM_SANDBOX=1 reaches no network and reads body files only under MEM_SANDBOX_ROOTS and its
|
|
103
|
+
# working folder, and no other registered project's memories.
|
|
104
|
+
SANDBOX = "MEM_SANDBOX"
|
|
105
|
+
SANDBOX_ROOTS = "MEM_SANDBOX_ROOTS"
|
|
106
|
+
_SANDBOX_COMMANDS = ("import", "fetch-sources")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def sandbox_active(env: Mapping[str, str] | None = None) -> bool:
|
|
110
|
+
return (os.environ if env is None else env).get(SANDBOX) == "1"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def body_file_allowed(source: str) -> bool:
|
|
114
|
+
"""`-` (standard input) and any file under MEM_SANDBOX_ROOTS or the working directory; symlinks resolved."""
|
|
115
|
+
if source == "-":
|
|
116
|
+
return True
|
|
117
|
+
roots = [
|
|
118
|
+
Path.cwd(),
|
|
119
|
+
*(Path(r) for r in os.environ.get(SANDBOX_ROOTS, "").split(os.pathsep) if r),
|
|
120
|
+
]
|
|
121
|
+
target = Path(os.path.realpath(source))
|
|
122
|
+
return any(target.is_relative_to(os.path.realpath(r)) for r in roots)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _option_refusal(command: str, args: dict) -> str | None:
|
|
126
|
+
if command in _SANDBOX_COMMANDS:
|
|
127
|
+
return f"{command} is off in this session"
|
|
128
|
+
if command == "new" and args.get("url"):
|
|
129
|
+
return "--url is off in this session"
|
|
130
|
+
for key in ("all_projects", "project"):
|
|
131
|
+
# other registered projects' memories are not in the session's read scope; curate's --project is the flag `is_project`
|
|
132
|
+
if args.get(key):
|
|
133
|
+
return f"--{key.replace('_', '-')} is off in this session"
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _file_refusal(args: dict) -> str | None:
|
|
138
|
+
for key, value in args.items():
|
|
139
|
+
# every option that names a file to read: --body-file, --note-body-file, --summary-file, curate --from, refs --file
|
|
140
|
+
if (
|
|
141
|
+
(key == "file" or key.endswith("_file"))
|
|
142
|
+
and isinstance(value, str)
|
|
143
|
+
and not body_file_allowed(value)
|
|
144
|
+
):
|
|
145
|
+
return (
|
|
146
|
+
f"--{key.replace('_', '-')} is outside the folders this session may read: {value}"
|
|
147
|
+
)
|
|
148
|
+
return None
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def sandbox_refusal(command: str, args: dict) -> str | None:
|
|
152
|
+
"""Why a `mem` call is refused in a sandboxed session, else None. `args` holds the parsed options."""
|
|
153
|
+
if not sandbox_active():
|
|
154
|
+
return None
|
|
155
|
+
return _option_refusal(command, args) or _file_refusal(args)
|