pi-sleep-agent 0.6.0 → 0.8.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 +1 -0
- package/package.json +1 -1
- package/sleepkit/cli.py +50 -6
- package/sleepkit/store.py +131 -1
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
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
|
-
|
|
73
|
-
|
|
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
|
|
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,13 +96,30 @@ 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):")
|
|
89
117
|
for c in prov[-12:]:
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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))
|
|
93
123
|
if ref:
|
|
94
124
|
_p("")
|
|
95
125
|
_p("refused (last 5, earlier rejections stay on record):")
|
|
@@ -132,6 +162,13 @@ def cmd_promote(a) -> int:
|
|
|
132
162
|
return 0 if ok else 3
|
|
133
163
|
|
|
134
164
|
|
|
165
|
+
def cmd_demote(a) -> int:
|
|
166
|
+
ok, out = store.demote(a.id, memory_dir=a.memory_dir, dry_run=a.dry_run,
|
|
167
|
+
note=a.note)
|
|
168
|
+
_p(("DEMOTED " if ok else "REFUSED ") + out)
|
|
169
|
+
return 0 if ok else 3
|
|
170
|
+
|
|
171
|
+
|
|
135
172
|
def cmd_refuse(a) -> int:
|
|
136
173
|
"""The other half of the review loop: 'this observation is wrong', recorded
|
|
137
174
|
rather than silently deleted, so the pool shows what was judged and rejected."""
|
|
@@ -340,6 +377,13 @@ def main(argv=None) -> int:
|
|
|
340
377
|
pr.add_argument("--dry-run", action="store_true")
|
|
341
378
|
pr.set_defaults(fn=cmd_promote)
|
|
342
379
|
|
|
380
|
+
dm = sub.add_parser("demote", help="un-approve a promoted memory (T2 -> refused, marked not deleted)")
|
|
381
|
+
dm.add_argument("id")
|
|
382
|
+
dm.add_argument("--memory-dir")
|
|
383
|
+
dm.add_argument("--note", default="")
|
|
384
|
+
dm.add_argument("--dry-run", action="store_true")
|
|
385
|
+
dm.set_defaults(fn=cmd_demote)
|
|
386
|
+
|
|
343
387
|
rf = sub.add_parser("refuse", help="mark a candidate wrong, with a note")
|
|
344
388
|
rf.add_argument("candidate_id")
|
|
345
389
|
rf.add_argument("--note", default="")
|
package/sleepkit/store.py
CHANGED
|
@@ -213,6 +213,44 @@ def refused_collision(text: str, threshold: float = REFUSED_DUP_THRESHOLD) -> tu
|
|
|
213
213
|
|
|
214
214
|
|
|
215
215
|
# ------------------------------------------------------------- candidates ---
|
|
216
|
+
def _record_rediscovery(cid: str, session: str) -> str | None:
|
|
217
|
+
"""Record that an agent re-learned an existing candidate in another session.
|
|
218
|
+
|
|
219
|
+
Returns a human message when the session differs from the ones already recorded
|
|
220
|
+
(a genuine cross-session rediscovery), or None when it is the same session again
|
|
221
|
+
(that is a repeat, not a pattern, and the plain duplicate message applies).
|
|
222
|
+
"""
|
|
223
|
+
got = get_candidate(cid)
|
|
224
|
+
if not got:
|
|
225
|
+
return None
|
|
226
|
+
meta, body = got
|
|
227
|
+
# The record's own session is the baseline: a repeat from the same session the
|
|
228
|
+
# fact was first filed in is a repeat, not a rediscovery. Only a *different*
|
|
229
|
+
# session counts.
|
|
230
|
+
sessions = [s for s in meta.get("rediscovered_in", "").split("|") if s]
|
|
231
|
+
own = (meta.get("session", "") or "").strip()
|
|
232
|
+
if own and own not in sessions:
|
|
233
|
+
sessions.append(own)
|
|
234
|
+
this = (session or "").strip()
|
|
235
|
+
if not this:
|
|
236
|
+
return None
|
|
237
|
+
if this in sessions:
|
|
238
|
+
return None
|
|
239
|
+
sessions.append(this)
|
|
240
|
+
n = int(meta.get("rediscovered", 0) or 0) + 1
|
|
241
|
+
meta["rediscovered"] = str(n)
|
|
242
|
+
meta["rediscovered_in"] = "|".join(sessions)
|
|
243
|
+
loc = paths.candidates_dir()
|
|
244
|
+
if not os.path.isfile(os.path.join(loc, cid + ".md")):
|
|
245
|
+
p = os.path.join(paths.archive_dir("candidates"), cid + ".md")
|
|
246
|
+
if os.path.isfile(p):
|
|
247
|
+
loc = paths.archive_dir("candidates")
|
|
248
|
+
with open(os.path.join(loc, cid + ".md"), "w", encoding="utf-8") as fh:
|
|
249
|
+
fh.write(emit(meta, body))
|
|
250
|
+
return "duplicate of %s (rediscovered in a later session: %d distinct sessions now; use `sleepctl show %s` to review)" % (
|
|
251
|
+
cid, n, cid)
|
|
252
|
+
|
|
253
|
+
|
|
216
254
|
def add_candidate(text: str, kind: str = "fact", source: str = "agent",
|
|
217
255
|
trust: str = "observed", session: str = "", cwd: str = "",
|
|
218
256
|
evidence: list[str] | None = None, supersedes: list[str] | None = None,
|
|
@@ -237,6 +275,14 @@ def add_candidate(text: str, kind: str = "fact", source: str = "agent",
|
|
|
237
275
|
pool = [(m["id"], m.get("_body", "")) for m in list_candidates(with_body=True)]
|
|
238
276
|
dup, score = nearest(red, pool)
|
|
239
277
|
if dup:
|
|
278
|
+
if source == "agent":
|
|
279
|
+
note = _record_rediscovery(dup, session)
|
|
280
|
+
if note:
|
|
281
|
+
# The agent independently re-learned a fact it already holds as a
|
|
282
|
+
# provisional candidate. It stays provisional (not a directive) and
|
|
283
|
+
# is not auto-kept; this just marks the cross-session rediscovery so
|
|
284
|
+
# the reviewer can weigh it. trust stays cap_trust(source) unchanged.
|
|
285
|
+
return False, note
|
|
240
286
|
return False, "duplicate of %s (%.2f); use `sleepctl supersede %s %s`" % (
|
|
241
287
|
dup, score, dup, "new-text")
|
|
242
288
|
ref_id, ref_score = refused_collision(red)
|
|
@@ -308,7 +354,14 @@ def set_status(cid: str, status: str, extra: dict | None = None) -> bool:
|
|
|
308
354
|
meta["reviewed"] = paths.now()
|
|
309
355
|
for k, v in (extra or {}).items():
|
|
310
356
|
meta[k] = v
|
|
311
|
-
|
|
357
|
+
# Write back where the record actually lives: promoted candidates are in the
|
|
358
|
+
# archive, pending ones in candidates. Writing always to candidates used to
|
|
359
|
+
# leave a promoted record's status change stranded in a stale archive copy.
|
|
360
|
+
loc = paths.candidates_dir()
|
|
361
|
+
if meta.get("promoted_to") or not os.path.isfile(os.path.join(loc, cid + ".md")):
|
|
362
|
+
if os.path.isfile(os.path.join(paths.archive_dir("candidates"), cid + ".md")):
|
|
363
|
+
loc = paths.archive_dir("candidates")
|
|
364
|
+
with open(os.path.join(loc, cid + ".md"), "w", encoding="utf-8") as fh:
|
|
312
365
|
fh.write(emit(meta, body))
|
|
313
366
|
return True
|
|
314
367
|
|
|
@@ -401,6 +454,83 @@ def append_index_line(memory_dir: str, line: str) -> tuple[bool, str]:
|
|
|
401
454
|
return True, "appended"
|
|
402
455
|
|
|
403
456
|
|
|
457
|
+
def remove_index_line(memory_dir: str, line: str, slug: str) -> bool:
|
|
458
|
+
"""Drop one managed index line by slug. Never touches content outside the block."""
|
|
459
|
+
idx = os.path.join(memory_dir, "MEMORY.md")
|
|
460
|
+
if not os.path.isfile(idx):
|
|
461
|
+
return False
|
|
462
|
+
with open(idx, encoding="utf-8") as fh:
|
|
463
|
+
existing = fh.read()
|
|
464
|
+
block_re = re.compile(re.escape(IDX_BEGIN) + r".*?" + re.escape(IDX_END), re.S)
|
|
465
|
+
m = block_re.search(existing)
|
|
466
|
+
if not m:
|
|
467
|
+
return False
|
|
468
|
+
block = m.group(0)
|
|
469
|
+
# Match any line whose "**<slug>**" heading equals ours, regardless of suffix.
|
|
470
|
+
target = "**%s**" % slug
|
|
471
|
+
kept, found = [], False
|
|
472
|
+
for ln in block.split("\n"):
|
|
473
|
+
if re.match(r"\s*- \*\*[^*]+\*\*:", ln) and target in ln:
|
|
474
|
+
found = True
|
|
475
|
+
continue
|
|
476
|
+
kept.append(ln)
|
|
477
|
+
if not found:
|
|
478
|
+
return False
|
|
479
|
+
new_block = "\n".join(kept)
|
|
480
|
+
updated = existing[:m.start()] + new_block + existing[m.end():]
|
|
481
|
+
with open(idx, "w", encoding="utf-8") as fh:
|
|
482
|
+
fh.write(updated)
|
|
483
|
+
return True
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def demote(cid: str, memory_dir: str | None = None, dry_run: bool = False,
|
|
487
|
+
note: str = "") -> tuple[bool, str]:
|
|
488
|
+
"""T2 -> refused. Explicit human act: an approved memory turned out wrong.
|
|
489
|
+
|
|
490
|
+
Promotion was "create a new file, never edit one"; reversal keeps that spirit.
|
|
491
|
+
The canonical T2 copy is *marked* retracted, not deleted, so the audit trail of
|
|
492
|
+
what was once approved survives; the index line is dropped so the retired value
|
|
493
|
+
no longer reads as active memory; and the archived candidate is re-opened as a
|
|
494
|
+
refused record the reviewer can see in `status`. Nothing on this path edits or
|
|
495
|
+
deletes a past verdict.
|
|
496
|
+
"""
|
|
497
|
+
got = get_candidate(cid)
|
|
498
|
+
if not got:
|
|
499
|
+
return False, "no such candidate: " + cid
|
|
500
|
+
meta, body = got
|
|
501
|
+
if meta.get("status") != "promoted":
|
|
502
|
+
return False, "not promoted (nothing to demote): " + cid
|
|
503
|
+
dest = meta.get("promoted_to") or ""
|
|
504
|
+
mdir = memory_dir or paths.memory_dir()
|
|
505
|
+
slug = os.path.basename(dest)[:-3] if dest else ""
|
|
506
|
+
if dry_run:
|
|
507
|
+
return True, "would retract %s (drop index line, mark candidate refused)" % (slug or cid)
|
|
508
|
+
stamp = paths.now()
|
|
509
|
+
# 1) mark the canonical T2 copy retracted
|
|
510
|
+
t2_ok = True
|
|
511
|
+
if dest and os.path.isfile(dest):
|
|
512
|
+
try:
|
|
513
|
+
with open(dest, encoding="utf-8") as fh:
|
|
514
|
+
m2, b2 = parse(fh.read())
|
|
515
|
+
m2["status"] = "retracted"
|
|
516
|
+
m2["retracted_at"] = stamp
|
|
517
|
+
if note:
|
|
518
|
+
m2["note"] = note
|
|
519
|
+
with open(dest, "w", encoding="utf-8") as fh:
|
|
520
|
+
fh.write(emit(m2, b2))
|
|
521
|
+
except (OSError, ValueError):
|
|
522
|
+
t2_ok = False
|
|
523
|
+
# 2) drop the index line so the retired value no longer reads as active
|
|
524
|
+
if slug and mdir:
|
|
525
|
+
remove_index_line(mdir, "", slug)
|
|
526
|
+
# 3) re-open the archived candidate as refused with a note the reviewer can see
|
|
527
|
+
if note:
|
|
528
|
+
set_status(cid, "refused", {"notes": note, "reviewed": stamp})
|
|
529
|
+
else:
|
|
530
|
+
set_status(cid, "refused", {"reviewed": stamp})
|
|
531
|
+
return True, ("retracted %s" % (slug or cid)
|
|
532
|
+
+ (" (T2 default not found)" if not t2_ok else ""))
|
|
533
|
+
|
|
404
534
|
def supersede(old_id: str, new_id: str) -> bool:
|
|
405
535
|
return (set_status(old_id, "superseded", {"superseded_by": new_id})
|
|
406
536
|
and set_status(new_id, "provisional", {"supersedes": old_id}))
|