pi-sleep-agent 0.8.8 → 0.8.9

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
@@ -322,6 +322,7 @@ Run the two dream components separately when you want more control:
322
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
+ | `./sleep.py doctor --contradictions --tier t2` | Adjudicate pairs of **approved** permanent memory instead of candidates (`--tier both` does both); a T2 finding is labelled `contradicting-memory` and carries the `demote <older>` command, because approved memory is un-approved, never superseded |
325
326
 
326
327
  The headless model call picks its transport by what exists on the machine, in this order:
327
328
  the host agent's own `omo -p` (used when an `omo` binary is on PATH), then `claude
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-sleep-agent",
3
- "version": "0.8.8",
3
+ "version": "0.8.9",
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
@@ -207,7 +207,14 @@ def _doctor_shortlist() -> list:
207
207
  return out
208
208
 
209
209
 
210
- def _llm_contradictions(pairs: list, budget: float, model: str | None) -> list:
210
+ def _tier_of(cid: str, memory_ids: set) -> str:
211
+ """Which tier a record belongs to, so a pair's own membership decides its wording."""
212
+ return "t2" if cid in memory_ids else "t1"
213
+
214
+
215
+ def _llm_contradictions(pairs: list, budget: float, model: str | None,
216
+ tier: str = "t1", records: dict | None = None,
217
+ memory_ids: set | None = None) -> list:
211
218
  """Ask the model to adjudicate shortlisted pairs. Report-only: returns findings,
212
219
  changes nothing. A failed or unparseable call yields [] so doctor still reports the
213
220
  rest of its scan instead of dying on a model problem."""
@@ -217,8 +224,15 @@ def _llm_contradictions(pairs: list, budget: float, model: str | None) -> list:
217
224
  # under meta["_body"] (that key only exists on the list_candidates path). Reading the
218
225
  # wrong one sent the model three pairs of empty bodies, and it answered, correctly,
219
226
  # that there was nothing to compare - a silently useless call, not a crash.
220
- seen = {}
227
+ # `records` carries (meta, body) for the ids the caller already parsed. A permanent
228
+ # T2 record is not in the candidate store, so `store.get_candidate` returns nothing
229
+ # for it and this function used to hand the model three pairs of EMPTY bodies - the
230
+ # model then answered, correctly, that no claim was present, and the whole T2 pass
231
+ # reported a clean store without reading a single memory.
232
+ seen = dict(records or {})
221
233
  for cid in {c for pair in pairs for c in pair}:
234
+ if cid in seen:
235
+ continue
222
236
  got = store.get_candidate(cid)
223
237
  seen[cid] = (got[0], got[1]) if got else ({}, "")
224
238
  lines = []
@@ -228,8 +242,16 @@ def _llm_contradictions(pairs: list, budget: float, model: str | None) -> list:
228
242
  meta, body = seen.get(cid, ({}, ""))
229
243
  lines.append(" id=%s ts=%s body=%s" % (cid, meta.get("ts", "?"),
230
244
  (body or "").replace("\n", " ").strip()))
231
- user = ("Unreviewed provisional memory records, grouped into candidate pairs.\n"
232
- "Adjudicate each pair per your instructions.\n\n" + "\n".join(lines))
245
+ if tier in ("t2", "both"):
246
+ user = ("Memory records, grouped into candidate pairs. Some are unreviewed "
247
+ "provisional candidates; some are permanent memories a human already "
248
+ "approved.\nAdjudicate each pair per your instructions: two approved "
249
+ "memories that now assert opposite things mean the older one needs a "
250
+ "human verdict, not that the memory store is broken.\n\n"
251
+ + "\n".join(lines))
252
+ else:
253
+ user = ("Unreviewed provisional memory records, grouped into candidate pairs.\n"
254
+ "Adjudicate each pair per your instructions.\n\n" + "\n".join(lines))
233
255
  pf = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "prompts",
234
256
  "contradiction-check.md")
235
257
  # The subprocess seam: tests replace llm.run with a fake so the adjudication path is
@@ -264,6 +286,7 @@ def _llm_contradictions(pairs: list, budget: float, model: str | None) -> list:
264
286
  if not isinstance(doc, dict):
265
287
  return []
266
288
  found = []
289
+ mem = memory_ids or set()
267
290
  for item in doc.get("pairs") or []:
268
291
  if not isinstance(item, dict) or not item.get("contradiction"):
269
292
  continue
@@ -271,18 +294,63 @@ def _llm_contradictions(pairs: list, budget: float, model: str | None) -> list:
271
294
  older, newer = pairs[int(item["pair"]) - 1]
272
295
  except (KeyError, IndexError, ValueError, TypeError):
273
296
  continue
274
- found.append({"issue": "contradicting-candidates",
275
- "pair": [older, newer], "older": older, "newer": newer,
276
- "source": "model", "reason": str(item.get("reason", ""))[:200],
277
- "suggest": "sleep.py supersede %s %s" % (older, newer)})
297
+ # The label follows the pair, not the --tier flag: in `both` mode a T1 finding
298
+ # must not be reported as memory, nor a memory finding as a candidate.
299
+ tier_of_pair = "t2" if (older in mem and newer in mem) else "t1"
300
+ # T2 has no supersede verb: the only honest action on approved memory is a
301
+ # human demote (un-approve) of the record that lost, so the suggestion differs.
302
+ if tier_of_pair == "t2":
303
+ found.append({"issue": "contradicting-memory",
304
+ "pair": [older, newer], "older": older, "newer": newer,
305
+ "source": "model", "reason": str(item.get("reason", ""))[:200],
306
+ "suggest": "sleep.py demote %s" % older})
307
+ else:
308
+ found.append({"issue": "contradicting-candidates",
309
+ "pair": [older, newer], "older": older, "newer": newer,
310
+ "source": "model", "reason": str(item.get("reason", ""))[:200],
311
+ "suggest": "sleep.py supersede %s %s" % (older, newer)})
278
312
  return found
279
313
 
280
314
 
315
+ def _doctor_memory_shortlist(memory_dir: str | None = None) -> list:
316
+ """(id, body, ts) for every active permanent T2 record, the input to candidate_pairs."""
317
+ return store.permanent_records(memory_dir)
318
+
319
+
320
+ def _memory_records(memory_dir: str | None = None) -> dict:
321
+ """id -> (meta, body) for active permanent records, the lookup the adjudicator needs."""
322
+ out = {}
323
+ for cid, body, ts in store.permanent_records(memory_dir):
324
+ out[cid] = ({"id": cid, "ts": ts}, body)
325
+ return out
326
+
327
+
281
328
  def cmd_doctor(a) -> int:
282
329
  issues = store.doctor(needle=a.stale)
283
330
  if getattr(a, "contradictions", False):
284
- pairs = store.candidate_pairs(_doctor_shortlist())
285
- issues += _llm_contradictions(pairs, getattr(a, "budget", 0.25), getattr(a, "model", None))
331
+ tier = getattr(a, "tier", "t1") or "t1"
332
+ mdir = getattr(a, "cwd", None) or None
333
+ records: dict = {}
334
+ memory_ids: set = set()
335
+ if tier == "t2":
336
+ recs = _doctor_memory_shortlist(mdir)
337
+ records = _memory_records(mdir)
338
+ memory_ids = set(records)
339
+ elif tier == "both":
340
+ mem_recs = _doctor_memory_shortlist(mdir)
341
+ records = _memory_records(mdir)
342
+ memory_ids = set(records)
343
+ recs = _doctor_shortlist() + mem_recs
344
+ else:
345
+ recs = _doctor_shortlist()
346
+ # Keep only same-tier pairs: a T1-vs-T2 pair has no single honest action (there is
347
+ # no verb that both supersedes a candidate and un-approves a memory), so asking the
348
+ # model about it would produce a suggestion no command can carry out.
349
+ pairpairs = [p for p in store.candidate_pairs(recs)
350
+ if (_tier_of(p[0], memory_ids) == _tier_of(p[1], memory_ids))]
351
+ issues += _llm_contradictions(pairpairs, getattr(a, "budget", 0.25),
352
+ getattr(a, "model", None), tier=tier,
353
+ records=records, memory_ids=memory_ids)
286
354
  if a.json:
287
355
  _p(json.dumps(issues, indent=2, sort_keys=True, default=str))
288
356
  elif not issues:
@@ -540,6 +608,10 @@ def main(argv=None) -> int:
540
608
  "conflicts (costs budget; report-only, supersedes nothing)")
541
609
  dc.add_argument("--budget", type=float, default=0.25,
542
610
  help="max USD for --contradictions (default 0.25)")
611
+ dc.add_argument("--tier", choices=["t1", "t2", "both"], default="t1",
612
+ help="which tier --contradictions adjudicates: unreviewed "
613
+ "candidates (t1, default), approved permanent memory (t2), "
614
+ "or both")
543
615
  dc.set_defaults(fn=cmd_doctor)
544
616
 
545
617
  rp = sub.add_parser("replay", help="layer 3: A/B measure provisional memory, report-only")
package/sleepkit/store.py CHANGED
@@ -650,6 +650,35 @@ def _first_ref(value) -> str:
650
650
  return str(value or "").split("|")[0].strip()
651
651
 
652
652
 
653
+ def permanent_records(memory_dir: str | None = None) -> list:
654
+ """(id, body, ts) for every ACTIVE permanent (T2) record, the T2 analogue of the
655
+ provisional shortlist input.
656
+
657
+ Retracted files are excluded: a memory a person already un-approved is a decision,
658
+ not an inconsistency to re-report. `id` prefers the frontmatter id and falls back to
659
+ the filename slug, so a hand-written file (no id in frontmatter) is still nameable
660
+ in a finding and actionable with `demote <slug>`.
661
+ """
662
+ mdir = memory_dir or paths.memory_dir()
663
+ out = []
664
+ if not os.path.isdir(mdir):
665
+ return out
666
+ for name in sorted(os.listdir(mdir)):
667
+ if not name.endswith(".md") or name == "MEMORY.md":
668
+ continue
669
+ path = os.path.join(mdir, name)
670
+ try:
671
+ with open(path, encoding="utf-8") as fh:
672
+ meta, body = parse(fh.read())
673
+ except (OSError, ValueError):
674
+ continue
675
+ if meta.get("status") == "retracted":
676
+ continue
677
+ ref = str(meta.get("id") or name[:-3]).strip()
678
+ out.append((ref, body or "", str(meta.get("ts") or meta.get("promoted_at") or "")))
679
+ return out
680
+
681
+
653
682
  def _archived_candidates() -> list:
654
683
  """Parsed frontmatter of archived candidates (promoted/superseded records live there)."""
655
684
  out = []