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
7 changes: 5 additions & 2 deletions pulse-memory/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,15 @@ ln -sfn "$(pwd)/pulse-memory/skills/pulse-memory" ~/.grok/skills/pulse-memory
```text
plugin.json
commands/pulse-memory.md
commands/pulse-rank.md
cursor/commands/pulse-memory.md
cursor/commands/pulse-rank.md
agents/pulse-memory.md
skills/pulse-memory/ # filter SoT
SKILL.md
references/admissions.md
references/store.md # SQLite archive vs memory
scripts/ # init, admit, retrieve, backfill
scripts/ # init, admit, retrieve, backfill, rank
.grok/workflows/pulse-memory.rhai
test/
```
Expand All @@ -66,9 +68,10 @@ 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
PULSE_MEMORY_DB=./pulse.sqlite scripts/pulse_rank.py --weekly
```

Retrieve returns JSON: one pulse (or a few, max 8), or `{ "ok": false, "status": "unknown" }`. It never prints the whole store.
Retrieve returns JSON: one pulse (or a few, max 8), or `{ "ok": false, "status": "unknown" }`. It never prints the whole store. Each hit is logged as keys only; `pulse_rank.py` ranks traces by those hits and proposes prunes, deleting nothing.

## Tests

Expand Down
15 changes: 15 additions & 0 deletions pulse-memory/commands/pulse-rank.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
description: Rank lived traces by whether they earned their keep; propose a prune list. Dry run. Deletes nothing.
argument-hint: optional --weekly, --as-of ISO, --days N
---

# /pulse-rank

Run `scripts/pulse_rank.py $ARGUMENTS`. Default JSON; `--weekly` prints the markdown report.

1. Observe: retrieve logs each hit as keys only.
2. Rank: score = 3·hits + restated + 4·locked + 2·supersedes + verified.
3. Tighten: propose `stale` then `idle` rows, at most `--max` (8).
4. Improve sparsely: a person prunes. The script never deletes.

`--record` appends the proposal to `archive_events`. Nothing else is written.
12 changes: 12 additions & 0 deletions pulse-memory/cursor/commands/pulse-rank.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
description: Rank lived traces by whether they earned their keep; propose a prune list. Dry run. Deletes nothing.
---

# /pulse-rank

Run `scripts/pulse_rank.py`, or `--weekly` for the markdown report. Same contract as the Grok command.

1. Observe: retrieve logs each hit as keys only.
2. Rank: score = 3·hits + restated + 4·locked + 2·supersedes + verified.
3. Tighten: propose `stale` then `idle` rows, at most 8.
4. Improve sparsely: a person prunes. The script never deletes.
22 changes: 21 additions & 1 deletion pulse-memory/scripts/pulse_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,24 @@ def lookup_rows(conn, wanted: str, key=None, prefetch_key=None):
return fts_or_like(conn, wanted), False


def retrieve(conn, query="", limit=DEFAULT_RETRIEVE, key=None, prefetch_key=None):
HIT_SOURCE = "pulse/retrieve"


def log_hits(conn, keys, mode):
"""Best effort: one archive row per retrieve that returned pulses. Keys only."""
if not keys or os.environ.get("PULSE_RETRIEVE_LOG", "1") == "0":
return
own = not conn.in_transaction
try:
archive_event(conn, HIT_SOURCE, {"keys": keys, "mode": mode}, keys[0])
if own:
conn.commit()
except sqlite3.Error:
if own:
conn.rollback()


def retrieve(conn, query="", limit=DEFAULT_RETRIEVE, key=None, prefetch_key=None, log=True):
try:
limit = int(limit)
except (TypeError, ValueError):
Expand Down Expand Up @@ -486,6 +503,9 @@ def retrieve(conn, query="", limit=DEFAULT_RETRIEVE, key=None, prefetch_key=None
candidates = narrowed
chosen = candidates[:limit]
pulses = [pulse_packet(row) for row in chosen]
if log:
mode = "key" if key else "prefetch" if prefetch_key else "query"
log_hits(conn, [pulse["key"] for pulse in pulses], mode)
returned_chars = sum(len(pulse["snippet"]) for pulse in pulses)
return {
"ok": True,
Expand Down
164 changes: 164 additions & 0 deletions pulse-memory/scripts/pulse_rank.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
#!/usr/bin/env python3
"""Rank lived traces by whether they earned their keep. Proposes a prune list. Deletes nothing.

pulse_rank.py [--as-of ISO] [--days N] [--min-age N] [--max N] [--weekly] [--record]
"""

import argparse
import json
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from pulse_common import HIT_SOURCE, archive_event, connect, hash_matches

RANK_SOURCE = "pulse/rank"
WEIGHTS = {"hit": 3, "restated": 1, "locked": 4, "supersedes": 2, "verified": 1}


def parse_time(raw):
if not raw or raw == "unknown":
return None
try:
t = datetime.fromisoformat(str(raw).replace("Z", "+00:00"))
except ValueError:
return None
return t if t.tzinfo else t.replace(tzinfo=timezone.utc)


def hits_by_key(conn, start, end):
hits, first = {}, None
rows = conn.execute(
"SELECT ts, payload FROM archive_events WHERE source=? ORDER BY ts", (HIT_SOURCE,)
)
for row in rows:
t = parse_time(row["ts"])
if t is None:
continue
first = first or t
if not (start <= t <= end):
continue
try:
keys = json.loads(row["payload"]).get("keys", [])
except (ValueError, AttributeError):
continue
for key in keys:
hits[key] = hits.get(key, 0) + 1
return hits, first


def rank(conn, as_of, days=7, min_age=14, cap=8):
start = as_of - timedelta(days=days)
hits, first_hit = hits_by_key(conn, start, as_of)
covered = first_hit is not None and first_hit <= start
winners = {}
for row in conn.execute("SELECT superseded_by FROM memory_traces WHERE superseded_by IS NOT NULL AND superseded_by != ''"):
winners[row[0]] = winners.get(row[0], 0) + 1
conflicted = set()
for row in conn.execute("SELECT left_id, right_id FROM conflicts"):
conflicted.update(row)
traces = []
for row in conn.execute("SELECT * FROM memory_traces ORDER BY nat_key"):
key = row["nat_key"]
signals = {
"hits": hits.get(key, 0),
"restated": max(row["seen_count"] - 1, 0),
"locked": row["lock"] == "locked",
"supersedes": winners.get(key, 0),
"verified": row["status"] == "tool-verified",
"conflict": row["id"] in conflicted,
}
score = (
WEIGHTS["hit"] * signals["hits"]
+ WEIGHTS["restated"] * signals["restated"]
+ WEIGHTS["locked"] * signals["locked"]
+ WEIGHTS["supersedes"] * signals["supersedes"]
+ WEIGHTS["verified"] * signals["verified"]
)
last = parse_time(row["last_seen"]) or parse_time(row["time"])
age = (as_of - last).days if last else None
if row["superseded_by"]:
tier, why = "stale", f"superseded by {row['superseded_by']}"
elif not hash_matches(row["snippet"], row["verify_hash"]):
tier, why = "repair", "hash mismatch"
elif signals["locked"] or signals["hits"] or signals["restated"] or signals["supersedes"]:
tier, why = "earned", "used or locked"
elif age is None or age < min_age:
tier, why = "young", f"younger than {min_age}d"
elif not covered:
tier, why = "unproven", "hit log does not cover the window"
else:
tier, why = "idle", f"no hit in {days}d, said once, open"
traces.append({"key": key, "kind": row["kind"], "score": score, "tier": tier, "why": why, "age_days": age, **signals})
traces.sort(key=lambda t: (-t["score"], t["key"]))
order = {"stale": 0, "idle": 1}
pool = sorted((t for t in traces if t["tier"] in order), key=lambda t: (order[t["tier"]], t["score"], t["key"]))
tiers = {}
for t in traces:
tiers[t["tier"]] = tiers.get(t["tier"], 0) + 1
return {
"ok": True,
"dry_run": True,
"as_of": as_of.isoformat(),
"window_days": days,
"hit_log": {"first": first_hit.isoformat() if first_hit else None, "covers_window": covered},
"kdi": {"traces": len(traces), "tiers": tiers, "hits": sum(hits.values())},
"prune": [{"key": t["key"], "tier": t["tier"], "why": t["why"]} for t in pool[:cap]],
"prune_more": max(len(pool) - cap, 0),
"repair": [t["key"] for t in traces if t["tier"] == "repair"],
"top": [{"key": t["key"], "score": t["score"]} for t in traces if t["tier"] == "earned"][:cap],
"traces": traces,
}


def weekly(report):
k = report["kdi"]
lines = [
f"# Pulse KDI week to {report['as_of'][:10]}",
"",
f"Traces {k['traces']} · retrieve hits {k['hits']} · window {report['window_days']}d · dry run",
"",
"| tier | n |",
"|------|---|",
]
lines += [f"| {tier} | {n} |" for tier, n in sorted(k["tiers"].items())]
if not report["hit_log"]["covers_window"]:
lines += ["", "Hit log is younger than the window. Idle is held as unproven."]
lines += ["", "## Earned", ""]
lines += [f"- `{t['key']}` {t['score']}" for t in report["top"]] or ["- none"]
lines += ["", "## Prune proposals (nothing deleted)", ""]
lines += [f"- `{p['key']}` {p['tier']}: {p['why']}" for p in report["prune"]] or ["- none"]
if report["prune_more"]:
lines.append(f"- and {report['prune_more']} more next week")
if report["repair"]:
lines += ["", "## Repair", ""] + [f"- `{key}` hash mismatch" for key in report["repair"]]
return "\n".join(lines) + "\n"


def main():
a = argparse.ArgumentParser(description="rank lived traces; propose a prune list; delete nothing")
a.add_argument("--as-of")
a.add_argument("--days", type=int, default=7)
a.add_argument("--min-age", type=int, default=14)
a.add_argument("--max", type=int, default=8)
a.add_argument("--weekly", action="store_true", help="markdown report")
a.add_argument("--record", action="store_true", help="append the proposal to archive_events")
o = a.parse_args()
as_of = parse_time(o.as_of) if o.as_of else datetime.now(timezone.utc)
if as_of is None or o.days < 1 or o.min_age < 0 or o.max < 0:
a.error("bad --as-of, --days, --min-age or --max")
conn = connect()
try:
report = rank(conn, as_of, o.days, o.min_age, o.max)
if o.record:
archive_event(conn, RANK_SOURCE, {k: report[k] for k in ("as_of", "kdi", "prune", "repair")})
conn.commit()
report["dry_run"] = False
print(weekly(report) if o.weekly else json.dumps(report, ensure_ascii=False))
finally:
conn.close()


if __name__ == "__main__":
main()
30 changes: 30 additions & 0 deletions pulse-memory/skills/pulse-memory/references/store.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Default file: $XDG_DATA_HOME/tstack/state.sqlite, or ~/.local/share/tstack/state
| `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 |
| `scripts/pulse_rank.py` | rank traces by earned keep; propose prunes; dry run; 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) |
Expand Down Expand Up @@ -100,6 +101,35 @@ tstack-state also refuses `@` in any field.
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`, `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.

## Rank: Key Decision Indicators

```mermaid
%%{init: {"theme":"base","themeVariables":{"primaryColor":"#e0f2fe","primaryBorderColor":"#0284c7","lineColor":"#7c3aed"}}}%%
flowchart LR
O[observe: retrieve hit log]:::o --> R[rank: KDI score]:::r --> T[tighten: prune proposals]:::t --> I[improve sparsely: a person prunes]:::i
I -.-> O
classDef o fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
classDef r fill:#ede9fe,stroke:#7c3aed,color:#4c1d95
classDef t fill:#fef3c7,stroke:#d97706,color:#78350f
classDef i fill:#dcfce7,stroke:#16a34a,color:#14532d
```

```text
hit(k) = archive_events where source = pulse/retrieve and k ∈ keys, inside the window
KDI(k) = 3·hit + (seen_count − 1) + 4·locked + 2·supersedes + 1·tool-verified
stale ⇐ superseded_by ≠ ∅
repair ⇐ verify_hash ≠ sha256(snippet)
earned ⇐ locked ∨ hit > 0 ∨ seen_count > 1 ∨ supersedes > 0
young ⇐ age < min_age (14d)
unproven ⇐ hit log starts after the window start
idle ⇐ otherwise
prune = (stale ++ idle)[:8]; nothing is deleted
```

Retrieve logs keys and mode only, never the query or snippet. `PULSE_RETRIEVE_LOG=0` turns it off. Gate outcomes are not stored per trace yet, so they do not score.

`pulse_rank.py --weekly` prints the week report. `--record` appends it to `archive_events`.

## What not to add (YAGNI)

- Always-on hooks that pulse every tool call (Winds).
Expand Down
9 changes: 9 additions & 0 deletions pulse-memory/test/test-thin.sh
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ need scripts/pulse_init_db.py
need scripts/pulse_admit.py
need scripts/pulse_retrieve.py
need scripts/pulse_backfill.py
need scripts/pulse_rank.py
need commands/pulse-rank.md
need cursor/commands/pulse-rank.md

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
Expand Down Expand Up @@ -101,6 +104,12 @@ else
bad "retrieve tests"
fi

if python3 "$ROOT/test/test_rank.py"; then
ok "rank tests"
else
bad "rank tests"
fi

echo "---"
if [[ "$fail" -ne 0 ]]; then
echo "$fail failure(s)"
Expand Down
Loading
Loading