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,614 @@
|
|
|
1
|
+
"""mem-settle: one bounded settling run in the background (plan 2026-11-17-memory-seamless, stage W).
|
|
2
|
+
|
|
3
|
+
`run` (detached, no output): takes the run lock first and exits quietly when it is busy; asks `mem settle due` whether
|
|
4
|
+
new global memories wait and the last apply ended more than `--minutes` ago (a failed run also waits that long before
|
|
5
|
+
the next); `mem settle pending --json` writes the look-alike pairs to a work folder; with none the run ends (no
|
|
6
|
+
session). Otherwise ONE headless Haiku session reads the pairs file and writes `verdicts.json`: it has no Bash, so it
|
|
7
|
+
cannot call `mem` itself, and Python applies the file with `mem settle apply`, which enforces what may change. A session
|
|
8
|
+
that fails, ends without a cost report, or leaves no valid verdict list changes nothing and is recorded as a failure,
|
|
9
|
+
shown by the next session start text until `mem-settle ack`. State, logs and transcripts: `<state folder>/settle/<id>/`
|
|
10
|
+
(mode 0700, runs kept 30 days). It never reads or writes the `mem-auto` status.
|
|
11
|
+
|
|
12
|
+
Usage: mem-settle run [--store PATH] [--claude PATH] [--budget USD] [--minutes M] | status | ack | --self-check
|
|
13
|
+
mem-settle run --dry-run (says whether it would start; starts nothing and changes nothing)
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import json
|
|
20
|
+
import logging
|
|
21
|
+
import math
|
|
22
|
+
import os
|
|
23
|
+
import shutil
|
|
24
|
+
import subprocess
|
|
25
|
+
import sys
|
|
26
|
+
import tempfile
|
|
27
|
+
import time
|
|
28
|
+
from dataclasses import dataclass, field
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger(__name__)
|
|
32
|
+
from memory_cli.core import codex_pass, headless, jobs, resources
|
|
33
|
+
from memory_cli.core import runner as runners
|
|
34
|
+
from memory_cli.settle import state as ss
|
|
35
|
+
from memory_cli.synthesize import pipeline as sp
|
|
36
|
+
from memory_cli.synthesize import run as synth_run
|
|
37
|
+
|
|
38
|
+
DEFAULT_BUDGET = 0.25 # USD per run
|
|
39
|
+
KEEP_SECONDS = 30 * 86400
|
|
40
|
+
SESSION_TIMEOUT = 600
|
|
41
|
+
CODEX_ADDENDUM = (
|
|
42
|
+
"Codex rule for the `merge` decision: if one claim states anything the other lacks (a detail, a condition, "
|
|
43
|
+
"a workaround), the pair is not a merge: choose `nothing`, plus any qualifier it added."
|
|
44
|
+
)
|
|
45
|
+
PRIVATE_MODE = 0o700
|
|
46
|
+
FAILURE_WAIT = (
|
|
47
|
+
30 # minutes a failed run waits at least, also at session end (which asks with 0 minutes)
|
|
48
|
+
)
|
|
49
|
+
SESSION_VARS = (
|
|
50
|
+
"CLAUDE_ENV_FILE",
|
|
51
|
+
"CLAUDE_PLUGIN_ROOT",
|
|
52
|
+
"CLAUDE_PLUGIN_DATA",
|
|
53
|
+
"CLAUDE_PROJECT_DIR",
|
|
54
|
+
"CLAUDE_PID",
|
|
55
|
+
"CLAUDE_CODE_SESSION_ID",
|
|
56
|
+
"CLAUDE_CODE_MESSAGING_SOCKET",
|
|
57
|
+
"CLAUDE_CODE_MESSAGING_TOKEN",
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def budget_of(value: str | float | None) -> float:
|
|
62
|
+
if value is None:
|
|
63
|
+
return DEFAULT_BUDGET
|
|
64
|
+
try:
|
|
65
|
+
number = float(value)
|
|
66
|
+
except ValueError:
|
|
67
|
+
return DEFAULT_BUDGET
|
|
68
|
+
return number if number > 0 else DEFAULT_BUDGET
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def stamp(seconds: float | None) -> str:
|
|
72
|
+
return time.strftime("%Y-%m-%d %H:%M", time.localtime(seconds)) if seconds else "never"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class State:
|
|
76
|
+
"""The files of one store's settling runs."""
|
|
77
|
+
|
|
78
|
+
def __init__(self, store: Path):
|
|
79
|
+
self.store = store
|
|
80
|
+
self.dir = ss.settle_dir(synth_run.state_dir(), store)
|
|
81
|
+
|
|
82
|
+
def status(self) -> dict:
|
|
83
|
+
return jobs.read_json(self.dir / jobs.STATUS_NAME)
|
|
84
|
+
|
|
85
|
+
def save_status(self, **changes) -> dict:
|
|
86
|
+
jobs.private_dir(self.dir)
|
|
87
|
+
data = {**self.status(), **changes}
|
|
88
|
+
jobs.write_json(self.dir / jobs.STATUS_NAME, data)
|
|
89
|
+
return data
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def run_env(store: Path) -> dict:
|
|
93
|
+
"""The `mem` calls and the session: aimed at `store`; a configured memories folder is kept."""
|
|
94
|
+
env = synth_run.session_env(store)
|
|
95
|
+
if os.environ.get("MEM_MEMORIES"):
|
|
96
|
+
env["MEM_MEMORIES"] = os.environ["MEM_MEMORIES"]
|
|
97
|
+
return env
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def prune(state: State, now: float) -> None:
|
|
101
|
+
jobs.prune_runs_older(state.dir / "runs", now, KEEP_SECONDS)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def session_spec(
|
|
105
|
+
claude: str, work: Path, brief: str, settings: Path, max_budget: float
|
|
106
|
+
) -> headless.Session:
|
|
107
|
+
return headless.Session(
|
|
108
|
+
claude=claude,
|
|
109
|
+
prompt=brief,
|
|
110
|
+
model="haiku",
|
|
111
|
+
settings=settings,
|
|
112
|
+
effort="medium",
|
|
113
|
+
# `//` is an absolute path
|
|
114
|
+
allowed=(f"Read(/{work}/**)", f"Write(/{work}/**)", f"Edit(/{work}/**)"),
|
|
115
|
+
disallowed=("Bash", "WebSearch", "WebFetch"),
|
|
116
|
+
max_budget=max_budget,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def session_cmd(
|
|
121
|
+
claude: str, work: Path, brief: str, settings: Path, max_budget: float
|
|
122
|
+
) -> list[str]:
|
|
123
|
+
"""One Haiku session. Tools: Read and Write/Edit inside `work` only; no Bash (a session with `Bash(mem *)` could
|
|
124
|
+
run any `mem` command and bypass the limits `mem settle apply` enforces), no web, hooks disabled by `settings`."""
|
|
125
|
+
return headless.command(session_spec(claude, work, brief, settings, max_budget))
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def session(cmd: list[str], work: Path, env: dict, log: Path) -> dict:
|
|
129
|
+
"""Runs a `session_cmd` command in `work`; the stream goes to `log`."""
|
|
130
|
+
start = time.monotonic()
|
|
131
|
+
raw = headless.run_raw(cmd, cwd=work, env=env, timeout=SESSION_TIMEOUT).stdout
|
|
132
|
+
log.write_text(raw, encoding="utf-8")
|
|
133
|
+
result = sp.parse(raw)
|
|
134
|
+
result["wall"] = time.monotonic() - start
|
|
135
|
+
return result
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def codex_session(claude: str, work: Path, brief: str, settings: Path, log: Path) -> dict:
|
|
139
|
+
"""The same session on Codex: it writes `verdicts.json` in `work`, which is its whole sandbox. The brief gets
|
|
140
|
+
`CODEX_ADDENDUM`: Codex reads the `merge` row literally and merges pairs where one claim adds a detail, while
|
|
141
|
+
the same sentence in the shared brief lowered Claude's recall (trial 2026-11-27, ADR 0037)."""
|
|
142
|
+
start = time.monotonic()
|
|
143
|
+
done = codex_pass.ask(
|
|
144
|
+
session_spec(claude, work, f"{brief}\n\n{CODEX_ADDENDUM}", settings, DEFAULT_BUDGET),
|
|
145
|
+
work,
|
|
146
|
+
writes=True,
|
|
147
|
+
timeout=SESSION_TIMEOUT,
|
|
148
|
+
)
|
|
149
|
+
log.write_text(done["raw"] if done["has_result"] else "", encoding="utf-8")
|
|
150
|
+
done["wall"] = time.monotonic() - start
|
|
151
|
+
return done
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def read_verdicts(path: Path) -> str | None:
|
|
155
|
+
"""None when `path` holds a JSON list; else why not."""
|
|
156
|
+
if not path.is_file():
|
|
157
|
+
return "the session wrote no verdicts file"
|
|
158
|
+
try:
|
|
159
|
+
rows = json.loads(path.read_text(encoding="utf-8"))
|
|
160
|
+
except (OSError, ValueError):
|
|
161
|
+
return "the verdicts file is not valid JSON"
|
|
162
|
+
return None if isinstance(rows, list) else "the verdicts file is not a JSON list"
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@dataclass
|
|
166
|
+
class Outcome:
|
|
167
|
+
"""What a run spent and found, filled as it goes, so an exception later still leaves what was spent."""
|
|
168
|
+
|
|
169
|
+
cost: float = 0.0
|
|
170
|
+
tokens: int = 0 # Codex only: it reports tokens, not money
|
|
171
|
+
runner: str = "" # "": not resolved yet
|
|
172
|
+
failures: list[str] = field(default_factory=list)
|
|
173
|
+
pairs: int = 0
|
|
174
|
+
summary: str = ""
|
|
175
|
+
log_file: Path | None = None # None: nothing started (not due, or the check failed)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@dataclass
|
|
179
|
+
class Job:
|
|
180
|
+
"""One started run: its folder, its log and its outcome."""
|
|
181
|
+
|
|
182
|
+
state: State
|
|
183
|
+
root: Path
|
|
184
|
+
out: Outcome
|
|
185
|
+
env: dict
|
|
186
|
+
runner: str = "claude"
|
|
187
|
+
|
|
188
|
+
@property
|
|
189
|
+
def work(self) -> Path:
|
|
190
|
+
return self.root / "work"
|
|
191
|
+
|
|
192
|
+
def log(self, text: str) -> None:
|
|
193
|
+
fd_log = os.open(self.root / "log.txt", os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
|
|
194
|
+
with os.fdopen(fd_log, "a") as f:
|
|
195
|
+
f.write(f"{time.strftime('%H:%M:%S')} {text}\n")
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _problem(found: subprocess.CompletedProcess[str], what: str) -> str:
|
|
199
|
+
return f"{what} failed: {(found.stderr or found.stdout).strip()[:150]}"
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _pending_pairs(job: Job) -> list | None:
|
|
203
|
+
"""The look-alike pairs `mem settle pending` found; None (a failure recorded) when it gave none."""
|
|
204
|
+
found = sp.mem(job.state.store, job.env, "settle", "pending", "--json")
|
|
205
|
+
if found.returncode:
|
|
206
|
+
job.out.failures.append(_problem(found, "mem settle pending"))
|
|
207
|
+
return None
|
|
208
|
+
try:
|
|
209
|
+
pairs = json.loads(found.stdout)
|
|
210
|
+
except ValueError:
|
|
211
|
+
pairs = None
|
|
212
|
+
if not isinstance(pairs, list):
|
|
213
|
+
job.out.failures.append("mem settle pending gave no JSON list")
|
|
214
|
+
return None
|
|
215
|
+
return pairs
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _ask_model(job: Job, claude: str, budget: float, pairs: list) -> Path | None:
|
|
219
|
+
"""The session; the verdicts file it wrote, or None (a failure recorded)."""
|
|
220
|
+
pairs_file, verdicts_file = job.work / "pairs.json", job.work / "verdicts.json"
|
|
221
|
+
pairs_file.write_text(json.dumps(pairs, ensure_ascii=False, indent=1), encoding="utf-8")
|
|
222
|
+
settings = job.root / "settings.json"
|
|
223
|
+
settings.write_text(
|
|
224
|
+
json.dumps({"disableAllHooks": True}), encoding="utf-8"
|
|
225
|
+
) # no hook of the session may commit or start a run
|
|
226
|
+
brief = sp.brief("settle", PAIRS_FILE=str(pairs_file), VERDICTS_FILE=str(verdicts_file))
|
|
227
|
+
log = job.root / "session.jsonl"
|
|
228
|
+
if job.runner == "codex":
|
|
229
|
+
done = codex_session(claude or "", job.work, brief, settings, log)
|
|
230
|
+
job.out.tokens += done["tokens"]
|
|
231
|
+
else:
|
|
232
|
+
done = session(
|
|
233
|
+
session_cmd(claude, job.work, brief, settings, budget), job.work, job.env, log
|
|
234
|
+
)
|
|
235
|
+
job.out.cost += done["cost"]
|
|
236
|
+
spent = f"tokens={done['tokens']}" if job.runner == "codex" else f"cost={done['cost']:.3f}"
|
|
237
|
+
job.log(
|
|
238
|
+
f"session: has_result={done['has_result']} error={done['error']} {spent} "
|
|
239
|
+
f"answer={'' if job.runner == 'codex' else ' '.join(done['answer'].split())[:200]}"
|
|
240
|
+
)
|
|
241
|
+
if job.runner == "codex" and job.out.tokens > codex_pass.token_cap():
|
|
242
|
+
job.out.failures.append(
|
|
243
|
+
f"{job.out.tokens} tokens exceeded the cap {codex_pass.token_cap()}"
|
|
244
|
+
)
|
|
245
|
+
return None
|
|
246
|
+
if not done["has_result"]:
|
|
247
|
+
job.out.failures.append(
|
|
248
|
+
"the session ended without a result" + codex_pass.reason(done)
|
|
249
|
+
if job.runner == "codex"
|
|
250
|
+
else sp.NO_COST
|
|
251
|
+
)
|
|
252
|
+
return None
|
|
253
|
+
if done["error"]:
|
|
254
|
+
job.out.failures.append("settling session failed")
|
|
255
|
+
return None
|
|
256
|
+
why = read_verdicts(verdicts_file)
|
|
257
|
+
if why:
|
|
258
|
+
job.out.failures.append(why)
|
|
259
|
+
return None
|
|
260
|
+
return verdicts_file
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _summary(lines: list[str]) -> str:
|
|
264
|
+
counts = {
|
|
265
|
+
word: sum(1 for ln in lines if ln.startswith(word + "\t"))
|
|
266
|
+
for word in ("applied", "refused", "failed")
|
|
267
|
+
}
|
|
268
|
+
return ", ".join(f"{n} {word}" for word, n in counts.items() if n)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _apply(job: Job, verdicts_file: Path) -> None:
|
|
272
|
+
applied = sp.mem(job.state.store, job.env, "settle", "apply", "--verdicts", str(verdicts_file))
|
|
273
|
+
job.log(f"apply: exit {applied.returncode}\n{applied.stdout.strip()}\n{applied.stderr.strip()}")
|
|
274
|
+
if applied.returncode:
|
|
275
|
+
job.out.failures.append(_problem(applied, "mem settle apply"))
|
|
276
|
+
return
|
|
277
|
+
lines = applied.stdout.splitlines()
|
|
278
|
+
job.out.summary = _summary(lines)
|
|
279
|
+
if any(ln.startswith("failed\t") for ln in lines):
|
|
280
|
+
job.out.failures.append("a settling was only partly done: see the log")
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def work_steps(job: Job, claude: str | None, budget: float) -> None:
|
|
284
|
+
"""Pairs, the session, the apply."""
|
|
285
|
+
job.work.mkdir(mode=PRIVATE_MODE)
|
|
286
|
+
pairs = _pending_pairs(job)
|
|
287
|
+
if pairs is None:
|
|
288
|
+
return
|
|
289
|
+
job.log(f"pairs: {len(pairs)}")
|
|
290
|
+
job.out.pairs = len(pairs)
|
|
291
|
+
if not pairs: # `pending` already judged the handles it looked at: nothing to ask a model
|
|
292
|
+
return
|
|
293
|
+
if job.runner == "codex" and runners.find_codex() is None:
|
|
294
|
+
job.out.failures.append(codex_pass.NO_CODEX)
|
|
295
|
+
return
|
|
296
|
+
if job.runner == "claude" and not claude:
|
|
297
|
+
job.out.failures.append("no claude binary (--claude, CLAUDE_CODE_EXECPATH or PATH)")
|
|
298
|
+
return
|
|
299
|
+
verdicts_file = _ask_model(job, claude or "", budget, pairs)
|
|
300
|
+
if verdicts_file is not None:
|
|
301
|
+
_apply(job, verdicts_file)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def due_check(store: Path, minutes: float) -> tuple[bool, str]:
|
|
305
|
+
"""(due, why not or the error): `mem settle due` exits 0 when work waits, 1 when none."""
|
|
306
|
+
done = sp.mem(store, run_env(store), "settle", "due", "--minutes", str(minutes))
|
|
307
|
+
if done.returncode == 0:
|
|
308
|
+
return True, done.stdout.strip()
|
|
309
|
+
if done.returncode == 1:
|
|
310
|
+
return False, "no new memories wait, or the last apply is recent"
|
|
311
|
+
return False, f"mem settle due failed: {(done.stderr or done.stdout).strip()[:150]}"
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _finish(state: State, out: Outcome) -> None:
|
|
315
|
+
"""The end status, written while the lock is still held."""
|
|
316
|
+
finished = time.time()
|
|
317
|
+
reason = "; ".join(out.failures)
|
|
318
|
+
if out.log_file is None: # nothing started (not due, or the check failed)
|
|
319
|
+
if out.failures:
|
|
320
|
+
state.save_status(failure={"at": finished, "reason": reason, "log": ""})
|
|
321
|
+
return
|
|
322
|
+
failure = (
|
|
323
|
+
{"failure": {"at": finished, "reason": reason, "log": str(out.log_file)}}
|
|
324
|
+
if out.failures
|
|
325
|
+
else {}
|
|
326
|
+
)
|
|
327
|
+
state.save_status(
|
|
328
|
+
state="failed" if out.failures else "ok",
|
|
329
|
+
finished=finished,
|
|
330
|
+
cost=out.cost,
|
|
331
|
+
tokens=out.tokens,
|
|
332
|
+
runner=out.runner,
|
|
333
|
+
reason=reason,
|
|
334
|
+
pairs=out.pairs,
|
|
335
|
+
summary=out.summary,
|
|
336
|
+
**failure,
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _open_job(state: State, out: Outcome, previous: dict, now: float) -> Job:
|
|
341
|
+
"""The run folder and the `running` status."""
|
|
342
|
+
stale = jobs.failure(
|
|
343
|
+
{
|
|
344
|
+
"state": previous.get("state"),
|
|
345
|
+
"started": previous.get("started"),
|
|
346
|
+
"log": previous.get("log"),
|
|
347
|
+
},
|
|
348
|
+
now,
|
|
349
|
+
)
|
|
350
|
+
root = state.dir / "runs" / f"{time.strftime('%Y%m%d-%H%M%S')}-{os.getpid()}"
|
|
351
|
+
jobs.private_dir(root)
|
|
352
|
+
prune(state, now)
|
|
353
|
+
out.log_file = root / "log.txt"
|
|
354
|
+
extra = {"failure": stale} if stale and not previous.get("failure") else {}
|
|
355
|
+
state.save_status(
|
|
356
|
+
state="running",
|
|
357
|
+
started=now,
|
|
358
|
+
finished=None,
|
|
359
|
+
cost=0.0,
|
|
360
|
+
tokens=0,
|
|
361
|
+
runner=out.runner,
|
|
362
|
+
reason="",
|
|
363
|
+
log=str(out.log_file),
|
|
364
|
+
**extra,
|
|
365
|
+
)
|
|
366
|
+
return Job(state, root, out, run_env(state.store), out.runner)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _attempt(
|
|
370
|
+
state: State,
|
|
371
|
+
claude: str | None,
|
|
372
|
+
budget_arg: str | float | None,
|
|
373
|
+
minutes: float,
|
|
374
|
+
out: Outcome,
|
|
375
|
+
) -> None:
|
|
376
|
+
now = time.time()
|
|
377
|
+
previous = state.status()
|
|
378
|
+
# a failed run is not retried at once: its pairs stay pending, and every write would start it again
|
|
379
|
+
if (
|
|
380
|
+
previous.get("state") == "failed"
|
|
381
|
+
and now - float(previous.get("finished") or 0) <= max(minutes, FAILURE_WAIT) * 60
|
|
382
|
+
):
|
|
383
|
+
return
|
|
384
|
+
budget = budget_of(budget_arg)
|
|
385
|
+
out.runner = out.runner or runners.resolve_runner(
|
|
386
|
+
None
|
|
387
|
+
) # once per run; a malformed setting fails the run
|
|
388
|
+
due, why = due_check(state.store, minutes)
|
|
389
|
+
if not due:
|
|
390
|
+
if why.startswith("mem settle due failed"):
|
|
391
|
+
out.failures.append(why)
|
|
392
|
+
_finish(state, out)
|
|
393
|
+
return
|
|
394
|
+
job = _open_job(state, out, previous, now)
|
|
395
|
+
job.log(f"start: budget {budget:.2f}")
|
|
396
|
+
work_steps(job, claude, budget)
|
|
397
|
+
if out.runner == "codex" and codex_pass.over_cap(out.tokens):
|
|
398
|
+
out.failures.append(f"{out.tokens} tokens reached the cap {codex_pass.token_cap()}")
|
|
399
|
+
if out.cost > budget + 1e-9:
|
|
400
|
+
out.failures.append(f"cost {out.cost:.2f} USD is over the budget {budget:.2f}")
|
|
401
|
+
_finish(state, out)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def cmd_run(
|
|
405
|
+
store: Path,
|
|
406
|
+
claude: str | None,
|
|
407
|
+
budget_arg: str | float | None,
|
|
408
|
+
minutes_arg: str | float | None,
|
|
409
|
+
runner: str | None = None,
|
|
410
|
+
) -> int:
|
|
411
|
+
state = State(store)
|
|
412
|
+
fd = jobs.take_run_lock(state.dir) # the first action: a busy lock means a run is going
|
|
413
|
+
if fd is None:
|
|
414
|
+
return 0
|
|
415
|
+
minutes = ss.minutes_of(minutes_arg)
|
|
416
|
+
out = Outcome(runner=runner or "")
|
|
417
|
+
try:
|
|
418
|
+
_attempt(state, claude, budget_arg, minutes, out)
|
|
419
|
+
except (
|
|
420
|
+
Exception
|
|
421
|
+
) as exc: # anything after the lock ends as a `failed` status; a killed run is the stale case
|
|
422
|
+
logger.debug("settling run failed", exc_info=True)
|
|
423
|
+
out.failures.append(f"{type(exc).__name__}: {exc}"[:150])
|
|
424
|
+
try:
|
|
425
|
+
_finish(state, out)
|
|
426
|
+
except Exception:
|
|
427
|
+
logger.debug("the end status could not be written", exc_info=True)
|
|
428
|
+
finally:
|
|
429
|
+
os.close(fd)
|
|
430
|
+
return 0
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def cmd_dry_run(store: Path, claude: str | None, budget_arg, minutes_arg) -> int:
|
|
434
|
+
minutes = ss.minutes_of(minutes_arg)
|
|
435
|
+
state = State(store)
|
|
436
|
+
previous = state.status()
|
|
437
|
+
due, why = due_check(store, minutes)
|
|
438
|
+
reason = (
|
|
439
|
+
"a settling run holds the lock"
|
|
440
|
+
if _lock_held(state)
|
|
441
|
+
else "the last run failed less than the minutes ago"
|
|
442
|
+
if previous.get("state") == "failed"
|
|
443
|
+
and time.time() - float(previous.get("finished") or 0) <= minutes * 60
|
|
444
|
+
else ""
|
|
445
|
+
if due
|
|
446
|
+
else why
|
|
447
|
+
)
|
|
448
|
+
print(
|
|
449
|
+
f"minutes: {minutes}; budget: {budget_of(budget_arg):.2f} USD; claude: {claude or '(none)'}; "
|
|
450
|
+
+ (f"would not start: {reason}" if reason else "would start")
|
|
451
|
+
)
|
|
452
|
+
return 0
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def _lock_held(state: State) -> bool:
|
|
456
|
+
"""Reads only: no folder is made; any doubt answers False."""
|
|
457
|
+
return jobs.lock_held(state.dir)
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def cmd_status(store: Path) -> int:
|
|
461
|
+
data = State(store).status()
|
|
462
|
+
if not data:
|
|
463
|
+
print("no settling run yet")
|
|
464
|
+
return 0
|
|
465
|
+
now = time.time()
|
|
466
|
+
shown = data.get("state", "?")
|
|
467
|
+
if shown == "running" and now - float(data.get("started") or 0) > jobs.STALE_RUNNING_SECONDS:
|
|
468
|
+
shown = "failed (a run that did not finish)"
|
|
469
|
+
print(
|
|
470
|
+
f"last run: {stamp(data.get('started'))}, state {shown}, cost {float(data.get('cost') or 0):.3f} USD, "
|
|
471
|
+
f"pairs {data.get('pairs', 0)}"
|
|
472
|
+
)
|
|
473
|
+
if data.get("summary"):
|
|
474
|
+
print(f"applied: {data['summary']}")
|
|
475
|
+
if data.get("reason"):
|
|
476
|
+
print(f"reason: {data['reason']}")
|
|
477
|
+
print(f"log: {data.get('log') or '(none)'}")
|
|
478
|
+
print(
|
|
479
|
+
f"unacknowledged failure: {'yes (mem-settle ack clears it)' if jobs.failure(data, now) else 'no'}"
|
|
480
|
+
)
|
|
481
|
+
return 0
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def cmd_ack(store: Path) -> int:
|
|
485
|
+
state = State(store)
|
|
486
|
+
data = state.status()
|
|
487
|
+
if data:
|
|
488
|
+
changes: dict = {"failure": None}
|
|
489
|
+
if jobs.failure({"state": data.get("state"), "started": data.get("started")}, time.time()):
|
|
490
|
+
changes["state"] = "failed" # a stale `running` is closed
|
|
491
|
+
state.save_status(**changes)
|
|
492
|
+
print("acknowledged: the failure line is cleared")
|
|
493
|
+
return 0
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def _check_tools(tmp: Path) -> None:
|
|
497
|
+
cmd = session_cmd("claude", tmp / "w", "brief", tmp / "s.json", 0.25)
|
|
498
|
+
allowed = cmd[cmd.index("--allowedTools") + 1 : cmd.index("--disallowedTools")]
|
|
499
|
+
assert (
|
|
500
|
+
not any(t.startswith("Bash") for t in allowed)
|
|
501
|
+
and "Bash" in cmd[cmd.index("--disallowedTools") + 1 :]
|
|
502
|
+
)
|
|
503
|
+
assert all(t.startswith(("Read(", "Write(", "Edit(")) and f"{tmp}/w" in t for t in allowed), (
|
|
504
|
+
allowed
|
|
505
|
+
)
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def self_check() -> int:
|
|
509
|
+
"""No model: the lock, the folder mode, the options, a run with nothing to settle (it starts no session) and the
|
|
510
|
+
session's tool list (no Bash)."""
|
|
511
|
+
assert (
|
|
512
|
+
budget_of("x") == DEFAULT_BUDGET
|
|
513
|
+
and math.isclose(budget_of("0.6"), 0.6)
|
|
514
|
+
and budget_of("0") == DEFAULT_BUDGET
|
|
515
|
+
)
|
|
516
|
+
with tempfile.TemporaryDirectory(prefix="mem-settle-check-") as tmp_name:
|
|
517
|
+
tmp = Path(tmp_name)
|
|
518
|
+
for name, folder in (
|
|
519
|
+
("MEM_DATA", "data"),
|
|
520
|
+
("XDG_DATA_HOME", "share"),
|
|
521
|
+
("MEM_PROJECT", "project"),
|
|
522
|
+
("XDG_CONFIG_HOME", "cfg"),
|
|
523
|
+
):
|
|
524
|
+
os.environ[name] = str(tmp / folder)
|
|
525
|
+
os.environ.pop("MEM_MEMORIES", None)
|
|
526
|
+
store = tmp / "store"
|
|
527
|
+
init = subprocess.run(
|
|
528
|
+
[*sp.MEM, "init", str(store)],
|
|
529
|
+
env=resources.child_env(),
|
|
530
|
+
capture_output=True,
|
|
531
|
+
text=True,
|
|
532
|
+
check=False,
|
|
533
|
+
)
|
|
534
|
+
assert init.returncode == 0, init.stderr
|
|
535
|
+
state = State(store)
|
|
536
|
+
held = jobs.take_run_lock(state.dir)
|
|
537
|
+
assert held is not None and jobs.take_run_lock(state.dir) is None
|
|
538
|
+
assert cmd_run(store, "/nonexistent", None, 0) == 0 and not state.status().get("state"), (
|
|
539
|
+
"ran while locked"
|
|
540
|
+
)
|
|
541
|
+
os.close(held)
|
|
542
|
+
assert (state.dir.stat().st_mode & 0o777) == PRIVATE_MODE, oct(state.dir.stat().st_mode)
|
|
543
|
+
assert cmd_run(store, "/nonexistent", None, 0) == 0 and not state.status().get("state"), (
|
|
544
|
+
"ran with nothing new"
|
|
545
|
+
)
|
|
546
|
+
(store / "memories").mkdir(exist_ok=True)
|
|
547
|
+
found = sp.mem(store, dict(os.environ), "settle", "log")
|
|
548
|
+
assert found.returncode == 0, found.stderr
|
|
549
|
+
_check_tools(tmp)
|
|
550
|
+
print("self-check passed")
|
|
551
|
+
return 0
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def _parser() -> argparse.ArgumentParser:
|
|
555
|
+
parser = argparse.ArgumentParser(
|
|
556
|
+
prog="mem-settle", description=(__doc__ or "").split("\n", 1)[0]
|
|
557
|
+
)
|
|
558
|
+
parser.add_argument("command", nargs="?", choices=["run", "status", "ack"])
|
|
559
|
+
parser.add_argument(
|
|
560
|
+
"--store", type=Path, help="default: the store `mem` resolves (MEM_STORE, else the default)"
|
|
561
|
+
)
|
|
562
|
+
parser.add_argument(
|
|
563
|
+
"--claude", default=os.environ.get("CLAUDE_CODE_EXECPATH") or shutil.which("claude")
|
|
564
|
+
)
|
|
565
|
+
parser.add_argument("--budget", help=f"USD per run (default {DEFAULT_BUDGET})")
|
|
566
|
+
runners.add_flag(parser)
|
|
567
|
+
parser.add_argument(
|
|
568
|
+
"--minutes",
|
|
569
|
+
help=f"a run starts only when the last apply ended more than this long ago "
|
|
570
|
+
f"(default {ss.DEFAULT_MINUTES:.0f}; 0 at the end of a session)",
|
|
571
|
+
)
|
|
572
|
+
parser.add_argument(
|
|
573
|
+
"--dry-run", action="store_true", help="say whether `run` would start; change nothing"
|
|
574
|
+
)
|
|
575
|
+
parser.add_argument(
|
|
576
|
+
"--self-check",
|
|
577
|
+
action="store_true",
|
|
578
|
+
help="no model: prove the lock, the gates and the tool list",
|
|
579
|
+
)
|
|
580
|
+
return parser
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def _requested_store(args: argparse.Namespace) -> Path | None:
|
|
584
|
+
return args.store.expanduser().resolve() if args.store else synth_run.default_store()
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def _no_store(command: str, store: Path | None) -> int:
|
|
588
|
+
if command != "run": # run is silent: it starts from a hook
|
|
589
|
+
print(f"mem-settle: no store at {store}", file=sys.stderr)
|
|
590
|
+
return 0 if command == "run" else 2
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def _run(store: Path, args: argparse.Namespace) -> int:
|
|
594
|
+
if args.dry_run:
|
|
595
|
+
return cmd_dry_run(store, args.claude, args.budget, args.minutes)
|
|
596
|
+
for name in SESSION_VARS: # left over from the session that started this process
|
|
597
|
+
os.environ.pop(name, None)
|
|
598
|
+
return cmd_run(store, args.claude, args.budget, args.minutes)
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def main(argv: list[str] | None = None) -> int:
|
|
602
|
+
parser = _parser()
|
|
603
|
+
args = parser.parse_args(argv)
|
|
604
|
+
if args.self_check:
|
|
605
|
+
return self_check()
|
|
606
|
+
if not args.command:
|
|
607
|
+
parser.error("a command is required")
|
|
608
|
+
runners.pin_flag(args.runner)
|
|
609
|
+
store = _requested_store(args)
|
|
610
|
+
if store is None or not (store / "mem-store.yaml").is_file():
|
|
611
|
+
return _no_store(args.command, store)
|
|
612
|
+
if args.command == "run":
|
|
613
|
+
return _run(store, args)
|
|
614
|
+
return {"status": lambda: cmd_status(store), "ack": lambda: cmd_ack(store)}[args.command]()
|