Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion pulse-memory/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ skills/pulse-memory/ # filter SoT
SKILL.md
references/admissions.md
references/store.md # SQLite archive vs memory
scripts/ # admit, retrieve, backfill
scripts/ # init, admit, retrieve, backfill
.grok/workflows/pulse-memory.rhai
test/
```
Expand All @@ -62,6 +62,7 @@ Plugins do not auto-register Rhai. Copy/symlink the workflow.
## CLI

```bash
PULSE_MEMORY_DB=./pulse.sqlite scripts/pulse_init_db.py
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
Expand Down
113 changes: 68 additions & 45 deletions pulse-memory/scripts/pulse_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,15 @@ def sync_fts(conn):
pass


MAX_KEY_CHARS = 200


def check_admit(nat_key, snippet, source, status, kind, lock, source_explicit=True):
if not nat_key or not str(nat_key).strip():
key = "" if nat_key is None else str(nat_key).strip()
if not key:
raise AdmitRejected("empty nat_key")
if len(key) > MAX_KEY_CHARS or "@" in key:
raise AdmitRejected("bad nat_key")
if status not in STATUSES:
raise AdmitRejected("bad status")
if kind not in KINDS:
Expand All @@ -180,10 +186,36 @@ def check_admit(nat_key, snippet, source, status, kind, lock, source_explicit=Tr
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(
return key, text


def fresh_key(conn, base):
n = 2
while True:
candidate = f"{base}-{n}"
if len(candidate) > MAX_KEY_CHARS:
raise AdmitRejected("bad nat_key")
taken = conn.execute(
"SELECT 1 FROM memory_traces WHERE nat_key=?", (candidate,)
).fetchone()
if taken is None:
return candidate
n += 1


def insert_trace(conn, key, text, source, t, status, kind, lock, topic=None):
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 (?,?,?,?,?,?,?,?,?,1,NULL,?,?)""",
(key, text, source, t, status, kind, lock,
content_hash(text), prefetch_key_for(key, kind, topic), t, t),
).lastrowid


def admit_row(
conn,
nat_key,
snippet,
Expand All @@ -196,71 +228,62 @@ def admit(
source_explicit=True,
topic=None,
):
text = check_admit(nat_key, snippet, source, status, kind, lock, source_explicit)
"""One admit path for pulse_admit.py and tstack-state. Caller commits."""
key, 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,)
"SELECT id, snippet, lock, seen_count FROM memory_traces WHERE nat_key=?", (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)
new_id = insert_trace(conn, key, text, source, t, status, kind, lock, topic)
_maybe_supersede(conn, key, supersede)
if kind == "data":
archive_event(
conn,
source,
{"nat_key": nat_key, "kind": kind, "reason": "data stays in archive"},
nat_key,
{"nat_key": key, "kind": kind, "reason": "data stays in archive"},
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"]
return {"action": "inserted", "id": new_id, "nat_key": key, "seen_count": 1}
if row["lock"] == "locked" and row["snippet"] != text:
fork = fresh_key(conn, key)
new_id = insert_trace(conn, fork, text, source, t, status, kind, lock, topic)
conn.execute(
"INSERT INTO conflicts(subject, left_id, right_id, resolution, ts) VALUES (?,?,?,?,?)",
(nat_key, row["id"], new_id, "not averaged", t),
(key, row["id"], new_id, "not in the evidence", t),
)
sync_fts(conn)
conn.commit()
return f"conflict->{new_key}"
return {"action": "conflict", "id": new_id, "nat_key": fork, "seen_count": 1}
conn.execute(
"""UPDATE memory_traces SET seen_count=seen_count+1, last_seen=?,
snippet=CASE WHEN lock='open' THEN ? ELSE snippet END,
time=CASE WHEN lock='open' THEN ? ELSE time 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),
WHERE id=?""",
(t, text, t, status, source, content_hash(text),
prefetch_key_for(key, kind, topic), kind, row["id"]),
)
_maybe_supersede(conn, nat_key, supersede)
_maybe_supersede(conn, key, supersede)
sync_fts(conn)
return {
"action": "upserted",
"id": row["id"],
"nat_key": key,
"seen_count": row["seen_count"] + 1,
}


def admit(conn, nat_key, snippet, *args, **kwargs):
result = admit_row(conn, nat_key, snippet, *args, **kwargs)
conn.commit()
return "upserted"
if result["action"] == "conflict":
return f"conflict->{result['nat_key']}"
return result["action"]


def _maybe_supersede(conn, winner, superseded):
Expand Down
32 changes: 32 additions & 0 deletions pulse-memory/scripts/pulse_init_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Create the pulse store at PULSE_MEMORY_DB, mode 0600. Idempotent. No deletes."""

import json
import os
import sqlite3
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from pulse_common import db_path, init_schema


def main():
if "-h" in sys.argv or "--help" in sys.argv:
print("usage: pulse_init_db.py")
return
os.umask(0o077)
path = db_path()
path.parent.mkdir(parents=True, exist_ok=True)
created = not path.exists()
conn = sqlite3.connect(path)
try:
init_schema(conn)
finally:
conn.close()
os.chmod(path, 0o600)
print(json.dumps({"db": "created" if created else "ready", "mode": "0600"}))


if __name__ == "__main__":
main()
22 changes: 20 additions & 2 deletions pulse-memory/skills/pulse-memory/references/store.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ 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_init_db.py` | create the store at `PULSE_MEMORY_DB`, mode 0600; idempotent |
| `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 |
Expand Down Expand Up @@ -73,14 +74,31 @@ CREATE TABLE IF NOT EXISTS conflicts (
);
```

Upsert: `ON CONFLICT(nat_key) DO UPDATE SET seen_count = seen_count + 1, last_seen = excluded.last_seen` **unless** `lock = 'locked'` and the new row disagrees — then insert a *new* key suffix and row in `conflicts`.
Upsert: one path, `admit_row` in `scripts/pulse_common.py`. `pulse_admit.py` and `tstack-state pulse admit` both call it.

```mermaid
%%{init: {"theme":"base","themeVariables":{"primaryColor":"#e0f2fe","primaryBorderColor":"#0284c7","lineColor":"#7c3aed","secondaryColor":"#dcfce7","tertiaryColor":"#fef3c7"}}}%%
flowchart LR
A[pulse_admit.py]:::cli --> R[admit_row]:::core
T[tstack-state pulse admit]:::cli --> R
R -->|new key| I[insert + hash + prefetch]:::ok
R -->|open| U[seen+1, newest wins]:::ok
R -->|locked, same text| S[seen+1]:::ok
R -->|locked, new text| F[key-2 + conflict row]:::warn
classDef cli fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
classDef core fill:#ede9fe,stroke:#7c3aed,color:#4c1d95
classDef ok fill:#dcfce7,stroke:#16a34a,color:#14532d
classDef warn fill:#fef3c7,stroke:#d97706,color:#78350f
```

tstack-state also refuses `@` in any field.

## Admissions write path

1. Candidate claim → hint tags required; else reject.
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. 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.
4. Retrieve injects current `fact`, `memory`, or `context` rows with a matching hash, `superseded_by IS NULL`, newest and locked first, **LIMIT 8**. A `data` row comes back only by exact key. A mismatch or a stale row is unknown, not a dump.

## What not to add (YAGNI)

Expand Down
1 change: 1 addition & 0 deletions pulse-memory/test/test-thin.sh
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ need .grok/workflows/pulse-memory.rhai
need test/fixtures/thinking.md
need test/fixtures/harness.md
need scripts/pulse_common.py
need scripts/pulse_init_db.py
need scripts/pulse_admit.py
need scripts/pulse_retrieve.py
need scripts/pulse_backfill.py
Expand Down
83 changes: 83 additions & 0 deletions pulse-memory/test/test_retrieve.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import json
import os
import sqlite3
import subprocess
import sys
import tempfile
import unittest
Expand Down Expand Up @@ -343,5 +344,87 @@ def test_cli_admit_retrieve_roundtrip(self):
tmp.cleanup()


class OneAdmitPath(unittest.TestCase):
def run_py(self, script, *args, env):
return subprocess.run(
[sys.executable, str(ROOT / "scripts" / script), *args],
env=env, text=True, capture_output=True,
)

def test_init_db_creates_private_store(self):
tmp = tempfile.TemporaryDirectory()
db = Path(tmp.name) / "nested" / "pulse.sqlite"
env = os.environ.copy()
env["PULSE_MEMORY_DB"] = str(db)
first = self.run_py("pulse_init_db.py", env=env)
self.assertEqual(first.returncode, 0, first.stderr)
self.assertEqual(json.loads(first.stdout)["db"], "created")
self.assertEqual(db.stat().st_mode & 0o777, 0o600)
again = self.run_py("pulse_init_db.py", env=env)
self.assertEqual(json.loads(again.stdout)["db"], "ready")
admitted = self.run_py("pulse_admit.py", "a/b", "kept", "test", env=env)
self.assertEqual(admitted.stdout.strip(), "inserted")
tmp.cleanup()

def test_locked_disagreement_forks_without_averaging(self):
tmp, conn = fresh()
admit(conn, "trace", "alpha", source="test", lock="locked")
self.assertEqual(admit(conn, "trace", "beta", source="test", lock="locked"), "conflict->trace-2")
self.assertEqual(admit(conn, "trace", "gamma", source="test", lock="locked"), "conflict->trace-3")
row = conn.execute("SELECT snippet FROM memory_traces WHERE nat_key='trace'").fetchone()
self.assertEqual(row["snippet"], "alpha")
res = {r[0] for r in conn.execute("SELECT resolution FROM conflicts")}
self.assertEqual(res, {"not in the evidence"})
self.assertEqual(admit(conn, "trace", "alpha", source="test", lock="locked"), "upserted")
conn.close()
tmp.cleanup()

def test_bad_key_rejected(self):
tmp, conn = fresh()
for key in ("", "a@b", "k" * 201):
with self.assertRaises(AdmitRejected):
admit(conn, key, "kept", source="test")
conn.close()
tmp.cleanup()

def test_tstack_and_cli_write_the_same_row(self):
state = ROOT.parent / "tstack" / "scripts" / "tstack-state"
if not state.exists():
self.skipTest("tstack not beside pulse-memory")
rows = []
for via in ("cli", "tstack"):
tmp = tempfile.TemporaryDirectory()
db = Path(tmp.name) / "pulse.sqlite"
env = os.environ.copy()
env.pop("TSTACK_STATE_DB", None)
env["PULSE_MEMORY_DB"] = str(db)
self.run_py("pulse_init_db.py", env=env)
when = "2026-01-01T00:00:00Z"
for snippet in ("one", "two"):
if via == "cli":
obj = {"nat_key": "loop/turn", "snippet": snippet, "source": "test",
"status": "tool-verified", "kind": "memory", "lock": "locked", "time": when}
out = subprocess.run(
[sys.executable, str(ROOT / "scripts" / "pulse_admit.py"), "--json"],
input=json.dumps(obj), env=env, text=True, capture_output=True,
)
else:
out = subprocess.run(
[sys.executable, str(state), "pulse", "admit", "--key", "loop/turn",
"--snippet", snippet, "--source", "test", "--time", when,
"--status", "tool-verified", "--kind", "memory", "--lock", "locked"],
env=env, text=True, capture_output=True,
)
self.assertEqual(out.returncode, 0, out.stdout + out.stderr)
conn = sqlite3.connect(db)
rows.append(conn.execute(
"""SELECT nat_key, snippet, status, kind, lock, verify_hash, prefetch_key, seen_count
FROM memory_traces ORDER BY nat_key"""
).fetchall() + conn.execute("SELECT subject, resolution FROM conflicts").fetchall())
conn.close()
tmp.cleanup()
self.assertEqual(rows[0], rows[1])


if __name__ == "__main__":
unittest.main(verbosity=2)
4 changes: 2 additions & 2 deletions tstack/references/state.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ tstack-state ask admit --ask TEXT
tstack-state pulse archive --source TEXT --payload TEXT [--correlation TEXT]
tstack-state pulse admit --key TEXT --snippet TEXT --source TEXT --time TEXT \
--status user-stated|tool-verified|inferred|unknown \
--kind data|context|fact|memory [--lock open|locked]
--kind data|context|fact|memory [--lock open|locked] [--supersede KEY]
tstack-state pulse list [--limit 8]
tstack-state pulse conflict --subject TEXT --left ID --right ID --resolution TEXT
tstack-state step start --map ID --stage ID --step NAME
Expand Down Expand Up @@ -77,7 +77,7 @@ Map ids and stage ids match `^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$` before insert. `d

`pulse list` returns `kind = memory` and `superseded_by IS NULL`, newest `time` first, default limit 8.

`pulse admit` inserts `seen_count = 1`, `lock` from `--lock` or `open`, and null `verify_hash`, `prefetch_key`, and `superseded_by`. `first_seen` and `last_seen` equal `--time`. On the same `nat_key`, an open lock, or a locked lock with the same snippet, bumps `seen_count` and sets `last_seen` to the new `--time`. Snippet, status, kind, and lock stay as stored. A locked key with a different snippet keeps the old row, inserts `nat_key-2` then `nat_key-3`, skipping keys that exist, and inserts `conflicts`. That path exits 0. `conflicts.subject` is the original `nat_key`, `left_id` and `right_id` are the row ids, `resolution` is `not in the evidence`, and `ts` is the new `--time`. The script does not pick a winner.
`pulse admit` calls `admit_row` in pulse-memory `scripts/pulse_common.py`, the same path as `pulse_admit.py`. It exits 3 with `pulse helper missing` when pulse-memory is not beside tstack. A new key inserts `seen_count = 1`, `verify_hash`, `prefetch_key`, and `first_seen = last_seen = --time`. An open key bumps `seen_count` and takes the newer snippet, time, status, kind, source, hash, and prefetch. A locked key with the same snippet only bumps `seen_count` and `last_seen`. A locked key with a different snippet keeps the old row, inserts `nat_key-2` then `nat_key-3`, skipping keys that exist, and inserts `conflicts`. That path exits 0. `conflicts.subject` is the original `nat_key`, `left_id` and `right_id` are the row ids, `resolution` is `not in the evidence`, and `ts` is the new `--time`. The script does not pick a winner. `--supersede KEY` marks that older key stale.

`pulse conflict --left` and `--right` are `nat_key` values. A missing key exits 3. After every `pulse admit` or `pulse conflict`, on the same connection, before commit:

Expand Down
Loading
Loading