pi-sleep-agent 0.8.1 → 0.8.3

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
@@ -6,14 +6,14 @@
6
6
 
7
7
  Capture while agents work. Consolidate when they stop. Promote only what you approve.
8
8
 
9
- [![Tests](https://img.shields.io/badge/tests-127%20passing-c4f042?labelColor=111827&style=flat-square)](#install)
9
+ [![Tests](https://img.shields.io/badge/tests-177%20passing-c4f042?labelColor=111827&style=flat-square)](#install)
10
10
  [![Python](https://img.shields.io/badge/python-3.10%2B-369eff?labelColor=111827&style=flat-square)](https://www.python.org/)
11
11
  [![Runtime dependencies](https://img.shields.io/badge/runtime%20dependencies-0-ffcb47?labelColor=111827&style=flat-square)](#install)
12
- [![Agents](https://img.shields.io/badge/agents-Pi%20%7C%20Claude-a78bfa?labelColor=111827&style=flat-square)](#supported-agents)
12
+ [![Agents](https://img.shields.io/badge/agent%20targets-9-a78bfa?labelColor=111827&style=flat-square)](#supported-agents)
13
13
 
14
14
  </div>
15
15
 
16
- Sleep adds a reviewable memory cycle to Pi, OmO, and Claude Code. It records useful observations during a session, turns them into provisional memory after the session, and keeps permanent memory behind an explicit human approval step.
16
+ Sleep adds a reviewable memory cycle to nine selectable coding-agent targets. It records useful observations during a session, turns them into provisional memory after the session, and keeps permanent memory behind an explicit human approval step.
17
17
 
18
18
  <p align="center">
19
19
  <img src=".github/assets/sleep-replay.png" alt="Terminal showing the sleep cycle: agents capture observations, sleep consolidates them into provisional memory, and only your promote makes them permanent" width="920" />
@@ -33,6 +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
+ - **Relevance-ranked injection.** With a query, provisional memory is ordered by overlap with the live request and each line carries its age, so the most relevant record survives the `--max` cut and stale facts read as stale.
36
37
  - **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
38
  - **Safety gates.** Secrets are redacted, hostile text is quarantined, and machine-generated prompts cannot claim user provenance.
38
39
 
@@ -42,18 +43,83 @@ Requirements:
42
43
 
43
44
  - Python 3.10 or newer
44
45
  - Claude Code CLI for model-backed consolidation and replay
45
- - Pi, OmO, Claude Code, or any combination of them
46
+ - One or more supported coding agents from the table below
46
47
 
47
48
  ```bash
48
49
  ./install.sh --dry-run # show every change without writing
49
- ./install.sh # install the shared skill and Claude Code hooks
50
- ./install.sh --extension # also install the Pi/OmO extension
51
- ./install.sh --launchd # also schedule the nightly pass on macOS
50
+ ./install.sh # install skill + hooks; asks whether to add the
51
+ # nightly pass and the Pi/OmO extension (no flags needed)
52
+ ./install.sh --extension # also install the Pi/OmO extension (no prompt)
53
+ ./install.sh --nightly # also schedule the nightly pass (no prompt)
54
+ ./install.sh --launchd # alias for --nightly (macOS convention)
52
55
  ```
53
56
 
54
- The installer runs the test suite first, creates backups before configuration changes, and is safe to run again.
57
+ On Windows the entry point `./install.sh` becomes `python tools\install.py` (or
58
+ `py tools\install.py`); the flags are identical:
55
59
 
56
- ### Pi / OmO extension
60
+ ```bat
61
+ py tools\install.py --dry-run
62
+ py tools\install.py --extension --nightly
63
+ ```
64
+
65
+ **Which agents get the capture hooks is your choice.** A plain `install.py` on a
66
+ real terminal asks which coding agents to wire (multi-select, default Claude Code).
67
+ Scripts and CI can pick explicitly without a prompt:
68
+
69
+ ```bash
70
+ python3 tools/install.py --agents claude # Claude Code only (default)
71
+ python3 tools/install.py --agents claude,gemini,cursor # several verified hook formats
72
+ python3 tools/install.py --agents pi,oh-my-pi # extension targets stay independent
73
+ SLEEP_PROJECT=/path/to/project python3 tools/install.py --agents opencode
74
+ ```
75
+
76
+ Accepted keys are `claude`, `gemini`, `pi`, `oh-my-pi`, `cursor`, `opencode`,
77
+ `windsurf`, `codex`, and `cline`. The interactive prompt shows the same list.
78
+ Selecting one key never installs another key. The older `--extension` flag selects
79
+ `pi` only.
80
+
81
+ | Key | Surface written | Capability | Confidence |
82
+ |---|---|---|---|
83
+ | `claude` | `$CLAUDE_HOME/settings.json` | Prompt capture, tool capture, stop and compact consolidation | Verified |
84
+ | `gemini` | `~/.gemini/settings.json` | `BeforePrompt`, `AfterTool`, `SessionEnd` | Measured hook grammar |
85
+ | `pi` | `~/.omo/agent/extensions/sleep` | Full TypeScript extension capture and context injection | Verified |
86
+ | `oh-my-pi` | `~/.omp/agent/extensions/sleep` | Pi-lineage extension path | Best effort |
87
+ | `cursor` | `~/.cursor/hooks.json` | Tool capture and session-end consolidation | Documented native hooks |
88
+ | `opencode` | `<project>/.opencode/` | Tool capture and idle consolidation through a project plugin | Verified plugin grammar |
89
+ | `windsurf` | `~/.codeium/windsurf/hooks.json` | Prompt and code-write capture | Measured hook grammar |
90
+ | `codex` | `~/.codex/config.toml` | Completion notification only; no per-turn prompt capture | Documented, limited |
91
+ | `cline` | VS Code user `settings.json` | `request_created` capture only | Best effort |
92
+
93
+ OpenCode is project-scoped. Set `SLEEP_PROJECT` when the project is not the
94
+ current directory. The installer renders the repository path into the copied
95
+ plugin and registers `./.opencode/plugins` in that project's
96
+ `.opencode/opencode.json`.
97
+
98
+ Codex has no per-turn hook. Its `[notify]` integration can wake consolidation
99
+ when a run completes, but it cannot capture the prompt stream. If `[notify]`
100
+ already owns a different command, Sleep leaves it unchanged. Cline and Oh My Pi
101
+ are marked best effort because their public integration contracts are less stable.
102
+ A missing event should be reported with the affected agent, config path, and the
103
+ last lines from `~/.sleep/logs/`.
104
+
105
+ Amp, Antigravity, GitHub Copilot, Aider, and OpenHands are not installer targets.
106
+ Their available surfaces are respectively absent/unstable lifecycle hooks or
107
+ transcript/event-stream polling, which this installer does not impersonate as a
108
+ working command-hook integration.
109
+
110
+ The installer runs the test suite first, creates backups before configuration
111
+ changes, and is safe to run again. `--dry-run` does not modify existing links or
112
+ config files. Uninstall removes only exact Sleep-owned commands, preserves foreign
113
+ entries, and backs up JSON/TOML files before changing them. It is one Python
114
+ script and works on macOS, Linux, and Windows; per-platform scheduling is chosen
115
+ automatically:
116
+
117
+ - **macOS** - a LaunchAgent (`~/Library/LaunchAgents/com.aydinnyunus.sleep-nightly.plist`).
118
+ - **Linux** - a cron job (`crontab -l`, kept inside owned `# BEGIN/END aydinnyunus-sleep-nightly` markers).
119
+ - **Windows** - a Task Scheduler task via `schtasks /create /tn aydinnyunus-sleep-nightly`.
120
+
121
+
122
+ ### Pi / OmO and Oh My Pi extensions
57
123
 
58
124
  Pi and OmO require Sleep's user-installed extension for automatic integration:
59
125
 
@@ -61,12 +127,17 @@ Pi and OmO require Sleep's user-installed extension for automatic integration:
61
127
  ./install.sh --extension
62
128
  ```
63
129
 
64
- The installer links this repository's `extension/` directory to:
130
+ The installer links this repository's `extension/` directory to the selected
131
+ extension target only:
65
132
 
66
133
  ```text
67
- ~/.omo/agent/extensions/sleep
134
+ pi -> ~/.omo/agent/extensions/sleep
135
+ oh-my-pi -> ~/.omp/agent/extensions/sleep
68
136
  ```
69
137
 
138
+ Use `--agents oh-my-pi` for Oh My Pi. `--extension` remains an alias for selecting
139
+ `pi`; it does not install Oh My Pi implicitly.
140
+
70
141
  The extension loads on the next Pi or OmO session and performs three jobs:
71
142
 
72
143
  - captures user messages and relevant tool activity into T0,
@@ -136,6 +207,8 @@ To remove Sleep and restore the backed-up configuration:
136
207
  ./uninstall.sh
137
208
  ```
138
209
 
210
+ On Windows, `python tools\uninstall.py` (or `py tools\uninstall.py`).
211
+
139
212
  ## Quick start
140
213
 
141
214
  Check the installation:
@@ -202,7 +275,7 @@ A dream pass performs four steps:
202
275
 
203
276
  1. **Mine.** Find instructions you repeated across separate sessions in the same project. This step is deterministic and makes no model call.
204
277
  2. **Consolidate.** When the sleep gate passes, ask the configured model to turn recent T0 observations into provisional T1 candidates.
205
- 3. **Hygiene.** Run the read-only `doctor` scan and fold any findings (duplicate headings, near-duplicate candidates, 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 candidates, records parked in quarantine awaiting review, or stale values when you pass `--stale <value>`) into the night's report.
206
279
  4. **Replay.** When replay is due, run selected tasks with provisional memory off and on, then write a comparison report.
207
280
 
208
281
  Every result stays reviewable. Candidates remain in T1 until you explicitly run `promote`.
@@ -246,20 +319,21 @@ Run the two dream components separately when you want more control:
246
319
  | `./sleep.py replay --run --limit 3` | Compare selected tasks with memory off and on |
247
320
  | `./sleep.py mine --dry-run` | Find preferences repeated across sessions |
248
321
  | `./sleep.py nightly --dry-run` | Preview the unattended nightly workflow |
249
- | `./sleep.py doctor` | Find duplicate or overlapping memory records, and flag provisional candidates not rediscovered for 4+ weeks (report only, never dropped) |
322
+ | `./sleep.py doctor` | Find duplicate or overlapping memory records, flag provisional candidates not rediscovered for 4+ weeks, and report records parked in quarantine awaiting a human (report only, never dropped or un-parked) |
250
323
  | `./sleep.py doctor --stale <value>` | Show which approved records still hold a stale value (e.g. a changed URL) |
251
- | `./sleep.py inject --project "$PWD"` | Print provisional context for the current project |
324
+ | `./sleep.py inject --project "$PWD"` | Print provisional context for the current project, newest first, each line dated |
325
+ | `./sleep.py inject --project "$PWD" --query "..."` | Same, but rank records by overlap with the live request so the most relevant survive `--max` |
252
326
 
253
327
  Run `./sleep.py <command> --help` for command-specific options.
254
328
 
255
329
  ## Supported agents
256
330
 
257
- | Agent | Integration |
258
- |---|---|
259
- | Claude Code | `UserPromptSubmit`, `PostToolUse`, `Stop`, and `PreCompact` hooks |
260
- | Pi / OmO | Required user-installed extension: `./install.sh --extension` |
261
-
262
- Both integrations share `$SLEEP_HOME`, so candidates reviewed from one client are visible to the other when the project scope matches.
331
+ The installer support matrix and confidence levels live in [Install](#install).
332
+ All selected integrations share `$SLEEP_HOME`, so candidates reviewed from one
333
+ client are visible to another when the project scope matches. Capture depth is not
334
+ identical: Claude, Gemini, Pi/OmO, OpenCode, Cursor, and Windsurf expose multiple
335
+ lifecycle boundaries; Codex is completion-only; Cline is request-created-only;
336
+ Oh My Pi is a best-effort Pi-lineage extension path.
263
337
 
264
338
  ## Configure unattended model calls
265
339
 
@@ -305,7 +379,7 @@ Additional safeguards:
305
379
  - Provisional memory is rendered as background, not as an instruction.
306
380
  - Secret-like values are replaced with redaction markers.
307
381
  - Prompt-injection and exfiltration shapes are moved to quarantine.
308
- - Mixed-project buffers fail closed instead of assigning facts to the wrong project.
382
+ - Mixed-project buffers are partitioned by project and consolidated separately; unaddressed records stay in T0.
309
383
  - Replay reports results but never promotes memory automatically.
310
384
  - Every model call has an explicit budget limit.
311
385
 
@@ -360,14 +434,15 @@ Use `--force` only when you intentionally want a model call.
360
434
 
361
435
  **The scheduled pass cannot reach the model**
362
436
 
363
- Confirm that `~/.sleep/env` exists, has mode `0600`, and contains the same provider settings used by your interactive shell. Then run `./sleep.py sleep --force` before relying on launchd.
437
+ Confirm that `~/.sleep/env` exists, has mode `0600`, and contains the same provider settings used by your interactive shell. Then run `./sleep.py sleep --force` before relying on the scheduled pass (launchd / cron / Task Scheduler).
364
438
 
365
439
  **A candidate appears in the wrong context**
366
440
 
367
- Run `./sleep.py show <id>` and check its `cwd`. Mixed-project batches are kept in T0 and return an error instead of producing candidates.
441
+ Run `./sleep.py show <id>` and check its `cwd`. Mixed-project batches are partitioned by canonical `cwd`; each project is consolidated independently, while records without a project address stay in T0.
368
442
 
369
443
  ## More documentation
370
444
 
445
+ - [Sleep: the reviewable-memory extension for coding agents](https://aydinnyunus.github.io/2026/11/01/sleep-agent-memory-extension/) (blog)
371
446
  - [Measured evidence and validation history](docs/EVIDENCE.md)
372
447
  - [Sleep Framework analysis](sleep-framework.md)
373
- - [Shared `/sleep` skill](skill/sleep/SKILL.md)
448
+ - [Shared `/sleep` skill](shared-skill/sleep/SKILL.md)
@@ -252,15 +252,21 @@ export default function sleep(pi, options = {}) {
252
252
  // request makes a duplicate impossible and makes stale memory impossible the same way.
253
253
  let block = "";
254
254
 
255
- async function loadBlock(ctx) {
255
+ // The live request text is passed as --query so the store can rank provisional records by
256
+ // overlap: with a capped --max, ordering decides what a model sees, and the newest line is
257
+ // not always the relevant one. Empty query = newest-first, the safe default.
258
+ async function loadBlock(ctx, query = "") {
256
259
  if (DISABLED()) return "";
257
260
  const cwd = ctx?.cwd || "";
261
+ const args = ["inject", "--project", cwd];
262
+ const q = String(query || "").trim().slice(0, 2000);
263
+ if (q) args.push("--query", q);
258
264
  // 5s, not the 20s default: this runs before the human's first reply is worth waiting on.
259
- const res = await sleepctl(["inject", "--project", cwd], 5000);
265
+ const res = await sleepctl(args, 5000);
260
266
  const text = (res.stdout || "").trim();
261
267
  block = text.includes("<provisional-memory") ? text : "";
262
268
  note("publish", block
263
- ? `cached ${block.length} chars for project=${cwd || "?"}`
269
+ ? `cached ${block.length} chars for project=${cwd || "?"} query=${q ? "yes" : "no"}`
264
270
  : `nothing to publish project=${cwd || "?"} ok=${res.ok} ${res.reason || ""}`.slice(0, 180));
265
271
  return block;
266
272
  }
@@ -288,6 +294,9 @@ export default function sleep(pi, options = {}) {
288
294
  pi_source: src, // rpc text wears the user's voice; Python decides what it is worth
289
295
  }, watchTimer);
290
296
  note("capture", `userprompt chars=${text.length} src=${src || "?"}`);
297
+ // Re-rank the provisional block against what this request is about, so the next
298
+ // request (the one that answers it) sees the most relevant memory first.
299
+ void loadBlock(ctx, text);
291
300
  });
292
301
 
293
302
  pi.on("tool_execution_start", async (event) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-sleep-agent",
3
- "version": "0.8.1",
3
+ "version": "0.8.3",
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
@@ -300,12 +300,48 @@ def _within_project(candidate_cwd: str, project: str) -> bool:
300
300
  return False
301
301
 
302
302
 
303
+ def _age_label(ts: str):
304
+ """Human-scale age for one record ("just now", "3h ago", "12d ago").
305
+
306
+ A model that can see a memory is three weeks old can discount it; one that sees
307
+ a bare fact cannot. Unparseable or missing timestamps yield None and the age is
308
+ simply omitted rather than guessed.
309
+ """
310
+ hours = store._hours_since(ts)
311
+ if hours is None:
312
+ return None
313
+ if hours < 1:
314
+ return "just now"
315
+ if hours < 48:
316
+ return "%dh ago" % int(hours)
317
+ return "%dd ago" % int(hours // 24)
318
+
319
+
320
+ def _inject_rank(records: list, query: str) -> list:
321
+ """Order records by overlap with ``query``, newest first as the tie-break.
322
+
323
+ Selection, not retrieval: there is no index and no embedding, only the same
324
+ token-overlap the dedupe gate already uses. With no query the order is by
325
+ timestamp descending, so the freshest memory is what survives a --max cut.
326
+ """
327
+ q = store._tokens(query) if query else set()
328
+ if q:
329
+ scored = []
330
+ for c in records:
331
+ body = c.get("_body", "")
332
+ overlap = len(q & store._tokens(body))
333
+ scored.append((overlap, c.get("ts", ""), c))
334
+ scored.sort(key=lambda t: (t[0], t[1]), reverse=True)
335
+ return [c for _, _, c in scored]
336
+ return sorted(records, key=lambda c: c.get("ts", ""), reverse=True)
337
+
338
+
303
339
  def cmd_inject(a) -> int:
304
340
  """Print the provisional-memory block for a session's context. Framed as context."""
341
+ pool = [c for c in store.list_candidates(status="provisional", with_body=True)
342
+ if _within_project(c.get("cwd", ""), a.project)]
305
343
  recs = []
306
- for c in store.list_candidates(status="provisional", with_body=True):
307
- if not _within_project(c.get("cwd", ""), a.project):
308
- continue
344
+ for c in _inject_rank(pool, getattr(a, "query", "") or ""):
309
345
  body = c.get("_body", "")
310
346
  src = c.get("source")
311
347
  trust = c.get("trust")
@@ -314,7 +350,11 @@ def cmd_inject(a) -> int:
314
350
  # its concrete targets masked so a wrong guess stays unactionable.
315
351
  if not (src == "user" and trust == "verified"):
316
352
  body, _ = safety.mask_unverified_targets(body)
317
- recs.append(safety.render_for_context({"text": body, "source": src, "trust": trust}))
353
+ line = safety.render_for_context({"text": body, "source": src, "trust": trust})
354
+ age = _age_label(c.get("ts", ""))
355
+ if age:
356
+ line += " (recorded %s)" % age
357
+ recs.append(line)
318
358
  if not recs:
319
359
  return 0
320
360
  _p("<provisional-memory unverified=\"true\">")
@@ -454,6 +494,9 @@ def main(argv=None) -> int:
454
494
  ij = sub.add_parser("inject", help="print the provisional-memory context block")
455
495
  ij.add_argument("--project", default="")
456
496
  ij.add_argument("--max", type=int, default=12)
497
+ ij.add_argument("--query", default="",
498
+ help="rank provisional records by overlap with this text "
499
+ "(the live request); newest first when omitted")
457
500
  ij.set_defaults(fn=cmd_inject)
458
501
 
459
502
  a = ap.parse_args(argv)
@@ -141,6 +141,24 @@ _RELAY_WEAK = [
141
141
  r"read-only code review\.|work in the git repo\b)"), "addressed to a role"),
142
142
  ]
143
143
 
144
+ # A skill's body reaches the hook as a typed prompt: the person invokes a slash command
145
+ # and the harness sends the skill text as the user turn, so it looks like authored speech
146
+ # while it is a program's instructions to a model. Measured 2026-11-01: the payload of
147
+ # ~/.claude-work/skills/ai-evaluator-pass/SKILL.md was captured twice as source=user and
148
+ # mined into a "preference" candidate; the shape gives it away. It is COMPOUND on purpose:
149
+ # a verdict token alone ("return PASS or FAIL") is something a person also types when they
150
+ # want a review, so it only counts together with a body-level constraint ("be concise",
151
+ # "do not edit files") that a slash-command payload carries and a person rarely does.
152
+ _RELAY_VERDICT = re.compile(
153
+ r"(?i)\b(?:return|respond with|answer|reply)\s+(?:pass|fail|ok|done)\b"
154
+ r"(?:\s*(?:or|/)\s*(?:pass|fail|ok|done)\b)?")
155
+ _RELAY_BODY_CONSTRAINT = re.compile(
156
+ r"(?i)\b(?:do not (?:edit|modify|write|create|touch)\s+(?:any\s+)?files?|be concise)\b")
157
+ _RELAY_COMPOUND = [
158
+ (lambda t: bool(_RELAY_VERDICT.search(t)) and bool(_RELAY_BODY_CONSTRAINT.search(t)),
159
+ "skill payload (verdict token + body constraint)"),
160
+ ]
161
+
144
162
 
145
163
  def machine_driven(environ: dict | None = None) -> str:
146
164
  """Name of an env marker proving this session was spawned by a host, else "".
@@ -163,6 +181,9 @@ def relay_reason(text: str, environ: dict | None = None) -> str | None:
163
181
  for pat, why in _RELAY_STRONG:
164
182
  if pat.search(t):
165
183
  return why
184
+ for pred, why in _RELAY_COMPOUND:
185
+ if pred(t):
186
+ return why
166
187
  if machine_driven(environ):
167
188
  for pat, why in _RELAY_WEAK:
168
189
  if pat.search(t):
package/sleepkit/store.py CHANGED
@@ -651,4 +651,17 @@ def doctor(memory_dir: str | None = None, targets: list[str] | None = None,
651
651
  if sim >= 0.7:
652
652
  out.append({"issue": "candidate-duplicates-memory", "id": cid, "file": path,
653
653
  "similarity": round(sim, 2)})
654
+ # Quarantine is a wait-for-a-human state, not a resting state: entries parked there
655
+ # are held out of every future consolidation until someone reads them. `doctor`
656
+ # reporting "clean" while the queue holds parked records is the failure a user hits
657
+ # by asking exactly the question doctor answers ("is anything waiting on me?").
658
+ # Report the count and the newest ids; nothing is dropped or changed here.
659
+ # Path assembled without paths.home(): home() creates the whole tier skeleton as a
660
+ # side effect, and a read-only report that lays down directories is not read-only.
661
+ qdir = os.path.join(paths.SLEEP_HOME, ".quarantine")
662
+ if os.path.isdir(qdir):
663
+ parked = sorted(f for f in os.listdir(qdir) if f.endswith(".json"))
664
+ if parked:
665
+ out.append({"issue": "quarantine-awaiting-review", "count": len(parked),
666
+ "newest": [f[:-5] for f in parked[-3:]]})
654
667
  return out