pi-sleep-agent 0.6.0 → 0.7.0

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
@@ -241,6 +241,7 @@ Run the two dream components separately when you want more control:
241
241
  | `./sleep.py sleep --force` | Run consolidation now |
242
242
  | `./sleep.py show <id>` | Inspect a candidate and its rendered context |
243
243
  | `./sleep.py promote <id>` | Move an approved candidate to permanent memory |
244
+ | `./sleep.py demote <id> --note "..."` | Un-approve a promoted memory: mark the approved record as retracted (kept on record, not deleted) and reopen the candidate as refused |
244
245
  | `./sleep.py refuse <id> --note "..."` | Record that a candidate is incorrect |
245
246
  | `./sleep.py replay --run --limit 3` | Compare selected tasks with memory off and on |
246
247
  | `./sleep.py mine --dry-run` | Find preferences repeated across sessions |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-sleep-agent",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
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
@@ -69,11 +69,24 @@ def cmd_status(a) -> int:
69
69
  _p("T0 buffer %d records / %d files / %d bytes (captured while you worked)" % (bc["records"], bc["files"], bc["bytes"]))
70
70
  _p("T1 candidates %d provisional, %d refused, %d total (distilled, shown as unverified context)" % (len(prov), len(ref), len(cands)))
71
71
  _p(" quarantine %d parked (needs human eyes) (held out until you review)" % len(q))
72
- _p("T2 canonical %s (%d permanent records; only you can promote)" % (mdir, len(permanent)))
73
- if permanent:
72
+ retracted = []
73
+ act_perm = []
74
+ for f in permanent:
75
+ st_ = "?"
76
+ try:
77
+ with open(os.path.join(mdir, f), encoding="utf-8") as fh:
78
+ st_ = store.parse(fh.read())[0].get("status", "?")
79
+ except (OSError, ValueError):
80
+ st_ = "?"
81
+ if st_ == "retracted":
82
+ retracted.append(f)
83
+ else:
84
+ act_perm.append(f)
85
+ _p("T2 canonical %s (%d permanent records; only you can promote)" % (mdir, len(act_perm)))
86
+ if act_perm:
74
87
  _p("")
75
88
  _p("permanent (last 5, promoted with review date + source):")
76
- for f in permanent[-5:]:
89
+ for f in act_perm[-5:]:
77
90
  try:
78
91
  with open(os.path.join(mdir, f), encoding="utf-8") as fh:
79
92
  m, b = store.parse(fh.read())
@@ -83,6 +96,21 @@ def cmd_status(a) -> int:
83
96
  src = m.get("source", "?")
84
97
  _p(" %-10s %-10s %-8s %s" % (f[:-3][:10], when, src,
85
98
  b.replace("\n", " ")[:88]))
99
+ if retracted:
100
+ _p("")
101
+ _p("retracted (last 5, demoted; kept on record, not active memory):")
102
+ for f in retracted[-5:]:
103
+ try:
104
+ with open(os.path.join(mdir, f), encoding="utf-8") as fh:
105
+ m, b = store.parse(fh.read())
106
+ except (OSError, ValueError):
107
+ m, b = {}, ""
108
+ when = m.get("retracted_at", "?")[:10]
109
+ line = " %-10s %-10s %s" % (f[:-3][:10], when,
110
+ b.replace("\n", " ")[:88])
111
+ if m.get("note"):
112
+ line += " [demoted: %s]" % str(m["note"]).replace("\n", " ")[:120]
113
+ _p(line)
86
114
  if prov:
87
115
  _p("")
88
116
  _p("provisional (context only, never directives):")
@@ -132,6 +160,13 @@ def cmd_promote(a) -> int:
132
160
  return 0 if ok else 3
133
161
 
134
162
 
163
+ def cmd_demote(a) -> int:
164
+ ok, out = store.demote(a.id, memory_dir=a.memory_dir, dry_run=a.dry_run,
165
+ note=a.note)
166
+ _p(("DEMOTED " if ok else "REFUSED ") + out)
167
+ return 0 if ok else 3
168
+
169
+
135
170
  def cmd_refuse(a) -> int:
136
171
  """The other half of the review loop: 'this observation is wrong', recorded
137
172
  rather than silently deleted, so the pool shows what was judged and rejected."""
@@ -340,6 +375,13 @@ def main(argv=None) -> int:
340
375
  pr.add_argument("--dry-run", action="store_true")
341
376
  pr.set_defaults(fn=cmd_promote)
342
377
 
378
+ dm = sub.add_parser("demote", help="un-approve a promoted memory (T2 -> refused, marked not deleted)")
379
+ dm.add_argument("id")
380
+ dm.add_argument("--memory-dir")
381
+ dm.add_argument("--note", default="")
382
+ dm.add_argument("--dry-run", action="store_true")
383
+ dm.set_defaults(fn=cmd_demote)
384
+
343
385
  rf = sub.add_parser("refuse", help="mark a candidate wrong, with a note")
344
386
  rf.add_argument("candidate_id")
345
387
  rf.add_argument("--note", default="")
package/sleepkit/store.py CHANGED
@@ -308,7 +308,14 @@ def set_status(cid: str, status: str, extra: dict | None = None) -> bool:
308
308
  meta["reviewed"] = paths.now()
309
309
  for k, v in (extra or {}).items():
310
310
  meta[k] = v
311
- with open(os.path.join(paths.candidates_dir(), cid + ".md"), "w", encoding="utf-8") as fh:
311
+ # Write back where the record actually lives: promoted candidates are in the
312
+ # archive, pending ones in candidates. Writing always to candidates used to
313
+ # leave a promoted record's status change stranded in a stale archive copy.
314
+ loc = paths.candidates_dir()
315
+ if meta.get("promoted_to") or not os.path.isfile(os.path.join(loc, cid + ".md")):
316
+ if os.path.isfile(os.path.join(paths.archive_dir("candidates"), cid + ".md")):
317
+ loc = paths.archive_dir("candidates")
318
+ with open(os.path.join(loc, cid + ".md"), "w", encoding="utf-8") as fh:
312
319
  fh.write(emit(meta, body))
313
320
  return True
314
321
 
@@ -401,6 +408,83 @@ def append_index_line(memory_dir: str, line: str) -> tuple[bool, str]:
401
408
  return True, "appended"
402
409
 
403
410
 
411
+ def remove_index_line(memory_dir: str, line: str, slug: str) -> bool:
412
+ """Drop one managed index line by slug. Never touches content outside the block."""
413
+ idx = os.path.join(memory_dir, "MEMORY.md")
414
+ if not os.path.isfile(idx):
415
+ return False
416
+ with open(idx, encoding="utf-8") as fh:
417
+ existing = fh.read()
418
+ block_re = re.compile(re.escape(IDX_BEGIN) + r".*?" + re.escape(IDX_END), re.S)
419
+ m = block_re.search(existing)
420
+ if not m:
421
+ return False
422
+ block = m.group(0)
423
+ # Match any line whose "**<slug>**" heading equals ours, regardless of suffix.
424
+ target = "**%s**" % slug
425
+ kept, found = [], False
426
+ for ln in block.split("\n"):
427
+ if re.match(r"\s*- \*\*[^*]+\*\*:", ln) and target in ln:
428
+ found = True
429
+ continue
430
+ kept.append(ln)
431
+ if not found:
432
+ return False
433
+ new_block = "\n".join(kept)
434
+ updated = existing[:m.start()] + new_block + existing[m.end():]
435
+ with open(idx, "w", encoding="utf-8") as fh:
436
+ fh.write(updated)
437
+ return True
438
+
439
+
440
+ def demote(cid: str, memory_dir: str | None = None, dry_run: bool = False,
441
+ note: str = "") -> tuple[bool, str]:
442
+ """T2 -> refused. Explicit human act: an approved memory turned out wrong.
443
+
444
+ Promotion was "create a new file, never edit one"; reversal keeps that spirit.
445
+ The canonical T2 copy is *marked* retracted, not deleted, so the audit trail of
446
+ what was once approved survives; the index line is dropped so the retired value
447
+ no longer reads as active memory; and the archived candidate is re-opened as a
448
+ refused record the reviewer can see in `status`. Nothing on this path edits or
449
+ deletes a past verdict.
450
+ """
451
+ got = get_candidate(cid)
452
+ if not got:
453
+ return False, "no such candidate: " + cid
454
+ meta, body = got
455
+ if meta.get("status") != "promoted":
456
+ return False, "not promoted (nothing to demote): " + cid
457
+ dest = meta.get("promoted_to") or ""
458
+ mdir = memory_dir or paths.memory_dir()
459
+ slug = os.path.basename(dest)[:-3] if dest else ""
460
+ if dry_run:
461
+ return True, "would retract %s (drop index line, mark candidate refused)" % (slug or cid)
462
+ stamp = paths.now()
463
+ # 1) mark the canonical T2 copy retracted
464
+ t2_ok = True
465
+ if dest and os.path.isfile(dest):
466
+ try:
467
+ with open(dest, encoding="utf-8") as fh:
468
+ m2, b2 = parse(fh.read())
469
+ m2["status"] = "retracted"
470
+ m2["retracted_at"] = stamp
471
+ if note:
472
+ m2["note"] = note
473
+ with open(dest, "w", encoding="utf-8") as fh:
474
+ fh.write(emit(m2, b2))
475
+ except (OSError, ValueError):
476
+ t2_ok = False
477
+ # 2) drop the index line so the retired value no longer reads as active
478
+ if slug and mdir:
479
+ remove_index_line(mdir, "", slug)
480
+ # 3) re-open the archived candidate as refused with a note the reviewer can see
481
+ if note:
482
+ set_status(cid, "refused", {"notes": note, "reviewed": stamp})
483
+ else:
484
+ set_status(cid, "refused", {"reviewed": stamp})
485
+ return True, ("retracted %s" % (slug or cid)
486
+ + (" (T2 default not found)" if not t2_ok else ""))
487
+
404
488
  def supersede(old_id: str, new_id: str) -> bool:
405
489
  return (set_status(old_id, "superseded", {"superseded_by": new_id})
406
490
  and set_status(new_id, "provisional", {"supersedes": old_id}))