diff --git a/pulse-memory/README.md b/pulse-memory/README.md index 0bfea96..9283398 100644 --- a/pulse-memory/README.md +++ b/pulse-memory/README.md @@ -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/ ``` @@ -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 diff --git a/pulse-memory/scripts/pulse_common.py b/pulse-memory/scripts/pulse_common.py index 4b52d8d..2c39020 100755 --- a/pulse-memory/scripts/pulse_common.py +++ b/pulse-memory/scripts/pulse_common.py @@ -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: @@ -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, @@ -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): diff --git a/pulse-memory/scripts/pulse_init_db.py b/pulse-memory/scripts/pulse_init_db.py new file mode 100755 index 0000000..34c506b --- /dev/null +++ b/pulse-memory/scripts/pulse_init_db.py @@ -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() diff --git a/pulse-memory/skills/pulse-memory/references/store.md b/pulse-memory/skills/pulse-memory/references/store.md index 3c388c5..4eb3719 100644 --- a/pulse-memory/skills/pulse-memory/references/store.md +++ b/pulse-memory/skills/pulse-memory/references/store.md @@ -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 | @@ -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) diff --git a/pulse-memory/test/test-thin.sh b/pulse-memory/test/test-thin.sh index c04ef0b..c0261c7 100755 --- a/pulse-memory/test/test-thin.sh +++ b/pulse-memory/test/test-thin.sh @@ -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 diff --git a/pulse-memory/test/test_retrieve.py b/pulse-memory/test/test_retrieve.py index 0f738a4..820bfa6 100755 --- a/pulse-memory/test/test_retrieve.py +++ b/pulse-memory/test/test_retrieve.py @@ -4,6 +4,7 @@ import json import os import sqlite3 +import subprocess import sys import tempfile import unittest @@ -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) diff --git a/tstack/references/state.md b/tstack/references/state.md index 5e0448d..e1630ca 100644 --- a/tstack/references/state.md +++ b/tstack/references/state.md @@ -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 @@ -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: diff --git a/tstack/scripts/tstack-state b/tstack/scripts/tstack-state index de3dcdc..d3ecd7c 100755 --- a/tstack/scripts/tstack-state +++ b/tstack/scripts/tstack-state @@ -1,7 +1,6 @@ #!/usr/bin/env python3 """Shared SQLite state for the tstack loop.""" -import hashlib import json import os import re @@ -14,9 +13,6 @@ SCHEMA = Path(__file__).resolve().parent / "schema.sql" ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$") CLASSES = ("Do", "Risk", "Wait", "Park", "Done") ENERGIES = ("high", "mid", "low") -STATUSES = ("user-stated", "tool-verified", "inferred", "unknown") -KINDS = ("data", "context", "fact", "memory") -LOCKS = ("open", "locked") FIGURE_WORDS = ("money", "health", "family") @@ -273,68 +269,6 @@ 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NULL, ?, ?)""", - ( - key, - snippet, - source, - time_s, - status, - kind, - lock, - content_hash(snippet), - prefetch_key_for(key, kind), - time_s, - time_s, - ), - ) - - -def fresh_key(conn, base): - n = 2 - while True: - candidate = f"{base}-{n}" - if len(candidate) > 200: - reject("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 rebuild_fts(conn): conn.execute("INSERT INTO memory_fts(memory_fts) VALUES('rebuild')") @@ -766,63 +700,37 @@ def cmd_pulse_archive(flags): def cmd_pulse_admit(flags): need(flags, "key", "snippet", "source", "time", "status", "kind") - only(flags, "key", "snippet", "source", "time", "status", "kind", "lock") + only(flags, "key", "snippet", "source", "time", "status", "kind", "lock", "supersede") key = parse_key(flags["key"]) snippet = flags["snippet"] - if not snippet.strip(): - reject("empty snippet") no_at("snippet", snippet) - source = flags["source"] time_s = flags["time"] if not time_s.strip(): reject("bad time") - status = flags["status"] - if status not in STATUSES: - reject("bad status") - kind = flags["kind"] - if kind not in KINDS: - reject("bad kind") - 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") + helper = pulse_helper() conn = connect() def work(): - row = conn.execute( - "SELECT id, snippet, lock, seen_count FROM memory_traces WHERE nat_key=?", - (key,), - ).fetchone() - if row is None: - cur = insert_trace(conn, key, snippet, source, time_s, status, kind, lock) - payload = {"id": cur.lastrowid, "nat_key": key, "seen_count": 1} - elif row["lock"] == "open" or row["snippet"] == snippet: - conn.execute( - "UPDATE memory_traces SET seen_count = seen_count + 1, last_seen=? WHERE id=?", - (time_s, row["id"]), - ) - payload = { - "id": row["id"], - "nat_key": key, - "seen_count": row["seen_count"] + 1, - } - else: - fresh = fresh_key(conn, key) - cur = insert_trace(conn, fresh, snippet, source, time_s, status, kind, lock) - new_id = cur.lastrowid - conn.execute( - """INSERT INTO conflicts (subject, left_id, right_id, resolution, ts) - VALUES (?, ?, ?, 'not in the evidence', ?)""", - (key, row["id"], new_id, time_s), - ) - payload = {"id": new_id, "nat_key": fresh, "seen_count": 1} - rebuild_fts(conn) - return payload + found = helper.admit_row( + conn, + key, + snippet, + source=flags["source"], + status=flags["status"], + kind=flags["kind"], + lock=flags.get("lock", "open"), + time=time_s, + supersede=flags.get("supersede"), + ) + return {name: found[name] for name in ("id", "nat_key", "seen_count")} - ok(in_tx(conn, work)) + try: + ok(in_tx(conn, work)) + except helper.AdmitRejected as exc: + helper.reject_and_maybe_archive( + conn, exc.reason, flags["source"], key, snippet, exc.archive + ) + reject(exc.reason) def cmd_pulse_list(flags): @@ -869,6 +777,13 @@ def load_pulse_common(): return None +def pulse_helper(): + helper = load_pulse_common() + if helper is None: + reject("pulse helper missing") + return helper + + def cmd_pulse_retrieve(flags): only(flags, "query", "key", "prefetch", "limit") query = flags.get("query", "") @@ -881,9 +796,7 @@ def cmd_pulse_retrieve(flags): 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") + helper = pulse_helper() conn = connect() payload = helper.retrieve( conn,