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/md_ingest.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
"""Ingest omp's builtin markdown memory into the honcho store.
|
|
2
|
+
|
|
3
|
+
Why this exists: omp's `learn` tool writes appended entries into
|
|
4
|
+
`memories/<project>/learned.md`, while the top of that same file claims memory
|
|
5
|
+
moved to honcho and tells the agent not to add notes there. Measured on
|
|
6
|
+
2026-11-26: `memories/--tmp--/learned.md` held 80 entries appended *after*
|
|
7
|
+
that tombstone, and all 80 were absent from the store - because the migration
|
|
8
|
+
that copied these files ran once (newest imported record 2026-11-18) and
|
|
9
|
+
nothing has read them since.
|
|
10
|
+
|
|
11
|
+
This module closes the fork without moving the files: it reads them
|
|
12
|
+
incrementally, keyed by (path, mtime, size, sha256), so a re-run is cheap and
|
|
13
|
+
an edited file is re-read while an untouched one costs one stat.
|
|
14
|
+
|
|
15
|
+
Design rules, each from a measured failure:
|
|
16
|
+
* Skip the tombstone block itself - it is boilerplate, not a lesson. Only
|
|
17
|
+
entries after the tombstone's end marker are candidates.
|
|
18
|
+
* An entry shorter than MIN_ENTRY_CHARS is a heading or a pointer, not a
|
|
19
|
+
fact worth a row.
|
|
20
|
+
* Content identity does the de-duplication: `upsert_record` is
|
|
21
|
+
content-addressed, so ingesting the same line twice is a no-op rather
|
|
22
|
+
than a duplicate row.
|
|
23
|
+
* A source tag records the file, so an operator can trace a record back.
|
|
24
|
+
"""
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import hashlib
|
|
28
|
+
import json
|
|
29
|
+
import os
|
|
30
|
+
import re
|
|
31
|
+
import re
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
def _store_cap() -> int:
|
|
35
|
+
"""The engine's own ceiling, read lazily so this module stays importable."""
|
|
36
|
+
from .db import MAX_RECORD_CHARS
|
|
37
|
+
return MAX_RECORD_CHARS
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
_STORE_CAP = _store_cap()
|
|
41
|
+
|
|
42
|
+
MIN_ENTRY_CHARS = 60
|
|
43
|
+
# A single `learn` entry can run 2,000+ characters. Stored whole, one such
|
|
44
|
+
# record sweeps every query that shares any of its many words: measured on the
|
|
45
|
+
# live store, 5 of the 6 most-returned records were md-ingested entries of
|
|
46
|
+
# 1,800-2,300 characters, at confidence 0.55, crowding out specific facts.
|
|
47
|
+
# Splitting at sentence boundaries keeps each stored unit about one idea, which
|
|
48
|
+
# is what lexical scoring can actually discriminate.
|
|
49
|
+
MAX_ENTRY_CHARS = 700
|
|
50
|
+
# When no break exists at all, cut here rather than at the store cap: a 2,000
|
|
51
|
+
# character piece still dominates lexical ranking, which is the thing being
|
|
52
|
+
# fixed. 900 keeps a substantial thought while staying near the corpus median.
|
|
53
|
+
HARD_CUT_CHARS = 900
|
|
54
|
+
STATE_NAME = "ingest_md.json"
|
|
55
|
+
# Which filenames are curated lessons. `raw_memories.md` is the full narrative
|
|
56
|
+
# of each rollout (1,605 candidate entries across 170 files, dominated by
|
|
57
|
+
# multi-paragraph session prose); ingesting it would bury the store in
|
|
58
|
+
# narrative that recall then has to rank against real facts. `rollout_summaries`
|
|
59
|
+
# is the same material again. Curated lesson files only.
|
|
60
|
+
INGEST_FILENAMES = ("learned.md", "MEMORY.md")
|
|
61
|
+
|
|
62
|
+
# The tombstone block ends at the first line that is not part of it. These are
|
|
63
|
+
# the markers actually present in the files on this machine.
|
|
64
|
+
_TOMBSTONE_MARKERS = (
|
|
65
|
+
"content moved to honcho",
|
|
66
|
+
"sudah dipindahkan ke database honcho",
|
|
67
|
+
"jangan tambah catatan di sini",
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
_BULLET_RE = re.compile(r"^[-*]\s+(.*)$")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def memories_root() -> Path:
|
|
74
|
+
"""Directory holding omp's per-project memory folders."""
|
|
75
|
+
explicit = os.environ.get("OMP_MEMORY_MD_ROOT")
|
|
76
|
+
if explicit:
|
|
77
|
+
return Path(explicit).expanduser()
|
|
78
|
+
agent = os.environ.get("PI_CODING_AGENT_DIR")
|
|
79
|
+
if agent:
|
|
80
|
+
return Path(agent) / "memories"
|
|
81
|
+
profile = os.environ.get("OMP_PROFILE") or "default"
|
|
82
|
+
return Path.home() / ".omp" / "profiles" / profile / "agent" / "memories"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _state_path(db_dir: Path) -> Path:
|
|
86
|
+
return db_dir / STATE_NAME
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _sha256(path: Path) -> str:
|
|
90
|
+
digest = hashlib.sha256()
|
|
91
|
+
with open(path, "rb") as handle:
|
|
92
|
+
for chunk in iter(lambda: handle.read(1 << 20), b""):
|
|
93
|
+
digest.update(chunk)
|
|
94
|
+
return digest.hexdigest()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _signature(path: Path) -> dict:
|
|
98
|
+
stat = path.stat()
|
|
99
|
+
return {"mtime": int(stat.st_mtime), "size": stat.st_size, "sha256": _sha256(path)}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def entries_after_tombstone(text: str) -> list[str]:
|
|
103
|
+
"""Bullet entries that follow the 'moved to honcho' notice.
|
|
104
|
+
|
|
105
|
+
The notice is real and must be skipped; what follows it is what `learn`
|
|
106
|
+
appended afterwards, which is exactly the part honcho never saw.
|
|
107
|
+
"""
|
|
108
|
+
lines = text.splitlines()
|
|
109
|
+
start = 0
|
|
110
|
+
for i, line in enumerate(lines):
|
|
111
|
+
if any(marker in line.lower() for marker in _TOMBSTONE_MARKERS):
|
|
112
|
+
start = i + 1
|
|
113
|
+
break
|
|
114
|
+
out = []
|
|
115
|
+
for line in lines[start:]:
|
|
116
|
+
match = _BULLET_RE.match(line.strip())
|
|
117
|
+
if not match:
|
|
118
|
+
continue
|
|
119
|
+
body = match.group(1).strip()
|
|
120
|
+
if len(body) < MIN_ENTRY_CHARS:
|
|
121
|
+
continue
|
|
122
|
+
out.extend(_split_long(body))
|
|
123
|
+
return out
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# Break on sentence punctuation, semicolons, and list markers: a `learn` entry
|
|
127
|
+
# often embeds bullet sub-points, and a pattern that only knows ". " leaves a
|
|
128
|
+
# 2,000-character blob containing 26 real breaks inside it.
|
|
129
|
+
_SENTENCE_END = re.compile(r"(?<=[.!?;])\s+|\s*\n\s*[-*]\s+|\s*\n\s*\n\s*")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _split_long(text: str, limit: int = MAX_ENTRY_CHARS) -> list[str]:
|
|
133
|
+
"""Break an over-long entry at sentence boundaries, never mid-sentence.
|
|
134
|
+
|
|
135
|
+
A fragment shorter than MIN_ENTRY_CHARS is merged into the previous piece
|
|
136
|
+
rather than stored as a stub, so the split produces units that are each
|
|
137
|
+
self-contained. If a single sentence exceeds the limit on its own it is
|
|
138
|
+
kept whole: truncating prose would corrupt the memory it is meant to carry.
|
|
139
|
+
"""
|
|
140
|
+
if len(text) <= limit:
|
|
141
|
+
return [text]
|
|
142
|
+
if len(text) > HARD_CUT_CHARS:
|
|
143
|
+
# No break point exists in a chunk this long: cut at the last word
|
|
144
|
+
# boundary before HARD_CUT_CHARS so no word is split, and recurse on
|
|
145
|
+
# the remainder.
|
|
146
|
+
head = text[:HARD_CUT_CHARS]
|
|
147
|
+
cut = head.rfind(" ")
|
|
148
|
+
cut = cut if cut > MIN_ENTRY_CHARS else HARD_CUT_CHARS
|
|
149
|
+
rest = text[cut:].strip()
|
|
150
|
+
return [text[:cut].strip()] + (_split_long(rest, limit) if rest else [])
|
|
151
|
+
pieces: list[str] = []
|
|
152
|
+
current = ""
|
|
153
|
+
for sentence in _SENTENCE_END.split(text):
|
|
154
|
+
candidate = f"{current} {sentence}".strip() if current else sentence
|
|
155
|
+
if current and len(candidate) > limit:
|
|
156
|
+
pieces.append(current)
|
|
157
|
+
current = sentence
|
|
158
|
+
else:
|
|
159
|
+
current = candidate
|
|
160
|
+
if current:
|
|
161
|
+
pieces.append(current)
|
|
162
|
+
# Re-merge a runt tail into its predecessor, but never past the store cap:
|
|
163
|
+
# a single sentence longer than MAX_RECORD_CHARS would otherwise be
|
|
164
|
+
# rejected by upsert_record and abort the whole ingest.
|
|
165
|
+
merged: list[str] = []
|
|
166
|
+
for piece in pieces:
|
|
167
|
+
if (merged and len(piece) < MIN_ENTRY_CHARS
|
|
168
|
+
and len(merged[-1]) + len(piece) + 1 <= _STORE_CAP):
|
|
169
|
+
merged[-1] = f"{merged[-1]} {piece}"
|
|
170
|
+
else:
|
|
171
|
+
merged.append(piece)
|
|
172
|
+
return [p for p in merged if len(p) >= MIN_ENTRY_CHARS]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def ingest_md(conn, db_mod, root: Path = None, apply: bool = False) -> dict:
|
|
176
|
+
"""Read every memories/**/*.md file and upsert new entries.
|
|
177
|
+
|
|
178
|
+
db_mod is the omp_memory.db module (passed to avoid a circular import).
|
|
179
|
+
Returns counts plus the per-file verdicts, so a caller can see which files
|
|
180
|
+
were skipped and why.
|
|
181
|
+
"""
|
|
182
|
+
root = Path(root) if root is not None else memories_root()
|
|
183
|
+
if not root.is_dir():
|
|
184
|
+
return {"root": str(root), "error": "memories directory not found",
|
|
185
|
+
"files": 0, "written": 0}
|
|
186
|
+
db_dir = Path(db_mod.DB_PATH).parent
|
|
187
|
+
state_path = _state_path(db_dir)
|
|
188
|
+
try:
|
|
189
|
+
state = json.loads(state_path.read_text(encoding="utf-8"))
|
|
190
|
+
except (OSError, json.JSONDecodeError):
|
|
191
|
+
state = {}
|
|
192
|
+
|
|
193
|
+
root_resolved = root.resolve()
|
|
194
|
+
files = []
|
|
195
|
+
for candidate in sorted(root.rglob("*.md")):
|
|
196
|
+
if candidate.name not in INGEST_FILENAMES:
|
|
197
|
+
continue
|
|
198
|
+
# rglob follows a symlinked directory, so a file "inside" the root can
|
|
199
|
+
# resolve outside it. Ingesting it would import whatever the link
|
|
200
|
+
# points at (a private key, a shell history) into long-term memory.
|
|
201
|
+
try:
|
|
202
|
+
resolved = candidate.resolve()
|
|
203
|
+
except OSError:
|
|
204
|
+
continue
|
|
205
|
+
if not resolved.is_relative_to(root_resolved):
|
|
206
|
+
continue
|
|
207
|
+
files.append(candidate)
|
|
208
|
+
written = 0
|
|
209
|
+
considered = 0
|
|
210
|
+
details = []
|
|
211
|
+
for path in files:
|
|
212
|
+
key = str(path)
|
|
213
|
+
try:
|
|
214
|
+
sig = _signature(path)
|
|
215
|
+
except OSError as exc:
|
|
216
|
+
details.append({"file": key, "skipped": f"unreadable: {exc}"})
|
|
217
|
+
continue
|
|
218
|
+
if state.get(key) == sig:
|
|
219
|
+
details.append({"file": key, "skipped": "unchanged"})
|
|
220
|
+
continue
|
|
221
|
+
try:
|
|
222
|
+
text = path.read_text(encoding="utf-8", errors="replace")
|
|
223
|
+
except OSError as exc:
|
|
224
|
+
details.append({"file": key, "skipped": f"unreadable: {exc}"})
|
|
225
|
+
continue
|
|
226
|
+
from . import capture, context
|
|
227
|
+
entries = []
|
|
228
|
+
for body in entries_after_tombstone(text):
|
|
229
|
+
# This file was written by another tool, not by this process: it
|
|
230
|
+
# gets the same treatment as any untrusted import.
|
|
231
|
+
if capture.scan_text(body):
|
|
232
|
+
continue
|
|
233
|
+
entries.append(context._neutralize_fence(body))
|
|
234
|
+
considered += len(entries)
|
|
235
|
+
# Order matters: the folder is "-Documents-project-demo--", so stripping
|
|
236
|
+
# hyphens first turns the marker into "Documents-project-demo" and the
|
|
237
|
+
# project name becomes the whole path. Replace the marker first, then
|
|
238
|
+
# trim the leftover separator hyphens.
|
|
239
|
+
folder = path.parent.name
|
|
240
|
+
project = folder.replace("-Documents-project-", "").replace(
|
|
241
|
+
"Documents-project-", "").strip("-")
|
|
242
|
+
if apply:
|
|
243
|
+
for body in entries:
|
|
244
|
+
db_mod.remember(
|
|
245
|
+
conn,
|
|
246
|
+
rtype="FACT",
|
|
247
|
+
content=body,
|
|
248
|
+
evidence=f"omp builtin memory: {path.name}",
|
|
249
|
+
confidence=0.55,
|
|
250
|
+
source=f"md:{path.parent.name}"[:120],
|
|
251
|
+
project_id=project,
|
|
252
|
+
)
|
|
253
|
+
written += 1
|
|
254
|
+
state[key] = sig
|
|
255
|
+
details.append({"file": key, "entries": len(entries), "project": project})
|
|
256
|
+
|
|
257
|
+
if apply:
|
|
258
|
+
db_dir.mkdir(parents=True, exist_ok=True)
|
|
259
|
+
state_path.write_text(json.dumps(state, indent=2), encoding="utf-8")
|
|
260
|
+
conn.commit()
|
|
261
|
+
return {
|
|
262
|
+
"root": str(root),
|
|
263
|
+
"files": len(files),
|
|
264
|
+
"entries": considered,
|
|
265
|
+
"written": written,
|
|
266
|
+
"apply": bool(apply),
|
|
267
|
+
"details": details,
|
|
268
|
+
}
|
omp_memory/outcomes.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Classify a tool result as an objective outcome, conservatively.
|
|
2
|
+
|
|
3
|
+
Credit assignment is the only evidence the engine has about being right, so a
|
|
4
|
+
wrong label is worse than a missing one. Every rule here needs an explicit
|
|
5
|
+
marker; ambiguity returns None and nothing is recorded.
|
|
6
|
+
"""
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
_FAIL = re.compile(
|
|
10
|
+
r"(?m)^\s*FAILED\b|^\s*ERROR\b|\b[1-9]\d* failed\b|\bFAILED\s+\("
|
|
11
|
+
r"|npm ERR!|\bAssertionError\b|Traceback \(most recent call last\)"
|
|
12
|
+
r"|error\[E\d+\]|^make(\[\d+\])?: \*\*\*|^error: test failed"
|
|
13
|
+
r"|\bexit code: [1-9]\d*\b|\bassertion failed\b", re.IGNORECASE)
|
|
14
|
+
_PASS = re.compile(
|
|
15
|
+
r"\b\d+ passed\b|\ball tests passed\b|\bBUILD SUCCEEDED\b"
|
|
16
|
+
r"|^ok\s+\S+\s+[\d.]+s|\bPASSED\b|\b0 failed\b",
|
|
17
|
+
re.IGNORECASE | re.MULTILINE)
|
|
18
|
+
_BUILD = re.compile(r"\b(build|cargo build|make all|tsc|compil)", re.IGNORECASE)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def classify(text: str):
|
|
22
|
+
"""Return an OUTCOME_KINDS member, or None when the text is ambiguous.
|
|
23
|
+
|
|
24
|
+
A failure marker wins over a pass marker: a summary line like
|
|
25
|
+
"10 passed, 2 failed" must not be read as success.
|
|
26
|
+
"""
|
|
27
|
+
if not text or len(text) > 20000:
|
|
28
|
+
return None
|
|
29
|
+
failed = bool(_FAIL.search(text))
|
|
30
|
+
passed = bool(_PASS.search(text))
|
|
31
|
+
if not failed and not passed:
|
|
32
|
+
return None
|
|
33
|
+
build = bool(_BUILD.search(text))
|
|
34
|
+
if failed:
|
|
35
|
+
return "build_fail" if build else "test_fail"
|
|
36
|
+
return "build_pass" if build else "test_pass"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def extract(entries) -> list:
|
|
40
|
+
"""Outcome kinds from a parsed transcript's entries, in order.
|
|
41
|
+
|
|
42
|
+
Only tool results are considered: a user saying "tests pass" is not an
|
|
43
|
+
outcome, and assistant prose is not evidence of anything.
|
|
44
|
+
"""
|
|
45
|
+
kinds = []
|
|
46
|
+
for entry in entries or []:
|
|
47
|
+
if entry.get("type") != "message":
|
|
48
|
+
continue
|
|
49
|
+
message = entry.get("message") or {}
|
|
50
|
+
if message.get("role") != "toolResult":
|
|
51
|
+
continue
|
|
52
|
+
text = message.get("content")
|
|
53
|
+
if isinstance(text, list):
|
|
54
|
+
text = " ".join(x.get("text", "") for x in text if isinstance(x, dict))
|
|
55
|
+
kind = classify(text or "")
|
|
56
|
+
if kind:
|
|
57
|
+
kinds.append(kind)
|
|
58
|
+
return kinds
|
omp_memory/provider.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
MemoryProvider - Abstract base class for pluggable memory providers.
|
|
4
|
+
Inspired by Hermes Agent (NousResearch/hermes-agent).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from abc import ABC, abstractmethod
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
12
|
+
import logging
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
PRE_COMPRESS_CHECKPOINT_API_VERSION = 2
|
|
17
|
+
|
|
18
|
+
INDICATOR_GLYPH = "🧠"
|
|
19
|
+
|
|
20
|
+
CORE_MEMORY_PROVIDER_SENTINELS = frozenset({"", "default", "builtin", "built-in", "none"})
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def is_core_memory_provider(name: Optional[str]) -> bool:
|
|
24
|
+
"""True when name means the built-in provider rather than a plugin."""
|
|
25
|
+
return str(name or "").strip().lower() in CORE_MEMORY_PROVIDER_SENTINELS
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class RecallStatus:
|
|
30
|
+
injected: int = 0
|
|
31
|
+
skipped: int = 0
|
|
32
|
+
reason: Optional[str] = None
|
|
33
|
+
glyph: str = INDICATOR_GLYPH
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class MemoryProvider(ABC):
|
|
37
|
+
pre_compress_checkpoint_api_version = 2
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
@abstractmethod
|
|
41
|
+
def name(self) -> str:
|
|
42
|
+
"""Short identifier for this provider."""
|
|
43
|
+
|
|
44
|
+
@abstractmethod
|
|
45
|
+
def is_available(self) -> bool:
|
|
46
|
+
"""Configured, credentialed and ready? Gates activation."""
|
|
47
|
+
|
|
48
|
+
@abstractmethod
|
|
49
|
+
def initialize(self, session_id: str, **kwargs) -> None:
|
|
50
|
+
"""Initialize once at agent startup."""
|
|
51
|
+
|
|
52
|
+
def unavailable_reason(self) -> str:
|
|
53
|
+
return ""
|
|
54
|
+
|
|
55
|
+
def system_prompt_block(self) -> str:
|
|
56
|
+
"""STATIC system-prompt text; "" to skip."""
|
|
57
|
+
return ""
|
|
58
|
+
|
|
59
|
+
def prefetch(self, query: str, *, session_id: str = "") -> str:
|
|
60
|
+
"""Formatted recall context for the upcoming turn."""
|
|
61
|
+
return ""
|
|
62
|
+
|
|
63
|
+
def queue_prefetch(self, query: str, *, session_id: str = "") -> None:
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
def recall_status(self) -> Optional[RecallStatus]:
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
def sync_turn(self, user_content: str, assistant_content: str, *,
|
|
70
|
+
session_id: str = "", messages: list = None,
|
|
71
|
+
turn_author: dict = None) -> None:
|
|
72
|
+
raise NotImplementedError
|
|
73
|
+
|
|
74
|
+
def get_tool_schemas(self) -> list:
|
|
75
|
+
return []
|
|
76
|
+
|
|
77
|
+
def handle_tool_call(self, tool_name: str, args: dict, **kwargs) -> str:
|
|
78
|
+
raise NotImplementedError(f"Provider {self.name} does not handle tool {tool_name}")
|
|
79
|
+
|
|
80
|
+
def shutdown(self) -> None:
|
|
81
|
+
pass
|
|
82
|
+
|
|
83
|
+
def on_turn_start(self, turn_number: int, message: str, **kwargs) -> None:
|
|
84
|
+
pass
|
|
85
|
+
|
|
86
|
+
def identity_signature(self) -> dict:
|
|
87
|
+
return {}
|
|
88
|
+
|
|
89
|
+
def on_session_end(self, messages: list) -> None:
|
|
90
|
+
pass
|
|
91
|
+
|
|
92
|
+
def on_session_switch(self, new_session_id: str, *,
|
|
93
|
+
parent_session_id: str = "",
|
|
94
|
+
reset: bool = False,
|
|
95
|
+
rewound: bool = False,
|
|
96
|
+
**kwargs) -> None:
|
|
97
|
+
pass
|
|
98
|
+
|
|
99
|
+
def on_pre_compress(self, messages: list) -> str:
|
|
100
|
+
return ""
|
|
101
|
+
|
|
102
|
+
def on_delegation(self, task: str, result: str, *,
|
|
103
|
+
child_session_id: str = "",
|
|
104
|
+
**kwargs) -> None:
|
|
105
|
+
pass
|
|
106
|
+
|
|
107
|
+
def get_config_schema(self) -> list:
|
|
108
|
+
return []
|
|
109
|
+
|
|
110
|
+
def save_config(self, values: dict, hermes_home: str) -> None:
|
|
111
|
+
pass
|
|
112
|
+
|
|
113
|
+
def on_memory_write(self, action: str, target: str, content: str,
|
|
114
|
+
metadata: dict = None) -> None:
|
|
115
|
+
pass
|
|
116
|
+
|
|
117
|
+
def backup_paths(self) -> list:
|
|
118
|
+
return []
|
|
119
|
+
|
|
120
|
+
def reinforce(self, record_id: str, signal: str, delta: float = 0.1,
|
|
121
|
+
source: str = "", content: str = None,
|
|
122
|
+
evidence: str = "") -> float:
|
|
123
|
+
raise NotImplementedError
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
if __name__ == "__main__":
|
|
127
|
+
print("MemoryProvider ABC loaded")
|
|
128
|
+
print(f"PRE_COMPRESS_CHECKPOINT_API_VERSION = {PRE_COMPRESS_CHECKPOINT_API_VERSION}")
|
|
129
|
+
print(f"INDICATOR_GLYPH = {INDICATOR_GLYPH}")
|
omp_memory/watch.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Idle watcher: capture session lessons after inactivity.
|
|
2
|
+
|
|
3
|
+
Polls the newest session log; when it has been quiet for IDLE_SECONDS
|
|
4
|
+
and not yet captured, runs capture_session(apply=True, reflect=True):
|
|
5
|
+
the capture writes the lessons and the reflect pass abstracts them
|
|
6
|
+
into patterns in the same connection. The state file records the last
|
|
7
|
+
captured mtime so a quiet session is only captured once.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import signal
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
import time
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from . import db
|
|
21
|
+
from .capture import latest_session, sessions_dir
|
|
22
|
+
|
|
23
|
+
IDLE_SECONDS = db.env_int("OMP_MEMORY_IDLE_SECONDS", 600, 1)
|
|
24
|
+
POLL_SECONDS = db.env_int("OMP_MEMORY_POLL_SECONDS", 60, 1)
|
|
25
|
+
SLEEP_INTERVAL = db.env_int("OMP_MEMORY_SLEEP_INTERVAL", 3600, 1)
|
|
26
|
+
|
|
27
|
+
STATE_FILE = Path(
|
|
28
|
+
os.environ.get(
|
|
29
|
+
"OMP_MEMORY_WATCH_STATE",
|
|
30
|
+
str(Path.home() / ".omp/memory/watch_state.json"),
|
|
31
|
+
)
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def load_state() -> dict:
|
|
36
|
+
try:
|
|
37
|
+
return json.loads(STATE_FILE.read_text(encoding="utf-8"))
|
|
38
|
+
except (OSError, json.JSONDecodeError):
|
|
39
|
+
return {}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def save_state(state: dict) -> None:
|
|
43
|
+
STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
44
|
+
STATE_FILE.write_text(json.dumps(state), encoding="utf-8")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def idle_seconds(mtime: float, now: float) -> float:
|
|
48
|
+
return now - mtime
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def should_capture(mtime: float, now: float, captured_mtime: float | None) -> bool:
|
|
52
|
+
"""Capture when the log is idle and has new content since last capture."""
|
|
53
|
+
if captured_mtime is not None and mtime <= captured_mtime:
|
|
54
|
+
return False
|
|
55
|
+
return idle_seconds(mtime, now) >= IDLE_SECONDS
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _session_project(session_path: Path) -> str:
|
|
59
|
+
"""Project id from the session folder name: -Documents-project-foo -> foo."""
|
|
60
|
+
rel = session_path.relative_to(sessions_dir())
|
|
61
|
+
parts = rel.parts[:-1]
|
|
62
|
+
name = "-".join(parts).lstrip("-")
|
|
63
|
+
if name.startswith("Documents-project-"):
|
|
64
|
+
return name[len("Documents-project-"):]
|
|
65
|
+
if name.startswith("project-"):
|
|
66
|
+
return name[len("project-"):]
|
|
67
|
+
return name
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def capture_once(db_mod, conn, now: float | None = None) -> dict:
|
|
71
|
+
"""Capture the newest session if it qualifies. Returns a summary dict."""
|
|
72
|
+
now = now if now is not None else time.time()
|
|
73
|
+
session = latest_session()
|
|
74
|
+
if session is None:
|
|
75
|
+
return {"action": "none", "reason": "no-session"}
|
|
76
|
+
mtime = session.stat().st_mtime
|
|
77
|
+
state = load_state()
|
|
78
|
+
captured = state.get("captured_mtime")
|
|
79
|
+
if not should_capture(mtime, now, captured):
|
|
80
|
+
return {"action": "none", "reason": "not-idle-or-already-captured"}
|
|
81
|
+
|
|
82
|
+
from . import capture
|
|
83
|
+
|
|
84
|
+
summary = capture.capture_session(db_mod, conn, session_path=session,
|
|
85
|
+
apply=True, reflect=True)
|
|
86
|
+
save_state({**state, "captured_mtime": mtime, "captured_at": now})
|
|
87
|
+
return {
|
|
88
|
+
"action": "captured",
|
|
89
|
+
"session": str(session),
|
|
90
|
+
"project": _session_project(session),
|
|
91
|
+
**{k: v for k, v in summary.items() if k != "candidates"},
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _notify(summary: dict) -> None:
|
|
96
|
+
"""Desktop notification so a capture is visible, not just silent.
|
|
97
|
+
|
|
98
|
+
Best-effort: a systemd unit has no session bus unless one is
|
|
99
|
+
exported, so fall back to the well-known /run/user path; without
|
|
100
|
+
it, or without notify-send, nothing fires and capture still works.
|
|
101
|
+
Opt-in via OMP_MEMORY_NOTIFY=1.
|
|
102
|
+
"""
|
|
103
|
+
if os.environ.get("OMP_MEMORY_NOTIFY") != "1":
|
|
104
|
+
return
|
|
105
|
+
refl = summary.get("reflect") or {}
|
|
106
|
+
body = (f"{summary.get('written', 0)} lessons, "
|
|
107
|
+
f"{refl.get('written', 0)} patterns")
|
|
108
|
+
env = dict(os.environ)
|
|
109
|
+
if "DBUS_SESSION_BUS_ADDRESS" not in env and "DISPLAY" not in env:
|
|
110
|
+
env["DBUS_SESSION_BUS_ADDRESS"] = f"unix:path=/run/user/{os.getuid()}/bus"
|
|
111
|
+
try:
|
|
112
|
+
subprocess.run(
|
|
113
|
+
["notify-send", "-a", "honcho-pi", "Memory saved", body],
|
|
114
|
+
timeout=10, check=False, env=env,
|
|
115
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
116
|
+
except (OSError, subprocess.SubprocessError):
|
|
117
|
+
pass
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def main(argv=None) -> int:
|
|
121
|
+
from . import db
|
|
122
|
+
|
|
123
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
124
|
+
if argv and argv[0] in ("--once", "once"):
|
|
125
|
+
conn = db.connect()
|
|
126
|
+
try:
|
|
127
|
+
print(json.dumps(capture_once(db, conn)))
|
|
128
|
+
finally:
|
|
129
|
+
conn.close()
|
|
130
|
+
return 0
|
|
131
|
+
|
|
132
|
+
running = {"flag": True}
|
|
133
|
+
|
|
134
|
+
def stop(_sig, _frm):
|
|
135
|
+
running["flag"] = False
|
|
136
|
+
|
|
137
|
+
signal.signal(signal.SIGTERM, stop)
|
|
138
|
+
signal.signal(signal.SIGINT, stop)
|
|
139
|
+
|
|
140
|
+
print(f"[watch] polling {sessions_dir()} every {POLL_SECONDS}s, idle {IDLE_SECONDS}s", flush=True)
|
|
141
|
+
conn = db.connect()
|
|
142
|
+
last_sleep = time.time()
|
|
143
|
+
try:
|
|
144
|
+
while running["flag"]:
|
|
145
|
+
try:
|
|
146
|
+
result = capture_once(db, conn)
|
|
147
|
+
if result["action"] != "none":
|
|
148
|
+
print(f"[watch] {json.dumps(result)}", flush=True)
|
|
149
|
+
_notify(result)
|
|
150
|
+
if time.time() - last_sleep >= SLEEP_INTERVAL:
|
|
151
|
+
report = db.sleep_pass(conn, apply=True)
|
|
152
|
+
last_sleep = time.time()
|
|
153
|
+
print(f"[watch] sleep {json.dumps(report)}", flush=True)
|
|
154
|
+
except Exception as exc: # noqa: BLE001 - watcher must survive
|
|
155
|
+
print(f"[watch] error: {exc}", file=sys.stderr, flush=True)
|
|
156
|
+
time.sleep(POLL_SECONDS)
|
|
157
|
+
finally:
|
|
158
|
+
conn.close()
|
|
159
|
+
return 0
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
if __name__ == "__main__":
|
|
163
|
+
raise SystemExit(main())
|