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/capture.py
ADDED
|
@@ -0,0 +1,658 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Capture lessons from OMP session logs into honcho memory.
|
|
3
|
+
|
|
4
|
+
This module is intentionally harness-specific: it reads OMP's session log
|
|
5
|
+
format (message/role/user, message/role/toolResult, custom/input/path,
|
|
6
|
+
model_change). The logic is copied from handoff.py so the repo stays
|
|
7
|
+
independent of any particular harness while the extraction quality matches.
|
|
8
|
+
|
|
9
|
+
Usage (MCP):
|
|
10
|
+
maintenance {"op": "capture"}
|
|
11
|
+
maintenance {"op": "capture", "apply": true} # write to DB
|
|
12
|
+
maintenance {"op": "capture", "reflect": true} # + reflect pass
|
|
13
|
+
|
|
14
|
+
The harness's session log lives in:
|
|
15
|
+
~/.omp/profiles/<profile>/agent/sessions/<project-slug>/<ts>_<id>.jsonl
|
|
16
|
+
OMP_MEMORY_SESSIONS overrides the sessions root.
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
# The review contract, kept here so the MCP tool and the CLI op cannot drift
|
|
21
|
+
# apart: both surfaces must ask the host agent for the same judgements. The
|
|
22
|
+
# host agent is already an LLM, so this engine never calls out to one.
|
|
23
|
+
REVIEW_PROMPT = (
|
|
24
|
+
"Review these candidate lessons from the session. For each: "
|
|
25
|
+
"(1) GROUNDING: is it supported by what actually happened, "
|
|
26
|
+
"not by what the agent wished happened? "
|
|
27
|
+
"(2) ROUTING: durable knowledge -> remember (FACT only if "
|
|
28
|
+
"verified, else INFERENCE); user preference -> about_peer; "
|
|
29
|
+
"one-off noise -> drop. "
|
|
30
|
+
"(3) DO NOT CAPTURE: environment failures (command not "
|
|
31
|
+
"found, missing credentials), unfixed complaints, secrets, "
|
|
32
|
+
"or anything already in memory (recall first, read before "
|
|
33
|
+
"write). "
|
|
34
|
+
"(4) If a candidate corrects an existing record, use "
|
|
35
|
+
"reinforce correction with evidence, not a new row."
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
import json
|
|
39
|
+
import os
|
|
40
|
+
import re
|
|
41
|
+
import sys
|
|
42
|
+
from collections import OrderedDict
|
|
43
|
+
from datetime import datetime, timezone
|
|
44
|
+
from pathlib import Path
|
|
45
|
+
from typing import Any
|
|
46
|
+
|
|
47
|
+
# Re-export for convenience
|
|
48
|
+
__all__ = ["extract_lessons", "capture_session", "sessions_dir"]
|
|
49
|
+
|
|
50
|
+
# ---------------------------------------------------------------------------
|
|
51
|
+
# Paths
|
|
52
|
+
# ---------------------------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
_FAILURE_RE = re.compile(
|
|
55
|
+
r"(exited with code [1-9]"
|
|
56
|
+
r"|exit code [1-9]"
|
|
57
|
+
r"|traceback \(most recent call last\)"
|
|
58
|
+
r"|\b\w+(?:Error|Exception)\b\s*:"
|
|
59
|
+
r"|\bHTTP (?:Error \d{3}|\d{3})"
|
|
60
|
+
r"|\b\d{3} (?:Not Found|Internal Server Error|Bad Gateway|Service Unavailable)"
|
|
61
|
+
r"|\"failed\":\s*[1-9]"
|
|
62
|
+
r"|\b[1-9][0-9]* failed\b"
|
|
63
|
+
r"|\berror:)"
|
|
64
|
+
, re.I
|
|
65
|
+
)
|
|
66
|
+
# A failure line is a lesson only when it names the error type. Bare
|
|
67
|
+
# "Command exited with code N", parse-error fragments, and echoed error
|
|
68
|
+
# text from a script under test are noise, not knowledge.
|
|
69
|
+
_LESSON_RE = re.compile(
|
|
70
|
+
r"(?i:(?<!except )(?<!raise )\b(?!isError\b)(?!STATUS_)\w+(?:Error|Exception)\b\s*:)"
|
|
71
|
+
r"|\bFAILED\s+\S+"
|
|
72
|
+
r"|\bE\s+[A-Z]\w+"
|
|
73
|
+
r"|\bTraceback"
|
|
74
|
+
)
|
|
75
|
+
# `FAILED tests/...` is pytest output: the agent running its own suite.
|
|
76
|
+
# The fix lands in the commit, not in memory, so candidates matching this
|
|
77
|
+
# shape are dropped in the failure loop. Assertion errors from other
|
|
78
|
+
# tooling (no tests/ path) still carry a real lesson.
|
|
79
|
+
_PYTEST_RE = re.compile(r"\bFAILED\s+(?:\./)?(?:tests?|test)/\S+")
|
|
80
|
+
# Lines that merely name an exception (except clauses, raise statements)
|
|
81
|
+
# are source code under test, not an outcome.
|
|
82
|
+
_NOISE_RE = re.compile(r"(?:^|\b\w+:\s)\s*(?:except|raise)\s+\S*?(?:Error|Exception)\b", re.I)
|
|
83
|
+
# Anti-hoarding (ported from hermes-agent _DO_NOT_CAPTURE_BLOCK, itself
|
|
84
|
+
# distilled from production issues): environment-dependent failures and
|
|
85
|
+
# unfixed complaints are not lessons. "command not found" is a missing
|
|
86
|
+
# install, not knowledge; "X does not work" without a verified fix is a
|
|
87
|
+
# complaint that would decay into confidently-wrong memory.
|
|
88
|
+
_ENV_FAILURE_RE = re.compile(
|
|
89
|
+
r"(?i)\b(?:command not found|no such file or directory|not recognized as|"
|
|
90
|
+
r"permission denied|connection refused|network is unreachable|"
|
|
91
|
+
r"could not resolve host|module not found|no module named|"
|
|
92
|
+
r"credential|not logged in|unauthorized|econnrefused|enotfound)\b"
|
|
93
|
+
)
|
|
94
|
+
_UNFIXED_COMPLAINT_RE = re.compile(
|
|
95
|
+
r"(?i)\b(?:does not work|doesn't work|is broken|still failing|still broken|"
|
|
96
|
+
r"not working|keeps failing)\b"
|
|
97
|
+
)
|
|
98
|
+
# Tools whose output is content, not an outcome: reading a file that mentions
|
|
99
|
+
# an error is not a failure. Only execution tools can fail.
|
|
100
|
+
_READ_TOOLS = {"read", "grep", "glob", "view", "search"}
|
|
101
|
+
_CONTENT_SKIP = re.compile(
|
|
102
|
+
r"^\[(?:HANDOFF|System note)\]|\brecalled memory context\b"
|
|
103
|
+
r"|\bObserved failure:", re.I
|
|
104
|
+
)
|
|
105
|
+
_TOKEN_RE = re.compile(r"\w{3,}")
|
|
106
|
+
_DEFAULT_SESSIONS = "" # empty = auto from env
|
|
107
|
+
|
|
108
|
+
# Keep at module level so callers can mutate before calling extract()
|
|
109
|
+
CAPTURE_DEFAULT_CONFIDENCE = 0.35
|
|
110
|
+
# Auto-captured lessons are pattern-matched from a transcript, not
|
|
111
|
+
# verified by anyone: clamp them well below the trust bar so a noisy
|
|
112
|
+
# session cannot outrank a confirmed fact.
|
|
113
|
+
CAPTURE_CONFIDENCE_CEILING = 0.6
|
|
114
|
+
CAPTURE_DEFAULT_TYPE = "INFERENCE"
|
|
115
|
+
MAX_FAILURES_STORED = 8
|
|
116
|
+
MAX_FILES_STORED = 30
|
|
117
|
+
MAX_FAIL_REPORTED = 8
|
|
118
|
+
MAX_FILE_REPORTED = 30
|
|
119
|
+
|
|
120
|
+
# Event segmentation (Wave F, EM-LLM 2407.9450): a session log is not one
|
|
121
|
+
# memory episode. Split on time gaps or topic shifts so a failure in a
|
|
122
|
+
# midnight deploy session does not inherit the tags of the refactor that
|
|
123
|
+
# followed at breakfast.
|
|
124
|
+
EVENT_GAP_MINUTES = 30.0
|
|
125
|
+
EVENT_TOPIC_OVERLAP = 0.2
|
|
126
|
+
EVENT_TAG_PREFIX = "event:"
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# Secret-shape patterns, shared by the CLI capture guard and the auto-capture
|
|
130
|
+
# pipeline. Patterns run in Python so the payload never reaches a shell.
|
|
131
|
+
SECRET_PATTERNS = [
|
|
132
|
+
("api_key", r"sk-[A-Za-z0-9_\-]{8,}"),
|
|
133
|
+
("api_key", r"(?:sk|pk)_(?:live|test)_[A-Za-z0-9]{8,}"),
|
|
134
|
+
("github_token", r"ghp_[A-Za-z0-9]{20,}"),
|
|
135
|
+
("aws_key", r"AKIA[0-9A-Z]{16}"),
|
|
136
|
+
("bearer", r"(?i)bearer\s+[A-Za-z0-9._-]{20,}"),
|
|
137
|
+
("private_key", r"-----BEGIN [A-Z ]+PRIVATE KEY-----"),
|
|
138
|
+
("assignment", r"(?i)(?:password|passwd|secret|api_key|apikey|token|credential)\s*[=:]\s*\S{6,}"),
|
|
139
|
+
]
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# Instructions that should never travel from memory into an agent's context as
|
|
143
|
+
# if they were policy. Heuristic, not a guarantee: it exists so an injected
|
|
144
|
+
# rule is quarantined for a human instead of silently obeyed. A pattern that
|
|
145
|
+
# merely mentions a destructive command ("never run rm -rf on the data dir")
|
|
146
|
+
# still matches, which is why a hit routes to review rather than deletion.
|
|
147
|
+
DANGEROUS_PATTERNS = [
|
|
148
|
+
("pipe_to_shell",
|
|
149
|
+
r"(?i)\b(?:curl|wget)\b[^\n]{0,200}\|\s*(?:sudo\s+)?(?:bash|sh|zsh|python3?|perl)\b"),
|
|
150
|
+
("destructive",
|
|
151
|
+
r"(?i)\brm\s+-rf?\b|\bgit\s+push\s+(?:--force|-f)\b"
|
|
152
|
+
r"|\bdrop\s+(?:table|database)\b|\bmkfs\b|\bdd\s+if=.*of=/dev/"),
|
|
153
|
+
("exfiltration",
|
|
154
|
+
r"(?i)\b(?:curl|wget|nc|ncat|scp|rsync)\b[^\n]{0,200}"
|
|
155
|
+
r"(?:\.env|id_rsa|id_ed25519|aws_secret|api[_-]?key|bearer\s+[A-Za-z0-9])"),
|
|
156
|
+
("override",
|
|
157
|
+
r"(?i)\bignore\s+(?:all\s+)?(?:the\s+)?(?:previous|prior|above)\b"
|
|
158
|
+
r"|\bdisable\s+(?:the\s+)?(?:audit|logging|monitoring|review|approval"
|
|
159
|
+
r"|auth|mfa|2fa)\b"
|
|
160
|
+
r"|\bdisregard\s+(?:the\s+)?(?:previous|prior|system)\b"
|
|
161
|
+
r"|\bskip\s+(?:the\s+)?(?:tests?|linters?|verification)\b"
|
|
162
|
+
r"|\bdisable\s+(?:safety|verification|checks?)\b"
|
|
163
|
+
r"|\bapprove\s+(?:every|all)\s+\w+\s+without\s+review\b"),
|
|
164
|
+
]
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def dangerous_instructions(text: str) -> list:
|
|
168
|
+
"""Return [(kind, fragment)] for instruction-shaped content."""
|
|
169
|
+
found = []
|
|
170
|
+
for kind, pattern in DANGEROUS_PATTERNS:
|
|
171
|
+
match = re.search(pattern, text or "")
|
|
172
|
+
if match:
|
|
173
|
+
found.append((kind, match.group(0)[:60]))
|
|
174
|
+
return found
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def scan_text(text: str) -> list:
|
|
178
|
+
"""Return [(kind, matched_fragment)] for secret-looking input."""
|
|
179
|
+
findings = []
|
|
180
|
+
for kind, pattern in SECRET_PATTERNS:
|
|
181
|
+
match = re.search(pattern, text or "")
|
|
182
|
+
if match:
|
|
183
|
+
findings.append((kind, match.group(0)[:24]))
|
|
184
|
+
return findings
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _agent_dir() -> Path:
|
|
188
|
+
explicit = os.environ.get("PI_CODING_AGENT_DIR")
|
|
189
|
+
if explicit:
|
|
190
|
+
return Path(explicit)
|
|
191
|
+
profile = os.environ.get("OMP_PROFILE") or "default"
|
|
192
|
+
return Path.home() / ".omp" / "profiles" / profile / "agent"
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def sessions_dir() -> Path:
|
|
196
|
+
"""Root of session logs, or the override via OMP_MEMORY_SESSIONS."""
|
|
197
|
+
override = os.environ.get("OMP_MEMORY_SESSIONS")
|
|
198
|
+
if override:
|
|
199
|
+
return Path(override).expanduser()
|
|
200
|
+
return _agent_dir() / "sessions"
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
_SESSION_FILE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T.*\.jsonl$")
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def latest_session() -> Path | None:
|
|
207
|
+
root = sessions_dir()
|
|
208
|
+
if not root.is_dir():
|
|
209
|
+
return None
|
|
210
|
+
files = [
|
|
211
|
+
p for p in root.rglob("*.jsonl")
|
|
212
|
+
if p.is_file() and _SESSION_FILE_RE.match(p.name)
|
|
213
|
+
]
|
|
214
|
+
if not files:
|
|
215
|
+
return None
|
|
216
|
+
return max(files, key=lambda p: p.stat().st_mtime)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _normalize_entry(entry: dict) -> dict:
|
|
220
|
+
"""Map another host's transcript line onto this parser's shape.
|
|
221
|
+
|
|
222
|
+
Best-effort by design: Claude Code documents its JSONL as internal and
|
|
223
|
+
version-dependent, so this only recognises the two shapes that have been
|
|
224
|
+
stable in practice and leaves anything else untouched (and therefore
|
|
225
|
+
ignored) rather than inventing meaning.
|
|
226
|
+
"""
|
|
227
|
+
if entry.get("type") == "message":
|
|
228
|
+
return entry
|
|
229
|
+
message = entry.get("message")
|
|
230
|
+
if isinstance(message, dict) and entry.get("type") in ("user", "assistant"):
|
|
231
|
+
content = message.get("content")
|
|
232
|
+
role = message.get("role") or entry.get("type")
|
|
233
|
+
if isinstance(content, list) and content and all(
|
|
234
|
+
isinstance(b, dict) and b.get("type") == "tool_result"
|
|
235
|
+
for b in content):
|
|
236
|
+
role = "toolResult"
|
|
237
|
+
content = " ".join(str(b.get("content") or "") for b in content
|
|
238
|
+
if isinstance(b, dict))
|
|
239
|
+
return {"type": "message", "message": {"role": role, "content": content}}
|
|
240
|
+
return entry
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _read_entries(path: Path) -> list[dict]:
|
|
244
|
+
out = []
|
|
245
|
+
try:
|
|
246
|
+
with open(path, encoding="utf-8", errors="replace") as fh:
|
|
247
|
+
for line in fh:
|
|
248
|
+
line = line.strip()
|
|
249
|
+
if not line:
|
|
250
|
+
continue
|
|
251
|
+
try:
|
|
252
|
+
out.append(_normalize_entry(json.loads(line)))
|
|
253
|
+
except json.JSONDecodeError:
|
|
254
|
+
continue
|
|
255
|
+
except OSError:
|
|
256
|
+
pass
|
|
257
|
+
return out
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
# ---------------------------------------------------------------------------
|
|
261
|
+
# Extraction
|
|
262
|
+
# ---------------------------------------------------------------------------
|
|
263
|
+
|
|
264
|
+
def _text_of(message: dict) -> str:
|
|
265
|
+
content = message.get("content") or ""
|
|
266
|
+
if isinstance(content, str):
|
|
267
|
+
return content
|
|
268
|
+
if isinstance(content, list):
|
|
269
|
+
parts = []
|
|
270
|
+
for block in content:
|
|
271
|
+
if isinstance(block, dict) and block.get("type") == "text":
|
|
272
|
+
parts.append(str(block.get("text") or ""))
|
|
273
|
+
return "\n".join(parts)
|
|
274
|
+
return ""
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _clip(s: str, n: int) -> str:
|
|
278
|
+
s = " ".join(str(s).split())
|
|
279
|
+
return s if len(s) <= n else s[: n - 1] + "…"
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _entry_ts(entry: dict) -> float | None:
|
|
283
|
+
"""ISO timestamp of an entry as epoch seconds, None when absent/unparseable."""
|
|
284
|
+
raw = str(entry.get("timestamp") or "")
|
|
285
|
+
if not raw:
|
|
286
|
+
return None
|
|
287
|
+
try:
|
|
288
|
+
return datetime.fromisoformat(raw.replace("Z", "+00:00")).timestamp()
|
|
289
|
+
except ValueError:
|
|
290
|
+
return None
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _tokens_of(text: str) -> set:
|
|
294
|
+
return set(_TOKEN_RE.findall(text.lower()))
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _segments(entries: list[dict]) -> list[dict]:
|
|
298
|
+
"""Split a session log into events at time gaps and topic shifts.
|
|
299
|
+
|
|
300
|
+
Boundary when consecutive entries sit more than EVENT_GAP_MINUTES apart
|
|
301
|
+
(from entry timestamps), or when a user turn's token overlap with the
|
|
302
|
+
running event drops below EVENT_TOPIC_OVERLAP (jaccard, db._tokens
|
|
303
|
+
vocabulary). Entries without timestamps follow the current segment.
|
|
304
|
+
"""
|
|
305
|
+
segments: list[dict] = []
|
|
306
|
+
cur: dict | None = None
|
|
307
|
+
last_ts: float | None = None
|
|
308
|
+
last_turn_tokens: set | None = None
|
|
309
|
+
for e in entries:
|
|
310
|
+
ts = _entry_ts(e)
|
|
311
|
+
is_user_turn = e.get("type") == "message" and \
|
|
312
|
+
(e.get("message") or {}).get("role") == "user"
|
|
313
|
+
turn_tokens: set | None = None
|
|
314
|
+
if is_user_turn:
|
|
315
|
+
txt = _text_of(e.get("message") or {}).strip()
|
|
316
|
+
if txt and not _CONTENT_SKIP.search(txt):
|
|
317
|
+
turn_tokens = _tokens_of(txt)
|
|
318
|
+
boundary = cur is None
|
|
319
|
+
if not boundary and ts is not None and last_ts is not None:
|
|
320
|
+
if ts - last_ts > EVENT_GAP_MINUTES * 60.0:
|
|
321
|
+
boundary = True
|
|
322
|
+
if not boundary and turn_tokens and last_turn_tokens and \
|
|
323
|
+
len(turn_tokens | last_turn_tokens):
|
|
324
|
+
overlap = len(turn_tokens & last_turn_tokens) / \
|
|
325
|
+
len(turn_tokens | last_turn_tokens)
|
|
326
|
+
if overlap < EVENT_TOPIC_OVERLAP:
|
|
327
|
+
boundary = True
|
|
328
|
+
if turn_tokens is not None:
|
|
329
|
+
last_turn_tokens = turn_tokens
|
|
330
|
+
# The entry that opens a new event belongs to it; without this the
|
|
331
|
+
# boundary user turn is dropped and the next overlap check compares
|
|
332
|
+
# against the previous event's last turn again.
|
|
333
|
+
if boundary:
|
|
334
|
+
cur = {"entries": [e], "start": ts, "end": ts, "index": len(segments)}
|
|
335
|
+
segments.append(cur)
|
|
336
|
+
else:
|
|
337
|
+
cur["entries"].append(e)
|
|
338
|
+
if ts is not None:
|
|
339
|
+
cur["end"] = ts
|
|
340
|
+
if cur is not None and ts is not None:
|
|
341
|
+
last_ts = ts
|
|
342
|
+
return segments
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _failure_line(raw: str) -> str:
|
|
346
|
+
"""Distil a toolResult body into the one line that says what failed.
|
|
347
|
+
|
|
348
|
+
A traceback is five lines of boilerplate around one message; a test
|
|
349
|
+
summary is one FAIL: line. The shortest line carrying an error-shaped
|
|
350
|
+
signal is usually the message, not the frames around it.
|
|
351
|
+
"""
|
|
352
|
+
lines = [ln.strip() for ln in raw.split("\n") if ln.strip()]
|
|
353
|
+
hits = [ln for ln in lines if _FAILURE_RE.search(ln)]
|
|
354
|
+
if not hits:
|
|
355
|
+
return raw
|
|
356
|
+
priority = sorted(hits, key=lambda ln: (
|
|
357
|
+
0 if re.search(r"(Error|Exception|FAIL)\s*:", ln) else 1,
|
|
358
|
+
len(ln),
|
|
359
|
+
))
|
|
360
|
+
return priority[0]
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _event_candidates(seg: dict, session_id: str, project_id: str,
|
|
364
|
+
max_failures: int, max_files: int) -> list[dict]:
|
|
365
|
+
"""Extraction rules for one event segment.
|
|
366
|
+
|
|
367
|
+
Mirrors the original per-session rules, but scoped to the segment's
|
|
368
|
+
entries: failures, files, and decision keywords inside this event only.
|
|
369
|
+
Each candidate carries the event id and an event tag so replay can
|
|
370
|
+
filter one episode without re-parsing the log.
|
|
371
|
+
"""
|
|
372
|
+
user_turns: list[str] = []
|
|
373
|
+
failures: list[str] = []
|
|
374
|
+
files: "OrderedDict[str, int]" = OrderedDict()
|
|
375
|
+
|
|
376
|
+
for e in seg["entries"]:
|
|
377
|
+
t = e.get("type")
|
|
378
|
+
if t == "message":
|
|
379
|
+
msg = e.get("message") or {}
|
|
380
|
+
role = msg.get("role")
|
|
381
|
+
if role == "user":
|
|
382
|
+
txt = _text_of(msg).strip()
|
|
383
|
+
if txt and not _CONTENT_SKIP.search(txt):
|
|
384
|
+
user_turns.append(txt)
|
|
385
|
+
elif role == "toolResult":
|
|
386
|
+
name = str(msg.get("toolName") or "")
|
|
387
|
+
body = _text_of(msg)
|
|
388
|
+
if (name not in _READ_TOOLS and _FAILURE_RE.search(body)
|
|
389
|
+
and not _CONTENT_SKIP.search(body)):
|
|
390
|
+
failures.append(f"{name}: {_clip(_failure_line(body), 200)}")
|
|
391
|
+
# track file tool calls
|
|
392
|
+
if name in ("bash", "shell"):
|
|
393
|
+
for word in _TOKEN_RE.findall(body):
|
|
394
|
+
if "/" in word and word.startswith("/"):
|
|
395
|
+
files[word] = files.get(word, 0) + 1
|
|
396
|
+
# Custom entries carry file paths
|
|
397
|
+
if t == "custom":
|
|
398
|
+
payload = e.get("custom") or e.get("data") or {}
|
|
399
|
+
if not isinstance(payload, dict):
|
|
400
|
+
payload = {}
|
|
401
|
+
for key in ("path", "file_path", "filePath"):
|
|
402
|
+
p = payload.get(key)
|
|
403
|
+
if isinstance(p, str) and "/" in p:
|
|
404
|
+
files[p] = files.get(p, 0) + 1
|
|
405
|
+
# Also check top-level input for older entry shapes
|
|
406
|
+
inp = e.get("input") if isinstance(e, dict) else None
|
|
407
|
+
if isinstance(inp, dict):
|
|
408
|
+
for key in ("path", "file_path"):
|
|
409
|
+
p = inp.get(key)
|
|
410
|
+
if isinstance(p, str) and "/" in p:
|
|
411
|
+
files[p] = files.get(p, 0) + 1
|
|
412
|
+
|
|
413
|
+
event_id = f"{session_id}#e{seg['index']}"
|
|
414
|
+
event_tag = f"{EVENT_TAG_PREFIX}{seg['index']}"
|
|
415
|
+
candidates: list[dict] = []
|
|
416
|
+
|
|
417
|
+
# Failure patterns -> INFERENCE (what went wrong, with confidence floor)
|
|
418
|
+
for failure in failures[:max_failures]:
|
|
419
|
+
lesson = _failure_line(failure)
|
|
420
|
+
# The matcher catches any line mentioning an error; only a line
|
|
421
|
+
# that names the error type carries a lesson. Bare "Command
|
|
422
|
+
# exited with code N" or a parse-error fragment is shell noise,
|
|
423
|
+
# and a typo session must not become permanent memory.
|
|
424
|
+
if _NOISE_RE.search(lesson) or not _LESSON_RE.search(lesson):
|
|
425
|
+
continue
|
|
426
|
+
if _PYTEST_RE.search(lesson):
|
|
427
|
+
continue
|
|
428
|
+
# Environment failures are setup problems, not lessons; an unfixed
|
|
429
|
+
# complaint is only a lesson when the same event also shows the fix
|
|
430
|
+
# (a later success line in the failure text).
|
|
431
|
+
if _ENV_FAILURE_RE.search(lesson):
|
|
432
|
+
continue
|
|
433
|
+
if _UNFIXED_COMPLAINT_RE.search(lesson) and \
|
|
434
|
+
not re.search(r"(?i)\b(?:fixed|resolved|works now|solution|fix:)\b", failure):
|
|
435
|
+
continue
|
|
436
|
+
candidates.append({
|
|
437
|
+
"rtype": CAPTURE_DEFAULT_TYPE,
|
|
438
|
+
"content": f"Observed failure: {lesson}",
|
|
439
|
+
"evidence": _clip(failure, 200),
|
|
440
|
+
"confidence": CAPTURE_DEFAULT_CONFIDENCE,
|
|
441
|
+
"source": "auto-capture",
|
|
442
|
+
"session_id": session_id,
|
|
443
|
+
"project_id": project_id,
|
|
444
|
+
"tags": f"failure,auto-capture,{event_tag}",
|
|
445
|
+
"event_id": event_id,
|
|
446
|
+
})
|
|
447
|
+
|
|
448
|
+
# File patterns -> ASSUMPTION (which files were worked on)
|
|
449
|
+
if files:
|
|
450
|
+
top_files = list(sorted(files.items(), key=lambda kv: -kv[1]))[:max_files]
|
|
451
|
+
file_list = ", ".join(f"{p}({n}x)" for p, n in top_files)
|
|
452
|
+
candidates.append({
|
|
453
|
+
"rtype": "ASSUMPTION",
|
|
454
|
+
"content": f"Files worked on in this session: {file_list}",
|
|
455
|
+
"evidence": f"{len(files)} unique file(s) touched",
|
|
456
|
+
"confidence": CAPTURE_DEFAULT_CONFIDENCE,
|
|
457
|
+
"source": "auto-capture",
|
|
458
|
+
"session_id": session_id,
|
|
459
|
+
"project_id": project_id,
|
|
460
|
+
"tags": f"files,auto-capture,{event_tag}",
|
|
461
|
+
"event_id": event_id,
|
|
462
|
+
})
|
|
463
|
+
|
|
464
|
+
# Decision patterns in user turns (heuristic)
|
|
465
|
+
decision_kw = re.compile(
|
|
466
|
+
r"\b(decided?|concluded|chose|agreed|picked|selected|settled on|going with)\b",
|
|
467
|
+
re.I,
|
|
468
|
+
)
|
|
469
|
+
for turn in user_turns:
|
|
470
|
+
m = decision_kw.search(turn)
|
|
471
|
+
if m:
|
|
472
|
+
# extract ~150 chars around the decision keyword
|
|
473
|
+
pos = m.start()
|
|
474
|
+
snippet = turn[max(0, pos - 80):pos + 80]
|
|
475
|
+
candidates.append({
|
|
476
|
+
"rtype": "INFERENCE",
|
|
477
|
+
"content": _clip(f"Possible decision: {snippet}", 300),
|
|
478
|
+
"evidence": f"keyword '{m.group()}' in: {turn[:200]}",
|
|
479
|
+
"confidence": 0.4,
|
|
480
|
+
"source": "auto-capture",
|
|
481
|
+
"session_id": session_id,
|
|
482
|
+
"project_id": project_id,
|
|
483
|
+
"tags": f"decision,auto-capture,{event_tag}",
|
|
484
|
+
"event_id": event_id,
|
|
485
|
+
})
|
|
486
|
+
return candidates
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def extract_lessons(
|
|
490
|
+
entries: list[dict],
|
|
491
|
+
session_path: Path | None = None,
|
|
492
|
+
max_failures: int = MAX_FAILURES_STORED,
|
|
493
|
+
max_files: int = MAX_FILES_STORED,
|
|
494
|
+
) -> list[dict]:
|
|
495
|
+
"""Turn a session log into a list of candidate memory records.
|
|
496
|
+
|
|
497
|
+
The log is first segmented into events (time gap or topic shift, see
|
|
498
|
+
_segments); each event yields its own candidates carrying that event's
|
|
499
|
+
id and tag, so a midnight deploy failure does not inherit the memory
|
|
500
|
+
tags of the refactor that followed at breakfast.
|
|
501
|
+
|
|
502
|
+
Each candidate is a dict with the keys that db.upsert_record() needs:
|
|
503
|
+
rtype, content, evidence, confidence, source, session_id,
|
|
504
|
+
project_id, tags, event_id.
|
|
505
|
+
|
|
506
|
+
The caller decides whether to write them (apply=True) or just inspect them.
|
|
507
|
+
"""
|
|
508
|
+
session_id = session_path.stem if session_path else ""
|
|
509
|
+
project_id = session_path.parent.name if session_path else ""
|
|
510
|
+
|
|
511
|
+
candidates: list[dict] = []
|
|
512
|
+
for seg in _segments(entries):
|
|
513
|
+
candidates.extend(
|
|
514
|
+
_event_candidates(seg, session_id, project_id,
|
|
515
|
+
max_failures, max_files))
|
|
516
|
+
|
|
517
|
+
# Never persist a candidate whose content or evidence carries a secret:
|
|
518
|
+
# toolResult bodies can contain env dumps, tokens in tracebacks, etc.
|
|
519
|
+
# The mcp remember path scans; auto-capture must not bypass it.
|
|
520
|
+
kept = []
|
|
521
|
+
for cand in candidates:
|
|
522
|
+
leaked = scan_text(cand["content"] + " " + str(cand.get("evidence") or ""))
|
|
523
|
+
if leaked:
|
|
524
|
+
continue
|
|
525
|
+
kept.append(cand)
|
|
526
|
+
return kept
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
def capture_session(
|
|
530
|
+
db_mod,
|
|
531
|
+
conn,
|
|
532
|
+
session_path: Path | None = None,
|
|
533
|
+
apply: bool = False,
|
|
534
|
+
dry_run: bool = False,
|
|
535
|
+
session_id: str = "",
|
|
536
|
+
reflect: bool = False,
|
|
537
|
+
staging: bool = False,
|
|
538
|
+
) -> dict:
|
|
539
|
+
"""Run extraction and optionally write candidates to the DB.
|
|
540
|
+
|
|
541
|
+
db_mod: the omp_memory.db module (passed to avoid circular import).
|
|
542
|
+
conn: an open, inited sqlite3.Connection.
|
|
543
|
+
session_path: path to the session .jsonl; default = latest_session().
|
|
544
|
+
apply: write candidates to DB (default False = dry_run mode).
|
|
545
|
+
dry_run: alias for apply=False (explicit).
|
|
546
|
+
reflect: after writing, run the experience pass so new lessons are
|
|
547
|
+
abstracted into patterns in the same transaction.
|
|
548
|
+
|
|
549
|
+
Returns a summary dict.
|
|
550
|
+
"""
|
|
551
|
+
if session_path is None:
|
|
552
|
+
session_path = latest_session()
|
|
553
|
+
if session_path is None:
|
|
554
|
+
return {"error": "no session file found", "candidates": [], "written": 0}
|
|
555
|
+
|
|
556
|
+
entries = _read_entries(session_path)
|
|
557
|
+
if not entries:
|
|
558
|
+
return {"error": "session file empty", "candidates": [], "written": 0}
|
|
559
|
+
|
|
560
|
+
# The id must match the one the agent passed to recall, or credit
|
|
561
|
+
# assignment cannot bind an outcome to what was actually shown.
|
|
562
|
+
sid = session_id or Path(session_path).stem
|
|
563
|
+
candidates = extract_lessons(entries, session_path)
|
|
564
|
+
|
|
565
|
+
if not candidates:
|
|
566
|
+
return {
|
|
567
|
+
"session": str(session_path),
|
|
568
|
+
"candidates": [],
|
|
569
|
+
"written": 0,
|
|
570
|
+
"apply": apply,
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
if not apply:
|
|
574
|
+
# Return candidates without writing
|
|
575
|
+
readable = [
|
|
576
|
+
{
|
|
577
|
+
"type": c["rtype"],
|
|
578
|
+
"content": c["content"],
|
|
579
|
+
"evidence": c["evidence"],
|
|
580
|
+
"confidence": c["confidence"],
|
|
581
|
+
}
|
|
582
|
+
for c in candidates
|
|
583
|
+
]
|
|
584
|
+
return {
|
|
585
|
+
"session": str(session_path),
|
|
586
|
+
"candidates": readable,
|
|
587
|
+
"written": 0,
|
|
588
|
+
"apply": False,
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
# Write each candidate that doesn't already exist (content-identity dedup)
|
|
592
|
+
written = 0
|
|
593
|
+
staged = 0
|
|
594
|
+
quarantined = []
|
|
595
|
+
for cand in candidates:
|
|
596
|
+
existing = db_mod.find_record(
|
|
597
|
+
conn,
|
|
598
|
+
cand["rtype"],
|
|
599
|
+
cand["content"],
|
|
600
|
+
cand["source"],
|
|
601
|
+
cand["project_id"],
|
|
602
|
+
)
|
|
603
|
+
if existing:
|
|
604
|
+
continue
|
|
605
|
+
danger = dangerous_instructions(cand["content"])
|
|
606
|
+
if danger:
|
|
607
|
+
# A transcript is attacker-influenced text. Instruction-shaped
|
|
608
|
+
# candidates never land directly; the operator decides.
|
|
609
|
+
db_mod.stage_write(conn, cand)
|
|
610
|
+
staged += 1
|
|
611
|
+
quarantined.append({"kind": danger[0][0],
|
|
612
|
+
"content": cand["content"][:80]})
|
|
613
|
+
continue
|
|
614
|
+
if staging:
|
|
615
|
+
# Write approval: candidates wait for the operator instead of
|
|
616
|
+
# landing directly. The agent never changes your memory
|
|
617
|
+
# without an approve.
|
|
618
|
+
db_mod.stage_write(conn, cand)
|
|
619
|
+
staged += 1
|
|
620
|
+
continue
|
|
621
|
+
db_mod.upsert_record(
|
|
622
|
+
conn,
|
|
623
|
+
rtype=cand["rtype"],
|
|
624
|
+
content=cand["content"],
|
|
625
|
+
evidence=cand["evidence"],
|
|
626
|
+
verified=0,
|
|
627
|
+
confidence=min(cand["confidence"], CAPTURE_CONFIDENCE_CEILING),
|
|
628
|
+
source=cand["source"],
|
|
629
|
+
tags=cand["tags"],
|
|
630
|
+
session_id=cand["session_id"],
|
|
631
|
+
project_id=cand["project_id"],
|
|
632
|
+
event_id=cand.get("event_id") or "",
|
|
633
|
+
)
|
|
634
|
+
written += 1
|
|
635
|
+
conn.commit()
|
|
636
|
+
# Objective outcomes found in the transcript, logged after the lessons so
|
|
637
|
+
# promotion can see them. Ambiguous results produce nothing.
|
|
638
|
+
from . import outcomes as _outcomes
|
|
639
|
+
logged = []
|
|
640
|
+
for kind in _outcomes.extract(entries):
|
|
641
|
+
logged.append(db_mod.log_outcome(
|
|
642
|
+
conn, kind, session_id=sid, evidence_ref=str(session_path)))
|
|
643
|
+
reflected = None
|
|
644
|
+
if reflect and apply:
|
|
645
|
+
from . import experience
|
|
646
|
+
reflected = experience.reflect(conn, apply=True)
|
|
647
|
+
report = {
|
|
648
|
+
"session": str(session_path),
|
|
649
|
+
"candidates": len(candidates),
|
|
650
|
+
"written": written,
|
|
651
|
+
"staged": staged,
|
|
652
|
+
"quarantined": quarantined,
|
|
653
|
+
"outcomes": logged,
|
|
654
|
+
"apply": True,
|
|
655
|
+
}
|
|
656
|
+
if reflected is not None:
|
|
657
|
+
report["reflect"] = reflected
|
|
658
|
+
return report
|