memory-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. memory_cli/__init__.py +1 -0
  2. memory_cli/__main__.py +49 -0
  3. memory_cli/capture/__init__.py +7 -0
  4. memory_cli/capture/codex_rollout.py +164 -0
  5. memory_cli/capture/event_lines.py +66 -0
  6. memory_cli/capture/extract.py +458 -0
  7. memory_cli/capture/state.py +183 -0
  8. memory_cli/commands/__init__.py +21 -0
  9. memory_cli/commands/admin.py +363 -0
  10. memory_cli/commands/common.py +609 -0
  11. memory_cli/commands/curate.py +1189 -0
  12. memory_cli/commands/diagnostics.py +126 -0
  13. memory_cli/commands/edit.py +1282 -0
  14. memory_cli/commands/hooks.py +730 -0
  15. memory_cli/commands/import_recovery.py +45 -0
  16. memory_cli/commands/install.py +152 -0
  17. memory_cli/commands/integrate.py +480 -0
  18. memory_cli/commands/memory.py +2152 -0
  19. memory_cli/commands/read.py +1290 -0
  20. memory_cli/commands/sources.py +766 -0
  21. memory_cli/commands/split.py +97 -0
  22. memory_cli/commands/split_plan.py +196 -0
  23. memory_cli/commands/split_transaction.py +230 -0
  24. memory_cli/commands/synthesis.py +1122 -0
  25. memory_cli/core/__init__.py +16 -0
  26. memory_cli/core/auto_state.py +30 -0
  27. memory_cli/core/codex_pass.py +109 -0
  28. memory_cli/core/config.py +87 -0
  29. memory_cli/core/file_journal.py +163 -0
  30. memory_cli/core/headless.py +130 -0
  31. memory_cli/core/jobs.py +130 -0
  32. memory_cli/core/resources.py +57 -0
  33. memory_cli/core/runner.py +398 -0
  34. memory_cli/core/safe_io.py +155 -0
  35. memory_cli/core/store_git.py +407 -0
  36. memory_cli/core/yaml_load.py +14 -0
  37. memory_cli/corroborate/__init__.py +11 -0
  38. memory_cli/corroborate/cli.py +267 -0
  39. memory_cli/corroborate/decide.py +893 -0
  40. memory_cli/corroborate/digest.py +425 -0
  41. memory_cli/corroborate/fill.py +744 -0
  42. memory_cli/corroborate/job.py +15 -0
  43. memory_cli/corroborate/reword.py +446 -0
  44. memory_cli/corroborate/run.py +1142 -0
  45. memory_cli/corroborate/state.py +300 -0
  46. memory_cli/digest/__init__.py +4 -0
  47. memory_cli/digest/lessons.py +483 -0
  48. memory_cli/entry/__init__.py +12 -0
  49. memory_cli/entry/auto.py +660 -0
  50. memory_cli/entry/capture.py +1403 -0
  51. memory_cli/entry/corroborate.py +214 -0
  52. memory_cli/entry/integrate.py +684 -0
  53. memory_cli/entry/integrate_self_check.py +203 -0
  54. memory_cli/entry/research.py +9 -0
  55. memory_cli/entry/settle.py +614 -0
  56. memory_cli/entry/split_auto.py +460 -0
  57. memory_cli/entry/synthesize.py +22 -0
  58. memory_cli/integrate/__init__.py +9 -0
  59. memory_cli/integrate/answers.py +42 -0
  60. memory_cli/integrate/briefs/check-brief.md +16 -0
  61. memory_cli/integrate/briefs/place-brief.md +26 -0
  62. memory_cli/integrate/log.py +43 -0
  63. memory_cli/integrate/plan.py +125 -0
  64. memory_cli/integrate/rows.py +99 -0
  65. memory_cli/integrate/state.py +158 -0
  66. memory_cli/integrate/undo.py +143 -0
  67. memory_cli/mem.py +1180 -0
  68. memory_cli/memories/__init__.py +16 -0
  69. memory_cli/memories/fingerprints.py +51 -0
  70. memory_cli/memories/journal.py +93 -0
  71. memory_cli/memories/locations.py +282 -0
  72. memory_cli/memories/matching.py +451 -0
  73. memory_cli/memories/model.py +205 -0
  74. memory_cli/memories/parse.py +237 -0
  75. memory_cli/memories/records.py +266 -0
  76. memory_cli/memories/rules.py +291 -0
  77. memory_cli/memories/sightings.py +314 -0
  78. memory_cli/memories/terms.py +148 -0
  79. memory_cli/memories/write.py +358 -0
  80. memory_cli/notes/__init__.py +13 -0
  81. memory_cli/notes/check.py +806 -0
  82. memory_cli/notes/due.py +260 -0
  83. memory_cli/notes/fields.py +217 -0
  84. memory_cli/notes/index.py +230 -0
  85. memory_cli/notes/links.py +170 -0
  86. memory_cli/notes/note.py +222 -0
  87. memory_cli/notes/search.py +391 -0
  88. memory_cli/notes/split_candidates.py +72 -0
  89. memory_cli/research/__init__.py +5 -0
  90. memory_cli/research/checks.py +1065 -0
  91. memory_cli/research/pipeline.py +952 -0
  92. memory_cli/session/__init__.py +5 -0
  93. memory_cli/session/handoff.py +139 -0
  94. memory_cli/session/notices.py +111 -0
  95. memory_cli/settle/__init__.py +5 -0
  96. memory_cli/settle/state.py +111 -0
  97. memory_cli/settle/verdicts.py +693 -0
  98. memory_cli/split/briefs/checker-brief.md +5 -0
  99. memory_cli/split/briefs/editor-brief.md +20 -0
  100. memory_cli/syntheses/__init__.py +8 -0
  101. memory_cli/syntheses/document.py +400 -0
  102. memory_cli/syntheses/edit.py +581 -0
  103. memory_cli/syntheses/project.py +384 -0
  104. memory_cli/syntheses/split_conservation.py +50 -0
  105. memory_cli/syntheses/units.py +427 -0
  106. memory_cli/synthesize/__init__.py +9 -0
  107. memory_cli/synthesize/backfill.py +431 -0
  108. memory_cli/synthesize/briefs/backfill-brief.md +26 -0
  109. memory_cli/synthesize/briefs/checker-brief.md +13 -0
  110. memory_cli/synthesize/briefs/fixer-brief.md +19 -0
  111. memory_cli/synthesize/briefs/memory-brief.md +30 -0
  112. memory_cli/synthesize/briefs/settle-brief.md +32 -0
  113. memory_cli/synthesize/briefs/verdict-brief.md +50 -0
  114. memory_cli/synthesize/briefs/web-brief.md +33 -0
  115. memory_cli/synthesize/cli.py +311 -0
  116. memory_cli/synthesize/pipeline.py +764 -0
  117. memory_cli/synthesize/references.py +164 -0
  118. memory_cli/synthesize/run.py +150 -0
  119. memory_cli/synthesize/topics.py +528 -0
  120. memory_cli/templates/knowledge.md +23 -0
  121. memory_cli/templates/literature.md +25 -0
  122. memory_cli/templates/research.md +23 -0
  123. memory_cli/templates/synthesis.md +6 -0
  124. memory_cli-0.1.0.dist-info/METADATA +102 -0
  125. memory_cli-0.1.0.dist-info/RECORD +128 -0
  126. memory_cli-0.1.0.dist-info/WHEEL +4 -0
  127. memory_cli-0.1.0.dist-info/entry_points.txt +9 -0
  128. memory_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,952 @@
1
+ """`mem-research`: answer a question from memory, then (by depth) check notes and the question against the web.
2
+
3
+ Plan 2026-11-17-memory-seamless, stage 1b. Five steps, three of them model sessions and none with a shell:
4
+ 1 memory (Python runs `mem search`; a Haiku session reads the results and writes `need.json`; at most one more round),
5
+ 2 web input (`research.checks.web_input`: only what passes the secret and forbidden-terms checks), 3 web (a Haiku
6
+ session with WebSearch and WebFetch only, in an empty folder, with no `mem` and no `MEM_*` around it), 4 check (Python
7
+ fetches each page and picks the passages), 5 verdict (a Haiku session reads the passages as data and writes
8
+ `verdicts.json`), 6 apply (Python enforces quotes, URLs and stances, then runs three fixed `mem` commands).
9
+ Every step's input and output stay in the run folder. Standard library only; the run never reads or writes the
10
+ `mem-auto` or settle state.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import functools
17
+ import hashlib
18
+ import json
19
+ import logging
20
+ import math
21
+ import os
22
+ import re
23
+ import shutil
24
+ import sys
25
+ import tempfile
26
+ import time
27
+ from pathlib import Path
28
+ from typing import Any, Required, TypedDict, Unpack
29
+
30
+ from memory_cli.core import codex_pass, config, headless, jobs
31
+ from memory_cli.core import runner as runners
32
+ from memory_cli.memories.records import tokenize
33
+ from memory_cli.notes.note import FrontmatterError, split_frontmatter
34
+ from memory_cli.research import checks as rc
35
+ from memory_cli.synthesize import pipeline as sp
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+ DEPTHS = ("memory", "contrast", "deep")
40
+ DEFAULT_DEPTH = "contrast"
41
+ LIMITS = {
42
+ "memory": (0.25, 180),
43
+ "contrast": (0.50, 300),
44
+ "deep": (2.00, 540),
45
+ } # (USD, seconds) for the whole run; under the 10 minutes a shell call of an agent may last
46
+ PAGES = {"contrast": 5, "deep": 15}
47
+ SHARE = {
48
+ "memory": 0.15,
49
+ "web": 0.55,
50
+ } # of the budget, at most, per such session; the verdict gets what is left
51
+ MAX_NOTES = 8 # notes contrasted in one run: the web prompt and the passages stay bounded
52
+ SEARCHES = 3 # extra searches the memory session may ask for
53
+ SEARCH_LIMIT = 5 # results per `mem search`
54
+ SHOWN = 6 # `mem show` calls per run
55
+ SHOW_CHARS, RESULT_CHARS = 1500, 8000
56
+ MEMORY_ROUNDS = 2 # the memory session runs once, and once more when it asks for searches
57
+ EPSILON = 1e-9 # a budget below this counts as spent
58
+ KEEP_SECONDS = 30 * 86400
59
+ RESULT_LINE = re.compile(r"^knowledge/[^\t]*?([^/\t]+)\.md\t", re.MULTILINE)
60
+ URL = re.compile(r"https?://[^\s\"'<>)\]]+")
61
+
62
+
63
+ class StopError(Exception):
64
+ """The run ends here and reports what it has."""
65
+
66
+
67
+ class ResearchOptions(TypedDict, total=False):
68
+ """The settings of one `research` run; `contrast` and `allow_hosts` default to none."""
69
+
70
+ depth: Required[str]
71
+ contrast: list[str]
72
+ claude: Required[str | None]
73
+ budget: Required[float]
74
+ seconds: Required[float]
75
+ allow_hosts: list[str]
76
+
77
+
78
+ class StepOptions(TypedDict, total=False):
79
+ """What the steps after the memory step need; `contrast` and `allow_hosts` default to none."""
80
+
81
+ question: Required[str]
82
+ claude: Required[str]
83
+ depth: Required[str]
84
+ contrast: list[str]
85
+ allow_hosts: list[str]
86
+ settings: Required[Path]
87
+
88
+
89
+ # ---- places and environments ----
90
+
91
+
92
+ state_dir = jobs.state_dir
93
+
94
+
95
+ def default_store() -> Path | None:
96
+ return config.resolve_store(None, os.environ)
97
+
98
+
99
+ def runs_dir(store: Path) -> Path:
100
+ return (
101
+ state_dir()
102
+ / "research"
103
+ / hashlib.sha1(str(store.resolve()).encode()).hexdigest()[:12]
104
+ / "runs"
105
+ )
106
+
107
+
108
+ def mem_env(store: Path) -> dict[str, str]:
109
+ """The `mem` calls: aimed at `store`; a configured memories folder is kept; no other project's memories."""
110
+ # The left side is an environment variable name: a str, so a set literal is safe.
111
+ env = {
112
+ k: v
113
+ for k, v in os.environ.items()
114
+ if k not in {"MEM_STORE", "MEM_PROJECT"} and not k.startswith("CLAUDE_PLUGIN_OPTION_")
115
+ }
116
+ env["PATH"] = os.pathsep.join(
117
+ p for p in env.get("PATH", "").split(os.pathsep) if "/plugins/cache/" not in p
118
+ )
119
+ env["MEM_STORE"] = str(store)
120
+ return env
121
+
122
+
123
+ # ---- sessions ----
124
+
125
+
126
+ def file_cmd(claude: str, prompt: str, work: Path, settings: Path, max_budget: float) -> list[str]:
127
+ """A session of the memory or verdict step. Only Read, Write and Edit exist (`--tools`, no MCP server), and the
128
+ rules allow them inside `work` only (`//` is an absolute path in a permission rule); no shell, no web."""
129
+ return headless.command(
130
+ headless.Session(
131
+ claude=claude,
132
+ prompt=prompt,
133
+ model="haiku",
134
+ effort="medium",
135
+ settings=settings,
136
+ tools=("Read", "Write", "Edit"),
137
+ allowed=(f"Read(/{work}/**)", f"Write(/{work}/**)", f"Edit(/{work}/**)"),
138
+ max_budget=max_budget,
139
+ )
140
+ )
141
+
142
+
143
+ def web_cmd(claude: str, prompt: str, settings: Path, max_budget: float) -> list[str]:
144
+ """The web session: only WebSearch and WebFetch, no MCP server, no plugin, hooks off, project settings only.
145
+ `--tools` says which tools exist; a headless session still needs the permission to call them."""
146
+ return headless.command(
147
+ headless.Session(
148
+ claude=claude,
149
+ prompt=prompt,
150
+ model="haiku",
151
+ effort="medium",
152
+ settings=settings,
153
+ tools=("WebSearch", "WebFetch"),
154
+ allowed=("WebSearch", "WebFetch"),
155
+ max_budget=max_budget,
156
+ )
157
+ )
158
+
159
+
160
+ def _dict_or_empty(value: object) -> dict[str, Any]:
161
+ return value if isinstance(value, dict) else {}
162
+
163
+
164
+ def _stream_events(raw: str) -> list[dict[str, Any]]:
165
+ """The lines of a session stream that are JSON objects."""
166
+ events: list[dict[str, Any]] = []
167
+ for line in raw.splitlines():
168
+ try:
169
+ event = json.loads(line)
170
+ except ValueError:
171
+ continue
172
+ if isinstance(event, dict):
173
+ events.append(event)
174
+ return events
175
+
176
+
177
+ def _content_parts(event: dict[str, Any]) -> list[dict[str, Any]]:
178
+ content = _dict_or_empty(event.get("message")).get("content")
179
+ return [part for part in content if isinstance(part, dict)] if isinstance(content, list) else []
180
+
181
+
182
+ def _tool_use_inputs(part: dict[str, Any]) -> tuple[str | None, str | None]:
183
+ """(query, url) a tool call was given, each None when absent or not a string."""
184
+ given = _dict_or_empty(part.get("input"))
185
+ query = given.get("query") if part.get("name") == "WebSearch" else None
186
+ url = given.get("url")
187
+ return (
188
+ query if isinstance(query, str) else None,
189
+ url if isinstance(url, str) else None,
190
+ )
191
+
192
+
193
+ def _result_text(body: Any) -> str:
194
+ if isinstance(body, str):
195
+ return body
196
+ return " ".join(b.get("text", "") for b in body or [] if isinstance(b, dict))
197
+
198
+
199
+ def _collect_part(part: dict[str, Any], queries: list[str], urls: list[str]) -> None:
200
+ """Add the query and URLs of one content part of the stream to `queries` and `urls`."""
201
+ if part.get("type") == "tool_use":
202
+ query, url = _tool_use_inputs(part)
203
+ if query is not None:
204
+ queries.append(query)
205
+ if url is not None:
206
+ urls.append(url)
207
+ elif part.get("type") == "tool_result":
208
+ urls += URL.findall(_result_text(part.get("content")))
209
+
210
+
211
+ def web_events(raw: str) -> dict[str, list[str]]:
212
+ """What the web session searched and fetched, from its stream: queries, and every URL its tools were given or
213
+ returned."""
214
+ queries: list[str] = []
215
+ urls: list[str] = []
216
+ for event in _stream_events(raw):
217
+ for part in _content_parts(event):
218
+ _collect_part(part, queries, urls)
219
+ return {"queries": list(dict.fromkeys(queries)), "urls": list(dict.fromkeys(urls))}
220
+
221
+
222
+ def render(name: str, **values: str) -> str:
223
+ """A brief with its `{PLACEHOLDER}`s filled in one pass, so a value that holds braces is never read as one."""
224
+ text = (sp.BRIEFS / f"{name}-brief.md").read_text()
225
+ return re.sub(r"\{([A-Z_]+)\}", lambda m: values.get(m.group(1), m.group(0)), text)
226
+
227
+
228
+ class Run:
229
+ """One run's folder, spend and clock."""
230
+
231
+ def __init__(self, folder: Path, budget: float, seconds: float):
232
+ self.folder, self.budget = folder, budget
233
+ self.deadline = time.monotonic() + seconds
234
+ self.cost = 0.0
235
+ self.sessions: list[dict[str, Any]] = []
236
+ self.status: dict[str, Any] = {}
237
+
238
+ def left(self) -> float:
239
+ return self.budget - self.cost
240
+
241
+ def seconds_left(self) -> float:
242
+ return self.deadline - time.monotonic()
243
+
244
+ def log(self, text: str) -> None:
245
+ fd = os.open(self.folder / "log.txt", os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
246
+ with os.fdopen(fd, "a") as f:
247
+ f.write(f"{time.strftime('%H:%M:%S')} {text}\n")
248
+
249
+ def save(self, **changes: Any) -> None:
250
+ self.status.update(changes)
251
+ jobs.write_json(self.folder / jobs.STATUS_NAME, self.status)
252
+
253
+ def step_dir(self, name: str) -> Path:
254
+ folder = self.folder / name
255
+ jobs.private_dir(folder / "work")
256
+ return folder
257
+
258
+ def session(
259
+ self, name: str, cmd: list[str], cwd: Path, env: dict[str, str], prompt: str
260
+ ) -> dict:
261
+ """Run one session, keep its prompt and stream next to its work folder, count its spend."""
262
+ folder = cwd.parent
263
+ (folder / "brief.txt").write_text(prompt, encoding="utf-8")
264
+ start = time.monotonic()
265
+ try:
266
+ out = headless.run_raw(cmd, cwd=cwd, env=env, timeout=max(1.0, self.seconds_left()))
267
+ raw = out.stdout
268
+ failed = "time limit reached" if out.timed_out else ""
269
+ except OSError as exc:
270
+ raw, failed = "", f"cannot start claude: {exc}"
271
+ (folder / "session.jsonl").write_text(raw)
272
+ result = sp.parse(raw)
273
+ result["raw"] = raw
274
+ self.cost += result["cost"]
275
+ self.sessions.append({
276
+ "step": name,
277
+ "cost": result["cost"],
278
+ "wall": round(time.monotonic() - start, 1),
279
+ })
280
+ self.save(cost=self.cost, sessions=self.sessions)
281
+ self.log(
282
+ f"{name}: has_result={result['has_result']} error={result['error']} cost={result['cost']:.3f} {failed}"
283
+ )
284
+ if failed:
285
+ raise StopError(failed)
286
+ if not result["has_result"]:
287
+ raise StopError(sp.NO_COST)
288
+ if result["error"]:
289
+ raise StopError(
290
+ f"the {name} session failed: {' '.join(result['answer'].split())[:150]}"
291
+ )
292
+ return result
293
+
294
+ def gate(self, share: float | None) -> float:
295
+ """The `--max-budget-usd` of the next session; StopError when nothing is left."""
296
+ if self.left() <= EPSILON:
297
+ raise StopError(f"budget spent ({self.cost:.2f} of {self.budget:.2f} USD)")
298
+ if self.seconds_left() <= 0:
299
+ raise StopError("time limit reached")
300
+ return min(self.left(), share * self.budget) if share else self.left()
301
+
302
+
303
+ # ---- step 1: memory ----
304
+
305
+
306
+ def mem_text(store: Path, *args: str) -> str:
307
+ done = sp.mem(store, mem_env(store), *args)
308
+ return (
309
+ done.stdout
310
+ if done.returncode == 0
311
+ else f"(mem {args[0]} failed: {(done.stderr or done.stdout).strip()[:200]})"
312
+ ).strip()
313
+
314
+
315
+ def search_block(store: Path, query: str, shown: set[str]) -> str:
316
+ """`mem search` for one query (one argument, no shell) and `mem show` for its first knowledge results."""
317
+ found = mem_text(store, "search", "--limit", str(SEARCH_LIMIT), "--", query)
318
+ block = [f"## search: {query}", found[:RESULT_CHARS] or "(no results)"]
319
+ for handle in RESULT_LINE.findall(found):
320
+ if len(shown) >= SHOWN:
321
+ break
322
+ if handle in shown:
323
+ continue
324
+ shown.add(handle)
325
+ text = mem_text(store, "show", handle, "--section", "conclusion")
326
+ block += [f"## show: {handle}", text[:SHOW_CHARS] or "(nothing)"]
327
+ return "\n".join(block) + "\n"
328
+
329
+
330
+ def knowledge_notes(store: Path) -> dict[str, Path]:
331
+ return {
332
+ p.stem: p for p in sorted((store / "knowledge").glob("*/*.md")) if p.name != "README.md"
333
+ }
334
+
335
+
336
+ def _search_texts(value: object) -> list[str]:
337
+ """The distinct, searchable queries of `more_searches`: whitespace collapsed, at most 200 characters each."""
338
+ searches: list[str] = []
339
+ for item in value if isinstance(value, list) else []:
340
+ text = " ".join(item.split())[:200] if isinstance(item, str) else ""
341
+ if text and tokenize(text) and text not in searches:
342
+ searches.append(text)
343
+ return searches
344
+
345
+
346
+ def read_need(path: Path) -> dict | str:
347
+ """`need.json` as a dict with `answer`, `covers`, `more_searches`, `contrast`; else why not."""
348
+ try:
349
+ data = json.loads(path.read_text(encoding="utf-8"))
350
+ except (OSError, ValueError):
351
+ return "the memory session wrote no valid need.json"
352
+ if (
353
+ not isinstance(data, dict)
354
+ or not isinstance(data.get("answer"), str)
355
+ or not isinstance(data.get("covers"), bool)
356
+ ):
357
+ return "need.json lacks an answer or a covers flag"
358
+ searches = _search_texts(data.get("more_searches"))
359
+ contrast = (
360
+ [h for h in data.get("contrast", []) if isinstance(h, str)]
361
+ if isinstance(data.get("contrast"), list)
362
+ else []
363
+ )
364
+ return {
365
+ "answer": data["answer"],
366
+ "covers": data["covers"],
367
+ "more_searches": searches[:SEARCHES],
368
+ "contrast": contrast,
369
+ }
370
+
371
+
372
+ def memory_step(run: Run, store: Path, claude: str, question: str, settings: Path) -> dict:
373
+ env = headless.session_env()
374
+ shown: set[str] = set()
375
+ text = search_block(store, question, shown)
376
+ need: dict | str = {}
377
+ for number in range(1, MEMORY_ROUNDS + 1):
378
+ folder = run.step_dir(f"memory-{number}")
379
+ work = folder / "work"
380
+ (work / "results.txt").write_text(text, encoding="utf-8")
381
+ rule = (
382
+ "up to three short searches (plain words, no quotes or operators) for what the results lack, each run "
383
+ "once on its own, after which you read the added results; an empty list when the results are enough"
384
+ if number == 1
385
+ else "an empty list: no further search is made"
386
+ )
387
+ prompt = render(
388
+ "memory",
389
+ QUESTION=question,
390
+ RESULTS_FILE=str(work / "results.txt"),
391
+ NEED_FILE=str(work / "need.json"),
392
+ SEARCH_RULE=rule,
393
+ )
394
+ run.session(
395
+ f"memory-{number}",
396
+ file_cmd(claude, prompt, work, settings, run.gate(SHARE["memory"])),
397
+ work,
398
+ env,
399
+ prompt,
400
+ )
401
+ need = read_need(work / "need.json")
402
+ if isinstance(need, str):
403
+ raise StopError(need)
404
+ if number == MEMORY_ROUNDS or not need["more_searches"]:
405
+ break
406
+ for query in need["more_searches"]:
407
+ text += "\n" + search_block(store, query, shown)
408
+ run.log(f"memory: covers={need['covers']} contrast={need['contrast']}")
409
+ return need
410
+
411
+
412
+ # ---- steps 2 to 6 ----
413
+
414
+
415
+ def web_prompt(items: list[dict[str, str]], depth: str) -> str:
416
+ lines = [f"- {key}: {item['text']}" for key, item in rc.item_ids(items).items()]
417
+ papers = (
418
+ " Ask for scientific papers too: prefer them to blogs, and give them `source_kind` `paper`."
419
+ if depth == "deep"
420
+ else ""
421
+ )
422
+ return render("web", PAGES=str(PAGES[depth]), PAPERS=papers, ITEMS="\n".join(lines))
423
+
424
+
425
+ def web_step(
426
+ run: Run, claude: str, items: list[dict[str, str]], depth: str, settings: Path
427
+ ) -> list | None:
428
+ folder = run.step_dir("web")
429
+ work = folder / "work" # empty: the session has nothing to read
430
+ prompt = web_prompt(items, depth)
431
+ done = run.session(
432
+ "web",
433
+ web_cmd(claude, prompt, settings, run.gate(SHARE["web"])),
434
+ work,
435
+ headless.session_env(),
436
+ prompt,
437
+ )
438
+ events = web_events(done["raw"])
439
+ (folder / "events.json").write_text(json.dumps(events, indent=1), encoding="utf-8")
440
+ (folder / "reply.txt").write_text(done["answer"], encoding="utf-8")
441
+ run.log(f"web: {len(events['queries'])} searches, {len(events['urls'])} urls")
442
+ return rc.parse_web_reply(done["answer"])
443
+
444
+
445
+ def verdict_input(
446
+ question: str, items: list[dict[str, str]], entries: list[dict]
447
+ ) -> dict[str, Any]:
448
+ """What the verdict session reads: the question, the claims sent to the web and the evidence found."""
449
+ return {
450
+ "question": question,
451
+ "notes": [{"note": i["handle"], "claim": i["text"]} for i in items if i["kind"] == "claim"],
452
+ "evidence": entries,
453
+ }
454
+
455
+
456
+ def verdict_step(run: Run, claude: str, data: dict[str, Any], settings: Path) -> dict:
457
+ folder = run.step_dir("verdict")
458
+ work = folder / "work"
459
+ (work / "input.json").write_text(
460
+ json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8"
461
+ )
462
+ prompt = render(
463
+ "verdict", INPUT_FILE=str(work / "input.json"), VERDICTS_FILE=str(work / "verdicts.json")
464
+ )
465
+ run.session(
466
+ "verdict",
467
+ file_cmd(claude, prompt, work, settings, run.gate(None)),
468
+ work,
469
+ headless.session_env(),
470
+ prompt,
471
+ )
472
+ try:
473
+ verdicts = json.loads((work / "verdicts.json").read_text(encoding="utf-8"))
474
+ except (OSError, ValueError):
475
+ raise StopError("the verdict session wrote no valid verdicts.json") from None
476
+ if not isinstance(verdicts, dict):
477
+ raise StopError("verdicts.json is not a JSON object")
478
+ return verdicts
479
+
480
+
481
+ def _frontmatter_field(path: Path, key: str) -> object:
482
+ """A field of a note's frontmatter; None when the note is unreadable or its frontmatter is not a mapping."""
483
+ try:
484
+ return split_frontmatter(path.read_text(encoding="utf-8"))[0].get(key)
485
+ except (OSError, FrontmatterError, AttributeError):
486
+ return None
487
+
488
+
489
+ def contrast_notes(
490
+ store: Path, handles: list[str]
491
+ ) -> tuple[list[dict[str, str]], list[dict[str, str]]]:
492
+ """({handle, claim} of the knowledge notes among `handles`, the handles dropped with their reason). A handle that
493
+ is not a knowledge note of the store cannot be confirmed or disputed, so it is dropped."""
494
+ known = knowledge_notes(store)
495
+ notes: list[dict[str, str]] = []
496
+ dropped: list[dict[str, str]] = []
497
+ for raw in handles:
498
+ handle = Path(raw.strip()).name.removesuffix(".md")
499
+ if handle in {n["handle"] for n in notes}:
500
+ continue
501
+ if handle not in known:
502
+ dropped.append({"handle": raw, "reason": "not a knowledge note of the store"})
503
+ continue
504
+ claim = _frontmatter_field(known[handle], "claim")
505
+ if not isinstance(claim, str) or not claim.strip():
506
+ dropped.append({"handle": handle, "reason": "no claim"})
507
+ elif len(notes) >= MAX_NOTES:
508
+ dropped.append({"handle": handle, "reason": f"over the {MAX_NOTES}-note limit"})
509
+ else:
510
+ notes.append({"handle": handle, "claim": claim})
511
+ return notes, dropped
512
+
513
+
514
+ def marks(applied: list[list[str]]) -> dict[str, tuple[str, str]]:
515
+ """Note handle -> (verdict, url) of the commands that were applied."""
516
+ out: dict[str, tuple[str, str]] = {}
517
+ for args in applied:
518
+ if args[:2] in (["note", "confirm"], ["note", "dispute"]):
519
+ out[args[2]] = (
520
+ "confirmed" if args[1] == "confirm" else "contradicted",
521
+ args[args.index("--source") + 1],
522
+ )
523
+ return out
524
+
525
+
526
+ def _memory_lines(need: Any) -> list[str]:
527
+ if not need:
528
+ return ["From memory", " (the memory step did not finish)"]
529
+ covers = "yes" if need["covers"] else "no"
530
+ return [
531
+ f"From memory (covers the question: {covers})",
532
+ f" {need['answer'].strip() or '(nothing)'}",
533
+ ]
534
+
535
+
536
+ def _unmarked_result(state: dict[str, Any], handle: str) -> str:
537
+ """The result column of a contrasted note that no applied command marked."""
538
+ why = next(
539
+ (
540
+ r["reason"]
541
+ for r in state.get("refused", [])
542
+ if isinstance(r["row"], dict) and r["row"].get("note") == handle
543
+ ),
544
+ "",
545
+ )
546
+ if any(f["args"][2:3] == [handle] for f in state.get("failed", [])):
547
+ return "failed to write"
548
+ if state.get("judged"):
549
+ return "no source" + (f" ({why})" if why else "")
550
+ return "not judged" if state.get("web_ran") else "not checked"
551
+
552
+
553
+ def _contrast_lines(state: dict[str, Any]) -> list[str]:
554
+ lines = ["", "Contrasted notes", " | note | result | source |", " |---|---|---|"]
555
+ got = marks(state.get("applied", []))
556
+ for handle in state["sent"]:
557
+ if handle in got:
558
+ lines.append(f" | {handle} | {got[handle][0]} | {got[handle][1]} |")
559
+ else:
560
+ lines.append(f" | {handle} | {_unmarked_result(state, handle)} | |")
561
+ return lines
562
+
563
+
564
+ def _web_lines(state: dict[str, Any]) -> list[str]:
565
+ lines = ["", "From the web (new and unconfirmed)"]
566
+ findings = [a for a in state.get("applied", []) if a[0] == "remember"]
567
+ lines += [
568
+ f" - {a[a.index('--claim') + 1]} ({a[a.index('--source') + 1]})" for a in findings
569
+ ] or [" nothing added"]
570
+ if state.get("web_answer"):
571
+ lines.append(f" Summary: {' '.join(state['web_answer'].split())[:1200]}")
572
+ if state.get("sent"):
573
+ lines += _contrast_lines(state)
574
+ return lines
575
+
576
+
577
+ def report_text(question: str, run: Run, state: dict[str, Any]) -> str:
578
+ """The short answer."""
579
+ out = [f"Question: {question}", ""]
580
+ out += _memory_lines(state.get("need"))
581
+ if state.get("depth") != "memory":
582
+ out += _web_lines(state)
583
+ dropped = state.get("dropped", [])
584
+ if dropped:
585
+ out += ["", "Dropped"] + [f" - {d}" for d in dropped]
586
+ if state.get("stopped"):
587
+ out += ["", f"Stopped: {state['stopped']}"]
588
+ out += [
589
+ "",
590
+ f"Cost: {run.cost:.3f} USD of {run.budget:.2f} ({len(run.sessions)} sessions). Run folder: {run.folder}",
591
+ ]
592
+ return "\n".join(out)
593
+
594
+
595
+ def _prune_old_runs(base: Path) -> None:
596
+ """Delete the run folders older than `KEEP_SECONDS`."""
597
+ for old in base.iterdir():
598
+ try:
599
+ if time.time() - old.stat().st_mtime > KEEP_SECONDS:
600
+ shutil.rmtree(old, ignore_errors=True)
601
+ except OSError:
602
+ continue
603
+
604
+
605
+ def _run_steps(run: Run, store: Path, state: dict[str, Any], **step: Unpack[StepOptions]) -> None:
606
+ """The memory step, then (by depth) the web and verdict steps; a `StopError` ends the run and is reported."""
607
+ try:
608
+ state["need"] = memory_step(run, store, step["claude"], step["question"], step["settings"])
609
+ if step["depth"] != "memory":
610
+ web_and_verdicts(run, store, state, **step)
611
+ except StopError as stop:
612
+ state["stopped"] = str(stop)
613
+ run.log(f"stopped: {stop}")
614
+ run.save(
615
+ state="stopped" if state.get("stopped") else "ok",
616
+ finished=time.time(),
617
+ reason=state.get("stopped", ""),
618
+ )
619
+
620
+
621
+ def _run_guarded(run: Run, store: Path, state: dict[str, Any], **step: Unpack[StepOptions]) -> int:
622
+ """Exit code of the run: 0, or 1 when something other than a `StopError` went wrong."""
623
+ try:
624
+ _run_steps(run, store, state, **step)
625
+ except Exception as exc: # the run folder still tells what happened
626
+ logger.debug("the research run failed", exc_info=True)
627
+ state["stopped"] = f"{type(exc).__name__}: {exc}"[:200]
628
+ run.save(state="failed", finished=time.time(), reason=state["stopped"])
629
+ return 1
630
+ return 0
631
+
632
+
633
+ def research(store: Path, question: str, **options: Unpack[ResearchOptions]) -> int:
634
+ question = " ".join(question.split())
635
+ depth, claude = options["depth"], options["claude"]
636
+ if depth != "memory":
637
+ problem = rc.question_problem(question)
638
+ if problem:
639
+ print(f"mem-research: {problem}; nothing was sent anywhere.", file=sys.stderr)
640
+ return 2
641
+ if not claude:
642
+ print(
643
+ "mem-research: no claude binary (--claude, CLAUDE_CODE_EXECPATH or PATH)",
644
+ file=sys.stderr,
645
+ )
646
+ return 2
647
+ base = runs_dir(store)
648
+ jobs.private_dir(base)
649
+ _prune_old_runs(base)
650
+ folder = base / f"{time.strftime('%Y%m%d-%H%M%S')}-{os.getpid()}"
651
+ jobs.private_dir(folder)
652
+ budget = options["budget"]
653
+ run = Run(folder, budget, options["seconds"])
654
+ run.save(
655
+ state="running",
656
+ started=time.time(),
657
+ depth=depth,
658
+ question=question,
659
+ budget=budget,
660
+ cost=0.0,
661
+ )
662
+ settings = folder / "settings.json"
663
+ settings.write_text(
664
+ json.dumps({"disableAllHooks": True})
665
+ ) # no hook of a session may commit or start a run
666
+ state: dict[str, Any] = {
667
+ "depth": depth,
668
+ "dropped": [],
669
+ "applied": [],
670
+ "refused": [],
671
+ "failed": [],
672
+ }
673
+ code = _run_guarded(
674
+ run,
675
+ store,
676
+ state,
677
+ question=question,
678
+ claude=claude,
679
+ depth=depth,
680
+ contrast=options.get("contrast", []),
681
+ allow_hosts=options.get("allow_hosts", []),
682
+ settings=settings,
683
+ )
684
+ text = report_text(question, run, state)
685
+ (folder / "report.txt").write_text(text, encoding="utf-8")
686
+ print(text)
687
+ return code
688
+
689
+
690
+ def without_experience(store: Path, handles: list[str]) -> tuple[list[str], list[str]]:
691
+ """(handles kept, handles dropped): a note of origin `experience` records the owner's own experiments, which the
692
+ web cannot confirm and which are the most private notes, so the memory step's choice never sends one. A handle
693
+ that is not a readable knowledge note stays, for `contrast_notes` to drop with its own reason."""
694
+ known = knowledge_notes(store)
695
+ kept: list[str] = []
696
+ dropped: list[str] = []
697
+ for raw in handles:
698
+ path = known.get(Path(raw.strip()).name.removesuffix(".md"))
699
+ origin = _frontmatter_field(path, "origin") if path else None
700
+ (dropped if origin == "experience" else kept).append(raw)
701
+ return kept, dropped
702
+
703
+
704
+ def web_and_verdicts(
705
+ run: Run, store: Path, state: dict[str, Any], **step: Unpack[StepOptions]
706
+ ) -> None:
707
+ question, depth, settings = step["question"], step["depth"], step["settings"]
708
+ chosen = step.get("contrast", [])
709
+ if (
710
+ not chosen
711
+ ): # named with --contrast, an experience note goes; chosen by the memory step, it does not
712
+ chosen, own = without_experience(store, state["need"]["contrast"])
713
+ state["dropped"] += [f"{h}: own experience: not sent to the web" for h in own]
714
+ notes, dropped = contrast_notes(store, chosen)
715
+ state["dropped"] += [f"{d['handle']}: {d['reason']}" for d in dropped]
716
+ web = rc.web_input(question, notes)
717
+ state["dropped"] += [f"{d['handle']}: {d['reason']}" for d in web.dropped]
718
+ state["sent"] = [i["handle"] for i in web.items if i["kind"] == "claim"]
719
+ (run.folder / "web-input.json").write_text(
720
+ json.dumps({"items": web.items, "dropped": web.dropped}, indent=1)
721
+ )
722
+ rows = web_step(run, step["claude"], web.items, depth, settings)
723
+ state["web_ran"] = True
724
+ if rows is None:
725
+ state["dropped"].append(
726
+ "the web session's reply was not the expected JSON list: no web results"
727
+ )
728
+ return
729
+ checked = rc.check_rows(
730
+ rows,
731
+ rc.item_ids(web.items),
732
+ functools.partial(rc.fetch_text, allow_hosts=step.get("allow_hosts", [])),
733
+ max_urls=PAGES[depth],
734
+ )
735
+ state["dropped"] += [
736
+ f"web row {json.dumps(d['row'], ensure_ascii=False)[:120]}: {d['reason']}"
737
+ for d in checked.dropped
738
+ ]
739
+ (run.folder / "check.json").write_text(
740
+ json.dumps(
741
+ {
742
+ "entries": checked.entries,
743
+ "dropped": checked.dropped,
744
+ "fetched": {u: len(t) for u, t in checked.pages.items()},
745
+ },
746
+ ensure_ascii=False,
747
+ indent=1,
748
+ )
749
+ )
750
+ if not checked.entries:
751
+ state["dropped"].append("no web page could be used")
752
+ return
753
+ verdicts = verdict_step(
754
+ run,
755
+ step["claude"],
756
+ verdict_input(question, web.items, checked.entries),
757
+ settings,
758
+ )
759
+ state["web_answer"] = verdicts["answer"] if isinstance(verdicts.get("answer"), str) else ""
760
+ state["judged"] = True
761
+ applied = rc.apply(
762
+ verdicts,
763
+ checked.entries,
764
+ checked.pages,
765
+ state["sent"],
766
+ mem_cmd=sp.MEM,
767
+ root=store,
768
+ env=mem_env(store),
769
+ )
770
+ (run.folder / "apply.json").write_text(json.dumps(applied, ensure_ascii=False, indent=1))
771
+ state.update(applied=applied["applied"], refused=applied["refused"], failed=applied["failed"])
772
+ state["dropped"] += [
773
+ f"verdict row {json.dumps(r['row'], ensure_ascii=False)[:120]}: {r['reason']}"
774
+ for r in applied["refused"]
775
+ ]
776
+
777
+
778
+ # ---- command line ----
779
+
780
+
781
+ def budget_of(value: str | float | None, depth: str) -> float:
782
+ if value is None:
783
+ return LIMITS[depth][0]
784
+ try:
785
+ number = float(value)
786
+ except ValueError:
787
+ return LIMITS[depth][0]
788
+ return number if number > 0 else LIMITS[depth][0]
789
+
790
+
791
+ def self_check() -> int:
792
+ """No model and no network: the limits, the web session's command and environment, the tool lists of the others,
793
+ the reply and passage helpers, and a refusal of an uncovered finding."""
794
+ assert math.isclose(budget_of("x", "deep"), LIMITS["deep"][0])
795
+ assert math.isclose(budget_of("0.3", "deep"), float("0.3"))
796
+ assert math.isclose(budget_of("-1", "contrast"), LIMITS["contrast"][0])
797
+ with tempfile.TemporaryDirectory(prefix="mem-research-check-") as tmp_name:
798
+ tmp = Path(tmp_name)
799
+ (tmp / "bin").mkdir()
800
+ (tmp / "bin" / "mem").write_text("#!/bin/sh\n")
801
+ (tmp / "bin" / "mem").chmod(0o755)
802
+ os.environ.update({
803
+ "MEM_STORE": "x",
804
+ "CLAUDE_PLUGIN_ROOT": "x",
805
+ "CLAUDE_PLUGIN_OPTION_STORE": "x",
806
+ "PATH": f"{tmp / 'bin'}{os.pathsep}{os.environ.get('PATH', '')}",
807
+ })
808
+ env = headless.session_env()
809
+ assert not any(k.startswith(("MEM_", "CLAUDE_PLUGIN")) for k in env), (
810
+ "a MEM or plugin variable reached a session"
811
+ )
812
+ assert not any(headless.has_mem(p) for p in env["PATH"].split(os.pathsep)), (
813
+ "mem is on a session's PATH"
814
+ )
815
+ cmd = web_cmd("claude", "prompt", tmp / "s.json", 0.2)
816
+ assert (
817
+ cmd[cmd.index("--tools") + 1] == "WebSearch,WebFetch" and "--strict-mcp-config" in cmd
818
+ )
819
+ assert "--plugin-dir" not in cmd
820
+ assert cmd[cmd.index("--allowedTools") + 1 : cmd.index("--allowedTools") + 3] == [
821
+ "WebSearch",
822
+ "WebFetch",
823
+ ]
824
+ cmd = file_cmd("claude", "prompt", tmp / "w", tmp / "s.json", 0.2)
825
+ assert (
826
+ cmd[cmd.index("--tools") + 1] == "Read,Write,Edit"
827
+ and "--strict-mcp-config" in cmd
828
+ and "Bash" not in cmd
829
+ )
830
+ allowed = cmd[cmd.index("--allowedTools") + 1 : cmd.index("--allowedTools") + 4]
831
+ assert all(t.startswith(("Read(", "Write(", "Edit(")) for t in allowed)
832
+ assert (
833
+ rc.parse_web_reply('```json\n[{"item": "q"}]\n```') == [{"item": "q"}]
834
+ and rc.parse_web_reply("no") is None
835
+ )
836
+ assert rc.select_passages(
837
+ "Alpha beta gamma are named here.\n\nUnrelated words only here.", "alpha beta"
838
+ )[0].startswith("Alpha")
839
+ assert rc.finding_problem("It holds 5000 cycles", "It holds 4000 cycles in the lab") is not None
840
+ assert rc.question_problem("What is the limit?", {}) is None
841
+ print("self-check passed")
842
+ return 0
843
+
844
+
845
+ DESCRIPTION = (__doc__ or "").splitlines()[0]
846
+
847
+
848
+ def _need_question(parser: argparse.ArgumentParser, question: str | None) -> None:
849
+ if not (question or "").strip():
850
+ parser.error("a question is required")
851
+
852
+
853
+ def _requested_store(requested: Path | None) -> Path | None:
854
+ """The store to use; None (and a message) when there is none."""
855
+ store = requested.expanduser().resolve() if requested else default_store()
856
+ if store is None or not (store / "mem-store.yaml").is_file():
857
+ print(f"mem-research: no store at {store}", file=sys.stderr)
858
+ return None
859
+ return store
860
+
861
+
862
+ def _default_claude() -> str | None:
863
+ return (
864
+ os.environ.get("MEM_CLAUDE")
865
+ or os.environ.get("CLAUDE_CODE_EXECPATH")
866
+ or shutil.which("claude")
867
+ )
868
+
869
+
870
+ def _default_depth() -> str:
871
+ option = os.environ.get("MEM_RESEARCH_DEPTH") or os.environ.get(
872
+ "CLAUDE_PLUGIN_OPTION_RESEARCH_DEPTH"
873
+ )
874
+ return option if option in DEPTHS else DEFAULT_DEPTH
875
+
876
+
877
+ def _dry_run(args: argparse.Namespace, store: Path, budget: float, seconds: int) -> int:
878
+ problem = rc.question_problem(args.question) if args.depth != "memory" else None
879
+ print(
880
+ f"depth: {args.depth}; budget: {budget:.2f} USD; time limit: {seconds / 60:.0f} min; "
881
+ f"pages: {PAGES.get(args.depth, 0)}; claude: {args.claude or '(none)'}; store: {store}; "
882
+ + (f"would stop: {problem}" if problem else "would start")
883
+ )
884
+ return 0
885
+
886
+
887
+ def main(argv: list[str] | None = None) -> int:
888
+ parser = argparse.ArgumentParser(prog="mem-research", description=DESCRIPTION)
889
+ parser.add_argument("question", nargs="?")
890
+ parser.add_argument(
891
+ "--depth",
892
+ choices=DEPTHS,
893
+ default=_default_depth(),
894
+ help="memory: only the memory; contrast: also 5 web pages; deep: 15 pages, papers asked for "
895
+ "(default: the plugin option research_depth, else contrast)",
896
+ )
897
+ parser.add_argument(
898
+ "--contrast",
899
+ nargs="+",
900
+ default=[],
901
+ metavar="NOTE",
902
+ help="knowledge notes to check against the web (replaces the choice of the memory step)",
903
+ )
904
+ parser.add_argument("--store", type=Path, help="default: MEM_STORE, else the default store")
905
+ parser.add_argument(
906
+ "--claude",
907
+ default=_default_claude(),
908
+ )
909
+ parser.add_argument(
910
+ "--budget", help="USD for the whole run (default: contrast 0.50, deep 2, memory 0.25)"
911
+ )
912
+ parser.add_argument(
913
+ "--allow-host",
914
+ action="append",
915
+ default=[],
916
+ metavar="HOST",
917
+ help="a host fetched although it resolves to a non-public address (a local test page)",
918
+ )
919
+ runners.add_flag(parser)
920
+ parser.add_argument(
921
+ "--dry-run", action="store_true", help="say what would run; start and change nothing"
922
+ )
923
+ parser.add_argument(
924
+ "--self-check",
925
+ action="store_true",
926
+ help="no model: prove the session limits and the checks",
927
+ )
928
+ args = parser.parse_args(argv)
929
+ if args.self_check:
930
+ return self_check()
931
+ if (refused := codex_pass.refuse_codex("mem-research", args.runner)) is not None:
932
+ return refused
933
+ _need_question(parser, args.question)
934
+ store = _requested_store(args.store)
935
+ if store is None:
936
+ return 2
937
+ budget = budget_of(args.budget, args.depth)
938
+ seconds = LIMITS[args.depth][1]
939
+ if args.dry_run:
940
+ return _dry_run(args, store, budget, seconds)
941
+ for name in headless.SESSION_VARS:
942
+ os.environ.pop(name, None)
943
+ return research(
944
+ store,
945
+ args.question,
946
+ depth=args.depth,
947
+ contrast=args.contrast,
948
+ claude=args.claude,
949
+ budget=budget,
950
+ seconds=seconds,
951
+ allow_hosts=args.allow_host,
952
+ )