diff --git a/pulse-memory/README.md b/pulse-memory/README.md index 0daa56c..0bfea96 100644 --- a/pulse-memory/README.md +++ b/pulse-memory/README.md @@ -52,12 +52,23 @@ skills/pulse-memory/ # filter SoT SKILL.md references/admissions.md references/store.md # SQLite archive vs memory +scripts/ # admit, retrieve, backfill .grok/workflows/pulse-memory.rhai test/ ``` Plugins do not auto-register Rhai. Copy/symlink the workflow. +## CLI + +```bash +PULSE_MEMORY_DB=./pulse.sqlite scripts/pulse_admit.py apply/example/constraints "Keep the cap." test tool-verified fact locked +PULSE_MEMORY_DB=./pulse.sqlite scripts/pulse_retrieve.py --key apply/example/constraints +PULSE_MEMORY_DB=./pulse.sqlite scripts/pulse_backfill.py +``` + +Retrieve returns JSON: one pulse (or a few, max 8), or `{ "ok": false, "status": "unknown" }`. It never prints the whole store. + ## Tests ```bash diff --git a/pulse-memory/scripts/pulse_admit.py b/pulse-memory/scripts/pulse_admit.py new file mode 100755 index 0000000..b14bdfc --- /dev/null +++ b/pulse-memory/scripts/pulse_admit.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Admit one memory trace, with a content hash and a prefetch key. + + pulse_admit.py NAT_KEY SNIPPET [source] [status] [kind] [lock] + pulse_admit.py --supersede OLD_KEY NAT_KEY SNIPPET [source] [status] [kind] [lock] + echo '{"nat_key":"...","snippet":"..."}' | pulse_admit.py --json +""" + +import json +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from pulse_common import ( + AdmitRejected, + admit, + connect, + reject_and_maybe_archive, +) + + +def run_admit(obj, source_explicit=True, supersede=None): + conn = connect() + try: + return admit( + conn, + obj["nat_key"], + obj["snippet"], + obj.get("source", "steward"), + obj.get("status", "user-stated"), + obj.get("kind", "memory"), + obj.get("lock", "open"), + obj.get("time"), + supersede=supersede or obj.get("supersede") or obj.get("supersedes"), + source_explicit=source_explicit, + topic=obj.get("topic"), + ) + except AdmitRejected as exc: + reject_and_maybe_archive( + conn, + exc.reason, + obj.get("source", "unknown"), + obj.get("nat_key"), + obj.get("snippet"), + exc.archive, + ) + print(f"rejected:{exc.reason}") + sys.exit(3) + finally: + conn.close() + + +def from_json(raw, supersede=None): + if not raw.strip(): + raise SystemExit("empty stdin for --json") + obj = json.loads(raw) + source_explicit = "source" in obj + print(run_admit(obj, source_explicit=source_explicit, supersede=supersede)) + + +def main(): + args = sys.argv[1:] + supersede = None + if args and args[0] == "--supersede": + if len(args) < 2: + print("usage: pulse_admit.py --supersede OLD_KEY ...", file=sys.stderr) + sys.exit(2) + supersede = args[1] + args = args[2:] + if args and args[0] in ("--json", "-j"): + from_json(sys.stdin.read(), supersede=supersede) + return + if not args and not sys.stdin.isatty(): + raw = sys.stdin.read() + if raw.strip().startswith("{"): + from_json(raw, supersede=supersede) + return + if len(args) < 2: + print( + "usage: pulse_admit.py NAT_KEY SNIPPET [source] [status] [kind] [lock]\n" + " pulse_admit.py --supersede OLD_KEY NAT_KEY SNIPPET [...]\n" + " pulse_admit.py --json < trace.json", + file=sys.stderr, + ) + sys.exit(2) + obj = { + "nat_key": args[0], + "snippet": args[1], + "source": args[2] if len(args) > 2 else "steward", + "status": args[3] if len(args) > 3 else "user-stated", + "kind": args[4] if len(args) > 4 else "memory", + "lock": args[5] if len(args) > 5 else "open", + } + source_explicit = len(args) > 2 + print(run_admit(obj, source_explicit=source_explicit, supersede=supersede)) + + +if __name__ == "__main__": + main() diff --git a/pulse-memory/scripts/pulse_backfill.py b/pulse-memory/scripts/pulse_backfill.py new file mode 100755 index 0000000..8392ddc --- /dev/null +++ b/pulse-memory/scripts/pulse_backfill.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +"""Fill empty verify_hash and prefetch_key values. Idempotent. No deletes.""" + +import json +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from pulse_common import backfill, connect + + +def main(): + if "-h" in sys.argv or "--help" in sys.argv: + print("usage: pulse_backfill.py") + return + conn = connect() + try: + result = backfill(conn) + print(json.dumps(result, ensure_ascii=False)) + if result["before"] != result["after"]: + sys.exit(1) + finally: + conn.close() + + +if __name__ == "__main__": + main() diff --git a/pulse-memory/scripts/pulse_common.py b/pulse-memory/scripts/pulse_common.py new file mode 100755 index 0000000..4b52d8d --- /dev/null +++ b/pulse-memory/scripts/pulse_common.py @@ -0,0 +1,524 @@ +#!/usr/bin/env python3 +"""Shared pulse admit, retrieve, and backfill helpers. Stdlib only.""" + +from __future__ import annotations + +import hashlib +import hmac +import json +import os +import re +import sqlite3 +from datetime import datetime, timezone +from pathlib import Path + +HASH_ALG = "sha256" +STATUSES = ("user-stated", "tool-verified", "inferred", "unknown") +KINDS = ("data", "context", "fact", "memory") +LOCKS = ("open", "locked") +STATUS_RANK = { + "tool-verified": 40, + "user-stated": 30, + "inferred": 10, + "unknown": 0, +} +MAX_SNIPPET_CHARS = 800 +MAX_RETRIEVE = 8 +DEFAULT_RETRIEVE = 1 + +SCHEMA = """ +PRAGMA journal_mode = WAL; +PRAGMA foreign_keys = ON; +CREATE TABLE IF NOT EXISTS schema_migrations ( + version INTEGER PRIMARY KEY, + applied_at TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS archive_events ( + id INTEGER PRIMARY KEY, + ts TEXT NOT NULL, + source TEXT NOT NULL, + payload TEXT NOT NULL, + correlation_id TEXT +); +CREATE TABLE IF NOT EXISTS memory_traces ( + id INTEGER PRIMARY KEY, + nat_key TEXT NOT NULL UNIQUE, + snippet TEXT NOT NULL, + source TEXT NOT NULL, + time TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN + ('user-stated','tool-verified','inferred','unknown')), + kind TEXT NOT NULL CHECK (kind IN + ('data','context','fact','memory')), + lock TEXT NOT NULL DEFAULT 'open' CHECK (lock IN ('open','locked')), + verify_hash TEXT, + prefetch_key TEXT, + seen_count INTEGER NOT NULL DEFAULT 1, + superseded_by TEXT, + first_seen TEXT NOT NULL, + last_seen TEXT NOT NULL +); +CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5( + nat_key, snippet, source, content='memory_traces', content_rowid='id' +); +CREATE TABLE IF NOT EXISTS conflicts ( + id INTEGER PRIMARY KEY, + subject TEXT NOT NULL, + left_id INTEGER NOT NULL REFERENCES memory_traces(id), + right_id INTEGER NOT NULL REFERENCES memory_traces(id), + resolution TEXT NOT NULL, + ts TEXT NOT NULL +); +""" + + +class AdmitRejected(Exception): + def __init__(self, reason, archive=False): + super().__init__(reason) + self.reason = reason + self.archive = archive + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def db_path() -> Path: + env = os.environ.get("PULSE_MEMORY_DB") + if env: + return Path(env) + return Path.home() / ".local/share/pulse-memory/pulse.sqlite" + + +def connect(): + path = db_path() + if not path.exists(): + raise SystemExit(f"missing db: {path} (run pulse_init_db.py)") + conn = sqlite3.connect(path) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys = ON") + return conn + + +def init_schema(conn): + conn.executescript(SCHEMA) + cur = conn.execute("SELECT 1 FROM schema_migrations WHERE version=1") + if not cur.fetchone(): + conn.execute( + "INSERT INTO schema_migrations(version, applied_at) VALUES (1, ?)", + (now(),), + ) + conn.commit() + + +def content_hash(snippet: str) -> str: + digest = hashlib.sha256(snippet.encode("utf-8")).hexdigest() + return f"{HASH_ALG}:{digest}" + + +def hash_matches(snippet: str, stored) -> bool: + if not stored: + return False + expected = content_hash(snippet) + if len(expected) != len(stored): + return False + return hmac.compare_digest(expected, stored) + + +def topic_of(nat_key: str) -> str: + key = nat_key.split("#", 1)[0] + if "/" in key: + parts = [part for part in key.split("/") if part] + if len(parts) >= 2: + return "/".join(parts[:-1]) + return parts[0] if parts else key + if ":" in key: + return key.split(":", 1)[0] + return key + + +def prefetch_key_for(nat_key: str, kind: str, topic: str | None = None) -> str: + chosen = (topic or topic_of(nat_key)).strip() + if not chosen: + chosen = nat_key.split("#", 1)[0] + return f"{chosen}/{kind}" + + +def archive_event(conn, source, payload, correlation_id=None): + body = payload if isinstance(payload, str) else json.dumps(payload, ensure_ascii=False) + conn.execute( + """INSERT INTO archive_events (ts, source, payload, correlation_id) + VALUES (?, ?, ?, ?)""", + (now(), source, body, correlation_id), + ) + + +def sync_fts(conn): + try: + conn.execute("INSERT INTO memory_fts(memory_fts) VALUES('rebuild')") + except sqlite3.OperationalError: + pass + + +def check_admit(nat_key, snippet, source, status, kind, lock, source_explicit=True): + if not nat_key or not str(nat_key).strip(): + raise AdmitRejected("empty nat_key") + if status not in STATUSES: + raise AdmitRejected("bad status") + if kind not in KINDS: + raise AdmitRejected("bad kind") + if lock not in LOCKS: + raise AdmitRejected("bad lock") + text = "" if snippet is None else str(snippet) + if not text.strip(): + raise AdmitRejected("empty snippet", archive=True) + if len(text) > MAX_SNIPPET_CHARS: + raise AdmitRejected("snippet too long for a pulse", archive=True) + if status == "inferred" and not source_explicit: + raise AdmitRejected("inferred write needs an explicit source", archive=True) + if status == "inferred" and not str(source or "").strip(): + raise AdmitRejected("inferred write needs a source", archive=True) + if status == "inferred" and lock == "locked": + raise AdmitRejected("inferred write cannot be locked") + return text + + +def admit( + conn, + nat_key, + snippet, + source="steward", + status="user-stated", + kind="memory", + lock="open", + time=None, + supersede=None, + source_explicit=True, + topic=None, +): + text = check_admit(nat_key, snippet, source, status, kind, lock, source_explicit) + t = time or now() + vhash = content_hash(text) + pkey = prefetch_key_for(nat_key, kind, topic) + row = conn.execute( + "SELECT * FROM memory_traces WHERE nat_key=?", (nat_key,) + ).fetchone() + if row is None: + conn.execute( + """INSERT INTO memory_traces + (nat_key, snippet, source, time, status, kind, lock, + verify_hash, prefetch_key, seen_count, superseded_by, + first_seen, last_seen) + VALUES (?,?,?,?,?,?,?,?,?,1,NULL,?,?)""", + (nat_key, text, source, t, status, kind, lock, vhash, pkey, t, t), + ) + _maybe_supersede(conn, nat_key, supersede) + if kind == "data": + archive_event( + conn, + source, + {"nat_key": nat_key, "kind": kind, "reason": "data stays in archive"}, + nat_key, + ) + sync_fts(conn) + conn.commit() + return "inserted" + if row["lock"] == "locked" and (row["snippet"] != text or row["status"] != status): + suffix = t.replace(":", "").replace("-", "")[:15] + new_key = f"{nat_key}#{suffix}" + fork_hash = content_hash(text) + fork_prefetch = prefetch_key_for(nat_key, kind, topic) + conn.execute( + """INSERT INTO memory_traces + (nat_key, snippet, source, time, status, kind, lock, + verify_hash, prefetch_key, seen_count, superseded_by, + first_seen, last_seen) + VALUES (?,?,?,?,?,?,?,?,?,1,NULL,?,?)""", + (new_key, text, source, t, status, kind, "open", fork_hash, fork_prefetch, t, t), + ) + new_id = conn.execute( + "SELECT id FROM memory_traces WHERE nat_key=?", (new_key,) + ).fetchone()["id"] + conn.execute( + "INSERT INTO conflicts(subject, left_id, right_id, resolution, ts) VALUES (?,?,?,?,?)", + (nat_key, row["id"], new_id, "not averaged", t), + ) + sync_fts(conn) + conn.commit() + return f"conflict->{new_key}" + conn.execute( + """UPDATE memory_traces SET seen_count=seen_count+1, last_seen=?, + snippet=CASE WHEN lock='open' THEN ? ELSE snippet END, + status=CASE WHEN lock='open' THEN ? ELSE status END, + source=CASE WHEN lock='open' THEN ? ELSE source END, + verify_hash=CASE WHEN lock='open' THEN ? ELSE verify_hash END, + prefetch_key=CASE WHEN lock='open' THEN ? ELSE prefetch_key END, + kind=CASE WHEN lock='open' THEN ? ELSE kind END + WHERE nat_key=?""", + (t, text, status, source, vhash, pkey, kind, nat_key), + ) + _maybe_supersede(conn, nat_key, supersede) + sync_fts(conn) + conn.commit() + return "upserted" + + +def _maybe_supersede(conn, winner, superseded): + if not superseded or superseded == winner: + return + conn.execute( + """UPDATE memory_traces SET superseded_by=? + WHERE nat_key=? AND (superseded_by IS NULL OR superseded_by='')""", + (winner, superseded), + ) + + +def reject_and_maybe_archive(conn, reason, source, nat_key, snippet, archive): + if archive: + archive_event( + conn, + source or "unknown", + { + "nat_key": nat_key, + "reason": reason, + "snippet_chars": len(snippet or ""), + }, + nat_key, + ) + conn.commit() + + +def like_escape(value: str) -> str: + return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + + +def is_stale(row) -> bool: + return bool(row["superseded_by"]) + + +def unknown_result(reason, corpus_chars, key=None): + return { + "ok": False, + "status": "unknown", + "reason": reason, + "key": key, + "pulses": [], + "stats": { + "returned": 0, + "corpus_chars": corpus_chars, + "returned_chars": 0, + "avoided_chars": corpus_chars or 0, + }, + } + + +def pulse_packet(row): + return { + "key": row["nat_key"], + "verify": row["verify_hash"], + "prefetch": row["prefetch_key"], + "snippet": row["snippet"], + "hint": { + "source": row["source"], + "time": row["time"], + "status": row["status"], + "kind": row["kind"], + "lock": row["lock"], + }, + "trust": "locked" if row["lock"] == "locked" else "belief", + } + + +def score_row(row, wanted: str) -> int: + key = row["nat_key"] + points = 100 + if key == wanted: + points = 1000 + elif row["prefetch_key"] == wanted: + points = 500 + elif key.startswith(wanted.rstrip("/") + "/") or key.startswith(wanted): + points = 300 + if row["lock"] == "locked": + points += 50 + points += STATUS_RANK.get(row["status"], 0) + points += {"memory": 8, "fact": 6, "context": 2, "data": 0}.get(row["kind"], 0) + return points + + +def fts_or_like(conn, wanted: str): + if wanted.strip() in {"*", "%", "match-all"}: + return [] + tokens = re.findall(r"[A-Za-z0-9_./:-]+", wanted) + if not tokens or tokens == ["*"]: + return [] + try: + match = " AND ".join('"' + token.replace('"', "") + '"' for token in tokens[:8]) + return list( + conn.execute( + """SELECT memory_traces.* FROM memory_traces + JOIN memory_fts ON memory_fts.rowid = memory_traces.id + WHERE memory_fts MATCH ? + LIMIT 16""", + (match,), + ) + ) + except sqlite3.OperationalError: + pattern = "%" + like_escape(wanted) + "%" + return list( + conn.execute( + """SELECT * FROM memory_traces + WHERE nat_key LIKE ? ESCAPE '\\' OR snippet LIKE ? ESCAPE '\\' + LIMIT 16""", + (pattern, pattern), + ) + ) + + +def lookup_rows(conn, wanted: str, key=None, prefetch_key=None): + if key: + return list(conn.execute("SELECT * FROM memory_traces WHERE nat_key=?", (key,))), True + if prefetch_key: + return list( + conn.execute("SELECT * FROM memory_traces WHERE prefetch_key=?", (prefetch_key,)) + ), False + rows = list(conn.execute("SELECT * FROM memory_traces WHERE nat_key=?", (wanted,))) + if rows: + return rows, True + rows = list(conn.execute("SELECT * FROM memory_traces WHERE prefetch_key=?", (wanted,))) + if rows: + return rows, False + prefix = like_escape(wanted.rstrip("/")) + rows = list( + conn.execute( + """SELECT * FROM memory_traces + WHERE nat_key = ? OR nat_key LIKE ? ESCAPE '\\' + LIMIT 16""", + (wanted, prefix + "/%"), + ) + ) + if rows: + return rows, False + return fts_or_like(conn, wanted), False + + +def retrieve(conn, query="", limit=DEFAULT_RETRIEVE, key=None, prefetch_key=None): + try: + limit = int(limit) + except (TypeError, ValueError): + limit = DEFAULT_RETRIEVE + if limit < 1: + limit = 1 + if limit > MAX_RETRIEVE: + limit = MAX_RETRIEVE + corpus_chars = conn.execute( + "SELECT COALESCE(SUM(length(snippet)), 0) FROM memory_traces" + ).fetchone()[0] + wanted = (key or prefetch_key or query or "").strip() + if not wanted: + return unknown_result("empty_query", corpus_chars) + rows, exact = lookup_rows(conn, wanted, key=key, prefetch_key=prefetch_key) + mismatches = [] + stale = [] + candidates = [] + for row in rows: + if is_stale(row): + stale.append(row) + continue + if not hash_matches(row["snippet"], row["verify_hash"]): + mismatches.append(row) + continue + if row["kind"] == "data" and not ( + key or row["nat_key"] == (query or "").strip() + ): + continue + candidates.append(row) + if exact and not candidates: + if mismatches: + return unknown_result("hash_mismatch", corpus_chars, key=wanted) + if stale: + return unknown_result("stale", corpus_chars, key=wanted) + return unknown_result("not_in_the_evidence", corpus_chars, key=wanted) + if not candidates: + if mismatches and not stale: + return unknown_result("hash_mismatch", corpus_chars, key=wanted) + if stale and not mismatches: + return unknown_result("stale", corpus_chars, key=wanted) + return unknown_result("not_in_the_evidence", corpus_chars, key=wanted) + candidates.sort( + key=lambda row: ( + score_row(row, wanted), + row["lock"] == "locked", + STATUS_RANK.get(row["status"], 0), + row["last_seen"] or row["time"] or "", + ), + reverse=True, + ) + locked = [row for row in candidates if row["lock"] == "locked"] + if locked: + locked_topics = {topic_of(row["nat_key"]) for row in locked} + narrowed = [] + for row in candidates: + if row["lock"] == "locked" or topic_of(row["nat_key"]) not in locked_topics: + narrowed.append(row) + candidates = narrowed + chosen = candidates[:limit] + pulses = [pulse_packet(row) for row in chosen] + returned_chars = sum(len(pulse["snippet"]) for pulse in pulses) + return { + "ok": True, + "mode": "pulse", + "pulses": pulses, + "unknown": None, + "stats": { + "returned": len(pulses), + "corpus_chars": corpus_chars, + "returned_chars": returned_chars, + "avoided_chars": max(int(corpus_chars) - returned_chars, 0), + }, + } + + +def backfill(conn): + rows = conn.execute( + """SELECT id, nat_key, snippet, kind, verify_hash, prefetch_key + FROM memory_traces""" + ).fetchall() + before = len(rows) + filled_hash = 0 + filled_prefetch = 0 + for row in rows: + sets = [] + args = [] + if not row["verify_hash"]: + sets.append("verify_hash=?") + args.append(content_hash(row["snippet"])) + filled_hash += 1 + if not row["prefetch_key"]: + sets.append("prefetch_key=?") + args.append(prefetch_key_for(row["nat_key"], row["kind"])) + filled_prefetch += 1 + if sets: + args.append(row["id"]) + conn.execute( + f"UPDATE memory_traces SET {', '.join(sets)} WHERE id=?", + args, + ) + sync_fts(conn) + conn.commit() + after = conn.execute("SELECT COUNT(*) FROM memory_traces").fetchone()[0] + empty_hash = conn.execute( + """SELECT COUNT(*) FROM memory_traces + WHERE verify_hash IS NULL OR verify_hash=''""" + ).fetchone()[0] + empty_prefetch = conn.execute( + """SELECT COUNT(*) FROM memory_traces + WHERE prefetch_key IS NULL OR prefetch_key=''""" + ).fetchone()[0] + return { + "before": before, + "after": after, + "filled_hash": filled_hash, + "filled_prefetch": filled_prefetch, + "empty_hash": empty_hash, + "empty_prefetch": empty_prefetch, + } diff --git a/pulse-memory/scripts/pulse_retrieve.py b/pulse-memory/scripts/pulse_retrieve.py new file mode 100755 index 0000000..d092a39 --- /dev/null +++ b/pulse-memory/scripts/pulse_retrieve.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Return one verified pulse, or a few, never the whole store. + + pulse_retrieve.py QUERY + pulse_retrieve.py --key NAT_KEY + pulse_retrieve.py --prefetch PREFETCH_KEY + pulse_retrieve.py --limit N QUERY +""" + +import json +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from pulse_common import MAX_RETRIEVE, connect, retrieve + + +def main(): + args = sys.argv[1:] + key = None + prefetch = None + limit = 1 + query_parts = [] + i = 0 + while i < len(args): + token = args[i] + if token == "--key": + if i + 1 >= len(args): + print("usage: pulse_retrieve.py --key NAT_KEY", file=sys.stderr) + sys.exit(2) + key = args[i + 1] + i += 2 + continue + if token in ("--prefetch", "--prefetch-key"): + if i + 1 >= len(args): + print("usage: pulse_retrieve.py --prefetch PREFETCH_KEY", file=sys.stderr) + sys.exit(2) + prefetch = args[i + 1] + i += 2 + continue + if token == "--limit": + if i + 1 >= len(args): + print("usage: pulse_retrieve.py --limit N QUERY", file=sys.stderr) + sys.exit(2) + limit = args[i + 1] + i += 2 + continue + if token in ("-h", "--help"): + print( + "usage: pulse_retrieve.py QUERY\n" + " pulse_retrieve.py --key NAT_KEY\n" + " pulse_retrieve.py --prefetch PREFETCH_KEY\n" + f" pulse_retrieve.py --limit N QUERY (max {MAX_RETRIEVE})" + ) + return + query_parts.append(token) + i += 1 + query = " ".join(query_parts) + conn = connect() + try: + result = retrieve( + conn, + query=query, + limit=limit, + key=key, + prefetch_key=prefetch, + ) + print(json.dumps(result, ensure_ascii=False)) + sys.exit(0) + finally: + conn.close() + + +if __name__ == "__main__": + main() diff --git a/pulse-memory/skills/pulse-memory/SKILL.md b/pulse-memory/skills/pulse-memory/SKILL.md index c5bfa84..7262fa8 100644 --- a/pulse-memory/skills/pulse-memory/SKILL.md +++ b/pulse-memory/skills/pulse-memory/SKILL.md @@ -89,6 +89,16 @@ pulse: hint: { source, time, status, kind, lock } ``` +Retrieve with the CLI. Inject one verified pulse, not a transcript dump: + +```text +pulse_retrieve.py apply/example/constraints +pulse_retrieve.py --prefetch apply/example/fact +pulse_retrieve.py --limit 3 apply/example +``` + +`PULSE_MEMORY_DB` selects the store. The command checks `verify_hash` before it returns a snippet. A mismatch or a superseded row comes back as `unknown` / not in the evidence. Prefetch keys are `{topic}/{kind}` from `nat_key`, kind, and topic. Admit computes both fields; `pulse_backfill.py` fills empty rows without deleting any. + --- ## Done when diff --git a/pulse-memory/skills/pulse-memory/references/admissions.md b/pulse-memory/skills/pulse-memory/references/admissions.md index 84ebdfa..88abddd 100644 --- a/pulse-memory/skills/pulse-memory/references/admissions.md +++ b/pulse-memory/skills/pulse-memory/references/admissions.md @@ -30,3 +30,5 @@ snippet # ~120 verified tokens, not a dump ``` Dumping grows *n* in the wrong direction (noise, heat, lost-in-the-middle). Pulse keeps the working set small and barriers high. + +`pulse_retrieve.py` is the inject path. It checks the hash, skips superseded rows, prefers locked traces over open belief, and returns unknown when the check fails. diff --git a/pulse-memory/skills/pulse-memory/references/store.md b/pulse-memory/skills/pulse-memory/references/store.md index 1fc8068..3c388c5 100644 --- a/pulse-memory/skills/pulse-memory/references/store.md +++ b/pulse-memory/skills/pulse-memory/references/store.md @@ -9,6 +9,9 @@ Default file: $XDG_DATA_HOME/tstack/state.sqlite, or ~/.local/share/tstack/state | Tool | Job | |------|-----| | `tstack-state` | writes, FTS rebuild, and migrations. The `sqlite3` CLI is inspect only. | +| `scripts/pulse_admit.py` | admit one tagged snippet; store `verify_hash` and `prefetch_key` | +| `scripts/pulse_retrieve.py` | return one verified pulse, or a few, never the whole store | +| `scripts/pulse_backfill.py` | fill empty hash and prefetch values; no deletes | | `/pulse-memory` skill | tag + resolve in the conversation | | `/workflow pulse-memory` | one pulse cycle over thinking + harness files | | scheduler (host) | fire the workflow; pass `as_of` (script has no wall clock) | @@ -75,9 +78,9 @@ Upsert: `ON CONFLICT(nat_key) DO UPDATE SET seen_count = seen_count + 1, last_se ## Admissions write path 1. Candidate claim → hint tags required; else reject. -2. Test: would it change **this** next action? No → `archive_events` only. +2. Test: would it change **this** next action? No → `archive_events` only. The CLI also rejects an empty snippet, a snippet over 800 characters, an inferred write with no explicit source, and an inferred write marked locked. 3. Conflict with existing `nat_key` → do not average; rank time then status; loser stays archive; winner is memory; log `conflicts`. -4. Inject only `kind = memory` rows with `superseded_by IS NULL`, newest `time` first, **LIMIT 8**. +4. Retrieve injects current `fact` or `memory` rows with a matching hash, `superseded_by IS NULL`, newest and locked first, **LIMIT 8**. A mismatch or a stale row is unknown, not a dump. ## What not to add (YAGNI) diff --git a/pulse-memory/test/test-thin.sh b/pulse-memory/test/test-thin.sh index 825e6ca..c04ef0b 100755 --- a/pulse-memory/test/test-thin.sh +++ b/pulse-memory/test/test-thin.sh @@ -22,6 +22,10 @@ need skills/pulse-memory/references/usecases.md need .grok/workflows/pulse-memory.rhai need test/fixtures/thinking.md need test/fixtures/harness.md +need scripts/pulse_common.py +need scripts/pulse_admit.py +need scripts/pulse_retrieve.py +need scripts/pulse_backfill.py if [[ -d "$ROOT/c" ]]; then bad "c/ present — EVA owns tether"; else ok "no c/"; fi if [[ -d "$ROOT/hooks" ]] || [[ -f "$ROOT/hooks.json" ]]; then bad "hooks — Winds"; else ok "no hooks"; fi @@ -90,6 +94,12 @@ sys.exit(fail) PY if [[ "$python_rc" -ne 0 ]]; then fail=$((fail + python_rc)); fi +if python3 "$ROOT/test/test_retrieve.py"; then + ok "retrieve tests" +else + bad "retrieve tests" +fi + echo "---" if [[ "$fail" -ne 0 ]]; then echo "$fail failure(s)" diff --git a/pulse-memory/test/test_retrieve.py b/pulse-memory/test/test_retrieve.py new file mode 100755 index 0000000..0f738a4 --- /dev/null +++ b/pulse-memory/test/test_retrieve.py @@ -0,0 +1,347 @@ +#!/usr/bin/env python3 +"""Admit, retrieve, hash, prefetch, and backfill tests. Uses temp DBs only.""" + +import json +import os +import sqlite3 +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) + +from pulse_common import ( # noqa: E402 + AdmitRejected, + MAX_RETRIEVE, + admit, + backfill, + content_hash, + hash_matches, + init_schema, + prefetch_key_for, + retrieve, + topic_of, +) + + +def fresh(): + tmp = tempfile.TemporaryDirectory() + path = Path(tmp.name) / "pulse.sqlite" + conn = sqlite3.connect(path) + conn.row_factory = sqlite3.Row + init_schema(conn) + return tmp, conn + + +class HashAndPrefetch(unittest.TestCase): + def test_hash_is_deterministic_and_prefixed(self): + first = content_hash("locked revision") + second = content_hash("locked revision") + other = content_hash("other revision") + self.assertTrue(first.startswith("sha256:")) + self.assertEqual(first, second) + self.assertNotEqual(first, other) + self.assertTrue(hash_matches("locked revision", first)) + self.assertFalse(hash_matches("locked revision", other)) + self.assertFalse(hash_matches("locked revision", None)) + self.assertFalse(hash_matches("locked revision", "")) + + def test_prefetch_key_from_nat_key_kind_and_topic(self): + self.assertEqual(topic_of("apply/example/constraints"), "apply/example") + self.assertEqual( + prefetch_key_for("apply/example/constraints", "fact"), + "apply/example/fact", + ) + self.assertEqual(prefetch_key_for("hunt/ledger/demo", "memory"), "hunt/ledger/memory") + self.assertEqual(prefetch_key_for("civic:item", "fact"), "civic/fact") + self.assertEqual(prefetch_key_for("solo", "memory"), "solo/memory") + self.assertEqual( + prefetch_key_for("apply/example/constraints#fork", "fact"), + "apply/example/fact", + ) + self.assertEqual( + prefetch_key_for("apply/example/constraints", "fact", topic="apply/example"), + "apply/example/fact", + ) + + +class AdmitAndRetrieve(unittest.TestCase): + def setUp(self): + self.tmp, self.conn = fresh() + + def tearDown(self): + self.conn.close() + self.tmp.cleanup() + + def test_admit_fills_hash_and_prefetch(self): + status = admit( + self.conn, + "apply/example/constraints", + "Keep the apply example under the published cap.", + source="test", + status="user-stated", + kind="fact", + lock="locked", + ) + self.assertEqual(status, "inserted") + row = self.conn.execute( + "SELECT * FROM memory_traces WHERE nat_key=?", + ("apply/example/constraints",), + ).fetchone() + self.assertEqual(row["verify_hash"], content_hash(row["snippet"])) + self.assertEqual(row["prefetch_key"], "apply/example/fact") + + def test_retrieve_exact_key_returns_one_pulse(self): + admit( + self.conn, + "apply/example/constraints", + "Keep the apply example under the published cap.", + source="test", + status="tool-verified", + kind="fact", + lock="locked", + ) + admit( + self.conn, + "apply/example/projects", + "Show three public projects on the apply example.", + source="test", + status="user-stated", + kind="memory", + ) + result = retrieve(self.conn, key="apply/example/constraints") + self.assertTrue(result["ok"]) + self.assertEqual(len(result["pulses"]), 1) + pulse = result["pulses"][0] + self.assertEqual(pulse["key"], "apply/example/constraints") + self.assertEqual(pulse["verify"], content_hash(pulse["snippet"])) + self.assertEqual(pulse["prefetch"], "apply/example/fact") + self.assertEqual(pulse["trust"], "locked") + self.assertLess(result["stats"]["returned_chars"], result["stats"]["corpus_chars"]) + self.assertGreater(result["stats"]["avoided_chars"], 0) + + def test_retrieve_prefetch_returns_neighborhood(self): + admit(self.conn, "apply/example/one", "First example pulse.", source="test", kind="memory") + admit(self.conn, "apply/example/two", "Second example pulse.", source="test", kind="memory") + admit(self.conn, "other/topic/three", "Unrelated pulse.", source="test", kind="memory") + result = retrieve(self.conn, prefetch_key="apply/example/memory", limit=3) + self.assertTrue(result["ok"]) + keys = {pulse["key"] for pulse in result["pulses"]} + self.assertEqual(keys, {"apply/example/one", "apply/example/two"}) + self.assertNotIn("other/topic/three", keys) + + def test_hash_mismatch_is_unknown(self): + admit(self.conn, "apply/example/constraints", "Original pulse.", source="test") + self.conn.execute( + "UPDATE memory_traces SET snippet=? WHERE nat_key=?", + ("tampered pulse", "apply/example/constraints"), + ) + self.conn.commit() + result = retrieve(self.conn, key="apply/example/constraints") + self.assertFalse(result["ok"]) + self.assertEqual(result["status"], "unknown") + self.assertEqual(result["reason"], "hash_mismatch") + self.assertEqual(result["pulses"], []) + + def test_stale_row_is_unknown(self): + admit(self.conn, "apply/example/old", "Old constraint.", source="test") + admit( + self.conn, + "apply/example/new", + "New constraint.", + source="test", + supersede="apply/example/old", + ) + result = retrieve(self.conn, key="apply/example/old") + self.assertFalse(result["ok"]) + self.assertEqual(result["reason"], "stale") + fresh = retrieve(self.conn, key="apply/example/new") + self.assertTrue(fresh["ok"]) + self.assertEqual(fresh["pulses"][0]["key"], "apply/example/new") + + def test_empty_or_star_query_does_not_dump(self): + for i in range(12): + admit(self.conn, f"apply/example/{i}", f"Example pulse {i}.", source="test") + empty = retrieve(self.conn, query="") + star = retrieve(self.conn, query="*") + self.assertFalse(empty["ok"]) + self.assertEqual(empty["reason"], "empty_query") + self.assertEqual(empty["pulses"], []) + self.assertFalse(star["ok"]) + self.assertEqual(star["pulses"], []) + capped = retrieve(self.conn, query="example", limit=99) + self.assertLessEqual(len(capped["pulses"]), MAX_RETRIEVE) + self.assertLessEqual(capped["stats"]["returned"], MAX_RETRIEVE) + + def test_prefers_locked_over_belief(self): + admit( + self.conn, + "apply/example/belief", + "A guessed constraint.", + source="test", + status="user-stated", + kind="memory", + lock="open", + ) + admit( + self.conn, + "apply/example/locked", + "The locked constraint.", + source="test", + status="tool-verified", + kind="memory", + lock="locked", + ) + result = retrieve(self.conn, query="apply/example", limit=3) + self.assertTrue(result["ok"]) + keys = [pulse["key"] for pulse in result["pulses"]] + self.assertIn("apply/example/locked", keys) + self.assertNotIn("apply/example/belief", keys) + self.assertEqual(result["pulses"][0]["trust"], "locked") + + def test_missing_key_is_unknown(self): + result = retrieve(self.conn, key="apply/example/missing") + self.assertFalse(result["ok"]) + self.assertEqual(result["reason"], "not_in_the_evidence") + self.assertEqual(result["status"], "unknown") + + +class AdmitRejects(unittest.TestCase): + def setUp(self): + self.tmp, self.conn = fresh() + + def tearDown(self): + self.conn.close() + self.tmp.cleanup() + + def test_empty_snippet_is_archived(self): + with self.assertRaises(AdmitRejected) as caught: + admit(self.conn, "apply/example/empty", " ", source="test") + self.assertTrue(caught.exception.archive) + + def test_inferred_needs_explicit_source(self): + with self.assertRaises(AdmitRejected): + admit( + self.conn, + "apply/example/guess", + "A guess.", + source="steward", + status="inferred", + source_explicit=False, + ) + + def test_inferred_cannot_lock(self): + with self.assertRaises(AdmitRejected): + admit( + self.conn, + "apply/example/guess", + "A guess.", + source="test", + status="inferred", + lock="locked", + source_explicit=True, + ) + + def test_too_long_snippet_is_rejected(self): + with self.assertRaises(AdmitRejected) as caught: + admit(self.conn, "apply/example/long", "x" * 801, source="test") + self.assertEqual(caught.exception.reason, "snippet too long for a pulse") + + def test_locked_conflict_is_not_averaged(self): + admit( + self.conn, + "apply/example/cap", + "First locked text.", + source="test", + lock="locked", + ) + result = admit( + self.conn, + "apply/example/cap", + "Second disagreeing text.", + source="test", + lock="open", + ) + self.assertTrue(result.startswith("conflict->")) + count = self.conn.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0] + self.assertEqual(count, 1) + original = self.conn.execute( + "SELECT snippet FROM memory_traces WHERE nat_key=?", + ("apply/example/cap",), + ).fetchone()[0] + self.assertEqual(original, "First locked text.") + + +class Backfill(unittest.TestCase): + def test_backfill_is_idempotent_and_keeps_row_count(self): + tmp, conn = fresh() + try: + admit(conn, "apply/example/one", "One.", source="test") + admit(conn, "apply/example/two", "Two.", source="test") + conn.execute( + "UPDATE memory_traces SET verify_hash=NULL, prefetch_key=NULL" + ) + conn.commit() + first = backfill(conn) + self.assertEqual(first["before"], 2) + self.assertEqual(first["after"], 2) + self.assertEqual(first["filled_hash"], 2) + self.assertEqual(first["filled_prefetch"], 2) + self.assertEqual(first["empty_hash"], 0) + self.assertEqual(first["empty_prefetch"], 0) + row = conn.execute( + "SELECT verify_hash, prefetch_key, snippet FROM memory_traces WHERE nat_key=?", + ("apply/example/one",), + ).fetchone() + self.assertEqual(row["verify_hash"], content_hash(row["snippet"])) + self.assertEqual(row["prefetch_key"], "apply/example/memory") + second = backfill(conn) + self.assertEqual(second["before"], 2) + self.assertEqual(second["after"], 2) + self.assertEqual(second["filled_hash"], 0) + self.assertEqual(second["filled_prefetch"], 0) + finally: + conn.close() + tmp.cleanup() + + +class CliSmoke(unittest.TestCase): + def test_cli_admit_retrieve_roundtrip(self): + import subprocess + + tmp = tempfile.TemporaryDirectory() + db = Path(tmp.name) / "pulse.sqlite" + conn = sqlite3.connect(db) + init_schema(conn) + conn.close() + env = os.environ.copy() + env["PULSE_MEMORY_DB"] = str(db) + admit_py = ROOT / "scripts" / "pulse_admit.py" + retrieve_py = ROOT / "scripts" / "pulse_retrieve.py" + backfill_py = ROOT / "scripts" / "pulse_backfill.py" + inserted = subprocess.check_output( + [sys.executable, str(admit_py), "apply/example/cli", "CLI pulse.", "test", "user-stated", "memory", "open"], + env=env, + text=True, + ).strip() + self.assertEqual(inserted, "inserted") + payload = json.loads( + subprocess.check_output( + [sys.executable, str(retrieve_py), "--key", "apply/example/cli"], + env=env, + text=True, + ) + ) + self.assertTrue(payload["ok"]) + self.assertEqual(payload["pulses"][0]["key"], "apply/example/cli") + filled = json.loads( + subprocess.check_output([sys.executable, str(backfill_py)], env=env, text=True) + ) + self.assertEqual(filled["before"], filled["after"]) + tmp.cleanup() + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tstack/scripts/tstack-state b/tstack/scripts/tstack-state index eeadeef..de3dcdc 100755 --- a/tstack/scripts/tstack-state +++ b/tstack/scripts/tstack-state @@ -1,6 +1,7 @@ #!/usr/bin/env python3 """Shared SQLite state for the tstack loop.""" +import hashlib import json import os import re @@ -272,14 +273,50 @@ def parse_depends(conn, raw, map_id, stage_id): return parts +def content_hash(snippet): + digest = hashlib.sha256(snippet.encode("utf-8")).hexdigest() + return f"sha256:{digest}" + + +def topic_of(nat_key): + key = nat_key.split("#", 1)[0] + if "/" in key: + parts = [part for part in key.split("/") if part] + if len(parts) >= 2: + return "/".join(parts[:-1]) + return parts[0] if parts else key + if ":" in key: + return key.split(":", 1)[0] + return key + + +def prefetch_key_for(nat_key, kind, topic=None): + chosen = (topic or topic_of(nat_key)).strip() + if not chosen: + chosen = nat_key.split("#", 1)[0] + return f"{chosen}/{kind}" + + def insert_trace(conn, key, snippet, source, time_s, status, kind, lock): return conn.execute( """INSERT INTO memory_traces ( nat_key, snippet, source, time, status, kind, lock, verify_hash, prefetch_key, seen_count, superseded_by, first_seen, last_seen - ) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, NULL, 1, NULL, ?, ?)""", - (key, snippet, source, time_s, status, kind, lock, time_s, time_s), + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NULL, ?, ?)""", + ( + key, + snippet, + source, + time_s, + status, + kind, + lock, + content_hash(snippet), + prefetch_key_for(key, kind), + time_s, + time_s, + ), ) @@ -748,6 +785,10 @@ def cmd_pulse_admit(flags): lock = flags.get("lock", "open") if lock not in LOCKS: reject("bad lock") + if status == "inferred" and lock == "locked": + reject("inferred write cannot be locked") + if len(snippet) > 800: + reject("snippet too long for a pulse") conn = connect() def work(): @@ -817,6 +858,43 @@ def cmd_pulse_list(flags): ok({"rows": [{name: row[name] for name in cols} for row in rows]}) +def load_pulse_common(): + root = Path(__file__).resolve().parents[2] / "pulse-memory" / "scripts" + if str(root) not in sys.path: + sys.path.insert(0, str(root)) + try: + import pulse_common + return pulse_common + except ImportError: + return None + + +def cmd_pulse_retrieve(flags): + only(flags, "query", "key", "prefetch", "limit") + query = flags.get("query", "") + key = flags.get("key") + prefetch = flags.get("prefetch") + limit = 1 + if "limit" in flags: + if not re.fullmatch(r"[1-9][0-9]*", flags["limit"]): + usage("usage") + limit = int(flags["limit"]) + if not (query or key or prefetch): + reject("empty query") + helper = load_pulse_common() + if helper is None: + reject("retrieve helper missing") + conn = connect() + payload = helper.retrieve( + conn, + query=query, + limit=limit, + key=key, + prefetch_key=prefetch, + ) + ok(payload) + + def cmd_pulse_conflict(flags): need(flags, "subject", "left", "right", "resolution") only(flags, "subject", "left", "right", "resolution") @@ -1109,6 +1187,7 @@ COMMANDS = { "pulse archive": cmd_pulse_archive, "pulse admit": cmd_pulse_admit, "pulse list": cmd_pulse_list, + "pulse retrieve": cmd_pulse_retrieve, "pulse conflict": cmd_pulse_conflict, } diff --git a/tstack/test/test-state.sh b/tstack/test/test-state.sh index af8cbba..fdf78f0 100755 --- a/tstack/test/test-state.sh +++ b/tstack/test/test-state.sh @@ -219,6 +219,13 @@ must "row 15 close" "$STATE" block close --map loop must "row 15 archive" "$STATE" pulse archive --source harvest --payload "merged sha" must "row 15 admit" "$STATE" pulse admit --key loop/turn --snippet shipped --source harvest \ --time 2026-10-16T03:00:00Z --status tool-verified --kind memory +[[ "$(sql "SELECT substr(verify_hash,1,7) FROM memory_traces WHERE nat_key='loop/turn'")" == "sha256:" ]] \ + && ok "row 15 hash prefix" || bad "row 15 hash prefix" +[[ "$(sql "SELECT prefetch_key FROM memory_traces WHERE nat_key='loop/turn'")" == "loop/memory" ]] \ + && ok "row 15 prefetch" || bad "row 15 prefetch" +must "row 15 retrieve" "$STATE" pulse retrieve --key loop/turn +python3 -c 'import json,sys; d=json.loads(sys.argv[1]); assert d["ok"] and d["pulses"][0]["key"]=="loop/turn"' "$OUT" \ + && ok "row 15 retrieve key" || bad "row 15 retrieve key" must "row 15 done" "$STATE" stage put --map loop --id one --class Done --a 1 --m 2 --b 3 --label First must "row 15 report" "$STATE" apply-report --map loop --critical two --next two must "row 15 next" "$STATE" next --map loop