pi-sleep-agent 0.8.13 → 0.8.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -34,6 +34,9 @@ Sleep adds a reviewable memory cycle to nine selectable coding-agent targets. It
34
34
  - **Project isolation.** A project's provisional memory is injected only into that project.
35
35
  - **Reviewable permanence.** Each approved memory in your index carries its review date and source, so you can tell when a saved instruction was pinned.
36
36
  - **Relevance-ranked injection.** With a query, provisional memory is ordered by overlap with the live request and each line carries its age, so the most relevant record survives the `--max` cut and stale facts read as stale.
37
+ - **Tagged records.** Consolidation writes 1-4 lowercase topic tags per record (`deploy|aws`),
38
+ normalized and capped in `store`, and `inject --topic` selects on them. A tag is a
39
+ hint a model proposed, so a wrong tag costs a missing filter hit, never a wrong fact.
37
40
  - **Served-record accounting.** Every injection stamps the records it actually printed (`injected`, `injected_at` on the record itself), so `doctor` can name a provisional that **no session has ever asked for** in 8+ weeks (`unused-candidate-never-served`). That is a different fact from "nobody re-learned it", and only the record can tell the two apart; report only, nothing is dropped.
38
41
  - **Indexed by default.** A long observation is injected as its opening claim plus a pointer (`[+714 chars: sleep.py show <id>]`) instead of its whole narrative; `inject --full` prints the complete bodies. Measured on a live pool of 11 records: 5581 -> 3377 characters per injection.
39
42
  - **Stale-value scan.** `doctor --stale <value>` finds which approved records still hold a value you know has changed (for example a deployment URL). Unreviewed provisional candidates are also flagged: a fact the agent proposed once and never rediscovered for 4+ weeks keeps getting injected into every session's context, so `doctor` surfaces it as `stale-candidate-unrediscovered` (a report line it never acts on, nothing is dropped).
@@ -338,6 +341,7 @@ name: it routes through its own config, so only `SLEEP_MODEL` reaches it.
338
341
  | `./sleep.py inject --project "$PWD"` | Print provisional context for the current project, newest first, each line dated |
339
342
  | `./sleep.py inject --project "$PWD" --query "..."` | Same, but rank records by overlap with the live request so the most relevant survive `--max` |
340
343
  | `./sleep.py inject --project "$PWD" --full` | Print each record's whole body instead of the index line |
344
+ | `./sleep.py inject --project "$PWD" --topic deploy` | Only records whose `tags` carry that topic (an index lookup, not a keyword search) |
341
345
 
342
346
  Run `./sleep.py <command> --help` for command-specific options.
343
347
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-sleep-agent",
3
- "version": "0.8.13",
3
+ "version": "0.8.14",
4
4
  "description": "A reviewable sleep and dream cycle for Pi agent memory.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -18,6 +18,7 @@ Each proposal is header fields, a blank line, then the observation:
18
18
  source: user | agent | inferred
19
19
  kind: fact | preference | procedure | warning
20
20
  trust: verified | observed | speculative
21
+ tags: <1-4 pipe-separated lowercase topics, e.g. deploy|aws or gitlab|auth>
21
22
  evidence: <optional, comma separated file paths or session refs>
22
23
 
23
24
  <one observation, 1-3 sentences, written so a reader in a future session can
@@ -52,5 +53,8 @@ here.
52
53
 
53
54
  - You have read access only, and you do not need it: the buffer and the existing
54
55
  pool are already in your prompt. Do not run commands.
56
+ - The `tags` line is the only index a future session can filter on: use the
57
+ topic words a person would search for (deploy, gitlab, auth), not the
58
+ sentence's verbs. Never repeat the kind as a tag.
55
59
  - Proposals are cheap and refusals are cheap; a poisoned memory store is not. When
56
60
  in doubt, emit fewer and mark the remainder `speculative`.
package/sleepkit/cli.py CHANGED
@@ -535,8 +535,10 @@ def _index_line(body: str, cid: str) -> str:
535
535
 
536
536
  def cmd_inject(a) -> int:
537
537
  """Print the provisional-memory block for a session's context. Framed as context."""
538
+ topic = getattr(a, "topic", "") or ""
538
539
  pool = [c for c in store.list_candidates(status="provisional", with_body=True)
539
- if _within_project(c.get("cwd", ""), a.project)]
540
+ if _within_project(c.get("cwd", ""), a.project)
541
+ and store.matches_topic(c, topic)]
540
542
  full = bool(getattr(a, "full", False))
541
543
  recs = []
542
544
  served = []
@@ -721,6 +723,9 @@ def main(argv=None) -> int:
721
723
  ij.add_argument("--query", default="",
722
724
  help="rank provisional records by overlap with this text "
723
725
  "(the live request); newest first when omitted")
726
+ ij.add_argument("--topic", default="",
727
+ help="only records tagged with this topic (matches the record's "
728
+ "tags field; records with no tags never match)")
724
729
  ij.add_argument("--full", action="store_true",
725
730
  help="print each record's whole body instead of the index line")
726
731
  ij.set_defaults(fn=cmd_inject)
@@ -15,7 +15,7 @@ from datetime import datetime
15
15
 
16
16
  from . import llm, paths, safety, store
17
17
 
18
- _HDR = re.compile(r"^(source|kind|trust|evidence)\s*:\s*(.+)$", re.M)
18
+ _HDR = re.compile(r"^(source|kind|trust|tags|evidence)\s*:\s*(.+)$", re.M)
19
19
 
20
20
 
21
21
  def pending_dir() -> str:
@@ -190,7 +190,8 @@ def distill(session: str | None = None, model: str | None = None,
190
190
 
191
191
  def parse_proposal(text: str) -> dict:
192
192
  """Split one proposal into header fields + body. Headers are optional."""
193
- fields = {"source": "agent", "kind": "fact", "trust": "observed", "evidence": ""}
193
+ fields = {"source": "agent", "kind": "fact", "trust": "observed",
194
+ "tags": "", "evidence": ""}
194
195
  for m in _HDR.finditer(text):
195
196
  fields[m.group(1)] = m.group(2).strip()
196
197
  body = _HDR.sub("", text).strip()
@@ -204,7 +205,7 @@ def parse_proposal(text: str) -> dict:
204
205
  # fallback. Neither decides what becomes memory: every block still goes through
205
206
  # ingest_records(), which is where the gates live.
206
207
  _SEP_LINE = re.compile(r"^[^A-Za-z0-9\n]*PROPOSAL[^A-Za-z0-9\n]*$", re.I | re.M)
207
- _HDR_LINE = re.compile(r"^(source|kind|trust|evidence)\s*:.*$", re.M)
208
+ _HDR_LINE = re.compile(r"^(source|kind|trust|tags|evidence)\s*:.*$", re.M)
208
209
 
209
210
 
210
211
  def split_blocks(text: str) -> tuple:
@@ -306,7 +307,10 @@ def ingest_records(parsed: list, session: str = "", cwd: str = "",
306
307
  item["body"], kind=f.get("kind", "fact"), source=source, trust=trust,
307
308
  session=session or os.environ.get("SLEEP_SESSION", ""),
308
309
  cwd=cwd or os.getcwd(),
309
- evidence=[x for x in f.get("evidence", "").split(",") if x])
310
+ evidence=[x for x in f.get("evidence", "").split(",") if x],
311
+ # The proposal's own tag line is a hint, never authority: store.add_candidate
312
+ # normalizes and caps it, and a wrong tag only costs a bad topic filter.
313
+ tags=[x for x in str(f.get("tags", "")).split("|") if x.strip()])
310
314
  (accepted if ok else refused).append({"body": item["body"][:60], "result": out})
311
315
  return {"proposals": len(parsed), "accepted": len(accepted), "refused": refused,
312
316
  "accepted_ids": [a["result"] for a in accepted]}
package/sleepkit/store.py CHANGED
@@ -324,7 +324,7 @@ def record_injection(ids: list[str]) -> int:
324
324
  def add_candidate(text: str, kind: str = "fact", source: str = "agent",
325
325
  trust: str = "observed", session: str = "", cwd: str = "",
326
326
  evidence: list[str] | None = None, supersedes: list[str] | None = None,
327
- notes: str = "") -> tuple[bool, str]:
327
+ notes: str = "", tags: list[str] | None = None) -> tuple[bool, str]:
328
328
  """T1: distilled, provisional. Never injected as a directive."""
329
329
  text = (text or "").strip()
330
330
  if not text:
@@ -369,7 +369,7 @@ def add_candidate(text: str, kind: str = "fact", source: str = "agent",
369
369
  "status": "provisional",
370
370
  "session": session or os.environ.get("SLEEP_SESSION", ""),
371
371
  "cwd": cwd or os.getcwd(),
372
- "tags": "|".join([]),
372
+ "tags": "|".join(_clean_tags(tags)),
373
373
  "evidence": "|".join(evidence or []),
374
374
  "supersedes": "|".join(supersedes or []),
375
375
  "superseded_by": "",
@@ -817,6 +817,42 @@ def prune_buffer(older_than_hours: float = 0.0, session: str | None = None) -> d
817
817
  return {"moved": moved, "remaining": buffer_counts()}
818
818
 
819
819
 
820
+ # Tags are the only index a record carries besides its project, so they are kept
821
+ # machine-shaped: lowercase, no spaces, bounded in number and length. A model may
822
+ # propose them, which is exactly why they are normalized here rather than trusted.
823
+ MAX_TAGS = 6
824
+ MAX_TAG_CHARS = 32
825
+
826
+
827
+ def _clean_tags(tags) -> list:
828
+ out, seen = [], set()
829
+ for raw in tags or []:
830
+ tag = re.sub(r"[^a-z0-9._:+-]+", "-", str(raw).strip().lower()).strip("-")
831
+ if not tag or tag in seen:
832
+ continue
833
+ seen.add(tag)
834
+ out.append(tag[:MAX_TAG_CHARS])
835
+ if len(out) >= MAX_TAGS:
836
+ break
837
+ return out
838
+
839
+
840
+ def matches_topic(meta: dict, topic: str) -> bool:
841
+ """True when a record carries the topic as one of its tags (substring, either way).
842
+
843
+ Deliberately tag-only: matching the body would turn a topic filter into a keyword
844
+ search, which is what --query already does. Substring in both directions so
845
+ `deploy` selects `deploy` and `deployment`, not `predeployed`."""
846
+ want = str(topic or "").strip().lower()
847
+ if not want:
848
+ return True
849
+ for tag in meta.get("tags") or []:
850
+ tag = str(tag).strip().lower()
851
+ if want == tag or want in tag or tag in want:
852
+ return True
853
+ return False
854
+
855
+
820
856
  # A cheap pre-filter for the LLM adjudicator. Token Jaccard is a poor *decider* on
821
857
  # short observations (measured: no real pair in a live 11-record pool cleared 0.5),
822
858
  # but it is a fine *shortlist*: pairs that share at least a handful of content words