counterparts 0.3.8 → 0.3.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.
Files changed (58) hide show
  1. package/CHANGELOG.md +130 -0
  2. package/docs/module-map.md +13 -4
  3. package/package.json +3 -1
  4. package/src/adapters/claude-code/CONTRACT.md +40 -13
  5. package/src/adapters/claude-code/INTERFACE-GAPS.md +12 -13
  6. package/src/adapters/claude-code/NOTES.md +31 -0
  7. package/src/adapters/claude-code/bin/hook.ts +2 -2
  8. package/src/adapters/claude-code/bin/runner.ts +3 -3
  9. package/src/adapters/claude-code/doctor.ts +111 -3
  10. package/src/adapters/claude-code/embed-client.ts +1 -1
  11. package/src/adapters/claude-code/hooks.ts +112 -1376
  12. package/src/adapters/claude-code/index.ts +5 -5
  13. package/src/adapters/claude-code/night-run.ts +8 -6
  14. package/src/adapters/cli/CONTRACT.md +19 -1
  15. package/src/adapters/cli/commands.ts +103 -7
  16. package/src/adapters/cli/coverage.ts +16 -2
  17. package/src/adapters/cli/desktop.ts +181 -0
  18. package/src/adapters/cli/help.ts +8 -0
  19. package/src/adapters/cli/install.ts +16 -10
  20. package/src/adapters/cli/report.ts +2 -0
  21. package/src/adapters/cli/uninstall.ts +1 -1
  22. package/src/adapters/{claude-code/config.ts → config.ts} +26 -4
  23. package/src/adapters/dashboard/web/actions.ts +4 -0
  24. package/src/adapters/dashboard/web/pages/memories/fold.js +6 -1
  25. package/src/adapters/dashboard/web/views/archive-words.ts +36 -22
  26. package/src/adapters/expansions.ts +4 -3
  27. package/src/adapters/fired.ts +5 -5
  28. package/src/adapters/hosts.ts +185 -0
  29. package/src/adapters/lifecycle.ts +1616 -0
  30. package/src/adapters/mcp/CONTRACT.md +86 -9
  31. package/src/adapters/mcp/INTERFACE-GAPS.md +17 -10
  32. package/src/adapters/mcp/NOTES.md +109 -11
  33. package/src/adapters/mcp/bin/serve.ts +86 -3
  34. package/src/adapters/mcp/deliberate.ts +56 -4
  35. package/src/adapters/mcp/index.ts +21 -2
  36. package/src/adapters/mcp/server.ts +637 -68
  37. package/src/adapters/mcp/tools.ts +97 -11
  38. package/src/adapters/mcp/write-up.ts +71 -11
  39. package/src/adapters/scopes.ts +9 -1
  40. package/src/adapters/sessions.ts +300 -12
  41. package/src/adapters/snapshots.ts +1 -1
  42. package/src/adapters/{claude-code/spawn.ts → spawn.ts} +13 -3
  43. package/src/core/associate/pending.ts +1 -1
  44. package/src/core/counterpart.ts +12 -0
  45. package/src/core/feelings-wheel.ts +2 -0
  46. package/src/core/leaving.ts +77 -0
  47. package/src/core/recall/CONTRACT.md +39 -0
  48. package/src/core/recall/NOTES.md +94 -0
  49. package/src/core/recall/activate.ts +250 -17
  50. package/src/core/recall/feeling-ask.ts +216 -0
  51. package/src/core/recall/gate.ts +15 -3
  52. package/src/core/recall/index.ts +74 -2
  53. package/src/core/recall/tunables.ts +16 -0
  54. package/src/core/self/NOTES.md +10 -0
  55. package/src/core/self/index.ts +19 -0
  56. package/src/core/sleep/cycle.ts +8 -0
  57. package/src/core/store/cache.ts +1 -1
  58. package/src/core/store/index.ts +25 -0
@@ -2,7 +2,15 @@
2
2
  * The hooks — this host's sensory and motor surface.
3
3
  *
4
4
  * Everything host-specific lives here so the core stays host-agnostic
5
- * (constitution 5). The rules this file mechanizes, each from the CONTRACT:
5
+ * (constitution 5). What a session is to this memory whatever the host — the
6
+ * wake's composition, recall for a turn, the boundary, the ask's pacing, the
7
+ * write-up pointer, the registry writes, the worker — is `../lifecycle.ts`'s
8
+ * `Lifecycle` (2026-09-30), which `ClaudeCodeAdapter` extends; this file keeps
9
+ * what is Claude Code's: its five events, its envelope and the room it
10
+ * measures, its transcript's delivery check, the Stop ask's words, the
11
+ * parallel run's primacy, the notices and the dream line. The rules this file
12
+ * mechanizes, each from the CONTRACT (some of them now in the lifecycle's
13
+ * methods it calls):
6
14
  *
7
15
  * **G2 — no hook ever fails the host.** Every entry point below is wrapped in
8
16
  * `guard()`: one try/catch, one logged failure, one safe return. There is no
@@ -37,70 +45,34 @@
37
45
  * (parallel-run G4: the mute is evidenced, not asserted).
38
46
  */
39
47
  import {
40
- ADAPTER_ASK_EVENT,
41
- BOUNDARY_EVENT,
42
48
  CHECKOUT_EVENT,
43
- Counterpart,
44
- RECALL_CREDIT_EVENT,
45
49
  PRIMACY_DELIVER_EVENT,
46
50
  PRIMACY_STANDDOWN_EVENT,
47
- RECALL_DELIVERED_EVENT,
48
- SPAWN_FAILED_EVENT,
49
- SPAWN_REFUSED_EVENT,
50
- SPAWN_STARTED_EVENT,
51
51
  WAKE_DELIVERED_EVENT,
52
52
  WAKE_INJECTED_EVENT,
53
- WRITE_UP_FAILED_EVENT,
54
53
  } from "../../core/counterpart.js";
55
- import type { AdapterDurableEventName, PlainReminder } from "../../core/counterpart.js";
54
+ import type { PlainReminder } from "../../core/counterpart.js";
56
55
  import { newNightRunId } from "../../core/dream/index.js";
57
56
  import type { DreamOffer } from "../../core/dream/index.js";
58
- import type {
59
- BoundaryKind,
60
- CaptureResult,
61
- Turn as CapturedTurn,
62
- } from "../../core/remember/index.js";
57
+ import type { BoundaryKind } from "../../core/remember/index.js";
63
58
 
64
- import { CONFIG_FILE_EVENT } from "../config-path.js";
59
+ import { isDesktopScratchWorkspace } from "../hosts.js";
60
+ import { stanceOfMode } from "../scopes.js";
65
61
  import {
66
- SCOPE_EVENT,
67
- SCOPE_JOINED_LATE_EVENT,
68
- SCOPE_REFUSED_EVENT,
69
- SCOPE_UNREADABLE_EVENT,
70
- stanceOfMode,
71
- } from "../scopes.js";
72
- import type { ScopeVerdict } from "../scopes.js";
73
- import { countTranslated, readHandleResolutions, translateExpansions } from "../expansions.js";
74
- import type { ExpansionsRead } from "../expansions.js";
75
- import {
76
- ASK_ROW_COUNTING,
77
62
  decideUpdateNotice,
78
63
  installedBuild,
79
64
  isLive,
80
65
  markUpdateNoticeShown,
81
- owedWriteUps,
82
- progressKey,
83
- pruneSessions,
84
- pruneWriteUpProgress,
85
66
  readSession,
86
- readWriteUpProgress,
87
67
  recordSession,
88
- saveWriteUpPointer,
89
- saveWriteUpProgress,
90
68
  stampSessionOpened,
91
- WRITE_UP_PART_BYTES,
92
- writeUpEntries,
93
- writeUpParts,
94
- writeUpPlan,
95
69
  } from "../sessions.js";
96
- import type { SessionPhase, SessionRecord } from "../sessions.js";
97
- import { pruneLog } from "../log/index.js";
70
+ import type { SessionRecord } from "../sessions.js";
71
+ import { Lifecycle, codeOf, plainContextLine, plainLine } from "../lifecycle.js";
72
+ import type { LifecycleOptions, SessionInput } from "../lifecycle.js";
98
73
 
99
- import { calendarDate } from "../../core/self/index.js";
100
- import { localClock, localDate, readableDate } from "../../core/time.js";
101
- import { capabilities } from "./config.js";
102
- import { TUNABLES } from "./config.js";
103
- import type { AdapterConfig, CapabilityReport } from "./config.js";
74
+ import { localDate } from "../../core/time.js";
75
+ import { TUNABLES } from "../config.js";
104
76
  import { TUNABLES as RECALL_TUNABLES } from "../../core/recall/tunables.js";
105
77
  import { HOST_SESSION_START, HOST_USER_PROMPT_SUBMIT, envelopeJson, escapedBytes } from "./envelope.js";
106
78
  import { SESSION_NOTICE_BUDGET_MS, checkoutIsGraded, doctorFindings, noticeMessage, readCheckout } from "./doctor.js";
@@ -108,10 +80,33 @@ import type { CheckoutReading } from "./doctor.js";
108
80
  import { primacy } from "./primacy.js";
109
81
  import { nightTimeoutMs, planNightRunner } from "./night-run.js";
110
82
  import type { NightKind } from "./night-run.js";
111
- import { planSpawn, spawnDetached } from "./spawn.js";
112
- import type { SpawnOutcome, Spawner } from "./spawn.js";
83
+ import { spawnDetached } from "../spawn.js";
84
+ import type { SpawnOutcome } from "../spawn.js";
113
85
  import { NO_ARRIVAL, STOP_ASK_OPENER, readWakeArrival } from "./transcript.js";
114
- import type { Expansion, WakeArrival } from "./transcript.js";
86
+ import type { WakeArrival } from "./transcript.js";
87
+
88
+ /**
89
+ * WHAT MOVED TO THE LIFECYCLE, named here too (2026-09-30): this file's public
90
+ * surface — and `index.ts`'s, which re-exports it — is what it was before the
91
+ * host-neutral half moved out, so a caller that imported any of these from the
92
+ * hooks still finds them.
93
+ */
94
+ export {
95
+ SPAWN_REFUSAL_PREFIX,
96
+ SPAWN_START_COUNT_KEY,
97
+ SPAWN_START_DATE_KEY,
98
+ WRITE_UP_ASK_COUNT_KEY,
99
+ WRITE_UP_ASK_DATE_KEY,
100
+ WRITE_UP_CLOSE,
101
+ WRITE_UP_OPEN,
102
+ WRITE_UP_SHORT_LINE,
103
+ WRITE_UP_TOOL,
104
+ plainContextLine,
105
+ plainLine,
106
+ substanceOf,
107
+ writeUpPointer,
108
+ } from "../lifecycle.js";
109
+ export type { AdapterEvent, HostTurn } from "../lifecycle.js";
115
110
 
116
111
  /** Every hook this adapter installs, by the name it is wired under. */
117
112
  export const HOOKS = [
@@ -138,26 +133,13 @@ export const BOUNDARY_KIND: Record<SessionEndingHook, BoundaryKind> = {
138
133
  "pre-compact": "pre-compaction",
139
134
  };
140
135
 
141
- /** A turn as the host reports it. `source` is what makes G10/G11 decidable;
142
- * `entry` (when the host has one) groups the blocks of one message, so pacing
143
- * counts the message once (`transcript.ts#TranscriptTurn`). */
144
- export interface HostTurn extends CapturedTurn {
145
- readonly entry?: number;
146
- }
147
-
148
- export interface HookInput {
149
- readonly sessionId: string;
150
- /** The project scope. The host's cwd, resolved — never a raw relative path. */
151
- readonly scope: string;
152
- /** The transcript slice the host can see. The cursor decides what is new. */
153
- readonly turns?: readonly HostTurn[];
154
- /** True when the host named a transcript this process could not read: the
155
- * empty `turns` are then not a count, and pacing moves no watermark on them. */
156
- readonly turnsUnread?: boolean;
157
- /** Deliberate-recall calls positioned against `turns` (`transcript.ts#Expansion`). */
158
- readonly expansions?: readonly Expansion[];
159
- /** What the user typed this turn (`user-prompt-submit`). */
160
- readonly prompt?: string;
136
+ /**
137
+ * One hook event's input: the lifecycle's `SessionInput` (session, scope, the
138
+ * transcript's turns and expansions — `transcript.ts#Expansion` — the prompt,
139
+ * the model, the date, the nightly run's quiet, the entrypoint), and the two
140
+ * facts only this host has.
141
+ */
142
+ export interface HookInput extends SessionInput {
161
143
  /**
162
144
  * WHERE THE HOST IS KEEPING THIS SESSION'S TRANSCRIPT — the path the payload
163
145
  * named, carried so the delivery check can read the head of it and see what
@@ -166,27 +148,6 @@ export interface HookInput {
166
148
  * file read for the one thing that parse deliberately skips.
167
149
  */
168
150
  readonly transcriptPath?: string;
169
- /** The model that wrote the transcript's last assistant entry, when known. */
170
- readonly model?: string;
171
- /** Today's calendar date, for the temporal channel and the horizon lane. */
172
- readonly at?: string;
173
- /**
174
- * This session is the HEADLESS NIGHTLY RUN this package started
175
- * (`night-run.ts`, `COUNTERPARTS_NIGHT_RUN` in its environment, 2026-09-29):
176
- * `claude -p` running the page writer, the dream and the reflection, which
177
- * nobody watches. It is kept QUIET — it still wakes with the ordinary wake,
178
- * and nothing else: no capture (so it owes no write-up), no dream lines, no
179
- * plain reminders, no Stop ask, no write-up pointer, no first-launch question.
180
- */
181
- readonly nightRun?: boolean;
182
- /**
183
- * How the host was started, from `CLAUDE_CODE_ENTRYPOINT` in the hook's
184
- * environment (`cli`, `sdk-cli` for `claude -p`, `sdk-ts` / `sdk-py` for the
185
- * Agent SDK, …). Kept on the session's registry record; a small owed
186
- * stretch from one that was not a person's interactive conversation is not
187
- * pointed at (`sessions.ts#NON_INTERACTIVE_ENTRYPOINTS`, review of #285 N2).
188
- */
189
- readonly entrypoint?: string;
190
151
  /**
191
152
  * THE HOST'S RE-FIRE. A blocked Stop comes back with `stop_hook_active`, and
192
153
  * that pass must ask nothing — v1's anti-loop, kept for the same reason. It is
@@ -282,65 +243,26 @@ export interface DreamTold {
282
243
  readonly offer: DreamOffer | null;
283
244
  }
284
245
 
285
- export interface AdapterEvent {
286
- readonly at: number;
287
- readonly name: string;
288
- readonly data: Record<string, string | number | boolean | null>;
289
- }
290
-
291
- export interface AdapterOptions {
292
- readonly counterpart: Counterpart;
293
- readonly config: AdapterConfig;
294
- /** The interpreter the detached worker runs under. */
295
- readonly command?: string;
296
- readonly args?: readonly string[];
246
+ /**
247
+ * The lifecycle's options (`../lifecycle.ts#LifecycleOptions`: the brain, the
248
+ * configuration, the worker's command, the clock, which configuration file this
249
+ * process read, the scope verdict) and the one only this host has.
250
+ *
251
+ * The scope verdict does two things here beyond the lifecycle's record of it:
252
+ * when it is `unset`, the first-launch question is appended to the wake, once
253
+ * per session (G41). The `off` decision is NOT here: it is made in the entry
254
+ * point, because "no output and no write" is only a guarantee if nothing was
255
+ * constructed. `guard()` still refuses on it as a second, cheap site, for the
256
+ * same reason the observer stand-down lives at the store seam as well as at
257
+ * the entry point (observer-mode G8).
258
+ */
259
+ export interface AdapterOptions extends LifecycleOptions {
297
260
  /**
298
261
  * The args that run `bin/nightly.ts` under `command` — the headless nightly
299
262
  * run's own process (2026-09-29). Absent: the headless run cannot start, and
300
263
  * the day's line asks instead (`could-not-start`, reason `runner`).
301
264
  */
302
265
  readonly nightArgs?: readonly string[];
303
- readonly spawner?: Spawner;
304
- readonly onEvent?: (e: AdapterEvent) => void;
305
- readonly now?: () => number;
306
- /**
307
- * WHICH `claude-code.json` THIS PROCESS READ — an absolute path, resolved by
308
- * the entry point (`bin/hook.ts`, via `adapters/config-path.ts`) and passed in
309
- * because it is a fact about one process's startup, not something the adapter
310
- * may go and re-derive.
311
- *
312
- * The adapter does three things with it, all of them recording:
313
- * - one ring event at construction;
314
- * - the `config` field of every session registry record it writes, which is
315
- * the only DURABLE trace a hook can leave of this (a hook has no stdout to
316
- * tell the owner with — that channel is the model's context);
317
- * - the pin onto the detached worker's environment, so parent and child read
318
- * one file rather than resolving two.
319
- */
320
- readonly configPath?: string;
321
- /**
322
- * WHAT `<config dir>/scopes.json` SAYS ABOUT THIS DIRECTORY, resolved by the
323
- * entry point before anything opened (`bin/hook.ts#hookScopeVerdict`).
324
- *
325
- * The adapter does exactly two things with it: records it once, and — when it
326
- * is `unset` — appends the first-launch question to the wake, once per
327
- * session (G41). The `off` decision is NOT here: it is made in the entry
328
- * point, because "no output and no write" is only a guarantee if nothing was
329
- * constructed. `guard()` still refuses on it as a second, cheap site, for the
330
- * same reason the observer stand-down lives at the store seam as well as at
331
- * the entry point (observer-mode G8).
332
- */
333
- readonly scope?: ScopeVerdict;
334
- /** The sentence a registry that IS there and could not be read produced. */
335
- readonly scopeUnreadable?: string;
336
- /**
337
- * The ENTRIES that registry refused, by key (#92 review, F2). A file can parse
338
- * while one directory's entry does not, and those directories read as unset —
339
- * which is ON. Ring event here, and a flag on the wake's durable row, because
340
- * a hook process lives for one turn and "why is this directory recording
341
- * again" has to be answerable tomorrow.
342
- */
343
- readonly scopeRefused?: readonly string[];
344
266
  }
345
267
 
346
268
  /**
@@ -420,86 +342,12 @@ function besideWords(question: boolean, plain: number): string {
420
342
  export const PAGE_WRITER_TOOL = "counterparts self_page";
421
343
 
422
344
  /**
423
- * THE NEXT-SESSION WRITE-UP'S POINTER (roadmap C2, owner 2026-09-23).
424
- *
425
- * A session that ended before it was written up — it owes, by `core/coverage/`'s
426
- * rule, read through `remember/owes.ts#planRetention` — is written up by the
427
- * NEXT session that starts in its project. This hook does not carry its words: it puts a short
428
- * POINTER beside the wake in `HookResult.ask` (how many sessions here are
429
- * waiting, the oldest one's id, date and size, and the call that fetches it),
430
- * and the words come back through the MCP door (`mcp/write-up.ts`):
431
- * `session_end` with `writeUp` and no memories returns the next part, up to
432
- * ~24 KB; the same call with memories — or `[]`, "nothing worth keeping" —
433
- * answers it. Nothing leaves the machine beyond what Claude Code already sees;
434
- * the write-up is in the model's voice. (It is the only route: the opt-in
435
- * Anthropic API sweep was removed with the key, 2026-09-24.)
436
- *
437
- * **Why a pointer (owner's choice, 2026-09-23, option (b) of INTERFACE-GAPS
438
- * §15).** The host caps a hook's whole output at 10,000 characters and turns
439
- * anything longer into a preview — of the WAKE, which comes first. On a store
440
- * whose wake fills its budget there was no room for the words; an MCP result
441
- * is not under that cap. The pointer names the ended session ONCE and this
442
- * session once: ~410 bytes with the host's 36-character ids (measured).
443
- *
444
- * **Measured against the host's plain-stdout cap, not the reported budget**
445
- * (PR #192 review, MAJOR 1). The budget is what the WAKE is composed to; with no
446
- * owner notice `bin/hook.ts#hostDelivery` prints the wake and the asks as PLAIN
447
- * text, which the host caps at 10,000 characters with no JSON escaping to allow
448
- * for (bytes ≥ characters, so a byte count under the cap is a character count
449
- * under it). With a notice, `hostDelivery`'s own rule drops the notice when the
450
- * envelope would not fit — the wake and its asks win, as always. A pointer that
451
- * does not fit DEFERS, claims nothing, and says so durably
452
- * (`sessions.ts#WRITE_UP_POINTER_KEY`), which doctor reads. The count is BYTES
453
- * against a cap in characters — accepted (PR #192 re-review, NIT): it is the
454
- * safe direction, and it defers early only for a multi-byte wake over ~9,575
455
- * bytes, which is already past the 9,000-byte budget `install` writes.
456
- *
457
- * **Once per session, and the day's allowance.** A compaction re-firing
458
- * SessionStart points at nothing; at most `WRITE_UP_ASKS_PER_DAY` sessions a
459
- * calendar day (local time) are pointed. It MAY COINCIDE with the page writer's
460
- * ask or the first-launch question — the roadmap's reading of §13 G3, which is
461
- * about the blocked Stop: both are carried, the other first. Never under
462
- * observer, never in a directory set `off` (the entry point returns before
463
- * anything opens).
345
+ * THE NEXT-SESSION WRITE-UP'S POINTER (roadmap C2) — its words, constants and
346
+ * rules are the lifecycle's since 2026-09-30 (`../lifecycle.ts#writeUpPointer`,
347
+ * `Lifecycle#deliverWriteUpAsk`), re-exported above. This host puts it beside
348
+ * the wake in `HookResult.ask`, measured against the room its envelope has
349
+ * (`sessionStart`).
464
350
  */
465
- export const WRITE_UP_OPEN = "<counterparts-write-up>";
466
- export const WRITE_UP_CLOSE = "</counterparts-write-up>";
467
- /** The door, named the way the other asks name their tools. */
468
- export const WRITE_UP_TOOL = "counterparts session_end";
469
- /** Today's pointer count, beside the spawn tally in box 2's meta: two fixed
470
- * keys, the date and the count, so nothing grows without a sweep. */
471
- export const WRITE_UP_ASK_DATE_KEY = "adapter.writeup.asks.date";
472
- export const WRITE_UP_ASK_COUNT_KEY = "adapter.writeup.asks.count";
473
-
474
- /** What the pointer adds for a SMALL owed stretch (2026-09-29; since
475
- * 2026-09-30 `coverage/`'s `small`, under six pieces): one plain sentence. */
476
- export const WRITE_UP_SHORT_LINE = "It was a short session: one line is enough, or memories: [] if nothing in it is worth keeping.";
477
-
478
- /** THE POINTER the model reads — short, because the words come from the door,
479
- * and naming the ended session once. A small owed stretch (`short`) gets the
480
- * same pointer and one sentence more. */
481
- export function writeUpPointer(input: {
482
- waiting: number;
483
- ended: string;
484
- endedOn: string;
485
- bytes: number;
486
- part: number;
487
- of: number;
488
- live: string;
489
- short?: boolean;
490
- }): string {
491
- const some =
492
- input.waiting === 1
493
- ? "An earlier session here ended before it was written up"
494
- : `${String(input.waiting)} earlier sessions here ended before they were written up`;
495
- const size = input.bytes < 1024 ? "under 1 KB" : `~${String(Math.round(input.bytes / 1024))} KB`;
496
- const part = input.of <= 1 ? "" : `, part ${String(input.part)} of ${String(input.of)}`;
497
- return [
498
- WRITE_UP_OPEN,
499
- `${some}; the oldest, from ${input.endedOn}, left ${size} of what was said to it${part}. To write it up, call ${WRITE_UP_TOOL} with session: ${input.live}, writeUp: ${input.ended} and no memories to get the words, then again with the memories worth keeping (or memories: []).${input.short === true ? ` ${WRITE_UP_SHORT_LINE}` : ""}`,
500
- WRITE_UP_CLOSE,
501
- ].join("\n");
502
- }
503
351
  /**
504
352
  * THE ONE STOP ASK — v2's front door and its journal, in one text.
505
353
  *
@@ -588,125 +436,21 @@ export function stopAsk(sessionId: string, chapter: number): string {
588
436
  */
589
437
  export const STOP_HUMAN_LINE = "Counterparts: asking the assistant to write up this session's memories.";
590
438
 
591
- const EVENT_RING = 500;
592
-
593
439
  /**
594
- * Where the per-reason spawn refusal counters live: box 2's meta, under
595
- * `adapter.spawn.refusals.<reason>`.
596
- *
597
- * In the STORE because scar E4's escalation is a claim about a HOST over time
598
- * and a hook process lives for one turn. I32 is the bill for having kept it in
599
- * an instance field: the worker was refused at every boundary for a week and
600
- * `escalate` read false every single time, because every count was the first.
601
- *
602
- * Meta keys, not a schema change — the same shape `sleep.pruned.<id>` uses.
440
+ * THE CLAUDE CODE ADAPTER: the host lifecycle (`../lifecycle.ts#Lifecycle`),
441
+ * driven by this host's five hook events. It EXTENDS the lifecycle rather than
442
+ * holding one, so a hook body calls `this.composeWake`, `this.captureBoundary`,
443
+ * `this.deliverWriteUpAsk` exactly where it called its own methods before
444
+ * 2026-09-30, in the same order.
603
445
  */
604
- export const SPAWN_REFUSAL_PREFIX = "adapter.spawn.refusals.";
605
-
606
- /**
607
- * The other side's counter (2026-09-20, E2): how many times the worker HAS
608
- * started today. Two fixed keys rather than one per date, because nothing mows
609
- * meta and the only question the `adapter.spawn.started` row asks of it is "how
610
- * many today" — the row itself carries the date.
611
- */
612
- export const SPAWN_START_DATE_KEY = "adapter.spawn.started.date";
613
- export const SPAWN_START_COUNT_KEY = "adapter.spawn.started.count";
614
-
615
- export class ClaudeCodeAdapter {
616
- readonly counterpart: Counterpart;
617
- readonly config: AdapterConfig;
618
- readonly observer: boolean;
619
-
620
- private readonly command: string;
621
- private readonly args: readonly string[];
446
+ export class ClaudeCodeAdapter extends Lifecycle {
622
447
  private readonly nightArgs: readonly string[] | undefined;
623
- private readonly spawner: Spawner | undefined;
624
- private readonly onEvent: ((e: AdapterEvent) => void) | undefined;
625
- private readonly nowFn: () => number;
626
- /** The `claude-code.json` this process read — recorded, pinned, never re-derived. */
627
- private readonly configPath: string | undefined;
628
- /** What the scope registry said about this directory. `unset` when nobody said. */
629
- readonly scope: ScopeVerdict;
630
- /**
631
- * WHETHER THE REGISTRY ITSELF WAS IN TROUBLE when this process read it, for
632
- * the wake's durable row (#92 review, F2): `unreadable` is the whole file,
633
- * `partial` is one or more entries refused by name. Null is the ordinary day,
634
- * and the field is `null` on the row rather than absent, so a reader can tell
635
- * "the registry was fine" from "this row predates the question".
636
- */
637
- private scopeTrouble: "unreadable" | "partial" | null = null;
638
- private readonly ring: AdapterEvent[] = [];
639
448
  /** The anti-loop guard: one hook per session in flight at a time. */
640
449
  private readonly inFlight = new Set<string>();
641
- /**
642
- * Consecutive identical spawn refusals, per reason (scar E4's escalation) —
643
- * IN MEMORY ONLY when this adapter cannot write, which is the observer case.
644
- *
645
- * The durable copy lives in box 2's meta under `adapter.spawn.refusals.<reason>`
646
- * and is the one that counts. This map used to BE the counter, and that is
647
- * half of why I32 ran for a week: a hook process lives for one turn, so
648
- * "consecutive" was always 1, `escalate` was always false, and scar E4's
649
- * widening — a repeated refusal reaches a human — was inert on this host after
650
- * shipping. An instrument still counts here and nowhere else (§15 G3).
651
- */
652
- private readonly volatileRefusals = new Map<string, number>();
653
450
 
654
451
  constructor(opts: AdapterOptions) {
655
- this.counterpart = opts.counterpart;
656
- this.config = opts.config;
657
- this.observer = opts.counterpart.observer;
658
- this.command = opts.command ?? process.execPath;
659
- this.args = opts.args ?? [];
452
+ super(opts);
660
453
  this.nightArgs = opts.nightArgs;
661
- this.spawner = opts.spawner;
662
- this.onEvent = opts.onEvent;
663
- this.nowFn = opts.now ?? ((): number => Date.now());
664
- this.configPath = opts.configPath;
665
- this.scope = opts.scope ?? { mode: "unset", matched: null, entry: null };
666
- // ONE event naming the configuration this process read: a hook's stdout
667
- // belongs to the model, so
668
- // "which file answered" has nowhere else to go in-process. The durable half
669
- // is the session record's `config` field (`noteSession`).
670
- if (opts.configPath !== undefined && opts.configPath.length > 0) {
671
- this.emit(CONFIG_FILE_EVENT, { path: opts.configPath });
672
- }
673
- // ONE event naming the scope verdict this process ran under, and which
674
- // entry produced it — the answer to "why did this directory record nothing
675
- // today", which is otherwise a question only a person reading two JSON
676
- // files can answer.
677
- this.emit(SCOPE_EVENT, {
678
- mode: this.scope.mode,
679
- matched: this.scope.matched,
680
- stance: stanceOfMode(this.scope.mode),
681
- });
682
- // A registry that IS there and could not be read resolved to `unset` — on,
683
- // today's behaviour — and says so, because a silent fall-back to the
684
- // default is exactly the shape scar §2.4 is about.
685
- if (opts.scopeUnreadable !== undefined && opts.scopeUnreadable.length > 0) {
686
- this.emit(SCOPE_UNREADABLE_EVENT, { detail: opts.scopeUnreadable });
687
- }
688
- // The per-ENTRY half of the same fact. Those directories read as unset,
689
- // which is on: an `off` somebody typed badly is an `off` nobody is keeping.
690
- if (opts.scopeRefused !== undefined && opts.scopeRefused.length > 0) {
691
- this.scopeTrouble = "partial";
692
- this.emit(SCOPE_REFUSED_EVENT, {
693
- count: opts.scopeRefused.length,
694
- keys: opts.scopeRefused.join(", "),
695
- });
696
- }
697
- // An unreadable FILE outranks refused entries: there were no entries.
698
- if (opts.scopeUnreadable !== undefined && opts.scopeUnreadable.length > 0) {
699
- this.scopeTrouble = "unreadable";
700
- }
701
- }
702
-
703
- events(name?: string): AdapterEvent[] {
704
- return this.ring.filter((e) => name === undefined || e.name === name).map((e) => ({ ...e }));
705
- }
706
-
707
- /** §4 G4: every host-dependent limit, as a checkable value. */
708
- capabilities(): CapabilityReport[] {
709
- return capabilities(this.config);
710
454
  }
711
455
 
712
456
  // ── session start: the wake ────────────────────────────────────────────────
@@ -752,17 +496,9 @@ export class ClaudeCodeAdapter {
752
496
  // directory this one opened in is a delivery-time fact exactly as the date
753
497
  // is — and it is the only thing that can decide whose handoff pointer,
754
498
  // if any, belongs at the foot of this wake.
755
- const woke = this.counterpart.wake(
756
- budget,
757
- { ...(input.at === undefined ? {} : { date: input.at }) },
758
- { scope: input.scope, session: input.sessionId.length === 0 ? null : input.sessionId },
759
- );
760
- // THE EXPECTATION, WRITTEN WHERE THE NEXT PROCESS CAN READ IT. This used
761
- // to be a `Map` on this instance, which is a line that only looks like it
762
- // works: every hook is its own process, so the hook that tests it always
763
- // met an empty map. `adapter.wake.delivered` wrote no row in two weeks of
764
- // running (mechanism inventory 2026-09-17, S2).
765
- this.noteWakeExpectation(input, woke.sentinel);
499
+ // The composition and THE EXPECTATION, written where the next process
500
+ // can read it (`Lifecycle#composeWake` → `noteWakeExpectation`).
501
+ const woke = this.composeWake(input, budget);
766
502
 
767
503
  // THE PERSON'S CLOCK, as the wake's first line (docs/time.md rule 5,
768
504
  // 2026-09-25): `Now: Fri 25 Sep 2026, 1:40 pm MDT`, in the store's zone.
@@ -894,6 +630,13 @@ export class ClaudeCodeAdapter {
894
630
  return false;
895
631
  }
896
632
  if (input.sessionId.length === 0 || input.nightRun === true) return false;
633
+ // A FOURTH (2026-09-30): Claude Desktop's Code tab, started with "No
634
+ // folder", runs in a scratch directory it deletes with the session — an
635
+ // answer recorded for it would outlive the folder it names.
636
+ if (isDesktopScratchWorkspace(input.scope)) {
637
+ this.emit("adapter.scope.ask.skipped", { reason: "scratch-workspace" });
638
+ return false;
639
+ }
897
640
  try {
898
641
  return readSession(this.counterpart.store.dir, input.sessionId)?.askedScope !== true;
899
642
  } catch {
@@ -931,167 +674,12 @@ export class ClaudeCodeAdapter {
931
674
  phase: "start",
932
675
  at: this.nowFn(),
933
676
  askedScope: true,
934
- ...(this.configPath === undefined || this.configPath.length === 0
935
- ? {}
936
- : { config: this.configPath }),
677
+ ...this.recordStamp(),
937
678
  });
938
679
  this.emit("adapter.scope.ask", { bytes: SCOPE_ASK_BYTES, recorded: marked !== null });
939
680
  return SCOPE_ASK;
940
681
  }
941
682
 
942
- /**
943
- * THE NEXT-SESSION WRITE-UP'S POINTER (C2) — find the session in this project
944
- * that ended owing a write-up and was pointed at least recently (oldest first
945
- * among equals), and point this session at it. Returns the block, or the empty
946
- * string.
947
- *
948
- * `spent` is the bytes the wake and any other ask already take, separators
949
- * included. **The whole body is fail-open**: a pointer that cannot be
950
- * composed costs the pointer and never the wake (§1 G7).
951
- *
952
- * The marks come before the words, the page writer's order: the progress
953
- * entry (so the rotation moves on even if nobody fetches), then this
954
- * session's `writeUpPointer` — the door's evidence that this session may
955
- * fetch that session's words — then the day's count and the durable outcome.
956
- * A mark that will not land hands nothing over.
957
- */
958
- private deliverWriteUpAsk(
959
- input: HookInput,
960
- spent: number,
961
- opts: { limit?: number; cost?: (text: string) => number; beside?: string } = {},
962
- ): string {
963
- try {
964
- // Never under observer: an instrument asks nobody to write into a store
965
- // it may not write, and has no registry mark to remember that it did.
966
- if (this.observer) return "";
967
- if (input.sessionId.length === 0 || input.nightRun === true) return "";
968
- const store = this.counterpart.store;
969
- const dir = store.dir;
970
- // ONE PER SESSION. A compaction re-fires SessionStart, and the record
971
- // carries the mark forward (`sessions.ts#recordSession`).
972
- const record = readSession(dir, input.sessionId);
973
- if (record?.writeUpPointer !== undefined) return "";
974
- // THE DAY'S ALLOWANCE, before anything is read — a spent day costs two
975
- // meta reads and nothing else.
976
- const today = this.counterpart.self.calendarToday();
977
- const spentToday =
978
- store.getMeta(WRITE_UP_ASK_DATE_KEY) === today ? Number(store.getMeta(WRITE_UP_ASK_COUNT_KEY) ?? "0") : 0;
979
- if (spentToday >= TUNABLES.WRITE_UP_ASKS_PER_DAY) {
980
- this.emit("adapter.writeup.skipped", { reason: "asks-spent", today: spentToday });
981
- return "";
982
- }
983
- const now = this.nowFn();
984
- const plan = writeUpPlan({ store, spans: this.counterpart.spans });
985
- // Entries whose session stopped owing some other way go first.
986
- pruneWriteUpProgress(store, plan);
987
- const inFlight = readWriteUpProgress(store);
988
- const zone = this.counterpart.store.zone();
989
- const owed = owedWriteUps(plan, dir, input.scope, now, {
990
- exclude: input.sessionId,
991
- progress: inFlight,
992
- pointedToday: (at) => calendarDate(at, zone) === today,
993
- });
994
- // Full write-ups come first (`owedWriteUps`), so a SMALL one is pointed
995
- // at only when no full one is waiting: it takes what is left of the
996
- // day's allowance.
997
- const first = owed[0];
998
- if (first === undefined) return "";
999
- const { held, here, short } = first;
1000
- // THIS PROJECT'S WORDS ONLY (MAJOR 6).
1001
- const entries = writeUpEntries(this.counterpart.spans, { session: held.session, scopes: [here] });
1002
- if (entries.length === 0) return "";
1003
- const key = progressKey(held.session, here);
1004
- const progress = inFlight[key];
1005
- const chunk = progress?.chunk ?? WRITE_UP_PART_BYTES;
1006
- // ONCE THE LAST PART HAS COME BACK (`answer` set, the mark still to
1007
- // land), the count is frozen: the words now read as kept, their marks
1008
- // lengthen the text, and a recount could find a part that was never
1009
- // served (re-review, m-B). The fetch finishes the mark.
1010
- const finished = progress !== undefined && progress.answer !== undefined;
1011
- const cut = finished ? [] : writeUpParts(entries, chunk);
1012
- if (!finished && cut.length === 0) return "";
1013
- const partsCount = finished ? progress.parts : cut.length;
1014
- const done = finished ? progress.parts : Math.min(progress?.done ?? 0, partsCount);
1015
- const text = writeUpPointer({
1016
- waiting: owed.length,
1017
- ended: held.session,
1018
- endedOn: calendarDate(held.clockFrom, this.counterpart.store.zone()),
1019
- bytes: cut.slice(done).reduce((n, p) => n + Buffer.byteLength(p, "utf8"), 0),
1020
- part: Math.min(done + 1, partsCount),
1021
- of: partsCount,
1022
- live: input.sessionId,
1023
- short,
1024
- });
1025
- const bytes = (opts.cost ?? ((t: string): number => Buffer.byteLength(t, "utf8")))(`\n\n${text}`);
1026
- const limit = opts.limit ?? TUNABLES.HOST_OUTPUT_CHARS;
1027
- const room = limit - spent;
1028
- const outcome = (o: "pointed" | "deferred", reason?: string): void => {
1029
- saveWriteUpPointer(store, {
1030
- at: now,
1031
- date: today,
1032
- outcome: o,
1033
- ...(reason === undefined ? {} : { reason }),
1034
- need: bytes,
1035
- room,
1036
- ...(limit === TUNABLES.HOST_OUTPUT_CHARS ? {} : { limit }),
1037
- ...(opts.beside === undefined || opts.beside.length === 0 ? {} : { beside: opts.beside }),
1038
- });
1039
- };
1040
- if (bytes > room) {
1041
- // DEFERRED, never truncated: nothing is claimed, so the next start in
1042
- // this project is pointed instead — and the deferral is DURABLE, so
1043
- // doctor can say the wake is too full and by how much.
1044
- this.emit("adapter.writeup.deferred", { reason: "host-cap", need: bytes, room });
1045
- this.emit("adapter.envelope.gave-way", { hook: "session-start", part: "pointer", need: bytes, room });
1046
- outcome("deferred", "host-cap");
1047
- return "";
1048
- }
1049
- const saved = saveWriteUpProgress(store, key, {
1050
- ...(progress ?? {}),
1051
- chunk,
1052
- parts: partsCount,
1053
- done,
1054
- handedAt: now,
1055
- });
1056
- const marked =
1057
- saved &&
1058
- recordSession(dir, {
1059
- sessionId: input.sessionId,
1060
- scope: input.scope,
1061
- phase: "start",
1062
- at: now,
1063
- writeUpPointer: held.session,
1064
- ...(this.configPath === undefined || this.configPath.length === 0 ? {} : { config: this.configPath }),
1065
- }) !== null;
1066
- if (!marked) {
1067
- this.emit("adapter.writeup.deferred", { reason: "mark-unwritten", need: bytes, room });
1068
- outcome("deferred", "mark-unwritten");
1069
- return "";
1070
- }
1071
- try {
1072
- if (store.getMeta(WRITE_UP_ASK_DATE_KEY) !== today) store.setMeta(WRITE_UP_ASK_DATE_KEY, today);
1073
- store.setMeta(WRITE_UP_ASK_COUNT_KEY, String(spentToday + 1));
1074
- } catch {
1075
- /* a lost count is never a lost hook (§5 G2) */
1076
- }
1077
- outcome("pointed");
1078
- this.emit("adapter.writeup.ask", {
1079
- ended: held.session,
1080
- part: Math.min(done + 1, partsCount),
1081
- of: partsCount,
1082
- bytes,
1083
- owed: owed.length,
1084
- short,
1085
- });
1086
- return text;
1087
- } catch (err) {
1088
- // DURABLE since 2026-09-30: whether a session was ever offered its
1089
- // write-up is a fact a later reading needs, and this ring dies with the hook.
1090
- this.record(WRITE_UP_FAILED_EVENT, input, { code: codeOf(err) });
1091
- return "";
1092
- }
1093
- }
1094
-
1095
683
  // ── the turn ───────────────────────────────────────────────────────────────
1096
684
 
1097
685
  /**
@@ -1132,38 +720,13 @@ export class ClaudeCodeAdapter {
1132
720
  ...(dream.told === null ? [] : [dream.told.notice]),
1133
721
  ...(dream.note === null ? [] : [dream.note.notice]),
1134
722
  ]);
1135
- const result = this.counterpart.recallForTurn(
1136
- {
1137
- sessionId: input.sessionId,
1138
- text,
1139
- ...(budgetBytes === undefined ? {} : { budgetBytes }),
1140
- },
1141
- {
1142
- ...(input.at === undefined ? {} : { at: input.at }),
1143
- // Said outright this turn, so not ALSO handed over as a quiet cue.
1144
- ...(plain.due.length === 0 ? {} : { withhold: new Set(plain.due.map((r) => r.memoryId)) }),
1145
- },
1146
- );
1147
- const decision = result.decision;
1148
- // The recall block states its own sentinel too, and nothing checks it: the
1149
- // line that used to hold it was the same dead `Map` the wake's expectation
1150
- // lived in. A recall-arrival check would need the same shape as the wake's
1151
- // — a persisted expectation and a turn-scoped read — and is an open ask
1152
- // (INTERFACE-GAPS §11), not a thing this row can pretend to.
1153
- this.record(RECALL_DELIVERED_EVENT, input, {
1154
- reason: decision.reason,
1155
- surfaced: decision.surfaced.length,
1156
- footnotes: decision.footnotes.length,
1157
- bytes: decision.bytes,
1158
- budget: decision.budgetBytes,
1159
- observer: decision.observer,
1160
- // WHERE the semantic channel's input came from, on the row a coverage
1161
- // watch can read out of the store tomorrow. `semantic: "none"` on every
1162
- // real turn is exactly the finding this PR closes; anything but
1163
- // "lagged" here after a worker ran is the lag failing, by name.
1164
- semantic: decision.semanticSource,
1165
- semanticFrom: decision.semanticFromTurn,
723
+ // The composed recall and its durable row (`Lifecycle#recallTurn`).
724
+ const result = this.recallTurn(input, text, {
725
+ ...(budgetBytes === undefined ? {} : { budgetBytes }),
726
+ // Said outright this turn, so not ALSO handed over as a quiet cue.
727
+ ...(plain.due.length === 0 ? {} : { withhold: new Set(plain.due.map((r) => r.memoryId)) }),
1166
728
  });
729
+ const decision = result.decision;
1167
730
  return {
1168
731
  ...out,
1169
732
  ok: true,
@@ -1410,63 +973,6 @@ export class ClaudeCodeAdapter {
1410
973
  }
1411
974
  }
1412
975
 
1413
- /** `Now: Fri 25 Sep 2026, 1:40 pm MDT` — this adapter's clock, in the store's zone. */
1414
- private nowLine(): string {
1415
- return `Now: ${localClock(this.nowFn(), this.counterpart.store.zone())}`;
1416
- }
1417
-
1418
- /**
1419
- * PLAIN REMINDERS, in words (owner decision 2026-09-25/26): "Today: pay your
1420
- * taxes". Two renderings of each, from the same record —
1421
- *
1422
- * - `notices`, for the PERSON, bare: the host shows them as the hook's
1423
- * `systemMessage` in the terminal (`bin/hook.ts#hostDelivery`);
1424
- * - `context`, for the MODEL, one line each ending in a newline, saying it
1425
- * was asked for and naming the memory, so it can raise it and look it up.
1426
- *
1427
- * A READ (2026-09-26 review): nothing is claimed here. The delivery claims
1428
- * what its envelope will certainly carry (`claimPlain`, from
1429
- * `bin/hook.ts#deliverTurn`) and strips the rest, so a beat is never spent
1430
- * on a line the person did not get. No date (`input.at` absent) means no
1431
- * calendar, and so nothing; the headless nightly run is told nothing
1432
- * (`HookInput.nightRun`). Never throws.
1433
- */
1434
- private plainFor(input: HookInput): { context: string; notices: string[]; due: PlainReminder[] } {
1435
- const none = { context: "", notices: [], due: [] };
1436
- if (input.at === undefined || input.nightRun === true) return none;
1437
- try {
1438
- const due = this.counterpart.plainDueToday({ at: input.at });
1439
- return {
1440
- context: due.map((r) => `${plainContextLine(r)}\n`).join(""),
1441
- notices: due.map(plainLine),
1442
- due,
1443
- };
1444
- } catch {
1445
- return none;
1446
- }
1447
- }
1448
-
1449
- /**
1450
- * CLAIM plain reminders the delivery is certainly about to show — the latch
1451
- * (`Counterpart.claimPlainReminder`) decides, so of two processes racing for
1452
- * one beat exactly one gets it back. Returns the ones this call claimed, in
1453
- * order; the caller shows only those. Never throws.
1454
- */
1455
- claimPlain(input: HookInput, due: readonly PlainReminder[]): PlainReminder[] {
1456
- if (input.at === undefined || due.length === 0) return [];
1457
- const at = input.at;
1458
- const claimed = due.filter((r) => {
1459
- try {
1460
- return this.counterpart.claimPlainReminder(r, { at });
1461
- } catch {
1462
- return false;
1463
- }
1464
- });
1465
- if (claimed.length > 0) this.emit("adapter.plain.told", { count: claimed.length });
1466
- if (claimed.length < due.length) this.emit("adapter.plain.lost", { count: due.length - claimed.length });
1467
- return claimed;
1468
- }
1469
-
1470
976
  /**
1471
977
  * "COUNTERPARTS WAS UPDATED" — the line this session's terminal gets, once,
1472
978
  * when the MCP server it is talking to runs an older build than the one
@@ -1666,467 +1172,33 @@ export class ClaudeCodeAdapter {
1666
1172
  }
1667
1173
 
1668
1174
  /**
1669
- * A DELIVERY record: to the ring and to box 2, with the calendar date and the
1670
- * session riding in the payload for the same reason `deliveryVerdict` puts
1671
- * them there — the store's `day` column is the lived day, and the parallel
1672
- * run counts these per calendar day, per session, after the process is gone.
1673
- */
1674
- private record(
1675
- name: AdapterDurableEventName,
1676
- input: HookInput,
1677
- data: Record<string, string | number | boolean | null>,
1678
- ): void {
1679
- const row = { ...data, date: input.at ?? null, session: input.sessionId };
1680
- this.emit(name, row);
1681
- this.counterpart.noteAdapterEvent(name, row);
1682
- }
1683
-
1684
- /**
1685
- * Capture and record the boundary. ONE function for all three paths, so a
1175
+ * Capture and record the boundary — `Lifecycle#captureBoundary`, under this
1176
+ * host's event name and boundary kind. ONE function for all three paths, so a
1686
1177
  * fourth session-ending event added later cannot accidentally get a different
1687
1178
  * shape (G3).
1688
1179
  */
1689
1180
  private claim(hook: SessionEndingHook, input: HookInput, out: HookResult): HookResult {
1690
- // THE HEADLESS NIGHTLY RUN CAPTURES NOTHING (2026-09-29): its turns are the
1691
- // launch prompt and the run's own tool calls — sleep, not lived — and a
1692
- // session with no captured text owes no write-up (`remember/owes.ts`).
1693
- const turns = input.nightRun === true ? [] : (input.turns ?? []);
1694
- // THE STRETCH THIS MEMORY WAS TOLD NOT TO HAVE, sealed before anything is
1695
- // captured. After a `sealed` the ordinary capture below reads NOTHING_NEW;
1696
- // after a `failed` it does not run at all, because a cursor that would not
1697
- // move is a boundary with no way to tell what is new from what was lived
1698
- // outside this memory — and an append lands before a cursor write does.
1699
- const seal = this.sealJoinedLate(hook, input, turns);
1700
- // G10/G11 computed side by side: capture takes EVERYTHING conversational
1701
- // including host-injected context; pacing counts only what the user said.
1702
- const captured: CaptureResult =
1703
- seal === "failed"
1704
- ? {
1705
- captured: false,
1706
- reason: "IO_FAILED",
1707
- spans: [],
1708
- deduped: 0,
1709
- excluded: turns.length,
1710
- cursorBefore: 0,
1711
- cursorAfter: 0,
1712
- }
1713
- : this.counterpart.captureSpans({
1714
- session: input.sessionId,
1715
- scope: input.scope,
1716
- turns,
1717
- });
1718
- const record = this.counterpart.boundary({
1719
- session: input.sessionId,
1720
- scope: input.scope,
1721
- kind: BOUNDARY_KIND[hook],
1722
- });
1723
- // Reference resolution (recall §9.2) over the SAME slice capture just took:
1724
- // the cursor is the one authority on what is new, for credit as for spans.
1725
- this.creditAtBoundary(input, captured.cursorBefore, captured.cursorAfter);
1726
- this.record(BOUNDARY_EVENT, input, {
1727
- hook,
1728
- kind: record.kind,
1729
- captured: captured.captured,
1730
- reason: captured.reason,
1731
- spans: captured.spans.length,
1732
- deduped: captured.deduped,
1733
- excluded: captured.excluded,
1734
- cursorBefore: captured.cursorBefore,
1735
- cursorAfter: captured.cursorAfter,
1736
- ask: record.askRaised,
1737
- // The DURABLE half of `adapter.scope.joined-late`: the boundary row is
1738
- // the one durable name a boundary already has, and this is a fact about
1739
- // THIS boundary. A row that says `joinedLate: true, captured: false` is
1740
- // the whole evidence that a stretch was sealed rather than lost.
1741
- joinedLate: seal !== "none",
1742
- });
1743
- return { ...out, ok: true, reason: captured.reason, spansAppended: captured.spans.length };
1181
+ const captured = this.captureBoundary(hook, BOUNDARY_KIND[hook], input);
1182
+ return { ...out, ok: true, reason: captured.reason, spansAppended: captured.spansAppended };
1744
1183
  }
1745
1184
 
1746
1185
  /**
1747
- * THE RETROACTIVE-CAPTURE GUARD (PR #92 review, F1) — the one place a
1748
- * directory that was `off` can still lose its silence.
1186
+ * THE ONE ASK at a Stop: the lifecycle's pacer (`Lifecycle#paceAsk`, one
1187
+ * pacer, fail-open — §13 G3–G5) decides whether this Stop asks and for which
1188
+ * chapter, and this host words it (`stopAsk`).
1749
1189
  *
1750
- * A session that lived under `off` or `paused` wrote NOTHING: no session
1751
- * record, because the hook process returned before a store was opened, and no
1752
- * span cursor for the same reason. Turn the directory back on mid-session —
1753
- * `counterparts scope . --resume`, or the `scope` tool, which is deliberately
1754
- * the one tool that answers in an off directory — and the next boundary sees
1755
- * a cursor of 0 against a transcript holding the WHOLE off conversation. It
1756
- * would deposit all of it. Measured on this branch before this guard: six
1757
- * marker hits in the buffer after the flip.
1758
- *
1759
- * So a boundary that finds NO SESSION RECORD and a cursor still at 0 treats
1760
- * the stretch as somebody else's: it advances the cursor to the end of what
1761
- * it can see, deposits nothing, and records that it did. What follows the
1762
- * flip is captured normally, because the cursor now starts there.
1763
- *
1764
- * **How the cursor moves without a deposit.** `SpanBuffer.capture` advances
1765
- * to `turns.length` when nothing in the slice is capture-eligible
1766
- * (`remember/spans.ts`, the ALL_EXCLUDED arm: "still advance, or the same
1767
- * tool output is re-scanned forever"). So the seal hands it `turns.length`
1768
- * PLACEHOLDERS whose source is `tool` — `enters()` refuses them — and the
1769
- * real turns are never passed to the core at all. That is the only
1770
- * adapter-reachable way to set a cursor today; a `SpanBuffer.sealCursor` in
1771
- * core would be the honest one, and is named in the PR as a core ask.
1772
- *
1773
- * Three conditions, each load-bearing:
1774
- * - **not an observer**: an observer captures nothing and writes no session
1775
- * record anyway, and a cursor it cannot write would make the seal a lie.
1776
- * An `off → observer → on` session is therefore still sealed at the first
1777
- * boundary after it reaches `on` — the observer stretch left no record.
1778
- * - **no session record**: the positive evidence that SessionStart ran
1779
- * inside this memory. It is what a live session has and an off one does not.
1780
- * - **cursor still 0**: a record PRUNED out from under a long-lived session
1781
- * (seven days, `sessions.ts`) leaves a cursor behind; that session has
1782
- * been captured all along and must not lose the turns since its last
1783
- * boundary.
1190
+ * **The re-fired Stop asks nothing and advances nothing.** The host's re-fire
1191
+ * of a blocked Stop is refused HERE, before the pacer is consulted: no pacing
1192
+ * advance, no ask slot, no row — the previous pass already left one.
1784
1193
  */
1785
- private sealJoinedLate(
1786
- hook: SessionEndingHook,
1787
- input: HookInput,
1788
- turns: readonly HostTurn[],
1789
- ): "none" | "sealed" | "failed" {
1790
- if (this.observer) return "none";
1791
- if (input.sessionId.length === 0) return "none";
1792
- try {
1793
- if (readSession(this.counterpart.store.dir, input.sessionId) !== null) return "none";
1794
- if (this.counterpart.spans.cursor(input.scope, input.sessionId) !== 0) return "none";
1795
- } catch {
1796
- // A registry or a cursor this cannot read is not a reason to fail a hook
1797
- // (§5 G2). The quiet answer here is the ordinary path.
1798
- return "none";
1799
- }
1800
- const placeholders: CapturedTurn[] = turns.map(() => ({
1801
- role: "user",
1802
- text: "",
1803
- source: "tool",
1804
- }));
1805
- const sealed = this.counterpart.captureSpans({
1806
- session: input.sessionId,
1807
- scope: input.scope,
1808
- turns: placeholders,
1809
- });
1810
- const moved = sealed.cursorAfter === turns.length;
1811
- this.emit(SCOPE_JOINED_LATE_EVENT, {
1812
- hook,
1813
- mode: this.scope.mode,
1814
- turns: turns.length,
1815
- cursor: sealed.cursorAfter,
1816
- sealed: moved,
1817
- reason: sealed.reason,
1818
- });
1819
- // THE ORDER IS THE SAFETY. The cursor moves first and the session record is
1820
- // written only if it did: a record written beside a cursor that stayed at 0
1821
- // would make the NEXT boundary read this session as an ordinary one and
1822
- // deposit the whole off stretch after all. A seal that could not move the
1823
- // cursor leaves no record either, so the next boundary tries again.
1824
- if (!moved) return "failed";
1825
- // The session becomes bindable HERE, at the first boundary inside the
1826
- // memory — `pre-compact` never calls `noteSession`, and a session with no
1827
- // record is a session the MCP tools refuse.
1828
- this.noteSession("boundary", input);
1829
- return "sealed";
1830
- }
1831
-
1832
- /**
1833
- * THE ONE ASK, ON ONE PACER, fail-open: an error in the ritual never costs the
1834
- * collection (§13 G5).
1835
- *
1836
- * What changed on 2026-09-04, and why:
1837
- *
1838
- * - **One pacer.** The authorship ask paced itself on turns-and-bytes since
1839
- * its own last ask; the episode ask paced itself on the chapter rule. They
1840
- * fired on different Stops, so the model was asked about a dozen times in
1841
- * one 13-turn evening. `episodeAsk` is now the only pacer, and its verdict
1842
- * decides whether this Stop says anything at all.
1843
- * - **The coverage read stays, as a RECORD and not a gate.** It measures
1844
- * rather than assumes (§2 G12) and it puts the unaskable tail on the
1845
- * record as a number instead of a hope; what it must not do is add a
1846
- * second condition to a single ask.
1847
- * - **The re-fired Stop asks nothing and advances nothing.**
1848
- */
1849
- /**
1850
- * THE CREDIT SEAM — the consumer recall INTERFACE-GAPS §5 said had no home.
1851
- *
1852
- * Assistant `conversation` turns and deliberate-recall calls from the new
1853
- * slice go to `Counterpart.creditReferences`, which decides (`reference.ts`)
1854
- * and credits (`resolveUses`). One durable row per boundary, `recall.credit`,
1855
- * with a `reason` the daily's readers split on: `credited` is the signal the
1856
- * `memory.reinforced` watch turns green on; `failed` and `budget-exceeded`
1857
- * are the ones to alarm on. A boundary that credits nothing still leaves its
1858
- * row (`nothing-to-credit` / `no-candidates`) — silence must never masquerade
1859
- * as health, and a seam that only wrote rows when it worked would be the ring
1860
- * this repo already learned from (I32).
1861
- *
1862
- * Never fails the boundary: telemetry may not fail the host (§1 G7), and a
1863
- * credit that could not be decided is a `failed` row, not a lost capture.
1864
- */
1865
- private creditAtBoundary(input: HookInput, from: number, to: number): void {
1866
- const started = this.nowFn();
1867
- // Read before the try: the failed row carries the day too.
1868
- const day = this.counterpart.store.livedDay();
1869
- const turns = input.turns ?? [];
1870
- const slice = turns.slice(Math.max(0, from), Math.max(from, to));
1871
- const assistantTurns = slice
1872
- .filter((t) => t.role === "assistant" && (t.source === undefined || t.source === "conversation"))
1873
- .map((t) => t.text);
1874
- // Half-open on the left: a call positioned AT `from` sat before the first
1875
- // new turn and belonged to the previous slice, which already judged it.
1876
- const raw = (input.expansions ?? [])
1877
- .filter((e) => e.atTurn > from && e.atTurn <= to)
1878
- .flatMap((e) => [...e.ids]);
1879
- // G50: a handle the recall tool RESOLVED becomes the id it resolved to.
1880
- // The transcript still decides WHICH handles and WHEN; what it cannot say is
1881
- // whose answer resolved them, so the translation is filtered to THIS
1882
- // PROJECT's resolutions — the same `sameScope` comparison the MCP server
1883
- // already trusts to bind a session. Without it the log hands this boundary
1884
- // the last answer anyone anywhere got, including the owner's resolution of a
1885
- // confidential memory this session was refused (or never asked for at all).
1886
- // A handle nobody resolved in this scope still counts `unresolvedHandles`.
1887
- //
1888
- // The SECOND filter is this session's own start, out of the same registry
1889
- // (`sessions.ts`): a project is a place, not a conversation, so one
1890
- // directory's table also holds last week's answers, and a resolution
1891
- // recorded before this session existed cannot be an answer to anything this
1892
- // session asked. A session whose first hook event is this very Stop has no
1893
- // record yet — `claim()` runs before `noteSession("boundary")` — and gets no
1894
- // floor; that is under-credit's direction only in the sense that it does not
1895
- // tighten, and it is the residual §9 records.
1896
- //
1897
- // The file is read only when there is something to translate — and the row
1898
- // says which of those two it was. `resolvedHandles: 0` alone cannot tell an
1899
- // idle table from a dead one, which is the exact shape of I32's failure.
1900
- //
1901
- // ALL OF IT INSIDE THE TRY. The first draft translated before the try, which
1902
- // meant any throw on this path cost the boundary its row entirely — and a
1903
- // seam that only writes rows when it works is the ring I32 is named for.
1904
- // Only the `expansionsRead` declaration, which cannot throw, sits outside,
1905
- // so the `failed` row can still say how far the read had got.
1906
- let expansionsRead: ExpansionsRead | "not-read" = "not-read";
1907
- try {
1908
- let resolutions = new Map<string, string | null>();
1909
- // Carried off the read rather than fetched again: the key a handle lands
1910
- // on is the store's salt plus the handle (G58), and the two halves of one
1911
- // lookup must not be able to disagree about which salt that was.
1912
- let salt = "";
1913
- if (raw.length > 0) {
1914
- const dataDir = this.counterpart.store.dir;
1915
- const sessionStartedAt = readSession(dataDir, input.sessionId)?.startedAt;
1916
- const read = readHandleResolutions(dataDir, {
1917
- now: this.nowFn(),
1918
- scope: input.scope,
1919
- ...(sessionStartedAt === undefined ? {} : { since: sessionStartedAt }),
1920
- });
1921
- resolutions = read.map;
1922
- salt = read.salt;
1923
- expansionsRead = read.reason;
1924
- }
1925
- const resolvedHandles = countTranslated(raw, resolutions, salt);
1926
- const expansions = translateExpansions(raw, resolutions, salt);
1927
- const summary = this.counterpart.creditReferences(input.sessionId, {
1928
- assistantTurns,
1929
- expansions,
1930
- deadline: started + TUNABLES.CREDIT_BUDGET_MS,
1931
- now: this.nowFn,
1932
- });
1933
- this.emit(RECALL_CREDIT_EVENT, {
1934
- reason: summary.reason,
1935
- considered: summary.considered,
1936
- expanded: summary.expanded,
1937
- quoted: summary.quoted,
1938
- credited: summary.credited,
1939
- elapsedMs: this.nowFn() - started,
1940
- });
1941
- this.counterpart.noteAdapterEvent(RECALL_CREDIT_EVENT, {
1942
- reason: summary.reason,
1943
- session: input.sessionId,
1944
- date: input.at ?? null,
1945
- day: summary.day,
1946
- turns: assistantTurns.length,
1947
- considered: summary.considered,
1948
- expanded: summary.expanded,
1949
- quoted: summary.quoted,
1950
- credited: summary.credited,
1951
- /** Uses refused strength credit for their day cadence that still joined
1952
- * the turn's links (2026-09-28). */
1953
- linkedDespite: summary.linkedDespite,
1954
- unresolvedHandles: summary.unresolvedHandles,
1955
- /** G50: expansions the handle-resolution log translated on the way in.
1956
- * Beside `unresolvedHandles`, it is the pair that says whether a
1957
- * by-title expansion earned credit or fell through the old gap. */
1958
- resolvedHandles,
1959
- /** WHY the log answered the way it did. `resolvedHandles: 0` on its own
1960
- * cannot tell an idle table from an absent, unreadable or corrupt one,
1961
- * and a number that cannot say which is how I32 stayed invisible.
1962
- * `not-read` means this slice carried no expansion to translate. */
1963
- expansionsRead,
1964
- skippedForBudget: summary.skippedForBudget,
1965
- unreadable: summary.unreadable,
1966
- refused: summary.refused,
1967
- ids: summary.ids.slice(0, 64),
1968
- idsTotal: summary.ids.length,
1969
- expandedIds: summary.expandedIds.slice(0, 64),
1970
- expandedTotal: summary.expandedIds.length,
1971
- /** Of the expanded, how many this session had seen as a QUIET POINTER
1972
- * (reached only through links, 2026-09-28) — whether pointers are used. */
1973
- pointersExpanded: summary.pointersExpanded,
1974
- elapsedMs: this.nowFn() - started,
1975
- });
1976
- } catch (err) {
1977
- const code = codeOf(err);
1978
- this.emit(RECALL_CREDIT_EVENT, { reason: "failed", code });
1979
- this.counterpart.noteAdapterEvent(RECALL_CREDIT_EVENT, {
1980
- reason: "failed",
1981
- session: input.sessionId,
1982
- date: input.at ?? null,
1983
- day,
1984
- code,
1985
- turns: assistantTurns.length,
1986
- // The RAW count: the translated list may not exist on this path, and a
1987
- // translation is one-for-one anyway.
1988
- expansions: raw.length,
1989
- expansionsRead,
1990
- });
1991
- }
1992
- }
1993
-
1994
1194
  private askAtStop(input: HookInput): string | null {
1995
- try {
1996
- // The host's re-fire of a blocked Stop. Nothing is evaluated: no pacing
1997
- // advance, no ask slot, no row — the previous pass already left one.
1998
- if (input.reFired === true) return null;
1999
- // Typed turns and both roles' text (`substanceOf`). The pacing and the
2000
- // per-session, per-calendar-day cap are `self/episodes.ts#askDue`'s; the
2001
- // history of both is in self NOTES. The date on every `adapter.ask` row
2002
- // below answers "how often was the pen offered today" across sessions.
2003
- const substance = substanceOf(input.turns ?? []);
2004
- // `scope`: what this session has not written up here is the pacer's
2005
- // third arm (`core/coverage/`, 2026-09-30), `due-unwritten` on the row.
2006
- const chapter = this.counterpart.episodeAsk(input.sessionId, substance, undefined, {
2007
- rebase: input.turnsUnread !== true,
2008
- scope: input.scope,
2009
- });
2010
- const outcome = chapter.asked
2011
- ? "asked"
2012
- : chapter.verdict.reason === "session-ask-cap"
2013
- ? "capped"
2014
- : "paced";
2015
- let coverage: { spans: number; covered: number; uncovered: number; unaskableSpans: number; unaskableBytes: number } | null =
2016
- null;
2017
- try {
2018
- coverage = this.counterpart.spans.coverageReport(input.scope);
2019
- } catch (err) {
2020
- this.emit("adapter.coverage.failed", { code: codeOf(err) });
2021
- }
2022
- this.record(ADAPTER_ASK_EVENT, input, {
2023
- asked: chapter.asked,
2024
- outcome,
2025
- reason: chapter.verdict.reason,
2026
- chapter: chapter.chapter,
2027
- turns: substance.turns,
2028
- bytes: substance.bytes,
2029
- // What `turns` counts, so a reader can tell these rows from older ones.
2030
- counting: ASK_ROW_COUNTING,
2031
- sinceTurns: chapter.verdict.sinceTurns,
2032
- sinceBytes: chapter.verdict.sinceBytes,
2033
- spans: coverage?.spans ?? null,
2034
- covered: coverage?.covered ?? null,
2035
- uncovered: coverage?.uncovered ?? null,
2036
- unaskableSpans: coverage?.unaskableSpans ?? null,
2037
- unaskableBytes: coverage?.unaskableBytes ?? null,
2038
- unwritten: chapter.verdict.unwritten?.pieces ?? null,
2039
- unwrittenMinutes: chapter.verdict.unwritten?.minutes ?? null,
2040
- });
2041
- // The ask NAMES this session and its chapter: the id is what the MCP
2042
- // server binds itself with, so an ask that omitted it would be an
2043
- // invitation the model has no way to accept on this host — and the
2044
- // chapter number is the STORE's, one past what was written.
2045
- return chapter.asked ? stopAsk(input.sessionId, chapter.chapter) : null;
2046
- } catch (err) {
2047
- this.emit("adapter.ask.failed", { code: codeOf(err) });
2048
- return null;
2049
- }
2050
- }
2051
-
2052
- /**
2053
- * THE LIVE-SESSION REGISTRY (`adapters/sessions.ts`), written here because the
2054
- * hooks are the only thing on this host that knows the session id.
2055
- *
2056
- * Host state, not memory: an id, a scope, three timestamps, no content. It is
2057
- * what lets the MCP server — which this host launches from a static config
2058
- * that carries no session — bind itself to the session the ask named, and
2059
- * refuse anything else. Ring-only telemetry: this fires at every Stop, and a
2060
- * durable row per turn to say "the file was written" is not evidence anyone
2061
- * needs.
2062
- *
2063
- * Under observer NOTHING is recorded (the tools stand down anyway), and every
2064
- * failure is silent by construction: `recordSession` returns null rather than
2065
- * throwing, because a hook may not fail the host (§5 G2).
2066
- */
2067
- private noteSession(phase: SessionPhase, input: HookInput): void {
2068
- if (this.observer) return;
2069
- if (input.sessionId.length === 0) return;
2070
- // The STORE's dir, not the config's: it is the one that went through
2071
- // `assertSafeDataDir`, and it is the same value the MCP server resolves on
2072
- // its own side. Reading the raw config here could put the registry in a
2073
- // sibling directory the tool never looks in, over a trailing slash.
2074
- const dir = this.counterpart.store.dir;
2075
- const record = recordSession(dir, {
2076
- sessionId: input.sessionId,
2077
- scope: input.scope,
2078
- phase,
2079
- at: this.nowFn(),
2080
- // THE DURABLE ANSWER TO "WHICH CONFIG DID THIS HOOK READ". A hook cannot
2081
- // print it — stdout is the model's context — so it is recorded here, in
2082
- // the one file this process writes that is host state rather than memory,
2083
- // under the store the configuration itself named. A record written by a
2084
- // process that was told nothing carries no field at all.
2085
- ...(this.configPath === undefined || this.configPath.length === 0
2086
- ? {}
2087
- : { config: this.configPath }),
2088
- // Which model answered last. A Stop writes this before its ask goes out,
2089
- // so the chapter that answers the ask finds it on the record.
2090
- ...(input.model === undefined ? {} : { model: input.model }),
2091
- ...(input.entrypoint === undefined ? {} : { entrypoint: input.entrypoint }),
2092
- });
2093
- this.emit("adapter.session.registry", { phase, ok: record !== null });
2094
- // Bounded growth, once per session rather than once per turn — and never on
2095
- // the SessionEnd path, whose hooks share 1.5 s between them.
2096
- if (phase === "start") {
2097
- const pruned = pruneSessions(dir, this.nowFn());
2098
- if (pruned > 0) this.emit("adapter.session.registry.pruned", { removed: pruned });
2099
- // The process log's week (`adapters/log/`), by the dates in its file names.
2100
- const logs = pruneLog(dir, localDate(this.nowFn(), this.counterpart.store.zone()));
2101
- if (logs > 0) this.emit("adapter.log.pruned", { removed: logs });
2102
- }
2103
- }
2104
-
2105
- /**
2106
- * WRITE DOWN WHAT THE HOST WAS JUST HANDED, so a later process can ask whether
2107
- * it arrived. A second write of the same phase, for the same reason
2108
- * `deliverScopeAsk` makes one: the first write happens before the delivery
2109
- * verdict and the bundle is composed after it.
2110
- *
2111
- * A wake with NO sentinel — the bootstrap line a store with nothing in it
2112
- * publishes — writes nothing, and the absence is the answer: there was no
2113
- * checkable bundle, so nothing was supposed to arrive.
2114
- */
2115
- private noteWakeExpectation(input: HookInput, sentinel: string | null): void {
2116
- if (this.observer) return;
2117
- if (input.sessionId.length === 0) return;
2118
- if (sentinel === null || sentinel.length === 0) return;
2119
- const marked = recordSession(this.counterpart.store.dir, {
2120
- sessionId: input.sessionId,
2121
- scope: input.scope,
2122
- phase: "start",
2123
- at: this.nowFn(),
2124
- wakeSentinel: sentinel,
2125
- ...(this.configPath === undefined || this.configPath.length === 0
2126
- ? {}
2127
- : { config: this.configPath }),
2128
- });
2129
- this.emit("adapter.wake.expected", { recorded: marked !== null });
1195
+ if (input.reFired === true) return null;
1196
+ const chapter = this.paceAsk(input);
1197
+ // The ask NAMES this session and its chapter: the id is what the MCP
1198
+ // server binds itself with, so an ask that omitted it would be an
1199
+ // invitation the model has no way to accept on this host — and the
1200
+ // chapter number is the STORE's, one past what was written.
1201
+ return chapter === null ? null : stopAsk(input.sessionId, chapter);
2130
1202
  }
2131
1203
 
2132
1204
  /**
@@ -2242,227 +1314,13 @@ export class ClaudeCodeAdapter {
2242
1314
  phase: "boundary",
2243
1315
  at: prior.lastBoundaryAt,
2244
1316
  wakeChecked: true,
2245
- ...(this.configPath === undefined || this.configPath.length === 0
2246
- ? {}
2247
- : { config: this.configPath }),
1317
+ ...this.recordStamp(),
2248
1318
  });
2249
1319
  } catch {
2250
1320
  /* the check runs again next turn; a hook may not fail the host (§5 G2) */
2251
1321
  }
2252
1322
  }
2253
1323
 
2254
- /** The orphanable tail: bounded and measured, never pretended away (§13). */
2255
- private noteTail(input: HookInput): void {
2256
- try {
2257
- // The same session state the ask above reads, for the same reason: a tail
2258
- // line that disagreed with the ask about why is how this bug gets found
2259
- // twice.
2260
- this.counterpart.noteOrphanTail(input.sessionId, substanceOf(input.turns ?? []), undefined, {
2261
- rebase: input.turnsUnread !== true,
2262
- });
2263
- } catch (err) {
2264
- this.emit("adapter.tail.failed", { code: codeOf(err) });
2265
- }
2266
- }
2267
-
2268
- /**
2269
- * The detached worker. The plan is checked BEFORE anything starts — watchdog
2270
- * against the staleness window, data dir, stance — and a refusal that repeats
2271
- * ESCALATES rather than re-logging (scar E4's widening).
2272
- *
2273
- * **The credential was never a precondition after I32** (2026-09-11), and
2274
- * since 2026-09-24 there is no credential at all; see `spawn.ts`'s §2.18
2275
- * paragraph for why refusing was worse than running.
2276
- *
2277
- * **Every refusal and every failure now leaves a DURABLE row**, one per reason
2278
- * per calendar date, and the per-reason counter that decides escalation lives
2279
- * in box 2's meta rather than in this object. Both halves are the same repair:
2280
- * a hook process lives for one turn, so anything it knows about a repeated
2281
- * failure dies before the next hook could act on it.
2282
- */
2283
- private spawnWorker(input?: HookInput): SpawnOutcome {
2284
- // The child is TOLD whose turn it just followed. Without it the worker can
2285
- // sweep and sleep but cannot leave the next turn a semantic cue, because
2286
- // that cue is per-session state (`recall/session.ts`).
2287
- const bound = {
2288
- ...(input?.sessionId === undefined || input.sessionId.length === 0
2289
- ? {}
2290
- : { session: input.sessionId }),
2291
- ...(input?.scope === undefined || input.scope.length === 0 ? {} : { scope: input.scope }),
2292
- // The child reads the SAME configuration this process read. Without the
2293
- // pin the worker would resolve its own — and a hook driven by `--config`
2294
- // would spawn a worker that went back to the default file, which is the
2295
- // shape scar §2.13 is about: parent and child resolving one value twice.
2296
- ...(this.configPath === undefined || this.configPath.length === 0
2297
- ? {}
2298
- : { configPath: this.configPath }),
2299
- };
2300
- const plan = planSpawn({
2301
- config: this.config,
2302
- command: this.command,
2303
- args: this.args,
2304
- priorFailures: 0,
2305
- ...bound,
2306
- });
2307
- // The PERSISTED count, read before the replan: `escalate` is a claim about
2308
- // how often this has happened on this host, not about this process.
2309
- const prior = plan.ok ? 0 : this.refusalCount(plan.reason);
2310
- const replanned = plan.ok
2311
- ? plan
2312
- : planSpawn({
2313
- config: this.config,
2314
- command: this.command,
2315
- args: this.args,
2316
- priorFailures: prior,
2317
- ...bound,
2318
- });
2319
- const outcome = spawnDetached(replanned, {
2320
- ...(this.spawner === undefined ? {} : { spawner: this.spawner }),
2321
- onEvent: (name, data) => this.emit(name, data),
2322
- });
2323
- if (outcome.started) {
2324
- // A start clears the slate for every reason: whatever was wrong is not
2325
- // wrong now, and a counter that only ever climbed would escalate forever
2326
- // off one bad afternoon.
2327
- this.clearRefusals();
2328
- this.noteSpawnStart(input);
2329
- return outcome;
2330
- }
2331
- const count = this.bumpRefusal(String(outcome.reason));
2332
- this.noteSpawnRefusal(outcome, count, input);
2333
- return outcome;
2334
- }
2335
-
2336
- /**
2337
- * THE DURABLE ROW for a worker that DID start (2026-09-20, E2).
2338
- *
2339
- * I32 made every refusal durable and left the other half open: a healthy
2340
- * start wrote nothing, so a worker dead all week and a week with nothing to
2341
- * do read exactly alike, and the fired view could only call the mechanism
2342
- * blind (inventory §2 row 23). Scar §2.4 is symmetrical — a door that opened
2343
- * and a door nobody opened must not be the same absence either.
2344
- *
2345
- * ONE ROW PER CALENDAR DATE, latched at the store exactly like the refusals
2346
- * beside it. This runs at every boundary, which is a hot path, and three
2347
- * hundred identical rows a day would drown the log the view reads.
2348
- *
2349
- * **THE ROW CARRIES NO COUNT, on purpose.** The latch means only the FIRST
2350
- * start of a day ever writes, so any tally put here would read `1` forever —
2351
- * a number that looks like a measurement and is an artefact of the latch. The
2352
- * day's real tally lives in box 2's meta beside the refusal counters, where
2353
- * `spawnStarts()` reads it and doctor's Spawn line prints it.
2354
- *
2355
- * Never throws, writes nothing under observer, and is not on the critical
2356
- * path: the worker has already been started by the time this runs.
2357
- */
2358
- private noteSpawnStart(input?: HookInput): void {
2359
- if (this.observer) return;
2360
- const date = input?.at ?? localDate(this.nowFn(), this.counterpart.store.zone());
2361
- try {
2362
- this.bumpStart(date);
2363
- this.counterpart.noteAdapterEvent(
2364
- SPAWN_STARTED_EVENT,
2365
- { date, session: input?.sessionId ?? null },
2366
- { dedupKey: `${SPAWN_STARTED_EVENT}:${date}` },
2367
- );
2368
- } catch (err) {
2369
- this.emit("adapter.spawn.record.failed", { code: codeOf(err) });
2370
- }
2371
- }
2372
-
2373
- /** How many times the worker has started TODAY, and the date that tally is
2374
- * for. The row says it happened; this says how often. A read, never a write. */
2375
- spawnStarts(): { date: string | null; count: number } {
2376
- try {
2377
- const store = this.counterpart.store;
2378
- const date = store.getMeta(SPAWN_START_DATE_KEY) ?? null;
2379
- return { date, count: Number(store.getMeta(SPAWN_START_COUNT_KEY) ?? "0") };
2380
- } catch {
2381
- return { date: null, count: 0 };
2382
- }
2383
- }
2384
-
2385
- /**
2386
- * The day's start tally, beside the refusal counters in box 2's meta. TWO
2387
- * KEYS, not one per date: a key per day would grow without a sweep to mow it,
2388
- * and the only question this answers is "how many today". The tally resets
2389
- * the moment the date it was stamped with is no longer today.
2390
- */
2391
- private bumpStart(date: string): number {
2392
- try {
2393
- const store = this.counterpart.store;
2394
- const on = store.getMeta(SPAWN_START_DATE_KEY);
2395
- const next = on === date ? Number(store.getMeta(SPAWN_START_COUNT_KEY) ?? "0") + 1 : 1;
2396
- if (on !== date) store.setMeta(SPAWN_START_DATE_KEY, date);
2397
- store.setMeta(SPAWN_START_COUNT_KEY, String(next));
2398
- return next;
2399
- } catch {
2400
- // A lost count is never a lost hook (§5 G2). The row still lands, and it
2401
- // still says the worker started today, which is what it is for.
2402
- return 1;
2403
- }
2404
- }
2405
-
2406
- /**
2407
- * THE DURABLE ROW for a worker that did not start (I32).
2408
- *
2409
- * One row per reason per CALENDAR DATE — `dedupKey` does the gating at the
2410
- * store, so a refusal repeating at every boundary writes once and not three
2411
- * hundred times. `count` is the persisted counter AT THIS MOMENT, so the day's
2412
- * one row still says how deep the hole was by the time it was written; the
2413
- * live depth is `spawnRefusals()`.
2414
- *
2415
- * Never throws: this is the tail of a hook, and a hook may not fail the host
2416
- * (§5 G2). An observer writes nothing — `noteAdapterEvent` stands down at the
2417
- * core's own seam, and the counter above stayed in memory for the same reason.
2418
- */
2419
- private noteSpawnRefusal(outcome: SpawnOutcome, count: number, input?: HookInput): void {
2420
- if (this.observer) return;
2421
- const name = outcome.reason === "SPAWN_FAILED" ? SPAWN_FAILED_EVENT : SPAWN_REFUSED_EVENT;
2422
- const date = input?.at ?? null;
2423
- try {
2424
- this.counterpart.noteAdapterEvent(
2425
- name,
2426
- {
2427
- reason: String(outcome.reason),
2428
- code: outcome.code,
2429
- count,
2430
- escalate: outcome.escalate,
2431
- date,
2432
- session: input?.sessionId ?? null,
2433
- },
2434
- // No date is still one row per reason per RUN OF DAYS rather than per
2435
- // boundary: a caller that knows no date is a test or a bare invocation,
2436
- // and neither should be able to flood the log.
2437
- { dedupKey: `${name}:${String(outcome.reason)}:${date ?? "no-date"}` },
2438
- );
2439
- } catch (err) {
2440
- this.emit("adapter.spawn.record.failed", { code: codeOf(err) });
2441
- }
2442
- }
2443
-
2444
- /**
2445
- * The per-reason refusal counters, as they stand. PR 2's session-start notice
2446
- * reads this — "your background worker has not started in four days" is a
2447
- * sentence somebody has to be able to say — and it is a read, never a write.
2448
- */
2449
- spawnRefusals(): Record<string, number> {
2450
- const out: Record<string, number> = {};
2451
- if (this.observer) {
2452
- for (const [reason, n] of this.volatileRefusals) out[reason] = n;
2453
- return out;
2454
- }
2455
- try {
2456
- for (const [key, value] of this.counterpart.store.metaWithPrefix(SPAWN_REFUSAL_PREFIX)) {
2457
- const n = Number(value);
2458
- if (n > 0) out[key.slice(SPAWN_REFUSAL_PREFIX.length)] = n;
2459
- }
2460
- } catch (err) {
2461
- this.emit("adapter.spawn.refusals.failed", { code: codeOf(err) });
2462
- }
2463
- return out;
2464
- }
2465
-
2466
1324
  /**
2467
1325
  * THE ONE OR TWO LINES THE OWNER SEES AT SESSION START, or null.
2468
1326
  *
@@ -2594,46 +1452,6 @@ export class ClaudeCodeAdapter {
2594
1452
  this.emit("adapter.envelope.gave-way", { hook: "delivery", part, count });
2595
1453
  }
2596
1454
 
2597
- private refusalCount(reason: string): number {
2598
- if (this.observer) return this.volatileRefusals.get(reason) ?? 0;
2599
- try {
2600
- return Number(this.counterpart.store.getMeta(`${SPAWN_REFUSAL_PREFIX}${reason}`) ?? "0");
2601
- } catch {
2602
- return 0;
2603
- }
2604
- }
2605
-
2606
- /** Returns the count AFTER this refusal. A meta write that loses the lock to
2607
- * an overlapping runner costs the count, never the hook (§5 G2). */
2608
- private bumpRefusal(reason: string): number {
2609
- const next = this.refusalCount(reason) + 1;
2610
- if (this.observer) {
2611
- this.volatileRefusals.set(reason, next);
2612
- return next;
2613
- }
2614
- try {
2615
- this.counterpart.store.setMeta(`${SPAWN_REFUSAL_PREFIX}${reason}`, String(next));
2616
- } catch (err) {
2617
- this.emit("adapter.spawn.count.failed", { code: codeOf(err) });
2618
- }
2619
- return next;
2620
- }
2621
-
2622
- private clearRefusals(): void {
2623
- this.volatileRefusals.clear();
2624
- if (this.observer) return;
2625
- try {
2626
- const store = this.counterpart.store;
2627
- for (const [key, value] of store.metaWithPrefix(SPAWN_REFUSAL_PREFIX)) {
2628
- // Zero, not deleted: `meta` has no delete on the write seam's allowlist,
2629
- // and a zero reads identically everywhere the counter is consulted.
2630
- if (value !== "0") store.setMeta(key, "0");
2631
- }
2632
- } catch (err) {
2633
- this.emit("adapter.spawn.count.failed", { code: codeOf(err) });
2634
- }
2635
- }
2636
-
2637
1455
  /**
2638
1456
  * The one wrapper. Stance first (an instrument stands down and SAYS SO), then
2639
1457
  * the anti-loop guard, then the work — and nothing that happens inside reaches
@@ -2694,49 +1512,6 @@ export class ClaudeCodeAdapter {
2694
1512
  this.inFlight.delete(key);
2695
1513
  }
2696
1514
  }
2697
-
2698
- private emit(name: string, data: Record<string, string | number | boolean | null>): void {
2699
- const event: AdapterEvent = { at: this.nowFn(), name, data };
2700
- this.ring.push(event);
2701
- if (this.ring.length > EVENT_RING) this.ring.shift();
2702
- try {
2703
- this.onEvent?.(event);
2704
- } catch {
2705
- // Even telemetry may not fail the host (§1 G7: "failed telemetry means
2706
- // the bootstrap line or nothing, and a clean exit").
2707
- }
2708
- }
2709
- }
2710
-
2711
- /**
2712
- * Substance for PACING.
2713
- *
2714
- * - **turns** — messages the PERSON typed: user-role `conversation` turns,
2715
- * one per transcript entry however many text blocks it holds. The
2716
- * assistant's text never counts as a turn, so its own writing cannot pace
2717
- * the ask turn by turn (measured 2026-09-24: 8 assistant blocks against the
2718
- * owner's 2 messages fired the first ask after his second message).
2719
- * - **bytes** — conversation text from BOTH roles, which is how a one-prompt
2720
- * agentic session still reaches an ask.
2721
- *
2722
- * Host-injected material is user-role but is not the user speaking, so it
2723
- * counts toward neither (§2 G11); tool output, file contents and images are the
2724
- * declared blind spot (§2 G10). The same turn list feeds `captureSpans`, where
2725
- * injected context IS kept — the two rules live one function apart on purpose.
2726
- */
2727
- export function substanceOf(turns: readonly HostTurn[]): { turns: number; bytes: number } {
2728
- let count = 0;
2729
- let bytes = 0;
2730
- let lastEntry: number | undefined;
2731
- for (const turn of turns) {
2732
- if ((turn.source ?? "conversation") !== "conversation") continue;
2733
- bytes += Buffer.byteLength(turn.text, "utf8");
2734
- if (turn.role !== "user") continue;
2735
- if (turn.entry !== undefined && turn.entry === lastEntry) continue;
2736
- lastEntry = turn.entry;
2737
- count += 1;
2738
- }
2739
- return { turns: count, bytes };
2740
1515
  }
2741
1516
 
2742
1517
  /** The six answers the delivery check can give, in plain words. */
@@ -2781,35 +1556,6 @@ export function wakeOutcome(expected: string | null, arrival: WakeArrival): Wake
2781
1556
  return "truncated";
2782
1557
  }
2783
1558
 
2784
- /**
2785
- * ONE PLAIN REMINDER, AS A PERSON READS IT (2026-09-26). The owner's example is
2786
- * the whole spec — "Today: pay your taxes" — so each beat is the shortest
2787
- * sentence that says when:
2788
- *
2789
- * day `Today: pay your taxes`
2790
- * opens `This month: launch the beta` / `Until Sat 31 Oct 2026: book flights`
2791
- * last-day `Last day today: file the extension`
2792
- *
2793
- * `what` is the memory's title or first line (`Counterpart.plainReminders`).
2794
- */
2795
- export function plainLine(r: Pick<PlainReminder, "beat" | "precision" | "lastDay" | "what">): string {
2796
- const max = TUNABLES.PLAIN_WHAT_MAX_CHARS;
2797
- const what = r.what.length <= max ? r.what : `${r.what.slice(0, max - 1).trimEnd()}…`;
2798
- if (r.beat === "day") return `Today: ${what}`;
2799
- if (r.beat === "last-day") return `Last day today: ${what}`;
2800
- if (r.precision === "month") return `This month: ${what}`;
2801
- return `Until ${readableDate(r.lastDay)}: ${what}`;
2802
- }
2803
-
2804
- /**
2805
- * The MODEL's copy of one plain reminder: says it was asked for, and names the
2806
- * memory so it can be looked up. One line, no newline — `what` is folded to
2807
- * single spaces upstream — so `withoutPlain` can take it back out by line.
2808
- */
2809
- export function plainContextLine(r: Pick<PlainReminder, "beat" | "precision" | "lastDay" | "what" | "memoryId">): string {
2810
- return `Plain reminder (they asked to be told) — ${plainLine(r)} [${r.memoryId}]`;
2811
- }
2812
-
2813
1559
  /**
2814
1560
  * A hook result WITHOUT the given plain reminders — their terminal lines, their
2815
1561
  * records and their context lines — for a delivery that could not carry them or
@@ -2866,13 +1612,3 @@ export function withoutDream<R extends { injection: string | null; dream?: Dream
2866
1612
  delete (rest as { dream?: unknown }).dream;
2867
1613
  return rest;
2868
1614
  }
2869
-
2870
- function codeOf(err: unknown): string {
2871
- if (err !== null && typeof err === "object") {
2872
- const code = (err as { code?: unknown }).code;
2873
- if (typeof code === "string") return code;
2874
- const name = (err as { name?: unknown }).name;
2875
- if (typeof name === "string") return name;
2876
- }
2877
- return "UNKNOWN";
2878
- }