omp-memory 0.2.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.
- omp_memory/__init__.py +188 -0
- omp_memory/__main__.py +8 -0
- omp_memory/capture.py +658 -0
- omp_memory/cli.py +1045 -0
- omp_memory/context.py +187 -0
- omp_memory/db.py +4638 -0
- omp_memory/experience.py +309 -0
- omp_memory/handoff.py +468 -0
- omp_memory/hooks.py +162 -0
- omp_memory/mcp.py +1046 -0
- omp_memory/md_ingest.py +268 -0
- omp_memory/outcomes.py +58 -0
- omp_memory/provider.py +129 -0
- omp_memory/watch.py +163 -0
- omp_memory/web/dist/assets/index-BMXPmOzw.js +216 -0
- omp_memory/web/dist/assets/index-qca123ar.css +1 -0
- omp_memory/web/dist/index.html +13 -0
- omp_memory/web.py +879 -0
- omp_memory-0.2.0.dist-info/METADATA +506 -0
- omp_memory-0.2.0.dist-info/RECORD +24 -0
- omp_memory-0.2.0.dist-info/WHEEL +5 -0
- omp_memory-0.2.0.dist-info/entry_points.txt +3 -0
- omp_memory-0.2.0.dist-info/licenses/LICENSE.md +19 -0
- omp_memory-0.2.0.dist-info/top_level.txt +1 -0
omp_memory/cli.py
ADDED
|
@@ -0,0 +1,1045 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Command line interface: one entry point for capture, search, recap, health.
|
|
3
|
+
|
|
4
|
+
The shell scripts in bin/ are thin shims so cron, hooks, and manual use keep
|
|
5
|
+
working without duplicating Python heredocs.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import shutil
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
from datetime import datetime, timezone
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from . import db
|
|
20
|
+
from .capture import scan_text
|
|
21
|
+
from .context import build_memory_context_block
|
|
22
|
+
|
|
23
|
+
DEFAULT_MIN_FREE_MB = 100
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _memory_dir() -> Path:
|
|
27
|
+
return Path(db.DB_PATH).parent
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _sessions_dir() -> Path:
|
|
31
|
+
return _memory_dir() / "sessions"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class CliError(Exception):
|
|
35
|
+
"""A user-facing failure: report it plainly, exit non-zero, no traceback."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _open():
|
|
39
|
+
"""Open and migrate the store, turning storage failures into a clear
|
|
40
|
+
message. Without this a corrupt or unreadable database surfaced as a
|
|
41
|
+
bare traceback on stderr and an empty stdout, which reads as success to
|
|
42
|
+
anything that only checks stdout."""
|
|
43
|
+
try:
|
|
44
|
+
conn = db.connect()
|
|
45
|
+
except Exception as exc: # sqlite3.OperationalError, OSError, ...
|
|
46
|
+
raise CliError(f"cannot open the memory database: {exc}") from exc
|
|
47
|
+
try:
|
|
48
|
+
db.init_db(conn)
|
|
49
|
+
except Exception as exc:
|
|
50
|
+
conn.close()
|
|
51
|
+
raise CliError(f"cannot initialise the memory database: {exc}") from exc
|
|
52
|
+
return conn
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# --- secret scanning ---------------------------------------------------------
|
|
56
|
+
# Patterns and scan_text live in capture.py so the auto-capture pipeline and
|
|
57
|
+
# this CLI guard share one definition.
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def cmd_scan(args) -> int:
|
|
61
|
+
text = args.text
|
|
62
|
+
if not text and not sys.stdin.isatty():
|
|
63
|
+
text = sys.stdin.read()
|
|
64
|
+
findings = scan_text(text)
|
|
65
|
+
for kind, fragment in findings:
|
|
66
|
+
print(f"WARNING: possible {kind} detected: {fragment}...", file=sys.stderr)
|
|
67
|
+
return 1 if findings else 0
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# --- capture -----------------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
def _project_id() -> str:
|
|
73
|
+
"""Stable short id for the current git project, or '' outside a repo."""
|
|
74
|
+
try:
|
|
75
|
+
remote = subprocess.run(
|
|
76
|
+
["git", "remote", "get-url", "origin"],
|
|
77
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace",
|
|
78
|
+
timeout=5, check=False,
|
|
79
|
+
)
|
|
80
|
+
except (OSError, subprocess.SubprocessError):
|
|
81
|
+
return ""
|
|
82
|
+
if remote.returncode == 0 and remote.stdout.strip():
|
|
83
|
+
return hashlib.sha256(remote.stdout.strip().encode()).hexdigest()[:12]
|
|
84
|
+
try:
|
|
85
|
+
top = subprocess.run(
|
|
86
|
+
["git", "rev-parse", "--show-toplevel"],
|
|
87
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace",
|
|
88
|
+
timeout=5, check=False,
|
|
89
|
+
)
|
|
90
|
+
except (OSError, subprocess.SubprocessError):
|
|
91
|
+
return ""
|
|
92
|
+
if top.returncode == 0 and top.stdout.strip():
|
|
93
|
+
return hashlib.sha256(top.stdout.strip().encode()).hexdigest()[:12]
|
|
94
|
+
return ""
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _check_disk(min_free_mb: int) -> bool:
|
|
98
|
+
target = _memory_dir()
|
|
99
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
100
|
+
try:
|
|
101
|
+
usage = shutil.disk_usage(str(target))
|
|
102
|
+
except OSError:
|
|
103
|
+
return False
|
|
104
|
+
return usage.free >= min_free_mb * 1024 * 1024
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def cmd_capture(args) -> int:
|
|
108
|
+
if not args.task or not args.outcome:
|
|
109
|
+
print("error: --task and --outcome are required", file=sys.stderr)
|
|
110
|
+
return 2
|
|
111
|
+
if args.type not in db.VALID_TYPES:
|
|
112
|
+
print(f"error: invalid --type {args.type}", file=sys.stderr)
|
|
113
|
+
return 2
|
|
114
|
+
if args.verified and not (args.evidence or "").strip():
|
|
115
|
+
print("error: --verified requires --evidence (what was checked)",
|
|
116
|
+
file=sys.stderr)
|
|
117
|
+
return 2
|
|
118
|
+
|
|
119
|
+
combined = f"{args.task} {args.outcome} {args.evidence}"
|
|
120
|
+
findings = scan_text(combined)
|
|
121
|
+
if findings and not args.allow_secrets:
|
|
122
|
+
for kind, fragment in findings:
|
|
123
|
+
print(f"error: possible {kind} in capture input: {fragment}...", file=sys.stderr)
|
|
124
|
+
print("refusing to store; pass --allow-secrets to override", file=sys.stderr)
|
|
125
|
+
return 1
|
|
126
|
+
|
|
127
|
+
if not _check_disk(args.min_free_mb):
|
|
128
|
+
print(f"error: less than {args.min_free_mb}MB free in {_memory_dir()}", file=sys.stderr)
|
|
129
|
+
return 1
|
|
130
|
+
|
|
131
|
+
project = args.project or _project_id()
|
|
132
|
+
session = args.session or f"sess-{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}"
|
|
133
|
+
content = f"{args.task} -> {args.outcome}"
|
|
134
|
+
|
|
135
|
+
conn = _open()
|
|
136
|
+
try:
|
|
137
|
+
db.start_session(conn, session_id=session, project_id=project,
|
|
138
|
+
parent_id=args.parent_id)
|
|
139
|
+
existing = db.find_record(conn, args.type, content, args.source, project)
|
|
140
|
+
record_id = db.upsert_record(
|
|
141
|
+
conn,
|
|
142
|
+
rtype=args.type,
|
|
143
|
+
content=content,
|
|
144
|
+
evidence=args.evidence,
|
|
145
|
+
verified=1 if args.verified else 0,
|
|
146
|
+
confidence=args.confidence,
|
|
147
|
+
source=args.source,
|
|
148
|
+
tags=args.tags,
|
|
149
|
+
session_id=session,
|
|
150
|
+
project_id=project,
|
|
151
|
+
parent_id=args.parent_id,
|
|
152
|
+
)
|
|
153
|
+
if existing and existing["id"] == record_id:
|
|
154
|
+
print(f"updated {record_id} (type={args.type})")
|
|
155
|
+
else:
|
|
156
|
+
print(f"captured {record_id} (type={args.type}, confidence={args.confidence})")
|
|
157
|
+
finally:
|
|
158
|
+
conn.close()
|
|
159
|
+
|
|
160
|
+
_append_jsonl(session, project, args, content)
|
|
161
|
+
if not args.no_audit:
|
|
162
|
+
_audit("capture", content, session, project)
|
|
163
|
+
return 0
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _append_jsonl(session: str, project: str, args, content: str) -> None:
|
|
167
|
+
"""Durable append-only capture log; survives a DB failure."""
|
|
168
|
+
sessions = _sessions_dir()
|
|
169
|
+
sessions.mkdir(parents=True, exist_ok=True)
|
|
170
|
+
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
|
171
|
+
path = sessions / f"capture-{stamp}-{os.getpid()}.jsonl"
|
|
172
|
+
entry = {
|
|
173
|
+
"timestamp": db.now_iso(),
|
|
174
|
+
"session": session,
|
|
175
|
+
"project": project,
|
|
176
|
+
"task": args.task,
|
|
177
|
+
"outcome": args.outcome,
|
|
178
|
+
"type": args.type,
|
|
179
|
+
"evidence": args.evidence,
|
|
180
|
+
"verified": int(bool(args.verified)),
|
|
181
|
+
"confidence": args.confidence,
|
|
182
|
+
"source": args.source,
|
|
183
|
+
"tags": args.tags,
|
|
184
|
+
"parent_id": args.parent_id,
|
|
185
|
+
}
|
|
186
|
+
with path.open("a", encoding="utf-8", newline="\n") as fh:
|
|
187
|
+
fh.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _audit(action: str, detail: str, session: str, project: str) -> None:
|
|
191
|
+
log = _memory_dir() / "audit.log"
|
|
192
|
+
line = (
|
|
193
|
+
f"[{datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}] "
|
|
194
|
+
f"action={action} session={session} project={project} detail={detail}\n"
|
|
195
|
+
)
|
|
196
|
+
try:
|
|
197
|
+
with log.open("a", encoding="utf-8", newline="\n") as fh:
|
|
198
|
+
fh.write(line)
|
|
199
|
+
except OSError:
|
|
200
|
+
pass
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
# --- search / list / recap ---------------------------------------------------
|
|
204
|
+
|
|
205
|
+
def cmd_search(args) -> int:
|
|
206
|
+
conn = _open()
|
|
207
|
+
try:
|
|
208
|
+
# as_of and expand only exist on recall(); plain search stays the
|
|
209
|
+
# fast lexical path. Routing on the flags keeps one command for both
|
|
210
|
+
# instead of asking the operator to remember which flags need which.
|
|
211
|
+
if args.as_of or args.expand or args.explain or args.brief:
|
|
212
|
+
rows = db.recall(
|
|
213
|
+
conn, args.query, limit=args.limit, rtype=args.type,
|
|
214
|
+
project_id=args.project, session_id=args.session,
|
|
215
|
+
verified_only=args.verified,
|
|
216
|
+
min_confidence=args.min_confidence, as_of=args.as_of,
|
|
217
|
+
expand=args.expand, full=True, explain=args.explain)
|
|
218
|
+
else:
|
|
219
|
+
rows = db.search(
|
|
220
|
+
conn, args.query, limit=args.limit, rtype=args.type,
|
|
221
|
+
project_id=args.project, session_id=args.session,
|
|
222
|
+
verified_only=args.verified,
|
|
223
|
+
min_confidence=args.min_confidence,
|
|
224
|
+
)
|
|
225
|
+
finally:
|
|
226
|
+
conn.close()
|
|
227
|
+
|
|
228
|
+
if args.json:
|
|
229
|
+
print(json.dumps(rows, indent=2, ensure_ascii=False))
|
|
230
|
+
return 0
|
|
231
|
+
if not rows:
|
|
232
|
+
print("no matches")
|
|
233
|
+
return 0
|
|
234
|
+
if args.brief:
|
|
235
|
+
lines = []
|
|
236
|
+
for row in rows:
|
|
237
|
+
first = next((l for l in row["content"].splitlines() if l.strip()), "")
|
|
238
|
+
lines.append(f"- {row['id']} [{row['type']}] {first[:100]} "
|
|
239
|
+
f"(conf {float(row['confidence']):.2f})")
|
|
240
|
+
body = "\n".join(lines)
|
|
241
|
+
print(f"Recalled {len(rows)} record(s) for {args.query!r} (brief index):")
|
|
242
|
+
print(body)
|
|
243
|
+
print(f"~{len(body) // 4} tokens. Detail: recall with a narrower query, "
|
|
244
|
+
"or reuse an id above.")
|
|
245
|
+
return 0
|
|
246
|
+
for row in rows:
|
|
247
|
+
print(f"{row['id']} [{row['type']}] conf={row['confidence']:.2f} {row['content']}")
|
|
248
|
+
if row.get("evidence"):
|
|
249
|
+
print(f" evidence: {row['evidence']}")
|
|
250
|
+
return 0
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def cmd_recap(args) -> int:
|
|
254
|
+
conn = _open()
|
|
255
|
+
try:
|
|
256
|
+
if args.session:
|
|
257
|
+
rows = [r for r in db.list_records(conn, limit=10_000)
|
|
258
|
+
if r["session_id"] == args.session]
|
|
259
|
+
else:
|
|
260
|
+
rows = db.list_records(conn, project_id=args.project, limit=args.limit)
|
|
261
|
+
finally:
|
|
262
|
+
conn.close()
|
|
263
|
+
|
|
264
|
+
if args.json:
|
|
265
|
+
print(json.dumps(rows, indent=2, ensure_ascii=False))
|
|
266
|
+
return 0
|
|
267
|
+
|
|
268
|
+
header = args.session or args.project or "all records"
|
|
269
|
+
print(f"# {header}")
|
|
270
|
+
print(f"{len(rows)} records")
|
|
271
|
+
for row in rows:
|
|
272
|
+
mark = "verified" if row["verified"] else "unverified"
|
|
273
|
+
print(f"- [{row['type']}/{mark} conf={row['confidence']:.2f}] {row['content']}")
|
|
274
|
+
if row.get("evidence"):
|
|
275
|
+
print(f" evidence: {row['evidence']}")
|
|
276
|
+
return 0
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def cmd_context(args) -> int:
|
|
280
|
+
"""Emit a fenced memory-context block for prompt injection."""
|
|
281
|
+
conn = _open()
|
|
282
|
+
try:
|
|
283
|
+
rows = db.search(conn, args.query, limit=args.limit, project_id=args.project)
|
|
284
|
+
finally:
|
|
285
|
+
conn.close()
|
|
286
|
+
body = "\n".join(f"- [{r['type']}] {r['content']}" for r in rows)
|
|
287
|
+
block = build_memory_context_block(body)
|
|
288
|
+
if not block:
|
|
289
|
+
return 0
|
|
290
|
+
print(block, end="")
|
|
291
|
+
return 0
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
# --- reinforce / promote -----------------------------------------------------
|
|
295
|
+
|
|
296
|
+
def cmd_reinforce(args) -> int:
|
|
297
|
+
conn = _open()
|
|
298
|
+
try:
|
|
299
|
+
new_conf = db.reinforce(conn, args.record_id, args.signal,
|
|
300
|
+
content=getattr(args, "content", None),
|
|
301
|
+
evidence=getattr(args, "evidence", None),
|
|
302
|
+
delta=args.delta, source=args.source)
|
|
303
|
+
except ValueError as exc:
|
|
304
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
305
|
+
return 1
|
|
306
|
+
finally:
|
|
307
|
+
conn.close()
|
|
308
|
+
print(f"{args.record_id} {args.signal} -> confidence {new_conf:.2f}")
|
|
309
|
+
return 0
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def cmd_verify(args) -> int:
|
|
313
|
+
"""Re-check structured evidence; valid keeps attestation, stale demotes."""
|
|
314
|
+
conn = _open()
|
|
315
|
+
try:
|
|
316
|
+
summary = db.verify_evidence(
|
|
317
|
+
conn, repo_root=args.repo or None, record_id=args.record_id,
|
|
318
|
+
project_id=args.project, apply=not args.dry_run)
|
|
319
|
+
finally:
|
|
320
|
+
conn.close()
|
|
321
|
+
if args.json:
|
|
322
|
+
print(json.dumps(summary, indent=2, sort_keys=True))
|
|
323
|
+
else:
|
|
324
|
+
print(f"checked {summary['checked']} structured, "
|
|
325
|
+
f"{summary['free_text']} free-text skipped")
|
|
326
|
+
print(f"valid {summary['valid']} stale {summary['stale']} "
|
|
327
|
+
f"gone {summary['gone']} invalid {summary['invalid']} "
|
|
328
|
+
f"demoted {summary['demoted']}")
|
|
329
|
+
return 0
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def cmd_calibrate(args) -> int:
|
|
333
|
+
conn = _open()
|
|
334
|
+
try:
|
|
335
|
+
report = db.calibrate(conn, min_samples=args.min_samples)
|
|
336
|
+
finally:
|
|
337
|
+
conn.close()
|
|
338
|
+
if args.json:
|
|
339
|
+
print(json.dumps(report, indent=2, sort_keys=True))
|
|
340
|
+
return 0
|
|
341
|
+
if report.get("insufficient"):
|
|
342
|
+
print(f"insufficient data: {report['samples']} labelled samples "
|
|
343
|
+
f"(need {report['min_samples']})")
|
|
344
|
+
if report.get("message"):
|
|
345
|
+
print(report["message"])
|
|
346
|
+
return 0
|
|
347
|
+
print(f"samples {report['samples']} brier {report['brier']:.4f} "
|
|
348
|
+
f"ece {report['ece']:.4f}")
|
|
349
|
+
print(f"{'bin':>9} {'n':>6} {'conf':>7} {'success':>8}")
|
|
350
|
+
for b in report["bins"]:
|
|
351
|
+
print(f"{b['lo']:.1f}-{b['hi']:.1f} {b['n']:6d} "
|
|
352
|
+
f"{b['mean_confidence']:7.3f} {b['observed_success']:8.3f}")
|
|
353
|
+
return 0
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def cmd_outcome(args) -> int:
|
|
357
|
+
conn = _open()
|
|
358
|
+
try:
|
|
359
|
+
report = db.log_outcome(conn, args.kind, session_id=args.session or "",
|
|
360
|
+
evidence_ref=args.evidence_ref or "")
|
|
361
|
+
finally:
|
|
362
|
+
conn.close()
|
|
363
|
+
print(f"outcome {args.kind} id={report['id']} credited {report['credited']}")
|
|
364
|
+
return 0
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def cmd_attest(args) -> int:
|
|
368
|
+
"""Operator attestation: the only path an agent-written record has into
|
|
369
|
+
ATTESTED trust. Deliberately CLI-only; no MCP tool exposes it."""
|
|
370
|
+
conn = _open()
|
|
371
|
+
try:
|
|
372
|
+
rec = db.attest(conn, args.record_id, args.evidence)
|
|
373
|
+
except (ValueError, db.NotFound) as exc:
|
|
374
|
+
print(f"attest: {exc}", file=sys.stderr)
|
|
375
|
+
return 1
|
|
376
|
+
finally:
|
|
377
|
+
conn.close()
|
|
378
|
+
print(f"{args.record_id} attested; trust={rec['trust']} verified=1")
|
|
379
|
+
return 0
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def cmd_maintenance(args) -> int:
|
|
383
|
+
"""Every maintenance op the MCP server exposes, reachable from a shell.
|
|
384
|
+
|
|
385
|
+
The CLI used to implement only 3 of the 10 ops, so `sleep`, `reflect`,
|
|
386
|
+
`capture`, `ingest_md`, `review`, `pending`, `approve`, `reject` and
|
|
387
|
+
`not_conflict` could only be triggered by an agent over MCP. A cron job,
|
|
388
|
+
a systemd timer, or an operator with no agent running had no path to them.
|
|
389
|
+
Parity is the fix: same names, same arguments.
|
|
390
|
+
"""
|
|
391
|
+
conn = _open()
|
|
392
|
+
try:
|
|
393
|
+
op = args.op
|
|
394
|
+
if op == "decay":
|
|
395
|
+
print(json.dumps({"decayed": db.apply_decay(conn)}, indent=2, sort_keys=True))
|
|
396
|
+
elif op == "forget_cold":
|
|
397
|
+
print(json.dumps(db.forget_cold(conn, apply=args.apply), indent=2, sort_keys=True))
|
|
398
|
+
elif op == "promote":
|
|
399
|
+
print(json.dumps({"promotion": db.promote_hot(conn)}, indent=2, sort_keys=True))
|
|
400
|
+
elif op == "sleep":
|
|
401
|
+
print(json.dumps(db.sleep_pass(conn, apply=args.apply),
|
|
402
|
+
indent=2, sort_keys=True))
|
|
403
|
+
elif op == "reflect":
|
|
404
|
+
from . import experience
|
|
405
|
+
print(json.dumps(experience.reflect(conn, apply=args.apply),
|
|
406
|
+
indent=2, sort_keys=True))
|
|
407
|
+
elif op == "capture":
|
|
408
|
+
from . import capture
|
|
409
|
+
report = capture.capture_session(
|
|
410
|
+
db, conn, apply=args.apply, reflect=args.reflect,
|
|
411
|
+
staging=args.staging, session_id=getattr(args, "session", "") or "")
|
|
412
|
+
print(json.dumps({k: v for k, v in report.items() if k != "candidates"},
|
|
413
|
+
indent=2, sort_keys=True))
|
|
414
|
+
elif op == "ingest_md":
|
|
415
|
+
from . import md_ingest
|
|
416
|
+
print(json.dumps(md_ingest.ingest_md(conn, db, apply=args.apply),
|
|
417
|
+
indent=2, sort_keys=True))
|
|
418
|
+
elif op == "review":
|
|
419
|
+
# Same contract the MCP tool returns: the host agent is already an
|
|
420
|
+
# LLM, so this surfaces candidates plus the review rules rather
|
|
421
|
+
# than calling out to a model.
|
|
422
|
+
from . import capture
|
|
423
|
+
report = capture.capture_session(db, conn, apply=False)
|
|
424
|
+
print(json.dumps({"review_prompt": capture.REVIEW_PROMPT,
|
|
425
|
+
"candidates": report.get("candidates", [])},
|
|
426
|
+
indent=2, sort_keys=True))
|
|
427
|
+
elif op == "pending":
|
|
428
|
+
print(json.dumps(db.list_pending(conn), indent=2, sort_keys=True))
|
|
429
|
+
elif op in ("approve", "reject"):
|
|
430
|
+
if args.pending_id is None:
|
|
431
|
+
print(f"maintenance {op}: --pending-id is required", file=sys.stderr)
|
|
432
|
+
return 2
|
|
433
|
+
print(json.dumps(db.decide_pending(conn, args.pending_id,
|
|
434
|
+
approve=(op == "approve")),
|
|
435
|
+
indent=2, sort_keys=True))
|
|
436
|
+
elif op == "not_conflict":
|
|
437
|
+
if not args.a or not args.b:
|
|
438
|
+
print("maintenance not_conflict: --a and --b are required",
|
|
439
|
+
file=sys.stderr)
|
|
440
|
+
return 2
|
|
441
|
+
print(json.dumps(db.mark_not_conflict(conn, args.a, args.b),
|
|
442
|
+
indent=2, sort_keys=True))
|
|
443
|
+
else:
|
|
444
|
+
print(f"maintenance: unknown op {op}", file=sys.stderr)
|
|
445
|
+
return 2
|
|
446
|
+
finally:
|
|
447
|
+
conn.close()
|
|
448
|
+
return 0
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def cmd_promote(args) -> int:
|
|
452
|
+
"""Promote verified, confident inferences/facts to RULE records."""
|
|
453
|
+
conn = _open()
|
|
454
|
+
promoted = 0
|
|
455
|
+
try:
|
|
456
|
+
for row in db.list_records(conn, limit=10_000, project_id=args.project):
|
|
457
|
+
if row["type"] not in ("INFERENCE", "FACT"):
|
|
458
|
+
continue
|
|
459
|
+
if not row["verified"] or row["confidence"] < args.threshold:
|
|
460
|
+
continue
|
|
461
|
+
existing = db.find_record(conn, "RULE", row["content"], f"promote:{args.source}",
|
|
462
|
+
row["project_id"])
|
|
463
|
+
if existing:
|
|
464
|
+
continue
|
|
465
|
+
db.upsert_record(
|
|
466
|
+
conn, rtype="RULE", content=row["content"], evidence=row["evidence"],
|
|
467
|
+
verified=1, confidence=row["confidence"], source=f"promote:{args.source}",
|
|
468
|
+
tags=row["tags"], session_id=row["session_id"],
|
|
469
|
+
project_id=row["project_id"], parent_id=row["id"],
|
|
470
|
+
)
|
|
471
|
+
promoted += 1
|
|
472
|
+
print(f"promoted {row['id']} -> RULE: {row['content'][:80]}")
|
|
473
|
+
finally:
|
|
474
|
+
conn.close()
|
|
475
|
+
print(f"{promoted} record(s) promoted (threshold={args.threshold})")
|
|
476
|
+
return 0
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
# --- analyze ----------------------------------------------------------------
|
|
480
|
+
|
|
481
|
+
def cmd_analyze(args) -> int:
|
|
482
|
+
"""Detect recurring keywords across capture logs and record INFERENCE rows."""
|
|
483
|
+
sessions = _sessions_dir()
|
|
484
|
+
captures = []
|
|
485
|
+
if sessions.is_dir():
|
|
486
|
+
for path in sorted(sessions.glob("*.jsonl")):
|
|
487
|
+
try:
|
|
488
|
+
with path.open(encoding="utf-8") as fh:
|
|
489
|
+
for line in fh:
|
|
490
|
+
line = line.strip()
|
|
491
|
+
if not line:
|
|
492
|
+
continue
|
|
493
|
+
try:
|
|
494
|
+
captures.append(json.loads(line))
|
|
495
|
+
except json.JSONDecodeError:
|
|
496
|
+
continue
|
|
497
|
+
except OSError:
|
|
498
|
+
continue
|
|
499
|
+
|
|
500
|
+
stop = {
|
|
501
|
+
"the", "and", "for", "with", "from", "that", "this", "have", "has", "had",
|
|
502
|
+
"was", "were", "been", "will", "would", "could", "should", "may", "might",
|
|
503
|
+
"must", "can", "just", "also", "into", "onto", "over", "under", "after",
|
|
504
|
+
"before", "between", "through", "during", "without", "within", "about",
|
|
505
|
+
"against", "among", "upon", "toward", "towards", "across", "along",
|
|
506
|
+
"around", "behind", "below", "beneath", "beside", "besides", "per", "via",
|
|
507
|
+
"not", "yes", "okay",
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
import re
|
|
511
|
+
|
|
512
|
+
groups = {}
|
|
513
|
+
for cap in captures:
|
|
514
|
+
text = f"{cap.get('task', '')} {cap.get('outcome', '')}".lower()
|
|
515
|
+
for word in set(re.findall(r"[a-z0-9]{3,}", text)):
|
|
516
|
+
if word in stop:
|
|
517
|
+
continue
|
|
518
|
+
groups.setdefault(word, []).append(cap)
|
|
519
|
+
|
|
520
|
+
findings = []
|
|
521
|
+
for word, items in groups.items():
|
|
522
|
+
if len(items) < args.min_occurrences:
|
|
523
|
+
continue
|
|
524
|
+
findings.append({
|
|
525
|
+
"content": f"Recurring pattern '{word}': {len(items)} occurrences across sessions",
|
|
526
|
+
"evidence": "; ".join(f"{i.get('task', '')} -> {i.get('outcome', '')}" for i in items[:5]),
|
|
527
|
+
"confidence": min(0.5 + len(items) * 0.08, 0.95),
|
|
528
|
+
"tags": f"pattern,{word}",
|
|
529
|
+
})
|
|
530
|
+
|
|
531
|
+
for cap in captures:
|
|
532
|
+
if cap.get("type") == "CORRECTION":
|
|
533
|
+
findings.append({
|
|
534
|
+
"content": f"User correction: {cap.get('task', '')} -> {cap.get('outcome', '')}",
|
|
535
|
+
"evidence": cap.get("evidence") or "user correction",
|
|
536
|
+
"confidence": 0.8,
|
|
537
|
+
"tags": "correction,user-feedback",
|
|
538
|
+
})
|
|
539
|
+
|
|
540
|
+
conn = _open()
|
|
541
|
+
written = 0
|
|
542
|
+
try:
|
|
543
|
+
for finding in findings:
|
|
544
|
+
source = "analyze-session"
|
|
545
|
+
if db.find_record(conn, "INFERENCE", finding["content"], source, args.project or ""):
|
|
546
|
+
continue
|
|
547
|
+
db.upsert_record(
|
|
548
|
+
conn, rtype="INFERENCE", content=finding["content"],
|
|
549
|
+
evidence=finding["evidence"], verified=0,
|
|
550
|
+
confidence=finding["confidence"], source=source,
|
|
551
|
+
tags=finding["tags"], session_id=args.session or "",
|
|
552
|
+
project_id=args.project or "",
|
|
553
|
+
)
|
|
554
|
+
written += 1
|
|
555
|
+
total = db.stats(conn)["total"]
|
|
556
|
+
finally:
|
|
557
|
+
conn.close()
|
|
558
|
+
|
|
559
|
+
print(f"analyzed {len(captures)} captures, {len(groups)} keyword groups, {total} records")
|
|
560
|
+
print(f"wrote {written} new INFERENCE record(s)")
|
|
561
|
+
return 0
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
# --- ops: health / backup / repair / stats / disk ---------------------------
|
|
565
|
+
|
|
566
|
+
def cmd_health(args) -> int:
|
|
567
|
+
conn = _open()
|
|
568
|
+
try:
|
|
569
|
+
report = db.health(conn)
|
|
570
|
+
finally:
|
|
571
|
+
conn.close()
|
|
572
|
+
if args.json:
|
|
573
|
+
print(json.dumps(report, indent=2))
|
|
574
|
+
else:
|
|
575
|
+
print(f"status: {report['status']}")
|
|
576
|
+
print(f"db: {report['db_path']}")
|
|
577
|
+
print(f"records: {report['total_records']}")
|
|
578
|
+
print(f"backups: {report['backup_count']}")
|
|
579
|
+
return 0 if report["status"] == "ok" else 1
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def cmd_backup(args) -> int:
|
|
583
|
+
path = db.backup_db(db.DB_PATH)
|
|
584
|
+
if not path:
|
|
585
|
+
print("backup failed: database missing or unreadable", file=sys.stderr)
|
|
586
|
+
return 1
|
|
587
|
+
print(f"backup: {path}")
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def cmd_mirror(args) -> int:
|
|
591
|
+
out_dir = Path(args.dir).expanduser().resolve()
|
|
592
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
593
|
+
conn = _open()
|
|
594
|
+
try:
|
|
595
|
+
exported = db.export_markdown(conn, out_dir)
|
|
596
|
+
finally:
|
|
597
|
+
conn.close()
|
|
598
|
+
synced = db.sync_mirror(out_dir, message=args.message, init=args.init)
|
|
599
|
+
parts = [f"written={len(exported['written'])}", f"removed={len(exported['removed'])}",
|
|
600
|
+
f"unchanged={len(exported['unchanged'])}"]
|
|
601
|
+
if synced.get("committed"):
|
|
602
|
+
parts.append(f"committed={synced['sha'][:12]}")
|
|
603
|
+
else:
|
|
604
|
+
parts.append(f"git={synced.get('reason', 'clean')}")
|
|
605
|
+
print("mirror: " + ", ".join(parts))
|
|
606
|
+
return 0
|
|
607
|
+
|
|
608
|
+
def cmd_skill_export(args) -> int:
|
|
609
|
+
conn = _open()
|
|
610
|
+
try:
|
|
611
|
+
result = db.export_skill(conn, args.record_id, args.dir)
|
|
612
|
+
except (ValueError, db.NotFound) as e:
|
|
613
|
+
print(f"skill-export: {e}", file=sys.stderr)
|
|
614
|
+
return 1
|
|
615
|
+
finally:
|
|
616
|
+
conn.close()
|
|
617
|
+
print(f"skill-export: {result['dir']} ({len(result['references'])} references)")
|
|
618
|
+
return 0
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
def cmd_pack(args) -> int:
|
|
622
|
+
conn = _open()
|
|
623
|
+
try:
|
|
624
|
+
result = db.export_pack(conn, args.file)
|
|
625
|
+
finally:
|
|
626
|
+
conn.close()
|
|
627
|
+
print(f"pack: {result['records']} records -> {result['file']} "
|
|
628
|
+
f"({result['bytes']} bytes, sha256 {result['sha256'][:12]})")
|
|
629
|
+
return 0
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
def cmd_unpack(args) -> int:
|
|
633
|
+
conn = _open()
|
|
634
|
+
try:
|
|
635
|
+
result = db.import_pack(conn, args.file)
|
|
636
|
+
except (ValueError, OSError) as e:
|
|
637
|
+
print(f"unpack: {e}")
|
|
638
|
+
return 1
|
|
639
|
+
finally:
|
|
640
|
+
conn.close()
|
|
641
|
+
print(f"unpack: {result['imported']} new, {result['merged']} merged")
|
|
642
|
+
return 0
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
def cmd_repair(args) -> int:
|
|
646
|
+
ok = db.repair_from_backup(db.DB_PATH)
|
|
647
|
+
print("repair: ok" if ok else "repair: failed, no usable backup")
|
|
648
|
+
return 0 if ok else 1
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def cmd_stats(args) -> int:
|
|
652
|
+
conn = _open()
|
|
653
|
+
try:
|
|
654
|
+
data = db.stats(conn)
|
|
655
|
+
# Instrumentation the roadmap asks for: if recall is never called, the
|
|
656
|
+
# memory cannot help, and that has to be visible in a number.
|
|
657
|
+
data["usage"] = {
|
|
658
|
+
"recall_events": conn.execute(
|
|
659
|
+
"SELECT count(*) FROM recall_events").fetchone()[0],
|
|
660
|
+
"sessions_with_recall": conn.execute(
|
|
661
|
+
"SELECT count(DISTINCT session_id) FROM recall_events"
|
|
662
|
+
" WHERE session_id <> ''").fetchone()[0],
|
|
663
|
+
"outcome_events": conn.execute(
|
|
664
|
+
"SELECT count(*) FROM outcome_events").fetchone()[0],
|
|
665
|
+
}
|
|
666
|
+
finally:
|
|
667
|
+
conn.close()
|
|
668
|
+
print(json.dumps(data, indent=2))
|
|
669
|
+
return 0
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def cmd_doctor(args) -> int:
|
|
673
|
+
"""One command that answers 'is this installation healthy'."""
|
|
674
|
+
import sqlite3
|
|
675
|
+
from . import __version__
|
|
676
|
+
report = {"package_version": __version__,
|
|
677
|
+
"python": sys.version.split()[0],
|
|
678
|
+
"sqlite": sqlite3.sqlite_version}
|
|
679
|
+
conn = None
|
|
680
|
+
try:
|
|
681
|
+
conn = db.connect()
|
|
682
|
+
db.init_db(conn)
|
|
683
|
+
path = Path(db.DB_PATH)
|
|
684
|
+
report["db_path"] = str(path)
|
|
685
|
+
report["db_exists"] = path.is_file()
|
|
686
|
+
report["schema_version"] = conn.execute(
|
|
687
|
+
"SELECT version FROM schema_version").fetchone()[0]
|
|
688
|
+
report["records"] = conn.execute("SELECT count(*) FROM records").fetchone()[0]
|
|
689
|
+
report["fts_rows"] = conn.execute(
|
|
690
|
+
"SELECT count(*) FROM records_fts").fetchone()[0]
|
|
691
|
+
report["fts_in_sync"] = report["fts_rows"] == report["records"]
|
|
692
|
+
report["quick_check"] = db.quick_check(conn)
|
|
693
|
+
if path.is_file():
|
|
694
|
+
mode = path.stat().st_mode & 0o777
|
|
695
|
+
report["db_mode"] = oct(mode)
|
|
696
|
+
report["db_private"] = mode & 0o077 == 0
|
|
697
|
+
except Exception as exc: # doctor reports, it does not crash
|
|
698
|
+
report["error"] = str(exc)
|
|
699
|
+
finally:
|
|
700
|
+
if conn is not None:
|
|
701
|
+
conn.close()
|
|
702
|
+
try:
|
|
703
|
+
report["disk_free_mb"] = shutil.disk_usage(
|
|
704
|
+
str(Path(db.DB_PATH).parent)).free // (1024 * 1024)
|
|
705
|
+
except OSError:
|
|
706
|
+
report["disk_free_mb"] = None
|
|
707
|
+
from . import hooks
|
|
708
|
+
settings = hooks.settings_path()
|
|
709
|
+
report["agent_hooks"] = {"settings": str(settings),
|
|
710
|
+
"installed": settings.is_file()
|
|
711
|
+
and "session-start" in settings.read_text(
|
|
712
|
+
encoding="utf-8", errors="replace")}
|
|
713
|
+
fts_ok = True
|
|
714
|
+
try:
|
|
715
|
+
probe = sqlite3.connect(":memory:")
|
|
716
|
+
probe.execute("CREATE VIRTUAL TABLE t USING fts5(x)")
|
|
717
|
+
probe.close()
|
|
718
|
+
except sqlite3.OperationalError:
|
|
719
|
+
fts_ok = False
|
|
720
|
+
report["fts5_available"] = fts_ok
|
|
721
|
+
if args.json:
|
|
722
|
+
print(json.dumps(report, indent=2, sort_keys=True))
|
|
723
|
+
else:
|
|
724
|
+
for key in ("package_version", "python", "sqlite", "fts5_available",
|
|
725
|
+
"db_path", "db_mode", "db_private", "schema_version",
|
|
726
|
+
"records", "fts_rows", "fts_in_sync", "quick_check",
|
|
727
|
+
"disk_free_mb"):
|
|
728
|
+
print(f"{key:16s} {report.get(key)}")
|
|
729
|
+
hooks_info = report.get("agent_hooks", {})
|
|
730
|
+
print(f"{'agent_hooks':16s} {hooks_info.get('installed')} "
|
|
731
|
+
f"({hooks_info.get('settings')})")
|
|
732
|
+
if report.get("error"):
|
|
733
|
+
print(f"{'error':16s} {report['error']}")
|
|
734
|
+
return 0 if report.get("quick_check") and not report.get("error") else 1
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
def cmd_install_hooks(args) -> int:
|
|
738
|
+
from . import hooks
|
|
739
|
+
report = hooks.install_claude_code(dry_run=args.dry_run,
|
|
740
|
+
uninstall=args.uninstall)
|
|
741
|
+
if report.get("error"):
|
|
742
|
+
print(f"install-hooks: {report['error']}", file=sys.stderr)
|
|
743
|
+
return 1
|
|
744
|
+
if args.dry_run:
|
|
745
|
+
print(f"would {report['plan']} in {report['path']}")
|
|
746
|
+
if report.get("changed"):
|
|
747
|
+
print("--- before ---")
|
|
748
|
+
print(report.get("before") or "(absent)")
|
|
749
|
+
print("--- after ---")
|
|
750
|
+
print(report.get("after") or "(absent)")
|
|
751
|
+
return 0
|
|
752
|
+
action = "updated" if report["changed"] else "already current"
|
|
753
|
+
print(f"{report['path']}: {action} ({report['plan']})")
|
|
754
|
+
return 0
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
def cmd_hook(args) -> int:
|
|
758
|
+
"""Entry point a host calls. Reads JSON on stdin, writes a digest on stdout."""
|
|
759
|
+
from . import hooks
|
|
760
|
+
payload = hooks.read_payload()
|
|
761
|
+
if args.action == "session-start":
|
|
762
|
+
block = hooks.session_start(payload)
|
|
763
|
+
if block:
|
|
764
|
+
print(block)
|
|
765
|
+
return 0
|
|
766
|
+
report = hooks.session_end(payload)
|
|
767
|
+
if report.get("skipped"):
|
|
768
|
+
print(f"[honcho] {report['skipped']}", file=sys.stderr)
|
|
769
|
+
return 0
|
|
770
|
+
print(f"[honcho] captured: {json.dumps({k: report.get(k) for k in
|
|
771
|
+
('written', 'staged', 'quarantined')})}", file=sys.stderr)
|
|
772
|
+
return 0
|
|
773
|
+
|
|
774
|
+
def cmd_digest(args) -> int:
|
|
775
|
+
conn = _open()
|
|
776
|
+
try:
|
|
777
|
+
d = db.digest(conn, budget=args.budget, project_id=args.project)
|
|
778
|
+
finally:
|
|
779
|
+
conn.close()
|
|
780
|
+
print(d["text"])
|
|
781
|
+
return 0
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
def cmd_disk(args) -> int:
|
|
785
|
+
ok = _check_disk(args.min_free_mb)
|
|
786
|
+
try:
|
|
787
|
+
usage = shutil.disk_usage(str(_memory_dir()))
|
|
788
|
+
free_mb = usage.free // (1024 * 1024)
|
|
789
|
+
except OSError:
|
|
790
|
+
free_mb = 0
|
|
791
|
+
if args.json:
|
|
792
|
+
print(json.dumps({"available_mb": free_mb, "min_required_mb": args.min_free_mb, "ok": ok}))
|
|
793
|
+
else:
|
|
794
|
+
print(f"{'ok' if ok else 'warning'}: {free_mb}MB free (need {args.min_free_mb}MB)")
|
|
795
|
+
return 0 if ok else 1
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
def cmd_checkpoint(args) -> int:
|
|
799
|
+
conn = _open()
|
|
800
|
+
try:
|
|
801
|
+
cp = db.create_pre_compress_checkpoint(
|
|
802
|
+
conn, session_id=args.session, project_id=args.project or "",
|
|
803
|
+
evidence_hash=args.evidence_hash or "",
|
|
804
|
+
)
|
|
805
|
+
finally:
|
|
806
|
+
conn.close()
|
|
807
|
+
print(json.dumps(cp, indent=2))
|
|
808
|
+
return 0
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
def cmd_restore(args) -> int:
|
|
812
|
+
conn = _open()
|
|
813
|
+
try:
|
|
814
|
+
result = db.restore_from_checkpoint(conn, args.checkpoint_id)
|
|
815
|
+
except ValueError as exc:
|
|
816
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
817
|
+
return 1
|
|
818
|
+
finally:
|
|
819
|
+
conn.close()
|
|
820
|
+
print(json.dumps(result, indent=2))
|
|
821
|
+
return 0
|
|
822
|
+
|
|
823
|
+
|
|
824
|
+
# --- parser -----------------------------------------------------------------
|
|
825
|
+
|
|
826
|
+
|
|
827
|
+
def cmd_overview(args) -> int:
|
|
828
|
+
from . import web
|
|
829
|
+
|
|
830
|
+
return web.main(["--port", str(args.port)] + (["--no-open"] if args.no_open else []))
|
|
831
|
+
|
|
832
|
+
|
|
833
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
834
|
+
parser = argparse.ArgumentParser(
|
|
835
|
+
prog="omp-memory",
|
|
836
|
+
description="Local-first SQLite memory for coding agents.",
|
|
837
|
+
)
|
|
838
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
839
|
+
|
|
840
|
+
p = sub.add_parser("capture", help="record a task -> outcome lesson")
|
|
841
|
+
p.add_argument("--task", required=True)
|
|
842
|
+
p.add_argument("--outcome", required=True)
|
|
843
|
+
p.add_argument("--type", default="FACT", choices=sorted(db.VALID_TYPES))
|
|
844
|
+
p.add_argument("--evidence", default="")
|
|
845
|
+
p.add_argument("--verified", action="store_true")
|
|
846
|
+
p.add_argument("--confidence", type=float, default=0.5)
|
|
847
|
+
p.add_argument("--source", default="session-capture")
|
|
848
|
+
p.add_argument("--tags", default="")
|
|
849
|
+
p.add_argument("--project", default="")
|
|
850
|
+
p.add_argument("--session", default="")
|
|
851
|
+
p.add_argument("--parent-id", default="")
|
|
852
|
+
p.add_argument("--min-free-mb", type=int, default=DEFAULT_MIN_FREE_MB)
|
|
853
|
+
p.add_argument("--allow-secrets", action="store_true")
|
|
854
|
+
p.add_argument("--no-audit", action="store_true")
|
|
855
|
+
p.set_defaults(func=cmd_capture)
|
|
856
|
+
|
|
857
|
+
p = sub.add_parser("search", help="full-text search")
|
|
858
|
+
p.add_argument("query")
|
|
859
|
+
p.add_argument("--limit", type=int, default=20)
|
|
860
|
+
p.add_argument("--type", default=None, choices=sorted(db.VALID_TYPES))
|
|
861
|
+
p.add_argument("--project", default=None)
|
|
862
|
+
p.add_argument("--verified", action="store_true")
|
|
863
|
+
p.add_argument("--min-confidence", type=float, default=0.0)
|
|
864
|
+
p.add_argument("--as-of", default=None,
|
|
865
|
+
help="ISO timestamp: what was true then")
|
|
866
|
+
p.add_argument("--expand", type=int, default=0,
|
|
867
|
+
help="window size; each hit gains temporally adjacent records")
|
|
868
|
+
p.add_argument("--explain", action="store_true",
|
|
869
|
+
help="show the score decomposition")
|
|
870
|
+
p.add_argument("--session", default=None,
|
|
871
|
+
help="restrict to one capture session")
|
|
872
|
+
p.add_argument("--brief", action="store_true",
|
|
873
|
+
help="L0 index: id, type and first line only, with a token "
|
|
874
|
+
"estimate (same shape as the MCP recall brief)")
|
|
875
|
+
p.add_argument("--json", action="store_true")
|
|
876
|
+
p.set_defaults(func=cmd_search)
|
|
877
|
+
|
|
878
|
+
p = sub.add_parser("recap", help="summarise a session or project")
|
|
879
|
+
p.add_argument("--session", default=None)
|
|
880
|
+
p.add_argument("--project", default=None)
|
|
881
|
+
p.add_argument("--limit", type=int, default=50)
|
|
882
|
+
p.add_argument("--json", action="store_true")
|
|
883
|
+
p.set_defaults(func=cmd_recap)
|
|
884
|
+
|
|
885
|
+
p = sub.add_parser("context", help="emit a fenced memory-context block")
|
|
886
|
+
p.add_argument("query")
|
|
887
|
+
p.add_argument("--limit", type=int, default=5)
|
|
888
|
+
p.add_argument("--project", default=None)
|
|
889
|
+
p.set_defaults(func=cmd_context)
|
|
890
|
+
|
|
891
|
+
p = sub.add_parser("reinforce", help="apply a reinforcement signal")
|
|
892
|
+
p.add_argument("record_id")
|
|
893
|
+
p.add_argument("signal", choices=sorted(db.VALID_SIGNALS))
|
|
894
|
+
p.add_argument("--delta", type=float, default=None)
|
|
895
|
+
p.add_argument("--source", default="")
|
|
896
|
+
p.add_argument("--content", default=None,
|
|
897
|
+
help="correction only: the corrected statement")
|
|
898
|
+
p.add_argument("--evidence", default=None,
|
|
899
|
+
help="why the correction is true")
|
|
900
|
+
p.set_defaults(func=cmd_reinforce)
|
|
901
|
+
|
|
902
|
+
p = sub.add_parser("verify", help="re-check structured evidence and demote stale attestations")
|
|
903
|
+
p.add_argument("--repo", default=None, help="repository root for file and commit evidence")
|
|
904
|
+
p.add_argument("--record-id", default=None)
|
|
905
|
+
p.add_argument("--project", default=None)
|
|
906
|
+
p.add_argument("--dry-run", action="store_true")
|
|
907
|
+
p.add_argument("--json", action="store_true")
|
|
908
|
+
p.set_defaults(func=cmd_verify)
|
|
909
|
+
|
|
910
|
+
p = sub.add_parser("calibrate", help="confidence vs observed outcomes: Brier and ECE")
|
|
911
|
+
p.add_argument("--min-samples", type=int, default=None)
|
|
912
|
+
p.add_argument("--json", action="store_true")
|
|
913
|
+
p.set_defaults(func=cmd_calibrate)
|
|
914
|
+
|
|
915
|
+
p = sub.add_parser("outcome", help="record an objective outcome for credit assignment")
|
|
916
|
+
p.add_argument("kind", choices=sorted(db.OUTCOME_KINDS))
|
|
917
|
+
p.add_argument("--session", default=None)
|
|
918
|
+
p.add_argument("--evidence-ref", default=None)
|
|
919
|
+
p.set_defaults(func=cmd_outcome)
|
|
920
|
+
|
|
921
|
+
p = sub.add_parser("attest", help="mark a record operator-attested (agent records cannot self-verify)")
|
|
922
|
+
p.add_argument("record_id")
|
|
923
|
+
p.add_argument("--evidence", required=True,
|
|
924
|
+
help="what you checked, outside the agent's own claim")
|
|
925
|
+
p.set_defaults(func=cmd_attest)
|
|
926
|
+
|
|
927
|
+
p = sub.add_parser("promote", help="promote verified records to RULE")
|
|
928
|
+
p.add_argument("--threshold", type=float, default=0.85)
|
|
929
|
+
p.add_argument("--project", default=None)
|
|
930
|
+
p.add_argument("--source", default="promote")
|
|
931
|
+
p.set_defaults(func=cmd_promote)
|
|
932
|
+
|
|
933
|
+
p = sub.add_parser("analyze", help="derive INFERENCE rows from capture logs")
|
|
934
|
+
p.add_argument("--project", default=None)
|
|
935
|
+
p.add_argument("--session", default=None)
|
|
936
|
+
p.add_argument("--min-occurrences", type=int, default=2)
|
|
937
|
+
p.set_defaults(func=cmd_analyze)
|
|
938
|
+
|
|
939
|
+
p = sub.add_parser("health", help="health report")
|
|
940
|
+
p.add_argument("--json", action="store_true")
|
|
941
|
+
p.set_defaults(func=cmd_health)
|
|
942
|
+
|
|
943
|
+
p = sub.add_parser("doctor", help="installation health: versions, DB, FTS, hooks")
|
|
944
|
+
p.add_argument("--json", action="store_true")
|
|
945
|
+
p.set_defaults(func=cmd_doctor)
|
|
946
|
+
|
|
947
|
+
p = sub.add_parser("install-hooks", help="wire SessionStart/SessionEnd hooks into an agent")
|
|
948
|
+
p.add_argument("--agent", default="claude-code", choices=["claude-code"])
|
|
949
|
+
p.add_argument("--dry-run", action="store_true")
|
|
950
|
+
p.add_argument("--uninstall", action="store_true")
|
|
951
|
+
p.set_defaults(func=cmd_install_hooks)
|
|
952
|
+
|
|
953
|
+
p = sub.add_parser("hook", help="run one agent hook (reads JSON on stdin)")
|
|
954
|
+
p.add_argument("action", choices=["session-start", "session-end"])
|
|
955
|
+
p.set_defaults(func=cmd_hook)
|
|
956
|
+
|
|
957
|
+
p = sub.add_parser("stats", help="record counts by type")
|
|
958
|
+
p.set_defaults(func=cmd_stats)
|
|
959
|
+
|
|
960
|
+
p = sub.add_parser("digest", help="always-in-context memory block (char budget)")
|
|
961
|
+
p.add_argument("--budget", type=int, default=2000)
|
|
962
|
+
p.add_argument("--project", default=None)
|
|
963
|
+
p.set_defaults(func=cmd_digest)
|
|
964
|
+
|
|
965
|
+
p = sub.add_parser("maintenance",
|
|
966
|
+
help="maintenance ops (same set the MCP server exposes)")
|
|
967
|
+
p.add_argument("op", choices=["decay", "forget_cold", "promote", "sleep",
|
|
968
|
+
"reflect", "capture", "ingest_md", "review", "pending",
|
|
969
|
+
"approve", "reject", "not_conflict"])
|
|
970
|
+
p.add_argument("--apply", action="store_true",
|
|
971
|
+
help="write changes (default: report only)")
|
|
972
|
+
p.add_argument("--reflect", action="store_true",
|
|
973
|
+
help="capture: run the abstraction pass afterwards")
|
|
974
|
+
p.add_argument("--staging", action="store_true",
|
|
975
|
+
help="capture: park candidates for review instead of writing")
|
|
976
|
+
p.add_argument("--pending-id", type=int, default=None,
|
|
977
|
+
help="approve/reject: the pending write id")
|
|
978
|
+
p.add_argument("--a", default=None, help="not_conflict: first record id")
|
|
979
|
+
p.add_argument("--b", default=None, help="not_conflict: second record id")
|
|
980
|
+
p.set_defaults(func=cmd_maintenance)
|
|
981
|
+
p = sub.add_parser("backup", help="consistent snapshot")
|
|
982
|
+
p.set_defaults(func=cmd_backup)
|
|
983
|
+
|
|
984
|
+
p = sub.add_parser("repair", help="restore from newest usable backup")
|
|
985
|
+
p.set_defaults(func=cmd_repair)
|
|
986
|
+
p = sub.add_parser("mirror", help="export records to markdown and commit to a git mirror")
|
|
987
|
+
p.add_argument("dir", help="mirror directory (created if missing)")
|
|
988
|
+
p.add_argument("-m", "--message", default=None, help="git commit message")
|
|
989
|
+
p.add_argument("--init", action="store_true",
|
|
990
|
+
help="git init the directory when it is not a repository yet")
|
|
991
|
+
p.set_defaults(func=cmd_mirror)
|
|
992
|
+
|
|
993
|
+
p = sub.add_parser("skill-export", help="export a procedural record as an agentskills.io SKILL.md")
|
|
994
|
+
p.add_argument("record_id")
|
|
995
|
+
p.add_argument("dir", help="output directory (skill folder created inside)")
|
|
996
|
+
p.set_defaults(func=cmd_skill_export)
|
|
997
|
+
|
|
998
|
+
p = sub.add_parser("pack", help="export the store as a compressed sync pack")
|
|
999
|
+
p.add_argument("file", help="output .pack file (committable to a team repo)")
|
|
1000
|
+
p.set_defaults(func=cmd_pack)
|
|
1001
|
+
|
|
1002
|
+
p = sub.add_parser("unpack", help="import a sync pack (content-identity merge)")
|
|
1003
|
+
p.add_argument("file", help="pack file to import")
|
|
1004
|
+
p.set_defaults(func=cmd_unpack)
|
|
1005
|
+
|
|
1006
|
+
p = sub.add_parser("disk", help="check free space")
|
|
1007
|
+
p.add_argument("min_free_mb", type=int, nargs="?", default=DEFAULT_MIN_FREE_MB)
|
|
1008
|
+
p.add_argument("--json", action="store_true")
|
|
1009
|
+
p.set_defaults(func=cmd_disk)
|
|
1010
|
+
|
|
1011
|
+
p = sub.add_parser("scan", help="scan text or stdin for secrets")
|
|
1012
|
+
p.add_argument("text", nargs="?", default="")
|
|
1013
|
+
p.set_defaults(func=cmd_scan)
|
|
1014
|
+
|
|
1015
|
+
p = sub.add_parser("overview", help="open the interactive graph view in a browser")
|
|
1016
|
+
p.add_argument("--port", type=int, default=4173)
|
|
1017
|
+
p.add_argument("--no-open", action="store_true")
|
|
1018
|
+
p.set_defaults(func=cmd_overview)
|
|
1019
|
+
|
|
1020
|
+
p = sub.add_parser("checkpoint", help="snapshot session evidence before compression")
|
|
1021
|
+
p.add_argument("--session", required=True)
|
|
1022
|
+
p.add_argument("--project", default="")
|
|
1023
|
+
p.add_argument("--evidence-hash", default="")
|
|
1024
|
+
p.set_defaults(func=cmd_checkpoint)
|
|
1025
|
+
|
|
1026
|
+
p = sub.add_parser("restore", help="restore a pre-compress checkpoint")
|
|
1027
|
+
p.add_argument("checkpoint_id")
|
|
1028
|
+
p.set_defaults(func=cmd_restore)
|
|
1029
|
+
|
|
1030
|
+
return parser
|
|
1031
|
+
|
|
1032
|
+
|
|
1033
|
+
def main(argv=None) -> int:
|
|
1034
|
+
args = build_parser().parse_args(argv)
|
|
1035
|
+
try:
|
|
1036
|
+
return args.func(args)
|
|
1037
|
+
except BrokenPipeError:
|
|
1038
|
+
return 0
|
|
1039
|
+
except Exception as exc: # noqa: BLE001 - CLI boundary
|
|
1040
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
1041
|
+
return 1
|
|
1042
|
+
|
|
1043
|
+
|
|
1044
|
+
if __name__ == "__main__":
|
|
1045
|
+
sys.exit(main())
|