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,744 @@
1
+ """mem-corroborate: `fill`, the short form and topic of the lessons that lack them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import datetime
7
+ import hashlib
8
+ import json
9
+ import logging
10
+ import os
11
+ import shutil
12
+ import sys
13
+ import tempfile
14
+ import time
15
+ from pathlib import Path
16
+ from typing import NamedTuple
17
+
18
+ from memory_cli.core import jobs
19
+ from memory_cli.core import runner as runners
20
+ from memory_cli.corroborate import decide as corroborate_decide
21
+ from memory_cli.corroborate import job as corroborate_job
22
+ from memory_cli.corroborate import run as corroborate_run
23
+ from memory_cli.corroborate import state as corroborate_state
24
+ from memory_cli.memories import model, records, rules
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ ATTEMPTS_NAME = "fill-attempts.json"
29
+
30
+
31
+ CHECK_REFUSAL = "the checker did not find the short form faithful to the claim"
32
+
33
+
34
+ APPLY_REFUSAL = "mem refused to write the short form"
35
+
36
+
37
+ def _scope(project: Path | None, names: dict) -> str:
38
+ return "global" if project is None else names.get(project, str(project))
39
+
40
+
41
+ def _dry_run_refusal(args, spend: corroborate_run.Spend) -> int | None:
42
+ """The exit code of a dry run that cannot start, or None."""
43
+ if spend.runner == "claude" and not args.claude:
44
+ print(
45
+ "mem-corroborate: no claude binary (--claude, CLAUDE_CODE_EXECPATH or PATH)",
46
+ file=sys.stderr,
47
+ )
48
+ return 1
49
+ if missing := corroborate_run.missing_codex(spend):
50
+ print(f"mem-corroborate: {missing}", file=sys.stderr)
51
+ return 1
52
+ folder = Path(args.out).expanduser().resolve().parent
53
+ if not (folder.is_dir() and os.access(folder, os.W_OK | os.X_OK)):
54
+ print(
55
+ f"mem-corroborate: --out: {folder} is not a folder that can be written", file=sys.stderr
56
+ )
57
+ return 2
58
+ repo = corroborate_run.repo_above(folder)
59
+ if repo is not None:
60
+ print(
61
+ f"mem-corroborate: --out is inside a repository ({repo}); the result holds memory text",
62
+ file=sys.stderr,
63
+ )
64
+ return 2
65
+ return None
66
+
67
+
68
+ def _propose_in(
69
+ args, scratch: Path, candidates: list, spend: corroborate_run.Spend
70
+ ) -> tuple[dict, list[str], float] | None:
71
+ """One writer session in `scratch`: (the kept items, the reasons for the dropped ones, the cost), or None when
72
+ the session failed."""
73
+ settings = scratch / "settings.json"
74
+ corroborate_state.write_private(settings, json.dumps({"disableAllHooks": True}))
75
+ work = scratch / "fill"
76
+ work.mkdir(mode=0o700)
77
+ corroborate_state.write_private(work / "lessons.txt", corroborate_decide.fill_lines(candidates))
78
+ out = work / "fill.json"
79
+ brief = corroborate_run.FILL_BRIEF.format(lessons=work / "lessons.txt", out=out)
80
+ limits = corroborate_run.SessionLimits(corroborate_run.PROPOSE_MODEL, args.budget)
81
+ done = corroborate_run.run_on(
82
+ spend,
83
+ work,
84
+ corroborate_run.session_spec(args.claude or "", work, brief, settings, limits),
85
+ out,
86
+ )
87
+ if not done["has_result"] or done["error"]:
88
+ print(
89
+ f"mem-corroborate: the session failed{corroborate_run.because(done)}; nothing was written",
90
+ file=sys.stderr,
91
+ )
92
+ return None
93
+ kept, reasons = corroborate_decide.validate_fill(
94
+ corroborate_run.read_object(out), [i for i, _m in candidates]
95
+ )
96
+ return kept, reasons, done["cost"]
97
+
98
+
99
+ def _propose(
100
+ args, candidates: list, spend: corroborate_run.Spend
101
+ ) -> tuple[dict, list[str], float] | None:
102
+ scratch = Path(tempfile.mkdtemp(prefix="mem-corroborate-fill-"))
103
+ try:
104
+ return _propose_in(args, scratch, candidates, spend)
105
+ finally:
106
+ shutil.rmtree(scratch, ignore_errors=True)
107
+
108
+
109
+ def _dry_items(kept: dict, by_id: dict, where: dict, names: dict) -> list[dict]:
110
+ """The file the owner edits: an item for every candidate; one with no proposal says so in `problem`."""
111
+ for ident in by_id:
112
+ kept.setdefault(ident, {"short": "", "topic": "", "problem": "no proposal"})
113
+ items = []
114
+ for ident, fields in kept.items():
115
+ m = by_id[ident]
116
+ items.append({
117
+ "id": ident,
118
+ "handle": m.handle,
119
+ "scope": _scope(where[ident], names),
120
+ "claim": m.claim,
121
+ "short": fields["short"],
122
+ "topic": fields["topic"],
123
+ "load": "index" if m.load == "index" else "yes",
124
+ "claim_digest": corroborate_decide.claim_digest(m),
125
+ **({"problem": fields["problem"]} if "problem" in fields else {}),
126
+ })
127
+ return items
128
+
129
+
130
+ def _write_dry_run(args, items: list[dict], asked: int, reasons: list[str], spent: str) -> None:
131
+ to_edit = sum("problem" in i for i in items)
132
+ corroborate_state.write_private(
133
+ Path(args.out).expanduser(), json.dumps(items, ensure_ascii=False, indent=1) + "\n"
134
+ )
135
+ print(
136
+ f"mem-corroborate: fill: {asked} lessons asked, {len(items) - to_edit} kept, {to_edit} to edit, {len(reasons)} dropped, "
137
+ f"{spent}; read {args.out}, edit or cut it, then run fill --items {args.out}"
138
+ )
139
+ for why in reasons:
140
+ print(f" not kept: {why}", file=sys.stderr)
141
+
142
+
143
+ def fill_dry_run(args) -> int:
144
+ try:
145
+ spend = corroborate_run.Spend(getattr(args, "runner", None) or runners.resolve_runner(None))
146
+ except ValueError as exc:
147
+ print(f"mem-corroborate: {exc}", file=sys.stderr)
148
+ return 2
149
+ refused = _dry_run_refusal(args, spend)
150
+ if refused is not None:
151
+ return refused
152
+ try:
153
+ _data, projects, gfolder, names = corroborate_run._fill_world()
154
+ except ValueError as exc:
155
+ print(f"mem-corroborate: registry unreadable: {exc}", file=sys.stderr)
156
+ return 1
157
+ candidates = corroborate_decide.fill_candidates(projects, gfolder, datetime.date.today())
158
+ where = {i: p for i, p, _m in corroborate_decide.fill_records(projects, gfolder)}
159
+ kept: dict[str, dict] = {}
160
+ reasons: list[str] = []
161
+ cost = 0.0
162
+ if candidates:
163
+ proposed = _propose(args, candidates, spend)
164
+ if proposed is None:
165
+ return 1
166
+ kept, reasons, cost = proposed
167
+ items = _dry_items(kept, dict(candidates), where, names)
168
+ spent = f"{spend.tokens} tokens (codex)" if spend.runner == "codex" else f"cost {cost:.3f} USD"
169
+ _write_dry_run(args, items, len(candidates), reasons, spent)
170
+ return 0
171
+
172
+
173
+ LOAD_FLAGS = {"yes": ["--load"], "index": ["--index-only"], "no": ["--no-load"]}
174
+
175
+
176
+ class _Item(NamedTuple):
177
+ """An item of the fill file that has an id, a short form and a topic; `load` is the item's own value, unchecked."""
178
+
179
+ ident: str
180
+ short: str
181
+ topic: str
182
+ load: object
183
+ raw: dict
184
+
185
+
186
+ class _Known(NamedTuple):
187
+ project: Path | None
188
+ m: records.Memory
189
+ scope: str
190
+
191
+
192
+ class _Outcome:
193
+ def __init__(self) -> None:
194
+ self.written = self.dropped = self.failed = 0
195
+ self.applied: list[str] = []
196
+ self.refused: list[str] = []
197
+
198
+ def as_dict(self) -> dict:
199
+ return {
200
+ "written": self.written,
201
+ "dropped": self.dropped,
202
+ "failed": self.failed,
203
+ "applied": self.applied,
204
+ "refused": self.refused,
205
+ }
206
+
207
+
208
+ def _parse_item(raw: object, user_read: bool) -> _Item | None:
209
+ """None when `raw` is not an object with a string id, short and topic. Without `user_read` the item's `load` is ignored."""
210
+ if not isinstance(raw, dict):
211
+ return None
212
+ ident, short, topic = raw.get("id"), raw.get("short"), raw.get("topic")
213
+ if not (isinstance(ident, str) and isinstance(short, str) and isinstance(topic, str)):
214
+ return None
215
+ return _Item(ident, short, topic, raw.get("load") if user_read else None, raw)
216
+
217
+
218
+ def _valid_load(load: object) -> bool:
219
+ """`load` comes from a file the owner edits: any JSON value, a list included, so it is never hashed."""
220
+ return isinstance(load, str) and load in {"yes", "index", "no"}
221
+
222
+
223
+ def _load_flags(load: object) -> list[str]:
224
+ return LOAD_FLAGS.get(load, []) if isinstance(load, str) else []
225
+
226
+
227
+ class _Filler:
228
+ """Applies the items one at a time into the records, journaling them in a run folder."""
229
+
230
+ def __init__(self, run: Path, user_read: bool) -> None:
231
+ _data, projects, gfolder, names = corroborate_run._fill_world()
232
+ jobs.private_dir(run)
233
+ corroborate_state.write_private(
234
+ run / "fill", ""
235
+ ) # marks the run: its undo leaves the pass's `seen.json` alone
236
+ self.user_read = user_read
237
+ self.known = {
238
+ i: _Known(p, m, _scope(p, names))
239
+ for i, p, m in corroborate_decide.fill_records(projects, gfolder)
240
+ }
241
+ self.applier = corroborate_run.Applier(
242
+ corroborate_state.Journal(run), {}, gfolder, run, self._log
243
+ )
244
+ self.outcome = _Outcome()
245
+ self.used: set[str] = set()
246
+ self.today = datetime.date.today()
247
+
248
+ def _log(self, text: str) -> None:
249
+ fd = os.open(self.applier.cwd / "log.txt", os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
250
+ with os.fdopen(fd, "a", encoding="utf-8", errors="replace") as f:
251
+ f.write(f"{time.strftime('%H:%M:%S')} {text}\n")
252
+
253
+ def _refusal(self, item: _Item) -> str | None:
254
+ if item.ident not in self.known:
255
+ return f"unknown id {item.ident}"
256
+ if item.ident in self.used:
257
+ return f"repeats {item.ident}"
258
+ if not records.valid_short(item.short):
259
+ return "short is not one line of at most 120 characters"
260
+ if not records.valid_topic(item.topic):
261
+ return "topic is not one or two lowercase words"
262
+ if self.user_read and "load" in item.raw and not _valid_load(item.load):
263
+ return "load must be yes, index or no"
264
+ return self._record_refusal(item)
265
+
266
+ def _record_refusal(self, item: _Item) -> str | None:
267
+ _project, m, scope = self.known[item.ident]
268
+ if item.raw.get("handle", m.handle) != m.handle or item.raw.get("scope", scope) != scope:
269
+ return "handle or scope does not match its id"
270
+ turned_on = (
271
+ m.load == "no" and item.load is not None
272
+ ) # a record turned off may be turned on again by an item that names `load`
273
+ if m.triage == "pending" or not rules.eligible(
274
+ dataclasses.replace(m, load=None) if turned_on else m, self.today
275
+ ):
276
+ return "not a lesson that can load"
277
+ return None
278
+
279
+ def _edit(self, item: _Item, known: _Known) -> bool:
280
+ project, m, _scope_name = known
281
+ watched = (
282
+ [m.path]
283
+ if project is not None
284
+ else [m.path, m.path.parent / corroborate_run.SETTLE_STATE]
285
+ ) # an edit of a global record may update it
286
+ before = self.applier.journal.watch(watched)
287
+ done = self.applier.mem(
288
+ [
289
+ "memory",
290
+ "edit",
291
+ f"m:{m.handle}",
292
+ *(["--global"] if project is None else []),
293
+ f"--short={item.short}",
294
+ *(["--user-read"] if self.user_read else []),
295
+ f"--topic={item.topic}",
296
+ *_load_flags(item.load),
297
+ ],
298
+ project,
299
+ drop_env=corroborate_run.SETTLE_VARS,
300
+ )
301
+ self.applier.journal.commit("fill", before)
302
+ return done is not None and done.returncode == 0
303
+
304
+ def step(self, n: int, raw: object) -> None:
305
+ out = self.outcome
306
+ item = _parse_item(raw, self.user_read)
307
+ why = "not an object with id, short and topic" if item is None else self._refusal(item)
308
+ if item is None or why:
309
+ out.dropped += 1
310
+ self._log(f"item {n} dropped: {why}")
311
+ return
312
+ self.used.add(item.ident)
313
+ known = self.known[item.ident]
314
+ if item.raw.get("claim_digest") != corroborate_decide.claim_digest(known.m):
315
+ out.failed += 1
316
+ self._log(f"item {n} failed: {item.ident} changed its claim since the file was made")
317
+ elif self._edit(item, known):
318
+ out.written += 1
319
+ out.applied.append(item.ident)
320
+ else:
321
+ out.failed += 1
322
+ out.refused.append(item.ident)
323
+ self._log(f"item {n} failed: mem refused or could not run for {item.ident}")
324
+
325
+
326
+ def apply_fill(items: list[dict], run: Path, user_read: bool) -> dict:
327
+ """Writes the items into the records and journals them in `run` (the caller holds the run lock). Returns
328
+ {"written", "dropped", "failed", "applied", "refused"}; `applied` holds the id of each item written and `refused`
329
+ the id of each one `mem memory edit` refused. Without `user_read` (the automatic fill) an item never sets `load`:
330
+ a record turned off is dropped, and a record's load stays as the owner has it."""
331
+ filler = _Filler(run, user_read)
332
+ for n, item in enumerate(items, start=1):
333
+ filler.step(n, item)
334
+ return filler.outcome.as_dict()
335
+
336
+
337
+ def _apply_items(items: list, cdir: Path) -> int:
338
+ start = time.time()
339
+ run = cdir / "runs" / f"{time.strftime('%Y%m%d-%H%M%S')}-{os.getpid()}-fill"
340
+ result = apply_fill(items, run, user_read=True)
341
+ written, dropped, failed = result["written"], result["dropped"], result["failed"]
342
+ line = {
343
+ "t": datetime.datetime.now(datetime.UTC).isoformat(timespec="seconds"),
344
+ "fill": {"asked": len(items), "written": written, "dropped": dropped, "failed": failed},
345
+ "ms": int((time.time() - start) * 1000),
346
+ }
347
+ corroborate_state.append_log(cdir, line)
348
+ print(
349
+ f"mem-corroborate: fill: {len(items)} asked, {written} written, {dropped} dropped, {failed} failed; "
350
+ f"undo with: mem-corroborate undo {run.name}"
351
+ )
352
+ return 1 if failed else 0
353
+
354
+
355
+ def fill_items(args) -> int:
356
+ path = Path(args.items).expanduser()
357
+ items = corroborate_run.read_object(path)
358
+ if not isinstance(items, list):
359
+ print(f"mem-corroborate: {path} is not a JSON list of items", file=sys.stderr)
360
+ return 2
361
+ cdir = corroborate_state.corroborate_dir(corroborate_state.data_dir())
362
+ lock = jobs.take_run_lock(cdir)
363
+ if lock is None:
364
+ print("mem-corroborate: a run is going: try again later", file=sys.stderr)
365
+ return 1
366
+ try:
367
+ return _apply_items(items, cdir)
368
+ except Exception as exc:
369
+ logger.debug("fill failed", exc_info=True)
370
+ print(f"mem-corroborate: fill failed: {type(exc).__name__}: {exc}", file=sys.stderr)
371
+ return 1
372
+ finally:
373
+ os.close(lock)
374
+
375
+
376
+ def _fill_state(cdir: Path) -> dict:
377
+ """The automatic fill's memory, read defensively: a missing or broken file is an empty state."""
378
+ data = jobs.read_json(cdir / ATTEMPTS_NAME)
379
+ lessons = data.get("lessons")
380
+ failures = data.get("failures")
381
+ lessons = (
382
+ {k: v for k, v in lessons.items() if isinstance(v, dict)}
383
+ if isinstance(lessons, dict)
384
+ else {}
385
+ )
386
+ failures = failures if isinstance(failures, dict) else {}
387
+ count = failures.get("count")
388
+ return {
389
+ "lessons": lessons,
390
+ "failures": {
391
+ "count": count if isinstance(count, int) and count > 0 else 0,
392
+ "fingerprint": failures.get("fingerprint"),
393
+ },
394
+ }
395
+
396
+
397
+ def _fill_run_folder(cdir: Path) -> Path:
398
+ """`<stamp>-<pid>-fill`, with a number before `-fill` when a run of this process already took the second."""
399
+ base = f"{time.strftime('%Y%m%d-%H%M%S')}-{os.getpid()}"
400
+ run, n = cdir / "runs" / f"{base}-fill", 1
401
+ while run.exists():
402
+ n += 1
403
+ run = cdir / "runs" / f"{base}-{n}-fill"
404
+ return run
405
+
406
+
407
+ def fill_auto(claude: str | None, budget: float, runner: str | None = None) -> dict:
408
+ """Writes the short forms of the lessons that lack one, with nobody reading them first: a writer session, the
409
+ code check (`short_problems`), a second session that checks the survivors against their claims, then `apply_fill`.
410
+ Every doubt ends in not writing. A session with no usable answer is a failed session: no lesson is charged an
411
+ attempt and nothing is applied. The result holds numbers and `stopped` only; the same dict is the saved status."""
412
+ cdir = corroborate_state.corroborate_dir(corroborate_state.data_dir())
413
+ result = {
414
+ "asked": 0,
415
+ "written": 0,
416
+ "dropped": 0,
417
+ "refused_code": 0,
418
+ "refused_check": 0,
419
+ "to_triage": 0,
420
+ "left": 0,
421
+ "cost": 0.0,
422
+ "tokens": 0,
423
+ "runner": "claude",
424
+ "stopped": None,
425
+ }
426
+ lock = jobs.take_run_lock(cdir)
427
+ if lock is None:
428
+ return {**result, "stopped": "a run is going"}
429
+ try:
430
+ return _fill_locked(claude, budget, cdir, result, runner)
431
+ finally:
432
+ os.close(lock)
433
+
434
+
435
+ class _SessionError(Exception):
436
+ """A session gave no usable answer; the message says which."""
437
+
438
+
439
+ class _Lesson(NamedTuple):
440
+ m: records.Memory
441
+ project: Path | None
442
+ key: str
443
+ digest: str
444
+
445
+
446
+ @dataclasses.dataclass
447
+ class _Auto:
448
+ """One automatic fill: the lessons asked, the attempts state and the status the run saves."""
449
+
450
+ cdir: Path
451
+ result: dict
452
+ state: dict
453
+ lessons: dict[str, _Lesson]
454
+ names: dict
455
+ gfolder: Path | None
456
+ fingerprint: str
457
+ spend: corroborate_run.Spend = dataclasses.field(default_factory=corroborate_run.Spend)
458
+
459
+ def save(self) -> None:
460
+ jobs.write_json(self.cdir / ATTEMPTS_NAME, self.state)
461
+
462
+
463
+ class _Verdicts(NamedTuple):
464
+ reason: dict[str, str] # id -> why the lesson was refused
465
+ passed: list[tuple[str, dict]]
466
+ faithful: dict[str, bool]
467
+
468
+
469
+ def _finish(cdir: Path, result: dict, **changes) -> dict:
470
+ finished = corroborate_job.finish(result, **changes)
471
+ corroborate_state.save_status(cdir, fill=dict(finished))
472
+ return finished
473
+
474
+
475
+ def _lessons(projects: list, gfolder: Path | None, state: dict) -> dict[str, _Lesson]:
476
+ candidates = corroborate_decide.fill_candidates(
477
+ projects, gfolder, datetime.date.today(), attempts=state["lessons"]
478
+ )
479
+ where = {i: p for i, p, _m in corroborate_decide.fill_records(projects, gfolder)}
480
+ return {
481
+ i: _Lesson(
482
+ m,
483
+ where[i],
484
+ corroborate_decide.fill_key(where[i], m.handle),
485
+ corroborate_decide.claim_digest(m),
486
+ )
487
+ for i, m in candidates
488
+ }
489
+
490
+
491
+ def _plan(cdir: Path, result: dict) -> _Auto | dict:
492
+ """The run's context, or the finished status when there is nothing to ask or the run must wait."""
493
+ try:
494
+ _data, projects, gfolder, names = corroborate_run._fill_world()
495
+ except ValueError:
496
+ return _finish(cdir, result, stopped="the registry is unreadable")
497
+ state = _fill_state(cdir)
498
+ lessons = _lessons(projects, gfolder, state)
499
+ result["asked"] = len(lessons)
500
+ if not lessons:
501
+ return _finish(cdir, result)
502
+ fingerprint = hashlib.sha256(
503
+ json.dumps(sorted((x.key, x.digest) for x in lessons.values())).encode()
504
+ ).hexdigest()
505
+ failures = state["failures"]
506
+ if failures["fingerprint"] != fingerprint:
507
+ failures["count"] = 0
508
+ if failures["count"] >= corroborate_decide.FILL_FAILURES:
509
+ return _finish(cdir, result, stopped="waiting for the lessons to change", asked=0)
510
+ return _Auto(cdir, result, state, lessons, names, gfolder, fingerprint)
511
+
512
+
513
+ def _failed_session(ctx: _Auto, why: str) -> dict:
514
+ failures = ctx.state["failures"]
515
+ failures["count"] += 1
516
+ failures["fingerprint"] = ctx.fingerprint
517
+ ctx.save()
518
+ return _finish(ctx.cdir, ctx.result, stopped=why)
519
+
520
+
521
+ def _writer_session(
522
+ ctx: _Auto, claude: str, scratch: Path, budget: float
523
+ ) -> tuple[dict[str, str], list[tuple[str, dict]]]:
524
+ """The writer's proposals through the code check: (id -> why refused, the (id, item) pairs that passed)."""
525
+ lines = corroborate_decide.fill_lines([(i, x.m) for i, x in ctx.lessons.items()])
526
+ limits = corroborate_run.SessionLimits(corroborate_run.PROPOSE_MODEL, budget)
527
+ payload, cost, ok, why = corroborate_run._ask(
528
+ claude,
529
+ scratch,
530
+ "write",
531
+ limits,
532
+ corroborate_run.AskJob(
533
+ corroborate_run.FILL_BRIEF, lines, "lessons", "fill.json", ctx.spend
534
+ ),
535
+ )
536
+ ctx.result["cost"] += cost
537
+ ctx.result["tokens"] = ctx.spend.tokens
538
+ if not (ok and isinstance(payload, dict) and isinstance(payload.get("items"), list)):
539
+ raise _SessionError(f"the writer session gave no usable answer{why}")
540
+ kept, _dropped_reasons = corroborate_decide.validate_fill(payload, list(ctx.lessons))
541
+ reason: dict[str, str] = {}
542
+ passed: list[tuple[str, dict]] = []
543
+ for i, x in ctx.lessons.items():
544
+ item = kept.get(i)
545
+ if item is None:
546
+ reason[i] = "no proposal"
547
+ elif "problem" in item:
548
+ reason[i] = item["problem"]
549
+ elif found := model.short_problems(x.m.claim, item["short"]):
550
+ reason[i] = found[0]
551
+ else:
552
+ passed.append((i, item))
553
+ ctx.result["refused_code"] = len(
554
+ reason
555
+ ) # every refusal before the checker, a missing proposal included
556
+ return reason, passed
557
+
558
+
559
+ def _checker_session(
560
+ ctx: _Auto, claude: str, scratch: Path, budget: float, passed: list[tuple[str, dict]]
561
+ ) -> dict[str, bool]:
562
+ text = corroborate_decide.check_lines([
563
+ (i, ctx.lessons[i].m.claim, ctx.lessons[i].m.context, item["short"]) for i, item in passed
564
+ ])
565
+ limits = corroborate_run.SessionLimits(corroborate_run.CHECK_MODEL, budget)
566
+ payload, cost, ok, why = corroborate_run._ask(
567
+ claude,
568
+ scratch,
569
+ "check",
570
+ limits,
571
+ corroborate_run.AskJob(
572
+ corroborate_run.CHECK_BRIEF, text, "pairs", "verdicts.json", ctx.spend
573
+ ),
574
+ )
575
+ ctx.result["cost"] += cost
576
+ ctx.result["tokens"] = ctx.spend.tokens
577
+ checked = corroborate_decide.validate_check(payload, [i for i, _x in passed]) if ok else None
578
+ if checked is None:
579
+ raise _SessionError(f"the checker session gave no usable answer{why}")
580
+ return checked
581
+
582
+
583
+ def _sessions_in(ctx: _Auto, claude: str, scratch: Path, budget: float) -> _Verdicts:
584
+ corroborate_state.write_private(
585
+ scratch / "settings.json", json.dumps({"disableAllHooks": True})
586
+ )
587
+ reason, passed = _writer_session(ctx, claude, scratch, budget)
588
+ faithful = _checker_session(ctx, claude, scratch, budget, passed) if passed else {}
589
+ return _Verdicts(reason, passed, faithful)
590
+
591
+
592
+ def _sessions(ctx: _Auto, claude: str, budget: float) -> _Verdicts:
593
+ """The writer session, the code check and the checker session. Raises `_SessionError` for an unusable answer."""
594
+ scratch = Path(tempfile.mkdtemp(prefix="mem-corroborate-fill-"))
595
+ try:
596
+ return _sessions_in(ctx, claude, scratch, budget)
597
+ finally:
598
+ shutil.rmtree(scratch, ignore_errors=True)
599
+
600
+
601
+ def _checked_items(ctx: _Auto, verdicts: _Verdicts) -> list[dict]:
602
+ """The faithful short forms as fill items; the others are refused, with the checker's reason."""
603
+ items = []
604
+ for i, fields in verdicts.passed:
605
+ if not verdicts.faithful[i]:
606
+ verdicts.reason[i] = CHECK_REFUSAL
607
+ ctx.result["refused_check"] += 1
608
+ continue
609
+ x = ctx.lessons[i]
610
+ items.append({
611
+ "id": i,
612
+ "handle": x.m.handle,
613
+ "scope": _scope(x.project, ctx.names),
614
+ "claim": x.m.claim,
615
+ "short": fields["short"],
616
+ "topic": fields["topic"],
617
+ "claim_digest": x.digest,
618
+ })
619
+ return items
620
+
621
+
622
+ def _apply_checked(ctx: _Auto, items: list[dict], reason: dict[str, str]) -> tuple[list[str], bool]:
623
+ """Applies the items: (the ids written, whether the apply raised)."""
624
+ if not items:
625
+ return [], False
626
+ run = _fill_run_folder(ctx.cdir)
627
+ try:
628
+ done = apply_fill(items, run, user_read=False)
629
+ except (
630
+ Exception
631
+ ): # an apply that raised is an outcome: what reached the records is read back from them
632
+ logger.debug("the apply raised", exc_info=True)
633
+ applied = _written_ids(items)
634
+ for x in items:
635
+ if x["id"] not in applied:
636
+ reason[x["id"]] = APPLY_REFUSAL
637
+ return applied, True
638
+ for i in done["refused"]:
639
+ reason[i] = APPLY_REFUSAL
640
+ corroborate_state.write_private(
641
+ run / "applied.json", json.dumps([ctx.lessons[i].m.handle for i in done["applied"]])
642
+ )
643
+ ctx.result["written"], ctx.result["dropped"], ctx.result["left"] = (
644
+ done["written"],
645
+ done["dropped"],
646
+ done["failed"],
647
+ )
648
+ return done["applied"], False
649
+
650
+
651
+ def _count_attempts(
652
+ ctx: _Auto, applied: list[str], reason: dict[str, str]
653
+ ) -> list[tuple[str, str]]:
654
+ """Charges an attempt to every refused lesson; returns (id, why) of those that used the last one."""
655
+ attempts = ctx.state["lessons"]
656
+ for i in applied:
657
+ attempts[ctx.lessons[i].key] = {
658
+ "digest": ctx.lessons[i].digest,
659
+ "count": corroborate_decide.FILL_ATTEMPTS,
660
+ }
661
+ holds: list[tuple[str, str]] = []
662
+ for i, why in reason.items():
663
+ x = ctx.lessons[i]
664
+ count = corroborate_decide.attempt_count(attempts.get(x.key), x.digest) + 1
665
+ attempts[x.key] = {"digest": x.digest, "count": count}
666
+ if count >= corroborate_decide.FILL_ATTEMPTS:
667
+ holds.append((i, why))
668
+ return holds
669
+
670
+
671
+ def _settle(ctx: _Auto, holds: list[tuple[str, str]], apply_failed: bool) -> None:
672
+ """Saves the attempts and the failure count, then sends the lessons that used their last attempt to triage."""
673
+ failures = ctx.state["failures"]
674
+ if apply_failed:
675
+ failures["count"] += 1
676
+ failures["fingerprint"] = ctx.fingerprint
677
+ else:
678
+ failures["count"], failures["fingerprint"] = 0, None
679
+ ctx.save()
680
+ for i, why in holds:
681
+ x = ctx.lessons[i]
682
+ if x.project is None and _hold(x.m.handle, why, ctx.cdir, ctx.gfolder):
683
+ ctx.result["to_triage"] += 1
684
+ else:
685
+ ctx.result["left"] += 1
686
+
687
+
688
+ def _fill_runner(ctx: _Auto, claude: str | None, runner: str | None) -> str | None:
689
+ """Resolves the run's runner once into `ctx`; why the run cannot start (the `stopped` text), or None."""
690
+ try:
691
+ ctx.spend.runner = ctx.result["runner"] = runner or runners.resolve_runner(None)
692
+ except ValueError:
693
+ return "the runner setting is invalid"
694
+ if ctx.spend.runner == "claude":
695
+ return None if claude else "no claude binary"
696
+ return "no codex binary" if corroborate_run.missing_codex(ctx.spend) else None
697
+
698
+
699
+ def _fill_locked(
700
+ claude: str | None, budget: float, cdir: Path, result: dict, runner: str | None = None
701
+ ) -> dict:
702
+ ctx = _plan(cdir, result)
703
+ if isinstance(ctx, dict):
704
+ return ctx
705
+ if stopped := _fill_runner(ctx, claude, runner):
706
+ return _finish(cdir, result, stopped=stopped)
707
+ try:
708
+ verdicts = _sessions(ctx, claude or "", budget)
709
+ except _SessionError as exc:
710
+ return _failed_session(ctx, str(exc))
711
+ items = _checked_items(ctx, verdicts)
712
+ applied, apply_failed = _apply_checked(ctx, items, verdicts.reason)
713
+ _settle(ctx, _count_attempts(ctx, applied, verdicts.reason), apply_failed)
714
+ return (
715
+ _finish(cdir, result, stopped="the apply failed") if apply_failed else _finish(cdir, result)
716
+ )
717
+
718
+
719
+ def _written_ids(items: list[dict]) -> list[str]:
720
+ """The ids of the items whose short form is in the records now: what an `apply_fill` that raised had written."""
721
+ try:
722
+ _data, projects, gfolder, _names = corroborate_run._fill_world()
723
+ known = {i: m for i, _p, m in corroborate_decide.fill_records(projects, gfolder)}
724
+ except ValueError:
725
+ return []
726
+ return [
727
+ x["id"]
728
+ for x in items
729
+ if x["id"] in known
730
+ and known[x["id"]].short == x["short"]
731
+ and known[x["id"]].short_by == "model"
732
+ ]
733
+
734
+
735
+ def _hold(handle: str, why: str, cdir: Path, gfolder: Path | None) -> bool:
736
+ applier = corroborate_run.Applier(
737
+ corroborate_state.Journal(cdir), {}, gfolder, cdir, lambda _text: None
738
+ )
739
+ done = applier.mem(
740
+ ["triage", "hold", f"m:{handle}", "--because", why[:200]],
741
+ None,
742
+ drop_env=corroborate_run.SETTLE_VARS,
743
+ )
744
+ return done is not None and done.returncode == 0