memory-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- memory_cli/__init__.py +1 -0
- memory_cli/__main__.py +49 -0
- memory_cli/capture/__init__.py +7 -0
- memory_cli/capture/codex_rollout.py +164 -0
- memory_cli/capture/event_lines.py +66 -0
- memory_cli/capture/extract.py +458 -0
- memory_cli/capture/state.py +183 -0
- memory_cli/commands/__init__.py +21 -0
- memory_cli/commands/admin.py +363 -0
- memory_cli/commands/common.py +609 -0
- memory_cli/commands/curate.py +1189 -0
- memory_cli/commands/diagnostics.py +126 -0
- memory_cli/commands/edit.py +1282 -0
- memory_cli/commands/hooks.py +730 -0
- memory_cli/commands/import_recovery.py +45 -0
- memory_cli/commands/install.py +152 -0
- memory_cli/commands/integrate.py +480 -0
- memory_cli/commands/memory.py +2152 -0
- memory_cli/commands/read.py +1290 -0
- memory_cli/commands/sources.py +766 -0
- memory_cli/commands/split.py +97 -0
- memory_cli/commands/split_plan.py +196 -0
- memory_cli/commands/split_transaction.py +230 -0
- memory_cli/commands/synthesis.py +1122 -0
- memory_cli/core/__init__.py +16 -0
- memory_cli/core/auto_state.py +30 -0
- memory_cli/core/codex_pass.py +109 -0
- memory_cli/core/config.py +87 -0
- memory_cli/core/file_journal.py +163 -0
- memory_cli/core/headless.py +130 -0
- memory_cli/core/jobs.py +130 -0
- memory_cli/core/resources.py +57 -0
- memory_cli/core/runner.py +398 -0
- memory_cli/core/safe_io.py +155 -0
- memory_cli/core/store_git.py +407 -0
- memory_cli/core/yaml_load.py +14 -0
- memory_cli/corroborate/__init__.py +11 -0
- memory_cli/corroborate/cli.py +267 -0
- memory_cli/corroborate/decide.py +893 -0
- memory_cli/corroborate/digest.py +425 -0
- memory_cli/corroborate/fill.py +744 -0
- memory_cli/corroborate/job.py +15 -0
- memory_cli/corroborate/reword.py +446 -0
- memory_cli/corroborate/run.py +1142 -0
- memory_cli/corroborate/state.py +300 -0
- memory_cli/digest/__init__.py +4 -0
- memory_cli/digest/lessons.py +483 -0
- memory_cli/entry/__init__.py +12 -0
- memory_cli/entry/auto.py +660 -0
- memory_cli/entry/capture.py +1403 -0
- memory_cli/entry/corroborate.py +214 -0
- memory_cli/entry/integrate.py +684 -0
- memory_cli/entry/integrate_self_check.py +203 -0
- memory_cli/entry/research.py +9 -0
- memory_cli/entry/settle.py +614 -0
- memory_cli/entry/split_auto.py +460 -0
- memory_cli/entry/synthesize.py +22 -0
- memory_cli/integrate/__init__.py +9 -0
- memory_cli/integrate/answers.py +42 -0
- memory_cli/integrate/briefs/check-brief.md +16 -0
- memory_cli/integrate/briefs/place-brief.md +26 -0
- memory_cli/integrate/log.py +43 -0
- memory_cli/integrate/plan.py +125 -0
- memory_cli/integrate/rows.py +99 -0
- memory_cli/integrate/state.py +158 -0
- memory_cli/integrate/undo.py +143 -0
- memory_cli/mem.py +1180 -0
- memory_cli/memories/__init__.py +16 -0
- memory_cli/memories/fingerprints.py +51 -0
- memory_cli/memories/journal.py +93 -0
- memory_cli/memories/locations.py +282 -0
- memory_cli/memories/matching.py +451 -0
- memory_cli/memories/model.py +205 -0
- memory_cli/memories/parse.py +237 -0
- memory_cli/memories/records.py +266 -0
- memory_cli/memories/rules.py +291 -0
- memory_cli/memories/sightings.py +314 -0
- memory_cli/memories/terms.py +148 -0
- memory_cli/memories/write.py +358 -0
- memory_cli/notes/__init__.py +13 -0
- memory_cli/notes/check.py +806 -0
- memory_cli/notes/due.py +260 -0
- memory_cli/notes/fields.py +217 -0
- memory_cli/notes/index.py +230 -0
- memory_cli/notes/links.py +170 -0
- memory_cli/notes/note.py +222 -0
- memory_cli/notes/search.py +391 -0
- memory_cli/notes/split_candidates.py +72 -0
- memory_cli/research/__init__.py +5 -0
- memory_cli/research/checks.py +1065 -0
- memory_cli/research/pipeline.py +952 -0
- memory_cli/session/__init__.py +5 -0
- memory_cli/session/handoff.py +139 -0
- memory_cli/session/notices.py +111 -0
- memory_cli/settle/__init__.py +5 -0
- memory_cli/settle/state.py +111 -0
- memory_cli/settle/verdicts.py +693 -0
- memory_cli/split/briefs/checker-brief.md +5 -0
- memory_cli/split/briefs/editor-brief.md +20 -0
- memory_cli/syntheses/__init__.py +8 -0
- memory_cli/syntheses/document.py +400 -0
- memory_cli/syntheses/edit.py +581 -0
- memory_cli/syntheses/project.py +384 -0
- memory_cli/syntheses/split_conservation.py +50 -0
- memory_cli/syntheses/units.py +427 -0
- memory_cli/synthesize/__init__.py +9 -0
- memory_cli/synthesize/backfill.py +431 -0
- memory_cli/synthesize/briefs/backfill-brief.md +26 -0
- memory_cli/synthesize/briefs/checker-brief.md +13 -0
- memory_cli/synthesize/briefs/fixer-brief.md +19 -0
- memory_cli/synthesize/briefs/memory-brief.md +30 -0
- memory_cli/synthesize/briefs/settle-brief.md +32 -0
- memory_cli/synthesize/briefs/verdict-brief.md +50 -0
- memory_cli/synthesize/briefs/web-brief.md +33 -0
- memory_cli/synthesize/cli.py +311 -0
- memory_cli/synthesize/pipeline.py +764 -0
- memory_cli/synthesize/references.py +164 -0
- memory_cli/synthesize/run.py +150 -0
- memory_cli/synthesize/topics.py +528 -0
- memory_cli/templates/knowledge.md +23 -0
- memory_cli/templates/literature.md +25 -0
- memory_cli/templates/research.md +23 -0
- memory_cli/templates/synthesis.md +6 -0
- memory_cli-0.1.0.dist-info/METADATA +102 -0
- memory_cli-0.1.0.dist-info/RECORD +128 -0
- memory_cli-0.1.0.dist-info/WHEEL +4 -0
- memory_cli-0.1.0.dist-info/entry_points.txt +9 -0
- memory_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1403 @@
|
|
|
1
|
+
"""mem-capture: an offline trial of memory capture from one session transcript.
|
|
2
|
+
|
|
3
|
+
`run` reduces the transcript to an extract (`capture.extract`), gives it with the claims already recorded in the project's
|
|
4
|
+
memory to ONE headless session that has no Bash and no hooks, and keeps the candidates that `capture.validate` accepts
|
|
5
|
+
in a local JSON file. It writes nothing to the memory store and no hook runs it: it is started by hand.
|
|
6
|
+
|
|
7
|
+
With `--write`, code (never the model) then applies each kept candidate to the PROJECT's memory through `bin/mem`, so
|
|
8
|
+
every check that command makes at writing applies unchanged; nothing else runs it.
|
|
9
|
+
|
|
10
|
+
`auto --trigger {pre-compact,session-end}` is what a hook starts, detached and with its output discarded, when the plugin
|
|
11
|
+
option `auto_capture` is exactly `true`: it reads the hook JSON from standard input and the session from its saved
|
|
12
|
+
offset, in up to MAX_WINDOWS windows, and records what the windows hold in the project's memory (`run --write` per
|
|
13
|
+
window). It always exits 0 and prints nothing: it leaves `<data folder>/capture/status.json`, `log.jsonl` (counts only)
|
|
14
|
+
and `runs/<stamp>/`. `ack` clears the failure it left.
|
|
15
|
+
|
|
16
|
+
Usage: mem-capture run --transcript PATH --out FILE [--project DIR] [--since-line N] [--forward] [--model NAME] [--budget USD]
|
|
17
|
+
[--claude PATH] [--no-rules] [--keep-work] [--write]
|
|
18
|
+
mem-capture auto --trigger {pre-compact,session-end} [--claude PATH] < hook.json
|
|
19
|
+
mem-capture ack
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import argparse
|
|
25
|
+
import contextlib
|
|
26
|
+
import datetime
|
|
27
|
+
import json
|
|
28
|
+
import math
|
|
29
|
+
import os
|
|
30
|
+
import shutil
|
|
31
|
+
import subprocess
|
|
32
|
+
import sys
|
|
33
|
+
import tempfile
|
|
34
|
+
import time
|
|
35
|
+
from dataclasses import dataclass
|
|
36
|
+
from pathlib import Path
|
|
37
|
+
from typing import Any
|
|
38
|
+
|
|
39
|
+
from memory_cli.capture import codex_rollout
|
|
40
|
+
from memory_cli.capture import extract as capture
|
|
41
|
+
from memory_cli.capture import state as cs
|
|
42
|
+
from memory_cli.core import codex_pass, headless, jobs, resources
|
|
43
|
+
from memory_cli.core import runner as runners
|
|
44
|
+
from memory_cli.memories import records
|
|
45
|
+
from memory_cli.synthesize import pipeline as sp
|
|
46
|
+
|
|
47
|
+
LOCK_POLL_SECONDS = 5.0
|
|
48
|
+
MIN_LOCK_POLL_SECONDS = 0.01
|
|
49
|
+
|
|
50
|
+
DEFAULT_BUDGET = 0.25 # USD; also the default of `auto`
|
|
51
|
+
DEFAULT_MODEL = "haiku"
|
|
52
|
+
SESSION_TIMEOUT = 600
|
|
53
|
+
MAX_CANDIDATES_BYTES = 1_000_000
|
|
54
|
+
MIN_OWNER_LINES = 3
|
|
55
|
+
CWD_SCAN_LINES = 200 # lines of a transcript the sweep reads to find its working folder
|
|
56
|
+
DAY_DEPTH = 3 # a Codex day folder sits at sessions/YYYY/MM/DD
|
|
57
|
+
FIRST_LINE_LIMIT = 1 << 20 # a first line longer than this is not a Codex `session_meta`
|
|
58
|
+
RULES_LIMIT = 30_000
|
|
59
|
+
LAPSED_DAYS = (
|
|
60
|
+
60 # a lapsed unconfirmed transcript memory can still be revived by a new sighting this long
|
|
61
|
+
)
|
|
62
|
+
MEM = resources.mem_command()
|
|
63
|
+
CORROBORATE = resources.mem_command("mem-corroborate")
|
|
64
|
+
MEM_TIMEOUT = 60
|
|
65
|
+
MEM_EXIT_COUNTED = 3 # `bin/mem`: this session already counted, or the claim is already recorded
|
|
66
|
+
MEM_EXIT_SECRET = 4 # `bin/mem`: the claim holds a secret
|
|
67
|
+
SESSION_VARS = (
|
|
68
|
+
"CLAUDE_ENV_FILE",
|
|
69
|
+
"CLAUDE_PLUGIN_ROOT",
|
|
70
|
+
"CLAUDE_PLUGIN_DATA",
|
|
71
|
+
"CLAUDE_PROJECT_DIR",
|
|
72
|
+
"CLAUDE_PID",
|
|
73
|
+
"CLAUDE_CODE_SESSION_ID",
|
|
74
|
+
"CLAUDE_CODE_MESSAGING_SOCKET",
|
|
75
|
+
"CLAUDE_CODE_MESSAGING_TOKEN",
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
WORK_PLACEHOLDER = "{work}"
|
|
79
|
+
BRIEF = """You read the record of one coding session and find what a later session should not have to learn again.
|
|
80
|
+
|
|
81
|
+
Files in {work}:
|
|
82
|
+
- extract-1.txt, extract-2.txt, ...: the session in order, one event per line. Read every one of them before you write. OWNER is the human, OWNER ANSWER the human's answer to a question, AGENT the assistant, REPORT a message from a subagent or another agent (not the human), TOOL lines the assistant's tool calls, TOOL ERROR a call that failed, TOOL OK the same tool succeeding after an error. The bracket and the label at the start of a line are positions, not content.
|
|
83
|
+
- recorded.txt: what the memory already holds, one per line. A line starting with m: is a memory of this project, with its handle; a line starting with g: is a general lesson recorded from other sessions, with its handle; a line starting with (general) holds in every project.
|
|
84
|
+
- rules.txt: the standing instructions the owner already wrote for the agent.
|
|
85
|
+
|
|
86
|
+
Write {work}/candidates.json: a JSON list of at most 5 objects, or [] when nothing qualifies. Most sessions hold one or two things worth keeping, many hold none; five is a ceiling, not a target. Order what you found by how much a later session would lose without it, and keep only the ones you would defend to the owner.
|
|
87
|
+
|
|
88
|
+
Two kinds of thing qualify, and they are not the same:
|
|
89
|
+
- A lesson or a pitfall: something that generalises beyond this session and can be said as advice.
|
|
90
|
+
- A decision of this project with its reason. That is a record of the project, not a lesson: give it "kind": "decision" and "reach": "project".
|
|
91
|
+
A technical detail of one component, a progress report, or a request the owner made once is neither: leave it out, unless the step the owner asked for visibly paid off (the signal "owner_request_paid_off").
|
|
92
|
+
|
|
93
|
+
Each object has these keys:
|
|
94
|
+
- "signal": what in the session backs it. One of
|
|
95
|
+
"owner_correction" (the owner corrected the agent or rejected its approach; the evidence must come from an OWNER line),
|
|
96
|
+
"failed_then_passed" (a check or command failed, the agent changed something, it passed),
|
|
97
|
+
"verified_review_finding" (a review found a defect that was then confirmed and fixed),
|
|
98
|
+
"plan_changed_by_review" (a pre-mortem, a review or the owner changed a plan or a design before it was built),
|
|
99
|
+
"delegation_failed" (a subagent returned no report, stopped at a limit, misread its brief, or its report proved wrong),
|
|
100
|
+
"rework" (work declared done had to be redone or fixed right after),
|
|
101
|
+
"repeated_tool_error" (the same kind of tool error happened more than once),
|
|
102
|
+
"decision_with_reason" (the owner decided something and said why; the evidence must come from an OWNER or OWNER ANSWER line),
|
|
103
|
+
"owner_approval" (the owner said that a way of working served them well, or asked for more of it; the evidence must come from an OWNER or OWNER ANSWER line),
|
|
104
|
+
"owner_request_paid_off" (the owner asked, unprompted, for a step the agent had not planned, such as one more review, a check or a comparison, and the step visibly paid off: it found something, prevented rework or improved the result; the evidence must come from the OWNER or OWNER ANSWER line that asked for the step, and the claim says what the step then showed),
|
|
105
|
+
"effective_practice" (a way of planning, briefing, checking or using a tool visibly paid off in this session: it worked the first time where earlier attempts had not, saved a round, or caught something early; the evidence shows the result, not the intention).
|
|
106
|
+
Without one of these there is no candidate: an idea the agent had about itself, with nothing outside confirming it, is not kept.
|
|
107
|
+
Look for what worked as much as for what failed. The aim is not only fewer mistakes but better and cheaper work: a lesson may say "doing it this way tended to give a better result" and what made it work. It is also less work for the owner: when the owner had to ask for a step that then proved its worth, the lesson is to consider that step without being asked, as a suggestion, so that the owner needs to step in less often.
|
|
108
|
+
- "kind": "lesson" (how to work), "pitfall" (something that breaks or misleads), or "decision".
|
|
109
|
+
- "reach": "project" when it is about this codebase, its tools or its rules; "general" when it is about how the agent itself works in any project: how it plans, frames a request, briefs or checks a subagent, uses a skill or a plugin, verifies before claiming, or reads the owner's intent. Look for the general ones on purpose: a slip in method teaches more than the bug it caused. A general claim names no file, project or person. A project claim should name the exact file, command or setting it is about, because that is what makes it usable.
|
|
110
|
+
- "weight": how much following it restricts the agent or the owner, and what it costs if it is wrong: "light" (a cheap habit that can hardly hurt), "medium", or "strong" (it forbids something, or a mistake would be costly).
|
|
111
|
+
- "form": "suggestion" (worth trying) or "recommendation" (do this unless there is a reason not to). Never an order.
|
|
112
|
+
- "claim": 20 to 400 characters, in English, standing on its own in six months. Say what was seen and what it suggests, at the strength the evidence gives it and no more. This session is one sighting: write "in one session ...", "when X, Y happened, so consider ...", not "always" or "never". Say what is not known: whether it holds elsewhere, whether it may be temporary, under which condition it was seen. When the signal is a correction by the owner, report it as what the owner said and did, and weigh the other reading too: the owner may have misread the agent, and then the lesson is to explain more clearly.
|
|
113
|
+
- "context": one sentence on when it applies.
|
|
114
|
+
- "evidence": a passage copied character for character from inside one line of an extract file, without the bracket and label, 15 to 300 characters, that shows the signal. A paraphrase, or a passage that spans two lines, is rejected by a program.
|
|
115
|
+
- "same_as": only when a line of recorded.txt starting with m: or g: already says this: its handle, exactly as written (for example "m:some-handle" or "g:some-handle"). Then this session is one more sighting of it; still give the other keys.
|
|
116
|
+
|
|
117
|
+
Leave out: what a (general) line of recorded.txt or rules.txt already says; what the code, the git history or the project's documents already state; secrets, tokens, names of people or clients.
|
|
118
|
+
A candidate that states the same lesson as a line starting with m: or g: is not left out for that reason: give it, with "same_as" set to that handle.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def budget_arg(value: str) -> float:
|
|
123
|
+
try:
|
|
124
|
+
number = float(value)
|
|
125
|
+
except ValueError:
|
|
126
|
+
raise argparse.ArgumentTypeError(f"not a number: {value!r}") from None
|
|
127
|
+
if not math.isfinite(number) or number <= 0:
|
|
128
|
+
raise argparse.ArgumentTypeError(f"must be a positive number: {value!r}")
|
|
129
|
+
return number
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def repo_above(folder: Path) -> Path | None:
|
|
133
|
+
"""The nearest folder, `folder` or an ancestor, that holds an entry named `.git`."""
|
|
134
|
+
for p in (folder, *folder.parents):
|
|
135
|
+
if os.path.lexists(p / ".git"):
|
|
136
|
+
return p
|
|
137
|
+
return None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def private_dirs(folder: Path) -> None:
|
|
141
|
+
"""`folder` and the parents it lacks, mode 0700 (`mkdir(parents=True)` gives the parents the default mode)."""
|
|
142
|
+
missing = []
|
|
143
|
+
for p in (folder, *folder.parents):
|
|
144
|
+
if p.exists():
|
|
145
|
+
break
|
|
146
|
+
missing.append(p)
|
|
147
|
+
for p in reversed(missing):
|
|
148
|
+
p.mkdir(mode=0o700, exist_ok=True)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def write_private(path: Path, text: str) -> None:
|
|
152
|
+
"""Never follows a symlink at `path`; the mode is set on the descriptor before anything is written."""
|
|
153
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
|
154
|
+
with os.fdopen(fd, "w", encoding="utf-8", errors="replace") as f:
|
|
155
|
+
os.fchmod(f.fileno(), 0o600)
|
|
156
|
+
f.write(text)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _one_line(text: str) -> str:
|
|
160
|
+
return " ".join(text.split())
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _lapsed(m, today: datetime.date) -> bool:
|
|
164
|
+
"""An active unconfirmed memory whose validity ended at most LAPSED_DAYS ago."""
|
|
165
|
+
return (
|
|
166
|
+
m.status == "active"
|
|
167
|
+
and records.standing(m) == "unconfirmed"
|
|
168
|
+
and m.valid_until is not None
|
|
169
|
+
and today - datetime.timedelta(days=LAPSED_DAYS) <= m.valid_until < today
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def recorded_lines(project: Path) -> tuple[list[str], dict[str, str]]:
|
|
174
|
+
r"""The lines of recorded.txt, and the claims by handle: the project's memories ("m:<handle>") and the global
|
|
175
|
+
records of origin transcript ("g:<handle>").
|
|
176
|
+
|
|
177
|
+
Project: live memories, and unconfirmed transcript memories lapsed for at most LAPSED_DAYS (a new sighting
|
|
178
|
+
revives them); a line is `m:<handle>\t<claim>`. Global: transcript records, live or lapsed alike and in
|
|
179
|
+
quarantine too, as `g:<handle>\t<claim>`; the other live ones as `(general)\t<claim>`, with no handle."""
|
|
180
|
+
today = datetime.date.today()
|
|
181
|
+
lines: list[str] = []
|
|
182
|
+
handles: dict[str, str] = {}
|
|
183
|
+
for m in records.load_memories(records.project_dir(project), "project"):
|
|
184
|
+
claim = _one_line(m.claim)
|
|
185
|
+
lapsed = m.origin == "transcript" and _lapsed(m, today)
|
|
186
|
+
if claim and (records.is_live(m, today) or lapsed):
|
|
187
|
+
lines.append(f"m:{m.handle}\t{claim}")
|
|
188
|
+
handles[f"m:{m.handle}"] = claim
|
|
189
|
+
for m in records.load_memories(records.global_memories_root(os.environ), "global"):
|
|
190
|
+
claim = _one_line(m.claim)
|
|
191
|
+
if claim:
|
|
192
|
+
_global_line(m, claim, today, lines, handles)
|
|
193
|
+
return lines, handles
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _global_line(
|
|
197
|
+
m, claim: str, today: datetime.date, lines: list[str], handles: dict[str, str]
|
|
198
|
+
) -> None:
|
|
199
|
+
"""Add a global memory to the recorded lines: transcript ones with a handle (quarantined ones too: that is
|
|
200
|
+
how they get corroborated), the other live ones as `(general)`."""
|
|
201
|
+
if m.origin == "transcript" and (records.is_live(m, today) or _lapsed(m, today)):
|
|
202
|
+
lines.append(f"g:{m.handle}\t{claim}")
|
|
203
|
+
handles[f"g:{m.handle}"] = claim
|
|
204
|
+
elif records.is_live(m, today):
|
|
205
|
+
lines.append(f"(general)\t{claim}")
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def rules_text(project: Path) -> tuple[str, bool]:
|
|
209
|
+
"""The owner's always-loaded instruction files, each under `## <name>`, the project's first, each cut to
|
|
210
|
+
RULES_LIMIT characters; and whether any was cut."""
|
|
211
|
+
config = os.environ.get("CLAUDE_CONFIG_DIR")
|
|
212
|
+
config_dir = Path(config).expanduser() if config else Path.home() / ".claude"
|
|
213
|
+
parts: list[str] = []
|
|
214
|
+
cut = False
|
|
215
|
+
for path in (project / "CLAUDE.md", project / "AGENTS.md", config_dir / "CLAUDE.md"):
|
|
216
|
+
try:
|
|
217
|
+
if path.is_file():
|
|
218
|
+
with path.open(encoding="utf-8", errors="replace") as f:
|
|
219
|
+
text = f.read(RULES_LIMIT + 1) # never the whole of a huge file
|
|
220
|
+
else:
|
|
221
|
+
text = ""
|
|
222
|
+
except OSError:
|
|
223
|
+
text = ""
|
|
224
|
+
if not text.strip():
|
|
225
|
+
continue
|
|
226
|
+
if len(text) > RULES_LIMIT:
|
|
227
|
+
text, cut = text[:RULES_LIMIT].rstrip("\n") + "\n[...] cut", True
|
|
228
|
+
parts.append(f"## {path.name}\n{text.rstrip(chr(10))}\n")
|
|
229
|
+
return "\n".join(parts), cut
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def session_cmd(
|
|
233
|
+
claude: str, work: Path, settings: Path, model: str, max_budget: float
|
|
234
|
+
) -> list[str]:
|
|
235
|
+
"""One session. Only the Read and Write tools exist (`--tools`, no MCP server), allowed inside `work` only (`//` is
|
|
236
|
+
an absolute path in a permission rule; a new file needs the Edit rule beside Write); no Bash, no web, hooks disabled
|
|
237
|
+
by `settings`. `work` is resolved so the prompt and the rules name the path the session sees (macOS /var is a link
|
|
238
|
+
to /private/var)."""
|
|
239
|
+
work = work.resolve()
|
|
240
|
+
return headless.command(
|
|
241
|
+
headless.Session(
|
|
242
|
+
claude=claude,
|
|
243
|
+
prompt=BRIEF.replace(WORK_PLACEHOLDER, str(work)),
|
|
244
|
+
model=model,
|
|
245
|
+
settings=settings,
|
|
246
|
+
effort="medium",
|
|
247
|
+
tools=("Read", "Write"),
|
|
248
|
+
allowed=(f"Read(/{work}/**)", f"Write(/{work}/**)", f"Edit(/{work}/**)"),
|
|
249
|
+
disallowed=("Bash", "WebSearch", "WebFetch"),
|
|
250
|
+
max_budget=max_budget,
|
|
251
|
+
)
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def run_session(cmd: list[str], work: Path) -> dict:
|
|
256
|
+
env = {k: v for k, v in os.environ.items() if k not in SESSION_VARS}
|
|
257
|
+
raw = headless.run_raw(cmd, cwd=work, env=env, timeout=SESSION_TIMEOUT).stdout
|
|
258
|
+
return sp.parse(raw)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def read_candidates(path: Path) -> tuple[object, str | None]:
|
|
262
|
+
if not path.is_file():
|
|
263
|
+
return None, "the session wrote no candidates.json"
|
|
264
|
+
try:
|
|
265
|
+
if path.stat().st_size > MAX_CANDIDATES_BYTES:
|
|
266
|
+
return None, "candidates file too large"
|
|
267
|
+
rows = json.loads(path.read_text(encoding="utf-8"))
|
|
268
|
+
except (OSError, ValueError):
|
|
269
|
+
return None, "candidates.json is not valid JSON"
|
|
270
|
+
return (rows, None) if isinstance(rows, list) else (None, "candidates.json is not a JSON list")
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
Applied = tuple[str, str | None, str | None] # (outcome, handle, reason)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _run_mem(
|
|
277
|
+
cmd: list[str], env: dict, stdin: str | None = None
|
|
278
|
+
) -> subprocess.CompletedProcess | None:
|
|
279
|
+
"""`bin/mem` with `cmd`, or None when it could not run."""
|
|
280
|
+
try:
|
|
281
|
+
return subprocess.run(
|
|
282
|
+
cmd,
|
|
283
|
+
check=False,
|
|
284
|
+
env=resources.child_env(env),
|
|
285
|
+
input=stdin,
|
|
286
|
+
capture_output=True,
|
|
287
|
+
text=True,
|
|
288
|
+
timeout=MEM_TIMEOUT,
|
|
289
|
+
)
|
|
290
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
291
|
+
return None
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def apply_global_sighting(
|
|
295
|
+
item: dict, session: str, env: dict, clean, day: str | None = None
|
|
296
|
+
) -> Applied:
|
|
297
|
+
"""One more sighting of a global record, counted with the project's key. The note never holds the evidence:
|
|
298
|
+
text of a transcript must not reach the global scope."""
|
|
299
|
+
project = Path(env["MEM_PROJECT"])
|
|
300
|
+
if records.under_temp(project):
|
|
301
|
+
return "skipped", None, "a temporary project"
|
|
302
|
+
handle = item["same_as"][2:]
|
|
303
|
+
if not any(
|
|
304
|
+
m.handle == handle and m.origin == "transcript" and m.status == "active"
|
|
305
|
+
for m in records.load_memories(records.global_memories_root(os.environ), "global")
|
|
306
|
+
):
|
|
307
|
+
return "skipped", None, "not a global memory any more"
|
|
308
|
+
source = records.sighting_entry(session, records.project_key(project))
|
|
309
|
+
cmd = [
|
|
310
|
+
*MEM,
|
|
311
|
+
"confirm",
|
|
312
|
+
f"m:{handle}",
|
|
313
|
+
"--global",
|
|
314
|
+
clean(f"--source={source}"),
|
|
315
|
+
f"--note=Seen again ({item['signal']}).",
|
|
316
|
+
f"--outcome={capture.outcome(item['signal'])}",
|
|
317
|
+
*_seen_on(day),
|
|
318
|
+
]
|
|
319
|
+
done = _run_mem(cmd, env)
|
|
320
|
+
if done is None:
|
|
321
|
+
return "skipped", None, "mem could not run"
|
|
322
|
+
if done.returncode == 0:
|
|
323
|
+
return "sighting", handle, None
|
|
324
|
+
if done.returncode == MEM_EXIT_COUNTED:
|
|
325
|
+
return "skipped", None, "this session already counted"
|
|
326
|
+
return "skipped", None, f"mem failed ({done.returncode})"
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _seen_on(day: str | None) -> list[str]:
|
|
330
|
+
return [f"--seen-on={day}"] if day else []
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _clean(text: str) -> str:
|
|
334
|
+
"""A lone surrogate cannot be encoded as an argument."""
|
|
335
|
+
return text.encode("utf-8", "replace").decode("utf-8")
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _confirm_cmd(item: dict, session: str, day: str | None) -> list[str]:
|
|
339
|
+
return [
|
|
340
|
+
*MEM,
|
|
341
|
+
"confirm",
|
|
342
|
+
item["same_as"],
|
|
343
|
+
f"--source={session}",
|
|
344
|
+
_clean(f"--note=Seen again ({item['signal']}): “{item['evidence']}”"),
|
|
345
|
+
f"--outcome={capture.outcome(item['signal'])}",
|
|
346
|
+
*_seen_on(day),
|
|
347
|
+
]
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _remember_cmd(item: dict, session: str, day: str | None) -> tuple[list[str], str]:
|
|
351
|
+
"""The `mem remember` command and what it reads on standard input."""
|
|
352
|
+
cmd = [
|
|
353
|
+
*MEM,
|
|
354
|
+
"remember",
|
|
355
|
+
f"--kind={item['kind']}",
|
|
356
|
+
_clean(f"--claim={item['claim']}"),
|
|
357
|
+
_clean(f"--context={item['context']}"),
|
|
358
|
+
"--origin",
|
|
359
|
+
"transcript",
|
|
360
|
+
"--reach",
|
|
361
|
+
item["reach"],
|
|
362
|
+
"--weight",
|
|
363
|
+
item["weight"],
|
|
364
|
+
f"--source={session}",
|
|
365
|
+
"--body-file",
|
|
366
|
+
"-",
|
|
367
|
+
f"--outcome={capture.outcome(item['signal'])}",
|
|
368
|
+
*_seen_on(day),
|
|
369
|
+
]
|
|
370
|
+
body = _clean(
|
|
371
|
+
f"Signal: {item['signal']}\nForm: {item['form']}\nEvidence: “{item['evidence']}”\n"
|
|
372
|
+
)
|
|
373
|
+
return cmd, body
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _already_recorded(item: dict, stdout: str) -> Applied:
|
|
377
|
+
"""`mem remember` found the same claim: what it printed first says whether this session counted."""
|
|
378
|
+
if item["same_as"]:
|
|
379
|
+
return "skipped", None, "this session already counted"
|
|
380
|
+
lines = stdout.strip().splitlines()
|
|
381
|
+
handle, _, verdict = lines[0].partition("\t") if lines else ("", "", "")
|
|
382
|
+
if verdict in {"sighting", "case"}:
|
|
383
|
+
return "sighting", handle, None
|
|
384
|
+
if verdict == "already counted":
|
|
385
|
+
return "skipped", handle, "this session already counted"
|
|
386
|
+
return "skipped", None, "same claim already recorded"
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _mem_result(item: dict, done: subprocess.CompletedProcess) -> Applied:
|
|
390
|
+
handle = done.stdout.split("\t", 1)[0].strip() if done.stdout.startswith("m:") else None
|
|
391
|
+
if done.returncode == 0:
|
|
392
|
+
return ("sighting" if item["same_as"] else "remembered"), handle, None
|
|
393
|
+
if done.returncode == MEM_EXIT_COUNTED:
|
|
394
|
+
return _already_recorded(item, done.stdout)
|
|
395
|
+
if done.returncode == MEM_EXIT_SECRET:
|
|
396
|
+
return "skipped", None, "refused: a secret"
|
|
397
|
+
return "skipped", None, f"mem failed ({done.returncode})"
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _is_project_memory(handle: str, env: dict) -> bool:
|
|
401
|
+
"""`mem confirm` also finds global records: only a memory of this project may get the sighting."""
|
|
402
|
+
project = records.project_dir(Path(env["MEM_PROJECT"]))
|
|
403
|
+
return any(f"m:{m.handle}" == handle for m in records.load_memories(project, "project"))
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def apply_one(item: dict, session: str, env: dict, day: str | None = None) -> Applied:
|
|
407
|
+
"""Apply one kept candidate with `bin/mem`: (outcome, handle, reason). Text arguments use `--name=value`
|
|
408
|
+
because a claim may start with `-`."""
|
|
409
|
+
same_as = item["same_as"]
|
|
410
|
+
if same_as and same_as.startswith("g:"):
|
|
411
|
+
return apply_global_sighting(item, session, env, _clean, day)
|
|
412
|
+
stdin = None
|
|
413
|
+
if same_as:
|
|
414
|
+
if not _is_project_memory(same_as, env):
|
|
415
|
+
return "skipped", None, "not a memory of this project any more"
|
|
416
|
+
cmd = _confirm_cmd(item, session, day)
|
|
417
|
+
else:
|
|
418
|
+
cmd, stdin = _remember_cmd(item, session, day)
|
|
419
|
+
done = _run_mem(cmd, env, stdin)
|
|
420
|
+
if done is None:
|
|
421
|
+
return "skipped", None, "mem could not run"
|
|
422
|
+
return _mem_result(item, done)
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def apply_all(items: list[dict], transcript: Path, project: Path) -> list[dict]:
|
|
426
|
+
session = f"session {transcript.stem}"
|
|
427
|
+
env = {**os.environ, "MEM_PROJECT": str(project)}
|
|
428
|
+
try: # the day the session ended (its file's last change, local time), not the day of a late sweep
|
|
429
|
+
day = datetime.date.fromtimestamp(transcript.stat().st_mtime).isoformat()
|
|
430
|
+
except (OSError, OverflowError, ValueError):
|
|
431
|
+
day = None
|
|
432
|
+
rows = []
|
|
433
|
+
for item in items:
|
|
434
|
+
try:
|
|
435
|
+
outcome, handle, reason = apply_one(item, session, env, day)
|
|
436
|
+
except Exception: # ruff: ignore[blind-except] - one odd candidate never stops the others
|
|
437
|
+
outcome, handle, reason = "skipped", None, "could not be applied"
|
|
438
|
+
rows.append({
|
|
439
|
+
"claim": item["claim"][:80].encode("utf-8", "replace").decode("utf-8"),
|
|
440
|
+
"outcome": outcome,
|
|
441
|
+
"handle": handle,
|
|
442
|
+
"reason": reason,
|
|
443
|
+
})
|
|
444
|
+
return rows
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
@dataclass
|
|
448
|
+
class Window:
|
|
449
|
+
"""What `run_window` is asked for. `allow_out_in_repo` skips only the refusal of an `--out` inside a repository
|
|
450
|
+
(a symlink is always refused); `quiet` suppresses only the summary line on standard output; `project=None`
|
|
451
|
+
is `--project` absent."""
|
|
452
|
+
|
|
453
|
+
transcript: Path
|
|
454
|
+
out_path: Path
|
|
455
|
+
project: Path | None
|
|
456
|
+
since_line: int
|
|
457
|
+
model: str
|
|
458
|
+
budget: float
|
|
459
|
+
claude: str | None
|
|
460
|
+
forward: bool
|
|
461
|
+
write: bool
|
|
462
|
+
no_rules: bool = False
|
|
463
|
+
keep_work: bool = False
|
|
464
|
+
allow_out_in_repo: bool = False
|
|
465
|
+
quiet: bool = False
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
@dataclass
|
|
469
|
+
class Trial:
|
|
470
|
+
"""One window being run: its request, the resolved paths and the result dict that is filled as it goes."""
|
|
471
|
+
|
|
472
|
+
opts: Window
|
|
473
|
+
transcript: Path
|
|
474
|
+
project: Path
|
|
475
|
+
since: int
|
|
476
|
+
out: dict
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def _blank_result(name: str, since: int, model: str, project: Path) -> dict:
|
|
480
|
+
return {
|
|
481
|
+
"transcript": name,
|
|
482
|
+
"lines": [since + 1, since],
|
|
483
|
+
"model": model,
|
|
484
|
+
"cost": None,
|
|
485
|
+
"modeled": False,
|
|
486
|
+
"extract": {**_extract_info(""), "skipped": 0, "more": False},
|
|
487
|
+
"candidates": [],
|
|
488
|
+
"dropped": [],
|
|
489
|
+
"reason": None,
|
|
490
|
+
"project": project.name,
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def _extract_info(text: str) -> dict:
|
|
495
|
+
return {
|
|
496
|
+
"chars": len(text),
|
|
497
|
+
"cut": text.startswith(capture.LEFT_OUT_MARKER),
|
|
498
|
+
"parts": len(capture.parts(text)) if text else 0,
|
|
499
|
+
"skipped": capture.last_skipped,
|
|
500
|
+
"more": capture.last_more,
|
|
501
|
+
"lines": capture.counts(text),
|
|
502
|
+
"rules_chars": 0,
|
|
503
|
+
"rules_cut": False,
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def _out_refusal(out_path: Path, allow_out_in_repo: bool) -> str | None:
|
|
508
|
+
repo = None if allow_out_in_repo else repo_above(out_path.parent.resolve())
|
|
509
|
+
if repo is not None:
|
|
510
|
+
return f"--out is inside a repository ({repo}); the result holds session text"
|
|
511
|
+
if out_path.is_symlink():
|
|
512
|
+
return "--out is a symlink; refusing to write through it"
|
|
513
|
+
return None
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _summary_line(out: dict) -> str:
|
|
517
|
+
cost = "unknown" if out["cost"] is None else f"{out['cost']:.3f}"
|
|
518
|
+
line = (
|
|
519
|
+
f"mem-capture: {len(out['candidates'])} kept, {len(out['dropped'])} dropped, "
|
|
520
|
+
f"lines {out['lines'][0]}-{out['lines'][1]}, cost {cost}"
|
|
521
|
+
)
|
|
522
|
+
if "written" in out:
|
|
523
|
+
n = [
|
|
524
|
+
sum(w["outcome"] == k for w in out["written"])
|
|
525
|
+
for k in ("remembered", "sighting", "skipped")
|
|
526
|
+
]
|
|
527
|
+
line += f", written {n[0]} new, {n[1]} sightings, {n[2]} skipped"
|
|
528
|
+
return line
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def _finish(out: dict, out_path: Path, code: int, quiet: bool) -> tuple[dict, int]:
|
|
532
|
+
try:
|
|
533
|
+
private_dirs(out_path.parent)
|
|
534
|
+
write_private(out_path, json.dumps(out, ensure_ascii=False, indent=1) + "\n")
|
|
535
|
+
except OSError as exc:
|
|
536
|
+
print(f"mem-capture: cannot write {out_path.name}: {exc.strerror or exc}", file=sys.stderr)
|
|
537
|
+
return out, 1
|
|
538
|
+
if code:
|
|
539
|
+
print(f"mem-capture: {out['reason']}", file=sys.stderr)
|
|
540
|
+
elif not quiet:
|
|
541
|
+
print(_summary_line(out))
|
|
542
|
+
return out, code
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def _model_session(cmd: list[str], work: Path, out: dict, claude: str) -> str | None:
|
|
546
|
+
"""Run the session; fill `modeled` and `cost` in `out`; the reason it failed, else None."""
|
|
547
|
+
try:
|
|
548
|
+
done = run_session(cmd, work)
|
|
549
|
+
except OSError as exc:
|
|
550
|
+
return f"cannot start claude ({claude}): {exc.strerror or exc}"
|
|
551
|
+
out["modeled"] = True # a model session ran, whatever its end
|
|
552
|
+
out["cost"] = done["cost"] if done["has_result"] else None
|
|
553
|
+
if not done["has_result"]:
|
|
554
|
+
return "the session ended without a cost report"
|
|
555
|
+
return "the session failed" if done["error"] else None
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def _write_work(work: Path, text: str, trial: Trial) -> tuple[list[str], dict[str, str]]:
|
|
559
|
+
"""The files the session reads; the recorded lines and their handles."""
|
|
560
|
+
for number, piece in enumerate(capture.parts(text), 1):
|
|
561
|
+
write_private(work / f"extract-{number}.txt", piece + "\n")
|
|
562
|
+
recorded, handles = recorded_lines(trial.project)
|
|
563
|
+
write_private(work / "recorded.txt", "".join(f"{c}\n" for c in recorded))
|
|
564
|
+
rules, rules_cut = ("", False) if trial.opts.no_rules else rules_text(trial.project)
|
|
565
|
+
write_private(work / "rules.txt", rules)
|
|
566
|
+
trial.out["extract"]["rules_chars"], trial.out["extract"]["rules_cut"] = len(rules), rules_cut
|
|
567
|
+
return recorded, handles
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def _in_work_folder(root: Path, trial: Trial, claude: str, text: str) -> int:
|
|
571
|
+
work = root / "work"
|
|
572
|
+
work.mkdir(mode=0o700)
|
|
573
|
+
recorded, handles = _write_work(work, text, trial)
|
|
574
|
+
settings = root / "settings.json"
|
|
575
|
+
# no hook of the session may run anything
|
|
576
|
+
write_private(settings, json.dumps({"disableAllHooks": True}))
|
|
577
|
+
opts, out = trial.opts, trial.out
|
|
578
|
+
cmd = session_cmd(claude, work, settings, opts.model, opts.budget)
|
|
579
|
+
out["reason"] = _model_session(cmd, work, out, claude)
|
|
580
|
+
if out["reason"]:
|
|
581
|
+
return 1
|
|
582
|
+
rows, out["reason"] = read_candidates(work / "candidates.json")
|
|
583
|
+
if out["reason"]:
|
|
584
|
+
return 1
|
|
585
|
+
out["candidates"], out["dropped"] = capture.validate(
|
|
586
|
+
rows, text, [c.split("\t", 1)[1] for c in recorded], handles
|
|
587
|
+
)
|
|
588
|
+
if opts.write:
|
|
589
|
+
out["written"] = apply_all(out["candidates"], trial.transcript, trial.project)
|
|
590
|
+
return 0
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def _with_work_root(trial: Trial, claude: str, text: str) -> int:
|
|
594
|
+
root = Path(tempfile.mkdtemp(prefix="mem-capture-")) # mode 0700
|
|
595
|
+
try:
|
|
596
|
+
return _in_work_folder(root, trial, claude, text)
|
|
597
|
+
finally:
|
|
598
|
+
if trial.opts.keep_work:
|
|
599
|
+
print(f"mem-capture: work folder kept at {root}", file=sys.stderr)
|
|
600
|
+
else:
|
|
601
|
+
shutil.rmtree(root, ignore_errors=True)
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def _read_window(trial: Trial) -> int:
|
|
605
|
+
"""Extract the window and run the session on it; the exit code. Fills `trial.out`."""
|
|
606
|
+
out, opts = trial.out, trial.opts
|
|
607
|
+
if not trial.transcript.is_file():
|
|
608
|
+
out["reason"] = f"no transcript at {trial.transcript.name}"
|
|
609
|
+
return 1
|
|
610
|
+
text, last = capture.extract(trial.transcript, trial.since, opts.forward)
|
|
611
|
+
out["lines"] = [trial.since + 1, last]
|
|
612
|
+
out["extract"] = _extract_info(text)
|
|
613
|
+
if out["extract"]["lines"]["OWNER"] < MIN_OWNER_LINES:
|
|
614
|
+
out["reason"] = "too short"
|
|
615
|
+
return 0
|
|
616
|
+
if not opts.claude:
|
|
617
|
+
out["reason"] = NO_CLAUDE
|
|
618
|
+
return 1
|
|
619
|
+
return _with_work_root(trial, opts.claude, text)
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
def run_window(*args: Any, **kwargs: Any) -> tuple[dict, int]:
|
|
623
|
+
"""One window of one transcript: the result dict (also written to its `out_path`) and the exit code.
|
|
624
|
+
The arguments are the fields of `Window`, in order or by name."""
|
|
625
|
+
return run_window_of(Window(*args, **kwargs))
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def run_window_of(opts: Window) -> tuple[dict, int]:
|
|
629
|
+
"""`run_window` for a ready `Window`."""
|
|
630
|
+
transcript = Path(opts.transcript).expanduser()
|
|
631
|
+
given = Path(opts.project or ".").expanduser().resolve()
|
|
632
|
+
if opts.project is not None and not given.is_dir():
|
|
633
|
+
out: dict = {"reason": f"--project is not a folder: {given.name}"}
|
|
634
|
+
print(f"mem-capture: {out['reason']}", file=sys.stderr)
|
|
635
|
+
return out, 2
|
|
636
|
+
# an explicit --project wins over MEM_PROJECT in the caller's environment
|
|
637
|
+
env = (
|
|
638
|
+
{k: v for k, v in os.environ.items() if k != "MEM_PROJECT"}
|
|
639
|
+
if opts.project is not None
|
|
640
|
+
else os.environ
|
|
641
|
+
)
|
|
642
|
+
project = records.project_root(given, env) or given
|
|
643
|
+
since = max(opts.since_line, 0)
|
|
644
|
+
out = _blank_result(transcript.name, since, opts.model, project)
|
|
645
|
+
out_path = Path(opts.out_path).expanduser()
|
|
646
|
+
out["reason"] = _out_refusal(out_path, opts.allow_out_in_repo)
|
|
647
|
+
if out["reason"]:
|
|
648
|
+
print(f"mem-capture: {out['reason']}", file=sys.stderr)
|
|
649
|
+
return out, 1
|
|
650
|
+
code = _read_window(Trial(opts, transcript, project, since, out))
|
|
651
|
+
return _finish(out, out_path, code, opts.quiet)
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
def cmd_run(args: argparse.Namespace) -> int:
|
|
655
|
+
return run_window_of(
|
|
656
|
+
Window(
|
|
657
|
+
Path(args.transcript),
|
|
658
|
+
Path(args.out),
|
|
659
|
+
args.project,
|
|
660
|
+
args.since_line,
|
|
661
|
+
args.model or DEFAULT_MODEL,
|
|
662
|
+
args.budget,
|
|
663
|
+
args.claude,
|
|
664
|
+
args.forward,
|
|
665
|
+
args.write,
|
|
666
|
+
args.no_rules,
|
|
667
|
+
args.keep_work,
|
|
668
|
+
)
|
|
669
|
+
)[1]
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
data_dir = jobs.state_dir # the data folder, resolved as `mem-auto` does
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
def seconds_env(name: str, default: float) -> float:
|
|
676
|
+
try:
|
|
677
|
+
value = float(os.environ[name])
|
|
678
|
+
except (KeyError, ValueError):
|
|
679
|
+
return default
|
|
680
|
+
return value if math.isfinite(value) and value >= 0 else default
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def save_status(cdir: Path, **changes) -> dict:
|
|
684
|
+
jobs.private_dir(cdir)
|
|
685
|
+
data = {**jobs.read_json(cdir / jobs.STATUS_NAME), **changes}
|
|
686
|
+
for key in [k for k, v in data.items() if k == "failure" and v is None]:
|
|
687
|
+
del data[key]
|
|
688
|
+
jobs.write_json(cdir / jobs.STATUS_NAME, data)
|
|
689
|
+
return data
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
append_log = jobs.append_log
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
def hook_input() -> tuple[Path, Path] | None:
|
|
696
|
+
"""(transcript, cwd) from the hook JSON on standard input, or None when either is missing or unusable."""
|
|
697
|
+
try:
|
|
698
|
+
data = json.load(sys.stdin)
|
|
699
|
+
except Exception: # ruff: ignore[blind-except]
|
|
700
|
+
return None
|
|
701
|
+
if not isinstance(data, dict):
|
|
702
|
+
return None
|
|
703
|
+
path, cwd = data.get("transcript_path"), data.get("cwd")
|
|
704
|
+
if not isinstance(path, str) or not path or not Path(path).expanduser().is_file():
|
|
705
|
+
return None
|
|
706
|
+
if not isinstance(cwd, str) or not cwd or not Path(cwd).expanduser().is_dir():
|
|
707
|
+
return None
|
|
708
|
+
return Path(path).expanduser(), Path(cwd).expanduser()
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
def without_paths(reason: str) -> str:
|
|
712
|
+
"""`reason` with every token that holds a `/` replaced, so a log line carries no path."""
|
|
713
|
+
return " ".join("(path)" if "/" in token else token for token in reason.split())
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
NO_CLAUDE = "no claude binary (--claude, CLAUDE_CODE_EXECPATH or PATH)"
|
|
717
|
+
|
|
718
|
+
|
|
719
|
+
def has_memory_folder(cwd: Path) -> bool:
|
|
720
|
+
"""Standard library only, for when the engine cannot be imported: a `.memory` folder in `cwd` or a parent."""
|
|
721
|
+
name = ".memory" # records.PROJECT_DIR
|
|
722
|
+
return any((folder / name).is_dir() for folder in (cwd, *cwd.parents))
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
def window_failure(res: dict, code: int) -> str | None:
|
|
726
|
+
"""Why a window counts as failed, else None: a failed run, or candidates that `mem` could not record at all."""
|
|
727
|
+
if code != 0:
|
|
728
|
+
return str(res.get("reason") or f"exit code {code}")
|
|
729
|
+
rows = res.get("written") or []
|
|
730
|
+
reasons = [str(w.get("reason") or "") for w in rows]
|
|
731
|
+
if (
|
|
732
|
+
res["candidates"]
|
|
733
|
+
and rows
|
|
734
|
+
and all(r.startswith(("mem could not run", "mem failed")) for r in reasons)
|
|
735
|
+
):
|
|
736
|
+
return reasons[0]
|
|
737
|
+
return None
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
def auto(trigger: str, claude: str | None) -> None:
|
|
741
|
+
"""What a hook starts: read the hook JSON, then `auto_run`. Never raises and never prints."""
|
|
742
|
+
if os.environ.get(cs.OPTION) != "true":
|
|
743
|
+
return
|
|
744
|
+
given = hook_input()
|
|
745
|
+
if given is not None:
|
|
746
|
+
auto_run(trigger, given[0], given[1], claude)
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
def start_corroboration(claude: str | None) -> None:
|
|
750
|
+
"""Start `mem-corroborate auto` detached; a failure to start it is swallowed."""
|
|
751
|
+
with contextlib.suppress(Exception):
|
|
752
|
+
cmd = [*CORROBORATE, "auto", *(["--claude", claude] if claude else [])]
|
|
753
|
+
subprocess.Popen(
|
|
754
|
+
cmd,
|
|
755
|
+
stdin=subprocess.DEVNULL,
|
|
756
|
+
stdout=subprocess.DEVNULL,
|
|
757
|
+
stderr=subprocess.DEVNULL,
|
|
758
|
+
start_new_session=True,
|
|
759
|
+
env=resources.child_env(),
|
|
760
|
+
)
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
def session_budget() -> float:
|
|
764
|
+
"""The budget of one window from the plugin option, else DEFAULT_BUDGET."""
|
|
765
|
+
try:
|
|
766
|
+
budget = float(os.environ[cs.BUDGET_OPTION])
|
|
767
|
+
except (KeyError, ValueError):
|
|
768
|
+
return DEFAULT_BUDGET
|
|
769
|
+
return budget if math.isfinite(budget) and budget > 0 else DEFAULT_BUDGET
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
@dataclass
|
|
773
|
+
class Progress:
|
|
774
|
+
"""Where the windows of one `auto_run` stand: the saved offset and attempts, the memories made, and the failure."""
|
|
775
|
+
|
|
776
|
+
offset: int = 0
|
|
777
|
+
attempts: int = 0
|
|
778
|
+
new: int = 0
|
|
779
|
+
modeled: int = 0
|
|
780
|
+
failed: str | None = None
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
def append_run_log(run: Path, text: str) -> None:
|
|
784
|
+
fd = os.open(run / "log.txt", os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
|
|
785
|
+
with os.fdopen(fd, "a", encoding="utf-8") as f:
|
|
786
|
+
f.write(f"{time.strftime('%H:%M:%S')} {text}\n")
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
class AutoRun:
|
|
790
|
+
"""The state of one `auto_run`: the log line it fills and the lock it holds."""
|
|
791
|
+
|
|
792
|
+
def __init__(self, trigger: str, transcript: Path, cwd: Path, claude: str | None) -> None:
|
|
793
|
+
self.transcript, self.cwd, self.claude = transcript, cwd, claude
|
|
794
|
+
self.data = data_dir()
|
|
795
|
+
self.cdir = cs.capture_dir(self.data)
|
|
796
|
+
self.session = transcript.stem
|
|
797
|
+
self.start = time.time()
|
|
798
|
+
self.line: dict = {
|
|
799
|
+
"t": datetime.datetime.now(datetime.UTC).isoformat(timespec="seconds"),
|
|
800
|
+
"trigger": trigger,
|
|
801
|
+
"session": self.session,
|
|
802
|
+
"windows": 0,
|
|
803
|
+
"modeled": False,
|
|
804
|
+
"kept": 0,
|
|
805
|
+
"written": {"remembered": 0, "sighting": 0, "skipped": 0},
|
|
806
|
+
"cost": None,
|
|
807
|
+
"offset": 0,
|
|
808
|
+
"more": False,
|
|
809
|
+
"skipped": None,
|
|
810
|
+
"failed": None,
|
|
811
|
+
"given_up": 0,
|
|
812
|
+
"ms": 0,
|
|
813
|
+
}
|
|
814
|
+
self.result: dict | None = self.line
|
|
815
|
+
self.logged = False
|
|
816
|
+
self.usable = False
|
|
817
|
+
self.lock: int | None = None
|
|
818
|
+
self.progress = Progress()
|
|
819
|
+
|
|
820
|
+
def finish_log(self) -> None:
|
|
821
|
+
self.line["ms"] = int((time.time() - self.start) * 1000)
|
|
822
|
+
append_log(self.cdir, self.line)
|
|
823
|
+
self.logged = True
|
|
824
|
+
|
|
825
|
+
def take_lock(self, lock_wait: float) -> bool:
|
|
826
|
+
"""Wait for the capture lock, polling, up to `lock_wait` seconds."""
|
|
827
|
+
if self.line["trigger"] == "pre-compact":
|
|
828
|
+
time.sleep(seconds_env("MEM_CAPTURE_DELAY", cs.PRE_COMPACT_DELAY_SECONDS))
|
|
829
|
+
deadline = time.time() + seconds_env("MEM_CAPTURE_LOCK_WAIT", lock_wait)
|
|
830
|
+
# a floor, so a zero poll cannot spin the loop until the deadline
|
|
831
|
+
poll = max(seconds_env("MEM_CAPTURE_LOCK_POLL", LOCK_POLL_SECONDS), MIN_LOCK_POLL_SECONDS)
|
|
832
|
+
self.lock = jobs.take_run_lock(self.cdir)
|
|
833
|
+
while self.lock is None and time.time() < deadline:
|
|
834
|
+
time.sleep(min(poll, max(deadline - time.time(), 0.0)))
|
|
835
|
+
self.lock = jobs.take_run_lock(self.cdir)
|
|
836
|
+
return self.lock is not None
|
|
837
|
+
|
|
838
|
+
def skip(self, why: str) -> bool:
|
|
839
|
+
self.line["skipped"] = why
|
|
840
|
+
self.finish_log()
|
|
841
|
+
return False
|
|
842
|
+
|
|
843
|
+
def tally(self, res: dict) -> None:
|
|
844
|
+
"""Add one window's result to the log line and the count of new memories."""
|
|
845
|
+
line = self.line
|
|
846
|
+
line["windows"] += 1
|
|
847
|
+
line["modeled"] = line["modeled"] or bool(res.get("modeled"))
|
|
848
|
+
if res.get("cost") is not None:
|
|
849
|
+
line["cost"] = (line["cost"] or 0.0) + res["cost"]
|
|
850
|
+
line["kept"] += len(res["candidates"])
|
|
851
|
+
for row in res.get("written") or []:
|
|
852
|
+
line["written"][row["outcome"]] += 1
|
|
853
|
+
self.progress.new += sum(w["outcome"] == "remembered" for w in res.get("written") or [])
|
|
854
|
+
|
|
855
|
+
def window_failed(self, res: dict, reason: str) -> None:
|
|
856
|
+
"""A window failed: retry from the same offset, or give the window up after MAX_ATTEMPTS."""
|
|
857
|
+
progress = self.progress
|
|
858
|
+
progress.failed, self.line["more"] = reason, True
|
|
859
|
+
progress.attempts += 1
|
|
860
|
+
if progress.attempts < cs.MAX_ATTEMPTS:
|
|
861
|
+
cs.save_session(self.data, self.session, progress.offset, progress.attempts)
|
|
862
|
+
return
|
|
863
|
+
progress.offset, progress.attempts = res["lines"][1], 0
|
|
864
|
+
cs.save_session(self.data, self.session, progress.offset, 0)
|
|
865
|
+
self.line["given_up"] += 1
|
|
866
|
+
|
|
867
|
+
def step(self, project: Path, run: Path, number: int, budget: float) -> bool:
|
|
868
|
+
"""One window; whether another follows."""
|
|
869
|
+
progress = self.progress
|
|
870
|
+
opts = Window(
|
|
871
|
+
self.transcript,
|
|
872
|
+
run / f"window-{number}.json",
|
|
873
|
+
project,
|
|
874
|
+
progress.offset,
|
|
875
|
+
"haiku",
|
|
876
|
+
budget,
|
|
877
|
+
self.claude,
|
|
878
|
+
forward=True,
|
|
879
|
+
write=True,
|
|
880
|
+
allow_out_in_repo=True,
|
|
881
|
+
quiet=True,
|
|
882
|
+
)
|
|
883
|
+
res, code = run_window_of(opts)
|
|
884
|
+
self.tally(res)
|
|
885
|
+
more = bool(res["extract"]["more"])
|
|
886
|
+
if res["reason"] == NO_CLAUDE: # nothing can run: a skip, not a failure, and no retry
|
|
887
|
+
self.line["skipped"], self.line["more"] = (
|
|
888
|
+
NO_CLAUDE,
|
|
889
|
+
True,
|
|
890
|
+
) # `more`: a sweep keeps the file open
|
|
891
|
+
append_run_log(run, f"window {number}: skipped: {NO_CLAUDE}")
|
|
892
|
+
return False
|
|
893
|
+
reason = window_failure(res, code)
|
|
894
|
+
append_run_log(
|
|
895
|
+
run,
|
|
896
|
+
f"window {number}: lines {res['lines'][0]}-{res['lines'][1]}, kept {len(res['candidates'])}, "
|
|
897
|
+
f"dropped {len(res['dropped'])}, written {len(res.get('written') or [])}, more {more}"
|
|
898
|
+
+ (f", failed: {reason}" if reason else ""),
|
|
899
|
+
)
|
|
900
|
+
if reason:
|
|
901
|
+
self.window_failed(res, reason)
|
|
902
|
+
return False
|
|
903
|
+
self.line["more"] = more
|
|
904
|
+
short = res["reason"] == "too short"
|
|
905
|
+
if short and not more:
|
|
906
|
+
return False
|
|
907
|
+
progress.modeled += not short
|
|
908
|
+
progress.offset, progress.attempts = res["lines"][1], 0
|
|
909
|
+
cs.save_session(self.data, self.session, progress.offset, 0)
|
|
910
|
+
return more
|
|
911
|
+
|
|
912
|
+
def read_windows(self, project: Path, run: Path) -> None:
|
|
913
|
+
"""Read the session from its saved offset, in up to MAX_WINDOWS windows."""
|
|
914
|
+
budget = session_budget()
|
|
915
|
+
saved = cs.read_session(self.data, self.session)
|
|
916
|
+
progress = self.progress
|
|
917
|
+
progress.offset, progress.attempts = saved["offset"], saved["attempts"]
|
|
918
|
+
if count_lines(self.transcript) < progress.offset:
|
|
919
|
+
progress.offset, progress.attempts = 0, 0
|
|
920
|
+
for number in range(1, cs.MAX_WINDOWS + 1):
|
|
921
|
+
if progress.new >= cs.MAX_NEW_PER_TRIGGER or not self.step(
|
|
922
|
+
project, run, number, budget
|
|
923
|
+
):
|
|
924
|
+
break
|
|
925
|
+
|
|
926
|
+
def end_status(self, run: Path) -> dict:
|
|
927
|
+
progress = self.progress
|
|
928
|
+
done = time.time()
|
|
929
|
+
end: dict = {
|
|
930
|
+
"state": "failed" if progress.failed else "ok",
|
|
931
|
+
"finished": done,
|
|
932
|
+
"cost": self.line["cost"],
|
|
933
|
+
}
|
|
934
|
+
if progress.failed:
|
|
935
|
+
end["failure"] = {"at": done, "reason": progress.failed, "log": str(run)}
|
|
936
|
+
elif progress.modeled:
|
|
937
|
+
end["failure"] = None
|
|
938
|
+
return end
|
|
939
|
+
|
|
940
|
+
def capture(self, project: Path) -> bool:
|
|
941
|
+
"""The windows, then the end status and the log line; whether the corroboration pass should start."""
|
|
942
|
+
run = self.cdir / "runs" / f"{time.strftime('%Y%m%d-%H%M%S')}-{os.getpid()}"
|
|
943
|
+
jobs.private_dir(run)
|
|
944
|
+
save_status(self.cdir, state="running", started=time.time(), log=str(run))
|
|
945
|
+
self.read_windows(project, run)
|
|
946
|
+
progress, written = self.progress, self.line["written"]
|
|
947
|
+
failed = progress.failed
|
|
948
|
+
self.line["offset"], self.line["failed"] = (
|
|
949
|
+
progress.offset,
|
|
950
|
+
without_paths(failed) if failed else None,
|
|
951
|
+
)
|
|
952
|
+
save_status(self.cdir, **self.end_status(run))
|
|
953
|
+
self.finish_log()
|
|
954
|
+
cs.prune_runs(self.cdir / "runs", cs.KEEP_RUNS, cs.KEEP_RUN_DAYS, time.time())
|
|
955
|
+
return not failed and bool(written["remembered"] or written["sighting"])
|
|
956
|
+
|
|
957
|
+
def attempt(self, lock_wait: float) -> bool:
|
|
958
|
+
"""Everything up to the end of the run; whether the corroboration pass should start."""
|
|
959
|
+
project = records.project_root(self.cwd.resolve(), os.environ)
|
|
960
|
+
self.usable = True
|
|
961
|
+
if project is None or not records.project_dir(project).is_dir():
|
|
962
|
+
return self.skip("the project has no memory folder")
|
|
963
|
+
if not self.take_lock(lock_wait):
|
|
964
|
+
return self.skip("another capture is running")
|
|
965
|
+
if cs.is_excluded(self.data, self.transcript):
|
|
966
|
+
return self.skip("transcript excluded")
|
|
967
|
+
return self.capture(project)
|
|
968
|
+
|
|
969
|
+
def report_crash(self, exc: Exception) -> None:
|
|
970
|
+
with contextlib.suppress(Exception):
|
|
971
|
+
reason = self.line["failed"] = type(exc).__name__
|
|
972
|
+
log = str(jobs.read_json(self.cdir / jobs.STATUS_NAME).get("log") or "")
|
|
973
|
+
failure = {"at": time.time(), "reason": reason, "log": log}
|
|
974
|
+
save_status(self.cdir, state="failed", finished=time.time(), failure=failure)
|
|
975
|
+
if not self.logged and (self.usable or self.cdir.exists()):
|
|
976
|
+
with contextlib.suppress(Exception):
|
|
977
|
+
self.finish_log()
|
|
978
|
+
|
|
979
|
+
|
|
980
|
+
def auto_run(
|
|
981
|
+
trigger: str,
|
|
982
|
+
transcript: Path,
|
|
983
|
+
cwd: Path,
|
|
984
|
+
claude: str | None,
|
|
985
|
+
lock_wait: float = cs.LOCK_WAIT_SECONDS,
|
|
986
|
+
) -> dict | None:
|
|
987
|
+
"""The whole of `auto` for one transcript; see the module docstring. Never raises and never prints.
|
|
988
|
+
`lock_wait` is the seconds to wait for the capture lock (`MEM_CAPTURE_LOCK_WAIT` overrides it);
|
|
989
|
+
`MEM_CAPTURE_LOCK_POLL` overrides the seconds between attempts.
|
|
990
|
+
After a run that wrote a record and did not fail, and once the capture lock is released, it starts the
|
|
991
|
+
corroboration pass. Returns the run's log line. In it `windows` counts
|
|
992
|
+
the windows read (0 when nothing was read: lock held, no memory folder) and `modeled` is true when a model
|
|
993
|
+
session was started in any of them, even one that failed; `cost` is not that signal (a killed session has none)."""
|
|
994
|
+
job = AutoRun(trigger, transcript, cwd, claude)
|
|
995
|
+
corroborate = False
|
|
996
|
+
try:
|
|
997
|
+
corroborate = job.attempt(lock_wait)
|
|
998
|
+
except Exception as exc: # ruff: ignore[blind-except] - a background process reports and ends
|
|
999
|
+
job.report_crash(exc)
|
|
1000
|
+
finally:
|
|
1001
|
+
if job.lock is not None:
|
|
1002
|
+
os.close(job.lock)
|
|
1003
|
+
if corroborate:
|
|
1004
|
+
start_corroboration(claude)
|
|
1005
|
+
return job.result
|
|
1006
|
+
|
|
1007
|
+
|
|
1008
|
+
def count_lines(path: Path) -> int:
|
|
1009
|
+
with path.open("rb") as f:
|
|
1010
|
+
return sum(1 for _ in f)
|
|
1011
|
+
|
|
1012
|
+
|
|
1013
|
+
def _cwd_value(raw: bytes) -> str | None:
|
|
1014
|
+
"""The `cwd` string of one transcript line, if it has one."""
|
|
1015
|
+
if b'"cwd"' not in raw:
|
|
1016
|
+
return None
|
|
1017
|
+
try:
|
|
1018
|
+
item = json.loads(raw)
|
|
1019
|
+
except ValueError:
|
|
1020
|
+
return None
|
|
1021
|
+
if not isinstance(item, dict):
|
|
1022
|
+
return None
|
|
1023
|
+
payload = item.get("payload") # a Codex rollout keeps it in `session_meta` and `turn_context`
|
|
1024
|
+
nested = payload.get("cwd") if isinstance(payload, dict) else None
|
|
1025
|
+
value = item.get("cwd") or nested
|
|
1026
|
+
return value if isinstance(value, str) and value else None
|
|
1027
|
+
|
|
1028
|
+
|
|
1029
|
+
def first_cwd(path: Path) -> Path | None:
|
|
1030
|
+
"""The first `cwd` value that is an existing directory among the first CWD_SCAN_LINES lines; read line by line."""
|
|
1031
|
+
with path.open("rb") as f:
|
|
1032
|
+
for number, raw in enumerate(f):
|
|
1033
|
+
if number >= CWD_SCAN_LINES:
|
|
1034
|
+
break
|
|
1035
|
+
value = _cwd_value(raw)
|
|
1036
|
+
if value and Path(value).expanduser().is_dir():
|
|
1037
|
+
return Path(value).expanduser()
|
|
1038
|
+
return None
|
|
1039
|
+
|
|
1040
|
+
|
|
1041
|
+
def _first_line(path: Path) -> str:
|
|
1042
|
+
"""The first line, "" when unreadable or longer than FIRST_LINE_LIMIT bytes."""
|
|
1043
|
+
try:
|
|
1044
|
+
with path.open("rb") as f:
|
|
1045
|
+
raw = f.readline(FIRST_LINE_LIMIT + 1)
|
|
1046
|
+
except OSError:
|
|
1047
|
+
return ""
|
|
1048
|
+
return "" if len(raw) > FIRST_LINE_LIMIT else raw.decode("utf-8", "replace")
|
|
1049
|
+
|
|
1050
|
+
|
|
1051
|
+
def _is_codex_rollout(path: Path) -> bool:
|
|
1052
|
+
"""A Codex rollout sits in a day folder and starts with `session_meta`; a Claude path is decided with no read."""
|
|
1053
|
+
root = _codex_root(path)
|
|
1054
|
+
if root is None:
|
|
1055
|
+
return False
|
|
1056
|
+
line = _first_line(path)
|
|
1057
|
+
# a start rollout whose first line is not written yet is still Codex's
|
|
1058
|
+
return codex_rollout.is_rollout(line) or not line.strip()
|
|
1059
|
+
|
|
1060
|
+
|
|
1061
|
+
def _codex_root(transcript: Path) -> Path | None:
|
|
1062
|
+
"""The `sessions` folder above a `YYYY/MM/DD` day folder of a Codex rollout, else None."""
|
|
1063
|
+
parents = transcript.parents
|
|
1064
|
+
if len(parents) > DAY_DEPTH and all(p.name.isdigit() for p in parents[:DAY_DEPTH]):
|
|
1065
|
+
return parents[DAY_DEPTH]
|
|
1066
|
+
return None
|
|
1067
|
+
|
|
1068
|
+
|
|
1069
|
+
def _sweep_folders(transcript: Path, now: float, codex: bool | None = None) -> list[Path]:
|
|
1070
|
+
"""Folders that hold the candidates: for a Codex rollout, today's day folder and the SWEEP_MAX_AGE_DAYS
|
|
1071
|
+
before it; else its own folder."""
|
|
1072
|
+
if codex is None:
|
|
1073
|
+
codex = _is_codex_rollout(transcript)
|
|
1074
|
+
root = _codex_root(transcript) if codex else None
|
|
1075
|
+
if root is None:
|
|
1076
|
+
return [transcript.parent]
|
|
1077
|
+
days = (
|
|
1078
|
+
datetime.date.fromtimestamp(now) - datetime.timedelta(days=n)
|
|
1079
|
+
for n in range(cs.SWEEP_MAX_AGE_DAYS + 1)
|
|
1080
|
+
)
|
|
1081
|
+
return [root / f"{d:%Y}" / f"{d:%m}" / f"{d:%d}" for d in days]
|
|
1082
|
+
|
|
1083
|
+
|
|
1084
|
+
def _idle_sessions(
|
|
1085
|
+
transcript: Path, now: float, codex: bool | None = None
|
|
1086
|
+
) -> list[tuple[float, int, Path]]:
|
|
1087
|
+
"""(mtime, size, path) of the other transcripts of the folder(s) that are idle and not too old."""
|
|
1088
|
+
found = []
|
|
1089
|
+
for folder in _sweep_folders(transcript, now, codex):
|
|
1090
|
+
if not folder.is_dir():
|
|
1091
|
+
continue
|
|
1092
|
+
for item in folder.iterdir():
|
|
1093
|
+
if item.suffix != ".jsonl" or not item.is_file() or item.stem == transcript.stem:
|
|
1094
|
+
continue
|
|
1095
|
+
info = item.stat()
|
|
1096
|
+
if cs.SWEEP_IDLE_SECONDS <= now - info.st_mtime <= cs.SWEEP_MAX_AGE_DAYS * 86400:
|
|
1097
|
+
found.append((info.st_mtime, info.st_size, item))
|
|
1098
|
+
return found
|
|
1099
|
+
|
|
1100
|
+
|
|
1101
|
+
def _project_of(cwd: Path | None) -> Path | None:
|
|
1102
|
+
return (
|
|
1103
|
+
records.project_root(cwd.resolve(), os.environ)
|
|
1104
|
+
if cwd is not None and cwd.is_dir()
|
|
1105
|
+
else None
|
|
1106
|
+
)
|
|
1107
|
+
|
|
1108
|
+
|
|
1109
|
+
def _rollout_meta(item: Path) -> dict | None:
|
|
1110
|
+
"""The `session_meta` payload of a Codex rollout, None when the file is not one."""
|
|
1111
|
+
line = _first_line(item)
|
|
1112
|
+
if not codex_rollout.is_rollout(line):
|
|
1113
|
+
return None
|
|
1114
|
+
meta = json.loads(line).get("payload")
|
|
1115
|
+
return meta if isinstance(meta, dict) else None
|
|
1116
|
+
|
|
1117
|
+
|
|
1118
|
+
def _in_project(meta: dict, project: Path | None) -> bool:
|
|
1119
|
+
cwd = meta.get("cwd")
|
|
1120
|
+
return (
|
|
1121
|
+
project is not None
|
|
1122
|
+
and isinstance(cwd, str)
|
|
1123
|
+
and bool(cwd)
|
|
1124
|
+
and _project_of(Path(cwd).expanduser()) == project
|
|
1125
|
+
)
|
|
1126
|
+
|
|
1127
|
+
|
|
1128
|
+
def _sweep_cwd(store: Path, item: Path) -> Path | None:
|
|
1129
|
+
"""The folder of a session that has lines left to read and a memory folder, else None."""
|
|
1130
|
+
if count_lines(item) <= cs.read_session(store, item.stem)["offset"]:
|
|
1131
|
+
return None
|
|
1132
|
+
cwd = first_cwd(item)
|
|
1133
|
+
if cwd is not None:
|
|
1134
|
+
project = records.project_root(cwd.resolve(), os.environ)
|
|
1135
|
+
if project is None or not records.project_dir(project).is_dir():
|
|
1136
|
+
return None
|
|
1137
|
+
return cwd
|
|
1138
|
+
|
|
1139
|
+
|
|
1140
|
+
def _note_sweep_run(store: Path, now: float, item: Path, size: int, run: dict | None) -> bool:
|
|
1141
|
+
"""Record what a sweep run settled; whether it started a model session."""
|
|
1142
|
+
if run is None or not run["windows"]:
|
|
1143
|
+
return False # nothing was read (lock held, no memory folder): a later start may
|
|
1144
|
+
if run["modeled"]:
|
|
1145
|
+
cs.note_sweep(store, now)
|
|
1146
|
+
if not run["failed"] and not run["more"]:
|
|
1147
|
+
# read to the end; otherwise a later start continues or retries
|
|
1148
|
+
cs.save_swept_size(store, item.stem, size)
|
|
1149
|
+
return bool(run["modeled"])
|
|
1150
|
+
|
|
1151
|
+
|
|
1152
|
+
def _swept_transcript(data: object) -> Path | None:
|
|
1153
|
+
"""The starting session's transcript from the hook JSON, when its folder exists."""
|
|
1154
|
+
path = data.get("transcript_path") if isinstance(data, dict) else None
|
|
1155
|
+
if not isinstance(path, str) or not path:
|
|
1156
|
+
return None
|
|
1157
|
+
transcript = Path(path).expanduser()
|
|
1158
|
+
return transcript if transcript.parent.is_dir() else None
|
|
1159
|
+
|
|
1160
|
+
|
|
1161
|
+
def _sweep_limit_reached(store: Path, now: float, used: int, examined: int) -> bool:
|
|
1162
|
+
return (
|
|
1163
|
+
used >= cs.SWEEP_MAX_SESSIONS
|
|
1164
|
+
or examined >= cs.SWEEP_MAX_EXAMINED
|
|
1165
|
+
or cs.sweeps_today(store, now) >= cs.SWEEP_MAX_PER_DAY
|
|
1166
|
+
)
|
|
1167
|
+
|
|
1168
|
+
|
|
1169
|
+
def _to_examine(store: Path, size: int, item: Path, codex: bool, project: Path | None) -> bool:
|
|
1170
|
+
"""False for a file unchanged since its last sweep (one stat) and, on Codex, for another project's or a
|
|
1171
|
+
subagent's rollout (a day folder mixes them): neither counts as an examination. A rollout that is not an
|
|
1172
|
+
owner thread stays so while the file is unchanged, so its size is remembered; another project's rollout
|
|
1173
|
+
is not (the store is shared: that project's own start must still take it)."""
|
|
1174
|
+
if cs.swept_size(store, item.stem) == size:
|
|
1175
|
+
return False
|
|
1176
|
+
if not codex:
|
|
1177
|
+
return True
|
|
1178
|
+
meta = _rollout_meta(item)
|
|
1179
|
+
if (
|
|
1180
|
+
meta is None
|
|
1181
|
+
): # unreadable now (or not a rollout): not remembered, a later start reads it again
|
|
1182
|
+
return False
|
|
1183
|
+
if (
|
|
1184
|
+
meta.get("thread_source", "user") != "user"
|
|
1185
|
+
): # a missing key is an owner thread, as the decoder reads it
|
|
1186
|
+
cs.save_swept_size(store, item.stem, size)
|
|
1187
|
+
return False
|
|
1188
|
+
return _in_project(meta, project)
|
|
1189
|
+
|
|
1190
|
+
|
|
1191
|
+
def _sweep_start(store: Path, transcript: Path, hook: dict, now: float) -> tuple | None:
|
|
1192
|
+
lock = jobs.take_run_lock(cs.capture_dir(store))
|
|
1193
|
+
if lock is None:
|
|
1194
|
+
return None
|
|
1195
|
+
try:
|
|
1196
|
+
if cs.is_excluded(store, transcript):
|
|
1197
|
+
codex = _codex_root(transcript) is not None
|
|
1198
|
+
cwd = hook.get("cwd") if isinstance(hook, dict) else None
|
|
1199
|
+
project = _project_of(Path(cwd)) if codex and isinstance(cwd, str) else None
|
|
1200
|
+
else:
|
|
1201
|
+
codex = _is_codex_rollout(transcript)
|
|
1202
|
+
project = _project_of(first_cwd(transcript)) if codex else None
|
|
1203
|
+
found = _idle_sessions(transcript, now, codex)
|
|
1204
|
+
return codex, project, found
|
|
1205
|
+
finally:
|
|
1206
|
+
os.close(lock)
|
|
1207
|
+
|
|
1208
|
+
|
|
1209
|
+
def _sweep_candidate(
|
|
1210
|
+
store: Path, size: int, item: Path, codex: bool, project: Path | None
|
|
1211
|
+
) -> tuple[bool, Path | None] | None:
|
|
1212
|
+
lock = jobs.take_run_lock(cs.capture_dir(store))
|
|
1213
|
+
if lock is None:
|
|
1214
|
+
return None
|
|
1215
|
+
try:
|
|
1216
|
+
eligible = not cs.is_excluded(store, item) and _to_examine(
|
|
1217
|
+
store, size, item, codex, project
|
|
1218
|
+
)
|
|
1219
|
+
cwd = _sweep_cwd(store, item) if eligible else None
|
|
1220
|
+
if eligible and cwd is None:
|
|
1221
|
+
cs.save_swept_size(store, item.stem, size)
|
|
1222
|
+
return eligible, cwd
|
|
1223
|
+
finally:
|
|
1224
|
+
os.close(lock)
|
|
1225
|
+
|
|
1226
|
+
|
|
1227
|
+
def _sweep_found(store: Path, now: float, setup: tuple, claude: str | None) -> None:
|
|
1228
|
+
codex, project, found = setup
|
|
1229
|
+
examined = used = 0 # files opened; runs that started a model session
|
|
1230
|
+
for _mtime, size, item in sorted(found, key=lambda row: row[0], reverse=True):
|
|
1231
|
+
if _sweep_limit_reached(store, now, used, examined):
|
|
1232
|
+
break
|
|
1233
|
+
candidate = _sweep_candidate(store, size, item, codex, project)
|
|
1234
|
+
if candidate is None:
|
|
1235
|
+
return
|
|
1236
|
+
eligible, cwd = candidate
|
|
1237
|
+
if not eligible:
|
|
1238
|
+
continue
|
|
1239
|
+
examined += 1
|
|
1240
|
+
if cwd is not None:
|
|
1241
|
+
run = auto_run("sweep", item, cwd, claude, lock_wait=cs.SWEEP_LOCK_WAIT_SECONDS)
|
|
1242
|
+
used += _note_sweep_run(store, now, item, size, run)
|
|
1243
|
+
|
|
1244
|
+
|
|
1245
|
+
def _sweep(claude: str | None) -> None:
|
|
1246
|
+
if os.environ.get(cs.OPTION) != "true":
|
|
1247
|
+
return
|
|
1248
|
+
hook = json.load(sys.stdin)
|
|
1249
|
+
transcript = _swept_transcript(hook)
|
|
1250
|
+
if transcript is None:
|
|
1251
|
+
return
|
|
1252
|
+
store, now = data_dir(), time.time()
|
|
1253
|
+
setup = _sweep_start(store, transcript, hook, now)
|
|
1254
|
+
if setup is not None:
|
|
1255
|
+
_sweep_found(store, now, setup, claude)
|
|
1256
|
+
|
|
1257
|
+
|
|
1258
|
+
def sweep(claude: str | None) -> None:
|
|
1259
|
+
"""Capture sessions of the starting session's folder that were left open and never ended. Never raises, never prints."""
|
|
1260
|
+
with contextlib.suppress(Exception): # a background process ends quietly
|
|
1261
|
+
try:
|
|
1262
|
+
_sweep(claude)
|
|
1263
|
+
except cs.ExclusionRegistryError as exc:
|
|
1264
|
+
now = time.time()
|
|
1265
|
+
cdir = cs.capture_dir(data_dir())
|
|
1266
|
+
save_status(cdir, state="failed", finished=now, failure={"at": now, "reason": str(exc)})
|
|
1267
|
+
|
|
1268
|
+
|
|
1269
|
+
def cmd_sweep(args: argparse.Namespace) -> int:
|
|
1270
|
+
sweep(args.claude)
|
|
1271
|
+
return 0
|
|
1272
|
+
|
|
1273
|
+
|
|
1274
|
+
def cmd_ack() -> int:
|
|
1275
|
+
cdir = cs.capture_dir(data_dir())
|
|
1276
|
+
current = jobs.read_json(cdir / jobs.STATUS_NAME)
|
|
1277
|
+
if current:
|
|
1278
|
+
changes: dict = {"failure": None}
|
|
1279
|
+
started = current.get("started")
|
|
1280
|
+
if (
|
|
1281
|
+
current.get("state") == "running"
|
|
1282
|
+
and isinstance(started, (int, float))
|
|
1283
|
+
and time.time() - started > jobs.STALE_RUNNING_SECONDS
|
|
1284
|
+
):
|
|
1285
|
+
changes["state"] = (
|
|
1286
|
+
"failed" # a run that was killed: without this its "did not finish" line would stay
|
|
1287
|
+
)
|
|
1288
|
+
save_status(cdir, **changes)
|
|
1289
|
+
print("acknowledged: the failure line is cleared")
|
|
1290
|
+
return 0
|
|
1291
|
+
|
|
1292
|
+
|
|
1293
|
+
def cmd_auto(args: argparse.Namespace) -> int:
|
|
1294
|
+
auto(args.trigger, args.claude)
|
|
1295
|
+
return 0
|
|
1296
|
+
|
|
1297
|
+
|
|
1298
|
+
def cmd_exclude(args: argparse.Namespace) -> int:
|
|
1299
|
+
"""Wait for in-flight capture and record an exclusion under the same lock."""
|
|
1300
|
+
data = data_dir()
|
|
1301
|
+
job = AutoRun("exclude", Path(args.transcript), Path.cwd(), None)
|
|
1302
|
+
try:
|
|
1303
|
+
if not job.take_lock(cs.LOCK_WAIT_SECONDS):
|
|
1304
|
+
print(
|
|
1305
|
+
"mem-capture: capture lock timed out; exclusion was not recorded", file=sys.stderr
|
|
1306
|
+
)
|
|
1307
|
+
return 1
|
|
1308
|
+
cs.exclude(data, Path(args.transcript))
|
|
1309
|
+
except (OSError, TypeError, ValueError) as exc:
|
|
1310
|
+
print(f"mem-capture: could not record exclusion: {exc}", file=sys.stderr)
|
|
1311
|
+
return 1
|
|
1312
|
+
finally:
|
|
1313
|
+
if job.lock is not None:
|
|
1314
|
+
os.close(job.lock)
|
|
1315
|
+
print("Automatic capture excluded for this transcript.")
|
|
1316
|
+
return 0
|
|
1317
|
+
|
|
1318
|
+
|
|
1319
|
+
def main(argv: list[str] | None = None) -> int:
|
|
1320
|
+
parser = argparse.ArgumentParser(
|
|
1321
|
+
prog="mem-capture", description=(__doc__ or "").splitlines()[0]
|
|
1322
|
+
)
|
|
1323
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
1324
|
+
exclude = commands.add_parser(
|
|
1325
|
+
"exclude",
|
|
1326
|
+
help="permanently exclude a transcript from automatic capture",
|
|
1327
|
+
description="Exclude this transcript from future automatic capture, including earlier unread text. "
|
|
1328
|
+
"Waits for an in-flight capture to finish before returning. Previously recorded memories remain. "
|
|
1329
|
+
"Use the same transcript path as the host hook. Manual runs are unaffected.",
|
|
1330
|
+
)
|
|
1331
|
+
exclude.add_argument("--transcript", required=True, help="the session transcript path")
|
|
1332
|
+
exclude.set_defaults(func=cmd_exclude)
|
|
1333
|
+
run = commands.add_parser("run", help="read one transcript and keep the validated candidates")
|
|
1334
|
+
run.add_argument("--transcript", required=True, help="the session transcript (JSONL)")
|
|
1335
|
+
run.add_argument("--out", required=True, help="the result file (mode 0600)")
|
|
1336
|
+
run.add_argument(
|
|
1337
|
+
"--project",
|
|
1338
|
+
default=None,
|
|
1339
|
+
help="project folder whose memories are the claims already recorded "
|
|
1340
|
+
"(default: the current directory)",
|
|
1341
|
+
)
|
|
1342
|
+
run.add_argument(
|
|
1343
|
+
"--since-line", type=int, default=0, help="read the transcript after this line"
|
|
1344
|
+
)
|
|
1345
|
+
run.add_argument(
|
|
1346
|
+
"--forward",
|
|
1347
|
+
action="store_true",
|
|
1348
|
+
help="read a window from --since-line forward, not the newest lines",
|
|
1349
|
+
)
|
|
1350
|
+
run.add_argument("--model", help=f"model of the session (default {DEFAULT_MODEL})")
|
|
1351
|
+
run.add_argument(
|
|
1352
|
+
"--budget",
|
|
1353
|
+
type=budget_arg,
|
|
1354
|
+
default=DEFAULT_BUDGET,
|
|
1355
|
+
help=f"USD for the session (default {DEFAULT_BUDGET})",
|
|
1356
|
+
)
|
|
1357
|
+
run.add_argument(
|
|
1358
|
+
"--claude", default=os.environ.get("CLAUDE_CODE_EXECPATH") or shutil.which("claude")
|
|
1359
|
+
)
|
|
1360
|
+
runners.add_flag(run)
|
|
1361
|
+
run.add_argument(
|
|
1362
|
+
"--no-rules",
|
|
1363
|
+
action="store_true",
|
|
1364
|
+
help="leave rules.txt empty (the instruction files are not given)",
|
|
1365
|
+
)
|
|
1366
|
+
run.add_argument(
|
|
1367
|
+
"--write",
|
|
1368
|
+
action="store_true",
|
|
1369
|
+
help="record the kept candidates in the project's memory (via bin/mem)",
|
|
1370
|
+
)
|
|
1371
|
+
run.add_argument(
|
|
1372
|
+
"--keep-work", action="store_true", help="keep the work folder (it holds session text)"
|
|
1373
|
+
)
|
|
1374
|
+
run.set_defaults(func=cmd_run)
|
|
1375
|
+
auto_cmd = commands.add_parser(
|
|
1376
|
+
"auto", help="what a hook starts: read a session from its saved offset, in the background"
|
|
1377
|
+
)
|
|
1378
|
+
auto_cmd.add_argument("--trigger", required=True, choices=["pre-compact", "session-end"])
|
|
1379
|
+
auto_cmd.add_argument(
|
|
1380
|
+
"--claude", default=os.environ.get("CLAUDE_CODE_EXECPATH") or shutil.which("claude")
|
|
1381
|
+
)
|
|
1382
|
+
runners.add_flag(auto_cmd)
|
|
1383
|
+
auto_cmd.set_defaults(func=cmd_auto)
|
|
1384
|
+
sweep_cmd = commands.add_parser(
|
|
1385
|
+
"sweep", help="what the session start launches: read sessions of the folder left open"
|
|
1386
|
+
)
|
|
1387
|
+
sweep_cmd.add_argument(
|
|
1388
|
+
"--claude", default=os.environ.get("CLAUDE_CODE_EXECPATH") or shutil.which("claude")
|
|
1389
|
+
)
|
|
1390
|
+
runners.add_flag(sweep_cmd)
|
|
1391
|
+
sweep_cmd.set_defaults(func=cmd_sweep)
|
|
1392
|
+
ack = commands.add_parser(
|
|
1393
|
+
"ack", help="clear the failure line left by a failed automatic capture"
|
|
1394
|
+
)
|
|
1395
|
+
ack.set_defaults(func=lambda _args: cmd_ack())
|
|
1396
|
+
args = parser.parse_args(argv)
|
|
1397
|
+
if (
|
|
1398
|
+
args.command not in {"ack", "exclude"}
|
|
1399
|
+
and (refused := codex_pass.refuse_codex("mem-capture", getattr(args, "runner", None)))
|
|
1400
|
+
is not None
|
|
1401
|
+
):
|
|
1402
|
+
return refused
|
|
1403
|
+
return args.func(args)
|