pi-sleep-agent 0.7.0 → 0.8.1

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
@@ -33,7 +33,7 @@ Sleep adds a reviewable memory cycle to Pi, OmO, and Claude Code. It records use
33
33
  - **Repeated preference detection.** `mine` finds instructions you gave in multiple sessions without a model call.
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
- - **Stale-value scan.** `doctor --stale <value>` finds which approved records still hold a value you know has changed (for example a deployment URL).
36
+ - **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).
37
37
  - **Safety gates.** Secrets are redacted, hostile text is quarantined, and machine-generated prompts cannot claim user provenance.
38
38
 
39
39
  ## Install
@@ -246,7 +246,7 @@ Run the two dream components separately when you want more control:
246
246
  | `./sleep.py replay --run --limit 3` | Compare selected tasks with memory off and on |
247
247
  | `./sleep.py mine --dry-run` | Find preferences repeated across sessions |
248
248
  | `./sleep.py nightly --dry-run` | Preview the unattended nightly workflow |
249
- | `./sleep.py doctor` | Find duplicate or overlapping memory records |
249
+ | `./sleep.py doctor` | Find duplicate or overlapping memory records, and flag provisional candidates not rediscovered for 4+ weeks (report only, never dropped) |
250
250
  | `./sleep.py doctor --stale <value>` | Show which approved records still hold a stale value (e.g. a changed URL) |
251
251
  | `./sleep.py inject --project "$PWD"` | Print provisional context for the current project |
252
252
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-sleep-agent",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
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
@@ -115,9 +115,11 @@ def cmd_status(a) -> int:
115
115
  _p("")
116
116
  _p("provisional (context only, never directives):")
117
117
  for c in prov[-12:]:
118
- _p(" %-10s %-8s %-11s %s" % (c["id"], c.get("source", "?"),
119
- c.get("trust", "?"),
120
- c.get("_body", "").replace("\n", " ")[:88]))
118
+ rd = c.get("rediscovered")
119
+ tag = (" [rediscovered x%s in %s sessions]" % (rd, c.get("rediscovered_in", "").strip("|")) if rd else "")
120
+ _p(" %-10s %-8s %-11s %s%s" % (c["id"], c.get("source", "?"),
121
+ c.get("trust", "?"),
122
+ c.get("_body", "").replace("\n", " ")[:88], tag))
121
123
  if ref:
122
124
  _p("")
123
125
  _p("refused (last 5, earlier rejections stay on record):")
package/sleepkit/store.py CHANGED
@@ -16,11 +16,30 @@ import os
16
16
  import re
17
17
  import shutil
18
18
  import time
19
+ from datetime import datetime
19
20
 
20
21
  from . import paths, safety
21
22
 
22
23
  KINDS = ("fact", "preference", "procedure", "warning")
23
24
 
25
+ # Doctor flags a provisional candidate as stale when its last activity (creation
26
+ # or the most recent rediscovery) is older than this.
27
+ STALE_CANDIDATE_WEEKS = 4.0
28
+
29
+
30
+ def _hours_since(ts: str) -> float | None:
31
+ """Hours since an ISO timestamp written by paths.now(). Unparseable input
32
+ returns None, meaning 'no constraint' rather than 'flag everything'."""
33
+ if not ts:
34
+ return None
35
+ try:
36
+ dt = datetime.fromisoformat(ts)
37
+ except (ValueError, TypeError):
38
+ return None
39
+ if dt.tzinfo is None:
40
+ dt = dt.astimezone()
41
+ return (datetime.now(dt.tzinfo) - dt).total_seconds() / 3600.0
42
+
24
43
  IDX_BEGIN = "<!-- sleep:begin (managed by sleepctl; lines here are appended, never rewritten) -->"
25
44
  IDX_END = "<!-- sleep:end -->"
26
45
 
@@ -213,6 +232,45 @@ def refused_collision(text: str, threshold: float = REFUSED_DUP_THRESHOLD) -> tu
213
232
 
214
233
 
215
234
  # ------------------------------------------------------------- candidates ---
235
+ def _record_rediscovery(cid: str, session: str) -> str | None:
236
+ """Record that an agent re-learned an existing candidate in another session.
237
+
238
+ Returns a human message when the session differs from the ones already recorded
239
+ (a genuine cross-session rediscovery), or None when it is the same session again
240
+ (that is a repeat, not a pattern, and the plain duplicate message applies).
241
+ """
242
+ got = get_candidate(cid)
243
+ if not got:
244
+ return None
245
+ meta, body = got
246
+ # The record's own session is the baseline: a repeat from the same session the
247
+ # fact was first filed in is a repeat, not a rediscovery. Only a *different*
248
+ # session counts.
249
+ sessions = [s for s in meta.get("rediscovered_in", "").split("|") if s]
250
+ own = (meta.get("session", "") or "").strip()
251
+ if own and own not in sessions:
252
+ sessions.append(own)
253
+ this = (session or "").strip()
254
+ if not this:
255
+ return None
256
+ if this in sessions:
257
+ return None
258
+ sessions.append(this)
259
+ n = int(meta.get("rediscovered", 0) or 0) + 1
260
+ meta["rediscovered"] = str(n)
261
+ meta["rediscovered_in"] = "|".join(sessions)
262
+ meta["rediscovered_at"] = paths.now()
263
+ loc = paths.candidates_dir()
264
+ if not os.path.isfile(os.path.join(loc, cid + ".md")):
265
+ p = os.path.join(paths.archive_dir("candidates"), cid + ".md")
266
+ if os.path.isfile(p):
267
+ loc = paths.archive_dir("candidates")
268
+ with open(os.path.join(loc, cid + ".md"), "w", encoding="utf-8") as fh:
269
+ fh.write(emit(meta, body))
270
+ return "duplicate of %s (rediscovered in a later session: %d distinct sessions now; use `sleepctl show %s` to review)" % (
271
+ cid, n, cid)
272
+
273
+
216
274
  def add_candidate(text: str, kind: str = "fact", source: str = "agent",
217
275
  trust: str = "observed", session: str = "", cwd: str = "",
218
276
  evidence: list[str] | None = None, supersedes: list[str] | None = None,
@@ -237,6 +295,14 @@ def add_candidate(text: str, kind: str = "fact", source: str = "agent",
237
295
  pool = [(m["id"], m.get("_body", "")) for m in list_candidates(with_body=True)]
238
296
  dup, score = nearest(red, pool)
239
297
  if dup:
298
+ if source == "agent":
299
+ note = _record_rediscovery(dup, session)
300
+ if note:
301
+ # The agent independently re-learned a fact it already holds as a
302
+ # provisional candidate. It stays provisional (not a directive) and
303
+ # is not auto-kept; this just marks the cross-session rediscovery so
304
+ # the reviewer can weigh it. trust stays cap_trust(source) unchanged.
305
+ return False, note
240
306
  return False, "duplicate of %s (%.2f); use `sleepctl supersede %s %s`" % (
241
307
  dup, score, dup, "new-text")
242
308
  ref_id, ref_score = refused_collision(red)
@@ -560,6 +626,19 @@ def doctor(memory_dir: str | None = None, targets: list[str] | None = None,
560
626
  if sim >= 0.75:
561
627
  out.append({"issue": "near-duplicate-candidates",
562
628
  "pair": [pool[i][0], pool[j][0]], "similarity": round(sim, 2)})
629
+ cutoff_hours = STALE_CANDIDATE_WEEKS * 7 * 24
630
+ for c in list_candidates():
631
+ if c.get("status") != "provisional":
632
+ continue
633
+ # Last activity = the most recent rediscovery if there was one, else the
634
+ # record's own creation ts. A provisional that is neither being promoted
635
+ # nor re-learned for weeks is noise the queue keeps injecting into every
636
+ # session's context, so the doctor surfaces it (report only, nothing drops).
637
+ last = c.get("rediscovered_at") or c.get("ts")
638
+ age_h = _hours_since(str(last)) if last else None
639
+ if age_h is not None and age_h >= cutoff_hours:
640
+ out.append({"issue": "stale-candidate-unrediscovered", "id": c["id"],
641
+ "last_seen": str(last)[:10], "rediscovered": int(c.get("rediscovered", 0) or 0)})
563
642
  for cid, body in pool:
564
643
  for path, text in bodies.items():
565
644
  # MEMORY.md is the index: it restates every entry by design, so scoring