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,684 @@
|
|
|
1
|
+
"""mem-integrate: joins loose knowledge notes to the parts of syntheses with two cheap read-only sessions each
|
|
2
|
+
(plan 2026-11-26-memory-seamless-stage-3-integration). Not measured: opt-in by running it. Claude only: a Codex
|
|
3
|
+
default is ignored, `--runner codex` exits 2 (Codex placed 0 of 17 appends in 4 runs, ADR 0037 trial 2026-11-27).
|
|
4
|
+
|
|
5
|
+
`run`: takes the `mem-auto` run lock (busy: nothing starts), commits the store, asks `mem synthesis integrate
|
|
6
|
+
--candidates`, drops the notes the done list already holds, and per synthesis runs (1) a place session that answers
|
|
7
|
+
`note | part | append|unit N | fingerprint` lines and (2) a check session that lists the rows it accepts (its stray
|
|
8
|
+
lines are ignored and logged: only a row the place session proposed can be kept). Only rows
|
|
9
|
+
both answered, and that `placement_rows` kept, are written by Python to a rows file and applied with ONE
|
|
10
|
+
`mem synthesis integrate FILE` (one logged group per synthesis). The sessions only Read their input folder, so no
|
|
11
|
+
model text reaches the store. State: `<state folder>/integrate/<id>/` (`done.json`, `<run id>/record.json`, logs).
|
|
12
|
+
|
|
13
|
+
`--undo RUN` undoes a run's groups newest first (exit 2 when a file changed since: nothing is restored, stdout says
|
|
14
|
+
how many groups remain); `status` prints the last run.
|
|
15
|
+
|
|
16
|
+
Usage: mem-integrate run [--store PATH] [--claude PATH] [--budget USD] [--dry-run] | status | --undo RUN | --self-check
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import argparse
|
|
22
|
+
import hashlib
|
|
23
|
+
import json
|
|
24
|
+
import logging
|
|
25
|
+
import math
|
|
26
|
+
import os
|
|
27
|
+
import re
|
|
28
|
+
import shutil
|
|
29
|
+
import sys
|
|
30
|
+
import time
|
|
31
|
+
import uuid
|
|
32
|
+
from dataclasses import dataclass, field
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import TYPE_CHECKING, Any
|
|
35
|
+
|
|
36
|
+
from memory_cli.core import auto_state, codex_pass, headless, jobs, resources, runner
|
|
37
|
+
from memory_cli.core.file_journal import FileJournal
|
|
38
|
+
from memory_cli.entry import integrate_self_check
|
|
39
|
+
from memory_cli.integrate import answers, plan
|
|
40
|
+
from memory_cli.integrate import state as run_state
|
|
41
|
+
from memory_cli.integrate import undo as run_undo
|
|
42
|
+
from memory_cli.integrate.log import log_entries
|
|
43
|
+
from memory_cli.integrate.rows import row_line
|
|
44
|
+
from memory_cli.synthesize import pipeline as sp
|
|
45
|
+
from memory_cli.synthesize import run as synth_run
|
|
46
|
+
|
|
47
|
+
if TYPE_CHECKING:
|
|
48
|
+
from memory_cli.integrate.rows import Row
|
|
49
|
+
|
|
50
|
+
logger = logging.getLogger(__name__)
|
|
51
|
+
|
|
52
|
+
DEFAULT_BUDGET = 0.50 # USD per run
|
|
53
|
+
SESSION_TIMEOUT = 600
|
|
54
|
+
MAX_INPUT_BYTES = 128 * 1024 # Operational bound, not a token limit.
|
|
55
|
+
PRIVATE_MODE = 0o700
|
|
56
|
+
CHARS_PER_TOKEN = 4
|
|
57
|
+
EPSILON = 1e-9
|
|
58
|
+
FAILURE_CUT = 150
|
|
59
|
+
INTEGRATE_BRIEFS = resources.INTEGRATE_BRIEFS
|
|
60
|
+
SESSION_VARS = (
|
|
61
|
+
"CLAUDE_ENV_FILE",
|
|
62
|
+
"CLAUDE_PLUGIN_ROOT",
|
|
63
|
+
"CLAUDE_PLUGIN_DATA",
|
|
64
|
+
"CLAUDE_PROJECT_DIR",
|
|
65
|
+
"CLAUDE_PID",
|
|
66
|
+
"CLAUDE_CODE_SESSION_ID",
|
|
67
|
+
"CLAUDE_CODE_MESSAGING_SOCKET",
|
|
68
|
+
"CLAUDE_CODE_MESSAGING_TOKEN",
|
|
69
|
+
)
|
|
70
|
+
UNREADABLE = re.compile(r"permission denied|cannot read|could not read|no such file", re.IGNORECASE)
|
|
71
|
+
UNREADABLE_FAILURE = "the session could not read its input file"
|
|
72
|
+
COLUMNS = ("synthesis", "notes", "placed", "checked", "applied", "refused", "cost")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def budget_of(value: str | float | None) -> float:
|
|
76
|
+
if value is None:
|
|
77
|
+
return DEFAULT_BUDGET
|
|
78
|
+
try:
|
|
79
|
+
number = float(value)
|
|
80
|
+
except ValueError:
|
|
81
|
+
return DEFAULT_BUDGET
|
|
82
|
+
return number if number > 0 else DEFAULT_BUDGET
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _budget_arg(text: str) -> str:
|
|
86
|
+
"""The `--budget` text when it is a finite number above 0; a usage error naming it otherwise."""
|
|
87
|
+
try:
|
|
88
|
+
ok = 0 < float(text) < math.inf
|
|
89
|
+
except ValueError:
|
|
90
|
+
ok = False
|
|
91
|
+
if not ok:
|
|
92
|
+
raise argparse.ArgumentTypeError(f"{text!r} is not a finite number above 0")
|
|
93
|
+
return text
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def state_folder(store: Path) -> Path:
|
|
97
|
+
"""`<state folder>/integrate/<id>`: the done list and one folder per run."""
|
|
98
|
+
ident = hashlib.sha1(str(store.resolve()).encode()).hexdigest()[:12]
|
|
99
|
+
return synth_run.state_dir() / "integrate" / ident
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def run_env(store: Path) -> dict:
|
|
103
|
+
"""The `mem` calls and the sessions: aimed at `store`; a configured memories folder is kept."""
|
|
104
|
+
env = synth_run.session_env(store)
|
|
105
|
+
if os.environ.get("MEM_MEMORIES"):
|
|
106
|
+
env["MEM_MEMORIES"] = os.environ["MEM_MEMORIES"]
|
|
107
|
+
return env
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def session_spec(
|
|
111
|
+
claude: str, work: Path, brief: str, settings: Path, max_budget: float
|
|
112
|
+
) -> headless.Session:
|
|
113
|
+
return headless.Session(
|
|
114
|
+
claude=claude,
|
|
115
|
+
prompt=brief,
|
|
116
|
+
model="haiku",
|
|
117
|
+
settings=settings,
|
|
118
|
+
effort="medium",
|
|
119
|
+
tools=("Read",),
|
|
120
|
+
allowed=(f"Read(/{work}/**)",),
|
|
121
|
+
disallowed=("Bash", "WebSearch", "WebFetch"),
|
|
122
|
+
max_budget=max_budget,
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def session_cmd(
|
|
127
|
+
claude: str, work: Path, brief: str, settings: Path, max_budget: float
|
|
128
|
+
) -> list[str]:
|
|
129
|
+
"""One Haiku session. Only Read exists and only inside `work` (`//` is an absolute path in a rule); no shell,
|
|
130
|
+
no web, no write; hooks are disabled by `settings`."""
|
|
131
|
+
return headless.command(session_spec(claude, work, brief, settings, max_budget))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
@dataclass
|
|
135
|
+
class Tally:
|
|
136
|
+
"""One synthesis's row of the summary table."""
|
|
137
|
+
|
|
138
|
+
synthesis: str
|
|
139
|
+
notes: int = 0
|
|
140
|
+
placed: int = 0
|
|
141
|
+
checked: int = 0
|
|
142
|
+
applied: int = 0
|
|
143
|
+
refused: int = 0
|
|
144
|
+
cost: float = 0.0
|
|
145
|
+
|
|
146
|
+
def cells(self) -> list[str]:
|
|
147
|
+
return [
|
|
148
|
+
self.synthesis,
|
|
149
|
+
str(self.notes),
|
|
150
|
+
str(self.placed),
|
|
151
|
+
str(self.checked),
|
|
152
|
+
str(self.applied),
|
|
153
|
+
str(self.refused),
|
|
154
|
+
f"{self.cost:.3f}",
|
|
155
|
+
]
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@dataclass
|
|
159
|
+
class Job:
|
|
160
|
+
"""One started run: its folder, its record (rewritten after every group) and what it spent."""
|
|
161
|
+
|
|
162
|
+
store: Path
|
|
163
|
+
env: dict
|
|
164
|
+
claude: str
|
|
165
|
+
budget: float
|
|
166
|
+
folder: Path
|
|
167
|
+
record: run_state.RunRecord
|
|
168
|
+
tallies: list[Tally] = field(default_factory=list)
|
|
169
|
+
stop_on_failure: bool = False
|
|
170
|
+
spend_halted: bool = False
|
|
171
|
+
unresolved: bool = False # an intent could not be settled: no further candidate may be applied
|
|
172
|
+
current: Tally | None = (
|
|
173
|
+
None # the synthesis being worked on: every session's cost lands in its row
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
@property
|
|
177
|
+
def root(self) -> Path:
|
|
178
|
+
return self.folder / self.record.run_id
|
|
179
|
+
|
|
180
|
+
def log(self, text: str) -> None:
|
|
181
|
+
fd_log = os.open(self.root / "log.txt", os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
|
|
182
|
+
with os.fdopen(fd_log, "a") as f:
|
|
183
|
+
f.write(f"{time.strftime('%H:%M:%S')} {text}\n")
|
|
184
|
+
|
|
185
|
+
def fail(self, text: str) -> None:
|
|
186
|
+
self.record.failures.append(text)
|
|
187
|
+
self.log(f"failure: {text}")
|
|
188
|
+
run_state.write_record(self.folder, self.record)
|
|
189
|
+
|
|
190
|
+
def ask(self, name: str, work: Path, data: Any) -> tuple[str, float] | None:
|
|
191
|
+
"""Runs session `name` over `data` written to `work`; (answer, cost), or None with a failure recorded."""
|
|
192
|
+
if self.spent_up():
|
|
193
|
+
self.fail("budget spent")
|
|
194
|
+
return None
|
|
195
|
+
serialized = json.dumps(data, ensure_ascii=False, indent=1).encode("utf-8")
|
|
196
|
+
if len(serialized) > MAX_INPUT_BYTES:
|
|
197
|
+
self.fail(
|
|
198
|
+
f"{name} input refused: {len(serialized)} bytes exceeds {MAX_INPUT_BYTES} bytes"
|
|
199
|
+
)
|
|
200
|
+
return None
|
|
201
|
+
work.mkdir(parents=True, exist_ok=True)
|
|
202
|
+
input_file = work / f"{name}.json"
|
|
203
|
+
input_file.write_bytes(serialized)
|
|
204
|
+
settings = self.root / "settings.json"
|
|
205
|
+
settings.write_text(json.dumps({"disableAllHooks": True}), encoding="utf-8")
|
|
206
|
+
brief = sp.brief(name, briefs=INTEGRATE_BRIEFS, INPUT_FILE=str(input_file))
|
|
207
|
+
start = time.monotonic()
|
|
208
|
+
done = self.run_session(work, brief, settings, work / f"{name}.jsonl")
|
|
209
|
+
remaining = self.budget - self.record.cost
|
|
210
|
+
self.record.cost += done["cost"]
|
|
211
|
+
if self.current is not None:
|
|
212
|
+
self.current.cost += done["cost"]
|
|
213
|
+
self.log(
|
|
214
|
+
f"{name}: has_result={done['has_result']} error={done['error']} cost={done['cost']:.3f} "
|
|
215
|
+
f"wall={time.monotonic() - start:.1f}s answer={' '.join(done['answer'].split())[:200]}"
|
|
216
|
+
)
|
|
217
|
+
if not self.accept_spend(name, done, remaining):
|
|
218
|
+
return None
|
|
219
|
+
if not done["has_result"] or done["error"]:
|
|
220
|
+
self.fail(f"{name} session {'failed' if done['has_result'] else sp.NO_COST}")
|
|
221
|
+
return None
|
|
222
|
+
return done["answer"], done["cost"]
|
|
223
|
+
|
|
224
|
+
def accept_spend(self, name: str, done: dict, remaining: float) -> bool:
|
|
225
|
+
if not done["cost_known"]:
|
|
226
|
+
self.spend_halted = True
|
|
227
|
+
self.fail(f"{name} session {sp.NO_COST}")
|
|
228
|
+
return False
|
|
229
|
+
if done["cost"] > remaining + EPSILON:
|
|
230
|
+
self.spend_halted = True
|
|
231
|
+
self.fail("budget spent")
|
|
232
|
+
return False
|
|
233
|
+
return True
|
|
234
|
+
|
|
235
|
+
def spent_up(self) -> bool:
|
|
236
|
+
return self.budget - self.record.cost <= EPSILON
|
|
237
|
+
|
|
238
|
+
def run_session(self, work: Path, brief: str, settings: Path, log: Path) -> dict:
|
|
239
|
+
"""One session, its stream written to `log`; the `sp.parse` dict."""
|
|
240
|
+
cmd = session_cmd(self.claude, work, brief, settings, self.budget - self.record.cost)
|
|
241
|
+
raw = headless.run_raw(cmd, cwd=work, env=self.env, timeout=SESSION_TIMEOUT).stdout
|
|
242
|
+
log.write_text(raw, encoding="utf-8")
|
|
243
|
+
return sp.parse(raw)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def candidates(job: Job) -> list[dict] | None:
|
|
247
|
+
"""The synthesis candidates minus the notes the done list holds; None (a failure recorded) when `mem` gave none."""
|
|
248
|
+
found = sp.mem(job.store, job.env, "synthesis", "integrate", "--candidates")
|
|
249
|
+
try:
|
|
250
|
+
data = json.loads(found.stdout) if found.returncode == 0 else None
|
|
251
|
+
except ValueError:
|
|
252
|
+
data = None
|
|
253
|
+
if not isinstance(data, list):
|
|
254
|
+
text = (found.stderr or found.stdout).strip()[:FAILURE_CUT]
|
|
255
|
+
job.fail(f"mem synthesis integrate --candidates failed: {text}")
|
|
256
|
+
return None
|
|
257
|
+
done = run_state.read_done(job.folder)
|
|
258
|
+
out = []
|
|
259
|
+
for cand in data:
|
|
260
|
+
cand["notes"] = [
|
|
261
|
+
n for n in cand["notes"] if not run_state.is_done(done, n["handle"], n["digest"])
|
|
262
|
+
]
|
|
263
|
+
if cand["notes"]:
|
|
264
|
+
out.append(cand)
|
|
265
|
+
return out
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def place_input(cand: dict) -> dict:
|
|
269
|
+
"""What the place session reads: the notes with their claims, the parts with fingerprint and numbered units."""
|
|
270
|
+
syn = cand["synthesis"]
|
|
271
|
+
return {
|
|
272
|
+
"synthesis": syn,
|
|
273
|
+
"notes": [{"note": n["handle"], "claim": n["claim"]} for n in cand["notes"]],
|
|
274
|
+
"parts": [
|
|
275
|
+
{
|
|
276
|
+
"part": f"s:{syn}#{p['section']}",
|
|
277
|
+
"fingerprint": p["fingerprint"],
|
|
278
|
+
"units": p["units"],
|
|
279
|
+
}
|
|
280
|
+
for p in cand["parts"]
|
|
281
|
+
],
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def check_input(cand: dict, rows: list[Row]) -> dict:
|
|
286
|
+
"""What the check session reads: each proposed row with the note's claim and the text it would touch."""
|
|
287
|
+
claims = {n["handle"]: n["claim"] for n in cand["notes"]}
|
|
288
|
+
parts = {f"s:{cand['synthesis']}#{p['section']}": p["units"] for p in cand["parts"]}
|
|
289
|
+
items = []
|
|
290
|
+
part_texts = {}
|
|
291
|
+
for row in rows:
|
|
292
|
+
units = parts[row.target]
|
|
293
|
+
if row.unit is None:
|
|
294
|
+
if row.target not in part_texts:
|
|
295
|
+
part_texts[row.target] = " ".join(u["text"] for u in units)
|
|
296
|
+
target = {"part": row.target}
|
|
297
|
+
else:
|
|
298
|
+
target = {"unit": row.unit, "sentence": units[row.unit - 1]["text"]}
|
|
299
|
+
items.append({"row": row_line(row), "claim": claims[row.note], **target})
|
|
300
|
+
return {"parts": part_texts, "rows": items}
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def apply_rows(
|
|
304
|
+
job: Job, work: Path, synthesis: str, rows: list[Row], digests: dict[str, str]
|
|
305
|
+
) -> tuple[int, int] | None:
|
|
306
|
+
"""Applies the rows with one `mem synthesis integrate`; (applied, refused) and the group recorded, or None
|
|
307
|
+
(a failure recorded) when the command failed. An intent file written first lets the next run settle an apply
|
|
308
|
+
this process did not live to record (`reconcile`); `digests` maps note handle to digest."""
|
|
309
|
+
rows_file = work / "rows.txt"
|
|
310
|
+
rows_file.write_text("\n".join(row_line(r) for r in rows) + "\n", encoding="utf-8")
|
|
311
|
+
notes = [
|
|
312
|
+
{"handle": h, "digest": d} for h, d in digests.items()
|
|
313
|
+
] # every candidate: all end up done
|
|
314
|
+
group = uuid.uuid4().hex
|
|
315
|
+
expect = work / "expect-notes.json"
|
|
316
|
+
expect.write_text(
|
|
317
|
+
json.dumps({h: digests[h] for h in dict.fromkeys(r.note for r in rows)}), encoding="utf-8"
|
|
318
|
+
)
|
|
319
|
+
try:
|
|
320
|
+
run_state.write_intent(
|
|
321
|
+
job.folder, run_state.Intent(group, synthesis, notes, job.record.run_id)
|
|
322
|
+
)
|
|
323
|
+
except run_state.IntentError as exc:
|
|
324
|
+
job.unresolved = True
|
|
325
|
+
job.fail(f"{synthesis}: {exc}"[:FAILURE_CUT])
|
|
326
|
+
return None
|
|
327
|
+
found = sp.mem(
|
|
328
|
+
job.store,
|
|
329
|
+
job.env,
|
|
330
|
+
"synthesis",
|
|
331
|
+
"integrate",
|
|
332
|
+
str(rows_file),
|
|
333
|
+
"--group",
|
|
334
|
+
group,
|
|
335
|
+
"--expect-notes",
|
|
336
|
+
str(expect),
|
|
337
|
+
)
|
|
338
|
+
job.log(f"apply: exit {found.returncode}\n{found.stdout.strip()}\n{found.stderr.strip()}")
|
|
339
|
+
if found.returncode:
|
|
340
|
+
job.fail(
|
|
341
|
+
f"mem synthesis integrate failed: {(found.stderr or found.stdout).strip()[:FAILURE_CUT]}"
|
|
342
|
+
)
|
|
343
|
+
job.unresolved = not reconcile(job)
|
|
344
|
+
return None
|
|
345
|
+
lines = found.stdout.splitlines()
|
|
346
|
+
for line in lines:
|
|
347
|
+
if line.startswith("group\t"):
|
|
348
|
+
record = run_state.GroupRecord([f"s:{synthesis}"], line.split("\t", 1)[1], "integrate")
|
|
349
|
+
job.record.groups.append(record)
|
|
350
|
+
run_state.write_record(job.folder, job.record)
|
|
351
|
+
count = {w: sum(x.startswith(w + "\t") for x in lines) for w in ("applied", "refused")}
|
|
352
|
+
return count["applied"], count["refused"]
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _recover(job: Job) -> bool:
|
|
356
|
+
"""Rolls back a pending integration journal; False (a failure recorded) when that failed."""
|
|
357
|
+
if not FileJournal(job.store.resolve(), ".integrate-recovery").pending():
|
|
358
|
+
return True
|
|
359
|
+
found = sp.mem(job.store, job.env, "synthesis", "integrate", "--recover")
|
|
360
|
+
job.log(f"recover: exit {found.returncode} {found.stdout.strip()} {found.stderr.strip()}")
|
|
361
|
+
if found.returncode:
|
|
362
|
+
text = (found.stderr or found.stdout).strip()[:FAILURE_CUT]
|
|
363
|
+
job.fail(f"mem synthesis integrate --recover failed: {text}")
|
|
364
|
+
return False
|
|
365
|
+
return True
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _adopt(job: Job, intent: run_state.Intent) -> None:
|
|
369
|
+
"""Records a committed group the run did not see and marks its notes done."""
|
|
370
|
+
if all(g.group_id != intent.group for g in job.record.groups):
|
|
371
|
+
job.record.groups.append(
|
|
372
|
+
run_state.GroupRecord([f"s:{intent.synthesis}"], intent.group, "integrate")
|
|
373
|
+
)
|
|
374
|
+
run_state.write_record(job.folder, job.record)
|
|
375
|
+
for note in intent.notes:
|
|
376
|
+
run_state.mark_done(job.folder, note["handle"], note["digest"])
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def reconcile(job: Job) -> bool:
|
|
380
|
+
"""Settles an intent a dead or failed apply left: rolls back a pending journal, then, when the intent's group
|
|
381
|
+
is in the curation log, records it and marks its notes done; otherwise the notes stay eligible. A pending
|
|
382
|
+
journal is rolled back even when there is no intent (a crashed manual `mem synthesis integrate`). False (a
|
|
383
|
+
failure recorded, the intent kept) when recovery failed or the intent is malformed."""
|
|
384
|
+
if not _recover(job):
|
|
385
|
+
return False
|
|
386
|
+
try:
|
|
387
|
+
intent = run_state.read_intent(job.folder)
|
|
388
|
+
except run_state.IntentError as exc:
|
|
389
|
+
job.fail(
|
|
390
|
+
f"unreadable intent file {job.folder / run_state.INTENT_FILE}: {exc}"[:FAILURE_CUT]
|
|
391
|
+
)
|
|
392
|
+
return False
|
|
393
|
+
if intent is None:
|
|
394
|
+
return True
|
|
395
|
+
committed = any(entry.get("group") == intent.group for _, entry in log_entries(job.store))
|
|
396
|
+
if committed:
|
|
397
|
+
_adopt(job, intent)
|
|
398
|
+
run_state.delete_intent(job.folder)
|
|
399
|
+
state = "committed" if committed else "not committed"
|
|
400
|
+
job.log(f"reconciled group {intent.group}: {state}")
|
|
401
|
+
return True
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def ask_readable(
|
|
405
|
+
job: Job, name: str, work: Path, cand: dict, data: Any
|
|
406
|
+
) -> tuple[str, float] | None:
|
|
407
|
+
"""`Job.ask`, and None with a failure recorded when the answer says the session could not read its file."""
|
|
408
|
+
asked = job.ask(name, work, data)
|
|
409
|
+
if asked is not None and UNREADABLE.search(asked[0]):
|
|
410
|
+
job.fail(f"{cand['synthesis']}: {UNREADABLE_FAILURE}")
|
|
411
|
+
return None
|
|
412
|
+
return asked
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def log_ignored(job: Job, ignored: list[str]) -> None:
|
|
416
|
+
if ignored:
|
|
417
|
+
shown = "; ".join(x[:80] for x in ignored[:3])
|
|
418
|
+
job.log(f"check: {len(ignored)} lines ignored: {shown}")
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def place_and_check(job: Job, work: Path, cand: dict, tally: Tally) -> list[Row] | None:
|
|
422
|
+
"""The rows both sessions agree on; None (a failure recorded) when a session failed or an answer is malformed.
|
|
423
|
+
|
|
424
|
+
A malformed place answer fails the synthesis: nothing is applied for it. A check answer's stray lines are
|
|
425
|
+
ignored (only rows place proposed can be kept); one that decides nothing fails it too."""
|
|
426
|
+
placed = ask_readable(job, "place", work, cand, place_input(cand))
|
|
427
|
+
if placed is None:
|
|
428
|
+
return None
|
|
429
|
+
lines = answers.answer_lines(placed[0])
|
|
430
|
+
if lines is None:
|
|
431
|
+
job.fail(f"{cand['synthesis']}: the place answer is not rows or none")
|
|
432
|
+
return None
|
|
433
|
+
rows, refusals = plan.placement_rows(lines, plan.offered_of(cand))
|
|
434
|
+
tally.placed, tally.refused = len(rows), len(refusals)
|
|
435
|
+
job.log("place refusals: " + "; ".join(refusals))
|
|
436
|
+
if not rows:
|
|
437
|
+
return []
|
|
438
|
+
checked = ask_readable(job, "check", work, cand, check_input(cand, rows))
|
|
439
|
+
if checked is None:
|
|
440
|
+
return None
|
|
441
|
+
kept = plan.agreed(rows, checked[0])
|
|
442
|
+
log_ignored(job, plan.ignored_lines(rows, checked[0]))
|
|
443
|
+
if kept is None:
|
|
444
|
+
job.fail(f"{cand['synthesis']}: the check answer is not rows or none")
|
|
445
|
+
return None
|
|
446
|
+
tally.checked = len(kept)
|
|
447
|
+
return kept
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def integrate_synthesis(job: Job, index: int, cand: dict) -> None:
|
|
451
|
+
syn = cand["synthesis"]
|
|
452
|
+
tally = Tally(syn, notes=len(cand["notes"]))
|
|
453
|
+
job.tallies.append(tally)
|
|
454
|
+
job.current = tally
|
|
455
|
+
work = job.root / "work" / str(index)
|
|
456
|
+
kept = place_and_check(job, work, cand, tally)
|
|
457
|
+
if kept is None:
|
|
458
|
+
return # nothing is marked done: a failed session is tried again
|
|
459
|
+
if kept:
|
|
460
|
+
counts = apply_rows(job, work, syn, kept, {n["handle"]: n["digest"] for n in cand["notes"]})
|
|
461
|
+
if counts is None:
|
|
462
|
+
return # a failed apply marks nothing done: the notes are offered again
|
|
463
|
+
tally.applied, tally.refused = counts[0], tally.refused + counts[1]
|
|
464
|
+
for note in cand["notes"]:
|
|
465
|
+
run_state.mark_done(job.folder, note["handle"], note["digest"])
|
|
466
|
+
run_state.delete_intent(job.folder)
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def table(tallies: list[Tally]) -> str:
|
|
470
|
+
rows = [list(COLUMNS), *(t.cells() for t in tallies)]
|
|
471
|
+
widths = [max(len(r[i]) for r in rows) for i in range(len(COLUMNS))]
|
|
472
|
+
return "\n".join(
|
|
473
|
+
" | ".join(cell.ljust(w) for cell, w in zip(r, widths, strict=True)).rstrip() for r in rows
|
|
474
|
+
)
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def report(job: Job) -> None:
|
|
478
|
+
if job.tallies:
|
|
479
|
+
print(table(job.tallies))
|
|
480
|
+
for text in job.record.failures:
|
|
481
|
+
print(f"failed: {text}")
|
|
482
|
+
print(f"cost: {job.record.cost:.3f} USD of {job.budget:.2f}; run {job.record.run_id}")
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def work_steps(job: Job) -> None:
|
|
486
|
+
if not reconcile(job):
|
|
487
|
+
return
|
|
488
|
+
found = candidates(job)
|
|
489
|
+
for index, cand in enumerate(found or []):
|
|
490
|
+
integrate_synthesis(job, index, cand)
|
|
491
|
+
if (
|
|
492
|
+
job.spend_halted
|
|
493
|
+
or job.unresolved
|
|
494
|
+
or (
|
|
495
|
+
job.record.failures
|
|
496
|
+
and (job.stop_on_failure or job.record.failures[-1] == "budget spent")
|
|
497
|
+
)
|
|
498
|
+
):
|
|
499
|
+
return
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def run_locked(
|
|
503
|
+
store: Path, claude: str | None, budget: float, *, stop_on_failure: bool = False
|
|
504
|
+
) -> Job:
|
|
505
|
+
"""A run for a caller that already holds the store run lock (`mem-auto`, or `cmd_run`); the finished job: its
|
|
506
|
+
record holds the cost, failures and groups, `spend_halted` says a spend stopped it."""
|
|
507
|
+
run_id = f"{time.strftime('%Y%m%d-%H%M%S')}-{os.getpid()}"
|
|
508
|
+
record = run_state.RunRecord(run_id, time.strftime("%Y-%m-%dT%H:%M:%S%z"))
|
|
509
|
+
job = Job(
|
|
510
|
+
store,
|
|
511
|
+
run_env(store),
|
|
512
|
+
claude or "",
|
|
513
|
+
budget,
|
|
514
|
+
state_folder(store),
|
|
515
|
+
record,
|
|
516
|
+
stop_on_failure=stop_on_failure,
|
|
517
|
+
)
|
|
518
|
+
jobs.private_dir(job.root)
|
|
519
|
+
run_state.write_record(job.folder, record)
|
|
520
|
+
if not job.claude:
|
|
521
|
+
job.fail("no claude binary (--claude, CLAUDE_CODE_EXECPATH or PATH)")
|
|
522
|
+
else:
|
|
523
|
+
_guarded(job)
|
|
524
|
+
return job
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def cmd_run(store: Path, claude: str | None, budget_arg: str | None) -> int:
|
|
528
|
+
fd = jobs.take_run_lock(auto_state.auto_dir(synth_run.state_dir(), store))
|
|
529
|
+
if fd is None:
|
|
530
|
+
print("mem-integrate: a run holds the lock")
|
|
531
|
+
return 0
|
|
532
|
+
try:
|
|
533
|
+
report(run_locked(store, claude, budget_of(budget_arg)))
|
|
534
|
+
finally:
|
|
535
|
+
os.close(fd)
|
|
536
|
+
return 0
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def _guarded(job: Job) -> None:
|
|
540
|
+
try:
|
|
541
|
+
synth_run.history_commit(job.store, job.env, "mem-integrate: before", job.log)
|
|
542
|
+
work_steps(job)
|
|
543
|
+
except (
|
|
544
|
+
Exception
|
|
545
|
+
) as exc: # anything after the lock ends as a failure line; the groups so far stay recorded
|
|
546
|
+
logger.debug("integrate run failed", exc_info=True)
|
|
547
|
+
job.fail(f"{type(exc).__name__}: {exc}"[:FAILURE_CUT])
|
|
548
|
+
finally:
|
|
549
|
+
synth_run.history_commit(job.store, job.env, "mem-integrate: after", job.log)
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def cmd_dry_run(store: Path, budget_arg: str | None) -> int:
|
|
553
|
+
"""Lists what a run would do; starts no session and changes nothing."""
|
|
554
|
+
env = run_env(store)
|
|
555
|
+
found = sp.mem(store, env, "synthesis", "integrate", "--candidates")
|
|
556
|
+
try:
|
|
557
|
+
data = json.loads(found.stdout) if found.returncode == 0 else None
|
|
558
|
+
except ValueError:
|
|
559
|
+
data = None
|
|
560
|
+
if not isinstance(data, list):
|
|
561
|
+
print(
|
|
562
|
+
f"mem-integrate: no candidates: {(found.stderr or found.stdout).strip()[:FAILURE_CUT]}"
|
|
563
|
+
)
|
|
564
|
+
return 0
|
|
565
|
+
done = run_state.read_done(state_folder(store))
|
|
566
|
+
for cand in data:
|
|
567
|
+
notes = [n for n in cand["notes"] if not run_state.is_done(done, n["handle"], n["digest"])]
|
|
568
|
+
if notes:
|
|
569
|
+
size = len(json.dumps(place_input({**cand, "notes": notes}), ensure_ascii=False))
|
|
570
|
+
print(
|
|
571
|
+
f"{cand['synthesis']}: {len(notes)} notes, 2 sessions (place, check), "
|
|
572
|
+
f"place input about {size // CHARS_PER_TOKEN} tokens"
|
|
573
|
+
)
|
|
574
|
+
if jobs.lock_held(auto_state.auto_dir(synth_run.state_dir(), store)):
|
|
575
|
+
print("would not start: a run holds the lock")
|
|
576
|
+
print(f"budget: {budget_of(budget_arg):.2f} USD per run; nothing was started or changed")
|
|
577
|
+
return 0
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
UNDO_REFUSED = 2
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def cmd_undo(store: Path, run_id: str) -> int:
|
|
584
|
+
"""Undoes the groups of run `run_id`; exit 2 on a refusal (stderr names the file) or an unknown run."""
|
|
585
|
+
fd = jobs.take_run_lock(auto_state.auto_dir(synth_run.state_dir(), store))
|
|
586
|
+
if fd is None:
|
|
587
|
+
print("mem-integrate: a run holds the lock; nothing was undone", file=sys.stderr)
|
|
588
|
+
return UNDO_REFUSED
|
|
589
|
+
env = run_env(store)
|
|
590
|
+
try:
|
|
591
|
+
result = run_undo.undo(
|
|
592
|
+
store, state_folder(store), run_id, lambda *args: sp.mem(store, env, *args)
|
|
593
|
+
)
|
|
594
|
+
finally:
|
|
595
|
+
os.close(fd)
|
|
596
|
+
for group_id in result.already_restored:
|
|
597
|
+
print(f"already restored: group {group_id}")
|
|
598
|
+
print(f"undone: {result.undone}")
|
|
599
|
+
print(f"remaining: {result.remaining}")
|
|
600
|
+
if result.refusal:
|
|
601
|
+
print(f"mem-integrate: {result.refusal}", file=sys.stderr)
|
|
602
|
+
return UNDO_REFUSED
|
|
603
|
+
return 0
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def cmd_status(store: Path) -> int:
|
|
607
|
+
"""The last run's id, state, cost, groups and failure lines."""
|
|
608
|
+
folder = state_folder(store)
|
|
609
|
+
run_id = run_state.last_run_id(folder)
|
|
610
|
+
record = run_state.read_record(folder, run_id) if run_id else None
|
|
611
|
+
if record is None:
|
|
612
|
+
print("mem-integrate: no run yet")
|
|
613
|
+
return 0
|
|
614
|
+
undone = sum(g.undone for g in record.groups)
|
|
615
|
+
state = (
|
|
616
|
+
"failed"
|
|
617
|
+
if record.failures
|
|
618
|
+
else "undone"
|
|
619
|
+
if record.groups and undone == len(record.groups)
|
|
620
|
+
else "ok"
|
|
621
|
+
)
|
|
622
|
+
print(f"run: {record.run_id} (started {record.started})")
|
|
623
|
+
print(f"state: {state}")
|
|
624
|
+
print(f"cost: {record.cost:.3f} USD")
|
|
625
|
+
print(f"groups: {len(record.groups)}")
|
|
626
|
+
print(f"undone: {undone}")
|
|
627
|
+
for text in record.failures:
|
|
628
|
+
print(f"failed: {text}")
|
|
629
|
+
return 0
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
def _parser() -> argparse.ArgumentParser:
|
|
633
|
+
parser = argparse.ArgumentParser(
|
|
634
|
+
prog="mem-integrate", description=(__doc__ or "").split("\n", 1)[0]
|
|
635
|
+
)
|
|
636
|
+
parser.add_argument("command", nargs="?", choices=["run", "status"])
|
|
637
|
+
parser.add_argument("--store", type=Path, help="default: the store `mem` resolves")
|
|
638
|
+
parser.add_argument(
|
|
639
|
+
"--claude", default=os.environ.get("CLAUDE_CODE_EXECPATH") or shutil.which("claude")
|
|
640
|
+
)
|
|
641
|
+
parser.add_argument("--undo", metavar="RUN", help="undo the groups of run RUN, newest first")
|
|
642
|
+
parser.add_argument(
|
|
643
|
+
"--budget", type=_budget_arg, help=f"USD per run (default {DEFAULT_BUDGET})"
|
|
644
|
+
)
|
|
645
|
+
runner.add_flag(parser)
|
|
646
|
+
parser.add_argument(
|
|
647
|
+
"--dry-run", action="store_true", help="list what would run; start and change nothing"
|
|
648
|
+
)
|
|
649
|
+
parser.add_argument(
|
|
650
|
+
"--self-check", action="store_true", help="no model: prove the briefs, parser and flow"
|
|
651
|
+
)
|
|
652
|
+
return parser
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
def _dispatch(args: argparse.Namespace, store: Path) -> int:
|
|
656
|
+
if args.undo:
|
|
657
|
+
return cmd_undo(store, args.undo)
|
|
658
|
+
if args.command == "status":
|
|
659
|
+
return cmd_status(store)
|
|
660
|
+
if args.dry_run:
|
|
661
|
+
return cmd_dry_run(store, args.budget)
|
|
662
|
+
for name in SESSION_VARS: # left over from the session that started this process
|
|
663
|
+
os.environ.pop(name, None)
|
|
664
|
+
return cmd_run(store, args.claude, args.budget)
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def main(argv: list[str] | None = None) -> int:
|
|
668
|
+
parser = _parser()
|
|
669
|
+
args = parser.parse_args(argv)
|
|
670
|
+
if args.self_check:
|
|
671
|
+
return integrate_self_check.self_check(sys.modules[__name__])
|
|
672
|
+
if not args.command and not args.undo:
|
|
673
|
+
parser.error("a command or --undo RUN is required")
|
|
674
|
+
if (
|
|
675
|
+
refused := codex_pass.refuse_codex(
|
|
676
|
+
"mem-integrate", args.runner, why=codex_pass.WHY_INTEGRATE
|
|
677
|
+
)
|
|
678
|
+
) is not None:
|
|
679
|
+
return refused
|
|
680
|
+
store = args.store.expanduser().resolve() if args.store else synth_run.default_store()
|
|
681
|
+
if store is None or not (store / "mem-store.yaml").is_file():
|
|
682
|
+
print(f"mem-integrate: no store at {store}", file=sys.stderr)
|
|
683
|
+
return 2
|
|
684
|
+
return _dispatch(args, store)
|