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,764 @@
1
+ """The lean synthesis pipeline shared by `bin/mem-synthesize` and `evals/synthesis/run_trials.py`.
2
+
3
+ Lean loop (measured in docs/superpowers/plans/done/2026-11-17-memory-prompts-and-loop.md): check (one line per unsupported
4
+ claim) -> one fixer that changes only the listed sentences -> one check scoped to the parts and sentences the fixer
5
+ reports -> when it still lists claims, one delete-only step removes those sentences; no third pass. Every step is its
6
+ own `claude -p` session. Standard library and the engine's own modules (`records`, `syntheses`: PyYAML)."""
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import logging
12
+ import math
13
+ import os
14
+ import re
15
+ import subprocess
16
+ import time
17
+ import unicodedata
18
+ from dataclasses import dataclass, field
19
+ from typing import TYPE_CHECKING, Any, Required, TypedDict, Unpack
20
+
21
+ from memory_cli.core import headless, resources
22
+ from memory_cli.memories import records
23
+ from memory_cli.syntheses import document
24
+ from memory_cli.syntheses import units as synthesis_units
25
+
26
+ if TYPE_CHECKING:
27
+ from collections.abc import Callable, Iterator, Sequence
28
+ from pathlib import Path
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ PLUGIN = resources.plugin_root() # None outside the plugin: no skill file, no `--plugin-dir`
33
+ MEM = resources.mem_command()
34
+ BRIEFS = resources.SYNTHESIZE_BRIEFS
35
+ SKILL = PLUGIN / "skills" / "memory-synthesis" / "SKILL.md" if PLUGIN else None
36
+ CHEAP = "high" # effort of every Haiku checker and fixer (owner, 2026-11-17: raised from medium, unmeasured)
37
+ NOT_GIVEN = "(not given)"
38
+
39
+ COUNTS = re.compile(
40
+ r"^COUNTS: checked=(\d+) unsupported=(\d+)(?: used=(\d+) unused=(\d+))?\s*$", re.MULTILINE
41
+ )
42
+ NOTE_LINE = re.compile(r"^NOTE: (\S+) (used|unused)\s*$", re.MULTILINE)
43
+ CLAIM_LINE = re.compile(
44
+ r"^(?P<part>[^|\n]+?) \| (?P<start>[^|\n]*) \| (?P<kind>[^|\n]+?) \| (?P<note>[^|\n]*) \| (?P<fix>.*)$"
45
+ )
46
+ PARTS_LINE = re.compile(r"^PARTS: ?(.*)$", re.MULTILINE)
47
+ REF_LINE = re.compile(
48
+ r"^REF: (?P<part>[^|\n]+?) \| (?P<number>\d+) \| (?:(?P<missing>missing)|wrong (?P<current>[^|\n]+?)) \| "
49
+ r"(?P<target>[^|\n]*?)\s*$"
50
+ )
51
+ REFS_TOTAL = re.compile(r"^s:\S+: added (\d+), removed (\d+), refused (\d+)\s*$", re.MULTILINE)
52
+ DENIED = re.compile(
53
+ r"requested permissions|haven't granted|permission.{0,40}denied|denied.{0,40}permission",
54
+ re.IGNORECASE,
55
+ )
56
+ WRITE_COMMAND = re.compile(r"\s*mem synthesis (new|add|edit|append)\b")
57
+
58
+
59
+ DELETE_ONLY = """
60
+ ## Additional instruction for this step: delete only
61
+
62
+ This is the last pass. For every claim the report lists, delete that sentence from its part: ignore any replacement
63
+ sentence, write no new text, and leave every other character of the part as it is.
64
+ """
65
+
66
+
67
+ def brief(name: str, briefs: Path = BRIEFS, **values: str) -> str:
68
+ text = (briefs / f"{name}-brief.md").read_text(encoding="utf-8")
69
+ values.setdefault("SKILL_FILE", str(SKILL) if SKILL else NOT_GIVEN)
70
+ values.setdefault("PARTS", NOT_GIVEN)
71
+ values.setdefault("UNITS_FILE", NOT_GIVEN)
72
+ for key, value in values.items():
73
+ text = text.replace("{" + key + "}", value)
74
+ left = re.findall(r"\{[A-Z_]+\}", text)
75
+ assert not left, f"{name}-brief.md has unfilled placeholders: {left}"
76
+ return text
77
+
78
+
79
+ def mem(
80
+ store: Path, env: dict, *args: str, stdin: str | None = None
81
+ ) -> subprocess.CompletedProcess[str]:
82
+ return subprocess.run(
83
+ [*MEM, *args],
84
+ env=resources.child_env({**env, "MEM_STORE": str(store)}),
85
+ input=stdin,
86
+ capture_output=True,
87
+ text=True,
88
+ cwd=store,
89
+ check=False,
90
+ )
91
+
92
+
93
+ def model_family(model_id: str) -> str:
94
+ return next((f for f in ("haiku", "sonnet", "opus") if f in model_id.lower()), model_id)
95
+
96
+
97
+ def cost_by_family(model_usage: dict) -> dict[str, float]:
98
+ costs: dict[str, float] = {}
99
+ for model, usage in model_usage.items():
100
+ family = model_family(model)
101
+ costs[family] = costs.get(family, 0.0) + float(usage.get("costUSD") or 0.0)
102
+ return costs
103
+
104
+
105
+ def _events(stdout: str) -> Iterator[Any]:
106
+ """The JSON value of each line of a stream-json session; a line that is not JSON is skipped."""
107
+ for line in stdout.splitlines():
108
+ try:
109
+ yield json.loads(line)
110
+ except ValueError:
111
+ continue
112
+
113
+
114
+ def _content(event: Any) -> Any:
115
+ message = event.get("message")
116
+ return message.get("content") if isinstance(message, dict) else None
117
+
118
+
119
+ def _tool_uses(content: list) -> dict[str, tuple[str, str]]:
120
+ """Tool call id -> (tool name, its `command` input) of the assistant message's tool_use parts."""
121
+ return {
122
+ part["id"]: (part["name"], (part.get("input") or {}).get("command", ""))
123
+ for part in content
124
+ if part.get("type") == "tool_use"
125
+ }
126
+
127
+
128
+ def _result_text(body: Any) -> str:
129
+ return body if isinstance(body, str) else " ".join(b.get("text", "") for b in body or [])
130
+
131
+
132
+ def _is_write(name: str, command: str) -> bool:
133
+ return name == "Write" or (name == "Bash" and bool(WRITE_COMMAND.match(command)))
134
+
135
+
136
+ def _tally_result(out: dict, uses: dict[str, tuple[str, str]], part: dict) -> None:
137
+ """Count one tool_result: an error, a denial, a write with its exit status."""
138
+ name, command = uses.get(part.get("tool_use_id", ""), ("", ""))
139
+ text = _result_text(part.get("content"))
140
+ failed = bool(part.get("is_error"))
141
+ if failed:
142
+ out["tool_errors"] += 1
143
+ out["denied"] += bool(DENIED.search(text))
144
+ if _is_write(name, command):
145
+ out["writes"] += 1
146
+ out["write_errors"] += failed
147
+
148
+
149
+ def _tally_results(out: dict, uses: dict[str, tuple[str, str]], content: list) -> None:
150
+ for part in content:
151
+ if part.get("type") == "tool_result":
152
+ _tally_result(out, uses, part)
153
+
154
+
155
+ def _tally_final(out: dict, event: Any) -> None:
156
+ out["has_result"] = True
157
+ out["answer"] = event.get("result") or ""
158
+ out["model_usage"] = event.get("modelUsage") or {}
159
+ value = event.get("total_cost_usd")
160
+ try:
161
+ cost = float(value) if not isinstance(value, bool) else float("nan")
162
+ except (TypeError, ValueError, OverflowError):
163
+ cost = float("nan")
164
+ out["cost_known"] = math.isfinite(cost) and cost >= 0
165
+ out["cost"] = cost if out["cost_known"] else 0.0
166
+ out["error"] = bool(event.get("is_error"))
167
+
168
+
169
+ def parse(stdout: str) -> dict:
170
+ """Facts of one stream-json session: writes with their exit status, denials, cost per model, result."""
171
+ out: dict[str, Any] = {
172
+ "writes": 0,
173
+ "write_errors": 0,
174
+ "denied": 0,
175
+ "tool_errors": 0,
176
+ "model_usage": {},
177
+ "cost": 0.0,
178
+ "cost_known": False,
179
+ "error": True,
180
+ "answer": "",
181
+ "has_result": False,
182
+ }
183
+ uses: dict[str, tuple[str, str]] = {}
184
+ for event in _events(stdout):
185
+ kind = event.get("type")
186
+ content = _content(event)
187
+ if kind == "assistant" and isinstance(content, list):
188
+ uses.update(_tool_uses(content))
189
+ elif kind == "user" and isinstance(content, list):
190
+ _tally_results(out, uses, content)
191
+ elif kind == "result":
192
+ _tally_final(out, event)
193
+ return out
194
+
195
+
196
+ # The `mem` subcommands the background sessions may run, one `Bash(mem <sub>*)` rule each. Sources: the curator
197
+ # (agents/memory-curator.md: `curate` with `apply --safe`, `show`, `memories`, `search`, `rules --unread`, which only
198
+ # lists; `rules --read` marks short forms as read by the owner and stays out), the writer
199
+ # (agents/memory-synthesizer.md: `find`, `show`, `synthesis list|new|add|append|edit`, `check`), and the checker and
200
+ # fixer briefs (briefs/*.md: `search`, `show`, `synthesis edit`, `check`). No `import`, `fetch-sources`, `new`,
201
+ # `remember` or `history`: no brief names them, and `attach` and `refs` run from code (`mem()`), not in a session.
202
+ MEM_ALLOWED = (
203
+ "curate",
204
+ "show",
205
+ "memories",
206
+ "search",
207
+ "rules --unread",
208
+ "find",
209
+ "check",
210
+ "synthesis list",
211
+ "synthesis new",
212
+ "synthesis add",
213
+ "synthesis append",
214
+ "synthesis edit",
215
+ )
216
+
217
+
218
+ def session_roots(store: Path, env: dict, work: Path) -> list[Path]:
219
+ """The folders a background session may read: the store, the global memories folder when it lies outside the
220
+ store, and the work folder."""
221
+ memories = records.global_memories_root(env)
222
+ roots = [store.resolve(), work.resolve()]
223
+ if memories is not None and not records.inside(memories.resolve(), store.resolve()):
224
+ roots.insert(1, memories.resolve())
225
+ return roots
226
+
227
+
228
+ class SessionOptions(TypedDict, total=False):
229
+ """`run_session`'s keyword arguments: `env` and `log` are required, the rest default (timeout 1500)."""
230
+
231
+ env: Required[dict]
232
+ log: Required[Path]
233
+ timeout: int
234
+ effort: str | None
235
+ agent: str | None
236
+ max_budget: float | None
237
+ read_roots: Sequence[Path]
238
+
239
+
240
+ def _allowed_tools(work: Path, read_roots: Sequence[Path]) -> list[str]:
241
+ """Headless --allowedTools also limits what a session may run: exactly what a step needs. Body files go in the
242
+ work folder (`//` is an absolute path in a permission rule; a new file needs the Edit rule too); the web stays
243
+ out. Reads only under `read_roots` and the skill folder (`//` again: an absolute path), so injected note text
244
+ cannot make a session read other local files; `mem` runs only the subcommands of MEM_ALLOWED."""
245
+ return [
246
+ *(f"Bash(mem {sub}*)" for sub in MEM_ALLOWED),
247
+ *(
248
+ f"{tool}(/{root}/**)"
249
+ for root in (*read_roots, *([SKILL.parent] if SKILL else []))
250
+ for tool in ("Read", "Grep", "Glob")
251
+ ),
252
+ f"Write(/{work}/**)",
253
+ f"Edit(/{work}/**)",
254
+ ]
255
+
256
+
257
+ def _stream(cmd: list[str], work: Path, env: dict, timeout: int) -> str:
258
+ """The session's stdout; the part of it written before the timeout when the session is killed."""
259
+ return headless.run_raw(cmd, cwd=work, env=env, timeout=timeout).stdout
260
+
261
+
262
+ def run_session(
263
+ claude: str,
264
+ model: str,
265
+ prompt: str,
266
+ work: Path,
267
+ settings: Path,
268
+ **options: Unpack[SessionOptions],
269
+ ) -> dict:
270
+ read_roots = options.get("read_roots", ())
271
+ cmd = headless.command(
272
+ headless.Session(
273
+ claude=claude,
274
+ prompt=prompt,
275
+ model=model,
276
+ settings=settings,
277
+ effort=options.get("effort") or None,
278
+ plugin_dir=PLUGIN,
279
+ allowed=tuple(_allowed_tools(work, read_roots)),
280
+ disallowed=("WebSearch", "WebFetch"),
281
+ # the session stops itself past this spend (--print only)
282
+ max_budget=options.get("max_budget"),
283
+ # the agent's body is the session's system prompt
284
+ agent=options.get("agent") or None,
285
+ )
286
+ )
287
+ env = {
288
+ **options["env"],
289
+ "MEM_SANDBOX": "1",
290
+ "MEM_SANDBOX_ROOTS": os.pathsep.join(str(r) for r in read_roots),
291
+ }
292
+ start = time.monotonic()
293
+ raw = _stream(cmd, work, env, options.get("timeout", 1500))
294
+ options["log"].write_text(raw, encoding="utf-8")
295
+ result = parse(raw)
296
+ result["wall"] = time.monotonic() - start
297
+ return result
298
+
299
+
300
+ def units_text(synthesis: Path) -> str:
301
+ """What the checker's `{UNITS_FILE}` holds: per part (not the Summary) `## <handle>`, one line per unit
302
+ `<number> | <text without references> | <targets, or ->`, then `Sources: <note targets>`."""
303
+ lines = []
304
+ for section in document.load_one(synthesis).parts:
305
+ found, _ = synthesis_units.units(section.text)
306
+ lines.append(f"## {section.handle}")
307
+ lines += [
308
+ f"{u.n} | {' '.join(u.plain.split())} | {', '.join(u.refs) or '-'}" for u in found
309
+ ]
310
+ lines.append(
311
+ "Sources: " + ", ".join(t for t in section.sources if synthesis_units._is_ref(t))
312
+ )
313
+ return "\n".join(lines) + "\n"
314
+
315
+
316
+ def write_units(synthesis: Path, target: Path) -> None:
317
+ target.write_text(units_text(synthesis), encoding="utf-8")
318
+
319
+
320
+ def _ref_text(ln: str) -> str | None:
321
+ """A `REF:` line as the model may write it: after a bullet, indented, in backticks."""
322
+ s = ln.strip().lstrip("-*\u2022 \t").replace("`", "").strip()
323
+ return s if s.startswith("REF:") else None
324
+
325
+
326
+ def _target(value: str | None) -> str | None:
327
+ value = (value or "").strip().rstrip(".").strip()
328
+ return None if value.lower() in {"", "none"} else value
329
+
330
+
331
+ def _reported_handle(value: str) -> str:
332
+ """A model may write a heading where the brief asks for a handle: both become the handle `mem` gives the part."""
333
+ return section_handle(value.strip().removeprefix("s:").split("#")[-1])
334
+
335
+
336
+ def _ref_row(m: re.Match[str]) -> dict:
337
+ return {
338
+ "part": _reported_handle(m["part"]),
339
+ "number": int(m["number"]),
340
+ "kind": "missing" if m["missing"] else "wrong",
341
+ "current": _target(m["current"]),
342
+ "target": _target(m["target"]),
343
+ }
344
+
345
+
346
+ def _refs(lines: list[str]) -> tuple[list[dict], int]:
347
+ """The `REF:` lines' rows and the count of malformed ones."""
348
+ refs, malformed = [], 0
349
+ for ln in lines:
350
+ if (s := _ref_text(ln)) is None:
351
+ continue
352
+ if m := REF_LINE.match(s):
353
+ refs.append(_ref_row(m))
354
+ else:
355
+ malformed += 1
356
+ return refs, malformed
357
+
358
+
359
+ def _claims(lines: list[str]) -> list[dict]:
360
+ found = [m.groupdict() for ln in lines if _ref_text(ln) is None and (m := CLAIM_LINE.match(ln))]
361
+ for claim in found:
362
+ claim["part"] = _reported_handle(claim["part"])
363
+ return found
364
+
365
+
366
+ def _parts(text: str, claims: list[dict]) -> list[str]:
367
+ listed = PARTS_LINE.search(text)
368
+ parts = [
369
+ _reported_handle(h) for h in (listed.group(1) if listed else "").split(",") if h.strip()
370
+ ]
371
+ return list(dict.fromkeys(parts + [c["part"] for c in claims]))
372
+
373
+
374
+ def _note_states(text: str) -> dict[str, str]:
375
+ notes = {}
376
+ for rel, state in NOTE_LINE.findall(text):
377
+ at = rel.find("knowledge/")
378
+ notes[rel[at:] if at >= 0 else rel] = state
379
+ return notes
380
+
381
+
382
+ def parse_report(path: Path) -> dict | None:
383
+ """The checker's report: its last COUNTS line, the PARTS line, the claim lines, the `REF:` lines (reference
384
+ problems, never claims; a malformed one is only counted in `ref_malformed`) and the judge's NOTE lines.
385
+
386
+ None when the file or the COUNTS line is missing. A report with no unsupported claim holds only the COUNTS line."""
387
+ if not path.is_file():
388
+ return None
389
+ text = path.read_text(encoding="utf-8")
390
+ lines = [ln for ln in text.splitlines() if ln.strip()]
391
+ found = COUNTS.fullmatch(lines[-1]) if lines else None
392
+ if not found:
393
+ return None
394
+ claims = _claims(lines)
395
+ refs, malformed = _refs(lines)
396
+ unsupported = int(found.group(2))
397
+ if not claims and (refs or malformed):
398
+ # A checker that counted its reference problems as unsupported lists no claim: nothing is there to fix or
399
+ # delete, and the delete-only step must not run for it.
400
+ unsupported = 0
401
+ return {
402
+ "checked": int(found.group(1)),
403
+ "unsupported": unsupported,
404
+ "notes": _note_states(text),
405
+ "claims": claims,
406
+ "parts": _parts(text, claims),
407
+ "refs": refs,
408
+ "ref_malformed": malformed,
409
+ }
410
+
411
+
412
+ def scope_text(report: dict, fixer_answer: str) -> str:
413
+ """What the scoped second check receives in `{PARTS}`: the fixer's own report of the parts and sentences it
414
+ changed; when the fixer said nothing usable, the parts and sentence starts the first report listed."""
415
+ answer = fixer_answer.strip()
416
+ if answer:
417
+ return answer[:2000]
418
+ return "; ".join(
419
+ f"{c['part'].strip()}: {c['start'].strip()}" for c in report["claims"]
420
+ ) or ", ".join(report["parts"])
421
+
422
+
423
+ def section_handle(heading: str) -> str:
424
+ """As `document.section_handle` of the engine: the handle `mem` gives a part."""
425
+ ascii_text = unicodedata.normalize("NFKD", heading).encode("ascii", "ignore").decode()
426
+ return re.sub(r"[^a-z0-9]+", "-", ascii_text.lower()).strip("-")
427
+
428
+
429
+ def resolve_parts(parts: list[str], text: str) -> list[str]:
430
+ """Reported parts as handles: a checker may name a part by the line range `mem show s:<slug>` prints
431
+ (`12-30`), which is the part whose heading sits on the range's first line."""
432
+ by_line = {
433
+ n: section_handle(line[3:])
434
+ for n, line in enumerate(text.splitlines(), 1)
435
+ if line.startswith("## ")
436
+ }
437
+ out = []
438
+ for part in parts:
439
+ m = re.fullmatch(r"(\d+)-\d+", part)
440
+ out.append(by_line.get(int(m.group(1)), part) if m else part)
441
+ return list(dict.fromkeys(out))
442
+
443
+
444
+ def split_parts(text: str) -> dict[str, str]:
445
+ """Part handle -> exact part text (heading line included); the front matter and anything before the first part
446
+ are left out."""
447
+ pieces = re.split(r"^(?=## )", text, flags=re.MULTILINE)[1:]
448
+ return {section_handle(piece.splitlines()[0][3:]): piece for piece in pieces}
449
+
450
+
451
+ def changed_outside(before: str, after: str, allowed: list[str]) -> list[str]:
452
+ """Handles of the parts that differ between the two texts although they are not in `allowed`: a fixer may touch
453
+ only the parts its report lists, and an untouched part must stay byte-equal."""
454
+ old, new = split_parts(before), split_parts(after)
455
+ return sorted(
456
+ h for h in old.keys() | new.keys() if old.get(h) != new.get(h) and h not in allowed
457
+ )
458
+
459
+
460
+ class GuardOptions(TypedDict):
461
+ allowed: list[str]
462
+
463
+
464
+ def guard_parts(
465
+ store: Path, env: dict, topic: str, before: str, after: str, **options: Unpack[GuardOptions]
466
+ ) -> tuple[list[str], list[str]]:
467
+ """(violations, reverted): the parts changed outside `allowed` and those put back to their text in `before`
468
+ through `mem synthesis edit --shrink`, so the undo log and `mem check` stay consistent. A part the fixer removed
469
+ or added cannot be put back by `edit`: it stays in the violations only."""
470
+ violations = changed_outside(before, after, options["allowed"])
471
+ old, new = split_parts(before), split_parts(after)
472
+ reverted = [
473
+ handle
474
+ for handle in violations
475
+ if handle in old and handle in new and _put_back(store, env, topic, handle, old[handle])
476
+ ]
477
+ return violations, reverted
478
+
479
+
480
+ def _put_back(store: Path, env: dict, topic: str, handle: str, old_part: str) -> bool:
481
+ text = old_part.split("\n", 1)[1].strip("\n") if "\n" in old_part else ""
482
+ done = mem(
483
+ store,
484
+ env,
485
+ "synthesis",
486
+ "edit",
487
+ f"s:{topic}#{handle}",
488
+ "--body-file",
489
+ "-",
490
+ "--shrink",
491
+ "--drop-references",
492
+ stdin=text + "\n",
493
+ )
494
+ return done.returncode == 0
495
+
496
+
497
+ def summary(s: dict) -> dict:
498
+ return {
499
+ "role": s["role"],
500
+ "model": s["model"],
501
+ "costs": s["costs"],
502
+ "cost": s["cost"],
503
+ "wall": s["wall"],
504
+ "writes": s["writes"],
505
+ "write_errors": s["write_errors"],
506
+ "denied": s["denied"],
507
+ "tool_errors": s["tool_errors"],
508
+ "ok": s["has_result"] and not s["error"],
509
+ }
510
+
511
+
512
+ class StopError(Exception):
513
+ """The loop ends: the budget is spent, or a session left no cost report."""
514
+
515
+
516
+ NO_COST = "a session ended without a cost report"
517
+
518
+
519
+ class LoopOptions(TypedDict, total=False):
520
+ """`lean_loop`'s keyword arguments: `settings`, `topic` and `sessions` are required."""
521
+
522
+ settings: Required[Path]
523
+ topic: Required[str]
524
+ sessions: Required[list[dict]]
525
+ lean: bool
526
+ left: Callable[[], float] | None
527
+ briefs: Path
528
+ read_roots: Sequence[Path]
529
+
530
+
531
+ def _ref_lines(refs: list[dict]) -> list[str]:
532
+ """The reported `REF:` rows as `mem synthesis refs` proposal lines."""
533
+ lines = []
534
+ for r in refs:
535
+ if r["kind"] == "wrong" and r["current"]:
536
+ lines.append(f"{r['part']} | {r['number']} | remove {r['current']}")
537
+ if r["target"]:
538
+ lines.append(f"{r['part']} | {r['number']} | add {r['target']}")
539
+ return lines
540
+
541
+
542
+ def _record_refs_result(row: dict, done: subprocess.CompletedProcess[str]) -> None:
543
+ """What `mem synthesis refs` printed into the loop's row for the check."""
544
+ total = REFS_TOTAL.findall(done.stdout)
545
+ if done.returncode or not total:
546
+ row["error"] = (done.stderr.strip() or done.stdout.strip() or f"exit {done.returncode}")[
547
+ :200
548
+ ]
549
+ return
550
+ added, removed, refused = map(int, total[-1])
551
+ row.update(
552
+ applied=added + removed,
553
+ refused=refused,
554
+ reasons=[
555
+ ln[len("refused: ") :] for ln in done.stdout.splitlines() if ln.startswith("refused: ")
556
+ ],
557
+ )
558
+
559
+
560
+ @dataclass
561
+ class _Loop:
562
+ claude: str
563
+ env: dict
564
+ base: Path
565
+ store: Path
566
+ work: Path
567
+ settings: Path
568
+ topic: str
569
+ sessions: list[dict]
570
+ lean: bool
571
+ left: Callable[[], float] | None
572
+ briefs: Path
573
+ read_roots: Sequence[Path]
574
+ out: dict[str, Any] = field(
575
+ default_factory=lambda: {
576
+ "arm_count": None,
577
+ "why": "",
578
+ "fixes": 0,
579
+ "deleted": 0,
580
+ "scope_violations": [],
581
+ "reverted": [],
582
+ "refs": [],
583
+ }
584
+ )
585
+
586
+ @property
587
+ def synthesis(self) -> Path:
588
+ return self.store / "syntheses" / f"{self.topic}.md"
589
+
590
+ @property
591
+ def fill(self) -> dict[str, str]:
592
+ return {
593
+ "TOPIC": self.topic,
594
+ "SLUG": self.topic,
595
+ "STORE": str(self.store),
596
+ "WORK_DIR": str(self.work),
597
+ }
598
+
599
+ def step(self, role: str, model: str, text: str, level: str | None = None) -> dict:
600
+ remaining = self.left() if self.left else None
601
+ if remaining is not None and remaining <= 0:
602
+ raise StopError("budget spent")
603
+ s = run_session(
604
+ self.claude,
605
+ model,
606
+ text,
607
+ self.work,
608
+ self.settings,
609
+ env=self.env,
610
+ log=self.base / f"{len(self.sessions) + 1:02d}-{role}.jsonl",
611
+ effort=level,
612
+ max_budget=remaining,
613
+ read_roots=self.read_roots,
614
+ )
615
+ s.update(role=role, model=model, costs=cost_by_family(s["model_usage"]))
616
+ self.sessions.append(summary(s))
617
+ if self.left and not s["has_result"]:
618
+ raise StopError(NO_COST)
619
+ return s
620
+
621
+ def check(self, n: int, scope: str = NOT_GIVEN) -> dict | None:
622
+ report = self.work / f"report-{n}.md"
623
+ report.unlink(missing_ok=True)
624
+ units = self.work / f"units-{n}.md"
625
+ write_units(self.synthesis, units) # rewritten per check: the fixer changed the text
626
+ text = brief(
627
+ "checker",
628
+ self.briefs,
629
+ **self.fill,
630
+ REPORT_FILE=str(report),
631
+ PARTS=scope,
632
+ UNITS_FILE=str(units),
633
+ )
634
+ self.step("checker", "haiku", text, CHEAP)
635
+ return parse_report(report)
636
+
637
+ def apply_refs(self, n: int, report: dict | None) -> None:
638
+ """The report's `REF:` lines through `mem synthesis refs`, before anything changes the text their numbers
639
+ refer to. A failure is recorded, never raised."""
640
+ if not report or not (report["refs"] or report["ref_malformed"]):
641
+ return
642
+ lines = _ref_lines(report["refs"])
643
+ row = {
644
+ "check": n,
645
+ "reported": len(report["refs"]),
646
+ "malformed": report["ref_malformed"],
647
+ "lines": len(lines),
648
+ "applied": 0,
649
+ "refused": 0,
650
+ "reasons": [],
651
+ "error": "",
652
+ }
653
+ self.out["refs"].append(row)
654
+ if not lines:
655
+ return
656
+ proposals = self.work / f"refs-{n}.txt"
657
+ proposals.write_text("".join(ln + "\n" for ln in lines), encoding="utf-8")
658
+ try:
659
+ done = mem(
660
+ self.store,
661
+ self.env,
662
+ "synthesis",
663
+ "refs",
664
+ f"s:{self.topic}",
665
+ "--file",
666
+ str(proposals),
667
+ )
668
+ except OSError as exc:
669
+ row["error"] = str(exc)
670
+ return
671
+ _record_refs_result(row, done)
672
+
673
+ def guarded_fix(
674
+ self, model: str, level: str | None, text: str, report: dict, role: str = "fixer"
675
+ ) -> dict:
676
+ """One fixer step; the parts it changed outside the report's PARTS are recorded and put back."""
677
+ before = self.synthesis.read_text(encoding="utf-8")
678
+ s = self.step(role, model, text, level)
679
+ bad, back = guard_parts(
680
+ self.store,
681
+ self.env,
682
+ self.topic,
683
+ before,
684
+ self.synthesis.read_text(encoding="utf-8"),
685
+ allowed=resolve_parts(report["parts"], before),
686
+ )
687
+ self.out["scope_violations"].extend(bad)
688
+ self.out["reverted"].extend(back)
689
+ return s
690
+
691
+ def delete_only(self, text: str, second: dict) -> None:
692
+ report_1, report_2 = self.work / "report-1.md", self.work / "report-2.md"
693
+ self.guarded_fix(
694
+ "haiku",
695
+ CHEAP,
696
+ text.replace(str(report_1), str(report_2)) + DELETE_ONLY,
697
+ second,
698
+ "deleter",
699
+ )
700
+ self.out["deleted"] = len(second["claims"]) or second["unsupported"]
701
+
702
+ def fix(self, first: dict) -> None:
703
+ self.out["fixes"] = 1
704
+ text = brief("fixer", self.briefs, **self.fill, REPORT_FILE=str(self.work / "report-1.md"))
705
+ if not self.lean:
706
+ self.guarded_fix("sonnet", None, text, first)
707
+ return
708
+ fixed = self.guarded_fix("haiku", CHEAP, text, first)
709
+ second = self.check(2, scope_text(first, fixed["answer"]))
710
+ self.apply_refs(2, second)
711
+ if second is None:
712
+ self.out["why"] = "scoped check report unreadable"
713
+ elif second["unsupported"]:
714
+ self.delete_only(text, second)
715
+
716
+ def steps(self) -> None:
717
+ first = self.out["arm_count"] = self.check(1)
718
+ self.apply_refs(1, first)
719
+ if first is None:
720
+ self.out["why"] = "arm checker report unreadable"
721
+ elif first["unsupported"]:
722
+ self.fix(first)
723
+
724
+ def run(self) -> dict:
725
+ try:
726
+ self.steps()
727
+ except StopError as stop:
728
+ self.out["why"] = str(stop)
729
+ return self.out
730
+
731
+
732
+ def lean_loop(
733
+ claude: str,
734
+ env: dict,
735
+ base: Path,
736
+ store: Path,
737
+ work: Path,
738
+ **options: Unpack[LoopOptions],
739
+ ) -> dict:
740
+ """Check, fix, and (lean) scoped check and delete-only step for the synthesis `s:<topic>` already in `store`.
741
+
742
+ Each session's summary is appended to `sessions`; session streams go to `base/NN-<role>.jsonl`. Returns
743
+ `arm_count` (first check, None when its report is unreadable), `why` (empty when every step worked), `fixes`,
744
+ `deleted`, `scope_violations`, `reverted` (the violations put back), `refs` (per check that reported `REF:` lines:
745
+ `check`, `reported` lines, proposal `lines` sent, `applied` and `refused` as `mem synthesis refs` printed them,
746
+ `error` when the command failed). `briefs` is the folder the brief files are read from; `read_roots` the folders
747
+ the sessions may read (see `run_session`). `lean=False` is the trial's arm S: one Sonnet fixer, no second check.
748
+ `left` (a function: USD still allowed) caps every step: none starts when nothing is left, each session gets
749
+ `--max-budget-usd` of what is left, and a session without a result event (killed at its timeout: its spend is
750
+ unknown) ends the loop with `why` = NO_COST."""
751
+ return _Loop(
752
+ claude,
753
+ env,
754
+ base,
755
+ store,
756
+ work,
757
+ settings=options["settings"],
758
+ topic=options["topic"],
759
+ sessions=options["sessions"],
760
+ lean=options.get("lean", True),
761
+ left=options.get("left"),
762
+ briefs=options.get("briefs", BRIEFS),
763
+ read_roots=options.get("read_roots", ()),
764
+ ).run()