pi-sleep-agent 0.8.7 → 0.8.8

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
@@ -275,7 +275,7 @@ A dream pass performs four steps:
275
275
 
276
276
  1. **Mine.** Find instructions you repeated across separate sessions in the same project. This step is deterministic and makes no model call.
277
277
  2. **Consolidate.** When the sleep gate passes, ask the configured model to turn recent T0 observations into provisional T1 candidates.
278
- 3. **Hygiene.** Run the read-only `doctor` scan and fold any findings (duplicate headings, near-duplicate or contradicting candidates, records parked in quarantine awaiting review, or stale values when you pass `--stale <value>`) into the night's report.
278
+ 3. **Hygiene.** Run the read-only `doctor` scan and fold any findings (duplicate headings, near-duplicate or contradicting candidates, broken supersede links, records parked in quarantine awaiting review, or stale values when you pass `--stale <value>`) into the night's report.
279
279
  4. **Replay.** When replay is due, run selected tasks with provisional memory off and on, then write a comparison report.
280
280
 
281
281
  Every result stays reviewable. Candidates remain in T1 until you explicitly run `promote`.
@@ -319,7 +319,7 @@ Run the two dream components separately when you want more control:
319
319
  | `./sleep.py replay --run --limit 3` | Compare selected tasks with memory off and on |
320
320
  | `./sleep.py mine --dry-run` | Find preferences repeated across sessions |
321
321
  | `./sleep.py nightly --dry-run` | Preview the unattended nightly workflow |
322
- | `./sleep.py doctor` | Find duplicate or overlapping memory records, flag contradicting candidates (same subject, one side carries a correction marker) and print the `supersede <older> <newer>` command to run, flag provisional candidates not rediscovered for 4+ weeks, and report records parked in quarantine awaiting a human (report only: it never supersedes, drops, merges or un-parks anything itself) |
322
+ | `./sleep.py doctor` | Find duplicate or overlapping memory records, flag contradicting candidates (same subject, one side carries a correction marker) and print the `supersede <older> <newer>` command to run, flag provisional candidates not rediscovered for 4+ weeks, flag supersede pointers that name a record no longer in the store, and report records parked in quarantine awaiting a human (report only: it never supersedes, drops, merges or un-parks anything itself) |
323
323
  | `./sleep.py doctor --stale <value>` | Show which approved records still hold a stale value (e.g. a changed URL) |
324
324
  | `./sleep.py doctor --contradictions` | Ask a model to adjudicate shortlisted pairs of provisional records for conflicts (`--budget`, default $0.25); report-only, and each finding carries the `supersede <older> <newer>` command to run |
325
325
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-sleep-agent",
3
- "version": "0.8.7",
3
+ "version": "0.8.8",
4
4
  "description": "A reviewable sleep and dream cycle for Pi agent memory.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/sleepkit/cli.py CHANGED
@@ -151,6 +151,15 @@ def cmd_show(a) -> int:
151
151
  return 2
152
152
  meta, body = got
153
153
  _p(store.emit(meta, body))
154
+ # Show the supersede chain: with only the two pointer fields visible, answering
155
+ # "which record is current, and what did it replace?" means reading other files.
156
+ chain = store.supersession_chain(a.id)
157
+ if len(chain["order"]) > 1 or chain["broken"]:
158
+ _p("# supersede chain (oldest -> newest):")
159
+ _p(" " + " -> ".join(chain["order"]))
160
+ _p(" current: %s" % chain["current"])
161
+ for gone in chain["broken"]:
162
+ _p(" BROKEN: %s is referenced but not in the store" % gone)
154
163
  _p("# rendered for context:\n" + safety.render_for_context(
155
164
  {"text": body, "source": meta.get("source"), "trust": meta.get("trust")}))
156
165
  return 0
package/sleepkit/store.py CHANGED
@@ -638,6 +638,83 @@ def demote(cid: str, memory_dir: str | None = None, dry_run: bool = False,
638
638
  return True, ("retracted %s" % (slug or cid)
639
639
  + (" (T2 default not found)" if not t2_ok else ""))
640
640
 
641
+ def _first_ref(value) -> str:
642
+ """One id out of a supersede field, which parse() returns as a LIST.
643
+
644
+ store.parse() turns tags/evidence/supersedes/superseded_by into lists, so treating
645
+ the value as a string produced repr text like "['c1']" and every chain walk missed.
646
+ Accepts either shape and takes the first entry.
647
+ """
648
+ if isinstance(value, (list, tuple)):
649
+ return str(value[0]).strip() if value else ""
650
+ return str(value or "").split("|")[0].strip()
651
+
652
+
653
+ def _archived_candidates() -> list:
654
+ """Parsed frontmatter of archived candidates (promoted/superseded records live there)."""
655
+ out = []
656
+ d = paths.archive_dir("candidates")
657
+ if not os.path.isdir(d):
658
+ return out
659
+ for name in sorted(os.listdir(d)):
660
+ if not name.endswith(".md"):
661
+ continue
662
+ try:
663
+ with open(os.path.join(d, name), encoding="utf-8") as fh:
664
+ meta, _body = parse(fh.read())
665
+ except (OSError, ValueError):
666
+ continue
667
+ out.append(meta)
668
+ return out
669
+
670
+
671
+ def supersession_chain(cid: str, max_hops: int = 20) -> dict:
672
+ """Walk a record's supersede links in both directions.
673
+
674
+ A supersede writes one pointer on each side, so the *chain* is only visible by
675
+ following them: after three changes, "which record is current?" costs reading files.
676
+ Returns {"order": [oldest..newest], "current": id, "broken": [ids]} - `broken` names
677
+ ids that are referenced but missing from the store, which is how a hand-edited or
678
+ partially archived chain shows up instead of silently reading as a two-record story.
679
+ """
680
+ seen_up, chain = set(), []
681
+ node = cid
682
+ while node and node not in seen_up and len(chain) < max_hops:
683
+ seen_up.add(node)
684
+ chain.append(node)
685
+ got = get_candidate(node)
686
+ if not got:
687
+ break
688
+ node = _first_ref(got[0].get("supersedes"))
689
+ order = list(reversed(chain)) # oldest -> newest
690
+ missing = []
691
+ if order and not get_candidate(order[0]):
692
+ missing.append(order[0])
693
+ # Walk forward from the OLDEST end, not from the requested id: asking about the
694
+ # replaced record must still report what replaced it.
695
+ # Forward walk: follow superseded_by from whatever end we know, always extending the
696
+ # NEWEST side. It is not gated on the seed id (the oldest member has no supersedes and
697
+ # would otherwise stop the walk before it ever looked forward).
698
+ node = order[-1] if order else cid
699
+ seen_down = set(order)
700
+ while node and len(order) < max_hops:
701
+ got = get_candidate(node)
702
+ if not got:
703
+ break
704
+ nxt = _first_ref(got[0].get("superseded_by"))
705
+ if not nxt or nxt in seen_down:
706
+ break
707
+ seen_down.add(nxt)
708
+ if get_candidate(nxt):
709
+ order.append(nxt)
710
+ node = nxt
711
+ else:
712
+ missing.append(nxt)
713
+ break
714
+ current = order[-1] if order else cid
715
+ return {"order": order, "current": current, "broken": missing}
716
+
717
+
641
718
  def supersede(old_id: str, new_id: str) -> bool:
642
719
  """Mark old_id invalid as of now and new_id valid as of now.
643
720
 
@@ -808,6 +885,19 @@ def doctor(memory_dir: str | None = None, targets: list[str] | None = None,
808
885
  # Report the count and the newest ids; nothing is dropped or changed here.
809
886
  # Path assembled without paths.home(): home() creates the whole tier skeleton as a
810
887
  # side effect, and a read-only report that lays down directories is not read-only.
888
+ # A supersede writes a pointer on each side, so a link can dangle: the file was
889
+ # pruned, the archive lost it, or a hand edit dropped it. A dangling link reads as
890
+ # "this record replaced something" while the something is unrecoverable - worth one
891
+ # line, since it is invisible in every other view.
892
+ for c in list_candidates(with_body=False) + _archived_candidates():
893
+ cid = c.get("id")
894
+ if not cid:
895
+ continue
896
+ for field in ("supersedes", "superseded_by"):
897
+ target = _first_ref(c.get(field))
898
+ if target and not get_candidate(target):
899
+ out.append({"issue": "broken-supersede-link", "id": cid,
900
+ "field": field, "missing": target})
811
901
  qdir = os.path.join(paths.SLEEP_HOME, ".quarantine")
812
902
  if os.path.isdir(qdir):
813
903
  parked = sorted(f for f in os.listdir(qdir) if f.endswith(".json"))