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,528 @@
|
|
|
1
|
+
"""`mem-synthesize` for topics without a synthesis: one pipeline per topic, then the reference step."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import TYPE_CHECKING, Required, TypedDict, Unpack
|
|
14
|
+
|
|
15
|
+
from memory_cli.synthesize import backfill
|
|
16
|
+
from memory_cli.synthesize import pipeline as sp
|
|
17
|
+
from memory_cli.synthesize import references as bf
|
|
18
|
+
from memory_cli.synthesize import run as sr
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from collections.abc import Callable
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class RunOptions(backfill.BackfillRunOptions, total=False):
|
|
27
|
+
"""Keyword options of `run`; `references=False` skips the last step (adding references)."""
|
|
28
|
+
|
|
29
|
+
references: bool
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class TopicOptions(TypedDict, total=False):
|
|
33
|
+
settings: Required[Path]
|
|
34
|
+
log: Required[Callable[[str], None]]
|
|
35
|
+
budget_left: Callable[[], float] | None
|
|
36
|
+
references: bool
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ReferenceOptions(TypedDict, total=False):
|
|
40
|
+
settings: Required[Path]
|
|
41
|
+
log: Required[Callable[[str], None]]
|
|
42
|
+
budget_left: Required[float | None]
|
|
43
|
+
done: dict | None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class TopicReferenceOptions(TypedDict):
|
|
47
|
+
settings: Path
|
|
48
|
+
log: Callable[[str], None]
|
|
49
|
+
row: dict
|
|
50
|
+
budget: float | None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def new_row(topic: str, status: str = "ok") -> dict:
|
|
54
|
+
return {
|
|
55
|
+
"topic": topic,
|
|
56
|
+
"parts": 0,
|
|
57
|
+
"attached": 0,
|
|
58
|
+
"fixed": 0,
|
|
59
|
+
"deleted": 0,
|
|
60
|
+
"reverted": 0,
|
|
61
|
+
"refs": 0,
|
|
62
|
+
"refs_refused": 0,
|
|
63
|
+
"refs_none": 0,
|
|
64
|
+
"mem_check": "-",
|
|
65
|
+
"cost": 0.0,
|
|
66
|
+
"status": status,
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def add_references(
|
|
71
|
+
claude: str,
|
|
72
|
+
env: dict,
|
|
73
|
+
root: Path,
|
|
74
|
+
store: Path,
|
|
75
|
+
handle: str,
|
|
76
|
+
**options: Unpack[ReferenceOptions],
|
|
77
|
+
) -> dict | None:
|
|
78
|
+
"""The reference step, one implementation for `--backfill`'s normal-mode twin and the trial harness: one read-only
|
|
79
|
+
session for the due parts of synthesis `handle` (`backfill_one`), None when no part is due. `root` holds the
|
|
80
|
+
step's own folder `root/<handle>`; `done` receives the parts the answer settled."""
|
|
81
|
+
parts = bf.select(store / "syntheses" / f"{handle}.md", {})
|
|
82
|
+
if not parts:
|
|
83
|
+
return None
|
|
84
|
+
done = options.get("done")
|
|
85
|
+
return backfill.backfill_one(
|
|
86
|
+
claude,
|
|
87
|
+
env,
|
|
88
|
+
root,
|
|
89
|
+
store,
|
|
90
|
+
handle,
|
|
91
|
+
parts=parts,
|
|
92
|
+
settings=options["settings"],
|
|
93
|
+
log=options["log"],
|
|
94
|
+
budget_left=options["budget_left"],
|
|
95
|
+
done={} if done is None else done,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass
|
|
100
|
+
class _TopicRun:
|
|
101
|
+
"""The state of one topic's pipeline: its steps put what they learn in `row`, and the sessions they ran in
|
|
102
|
+
`sessions`."""
|
|
103
|
+
|
|
104
|
+
claude: str
|
|
105
|
+
env: dict
|
|
106
|
+
base: Path
|
|
107
|
+
store: Path
|
|
108
|
+
topic: str
|
|
109
|
+
settings: Path
|
|
110
|
+
log: Callable[[str], None]
|
|
111
|
+
budget_left: Callable[[], float] | None
|
|
112
|
+
references: bool
|
|
113
|
+
row: dict = field(init=False)
|
|
114
|
+
sessions: list[dict] = field(default_factory=list)
|
|
115
|
+
ref_cost: float = 0.0
|
|
116
|
+
|
|
117
|
+
def __post_init__(self) -> None:
|
|
118
|
+
self.row = new_row(self.topic)
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def work(self) -> Path:
|
|
122
|
+
return self.base / "work"
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def synthesis(self) -> Path:
|
|
126
|
+
return self.store / "syntheses" / f"{self.topic}.md"
|
|
127
|
+
|
|
128
|
+
def left(self) -> float:
|
|
129
|
+
"""USD still allowed for this topic's next session (only with a budget)."""
|
|
130
|
+
if self.budget_left is None:
|
|
131
|
+
msg = "no budget to count against"
|
|
132
|
+
raise TypeError(msg)
|
|
133
|
+
return self.budget_left() - sum(s["cost"] for s in self.sessions)
|
|
134
|
+
|
|
135
|
+
def remaining(self) -> float | None:
|
|
136
|
+
return None if self.budget_left is None else self.left()
|
|
137
|
+
|
|
138
|
+
def execute(self) -> dict:
|
|
139
|
+
self.work.mkdir(parents=True)
|
|
140
|
+
subprocess.run(["git", "init", "-q"], cwd=self.work, check=True)
|
|
141
|
+
try:
|
|
142
|
+
self._steps()
|
|
143
|
+
except Exception as exc: # a failed topic must not stop the run
|
|
144
|
+
logger.debug("topic %s failed", self.topic, exc_info=True)
|
|
145
|
+
self.row["status"] = f"failed: {type(exc).__name__}: {exc}"[:100]
|
|
146
|
+
finally:
|
|
147
|
+
self._close()
|
|
148
|
+
return self.row
|
|
149
|
+
|
|
150
|
+
def _steps(self) -> None:
|
|
151
|
+
if self.synthesis.exists():
|
|
152
|
+
self.row["status"] = "failed: a synthesis exists already"
|
|
153
|
+
return
|
|
154
|
+
answer = self._write()
|
|
155
|
+
if answer is None or not self._check_and_fix():
|
|
156
|
+
return
|
|
157
|
+
self._attach(answer)
|
|
158
|
+
self.row["parts"] = sr.count_parts(self.synthesis)
|
|
159
|
+
self.row["mem_check"] = sp.mem(self.store, self.env, "check").returncode
|
|
160
|
+
if self.references:
|
|
161
|
+
self.ref_cost = add_topic_references(
|
|
162
|
+
self.claude,
|
|
163
|
+
self.env,
|
|
164
|
+
self.base,
|
|
165
|
+
self.store,
|
|
166
|
+
self.topic,
|
|
167
|
+
settings=self.settings,
|
|
168
|
+
log=self.log,
|
|
169
|
+
row=self.row,
|
|
170
|
+
budget=self.remaining(),
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
def _write(self) -> str | None:
|
|
174
|
+
"""The writer session: its answer, or None when the topic stopped (`status` says why)."""
|
|
175
|
+
remaining = self.remaining()
|
|
176
|
+
if remaining is not None and remaining <= 0:
|
|
177
|
+
self.row["status"] = "failed: budget spent"
|
|
178
|
+
return None
|
|
179
|
+
prompt = (
|
|
180
|
+
f"Topic: {self.topic}\nSlug: {self.topic}\nStore: {self.store}\nWork folder: {self.work}\n"
|
|
181
|
+
f"The memory-synthesis skill file: {sp.SKILL or sp.NOT_GIVEN}"
|
|
182
|
+
)
|
|
183
|
+
w = sp.run_session(
|
|
184
|
+
self.claude,
|
|
185
|
+
"haiku",
|
|
186
|
+
prompt,
|
|
187
|
+
self.work,
|
|
188
|
+
self.settings,
|
|
189
|
+
env=self.env,
|
|
190
|
+
log=self.base / "01-writer.jsonl",
|
|
191
|
+
effort="high",
|
|
192
|
+
agent=sr.AGENT,
|
|
193
|
+
max_budget=remaining,
|
|
194
|
+
read_roots=sp.session_roots(self.store, self.env, self.work),
|
|
195
|
+
)
|
|
196
|
+
w.update(role="writer", model="haiku", costs=sp.cost_by_family(w["model_usage"]))
|
|
197
|
+
self.sessions.append(sp.summary(w))
|
|
198
|
+
answer = w["answer"].strip()
|
|
199
|
+
self.row["status"] = self._writer_status(w, answer)
|
|
200
|
+
return answer if self.row["status"] == "ok" else None
|
|
201
|
+
|
|
202
|
+
def _writer_status(self, writer: dict, answer: str) -> str:
|
|
203
|
+
if self.budget_left is not None and not writer["has_result"]:
|
|
204
|
+
return f"failed: {sp.NO_COST}"
|
|
205
|
+
if not self.sessions[-1]["ok"]:
|
|
206
|
+
return "failed: writer session"
|
|
207
|
+
if answer.startswith("STOP"):
|
|
208
|
+
return f"failed: {answer.splitlines()[0][:80]}"
|
|
209
|
+
if not self.synthesis.is_file():
|
|
210
|
+
return "failed: no synthesis written"
|
|
211
|
+
return "ok"
|
|
212
|
+
|
|
213
|
+
def _check_and_fix(self) -> bool:
|
|
214
|
+
"""The check, fix and delete-only steps; False when the loop ended the topic (`status` says why)."""
|
|
215
|
+
done = sp.lean_loop(
|
|
216
|
+
self.claude,
|
|
217
|
+
self.env,
|
|
218
|
+
self.base,
|
|
219
|
+
self.store,
|
|
220
|
+
self.work,
|
|
221
|
+
settings=self.settings,
|
|
222
|
+
topic=self.topic,
|
|
223
|
+
sessions=self.sessions,
|
|
224
|
+
left=self.left if self.budget_left is not None else None,
|
|
225
|
+
read_roots=sp.session_roots(self.store, self.env, self.work),
|
|
226
|
+
)
|
|
227
|
+
self.log(
|
|
228
|
+
f"{self.topic}: loop {json.dumps({k: v for k, v in done.items() if k != 'arm_count'})}"
|
|
229
|
+
)
|
|
230
|
+
if done["why"]:
|
|
231
|
+
self.row["status"] = f"failed: {done['why']}"
|
|
232
|
+
return False
|
|
233
|
+
first = done["arm_count"]
|
|
234
|
+
self.row["deleted"] = done["deleted"]
|
|
235
|
+
self.row["reverted"] = len(done["reverted"])
|
|
236
|
+
self.row["fixed"] = max(0, (first["unsupported"] if first else 0) - done["deleted"])
|
|
237
|
+
return True
|
|
238
|
+
|
|
239
|
+
def _attach(self, answer: str) -> None:
|
|
240
|
+
for rel, target in sr.attach_lines(answer):
|
|
241
|
+
self.row["attached"] += self._attach_one(rel, target)
|
|
242
|
+
|
|
243
|
+
def _attach_one(self, rel: str, target: str) -> bool:
|
|
244
|
+
note = self.store / rel
|
|
245
|
+
if not note.is_file():
|
|
246
|
+
self.log(f"{self.topic}: attach skipped, no note {rel}")
|
|
247
|
+
return False
|
|
248
|
+
current = sr.part_of(note)
|
|
249
|
+
if current and not current.startswith(f"{self.topic}#"):
|
|
250
|
+
self.log(f"{self.topic}: attach skipped, {rel} is part of s:{current}")
|
|
251
|
+
return False
|
|
252
|
+
out = sp.mem(self.store, self.env, "synthesis", "attach", rel, target)
|
|
253
|
+
if out.returncode:
|
|
254
|
+
self.log(f"{self.topic}: attach failed {rel} {target}: {out.stderr.strip()}")
|
|
255
|
+
return out.returncode == 0
|
|
256
|
+
|
|
257
|
+
def _close(self) -> None:
|
|
258
|
+
self.row["cost"] = sum(s["cost"] for s in self.sessions) + self.ref_cost
|
|
259
|
+
if self.synthesis.is_file() and not self.row["parts"]:
|
|
260
|
+
self.row["parts"] = sr.count_parts(self.synthesis)
|
|
261
|
+
for s in self.sessions:
|
|
262
|
+
self.log(
|
|
263
|
+
f"{self.topic}: {s['role']} {s['model']} ok={s['ok']} cost={s['cost']:.3f} wall={s['wall']:.0f}s "
|
|
264
|
+
f"denied={s['denied']} tool_errors={s['tool_errors']}"
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def run_topic(
|
|
269
|
+
claude: str,
|
|
270
|
+
env: dict,
|
|
271
|
+
root: Path,
|
|
272
|
+
store: Path,
|
|
273
|
+
topic: str,
|
|
274
|
+
**options: Unpack[TopicOptions],
|
|
275
|
+
) -> dict:
|
|
276
|
+
"""Run the pipeline for one topic; the row never raises: a failed step is `status`. The last step adds references:
|
|
277
|
+
its failure leaves the synthesis as the loop left it (`status` says so) and a later `--backfill` sends it."""
|
|
278
|
+
return _TopicRun(
|
|
279
|
+
claude=claude,
|
|
280
|
+
env=env,
|
|
281
|
+
base=root / topic,
|
|
282
|
+
store=store,
|
|
283
|
+
topic=topic,
|
|
284
|
+
settings=options["settings"],
|
|
285
|
+
log=options["log"],
|
|
286
|
+
budget_left=options.get("budget_left"),
|
|
287
|
+
references=options.get("references", True),
|
|
288
|
+
).execute()
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _reference_status(result: dict, topic: str) -> str | None:
|
|
292
|
+
"""The topic's new `status` after the reference step, None when the step left it a pass."""
|
|
293
|
+
if (
|
|
294
|
+
result["applied"] and result["mem_check"] != 0
|
|
295
|
+
): # the step wrote, and the store no longer checks
|
|
296
|
+
return f"failed: mem check exit {result['mem_check']} after references (undo: mem restore s:{topic})"
|
|
297
|
+
if result["status"] != "ok":
|
|
298
|
+
return f"ok, references not added: {result['status'].removeprefix('failed: ')}"[:100]
|
|
299
|
+
return None
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _save_done_list(store: Path, topic: str, done: dict, log: Callable[[str], None]) -> None:
|
|
303
|
+
try:
|
|
304
|
+
bf.save_done(backfill.done_file(), str(Path(store).resolve()), topic, done)
|
|
305
|
+
except Exception as exc: # the references are applied; the next `--backfill` just asks again
|
|
306
|
+
logger.debug("%s: done list not saved", topic, exc_info=True)
|
|
307
|
+
log(f"{topic}: done list not saved: {exc}")
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def add_topic_references(
|
|
311
|
+
claude: str,
|
|
312
|
+
env: dict,
|
|
313
|
+
base: Path,
|
|
314
|
+
store: Path,
|
|
315
|
+
topic: str,
|
|
316
|
+
**options: Unpack[TopicReferenceOptions],
|
|
317
|
+
) -> float:
|
|
318
|
+
"""Run the reference step after a successful topic and put its figures in `row`; returns its cost. A step that
|
|
319
|
+
did not run or did not finish leaves the topic a pass (`ok, references not added: ...`); the one failure is a
|
|
320
|
+
`mem check` that no longer exits 0 after references were written. A success is marked in the done list as
|
|
321
|
+
`--backfill` marks it; a failure is not, so a later `--backfill` sends the synthesis."""
|
|
322
|
+
row, budget = options["row"], options["budget"]
|
|
323
|
+
if (
|
|
324
|
+
budget is not None and budget < sr.ESTIMATE_PER_BACKFILL
|
|
325
|
+
): # a session capped below its usual cost only spends
|
|
326
|
+
row["status"] = "ok, references not added: budget spent"
|
|
327
|
+
return 0.0
|
|
328
|
+
done: dict = {}
|
|
329
|
+
try:
|
|
330
|
+
result = add_references(
|
|
331
|
+
claude,
|
|
332
|
+
env,
|
|
333
|
+
base / "references",
|
|
334
|
+
store,
|
|
335
|
+
topic,
|
|
336
|
+
settings=options["settings"],
|
|
337
|
+
log=options["log"],
|
|
338
|
+
budget_left=budget,
|
|
339
|
+
done=done,
|
|
340
|
+
)
|
|
341
|
+
except Exception as exc: # selecting the parts failed: the synthesis stays as the loop left it
|
|
342
|
+
logger.debug("topic %s: references not added", topic, exc_info=True)
|
|
343
|
+
row["status"] = f"ok, references not added: {type(exc).__name__}: {exc}"[:100]
|
|
344
|
+
return 0.0
|
|
345
|
+
if result is None:
|
|
346
|
+
return 0.0
|
|
347
|
+
row.update(
|
|
348
|
+
refs=result["applied"],
|
|
349
|
+
refs_refused=result["refused"],
|
|
350
|
+
refs_none=result["none"],
|
|
351
|
+
mem_check=result["mem_check"],
|
|
352
|
+
)
|
|
353
|
+
status = _reference_status(result, topic)
|
|
354
|
+
if status is not None:
|
|
355
|
+
row["status"] = status
|
|
356
|
+
elif done:
|
|
357
|
+
_save_done_list(store, topic, done, options["log"])
|
|
358
|
+
return result["cost"]
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def table(rows: list[dict]) -> str:
|
|
362
|
+
lines = [
|
|
363
|
+
sr.HEADER,
|
|
364
|
+
*(
|
|
365
|
+
(
|
|
366
|
+
r["topic"],
|
|
367
|
+
r["parts"],
|
|
368
|
+
r["attached"],
|
|
369
|
+
r["fixed"],
|
|
370
|
+
r["deleted"],
|
|
371
|
+
r["reverted"],
|
|
372
|
+
r["refs"],
|
|
373
|
+
r["refs_refused"],
|
|
374
|
+
r["refs_none"],
|
|
375
|
+
r["mem_check"],
|
|
376
|
+
f"{r['cost']:.3f}",
|
|
377
|
+
r["status"],
|
|
378
|
+
)
|
|
379
|
+
for r in rows
|
|
380
|
+
),
|
|
381
|
+
]
|
|
382
|
+
return sr._aligned(lines)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _dry_run_line(topics: list[str], budget: float, *, references: bool) -> str:
|
|
386
|
+
each = sr.ESTIMATE_PER_TOPIC + (sr.ESTIMATE_PER_BACKFILL if references else 0.0)
|
|
387
|
+
step = (
|
|
388
|
+
"each ends with a reference step (--no-references skips it); "
|
|
389
|
+
if references
|
|
390
|
+
else "no reference step; "
|
|
391
|
+
)
|
|
392
|
+
return (
|
|
393
|
+
f"mem-synthesize dry run: {len(topics)} topics: {', '.join(topics)}; {step}"
|
|
394
|
+
f"estimated cost {len(topics) * each:.2f} USD (budget {budget:.2f})"
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
@dataclass
|
|
399
|
+
class _TopicBatch:
|
|
400
|
+
"""The topics of one run, one after the other, with the budget they share."""
|
|
401
|
+
|
|
402
|
+
claude: str
|
|
403
|
+
env: dict
|
|
404
|
+
root: Path
|
|
405
|
+
store: Path
|
|
406
|
+
settings: Path
|
|
407
|
+
log: Callable[[str], None]
|
|
408
|
+
budget: float
|
|
409
|
+
references: bool
|
|
410
|
+
rows_out: list[dict] | None
|
|
411
|
+
rows: list[dict] = field(default_factory=list)
|
|
412
|
+
spent: float = 0.0
|
|
413
|
+
unknown: bool = False
|
|
414
|
+
|
|
415
|
+
def run(self, topics: list[str]) -> None:
|
|
416
|
+
for topic in topics:
|
|
417
|
+
if self.spent >= self.budget or self.unknown:
|
|
418
|
+
row = new_row(topic, "not started: budget")
|
|
419
|
+
else:
|
|
420
|
+
row = self._topic(topic)
|
|
421
|
+
self.rows.append(row)
|
|
422
|
+
if self.rows_out is not None:
|
|
423
|
+
self.rows_out.append(row)
|
|
424
|
+
|
|
425
|
+
def _topic(self, topic: str) -> dict:
|
|
426
|
+
self.log(f"{topic}: start (spent {self.spent:.3f})")
|
|
427
|
+
remaining = self.budget - self.spent
|
|
428
|
+
row = run_topic(
|
|
429
|
+
self.claude,
|
|
430
|
+
self.env,
|
|
431
|
+
self.root,
|
|
432
|
+
self.store,
|
|
433
|
+
topic,
|
|
434
|
+
settings=self.settings,
|
|
435
|
+
log=self.log,
|
|
436
|
+
budget_left=lambda: remaining,
|
|
437
|
+
references=self.references,
|
|
438
|
+
)
|
|
439
|
+
self.spent += row["cost"]
|
|
440
|
+
self.log(f"{topic}: {row}")
|
|
441
|
+
if sp.NO_COST in row["status"]:
|
|
442
|
+
self.unknown = True
|
|
443
|
+
return row
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _synthesize(
|
|
447
|
+
claude: str,
|
|
448
|
+
env: dict,
|
|
449
|
+
store: Path,
|
|
450
|
+
topics: list[str],
|
|
451
|
+
budget: float,
|
|
452
|
+
**options: Unpack[RunOptions],
|
|
453
|
+
) -> int:
|
|
454
|
+
out = options.get("out", sr.say)
|
|
455
|
+
root = (
|
|
456
|
+
options.get("root")
|
|
457
|
+
or sr.state_dir() / f"synthesize-{time.strftime('%Y%m%d-%H%M%S')}-{os.getpid()}"
|
|
458
|
+
)
|
|
459
|
+
root.mkdir(mode=0o700, parents=True) # the sessions' transcripts are private
|
|
460
|
+
log_file = root / "log.txt"
|
|
461
|
+
log = sr._file_logger(log_file)
|
|
462
|
+
out(
|
|
463
|
+
f"mem-synthesize: {len(topics)} topics ({', '.join(topics)}), budget {budget:.2f} USD, log {log_file}"
|
|
464
|
+
)
|
|
465
|
+
settings = root / "settings.json"
|
|
466
|
+
settings.write_text(
|
|
467
|
+
json.dumps({
|
|
468
|
+
"pluginConfigs": {"memory": {"options": {"store": str(store)}}},
|
|
469
|
+
"disableAllHooks": True,
|
|
470
|
+
}),
|
|
471
|
+
encoding="utf-8",
|
|
472
|
+
) # no session-end hook may commit between our two
|
|
473
|
+
label = ", ".join(topics)
|
|
474
|
+
sr.history_commit(store, env, f"mem-synthesize: before {label}", log)
|
|
475
|
+
batch = _TopicBatch(
|
|
476
|
+
claude=claude,
|
|
477
|
+
env=env,
|
|
478
|
+
root=root,
|
|
479
|
+
store=store,
|
|
480
|
+
settings=settings,
|
|
481
|
+
log=log,
|
|
482
|
+
budget=budget,
|
|
483
|
+
references=options.get("references", True),
|
|
484
|
+
rows_out=options.get("rows_out"),
|
|
485
|
+
)
|
|
486
|
+
batch.run(topics)
|
|
487
|
+
sr.history_commit(store, env, f"mem-synthesize: after {label}", log)
|
|
488
|
+
out(table(batch.rows))
|
|
489
|
+
out(f"total cost USD {batch.spent:.3f}; log {log_file}")
|
|
490
|
+
return (
|
|
491
|
+
0 if all(r["status"].split(",")[0] == "ok" for r in batch.rows) else 1
|
|
492
|
+
) # "ok, references not added" is a pass
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def run(
|
|
496
|
+
claude: str | None,
|
|
497
|
+
store: Path,
|
|
498
|
+
topics: list[str],
|
|
499
|
+
budget: float,
|
|
500
|
+
dry_run: bool,
|
|
501
|
+
**options: Unpack[RunOptions],
|
|
502
|
+
) -> int:
|
|
503
|
+
"""`root`: the run folder (default: a new one in the state folder, mode 0700); `rows_out` receives the rows;
|
|
504
|
+
`references=False` skips the last step (adding references)."""
|
|
505
|
+
out = options.get("out", sr.say)
|
|
506
|
+
env = sr.session_env(store)
|
|
507
|
+
if not topics:
|
|
508
|
+
found = sp.mem(store, env, "curate", "--notes")
|
|
509
|
+
if found.returncode:
|
|
510
|
+
print(
|
|
511
|
+
f"mem-synthesize: mem curate --notes failed: {found.stderr.strip()}",
|
|
512
|
+
file=sys.stderr,
|
|
513
|
+
)
|
|
514
|
+
return 2
|
|
515
|
+
topics = sr.topics_without_synthesis(found.stdout)
|
|
516
|
+
if not topics:
|
|
517
|
+
out("mem-synthesize: no topic without a synthesis")
|
|
518
|
+
return 0
|
|
519
|
+
if dry_run:
|
|
520
|
+
out(_dry_run_line(topics, budget, references=options.get("references", True)))
|
|
521
|
+
return 0
|
|
522
|
+
if not claude:
|
|
523
|
+
print(
|
|
524
|
+
"mem-synthesize: no claude binary (use --claude, or CLAUDE_CODE_EXECPATH)",
|
|
525
|
+
file=sys.stderr,
|
|
526
|
+
)
|
|
527
|
+
return 2
|
|
528
|
+
return _synthesize(claude, env, store, topics, budget, **options)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
---
|
|
2
|
+
claim: "<the conclusion in one sentence>"
|
|
3
|
+
topics: ["<topic-id>"]
|
|
4
|
+
confidence: "<high|medium|low>"
|
|
5
|
+
origin: "<literature|research|experience>"
|
|
6
|
+
updated: "<YYYY-MM-DD>"
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Claim
|
|
10
|
+
|
|
11
|
+
TODO(hub): the conclusion, stated precisely
|
|
12
|
+
|
|
13
|
+
## Evidence
|
|
14
|
+
|
|
15
|
+
TODO(hub): relative links to literature or research notes, or the anonymized experience; prefix our own reasoning with "Inference:"
|
|
16
|
+
|
|
17
|
+
## Applies when
|
|
18
|
+
|
|
19
|
+
TODO(hub): conditions under which the claim holds
|
|
20
|
+
|
|
21
|
+
## Does not apply when
|
|
22
|
+
|
|
23
|
+
TODO(hub): known exceptions and limits
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "<title>"
|
|
3
|
+
authors: ["<first-author-surname-or-publisher>"]
|
|
4
|
+
year: "<year>"
|
|
5
|
+
kind: "<paper|book|article|web|talk|repo|dataset>"
|
|
6
|
+
url: "<https-url>"
|
|
7
|
+
topics: ["<topic-id>"]
|
|
8
|
+
added: "<YYYY-MM-DD>"
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## TL;DR
|
|
12
|
+
|
|
13
|
+
TODO(hub): 1-3 lines on what the source contributes
|
|
14
|
+
|
|
15
|
+
## What the source says
|
|
16
|
+
|
|
17
|
+
TODO(hub): the source's own claims, faithfully summarized
|
|
18
|
+
|
|
19
|
+
## Our interpretation
|
|
20
|
+
|
|
21
|
+
TODO(hub): our reading, opinions and caveats, kept apart from the source's claims
|
|
22
|
+
|
|
23
|
+
## Relevance
|
|
24
|
+
|
|
25
|
+
TODO(hub): why this source matters and where it applies
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "<title>"
|
|
3
|
+
question: "<the question in one sentence>"
|
|
4
|
+
status: "<idea|active|paused|done|abandoned>"
|
|
5
|
+
started: "<YYYY-MM>"
|
|
6
|
+
topics: ["<topic-id>"]
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Question
|
|
10
|
+
|
|
11
|
+
TODO(hub): the question pursued, and the hypothesis if any
|
|
12
|
+
|
|
13
|
+
## Status
|
|
14
|
+
|
|
15
|
+
TODO(hub): where the investigation stands and the next step
|
|
16
|
+
|
|
17
|
+
## Findings
|
|
18
|
+
|
|
19
|
+
TODO(hub): what was found; one line and a link per finding promoted to knowledge
|
|
20
|
+
|
|
21
|
+
## Contents
|
|
22
|
+
|
|
23
|
+
TODO(hub): list of the notes, code, results and write-up in this folder
|