counterparts 0.3.43 → 0.3.45

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +6 -6
  3. package/package.json +1 -1
  4. package/src/adapters/claude-code/CONTRACT.md +15 -4
  5. package/src/adapters/claude-code/NOTES.md +53 -0
  6. package/src/adapters/claude-code/awake.ts +122 -0
  7. package/src/adapters/claude-code/bin/runner.ts +9 -1
  8. package/src/adapters/claude-code/child.ts +14 -4
  9. package/src/adapters/claude-code/doctor-self-page.ts +47 -2
  10. package/src/adapters/claude-code/doctor.ts +6 -1
  11. package/src/adapters/claude-code/hooks.ts +49 -9
  12. package/src/adapters/claude-code/night-catch-up.ts +66 -1
  13. package/src/adapters/claude-code/night-run.ts +97 -19
  14. package/src/adapters/cli/commands-note.ts +6 -5
  15. package/src/adapters/cli/commands-self.ts +36 -1
  16. package/src/adapters/cli/commands.ts +11 -2
  17. package/src/adapters/cli/dream-core.ts +1 -1
  18. package/src/adapters/cli/help.ts +3 -1
  19. package/src/adapters/config.ts +16 -3
  20. package/src/adapters/dashboard/registries.ts +1 -1
  21. package/src/adapters/dashboard/web/narrate.ts +5 -1
  22. package/src/adapters/log/index.ts +4 -1
  23. package/src/adapters/mcp/CONTRACT.md +5 -2
  24. package/src/adapters/mcp/INTERFACE-GAPS.md +5 -0
  25. package/src/adapters/mcp/NOTES.md +2 -1
  26. package/src/adapters/mcp/server-session-end.ts +2 -2
  27. package/src/adapters/mcp/server-words.ts +11 -2
  28. package/src/adapters/mcp/server.ts +25 -15
  29. package/src/adapters/mcp/write-up.ts +43 -3
  30. package/src/adapters/sessions.ts +29 -0
  31. package/src/adapters/snapshots.ts +59 -0
  32. package/src/core/associate/CONTRACT.md +4 -0
  33. package/src/core/associate/NOTES.md +43 -0
  34. package/src/core/associate/index.ts +41 -5
  35. package/src/core/associate/tunables.ts +29 -0
  36. package/src/core/counterpart-deposit.ts +45 -14
  37. package/src/core/counterpart-types.ts +5 -2
  38. package/src/core/counterpart.ts +4 -1
  39. package/src/core/dream/CONTRACT.md +4 -3
  40. package/src/core/dream/NOTES.md +2 -1
  41. package/src/core/dream/index.ts +22 -9
  42. package/src/core/dream/reflect.ts +8 -3
  43. package/src/core/physics/CONTRACT.md +4 -0
  44. package/src/core/physics/index.ts +11 -1
  45. package/src/core/remember/CONTRACT.md +18 -4
  46. package/src/core/remember/NOTES.md +157 -0
  47. package/src/core/remember/index.ts +2 -0
  48. package/src/core/remember/owes.ts +100 -1
  49. package/src/core/remember/owner-strike-seam.ts +7 -1
  50. package/src/core/remember/proposals.ts +75 -27
  51. package/src/core/remember/retention.ts +35 -3
  52. package/src/core/remember/spans.ts +19 -1
  53. package/src/core/self/CONTRACT.md +7 -0
  54. package/src/core/self/NOTES.md +14 -0
  55. package/src/core/self/index.ts +3 -0
  56. package/src/core/self/writer.ts +33 -2
  57. package/src/core/sleep/CONTRACT.md +2 -1
  58. package/src/core/sleep/consolidate.ts +2 -1
  59. package/src/core/types.ts +10 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,46 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.45 — 2026-11-01
4
+
5
+ Nearly nothing you'd notice changes. **One thing happens at once: the first pass after upgrading deletes the raw copies of notes saved with no session or with `counterparts note` that are already past their age (3 days once the memory has landed, 14 whatever). Memories aren't touched, and raw text deleted this way doesn't come back, even if you go back to 0.3.44.** Learned cue words skip path fragments and acknowledgements. A memory that couldn't be saved can be sent again. A laptop's sleep no longer stops the night's work, and a headless session leaves the night to the next one a person starts. No store-format change (store v15, cache v7), no migration. Nothing to run after upgrading beyond the usual restart of the dashboard and every Claude Code session. Going back to 0.3.44 needs no store restore: `counterparts disconnect`, 0.3.44's install, then `counterparts connect`.
6
+
7
+ - **Learned cue words skip path fragments and acknowledgements.** Words from file and socket paths (`tmp`, `uds`, ...),
8
+ hex ids, and replies like "sounds good, go ahead" no longer wire themselves to a memory, and what they learned before
9
+ is ignored. Nothing in your store is changed.
10
+ - **Notes saved with no session, or with `counterparts note`, now lose their raw copies on time.** Those copies shared
11
+ a label, so each new note restarted the clock for the old ones, and with a note every couple of days the oldest was
12
+ never deleted. Each now goes on its own age: 3 days once its memory has landed, never more than 14. The memories
13
+ themselves aren't touched. The first run after updating deletes every such copy already past those ages, at once;
14
+ doctor's Raw transcripts line says how many.
15
+ - **A laptop's sleep no longer stops the night's work.** A night's watchdogs count time awake now, so a machine that
16
+ slept mid-run picks up where it left off instead of killing the child on waking. What a run slept through is on its
17
+ row, and a run that's asleep isn't read as lost, so no second one starts beside it. A child that's really stuck is
18
+ still stopped on schedule.
19
+ - **A headless session no longer starts the night.** `claude -p` and the Agent SDK leave it for the next session a
20
+ person starts, which runs it as usual, so nothing is lost by waiting. `counterparts catch-up` is run by hand as before.
21
+ A store that only headless sessions use gets no nights, and doctor says so after two days.
22
+ - **A memory that couldn't be saved can be saved again.** When the store was locked or full
23
+ at the moment of writing, the note was recorded as handled anyway: nothing was stored, sending
24
+ it again was refused as a duplicate, and its raw copy started its 3-day clock, along with
25
+ everything else that session had said if it was a `session_end`. Now nothing is marked
26
+ until the memory is on disk, so sending it again saves it once, and an unsaved note's words
27
+ stay owed for a later write-up. `remember` says what happened and to send it again, and the
28
+ failure shows in doctor. A write-up part with a memory that didn't land stays open to be
29
+ sent again, unless it's the last part and another memory from it landed; then the reply
30
+ says to save the rest with `remember`.
31
+
32
+ ## 0.3.44 — 2026-11-01
33
+
34
+ Nothing you'd notice changes by default. `counterparts page-form own` is new: one store's nightly writers amend its self page in the page's own form, and it's off until you set it (`counterparts page-form default` puts it back). The core door's shadow has stopped recording; what becomes core is decided exactly as before and nothing in it moves. No store-format change (store v15, cache v7); the switch is one setting kept in the store, with no migration. Nothing to run after upgrading beyond the usual restart of the dashboard and every Claude Code session. Going back to 0.3.43 needs no store restore: `counterparts disconnect`, 0.3.43's install, then `counterparts connect`; 0.3.43 ignores the switch.
35
+
36
+ - **A store can keep its self page in its own form.** `counterparts page-form own` tells the nightly writers to amend
37
+ the page keeping its sections and headings, dated stories where it tells stories, instead of keeping "## How I
38
+ work" as a few short lessons. Off unless set, one store at a time; `counterparts page-form default` puts it back.
39
+ - **The new way of deciding the core no longer runs in shadow.** 0.3.36 started it beside the old one, recording each
40
+ night what it would have let in or kept out. Those records have stopped. The core is still decided exactly as it was,
41
+ and nothing already in it changes. The code stays in place, and `physics.CORE_DOOR_SUPPORT` set to `"shadow"` turns
42
+ the records back on.
43
+
3
44
  ## 0.3.43 — 2026-11-01
4
45
 
5
46
  Nearly nothing changes by default. A folder you set off, observer or paused no longer puts its plain work reminders in the line above the wake: one is said if the folder is turned back on within a week of its day, and doctor counts the ones waiting. `recall "elsewhere"` lists the other folders the way the wake's Elsewhere reads them. The wake's new shape is in, switched off: with it off, every wake is byte-for-byte what 0.3.42 writes, and `counterparts wake-shape on` turns it on for one store (`off` or `default` turns it back). No store-format change (store v15, cache v7); the switch is one setting kept in the store, with no migration. Nothing to run after upgrading beyond the usual restart of the dashboard and every Claude Code session. Going back to 0.3.42 needs no store restore: `counterparts disconnect`, 0.3.42's install, then `counterparts connect`; 0.3.42 ignores the switch.
package/README.md CHANGED
@@ -51,8 +51,9 @@ to be deleted. The full walkthrough is in [`docs/QUICKSTART.md`](docs/QUICKSTART
51
51
  thing reminds you of another.
52
52
  - **It's yours.** Everything lives on your machine in one SQLite file you can read,
53
53
  export or delete. No API keys, no accounts, nothing sent anywhere. The text of your
54
- conversations is kept only until it's written up: deleted 3 days after that, never
55
- kept more than 14 days, and never in a backup. You can delete the conversation text,
54
+ conversations is kept only until it's written up: deleted 3 days after that, or at most
55
+ about two weeks after the conversation goes quiet, whichever comes first, once Counterparts
56
+ next runs, and never in a backup. You can delete the conversation text,
56
57
  the backups or the activity log on their own at any time (`counterparts delete`).
57
58
 
58
59
  ## Who it's for
@@ -61,10 +62,9 @@ People interested in giving an AI its own sense of self and building a relations
61
62
  with it over time. Tinkerers, researchers, writers, and anyone who talks to an assistant
62
63
  every day and wishes it remembered.
63
64
 
64
- ## What it's not
65
-
66
- It's not a work memory. It doesn't track your tasks, code conventions or project docs.
67
- Plenty of tools do that, including the memory built into ChatGPT and Claude.
65
+ This is the AI's own memory of you and your work together, in its own words, keeping what
66
+ matters across every project. A committed CLAUDE.md stays the place for team-wide rules
67
+ shared through git.
68
68
 
69
69
  ## Where it's going
70
70
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "counterparts",
3
- "version": "0.3.43",
3
+ "version": "0.3.45",
4
4
  "license": "MIT",
5
5
  "description": "Memory that turns AI tools into counterparts - a local-first, human-memory-modeled memory layer for AI.",
6
6
  "repository": {
@@ -765,9 +765,15 @@ working default).** `hooks.ts#isInteractive`: the host's own `CLAUDE_CODE_SESSIO
765
765
  `sessions.ts#NON_INTERACTIVE_ENTRYPOINTS` (`sdk-cli` is `claude -p`; the SDKs; `mcp`; the
766
766
  GitHub action) claims none of them — the dream line, a night run's hand-back, a carried
767
767
  share, a raised contradiction, plain reminders (at SessionStart and at a prompt), the update
768
- notice. An unknown or absent value is a person's. It may still START the day's headless run
769
- (`startUnwatched`); the line it would have been told is held (`Dreams#holdTold`) and the next
770
- interactive prompt says it while the run is still going, claimed at delivery (`claimHeld`,
768
+ notice. An unknown or absent value is a person's. Since 2026-11-01 (NT1) a name on that list,
769
+ unless the host says `ATTENDED=1`, leaves the day's headless run too (`passesOnNight`,
770
+ `passOnNight`): it reads the offer, claims nothing, and the next session a person starts takes the
771
+ night, with one `adapter.dream.unwatched` log line (`passed: "headless"`) when a night was due.
772
+ That is narrower than `isInteractive` on purpose, so a wrong reading costs a held line rather than
773
+ the night: `ATTENDED=0` off the list (a person's `claude --bg`, a teammate, a host name the host's
774
+ own list lacks) and a turn no person started in a person's session (`startedByHost`) may still
775
+ START it (`startUnwatched`); the line it would have been told is held (`Dreams#holdTold`) and the
776
+ next prompt a person starts says it while the run is still going, claimed at delivery (`claimHeld`,
771
777
  an event latch per run) — once the run has ended its hand-back tells what it did instead. An
772
778
  `ask` is left unclaimed for the next interactive session. Every day's line now tells the
773
779
  model to say it ONCE, in its first reply, as one plain sentence (`dream/#sayOnce`); the
@@ -947,7 +953,12 @@ they still owe, over the ceiling, busy elsewhere, batches, what stopped it, stat
947
953
  process-log line record it, and doctor's Nightly run and Catch-up lines read it through one
948
954
  renderer (`catchUpWords`). Nothing owed: no child, no row. The hook's `started` row carries
949
955
  the catch-up's whole watchdog from the start (`nightRowTimeoutMs`), so a long catch-up is
950
- not read as lost. A clean exit that stopped short of
956
+ not read as lost. **Every one of these watchdogs counts time awake (2026-11-01, NT1;
957
+ `awake.ts`):** a child's (`child.ts`), the run's hour (`NIGHT_WRITE_UP_TOTAL_MS`), and the row's,
958
+ where the waiting process adds each sleep it notices to `NightRun.sleptMs` so a run asleep isn't
959
+ read as lost and a dead one stops adding. A sleep also renews the batch's claims and its runner's
960
+ record (`renewCatchUp`, `WRITE_UP_CLAIM_MS`), so the waking child still holds what it was writing.
961
+ A child truly stuck awake is killed on schedule, a tick late at worst. A clean exit that stopped short of
951
962
  its allowance — some granted session neither written up nor brought to its `upTo` part —
952
963
  is recorded `partial`, not `done` (a usage limit exits 0 too; its output is not read), and
953
964
  starts no further batch. A runner record a killed process left open is ended at the
@@ -2942,3 +2942,56 @@ still merge an off folder's memories into a new row filed where the night ran. O
2942
2942
  `verifyRebuild` left `skippedArchived` out of what it counted; the plain arm has counted it since I13. On
2943
2943
  a copy of the live store the difference was exactly the archived rows (621; superseded rows are all archived
2944
2944
  too). A miscount in the check, and no row was unaccounted for.
2945
+
2946
+ ## 2026-11-01 — the night's two holes (NT1)
2947
+
2948
+ **What the clocks do, and how we know.** Nothing in JavaScript exposes a clock that stops for sleep everywhere, and
2949
+ the two platforms go opposite ways. So `awake.ts` depends on neither: it looks for a late tick on the wall clock.
2950
+
2951
+ - macOS, RUN on this laptop, 2026-11-01: `CLOCK_MONOTONIC` was 197,008 s and `CLOCK_UPTIME_RAW` 151,537 s, so the
2952
+ first runs through sleep and the second doesn't. Node 20.19, 22.23 and 24.22's `process.hrtime` read about 197,014 to
2953
+ 197,057 s, on the sleep-counting side (they follow `CLOCK_MONOTONIC_RAW`). READ: libuv's `darwin.c` takes `uv__hrtime`
2954
+ from `mach_continuous_time`, and the event loop's time, which `setTimeout` runs on, comes from `uv__hrtime`.
2955
+ - bun on macOS: its `process.hrtime` starts at 0 for each process, so running it says nothing about sleep. The evidence is
2956
+ the live log of 11-01 (the MCP server runs under bun here): started 16:02:33Z, `adapter.night.writeup` `state: timed-out`
2957
+ at 16:17:02Z, `ms: 868484`, on a 600,000 ms timer. So its timer counted the sleep and fired on wake. Bun's source wasn't read.
2958
+ - Linux, READ ONLY (no Linux machine, no Docker): libuv's `linux.c` uses `CLOCK_MONOTONIC` (or `_COARSE`), which
2959
+ `clock_gettime(2)` says doesn't count suspended time, and `CLOCK_BOOTTIME` only for `uv_uptime`. So under Node on Linux a
2960
+ plain `setTimeout` already waits out a suspend. Bun on Linux was neither run across a suspend nor read. The fix doesn't
2961
+ care: a tick a suspend delays shows the same gap on the wall clock whichever way the timer behaves.
2962
+ - RUN, SIGSTOP, bun 1.3.10 and Node 22.23, macOS: an 800 ms plain timer in a process stopped from 150 to 2,150 ms fires at
2963
+ 2,154 ms under both. The clocks ran on through the stop, as they do through a Mac's sleep. CI runs the awake-time version
2964
+ of that under bun and Node on Linux and macOS (`night-holes.test.ts`, `node-smoke.ts`). A stop isn't a sleep: the child
2965
+ keeps running through it, and on Linux the clocks wouldn't run on through a suspend. It proves the gap is told from the
2966
+ watchdog in a real process. Real sleep gets read live (`docs/CHECK-AFTER.md`).
2967
+
2968
+ **The tick looks at the wall clock, not the runtime's monotonic clock,** because a monotonic clock that stops for a suspend
2969
+ would show no gap at all. A stepped wall clock costs one misread: forward reads as sleep (the watchdog is that much longer),
2970
+ back reads as no time (a tick shorter).
2971
+
2972
+ **Separate meters.** The child's watchdog, the catch-up's hour and the run's row each keep their own, each a timer a second
2973
+ in a process that's otherwise waiting. Sharing one would thread it through the seat, and a seat that isn't Claude Code's
2974
+ would lose the row and the hour.
2975
+
2976
+ **A small window on wake.** The renewals and the row wait for the first tick after waking: right away on a Mac, up to a
2977
+ second on Linux. A person's prompt or the child's own tool call inside that second can still read a claim or a row as
2978
+ expired, as it would have before.
2979
+
2980
+ **A run asleep past midnight (review of #712).** `Dreams#status` held a second run off only for a row of the same date. That
2981
+ looked older than NT1, but on a Mac the plain timer used to kill such a run on wake, ahead of the morning's first prompt. Now it
2982
+ wakes and goes on, and after hours of quiet its dream reads as abandoned, so the prompt would start a second run that resumes
2983
+ the same dream. The gate now holds for any date up to today (`night.date <= at`), until the run ends or is lost. Nothing ends up
2984
+ waiting long: only a living process adds to `sleptMs`, and its watchdogs count time awake.
2985
+
2986
+ **What the host's `ATTENDED` means (review of #712, READ from the 2.1.316 binary, not run).** `XU()`: false for a session of kind
2987
+ `bg`, `daemon` or `daemon-worker` and for a teammate, even with a terminal; true with a terminal; otherwise true only for a
2988
+ non-child process whose entrypoint is on the host's own list (`claude-vscode`, `claude-desktop`, `claude-desktop-3p`,
2989
+ `local-agent`, `remote`, `remote_desktop`, `remote_mobile`, `remote_projects`, `remote_cowork`, `ssh-remote`, Slack, Teams,
2990
+ `claude-coworker`, and so on). Hooks always get it, so the entrypoint fallback in `isInteractive` doesn't run on a current host.
2991
+ A person's `claude --bg` is `cli` with `ATTENDED=0`, and a new host with no terminal is `ATTENDED=0` under a name nobody knows.
2992
+ So the night reads the list (`passesOnNight`), and only the told lines read `ATTENDED`. Not measured in a real `--bg` session.
2993
+
2994
+ **A headless-only store.** A night waits for a session a person starts, so a store only `claude -p` or the Agent SDK uses gets
2995
+ none under `auto`, as it already got none under `ask`. An app a person really talks to through the Agent SDK reads as
2996
+ headless too, unless the host says `ATTENDED=1`. Doctor's `night-headless` line says so after two days without a night; nothing
2997
+ more was built.
@@ -0,0 +1,122 @@
1
+ /**
2
+ * TIME AWAKE, TOLD FROM TIME ASLEEP (2026-11-01, NT1).
3
+ *
4
+ * On 2026-11-01 a night started in a lid-closed dark wake. Its catch-up child got about 15 s
5
+ * awake, the laptop slept 853 s, and its 10-minute `setTimeout` fired on wake. A watchdog is
6
+ * there to stop a child that is stuck, not one whose machine was asleep.
7
+ *
8
+ * No clock JavaScript can read stops for sleep everywhere, and timers disagree (run and read
9
+ * in the PR): on macOS `process.hrtime` runs through sleep (libuv uses `mach_continuous_time`,
10
+ * and bun's timer fired on wake on 11-01); on Linux libuv uses `CLOCK_MONOTONIC`, which stops
11
+ * for a suspend. So this leans on none of them. It looks at the wall clock every tick while it
12
+ * waits: a tick that comes `NIGHT_ASLEEP_GAP_MS` late means the process was not running, and
13
+ * that gap is not charged. Whether the runtime's timer fired right on wake (macOS) or a tick
14
+ * after it (Linux), the wall clock shows the same gap.
15
+ *
16
+ * Loose on purpose. A sleep shorter than the gap is charged, so nothing below it is ever
17
+ * mistaken for sleep and a stuck child still dies on schedule, a tick late at worst. A wall
18
+ * clock stepped forward reads as sleep and one stepped back as no time at all, each once.
19
+ * A process stopped by SIGSTOP reads as asleep too: it was not running either.
20
+ */
21
+ import { TUNABLES } from "../config.js";
22
+
23
+ export interface AwakeOptions {
24
+ /** The wall clock. */
25
+ readonly now?: () => number;
26
+ readonly tickMs?: number;
27
+ readonly gapMs?: number;
28
+ /** Starts one wait and returns how to cancel it; absent, an unref'd `setTimeout`. */
29
+ readonly schedule?: (fn: () => void, ms: number) => () => void;
30
+ /** Told each sleep as it is noticed, with how long it lasted. Its throw is swallowed. */
31
+ readonly onSlept?: (ms: number) => void;
32
+ }
33
+
34
+ /** What a wait has seen so far. Reading it looks at the clock, so a wait that ends on wake sees the sleep before the next tick. */
35
+ export interface AwakeMeter {
36
+ asleepMs(): number;
37
+ stop(): void;
38
+ }
39
+
40
+ function realSchedule(fn: () => void, ms: number): () => void {
41
+ const t = setTimeout(fn, ms);
42
+ t.unref?.();
43
+ return () => {
44
+ clearTimeout(t);
45
+ };
46
+ }
47
+
48
+ /** The accounts, with no timer of their own. */
49
+ function accounts(opts: AwakeOptions): { readonly tick: number; look(): void; awake(): number; asleep(): number } {
50
+ const now = opts.now ?? ((): number => Date.now());
51
+ const tick = opts.tickMs ?? TUNABLES.NIGHT_AWAKE_TICK_MS;
52
+ const gap = opts.gapMs ?? TUNABLES.NIGHT_ASLEEP_GAP_MS;
53
+ let last = now();
54
+ let awake = 0;
55
+ let asleep = 0;
56
+ return {
57
+ tick,
58
+ look(): void {
59
+ const t = now();
60
+ const elapsed = t - last;
61
+ last = t;
62
+ if (elapsed > gap) {
63
+ const slept = elapsed - tick;
64
+ awake += tick;
65
+ asleep += slept;
66
+ try {
67
+ opts.onSlept?.(slept);
68
+ } catch {
69
+ /* a sleep nobody could write down is still a sleep */
70
+ }
71
+ } else if (elapsed > 0) {
72
+ awake += elapsed;
73
+ }
74
+ },
75
+ awake: () => awake,
76
+ asleep: () => asleep,
77
+ };
78
+ }
79
+
80
+ /** A running count of what a long wait slept through. */
81
+ export function awakeMeter(opts: AwakeOptions = {}): AwakeMeter {
82
+ const a = accounts(opts);
83
+ const schedule = opts.schedule ?? realSchedule;
84
+ let cancel: (() => void) | null = null;
85
+ const step = (): void => {
86
+ a.look();
87
+ if (cancel !== null) cancel = schedule(step, a.tick);
88
+ };
89
+ cancel = schedule(step, a.tick);
90
+ return {
91
+ asleepMs(): number {
92
+ a.look();
93
+ return a.asleep();
94
+ },
95
+ stop(): void {
96
+ cancel?.();
97
+ cancel = null;
98
+ },
99
+ };
100
+ }
101
+
102
+ /** Run `fn` once after `ms` of time awake. Returns how to cancel it. */
103
+ export function armAwake(fn: () => void, ms: number, opts: AwakeOptions = {}): () => void {
104
+ const a = accounts(opts);
105
+ const schedule = opts.schedule ?? realSchedule;
106
+ let cancel: (() => void) | null = null;
107
+ const step = (): void => {
108
+ a.look();
109
+ const left = ms - a.awake();
110
+ if (left <= 0) {
111
+ cancel = null;
112
+ fn();
113
+ return;
114
+ }
115
+ cancel = schedule(step, Math.min(a.tick, left));
116
+ };
117
+ cancel = schedule(step, Math.min(a.tick, ms));
118
+ return () => {
119
+ cancel?.();
120
+ cancel = null;
121
+ };
122
+ }
@@ -85,7 +85,7 @@ import type { HostSessionEvidence, RetentionReport } from "../../../core/remembe
85
85
  import { pruneRetention } from "../../../core/remember/retention.js";
86
86
  import { dataDir, describeGuardRefusal } from "../../../core/store/index.js";
87
87
  import type { Store } from "../../../core/store/index.js";
88
- import { hostSessionEvidence, installedVersion, writeUpSources } from "../../sessions.js";
88
+ import { hostSessionEvidence, installedVersion, rewindWriteUps, writeUpSources } from "../../sessions.js";
89
89
  import { openLog } from "../../log/index.js";
90
90
  import { BINARY, TRANSPILED } from "../../runtime.js";
91
91
  import { installRoute } from "../../plugin.js";
@@ -197,6 +197,8 @@ const EMPTY_RETENTION: RetentionReport = {
197
197
  failed: 0,
198
198
  lines: 0,
199
199
  bytes: 0,
200
+ unboundLines: 0,
201
+ unboundSessions: [],
200
202
  };
201
203
 
202
204
  /**
@@ -285,6 +287,11 @@ export function retentionJob(input: {
285
287
  if (report.reason === "IO_FAILED" && report.failed === 0 && report.scopes === 0) {
286
288
  return { ...none, reason: "failed", code: "LATCH_FAILED" };
287
289
  }
290
+ // Lines gone from the head of a bucket move every part after them, so a
291
+ // write-up of it part way through starts again rather than skip what moved.
292
+ // Only that bucket: a write-up of the other lost nothing, and starting it
293
+ // again on every pass could keep it from ever finishing.
294
+ for (const session of report.unboundSessions) rewindWriteUps(store, session);
288
295
  let recorded = false;
289
296
  try {
290
297
  store.appendEvent({
@@ -305,6 +312,7 @@ export function retentionJob(input: {
305
312
  keptLive: report.keptLive,
306
313
  failed: report.failed,
307
314
  lines: report.lines,
315
+ unboundLines: report.unboundLines,
308
316
  recorded,
309
317
  });
310
318
  return { reason: "ran", date, report, recorded, code: null };
@@ -17,6 +17,8 @@
17
17
  import { spawn } from "node:child_process";
18
18
 
19
19
  import { withHostUmask } from "../private-umask.js";
20
+ import { armAwake } from "./awake.js";
21
+ import type { AwakeOptions } from "./awake.js";
20
22
 
21
23
  /**
22
24
  * The host CLI a windowless child runs — always this one, resolved on the
@@ -95,12 +97,16 @@ export const STDERR_TAIL_BYTES = 8 * 1024;
95
97
  export const KILL_GRACE_MS = 5_000;
96
98
  export const REAP_GRACE_MS = 2_000;
97
99
 
98
- /** The real starter: one child, two alarms, and an end that does not need it. */
99
- export async function startChild(plan: ChildPlan, abort?: AbortSignal): Promise<ChildResult> {
100
+ /**
101
+ * The real starter: one child, two alarms, and an end that does not need it.
102
+ * `awake`: TESTS ONLY, the watchdog's tick and gap (`awake.ts`).
103
+ */
104
+ export async function startChild(plan: ChildPlan, abort?: AbortSignal, awake?: AwakeOptions): Promise<ChildResult> {
100
105
  return await new Promise<ChildResult>((resolve) => {
101
106
  let settled = false;
102
107
  let terminated = false;
103
108
  const timers: ReturnType<typeof setTimeout>[] = [];
109
+ let watchdog: (() => void) | null = null;
104
110
  let off: (() => void) | null = null;
105
111
  // THE CHILD'S OWN OUTPUT (2026-10-12), kept only when asked for and only
106
112
  // up to the cap. A child that writes past it is drained, never blocked.
@@ -118,6 +124,7 @@ export async function startChild(plan: ChildPlan, abort?: AbortSignal): Promise<
118
124
  if (settled) return;
119
125
  settled = true;
120
126
  for (const t of timers) clearTimeout(t);
127
+ watchdog?.();
121
128
  off?.();
122
129
  resolve({ ...r, ...output(), ...stderr() });
123
130
  };
@@ -190,9 +197,12 @@ export async function startChild(plan: ChildPlan, abort?: AbortSignal): Promise<
190
197
  );
191
198
  };
192
199
  // THE CHILD'S OWN WATCHDOG, armed here rather than left to `spawn`'s
193
- // `timeout` option, which only signals and never resolves anything.
200
+ // `timeout` option, which only signals and never resolves anything. In
201
+ // time AWAKE (2026-11-01, NT1): a laptop's sleep is not the child being
202
+ // stuck. The two graces above stay plain: a kill that waits out a sleep
203
+ // has nothing to lose by landing on wake.
194
204
  if (Number.isFinite(plan.timeoutMs) && plan.timeoutMs > 0) {
195
- timers.push(arm(terminate, plan.timeoutMs));
205
+ watchdog = armAwake(terminate, plan.timeoutMs, awake);
196
206
  }
197
207
  // THE CALLER'S WATCHDOG, which may be shorter than the child's. Fired, it
198
208
  // takes the child with it rather than leaving the caller holding the store
@@ -33,6 +33,7 @@ import {
33
33
  // dashboard's health panel so the three cannot disagree about what "silent"
34
34
  // means (constitution 16, the same rule this module already keeps for "healthy").
35
35
  import { daysBetween } from "../fired.js";
36
+ import { NIGHT_RUNNER_PREFIX, NON_INTERACTIVE_ENTRYPOINTS, listSessions } from "../sessions.js";
36
37
  import { pageWriterMode } from "../config.js";
37
38
  import type { AdapterConfig } from "../config.js";
38
39
  import { catchUpOf, catchUpWords } from "./night-catch-up.js";
@@ -112,6 +113,50 @@ function toldDuring(store: Store, startedAt: number): boolean {
112
113
  * working. The fix says what to look at.
113
114
  */
114
115
  export function nightRunFindings(input: DoctorInput, store: Store): Finding[] {
116
+ return [...lastNightFindings(input, store), ...headlessOnlyFindings(store)];
117
+ }
118
+
119
+ /** How long without a night, ms, before a store only headless sessions use says so. */
120
+ export const HEADLESS_ONLY_AFTER_MS = 2 * 24 * 60 * 60_000;
121
+
122
+ /**
123
+ * ONLY HEADLESS SESSIONS HERE, AND NO NIGHTS (2026-11-01, NT1): a night waits for
124
+ * a session a person starts (`hooks.ts#passOnNight`), so a store only `claude -p`
125
+ * or the Agent SDK ever uses gets none under `auto`, the same as it always did
126
+ * under `ask`. Its memories wait in the queue. AMBER: a mechanism the owner chose
127
+ * isn't running. Read from the registry's week, by entrypoint (it keeps no
128
+ * `attended`), so a session the registry can't call headless keeps this quiet.
129
+ */
130
+ function headlessOnlyFindings(store: Store): Finding[] {
131
+ try {
132
+ if (dreamingSetting(store) !== "auto") return [];
133
+ const now = store.now();
134
+ const run = nightRunOf(store);
135
+ let headless = 0;
136
+ let oldest = now;
137
+ for (const r of listSessions(store.dir)) {
138
+ if (r.sessionId.startsWith(NIGHT_RUNNER_PREFIX)) continue;
139
+ if (r.entrypoint === undefined || !NON_INTERACTIVE_ENTRYPOINTS.has(r.entrypoint)) return [];
140
+ headless += 1;
141
+ oldest = Math.min(oldest, r.startedAt);
142
+ }
143
+ if (headless === 0 || now - (run?.startedAt ?? oldest) < HEADLESS_ONLY_AFTER_MS) return [];
144
+ return [
145
+ finding(
146
+ "night-headless",
147
+ "amber",
148
+ "Nightly run",
149
+ `auto; no night ${run === null ? "yet" : `since ${run.date}`}: only headless sessions here this week (claude -p, the Agent SDK), and a night waits for a session a person starts`,
150
+ "Nothing is lost while it waits: the memories stay queued. Start one session by hand and the night runs.",
151
+ { setting: "auto", headless },
152
+ ),
153
+ ];
154
+ } catch {
155
+ return [];
156
+ }
157
+ }
158
+
159
+ function lastNightFindings(input: DoctorInput, store: Store): Finding[] {
115
160
  let setting: DreamingSetting;
116
161
  let run: ReturnType<typeof nightRunOf>;
117
162
  let now: number;
@@ -124,7 +169,7 @@ export function nightRunFindings(input: DoctorInput, store: Store): Finding[] {
124
169
  }
125
170
  if (run === null) {
126
171
  if (setting !== "auto") return [];
127
- return [finding("night-run", "green", "Nightly run", "auto; no headless run yet — the first session of a day with enough new memory, or with write-ups owed from an earlier day, starts one", "", { setting, state: null })];
172
+ return [finding("night-run", "green", "Nightly run", "auto; no headless run yet — the first session a person starts on a day with enough new memory, or with write-ups owed from an earlier day, starts one", "", { setting, state: null })];
128
173
  }
129
174
  // ITS MORNING CATCH-UP (2026-10-01, build 3), when it had anything owed.
130
175
  const cu = catchUpOf(store, run.run);
@@ -190,7 +235,7 @@ export function nightRunFindings(input: DoctorInput, store: Store): Finding[] {
190
235
  lost && setting === "auto" ? "amber" : "green",
191
236
  "Nightly run",
192
237
  lost
193
- ? `${setting}; the run of ${run.date} started ${mins(now - run.startedAt)} ago and never reported an end — its process went away (a sleep, a restart, a kill)`
238
+ ? `${setting}; the run of ${run.date} started ${mins(now - run.startedAt)} ago and never reported an end — its process went away (a restart, a kill)`
194
239
  : `${setting}; running now (${what}), started ${mins(now - run.startedAt)} ago`,
195
240
  lost ? "The next session asks instead of starting another headless run. If this repeats, run claude -p once by hand in a terminal to see whether it hangs (a login, an update prompt)." : "",
196
241
  data,
@@ -957,6 +957,7 @@ function retentionFindings(input: DoctorInput, store: Store): Finding[] {
957
957
  keptYoung: run.keptYoung,
958
958
  keptLive: run.keptLive,
959
959
  failed: run.failed,
960
+ unboundLines: run.unboundLines,
960
961
  };
961
962
  const unfinished = run.reason === "STARTED" || run.reason === "LATCH_HELD";
962
963
  if (unfinished && run.date < input.today) {
@@ -974,7 +975,11 @@ function retentionFindings(input: DoctorInput, store: Store): Finding[] {
974
975
  if (unfinished) {
975
976
  return [finding("retention", "green", TITLE, `${policy} · a pass started today`, "", data)];
976
977
  }
977
- const counts = `${String(run.deleted)} pruned ${run.date} · ${String(run.keptOwed)} kept until written up · ${String(run.keptLive)} still open`;
978
+ // The notes filed under a shared id, "mcp" or "console", go line by line, on
979
+ // their own age (`remember/owes.ts#planUnboundLines`), so they are not in `deleted`.
980
+ const unbound =
981
+ run.unboundLines > 0 ? ` · ${String(run.unboundLines)} old note${run.unboundLines === 1 ? "" : "s"} with no session let go` : "";
982
+ const counts = `${String(run.deleted)} pruned ${run.date}${unbound} · ${String(run.keptOwed)} kept until written up · ${String(run.keptLive)} still open`;
978
983
  if (run.failed > 0) {
979
984
  return [
980
985
  finding(
@@ -285,15 +285,30 @@ export interface DreamTold {
285
285
  * code does not know. A headless or SDK one (`sessions.ts#NON_INTERACTIVE_
286
286
  * ENTRYPOINTS`: `claude -p` is `sdk-cli`) — or, first, one the host itself
287
287
  * says nobody attends (`HookInput.attended`) — leaves them for the next session
288
- * that is; it may still START the nightly run. Measured 2026-10-01: the day's
289
- * first prompt came from an SDK session with no terminal, which started the
290
- * run (fine) and claimed the dream line (nobody saw it).
288
+ * that is. Measured 2026-10-01: the day's first prompt came from an SDK session
289
+ * with no terminal, which started the run and claimed the dream line (nobody saw
290
+ * it). Whether it may START the night is a narrower question: `passesOnNight`.
291
291
  */
292
292
  export function isInteractive(input: Pick<HookInput, "entrypoint" | "attended">): boolean {
293
293
  if (input.attended !== undefined) return input.attended;
294
294
  return input.entrypoint === undefined || !NON_INTERACTIVE_ENTRYPOINTS.has(input.entrypoint);
295
295
  }
296
296
 
297
+ /**
298
+ * DOES THIS SESSION LEAVE THE NIGHT TO SOMEONE ELSE? (2026-11-01, NT1; review of
299
+ * #712.) Only a name on the headless list (`claude -p`, the SDKs, `mcp`, the GitHub
300
+ * action), the same reading as doctor's (`sessions.ts#notPointableWhy`), unless the
301
+ * host says a person is there. NOT `!isInteractive`: a wrong "nobody's watching"
302
+ * only holds a line for the next prompt, and a wrong "headless" here means no
303
+ * nights. `ATTENDED=0` covers more than `claude -p` (read from the 2.1.316 binary):
304
+ * a person's `claude --bg` (kind `bg`, entrypoint `cli`), a teammate, and any process
305
+ * with no terminal whose entrypoint isn't on the host's own list. Those start the
306
+ * night unwatched (`startUnwatched`), as they always did.
307
+ */
308
+ export function passesOnNight(input: Pick<HookInput, "entrypoint" | "attended">): boolean {
309
+ return input.attended !== true && input.entrypoint !== undefined && NON_INTERACTIVE_ENTRYPOINTS.has(input.entrypoint);
310
+ }
311
+
297
312
  /**
298
313
  * IS A PERSON THERE FOR THIS SESSION START? (2026-10-12.) `isInteractive`,
299
314
  * and two starts no person makes even when the host says somebody attends:
@@ -1211,8 +1226,16 @@ export class ClaudeCodeAdapter extends Lifecycle {
1211
1226
  private dreamLines(input: HookInput, byHost = false): { text: string; told: DreamTold | null; note: { notice: string; context: string } | null } {
1212
1227
  const none = { text: "", told: null, note: null };
1213
1228
  if (this.observer || input.at === undefined || input.nightRun === true || input.sessionId.length === 0) return none;
1214
- // A TURN NO PERSON STARTED (review of #445, 2026-10-12; `startedByHost`):
1215
- // as a session nobody watches — the headless run may start and its line is
1229
+ // A HEADLESS SESSION LEAVES THE NIGHT (2026-11-01, NT1): the night of 11-01
1230
+ // started from one in a lid-closed dark wake. Nothing is claimed, so the
1231
+ // next session a person starts takes it, and nothing is lost by waiting.
1232
+ if (passesOnNight(input)) {
1233
+ this.passOnNight(input);
1234
+ return none;
1235
+ }
1236
+ // A TURN NO PERSON STARTED, in a person's session (review of #445,
1237
+ // 2026-10-12; `startedByHost`), or a session the host calls unattended that
1238
+ // isn't on the headless list: the headless run may start and its line is
1216
1239
  // held; the day's line, the morning share and the raises wait for a person.
1217
1240
  if (!isInteractive(input) || byHost) {
1218
1241
  this.startUnwatched(input);
@@ -1279,10 +1302,27 @@ export class ClaudeCodeAdapter extends Lifecycle {
1279
1302
  }
1280
1303
 
1281
1304
  /**
1282
- * A SESSION NOBODY WATCHES (2026-10-01, lane 8): it may START the day's
1305
+ * A HEADLESS SESSION PASSES ON THE NIGHT (2026-11-01, NT1): the offer is read
1306
+ * and never claimed, so the day stays the next person's. The line in the log
1307
+ * says one passed; nothing is written to the store. Never throws.
1308
+ */
1309
+ private passOnNight(input: HookInput): void {
1310
+ if (input.at === undefined) return;
1311
+ try {
1312
+ const offer = this.counterpart.dreams.offer({ at: input.at, session: input.sessionId });
1313
+ if (offer?.headless === true) this.emit("adapter.dream.unwatched", { started: false, passed: "headless", entrypoint: input.entrypoint ?? null });
1314
+ } catch {
1315
+ /* the log line is a courtesy */
1316
+ }
1317
+ }
1318
+
1319
+ /**
1320
+ * A TURN NO PERSON STARTED, IN A PERSON'S SESSION, OR A SESSION THE HOST CALLS
1321
+ * UNATTENDED OFF THE HEADLESS LIST (2026-10-01, lane 8; `claude -p`'s and the
1322
+ * SDK's until NT1, `passesOnNight`): it may START the day's
1283
1323
  * headless run — the start is the point — and the line it would have been
1284
- * told is held for the next interactive session (`Dreams#holdTold`). An
1285
- * ASK is left unclaimed for that session too: nobody here could answer it.
1324
+ * told is held for the next turn a person starts (`Dreams#holdTold`). An
1325
+ * ASK is left unclaimed for that turn too: nobody here could answer it.
1286
1326
  * Nothing else is offered, raised, carried or claimed. Never throws.
1287
1327
  */
1288
1328
  private startUnwatched(input: HookInput): void {
@@ -1447,7 +1487,7 @@ export class ClaudeCodeAdapter extends Lifecycle {
1447
1487
  });
1448
1488
  if (!out.started) return couldNot("runner", out.code ?? String(out.reason));
1449
1489
  dreams.recordNightRun({ ...base, state: "started" });
1450
- this.emit("adapter.night.started", { run, pid: out.pid, kind: kind.kind, ...(offer.dreamSkipped === undefined ? {} : { dreamSkipped: offer.dreamSkipped }) });
1490
+ this.emit("adapter.night.started", { run, pid: out.pid, kind: kind.kind, entrypoint: input.entrypoint ?? null, ...(offer.dreamSkipped === undefined ? {} : { dreamSkipped: offer.dreamSkipped }) });
1451
1491
  return true;
1452
1492
  } catch (err) {
1453
1493
  return couldNot("runner", codeOf(err));