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,660 @@
1
+ """mem-auto: one bounded curation run in the background, started by the SessionEnd hook when the plugin option
2
+ `auto_curation` is exactly `true`.
3
+
4
+ `run` (detached, no output): takes the store-wide run lock first and exits quietly when it is busy; checks the option
5
+ and that the records written since the last run's end (or the last curation pass, whichever is later) reach the
6
+ threshold (option `auto_curation_threshold`, default 10: global memories plus notes of the store, counted by
7
+ `mem curate --new-since`); writes status `running`; then the phases, in order, within the run's budget (option
8
+ `auto_curation_budget`, default 2 USD): `curate` (the curator in apply mode, where only `mem curate apply --safe`
9
+ changes anything, then `mem-synthesize` for the store topics with 8 notes or more and no synthesis) and `integrate`
10
+ (loose notes joined to their syntheses by `entry/integrate.py::run_locked` with the budget left; each committed group
11
+ is logged with its `mem-integrate --undo` route) and `split` (at most one verified split by
12
+ `entry/split_auto.py::run_locked` with the budget left, only while `SPLIT_ENABLED`; its committed group is logged with
13
+ its `mem synthesis split --undo` route). A session without a cost report or with unknown spend ends the run
14
+ before any further phase. Status, logs and transcripts: `<state folder>/auto/<id>/`, mode 0700, runs kept 30 days.
15
+ It never records `mem curate --done`.
16
+
17
+ Retry: an `integrate` or `split` phase that recorded a failure, or was not started for lack of budget, sets `retry` in the
18
+ status (a list of phase names; the mark is written when the phase starts, so a killed run leaves it); one that completes without failure (no candidates, only ambiguous ones or a checker abstention count) clears it. While `retry` is
19
+ set and the option is on, a trigger below the threshold runs only the marked phases (no curator, no synthesis) and
20
+ leaves the count window (`window`, else `finished`, else `started`) where it was; at the threshold every phase runs.
21
+ A phase not started because the run stopped is marked too. A retry-only run that ends with failures sets `retry_held`:
22
+ below the threshold the marks then wait (one retry per failure) for the next full run, which clears the hold.
23
+
24
+ Usage: mem-auto run [--store PATH] [--claude PATH] [--budget USD] [--threshold N] | status | ack | due | --self-check
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import functools
31
+ import json
32
+ import logging
33
+ import math
34
+ import os
35
+ import shutil
36
+ import subprocess
37
+ import sys
38
+ import tempfile
39
+ import time
40
+ from pathlib import Path
41
+ from typing import TYPE_CHECKING, NamedTuple
42
+
43
+ if TYPE_CHECKING:
44
+ from collections.abc import Callable
45
+
46
+ from memory_cli.core import auto_state as au
47
+ from memory_cli.core import codex_pass, jobs, resources
48
+ from memory_cli.core import runner as runners
49
+ from memory_cli.entry import integrate, split_auto
50
+ from memory_cli.synthesize import pipeline as sp
51
+ from memory_cli.synthesize import run as synth_run
52
+ from memory_cli.synthesize import topics as synth_topics
53
+
54
+ logger = logging.getLogger(__name__)
55
+
56
+ OPTION = "CLAUDE_PLUGIN_OPTION_AUTO_CURATION"
57
+ BUDGET_OPTION = "CLAUDE_PLUGIN_OPTION_AUTO_CURATION_BUDGET"
58
+ THRESHOLD_OPTION = "CLAUDE_PLUGIN_OPTION_AUTO_CURATION_THRESHOLD"
59
+ DEFAULT_BUDGET = 2.0 # USD per run
60
+ DEFAULT_THRESHOLD = 10 # new memories and notes that start a run
61
+ CURATE = "curate"
62
+ INTEGRATE = "integrate"
63
+ SPLIT = "split"
64
+ KEEP_SECONDS = 30 * 86400
65
+ DIR_MODE = 0o700
66
+ CHECK_BUDGET = 0.6
67
+ CHECK_THRESHOLD = 3
68
+ AGENT = "memory:memory-curator"
69
+ SESSION_VARS = (
70
+ "CLAUDE_ENV_FILE",
71
+ "CLAUDE_PLUGIN_ROOT",
72
+ "CLAUDE_PLUGIN_DATA",
73
+ "CLAUDE_PROJECT_DIR",
74
+ "CLAUDE_PID",
75
+ "CLAUDE_CODE_SESSION_ID",
76
+ "CLAUDE_CODE_MESSAGING_SOCKET",
77
+ "CLAUDE_CODE_MESSAGING_TOKEN",
78
+ )
79
+
80
+
81
+ def budget_of(value: str | float | None) -> float:
82
+ if value is None:
83
+ return DEFAULT_BUDGET
84
+ try:
85
+ number = float(value)
86
+ except ValueError:
87
+ return DEFAULT_BUDGET
88
+ return number if number > 0 else DEFAULT_BUDGET
89
+
90
+
91
+ def threshold_of(value: str | int | None) -> int:
92
+ if value is None:
93
+ return DEFAULT_THRESHOLD
94
+ try:
95
+ number = int(value)
96
+ except ValueError:
97
+ return DEFAULT_THRESHOLD
98
+ return number if number > 0 else DEFAULT_THRESHOLD
99
+
100
+
101
+ def stamp(seconds: float | None) -> str:
102
+ return time.strftime("%Y-%m-%d %H:%M", time.localtime(seconds)) if seconds else "never"
103
+
104
+
105
+ class State:
106
+ """The files of one store's automatic runs."""
107
+
108
+ def __init__(self, store: Path):
109
+ self.store = store
110
+ self.dir = au.auto_dir(synth_run.state_dir(), store)
111
+
112
+ def status(self) -> dict:
113
+ return jobs.read_json(self.dir / jobs.STATUS_NAME)
114
+
115
+ def save_status(self, **changes) -> dict:
116
+ jobs.private_dir(self.dir)
117
+ data = {**self.status(), **changes}
118
+ jobs.write_json(self.dir / jobs.STATUS_NAME, data)
119
+ return data
120
+
121
+
122
+ def window_start(status: dict) -> object:
123
+ """Where the count window starts: `window` is set by a full run at its end and kept by retry-only runs; a full
124
+ run clears it when it starts. From the end of the last run, not its start: its own attaches and merges are not
125
+ new work (a killed run has no end)."""
126
+ return status.get("window") or status.get("finished") or status.get("started")
127
+
128
+
129
+ def count_new(state: State, env: dict) -> int:
130
+ """Records written since the last run ended (or the last curation pass, whichever is later)."""
131
+ since = window_start(state.status())
132
+ found = sp.mem(
133
+ state.store,
134
+ env,
135
+ "curate",
136
+ "--new-since",
137
+ str(float(since) if isinstance(since, (int, float)) else 0),
138
+ )
139
+ if found.returncode or not found.stdout.strip().isdigit():
140
+ raise RuntimeError(f"mem curate --new-since failed: {found.stderr.strip()[:150]}")
141
+ return int(found.stdout.strip())
142
+
143
+
144
+ def topics_due(state: State, env: dict) -> list[str]:
145
+ found = sp.mem(state.store, env, "curate", "--notes")
146
+ if found.returncode:
147
+ raise RuntimeError(f"mem curate --notes failed: {found.stderr.strip()[:150]}")
148
+ return synth_run.topics_without_synthesis(found.stdout)
149
+
150
+
151
+ def prune(state: State, now: float) -> None:
152
+ jobs.prune_runs_older(state.dir / "runs", now, KEEP_SECONDS)
153
+
154
+
155
+ class RunContext(NamedTuple):
156
+ state: State
157
+ claude: str
158
+ budget: float
159
+ root: Path
160
+ log: Callable[[str], None]
161
+
162
+
163
+ class Phase(NamedTuple):
164
+ name: str
165
+ run: Callable[[RunContext, dict], None]
166
+
167
+
168
+ def _curate(ctx: RunContext, acct: dict) -> None:
169
+ """The curator, then the synthesis of the topics due. A session without a cost report or with unknown spend sets
170
+ `acct["stop"]`."""
171
+ state, claude, run_budget, root, log = ctx
172
+ env = synth_run.session_env(state.store)
173
+ store = state.store
174
+ settings = root / "settings.json"
175
+ settings.write_text(
176
+ json.dumps({
177
+ "pluginConfigs": {"memory": {"options": {"store": str(store)}}},
178
+ "disableAllHooks": True,
179
+ }),
180
+ encoding="utf-8",
181
+ ) # no hook of the sessions may commit or start a run
182
+ synth_run.history_commit(store, env, "mem-auto: before curation", log)
183
+ work = root / "curator-work"
184
+ work.mkdir(mode=DIR_MODE)
185
+ done = sp.run_session(
186
+ claude,
187
+ "haiku",
188
+ "apply",
189
+ work,
190
+ settings,
191
+ env=env,
192
+ log=root / "01-curator.jsonl",
193
+ timeout=900,
194
+ agent=AGENT,
195
+ max_budget=run_budget,
196
+ read_roots=sp.session_roots(store, env, work),
197
+ )
198
+ acct["cost"] += done["cost"]
199
+ log(
200
+ f"curator: has_result={done['has_result']} error={done['error']} cost={done['cost']:.3f} "
201
+ f"answer={' '.join(done['answer'].split())[:300]}"
202
+ )
203
+ synth_run.history_commit(store, env, "mem-auto: after curation", log)
204
+ if (
205
+ not done["has_result"] or not done["cost_known"]
206
+ ): # unknown spend: the budget left cannot be computed
207
+ acct["failures"].append(sp.NO_COST)
208
+ acct["stop"] = True
209
+ return
210
+ if done["error"]:
211
+ acct["failures"].append("curator session failed")
212
+ _synthesize(ctx, acct, env)
213
+
214
+
215
+ def _synthesize(ctx: RunContext, acct: dict, env: dict) -> None:
216
+ """The store topics due, within the budget left; whatever finished is counted."""
217
+ state, claude, run_budget, root, log = ctx
218
+ store = state.store
219
+ topics = topics_due(state, env)
220
+ log(f"topics due: {topics}")
221
+ if topics:
222
+ rows: list[dict] = []
223
+ try:
224
+ synth_topics.run(
225
+ claude,
226
+ store,
227
+ topics,
228
+ max(run_budget - acct["cost"], 0.0),
229
+ False,
230
+ out=lambda text: log(f"synthesize: {text}"),
231
+ root=root / "synthesize",
232
+ rows_out=rows,
233
+ )
234
+ finally: # rows arrive one by one: whatever finished is counted even when the call raises
235
+ for row in rows:
236
+ acct["cost"] += row["cost"]
237
+ if sp.NO_COST in row["status"]:
238
+ acct["stop"] = True
239
+ # "ok, references not added: ..." is a written synthesis: `mem-synthesize --backfill` adds them later.
240
+ if row["status"].split(",")[0] not in {
241
+ "ok",
242
+ "not started: budget",
243
+ "not started: unknown spend",
244
+ }:
245
+ acct["failures"].append(f"topic {row['topic']}: {row['status']}")
246
+
247
+
248
+ def _overspent(cost: float, remaining: float, log, phase: str) -> bool:
249
+ """A phase that spent more than the budget it was given: logged; the caller stops the run and keeps its mark."""
250
+ over = cost > remaining + integrate.EPSILON
251
+ if over:
252
+ log(f"{phase}: spent more than the budget it was given")
253
+ return over
254
+
255
+
256
+ def _integrate(ctx: RunContext, acct: dict) -> None:
257
+ """Joins loose notes to their syntheses with the budget left. No budget left is no start: the phase stays marked
258
+ for retry without a failure. A failure, or a halt on spend or on an unsettled intent, stops the run."""
259
+ state, claude, run_budget, _, log = ctx
260
+ remaining = run_budget - acct["cost"]
261
+ if remaining <= integrate.EPSILON:
262
+ log("integrate: not started: budget")
263
+ acct["retry"].add(INTEGRATE)
264
+ return
265
+ acct["retry"].add(INTEGRATE)
266
+ state.save_status(
267
+ retry=sorted(acct["retry"])
268
+ ) # a killed run leaves the phase marked: its intent is reconciled next
269
+ job = integrate.run_locked(state.store, claude, remaining, stop_on_failure=True)
270
+ record = job.record
271
+ acct["cost"] += record.cost
272
+ for text in record.failures:
273
+ acct["failures"].append(f"integrate: {text}")
274
+ for group in record.groups:
275
+ log(
276
+ f"integrate: group {group.group_id} ({', '.join(group.handles)}); "
277
+ f"undo: mem-integrate --undo {record.run_id}"
278
+ )
279
+ log(f"integrate: cost={record.cost:.3f} failures={len(record.failures)}")
280
+ over = _overspent(record.cost, remaining, log, INTEGRATE)
281
+ if record.failures or over:
282
+ acct["retry"].add(INTEGRATE)
283
+ else:
284
+ acct["retry"].discard(INTEGRATE)
285
+ acct["stop"] = acct["stop"] or bool(
286
+ record.failures or over or job.spend_halted or job.unresolved
287
+ )
288
+
289
+
290
+ def _split(ctx: RunContext, acct: dict) -> None:
291
+ """At most one verified split with the budget left, under the rules of `_integrate`: no budget is no start (marked
292
+ for retry), a failure or unknown spend stops the run. No candidate, ambiguous candidates only and a checker
293
+ abstention are clean completions."""
294
+ state, claude, run_budget, _, log = ctx
295
+ remaining = run_budget - acct["cost"]
296
+ acct["retry"].add(SPLIT)
297
+ if remaining <= integrate.EPSILON:
298
+ log("split: not started: budget")
299
+ return
300
+ state.save_status(retry=sorted(acct["retry"])) # a killed run leaves the phase marked
301
+ result = split_auto.run_locked(state.store, claude, remaining)
302
+ acct["cost"] += result.cost
303
+ for text in result.failures:
304
+ acct["failures"].append(f"split: {text}")
305
+ if result.group:
306
+ log(f"split: group {result.group}; undo: {result.undo}")
307
+ log(f"split: cost={result.cost:.3f} failures={len(result.failures)}")
308
+ if result.failures or not result.cost_known:
309
+ acct["stop"] = True
310
+ elif _overspent(result.cost, remaining, log, SPLIT):
311
+ acct["stop"] = True # the mark stays
312
+ else:
313
+ acct["retry"].discard(SPLIT)
314
+
315
+
316
+ SPLIT_ENABLED = True # on after the paid trial (stage 5 plan, 2026-11-28); False removes the phase
317
+
318
+
319
+ def active_phases() -> tuple[Phase, ...]:
320
+ """The phases in run order: `curate`, `integrate`, then `split` while `SPLIT_ENABLED`."""
321
+ return PHASES + ((Phase(SPLIT, _split),) if SPLIT_ENABLED else ())
322
+
323
+
324
+ PHASES = (
325
+ Phase(CURATE, _curate),
326
+ Phase(INTEGRATE, _integrate),
327
+ ) # run in this order; `active_phases` adds `split`
328
+
329
+
330
+ def run_steps(ctx: RunContext, acct: dict, names: frozenset[str] | None = None) -> None:
331
+ """The phases named (all by default), in order. `acct` (`cost`, `failures`, `retry`) is filled as work finishes, so
332
+ an exception later still leaves what was spent. A stopping failure (`acct["stop"]`) ends the run: no further phase,
333
+ and each phase left unstarted is marked for retry."""
334
+ pending = [p for p in active_phases() if names is None or p.name in names]
335
+ for index, phase in enumerate(pending):
336
+ phase.run(ctx, acct)
337
+ if acct["stop"]:
338
+ acct["retry"].update(
339
+ p.name for p in pending[index + 1 :]
340
+ ) # not started: stays eligible
341
+ return
342
+
343
+
344
+ def _append_log(log_file: Path, text: str) -> None:
345
+ fd_log = os.open(log_file, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
346
+ with os.fdopen(fd_log, "a", encoding="utf-8") as f:
347
+ f.write(f"{time.strftime('%H:%M:%S')} {text}\n")
348
+
349
+
350
+ def _finish(state: State, acct: dict) -> None:
351
+ """The end status, written while the lock is still held."""
352
+ failures = acct["failures"]
353
+ log_file = acct["log"]
354
+ finished = time.time()
355
+ reason = "; ".join(failures)
356
+ if log_file is None: # the run never started (the count failed): the count window must not move
357
+ if failures:
358
+ state.save_status(failure={"at": finished, "reason": reason, "log": ""})
359
+ return
360
+ state.save_status(
361
+ state="failed" if failures else "ok",
362
+ finished=finished,
363
+ cost=acct["cost"],
364
+ reason=reason,
365
+ retry=sorted(acct["retry"]),
366
+ retry_held=acct["retry_only"] and bool(failures),
367
+ window=acct["window"] if acct["window"] is not None else finished,
368
+ **(
369
+ {"failure": {"at": finished, "reason": reason, "log": str(log_file)}}
370
+ if failures
371
+ else {}
372
+ ),
373
+ )
374
+
375
+
376
+ def _marked(state: State) -> frozenset[str]:
377
+ """The phases the last run left marked for retry (only names this module knows)."""
378
+ found = state.status().get("retry")
379
+ known = {phase.name for phase in active_phases()}
380
+ return frozenset(n for n in found if n in known) if isinstance(found, list) else frozenset()
381
+
382
+
383
+ def _held(state: State) -> bool:
384
+ """A retry-only run ended with failures: the marks wait for the next full run (one retry per failure)."""
385
+ return state.status().get("retry_held") is True
386
+
387
+
388
+ def _gates(
389
+ state: State, budget_arg: str | float | None, threshold_arg: str | int | None
390
+ ) -> tuple[float, frozenset[str] | None] | None:
391
+ """(the run budget, the phases to run) when the option is on and a run is due, else None. The phases are None
392
+ (all) when the new records reach the threshold, else only those marked for retry."""
393
+ if os.environ.get(OPTION) != "true":
394
+ return None
395
+ budget = budget_of(budget_arg if budget_arg is not None else os.environ.get(BUDGET_OPTION))
396
+ threshold = threshold_of(
397
+ threshold_arg if threshold_arg is not None else os.environ.get(THRESHOLD_OPTION)
398
+ )
399
+ if count_new(state, synth_run.session_env(state.store)) >= threshold:
400
+ return budget, None
401
+ marked = _marked(state)
402
+ return (budget, marked) if marked and not _held(state) else None
403
+
404
+
405
+ def _start(state: State, acct: dict, *, full: bool) -> tuple[Path, Path]:
406
+ """The run folder and its log; writes status `running`. A full run clears the count window (a killed one counts
407
+ from its start); a retry-only run keeps it, so its own start and end do not move the count."""
408
+ now = time.time()
409
+ previous = state.status()
410
+ stale = jobs.failure(
411
+ {
412
+ "state": previous.get("state"),
413
+ "started": previous.get("started"),
414
+ "log": previous.get("log"),
415
+ },
416
+ now,
417
+ )
418
+ root = state.dir / "runs" / f"{time.strftime('%Y%m%d-%H%M%S')}-{os.getpid()}"
419
+ jobs.private_dir(root)
420
+ prune(state, now)
421
+ log_file = root / "log.txt"
422
+ acct["log"] = log_file
423
+ # a killed run leaves this `running` behind: shown as failed after an hour, and its failure kept here
424
+ extra = {"failure": stale} if stale and not previous.get("failure") else {}
425
+ window = {"window": None, "retry_held": False} if full else {}
426
+ state.save_status(
427
+ state="running",
428
+ started=now,
429
+ finished=None,
430
+ cost=0.0,
431
+ reason="",
432
+ log=str(log_file),
433
+ **window,
434
+ **extra,
435
+ )
436
+ return root, log_file
437
+
438
+
439
+ def _execute(
440
+ state: State,
441
+ claude: str | None,
442
+ budget_arg: str | float | None,
443
+ threshold_arg: str | int | None,
444
+ acct: dict,
445
+ ) -> None:
446
+ gate = _gates(state, budget_arg, threshold_arg)
447
+ if gate is None:
448
+ return
449
+ budget, names = gate
450
+ acct["retry"] = set(_marked(state))
451
+ acct["window"] = None if names is None else window_start(state.status())
452
+ acct["retry_only"] = names is not None
453
+ root, log_file = _start(state, acct, full=names is None)
454
+ log = functools.partial(_append_log, log_file)
455
+ log(f"start: budget {budget:.2f}, phases: {', '.join(sorted(names)) if names else 'all'}")
456
+ if not claude:
457
+ acct["failures"].append("no claude binary (--claude, CLAUDE_CODE_EXECPATH or PATH)")
458
+ else:
459
+ run_steps(RunContext(state, claude, budget, root, log), acct, names)
460
+ if acct["cost"] > budget + 1e-9:
461
+ acct["failures"].append(f"cost {acct['cost']:.2f} USD is over the budget {budget:.2f}")
462
+ _finish(state, acct)
463
+
464
+
465
+ def cmd_run(
466
+ store: Path, claude: str | None, budget_arg: str | float | None, threshold_arg: str | int | None
467
+ ) -> int:
468
+ state = State(store)
469
+ fd = jobs.take_run_lock(state.dir) # the first action: a busy lock means a run is going
470
+ if fd is None:
471
+ return 0
472
+ acct: dict = {
473
+ "cost": 0.0,
474
+ "failures": [],
475
+ "log": None,
476
+ "stop": False,
477
+ "retry": set(),
478
+ "retry_only": False,
479
+ "window": None,
480
+ }
481
+ try:
482
+ _execute(state, claude, budget_arg, threshold_arg, acct)
483
+ except (
484
+ Exception
485
+ ) as exc: # anything after the lock ends as a `failed` status; a killed run is the stale case
486
+ logger.debug("automatic curation run failed", exc_info=True)
487
+ acct["failures"].append(f"{type(exc).__name__}: {exc}"[:150])
488
+ try:
489
+ _finish(state, acct)
490
+ except Exception:
491
+ logger.debug("the end status could not be written", exc_info=True)
492
+ finally:
493
+ os.close(fd)
494
+ return 0
495
+
496
+
497
+ def cmd_due(store: Path, threshold_arg: str | None) -> int:
498
+ state = State(store)
499
+ threshold = threshold_of(threshold_arg or os.environ.get(THRESHOLD_OPTION))
500
+ marked = _marked(state)
501
+ try:
502
+ count = count_new(state, synth_run.session_env(store))
503
+ except RuntimeError as exc:
504
+ print(f"would not start: {exc}")
505
+ return 0
506
+ why = (
507
+ "the option auto_curation is not exactly true"
508
+ if os.environ.get(OPTION) != "true"
509
+ else "a run holds the lock"
510
+ if au.run_lock_held(synth_run.state_dir(), store)
511
+ else f"{count} is under the threshold"
512
+ if count < threshold and not (marked and not _held(state))
513
+ else ""
514
+ )
515
+ retry = f"; retry: {', '.join(sorted(marked))}" if marked else ""
516
+ retry += " (held until the next full run)" if marked and _held(state) else ""
517
+ print(
518
+ f"new records since the last run or pass: {count}; threshold: {threshold}{retry}; "
519
+ + (f"would not start: {why}" if why else "would start")
520
+ )
521
+ return 0
522
+
523
+
524
+ def cmd_status(store: Path) -> int:
525
+ state = State(store)
526
+ data = state.status()
527
+ if not data:
528
+ print("no automatic run yet")
529
+ return 0
530
+ now = time.time()
531
+ shown = data.get("state", "?")
532
+ if shown == "running" and now - float(data.get("started") or 0) > jobs.STALE_RUNNING_SECONDS:
533
+ shown = "failed (a run that did not finish)"
534
+ print(
535
+ f"last run: {stamp(data.get('started'))}, state {shown}, cost {float(data.get('cost') or 0):.3f} USD"
536
+ )
537
+ if data.get("reason"):
538
+ print(f"reason: {data['reason']}")
539
+ if marked := _marked(state):
540
+ when = "held until the next full run" if _held(state) else "runs alone at the next trigger"
541
+ print(f"retry: {', '.join(sorted(marked))} ({when})")
542
+ print(f"log: {data.get('log') or '(none)'}")
543
+ found = jobs.failure(data, now)
544
+ print(f"unacknowledged failure: {'yes (mem-auto ack clears it)' if found else 'no'}")
545
+ return 0
546
+
547
+
548
+ def cmd_ack(store: Path) -> int:
549
+ state = State(store)
550
+ data = state.status()
551
+ if data:
552
+ changes: dict = {"failure": None}
553
+ if jobs.failure({"state": data.get("state"), "started": data.get("started")}, time.time()):
554
+ changes["state"] = "failed" # a stale `running` is closed
555
+ state.save_status(**changes)
556
+ print("acknowledged: the failure line is cleared")
557
+ return 0
558
+
559
+
560
+ def self_check() -> int:
561
+ """No model: the lock, the folder mode, the options, and a run with the option unset (it starts nothing)."""
562
+ assert budget_of("x") == DEFAULT_BUDGET
563
+ assert math.isclose(budget_of("0.6"), CHECK_BUDGET)
564
+ assert threshold_of("3") == CHECK_THRESHOLD
565
+ assert threshold_of("0") == DEFAULT_THRESHOLD and threshold_of(None) == DEFAULT_THRESHOLD
566
+ with tempfile.TemporaryDirectory(prefix="mem-auto-check-") as tmp_name:
567
+ tmp = Path(tmp_name)
568
+ for name, folder in (
569
+ ("MEM_DATA", "data"),
570
+ ("XDG_DATA_HOME", "share"),
571
+ ("MEM_PROJECT", "project"),
572
+ ("XDG_CONFIG_HOME", "cfg"),
573
+ ):
574
+ os.environ[name] = str(tmp / folder)
575
+ os.environ.pop("MEM_MEMORIES", None)
576
+ store = tmp / "store"
577
+ init = subprocess.run(
578
+ [*sp.MEM, "init", str(store)],
579
+ env=resources.child_env(),
580
+ capture_output=True,
581
+ text=True,
582
+ check=False,
583
+ )
584
+ assert init.returncode == 0, init.stderr
585
+ state = State(store)
586
+ held = jobs.take_run_lock(state.dir)
587
+ assert held is not None and jobs.take_run_lock(state.dir) is None
588
+ assert au.run_lock_held(Path(os.environ["MEM_DATA"]), store)
589
+ os.close(held)
590
+ assert not au.run_lock_held(Path(os.environ["MEM_DATA"]), store)
591
+ assert (state.dir.stat().st_mode & 0o777) == DIR_MODE, oct(state.dir.stat().st_mode)
592
+ os.environ.pop(OPTION, None)
593
+ assert cmd_run(store, "/nonexistent", "2", 1) == 0 and not state.status().get("state"), (
594
+ "ran with the option unset"
595
+ )
596
+ os.environ[OPTION] = "true"
597
+ assert cmd_run(store, "/nonexistent", "2", 1000) == 0 and not state.status().get("state"), (
598
+ "ran under the threshold"
599
+ )
600
+ assert count_new(state, synth_run.session_env(store)) == 0
601
+ print("self-check passed")
602
+ return 0
603
+
604
+
605
+ def _missing_store(store: Path | None, command: str) -> int:
606
+ if command != "run": # run is silent: it starts from a hook
607
+ print(f"mem-auto: no store at {store}", file=sys.stderr)
608
+ return 0 if command == "run" else 2
609
+
610
+
611
+ def _dispatch(args: argparse.Namespace, store: Path) -> int:
612
+ if args.command == "run":
613
+ for name in SESSION_VARS: # left over from the session that started this process
614
+ os.environ.pop(name, None)
615
+ return cmd_run(store, args.claude, args.budget, args.threshold)
616
+ return {
617
+ "due": lambda: cmd_due(store, args.threshold),
618
+ "status": lambda: cmd_status(store),
619
+ "ack": lambda: cmd_ack(store),
620
+ }[args.command]()
621
+
622
+
623
+ def main(argv: list[str] | None = None) -> int:
624
+ parser = argparse.ArgumentParser(
625
+ prog="mem-auto", description=(__doc__ or "mem-auto").splitlines()[0]
626
+ )
627
+ parser.add_argument("command", nargs="?", choices=["run", "status", "ack", "due"])
628
+ parser.add_argument(
629
+ "--store", type=Path, help="default: the store `mem` resolves (MEM_STORE, else the default)"
630
+ )
631
+ parser.add_argument(
632
+ "--claude", default=os.environ.get("CLAUDE_CODE_EXECPATH") or shutil.which("claude")
633
+ )
634
+ runners.add_flag(parser)
635
+ parser.add_argument(
636
+ "--budget",
637
+ help=f"USD per run (default: the option auto_curation_budget, else {DEFAULT_BUDGET})",
638
+ )
639
+ parser.add_argument(
640
+ "--threshold",
641
+ help=f"new records that start a run (default: the option auto_curation_threshold, else {DEFAULT_THRESHOLD})",
642
+ )
643
+ parser.add_argument(
644
+ "--self-check",
645
+ action="store_true",
646
+ help="no model: prove the lock, the folder mode and the gates",
647
+ )
648
+ args = parser.parse_args(argv)
649
+ if args.self_check:
650
+ return self_check()
651
+ if not args.command:
652
+ parser.error("a command is required")
653
+ if args.command == "run" and (
654
+ refused := codex_pass.refuse_codex("mem-auto (the curator)", args.runner)
655
+ ):
656
+ return refused # before the store check: a run that starts from a hook is silent otherwise
657
+ store = args.store.expanduser().resolve() if args.store else synth_run.default_store()
658
+ if store is None or not (store / "mem-store.yaml").is_file():
659
+ return _missing_store(store, args.command)
660
+ return _dispatch(args, store)