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,730 @@
|
|
|
1
|
+
"""The hook handlers (A5, ADR 0028): `session-index`, `compact-log` and `signal`, with the logic only they use (the session start text, its due counts and notices, the compact summary check, the signal text)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import datetime
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import shlex
|
|
12
|
+
import sys
|
|
13
|
+
import time
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import TYPE_CHECKING, Any, TypedDict, Unpack
|
|
16
|
+
|
|
17
|
+
from memory_cli.capture import state as capture_state
|
|
18
|
+
from memory_cli.commands import common, curate, install
|
|
19
|
+
from memory_cli.core import auto_state, jobs, resources
|
|
20
|
+
from memory_cli.memories import records, rules
|
|
21
|
+
from memory_cli.session import handoff
|
|
22
|
+
from memory_cli.session import notices as session_notices
|
|
23
|
+
from memory_cli.settle import state as settle_state
|
|
24
|
+
|
|
25
|
+
if TYPE_CHECKING:
|
|
26
|
+
import argparse
|
|
27
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger(__name__)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
_INDEX_HEAD = "memory: the mem command searches notes and memories (skill: memory)."
|
|
33
|
+
_INDEX_RULES = (
|
|
34
|
+
_INDEX_HEAD + "\n"
|
|
35
|
+
'- Before you act on this project, change something or research a topic: mem search "<topic in English>". '
|
|
36
|
+
"It returns decisions, constraints and pitfalls recorded earlier that the files do not show.\n"
|
|
37
|
+
"- To remember: preferences and personal matters -> auto memory; what a later session would need (a decision, "
|
|
38
|
+
"constraint, pitfall or finding) -> mem remember, in English, with --global if it holds in any project and names "
|
|
39
|
+
"no business; the project's current situation -> both."
|
|
40
|
+
)
|
|
41
|
+
# Codex has no auto memory (a Claude Code feature) and no memory:* subagents: its variants of the lines above.
|
|
42
|
+
_INDEX_RULES_CODEX = _INDEX_RULES.replace(
|
|
43
|
+
"preferences and personal matters -> auto memory; what", "what"
|
|
44
|
+
).replace(
|
|
45
|
+
"; the project's current situation -> both.",
|
|
46
|
+
"; the project's current situation -> mem remember too.",
|
|
47
|
+
)
|
|
48
|
+
# Only a project with a live state memory has written state for the status checker to read (ADR 0030).
|
|
49
|
+
_STATUS_LINE = (
|
|
50
|
+
"- Resuming earlier work, or asked where things stand: dispatch memory:memory-status-checker "
|
|
51
|
+
"before reading plans or the backlog yourself."
|
|
52
|
+
)
|
|
53
|
+
_STATUS_LINE_CODEX = (
|
|
54
|
+
"- Resuming earlier work, or asked where things stand: read the project's state memories with "
|
|
55
|
+
"`mem memories --kind state` before reading plans or the backlog yourself."
|
|
56
|
+
)
|
|
57
|
+
_INDEX_LIMIT = 1500
|
|
58
|
+
_CLAIM_LIMIT = 100
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
_SUPERSEDED_LINE = re.compile(r"^superseded_by:", re.MULTILINE)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _host() -> str:
|
|
65
|
+
"""The host that runs the hook: `codex` when the hook sets MEM_HOST=codex, otherwise `claude`."""
|
|
66
|
+
return "codex" if os.environ.get("MEM_HOST") == "codex" else "claude"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _is_superseded_file(path: Path) -> bool:
|
|
70
|
+
"""Whether the frontmatter at the top of the file has `superseded_by`; only the first 16 KB is read."""
|
|
71
|
+
try:
|
|
72
|
+
with path.open(encoding="utf-8", errors="replace") as f:
|
|
73
|
+
head = f.read(16384)
|
|
74
|
+
except OSError:
|
|
75
|
+
return False
|
|
76
|
+
m = re.match(r"---\r?\n(.*?)\r?\n---", head, re.DOTALL)
|
|
77
|
+
return m is not None and _SUPERSEDED_LINE.search(m.group(1)) is not None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _count_notes(store: Path) -> int:
|
|
81
|
+
"""Notes by file name only: the index runs at every session start and must not read them."""
|
|
82
|
+
try:
|
|
83
|
+
files = [
|
|
84
|
+
p
|
|
85
|
+
for kind in ("literature", "knowledge")
|
|
86
|
+
for p in store.glob(f"{kind}/*/*.md")
|
|
87
|
+
if p.name != "README.md"
|
|
88
|
+
]
|
|
89
|
+
files += list(store.glob("research/*/README.md"))
|
|
90
|
+
return sum(1 for f in files if not _is_superseded_file(f))
|
|
91
|
+
except OSError:
|
|
92
|
+
return 0
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class SessionIndexOptions(TypedDict, total=False):
|
|
96
|
+
"""The keyword options of `session_index`; `tracked` defaults to an empty set, the rest to 0 or None."""
|
|
97
|
+
|
|
98
|
+
limit: int
|
|
99
|
+
passes: Mapping[str, datetime.date] | None
|
|
100
|
+
notice: str | None
|
|
101
|
+
stats: dict[str, int] | None
|
|
102
|
+
marks: Mapping[str, frozenset[str]] | None
|
|
103
|
+
tracked: frozenset[str] | None
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@dataclasses.dataclass(frozen=True)
|
|
107
|
+
class _DueScan:
|
|
108
|
+
"""What the "Curation due" count of every folder shares."""
|
|
109
|
+
|
|
110
|
+
today: datetime.date
|
|
111
|
+
passes: Mapping[str, datetime.date] | None
|
|
112
|
+
marks: Mapping[str, frozenset[str]] | None
|
|
113
|
+
tracked: frozenset[str] | None
|
|
114
|
+
budget: records.Budget # one for both folders, the project's first (C101)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _index_existing(store: Path | None, memories: Path | None) -> tuple[Path | None, Path | None]:
|
|
118
|
+
"""The store and the global folder, each None when it is not a folder."""
|
|
119
|
+
try:
|
|
120
|
+
has_store = store is not None and store.is_dir()
|
|
121
|
+
has_memories = memories is not None and memories.is_dir()
|
|
122
|
+
except OSError:
|
|
123
|
+
return None, None
|
|
124
|
+
return (store if has_store else None, memories if has_memories else None)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _index_count_due(
|
|
128
|
+
due: dict[str, int],
|
|
129
|
+
folder: Path,
|
|
130
|
+
loaded: list[records.Memory],
|
|
131
|
+
root: Path | None,
|
|
132
|
+
scan: _DueScan,
|
|
133
|
+
) -> bool:
|
|
134
|
+
"""Add the decision items of one folder to `due`; True when all its pairs were checked."""
|
|
135
|
+
key = str(folder.resolve())
|
|
136
|
+
found = curate._decisions(
|
|
137
|
+
loaded,
|
|
138
|
+
scan.today,
|
|
139
|
+
since=(scan.passes or {}).get(key),
|
|
140
|
+
budget=scan.budget,
|
|
141
|
+
attempts=common._fill_attempts(os.environ),
|
|
142
|
+
root=root,
|
|
143
|
+
tracked=scan.tracked,
|
|
144
|
+
)
|
|
145
|
+
known = (scan.marks or {}).get(key, frozenset())
|
|
146
|
+
for k, label in found.keys().items():
|
|
147
|
+
if k not in known:
|
|
148
|
+
due[label] = due.get(label, 0) + 1
|
|
149
|
+
return found.pairs_checked
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _index_add_due(
|
|
153
|
+
due: dict[str, int],
|
|
154
|
+
folder: Path,
|
|
155
|
+
loaded: list[records.Memory],
|
|
156
|
+
root: Path | None,
|
|
157
|
+
scan: _DueScan,
|
|
158
|
+
) -> bool:
|
|
159
|
+
"""Like `_index_count_due`, but a failure leaves this folder out of the count (False): the rest prints."""
|
|
160
|
+
try:
|
|
161
|
+
return _index_count_due(due, folder, loaded, root, scan)
|
|
162
|
+
except Exception:
|
|
163
|
+
logger.debug("counting a store folder failed", exc_info=True)
|
|
164
|
+
return False
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _index_due_counts(
|
|
168
|
+
project: Path | None,
|
|
169
|
+
loaded_project: list[records.Memory],
|
|
170
|
+
memories: Path | None,
|
|
171
|
+
loaded_global: list[records.Memory],
|
|
172
|
+
scan: _DueScan,
|
|
173
|
+
) -> tuple[dict[str, int], bool]:
|
|
174
|
+
"""The decision items by label, and whether the count is complete; empty without `passes`."""
|
|
175
|
+
due: dict[str, int] = {}
|
|
176
|
+
complete = True
|
|
177
|
+
if scan.passes is None:
|
|
178
|
+
return due, complete
|
|
179
|
+
if project is not None:
|
|
180
|
+
complete = _index_add_due(due, project, loaded_project, project.parent, scan) and complete
|
|
181
|
+
if memories is not None:
|
|
182
|
+
complete = _index_add_due(due, memories, loaded_global, None, scan) and complete
|
|
183
|
+
return due, complete
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _index_folder_lines(
|
|
187
|
+
store: Path | None,
|
|
188
|
+
memories: Path | None,
|
|
189
|
+
loaded_global: list[records.Memory],
|
|
190
|
+
today: datetime.date,
|
|
191
|
+
) -> list[str]:
|
|
192
|
+
lines = []
|
|
193
|
+
if store is not None:
|
|
194
|
+
lines.append(f"Store: {_count_notes(store)} notes.")
|
|
195
|
+
if memories is not None:
|
|
196
|
+
lines.append(f"Global memories: {len(common._readable(loaded_global, today))}.")
|
|
197
|
+
return lines
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _index_due_line(due: dict[str, int], complete: bool) -> list[str]:
|
|
201
|
+
total = sum(due.values())
|
|
202
|
+
if not total:
|
|
203
|
+
return []
|
|
204
|
+
parts = ", ".join(
|
|
205
|
+
f"{due[label]} {label}" for label in curate._DECISION_LABELS.values() if label in due
|
|
206
|
+
)
|
|
207
|
+
action = (
|
|
208
|
+
"run a curation pass with the memory-curation skill"
|
|
209
|
+
if _host() == "codex"
|
|
210
|
+
else "dispatch memory:memory-curator"
|
|
211
|
+
)
|
|
212
|
+
return [
|
|
213
|
+
(
|
|
214
|
+
f"Curation due: {'' if complete else 'at least '}{total} {'item' if total == 1 else 'items'} "
|
|
215
|
+
f"({parts}) (after the current task: {action})."
|
|
216
|
+
)
|
|
217
|
+
]
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _index_triage_line(loaded_global: list[records.Memory], today: datetime.date) -> list[str]:
|
|
221
|
+
waiting = sum(1 for m in loaded_global if m.triage == "pending" and records.is_live(m, today))
|
|
222
|
+
if not waiting:
|
|
223
|
+
return []
|
|
224
|
+
return [
|
|
225
|
+
(
|
|
226
|
+
f"Triage: {waiting} general lesson{' awaits' if waiting == 1 else 's await'} triage "
|
|
227
|
+
"(mem curate --global)."
|
|
228
|
+
)
|
|
229
|
+
]
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _index_choose_rules(
|
|
233
|
+
loaded_project: list[records.Memory], loaded_global: list[records.Memory], today: datetime.date
|
|
234
|
+
) -> rules.Choice | None:
|
|
235
|
+
try:
|
|
236
|
+
return rules.choose(loaded_project, loaded_global, today)
|
|
237
|
+
except Exception:
|
|
238
|
+
logger.debug("loading the rules failed", exc_info=True)
|
|
239
|
+
return None
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _index_worse_count(
|
|
243
|
+
loaded_project: list[records.Memory],
|
|
244
|
+
loaded_global: list[records.Memory],
|
|
245
|
+
today: datetime.date,
|
|
246
|
+
choice: rules.Choice,
|
|
247
|
+
) -> list[str]:
|
|
248
|
+
worse = sum(
|
|
249
|
+
1 for _, loaded in curate._got_worse(loaded_project, loaded_global, today, choice) if loaded
|
|
250
|
+
)
|
|
251
|
+
if not worse:
|
|
252
|
+
return []
|
|
253
|
+
return [
|
|
254
|
+
f"Got worse: {worse} loaded lesson{' needs' if worse == 1 else 's need'} a decision (mem curate)."
|
|
255
|
+
]
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _index_worse_line(
|
|
259
|
+
loaded_project: list[records.Memory],
|
|
260
|
+
loaded_global: list[records.Memory],
|
|
261
|
+
today: datetime.date,
|
|
262
|
+
choice: rules.Choice | None,
|
|
263
|
+
) -> list[str]:
|
|
264
|
+
"""The "Got worse" line; nothing loads when the rules are off, so nothing "got worse after loading"."""
|
|
265
|
+
if choice is None:
|
|
266
|
+
return []
|
|
267
|
+
try:
|
|
268
|
+
return _index_worse_count(loaded_project, loaded_global, today, choice)
|
|
269
|
+
except Exception:
|
|
270
|
+
logger.debug("the session start usage tally failed", exc_info=True)
|
|
271
|
+
return []
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _index_head_lines(mine: list[records.Memory], due: dict[str, int], complete: bool) -> list[str]:
|
|
275
|
+
"""The project count and the curation line, which sit between the folder counts and the triage line."""
|
|
276
|
+
lines = [f"This project: {len(mine)} memories."] if mine else []
|
|
277
|
+
return lines + _index_due_line(due, complete)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _index_live_project(
|
|
281
|
+
loaded_project: list[records.Memory], today: datetime.date
|
|
282
|
+
) -> list[records.Memory]:
|
|
283
|
+
"""The project's live memories, the current situation first, then the newest observed."""
|
|
284
|
+
mine = [m for m in loaded_project if records.is_live(m, today)]
|
|
285
|
+
mine.sort(key=lambda m: m.handle) # stable sorts, least significant key first
|
|
286
|
+
mine.sort(key=lambda m: m.created or datetime.date.min, reverse=True)
|
|
287
|
+
mine.sort(key=lambda m: m.observed, reverse=True)
|
|
288
|
+
mine.sort(key=lambda m: m.kind != "state")
|
|
289
|
+
return mine
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _index_lines(
|
|
293
|
+
head: list[str],
|
|
294
|
+
mine: list[records.Memory],
|
|
295
|
+
notice: str | None,
|
|
296
|
+
store: Path | None,
|
|
297
|
+
today: datetime.date,
|
|
298
|
+
) -> list[str]:
|
|
299
|
+
"""The head line, the rules, the status line, the notice and the store's due lines."""
|
|
300
|
+
codex = _host() == "codex"
|
|
301
|
+
lines = [" ".join(head), *(_INDEX_RULES_CODEX if codex else _INDEX_RULES).split("\n")[1:]]
|
|
302
|
+
if any(m.kind == "state" for m in mine):
|
|
303
|
+
lines.append(_STATUS_LINE_CODEX if codex else _STATUS_LINE)
|
|
304
|
+
if notice:
|
|
305
|
+
lines.append(notice)
|
|
306
|
+
if store is not None:
|
|
307
|
+
lines += session_notices.store_due_lines(store, today, common.data_dir(os.environ))
|
|
308
|
+
return lines
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _index_rules_with_digest(
|
|
312
|
+
choice: rules.Choice, layout: str, digest: dict | None, topics: dict | None
|
|
313
|
+
) -> list[str]:
|
|
314
|
+
try:
|
|
315
|
+
extra = rules.block(choice, layout, digest=digest, topics=topics)
|
|
316
|
+
extra += rules.index_lines(choice, digest=digest, topics=topics)
|
|
317
|
+
except Exception: # a failure in the digest leaves the block without it
|
|
318
|
+
logger.debug("the rules digest failed", exc_info=True)
|
|
319
|
+
extra = rules.block(choice, "grouped" if layout == "digest" else layout)
|
|
320
|
+
more = rules.more_line(choice)
|
|
321
|
+
if more:
|
|
322
|
+
extra.append(more)
|
|
323
|
+
return extra
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _index_rules_lines(
|
|
327
|
+
choice: rules.Choice,
|
|
328
|
+
loaded_global: list[records.Memory],
|
|
329
|
+
today: datetime.date,
|
|
330
|
+
stats: dict[str, int] | None,
|
|
331
|
+
) -> list[str]:
|
|
332
|
+
layout = common._rules_layout()
|
|
333
|
+
digest, topics = common._rules_digest(loaded_global, today)
|
|
334
|
+
extra = _index_rules_with_digest(choice, layout, digest, topics)
|
|
335
|
+
if stats is not None:
|
|
336
|
+
stats.update(
|
|
337
|
+
rules=len(choice.loaded),
|
|
338
|
+
rules_left=len(rules.not_fitted(choice)),
|
|
339
|
+
rules_chars=len("\n".join(extra)),
|
|
340
|
+
)
|
|
341
|
+
return extra
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _index_rules_block(
|
|
345
|
+
choice: rules.Choice | None,
|
|
346
|
+
loaded_global: list[records.Memory],
|
|
347
|
+
today: datetime.date,
|
|
348
|
+
stats: dict[str, int] | None,
|
|
349
|
+
) -> list[str]:
|
|
350
|
+
"""The lessons that load as rules; `stats` receives their numbers. Empty when `choice` is None."""
|
|
351
|
+
if choice is None:
|
|
352
|
+
return []
|
|
353
|
+
try:
|
|
354
|
+
return _index_rules_lines(choice, loaded_global, today, stats)
|
|
355
|
+
except Exception:
|
|
356
|
+
logger.debug("the rules block failed", exc_info=True)
|
|
357
|
+
return []
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _index_memory_rows(mine: list[records.Memory]) -> list[str]:
|
|
361
|
+
rows = []
|
|
362
|
+
for m in mine:
|
|
363
|
+
claim = " ".join(m.claim.split())
|
|
364
|
+
if len(claim) > _CLAIM_LIMIT:
|
|
365
|
+
claim = claim[:_CLAIM_LIMIT] + "…"
|
|
366
|
+
created = m.created.isoformat() if m.created else "undated"
|
|
367
|
+
rows.append(f" m:{m.handle} [{m.kind}, {created}] {claim}")
|
|
368
|
+
return rows
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _index_fit(lines: list[str], extra: list[str], rows: list[str], limit: int) -> str:
|
|
372
|
+
"""The text with as many rows as fit `_INDEX_LIMIT` (the rules block does not count), at most `limit`."""
|
|
373
|
+
shown = min(limit, len(rows))
|
|
374
|
+
while True:
|
|
375
|
+
tail = (
|
|
376
|
+
[f' … and {len(rows) - shown} more: mem search "<words>" --scope memories']
|
|
377
|
+
if shown < len(rows)
|
|
378
|
+
else []
|
|
379
|
+
)
|
|
380
|
+
text = "\n".join(lines + rows[:shown] + tail)
|
|
381
|
+
if len(text) <= _INDEX_LIMIT or shown == 0:
|
|
382
|
+
return "\n".join(lines + extra + rows[:shown] + tail)
|
|
383
|
+
shown -= 1
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def session_index(
|
|
387
|
+
store: Path | None,
|
|
388
|
+
project: Path | None,
|
|
389
|
+
memories: Path | None,
|
|
390
|
+
today: datetime.date,
|
|
391
|
+
**options: Unpack[SessionIndexOptions],
|
|
392
|
+
) -> str:
|
|
393
|
+
"""Text for the start of a session: three generic lines with counts; the project's newest memories when limit > 0.
|
|
394
|
+
|
|
395
|
+
`passes` (date of the last curation pass per resolved folder) turns on the "Curation due" count; None leaves it out.
|
|
396
|
+
`marks` holds the decision keys each pass recorded (C100); the count is the keys of `_decisions` not in them.
|
|
397
|
+
`notice` is one more line after the rules (the failure of the automatic curation run).
|
|
398
|
+
The lessons that load as rules follow the notice; `stats`, when given, receives their numbers (rules, rules_left,
|
|
399
|
+
rules_chars). `limit` and `_INDEX_LIMIT` apply to the text without them."""
|
|
400
|
+
tracked = options.get("tracked", frozenset())
|
|
401
|
+
stats = options.get("stats")
|
|
402
|
+
store_dir, memories_dir = _index_existing(store, memories)
|
|
403
|
+
loaded_global = records.load_memories(memories_dir, "global")
|
|
404
|
+
loaded_project = records.mark_repository(records.load_memories(project, "project"), tracked)
|
|
405
|
+
scan = _DueScan(
|
|
406
|
+
today, options.get("passes"), options.get("marks"), tracked, records.Budget(PAIR_WORK)
|
|
407
|
+
)
|
|
408
|
+
due_counts = _index_due_counts(project, loaded_project, memories_dir, loaded_global, scan)
|
|
409
|
+
mine = _index_live_project(loaded_project, today)
|
|
410
|
+
rules_off = common._rules_off()
|
|
411
|
+
choice = None if rules_off else _index_choose_rules(loaded_project, loaded_global, today)
|
|
412
|
+
head = [_INDEX_HEAD, *_index_folder_lines(store_dir, memories_dir, loaded_global, today)]
|
|
413
|
+
head += _index_head_lines(mine, *due_counts)
|
|
414
|
+
head += _index_triage_line(loaded_global, today)
|
|
415
|
+
head += _index_worse_line(loaded_project, loaded_global, today, choice)
|
|
416
|
+
lines = _index_lines(head, mine, options.get("notice"), store_dir, today)
|
|
417
|
+
if rules_off and stats is not None:
|
|
418
|
+
stats.update(rules=0, rules_left=0, rules_chars=0)
|
|
419
|
+
extra = _index_rules_block(choice, loaded_global, today, stats)
|
|
420
|
+
limit = options.get("limit", 0)
|
|
421
|
+
if mine and limit > 0:
|
|
422
|
+
return _index_fit(lines, extra, _index_memory_rows(mine), limit)
|
|
423
|
+
return "\n".join(lines + extra)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _hook_input() -> dict[str, Any]:
|
|
427
|
+
"""The hook's JSON from standard input; {} when it is missing or not an object."""
|
|
428
|
+
try:
|
|
429
|
+
if sys.stdin is None or sys.stdin.isatty(): # nothing piped: never wait for a terminal
|
|
430
|
+
return {}
|
|
431
|
+
data = json.load(sys.stdin)
|
|
432
|
+
except (OSError, ValueError):
|
|
433
|
+
return {}
|
|
434
|
+
return data if isinstance(data, dict) else {}
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _corroborate_failure_line(data: Path | None, now: float) -> str | None:
|
|
438
|
+
"""The line `mem session-index` adds after a failed corroboration pass (`mem-corroborate ack` clears it)."""
|
|
439
|
+
if data is None:
|
|
440
|
+
return None
|
|
441
|
+
found = jobs.failure(jobs.read_json(data / "corroborate" / jobs.STATUS_NAME), now)
|
|
442
|
+
if found is None:
|
|
443
|
+
return None
|
|
444
|
+
reason = " ".join(str(found["reason"]).split())[:200]
|
|
445
|
+
return (
|
|
446
|
+
f"memory: the last corroboration pass failed ({reason}): see mem-corroborate status, "
|
|
447
|
+
"then mem-corroborate ack."
|
|
448
|
+
)
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
@dataclasses.dataclass(frozen=True)
|
|
452
|
+
class _HookScope:
|
|
453
|
+
"""Where a hook runs: the store when it is a given path, the folder of the hook's `cwd`, the global folder."""
|
|
454
|
+
|
|
455
|
+
store: Path | None
|
|
456
|
+
cwd: Path
|
|
457
|
+
memories: Path | None
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _hook_cwd(data: dict[str, Any]) -> Path:
|
|
461
|
+
cwd = Path(data["cwd"]) if isinstance(data.get("cwd"), str) and data["cwd"] else Path.cwd()
|
|
462
|
+
return cwd if cwd.is_dir() else Path.cwd()
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def _hook_scope(args: argparse.Namespace, data: dict[str, Any]) -> _HookScope:
|
|
466
|
+
store = args.root if isinstance(args.root, Path) else None
|
|
467
|
+
cwd = _hook_cwd(data)
|
|
468
|
+
memories = records.memories_root(
|
|
469
|
+
os.environ, store if store is not None and store.is_dir() else None
|
|
470
|
+
)
|
|
471
|
+
return _HookScope(store, cwd, memories)
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _session_notice(make: Callable[[], str | None]) -> str | None:
|
|
475
|
+
try:
|
|
476
|
+
return make()
|
|
477
|
+
except Exception:
|
|
478
|
+
logger.debug("a session start notice failed", exc_info=True)
|
|
479
|
+
return None
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def _session_notices(store: Path | None, memories: Path | None) -> str | None:
|
|
483
|
+
"""The failure lines of the background runs, one per line; None when there are none."""
|
|
484
|
+
notices = []
|
|
485
|
+
for make in (
|
|
486
|
+
lambda: auto_state.failure_line(common.data_dir(os.environ), store, time.time()),
|
|
487
|
+
lambda: settle_state.failure_line(common.data_dir(os.environ), store, time.time()),
|
|
488
|
+
lambda: capture_state.failure_line(common.data_dir(os.environ), time.time()),
|
|
489
|
+
lambda: _corroborate_failure_line(common.data_dir(os.environ), time.time()),
|
|
490
|
+
lambda: settle_state.settled_line(memories),
|
|
491
|
+
):
|
|
492
|
+
found = _session_notice(make)
|
|
493
|
+
if found:
|
|
494
|
+
notices.append(found)
|
|
495
|
+
return "\n".join(notices) or None
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def _session_text(args: argparse.Namespace, data: dict[str, Any], stats: dict[str, int]) -> str:
|
|
499
|
+
store = args.root if isinstance(args.root, Path) else None
|
|
500
|
+
cwd = _hook_cwd(data)
|
|
501
|
+
try:
|
|
502
|
+
project = records.project_root(cwd, os.environ)
|
|
503
|
+
except OSError:
|
|
504
|
+
project = None
|
|
505
|
+
memories = records.memories_root(
|
|
506
|
+
os.environ, store if store is not None and store.is_dir() else None
|
|
507
|
+
)
|
|
508
|
+
notice = _session_notices(store, memories)
|
|
509
|
+
return session_index(
|
|
510
|
+
store,
|
|
511
|
+
records.project_dir(project) if project else None,
|
|
512
|
+
memories,
|
|
513
|
+
datetime.date.today(),
|
|
514
|
+
limit=max(args.list, 0),
|
|
515
|
+
passes=curate.read_passes(os.environ),
|
|
516
|
+
notice=notice,
|
|
517
|
+
stats=stats,
|
|
518
|
+
marks=curate.read_marks(os.environ),
|
|
519
|
+
tracked=records.tracked_memories(project) if project else frozenset(),
|
|
520
|
+
)
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def cmd_session_index(args: argparse.Namespace) -> int:
|
|
524
|
+
"""Never fails: the rules matter most when nothing is configured yet. Writes only the hook log and the plugin-root record, with --hook,
|
|
525
|
+
and the day's due-note count (session_notices.DUE_CACHE_NAME)."""
|
|
526
|
+
started = time.monotonic()
|
|
527
|
+
data = _hook_input() if args.hook else {}
|
|
528
|
+
stats: dict[str, int] = {}
|
|
529
|
+
try:
|
|
530
|
+
text = _session_text(args, data, stats)
|
|
531
|
+
except Exception:
|
|
532
|
+
logger.debug("building the session start text failed", exc_info=True)
|
|
533
|
+
text = _INDEX_RULES_CODEX if _host() == "codex" else _INDEX_RULES
|
|
534
|
+
stats.clear()
|
|
535
|
+
if args.hook:
|
|
536
|
+
install.record_root()
|
|
537
|
+
if _host() == "codex" and install.launcher_missing():
|
|
538
|
+
mem = shlex.quote(resources.shell_mem())
|
|
539
|
+
text += f"\nmemory: mem is not installed as a command; run it as {mem}"
|
|
540
|
+
if resources.plugin_root() is not None: # only a plugin copy can install its launchers
|
|
541
|
+
text += f", or install it once: {mem} install-command"
|
|
542
|
+
print(text)
|
|
543
|
+
if args.hook:
|
|
544
|
+
source = data.get("source")
|
|
545
|
+
common._log_hook({
|
|
546
|
+
"hook": "session-index",
|
|
547
|
+
"host": _host(),
|
|
548
|
+
"source": source if isinstance(source, str) else None,
|
|
549
|
+
"ms": int((time.monotonic() - started) * 1000),
|
|
550
|
+
"chars": len(text),
|
|
551
|
+
"rules": stats.get("rules", 0),
|
|
552
|
+
"rules_left": stats.get("rules_left", 0),
|
|
553
|
+
"rules_chars": stats.get("rules_chars", 0),
|
|
554
|
+
})
|
|
555
|
+
return 0
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
_COMPACT_PARSE_LIMIT = 1_000_000
|
|
559
|
+
_COMPACT_OUT_LIMIT = 300
|
|
560
|
+
_SESSION_ID = re.compile(r"[A-Za-z0-9_-]{1,64}")
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _compact_entry(
|
|
564
|
+
data: dict[str, Any], summary: str, found: dict[str, str], lines: list[str], started: float
|
|
565
|
+
) -> dict[str, Any]:
|
|
566
|
+
"""The hook log line of a compaction: counts and flags only."""
|
|
567
|
+
text = summary[:_COMPACT_PARSE_LIMIT]
|
|
568
|
+
trigger, session = data.get("trigger"), data.get("session_id")
|
|
569
|
+
return {
|
|
570
|
+
"hook": "post-compact",
|
|
571
|
+
"trigger": trigger if isinstance(trigger, str) and trigger in {"manual", "auto"} else None,
|
|
572
|
+
"session": session if isinstance(session, str) and _SESSION_ID.fullmatch(session) else None,
|
|
573
|
+
"chars": len(summary),
|
|
574
|
+
"marker": handoff.has_marker(text),
|
|
575
|
+
"handoff": [f for f in handoff.FIELDS if f in found],
|
|
576
|
+
"plan_named": handoff.names_plan(found.get("plan", "")),
|
|
577
|
+
"unrecorded": handoff.unrecorded(text),
|
|
578
|
+
"mismatches": len(lines),
|
|
579
|
+
"ms": int((time.monotonic() - started) * 1000),
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def _compact_log(args: argparse.Namespace, started: float) -> None:
|
|
584
|
+
data = _hook_input() if args.hook else {}
|
|
585
|
+
summary = data.get("compact_summary")
|
|
586
|
+
if not isinstance(summary, str):
|
|
587
|
+
return
|
|
588
|
+
text = summary[:_COMPACT_PARSE_LIMIT]
|
|
589
|
+
cwd = _hook_cwd(data)
|
|
590
|
+
found = handoff.parse(text)
|
|
591
|
+
lines = handoff.mismatches(found, cwd)
|
|
592
|
+
if lines:
|
|
593
|
+
print("\n".join(lines)[:_COMPACT_OUT_LIMIT])
|
|
594
|
+
if args.hook:
|
|
595
|
+
common._log_hook(_compact_entry(data, summary, found, lines, started))
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def cmd_compact_log(args: argparse.Namespace) -> int:
|
|
599
|
+
"""Never fails and prints nothing on bad input. Prints the handoff mismatch lines and logs counts only."""
|
|
600
|
+
started = time.monotonic()
|
|
601
|
+
try:
|
|
602
|
+
_compact_log(args, started)
|
|
603
|
+
except Exception:
|
|
604
|
+
logger.debug("logging the compact summary failed", exc_info=True)
|
|
605
|
+
return 0
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
_SIGNAL_LIMIT = 400
|
|
609
|
+
_SIGNAL_HANDLES = 3
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def signal_text(strong: Sequence[records.Related], possible: Sequence[records.Related]) -> str:
|
|
613
|
+
"""The block appended to a subagent's brief: handles and counts only, at most _SIGNAL_LIMIT characters."""
|
|
614
|
+
if not strong:
|
|
615
|
+
return ""
|
|
616
|
+
shown = [
|
|
617
|
+
f"{r.kind}:{r.handle}" for r in strong[:_SIGNAL_HANDLES]
|
|
618
|
+
] # only strong matches are named
|
|
619
|
+
|
|
620
|
+
def render(items: list[str]) -> str:
|
|
621
|
+
return "\n".join([
|
|
622
|
+
f"[memory] For information: memories related to this task exist (not read yet): {' '.join(items)}",
|
|
623
|
+
(
|
|
624
|
+
f"{len(strong)} strong, {len(possible)} possibly related. Read one with: mem show m:<handle> "
|
|
625
|
+
"(they are files in .memory/)."
|
|
626
|
+
),
|
|
627
|
+
(
|
|
628
|
+
"They are experience, not fact: where one conflicts with this brief, the brief wins and you report "
|
|
629
|
+
"the conflict."
|
|
630
|
+
),
|
|
631
|
+
])
|
|
632
|
+
|
|
633
|
+
text = render(shown)
|
|
634
|
+
while len(text) > _SIGNAL_LIMIT and len(shown) > 1: # very long note names
|
|
635
|
+
shown.pop()
|
|
636
|
+
text = render(shown)
|
|
637
|
+
return text
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
@dataclasses.dataclass(frozen=True)
|
|
641
|
+
class _SignalInput:
|
|
642
|
+
"""The brief a signal is for, and with --hook the hook's JSON and the tool input it came in."""
|
|
643
|
+
|
|
644
|
+
data: dict[str, Any]
|
|
645
|
+
tool_input: Any
|
|
646
|
+
brief: str
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def _signal_input(args: argparse.Namespace) -> _SignalInput | None:
|
|
650
|
+
"""None when there is no brief to signal: not an Agent call, or an empty brief."""
|
|
651
|
+
data: dict[str, Any] = {}
|
|
652
|
+
tool_input: Any = None
|
|
653
|
+
if args.hook:
|
|
654
|
+
data = _hook_input()
|
|
655
|
+
tool_input = data.get("tool_input")
|
|
656
|
+
if data.get("tool_name") != "Agent" or not isinstance(tool_input, dict):
|
|
657
|
+
return None
|
|
658
|
+
brief = tool_input.get("prompt")
|
|
659
|
+
else:
|
|
660
|
+
brief = None if sys.stdin is None or sys.stdin.isatty() else sys.stdin.read()
|
|
661
|
+
if not isinstance(brief, str) or not brief.strip():
|
|
662
|
+
return None
|
|
663
|
+
return _SignalInput(data, tool_input, brief)
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
def _signal_related(
|
|
667
|
+
args: argparse.Namespace, given: _SignalInput
|
|
668
|
+
) -> tuple[list[records.Related], list[records.Related]]:
|
|
669
|
+
"""The strong and the possibly related memories of the brief (memories only)."""
|
|
670
|
+
scope = _hook_scope(args, given.data)
|
|
671
|
+
project = records.project_root(scope.cwd, os.environ)
|
|
672
|
+
found = records.load_memories(records.project_dir(project) if project else None, "project") + [
|
|
673
|
+
m for m in records.load_memories(scope.memories, "global") if not records.quarantined(m)
|
|
674
|
+
]
|
|
675
|
+
return records.related_records(
|
|
676
|
+
found, [], given.brief, datetime.date.today(), tokenize=records.tokenize
|
|
677
|
+
)
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
def _signal_log(
|
|
681
|
+
given: _SignalInput,
|
|
682
|
+
strong: Sequence[records.Related],
|
|
683
|
+
possible: Sequence[records.Related],
|
|
684
|
+
started: float,
|
|
685
|
+
) -> None:
|
|
686
|
+
subagent_type = given.tool_input.get("subagent_type")
|
|
687
|
+
common._log_hook({
|
|
688
|
+
"hook": "signal",
|
|
689
|
+
"ms": int((time.monotonic() - started) * 1000),
|
|
690
|
+
"strong": len(strong),
|
|
691
|
+
"possible": len(possible),
|
|
692
|
+
"subagent_type": subagent_type if isinstance(subagent_type, str) else None,
|
|
693
|
+
"words": len(given.brief.split()),
|
|
694
|
+
})
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
def _signal_print(args: argparse.Namespace, given: _SignalInput, text: str) -> None:
|
|
698
|
+
if not args.hook:
|
|
699
|
+
print(text)
|
|
700
|
+
return
|
|
701
|
+
updated = {**given.tool_input, "prompt": f"{given.brief}\n\n{text}"}
|
|
702
|
+
print(
|
|
703
|
+
json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "updatedInput": updated}})
|
|
704
|
+
)
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def _signal(args: argparse.Namespace, started: float) -> None:
|
|
708
|
+
given = _signal_input(args)
|
|
709
|
+
if given is None:
|
|
710
|
+
return
|
|
711
|
+
strong, possible = _signal_related(args, given)
|
|
712
|
+
text = signal_text(strong, possible)
|
|
713
|
+
if args.hook:
|
|
714
|
+
_signal_log(given, strong, possible, started)
|
|
715
|
+
if text:
|
|
716
|
+
_signal_print(args, given, text)
|
|
717
|
+
|
|
718
|
+
|
|
719
|
+
def cmd_signal(args: argparse.Namespace) -> int:
|
|
720
|
+
"""Never fails. Without --hook: the brief on standard input, the signal text out. With --hook: the hook's JSON in,
|
|
721
|
+
the brief with the signal appended out (updatedInput, never a permission decision), one line in the hook log."""
|
|
722
|
+
started = time.monotonic()
|
|
723
|
+
try:
|
|
724
|
+
_signal(args, started)
|
|
725
|
+
except Exception:
|
|
726
|
+
logger.debug("the signal hook failed", exc_info=True)
|
|
727
|
+
return 0
|
|
728
|
+
|
|
729
|
+
|
|
730
|
+
PAIR_WORK = 150_000 # claim comparisons the session start line may spend on pair searches, both folders together
|