counterparts 0.3.32 → 0.3.34

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 (65) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/package.json +1 -1
  3. package/src/adapters/claude-code/CONTRACT.md +7 -1
  4. package/src/adapters/claude-code/INTERFACE-GAPS.md +20 -0
  5. package/src/adapters/claude-code/NOTES.md +61 -0
  6. package/src/adapters/claude-code/bin/hook.ts +5 -399
  7. package/src/adapters/claude-code/doctor-self-page.ts +56 -12
  8. package/src/adapters/claude-code/doctor-upgrades.ts +34 -3
  9. package/src/adapters/claude-code/envelope.ts +407 -2
  10. package/src/adapters/claude-code/index.ts +15 -0
  11. package/src/adapters/claude-code/night-run.ts +353 -16
  12. package/src/adapters/claude-code/transcript.ts +34 -0
  13. package/src/adapters/cli/commands-note.ts +9 -0
  14. package/src/adapters/cli/commands-readings.ts +26 -2
  15. package/src/adapters/cli/commands-self.ts +84 -1
  16. package/src/adapters/cli/commands-shared.ts +6 -0
  17. package/src/adapters/cli/commands.ts +18 -8
  18. package/src/adapters/cli/dream-core.ts +21 -3
  19. package/src/adapters/cli/help.ts +8 -1
  20. package/src/adapters/cli/mechanisms.ts +526 -2
  21. package/src/adapters/cli/self-page.ts +1 -1
  22. package/src/adapters/cli/uninstall.ts +11 -2
  23. package/src/adapters/config.ts +72 -4
  24. package/src/adapters/dashboard/registries.ts +2 -2
  25. package/src/adapters/dashboard/web/narrate.ts +1 -1
  26. package/src/adapters/dashboard/web/pages/health/sections/checks.js +1 -1
  27. package/src/adapters/dashboard/web/pages/health/sections/wake.js +1 -1
  28. package/src/adapters/dashboard/web/pages/self/sections/page.js +14 -4
  29. package/src/adapters/dashboard/web/views/archive-words.ts +2 -0
  30. package/src/adapters/dashboard/web/views/mind.ts +17 -5
  31. package/src/adapters/mcp/server-self-tools.ts +397 -32
  32. package/src/adapters/mcp/server-words.ts +18 -1
  33. package/src/adapters/mcp/server.ts +37 -3
  34. package/src/adapters/mcp/tools.ts +26 -2
  35. package/src/core/counterpart-boundary.ts +3 -0
  36. package/src/core/counterpart.ts +41 -5
  37. package/src/core/dream/CONTRACT.md +34 -2
  38. package/src/core/dream/NOTES.md +91 -1
  39. package/src/core/dream/index.ts +372 -49
  40. package/src/core/dream/reflect.ts +563 -46
  41. package/src/core/dream/slices.ts +91 -7
  42. package/src/core/dream/tags.ts +79 -8
  43. package/src/core/dream/tunables.ts +74 -4
  44. package/src/core/fit/index.ts +162 -0
  45. package/src/core/leaving.ts +2 -0
  46. package/src/core/schemas/CONTRACT.md +9 -0
  47. package/src/core/schemas/NOTES.md +83 -0
  48. package/src/core/schemas/index.ts +288 -3
  49. package/src/core/schemas/tags.ts +65 -4
  50. package/src/core/schemas/tunables.ts +12 -0
  51. package/src/core/schemas/types.ts +21 -0
  52. package/src/core/seat.ts +36 -3
  53. package/src/core/self/NOTES.md +88 -0
  54. package/src/core/self/index.ts +67 -2
  55. package/src/core/self/measures.ts +48 -2
  56. package/src/core/self/page.ts +178 -0
  57. package/src/core/self/tunables.ts +48 -0
  58. package/src/core/self/writer.ts +152 -5
  59. package/src/core/sleep/CONTRACT.md +9 -1
  60. package/src/core/sleep/tags.ts +4 -1
  61. package/src/core/store/CONTRACT.md +5 -2
  62. package/src/core/store/errors.ts +2 -0
  63. package/src/core/store/index.ts +3 -1
  64. package/src/core/store/operational.ts +30 -7
  65. package/src/core/store/owner-op-seam.ts +67 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,94 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.34 — 2026-10-23
4
+
5
+ The night is lighter and better organised. Its helpers start slim, with only the memory tools they use and a short prompt of their own, and the dream's and the reflection's reading goes out as plain lines with short ids (on a copy of the author's store the dream's bundle fell by 43–45%, the reflection's by about 13%, with the same memories shown). The nightly page writer is now called **day's end**: it runs first, in its own child, reads the day by its chapters' summaries and its strongest memories, writes Lately and How I work, and leaves a short account of the day that the dream reads first; the reflection writes Core. The reflection sees the long view again: on busy nights it had been shown no core memories at all, and now it reads them first, with the last three weeks as a line a day. `counterparts night last` and doctor say what a night cost in tokens. No store-format change (store v14, cache v7), no wiring change: `counterparts connect` is not needed after upgrading. Restart the dashboard and every Claude Code session afterwards so the long-running memory server and dashboard load the new version.
6
+
7
+ - **The nightly page writer is now called day's end: it closes the day before the dream.** It now reads the day
8
+ as it was told, each of the day's chapters by its summary, plus the day's 12 strongest memories, and can say which
9
+ memories a sentence on your page rests on. The setting keeps its old name (`pageWriter.mode` in `claude-code.json`).
10
+ - **The night writes the self page in two lanes.** Day's end now runs first, on its own, and
11
+ amends the day's sections (Lately, How I work); the reflection writes Core, the long view. Each
12
+ keeps to its own sections, a sentence kept word for word keeps what it rested on, and the dream no
13
+ longer carries the day's page work. One setting turns it back (`self.PAGE_SPLIT`).
14
+ - **Day's end leaves a short account of the day; the dream reads it first and the reflection sees the last three
15
+ weeks as a line a day.** With its one closing call each night (with the page, or alone when the page stands), day's
16
+ end writes a few lines about what the day was about and what is in motion, and the memories they rest on. The
17
+ dream opens with it, above everything it was going to read anyway, and the morning reflection gets a timeline of
18
+ the last 21 days, so it can see a pattern across weeks. `counterparts night last` and the dashboard's page strip
19
+ show it. Switch: `self.DAY_SUMMARY`.
20
+ - **A known misread:** if day's end sends its summary alone and then writes a page anyway, that night's row
21
+ reads "nothing-to-say" although the page changed. Day's end is told to send the summary alone only when the
22
+ page stands.
23
+ - **The reflection reads the long view first.** On a busy night the morning reflection was handed the day's
24
+ chapters and a line for everything the dream saw before any of its core memories, and often never got to them
25
+ (on the author's 10-21 and 10-22 nights it was shown no core memories, candidates or strongly felt ones at all).
26
+ Now your core memories, the memories that may become core and the most strongly felt ones always come first,
27
+ then the last few days' chapters by their summaries, then what the dream changed.
28
+ - **The night reads lighter.** The dream's and the reflection's bundles now go out as plain
29
+ lines with short ids for the night (m1, m2… for memories, c1… for journals) instead of
30
+ JSON inside JSON, and the dream reads each chapter by its summary with its address, a
31
+ lookup away from the whole. On a copy of the author's store the dream's bundle fell from
32
+ about 147k characters in 4–5 parts to about 82k in 3, the reflection's by about 13%,
33
+ with the same memories shown. Every tool the night uses takes the short ids, and real
34
+ ids still work. `propose` and the reflection's `finish` answer with counts and only what
35
+ went wrong. On a quiet day the dream's room shrinks, spending less on whole texts while
36
+ showing the same memories. `dream.LEAN_BUNDLE` off puts the old shape back.
37
+ - **The night's helpers start lighter.** Each background run of the night (day's end, the dream, the
38
+ reflection, tagging, a write-up owed) now starts with only the memory tools it uses and a
39
+ short prompt of its own, instead of Claude Code's full coding setup, so it spends fewer
40
+ tokens before it begins.
41
+ - **`counterparts night last` shows what a night cost in tokens.** The night's line says its
42
+ total, and `counterparts doctor`'s Nightly run line says it too.
43
+ - **For a host built on the package:** `counterparts` now exports `SPLIT_DREAM_TOOLS`, `SPLIT_REFLECTION_TOOLS`
44
+ and `seatTools` (which memory tools each night child is served), and `counterparts/claude-code` exports
45
+ `NIGHT_SERVED_TOOLS`, `NIGHT_SYSTEM_PROMPT`, `childUsage` (a night child's tokens from its `result` line),
46
+ `NIGHT_DEBUG_DIR`, `NIGHT_TRANSCRIPT_DAYS`, `nightDebugDir`, `writeNightTranscript` and `pruneNightTranscripts`
47
+ (the dev-only `debug` switch, documented in CONTRIBUTING.md). Nothing was removed.
48
+
49
+ ## 0.3.33 — 2026-10-23
50
+
51
+ On the first new lived day after upgrading (when the first turn or session ends on a new day; if today's card pass already ran, tomorrow), the card pass merges once the pairs of cards that share a name (a race fixed in 0.3.31 left them; the author's store had 50 pairs): the younger card of each pair is archived under the older one, which gains the links neither had while both were live. `counterparts dream --undo-twins` puts the cards back if you want them. The same night hands cards that were filed as a person or a place only by how they were born back to its kinds question. The dream takes in more of the day's new memories a night (a 16,000-character list, 4 neighbours each; an experiment, checked 10-29). `counterparts note --tags` and `counterparts dream --undo-tags` are new, and `counterparts mechanisms` says how often a settled thing comes back. No store-format change (store v14, cache v7), no wiring change: `counterparts connect` is not needed after upgrading. Restart the dashboard and every Claude Code session afterwards so the long-running memory server and dashboard load the new version.
52
+
53
+ - **One name, one card again.** Once, the night merges pairs of cards that share a name, left by a
54
+ race fixed in 0.3.31 (the author's store had 50 pairs). It archives the younger card of each pair
55
+ under the older one, and leaves alone any pair that differs in any way. While both cards were live,
56
+ a memory naming the name was linked to neither. The older card now gains those links: on a copy
57
+ of the author's store (10-23), 50 pairs merged, none left alone, and 239 memories gained 338 links.
58
+ - `counterparts doctor`'s v14 upgrade line says how many it merged and linked.
59
+ - `counterparts dream --undo-twins` puts the cards back. The links stay, because they are true. The
60
+ cost: the name is held twice again, so new memories naming it link to neither card, and the night
61
+ won't merge them again.
62
+ - **A card is no longer called a person or a place just because of how it was born.** "Counterparts"
63
+ had been filed as a place and "Anthropic" as a person, from a single memory each. Only your own
64
+ card is a person without anyone judging it now. Once, the night hands the cards the upgrade sorted
65
+ that way back to its kinds question, which a model answers.
66
+ - **A night's dream takes in more of the day's new memories.** The list of new memories the
67
+ dream is handed may run to 16,000 characters (was 12,000), and each new memory comes with its
68
+ 4 nearest older memories (was 6). On the 10-22 night that is 64 new memories instead of 44,
69
+ for about 1,300 more tokens, with nothing else left out; fewer memories come with their whole text
70
+ (11 instead of 20). An experiment, checked 2026-10-29.
71
+ - **`counterparts note` takes tags:** `--tags garden,katie`. They are kept the way a session's tags
72
+ are, and the console says which it kept and which it left off.
73
+ - **`counterparts dream --undo-tags` takes back a night's tagging:** the newest night's by default,
74
+ or a named night and every night since. It removes the tags, tag merges and card kinds that night
75
+ set. Your own tags stay.
76
+ - **Marking a weekly reminder done through `remember` closes this week's occurrence** on the day the
77
+ session sees, even when the store's clock is a day behind.
78
+ - **`counterparts mechanisms` says how often a settled thing comes back.** A new line under the
79
+ mechanisms: of the memories changed or corrected before this week, how many a session drew on
80
+ the old side of again (changed and corrected apart: a corrected one is archived, so little can
81
+ reach it), how many came up again (a new disagreement, or a new memory saying the old thing),
82
+ and how many were only shown, split by the build that wrote them. `--json` prints the short
83
+ view as JSON, with example ids.
84
+ - **For a host built on the package:** `counterparts/claude-code` now exports `deliverTurn`
85
+ (what a hook prints on a turn, and the reminders it claims only once they are certainly
86
+ shown), `hostDelivery`, and `expansionIdsOf` (the recall ids a turn's transcript expands).
87
+ With them come `envelopeJson`, `HOST_SESSION_START`, `HOST_USER_PROMPT_SUBMIT` and `HOST_STOP`
88
+ (`counterparts/claude-code`), `settledReading` and `settledLines` (`counterparts/cli`, the
89
+ mechanisms line above), and `birthKindSubjectKind` and `deterministicSubjectKind`
90
+ (`counterparts/store`). Nothing was removed.
91
+
3
92
  ## 0.3.32 — 2026-10-22
4
93
 
5
94
  The sidebar is now a plugin of its own, `counterparts-sidebar`, and `counterparts` is the memory alone. If you use the plugin, the update (`/plugin marketplace update counterparts`) removes the sidebar; `/plugin install counterparts-sidebar@counterparts` brings it back, starting from the default view, theme and avatar. With the npm install beside both plugins, doctor's Claude Code line is green: the plugin stays installed for the sidebar and stands down. Open threads change meaning: an item is open only when someone owes an answer (a question to you, a check with a date, a promise), and one nobody has touched in 21 lived days, with no date and not a question you were asked, stops being carried in the wake and offered to the reflection; it is not closed, and using or revising it carries it again. **The first morning after upgrading counts the whole untouched backlog at once**, so that morning's share may say a large number left; it says the number once, never the list. Beliefs now show: the strongest two or three about a person, project or topic a message names come up beside the footnotes, and a project's folder may open with a short line of them. Doctor gains a Builds line. The core from beliefs is built and off (`self.CORE_FROM_BELIEFS`). No store-format change (store v14, cache v7), no wiring change: `counterparts connect` is not needed after upgrading. Restart the dashboard and every Claude Code session afterwards so the long-running memory server and dashboard load the new version.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "counterparts",
3
- "version": "0.3.32",
3
+ "version": "0.3.34",
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": {
@@ -849,7 +849,13 @@ output is ignored. Every child, the plain retry included, also passes
849
849
  `--no-session-persistence` (2026-10-21; checked on 2.1.306 with `--session-id` and
850
850
  `stream-json`), so the host keeps no transcript of it under `~/.claude/projects`: its
851
851
  words — memories it read, the conversation it wrote up — do not outlive this package's own
852
- retention there. On a host too old to know the flag the night does not run. It
852
+ retention there. On a host too old to know the flag the night does not run. Every child,
853
+ the plain retry and the catch-up included, is also SLIM (2026-10-23): `--tools ""` (no
854
+ built-in tool at all, `ToolSearch` included, so the host offers our tools up front instead
855
+ of deferring them — measured on 2.1.309 and so documented), `--system-prompt` our own
856
+ fixed words (`NIGHT_SYSTEM_PROMPT`) in place of the host's coding-assistant prompt, and
857
+ every counterparts tool the child is not granted denied (`NIGHT_SERVED_TOOLS`), so it is not
858
+ offered either; `NIGHT_DENIED_TOOLS` stays as the second fence. It
853
859
  starts in a NEUTRAL directory — the store's own — so no project's CLAUDE.md, hooks or MCP
854
860
  servers load. The parent's stance, `CLAUDE_PROJECT_DIR` and `CLAUDECODE` variables are
855
861
  removed; this package's values are written last.
@@ -903,3 +903,23 @@ read the child's transcript under `~/.claude/projects`). Three things it owes:
903
903
  3. **Not read:** the morning catch-up's child (its write-up parts are far under any line)
904
904
  and ordinary sessions. A cut in a session someone watches is in front of them; one in a
905
905
  session nobody watches (a GitHub action) is not seen by anything.
906
+
907
+ ## 19. A second host could not deliver a turn as this one does (2026-10-20, lane 1 handoff) — CLOSED 2026-10-22 (lane L)
908
+
909
+ The harness (`tools/harness/`) is held to the package's public exports
910
+ (`test/harness-imports.test.ts`), and two things it needed were not there: what a hook
911
+ prints and claims on a turn (`bin/hook.ts#deliverTurn`), and the recall ids a turn's
912
+ transcript expands (`transcript.ts#expansionIdsOf`). `harness week` copied both by hand.
913
+
914
+ - **`expansionIdsOf`** is exported from `index.ts` beside the other transcript readers;
915
+ `harness week` reads its model's recall calls through it.
916
+ - **`deliverTurn`**, with `hostDelivery`, `Delivery`, `UpdateNoticeDoors`, `HOST_STOP` and
917
+ `fieldsFit`, moved unchanged from `bin/hook.ts` into `envelope.ts`, and `index.ts`
918
+ exports them. Not re-exported from `bin/hook.ts` directly: that file is the hook's entry
919
+ script, does work at load (its config path, its sibling scripts) and imports `index.ts`
920
+ itself. `bin/hook.ts` imports them back and re-exports them, so tests and the
921
+ `bin/hook.ts#deliverTurn` references still hold. A test pins that the public entry's
922
+ import graph reaches no `bin/` file.
923
+ - **Not done:** `harness week`'s own `claim` still claims whatever a hook offers without
924
+ asking whether the envelope had room. Moving it onto `deliverTurn` would change what
925
+ `harness week` reports on a full-wake day; that is its own change, with a compare.
@@ -2646,3 +2646,64 @@ running both, found confusing. The npm install now leaves `npm-live.json` beside
2646
2646
  folder under `~/.claude/projects` for its directory.
2647
2647
  - `tools/harness/week.ts` drops the flag for its scripted person's turns, which
2648
2648
  `--resume` the session and whose hooks read its transcript.
2649
+
2650
+ ## 2026-10-22 — the night's row names each child's session; the turn's delivery is public (lane L)
2651
+
2652
+ - **Each child's `--session-id` is on the row** (`NightChildRun.hostSession`, set by
2653
+ `runNightChild` and carried by `NightAnswer.hostSession`), and on the `dream.night` event
2654
+ as `childSessions` (`dream:<id>,reflection:<id>`). No store change: the row is JSON in
2655
+ meta and in the event's payload. Recorded only when the child that ran is the one named:
2656
+ a plain retry (a host that refused the flag) ran under an id its host chose, and a child
2657
+ that never started has none. `children`, the words the log and the dashboard show, is
2658
+ unchanged.
2659
+ - **The harness matches by name first**: `tools/harness/night.ts#nightRowFor` finds the
2660
+ row naming a transcript's `sessionId` and takes the night's reflection by id; a row from
2661
+ before (or a transcript from elsewhere) falls back to the time window, and the record
2662
+ says which (`matchedBy`).
2663
+ - **`deliverTurn` and its envelope moved to `envelope.ts`**, unchanged, so `index.ts`
2664
+ exports them without loading the hook's entry script (INTERFACE-GAPS §19).
2665
+ - Fixed on the way: `core/dream#childRunOf` read back only `dream` and `reflection`
2666
+ children, so a `tags` child (10-21) was dropped from a row read back from meta (the
2667
+ run's own return and the event's `children` words kept it). It now keeps `tags`, with
2668
+ its `hostSession`.
2669
+
2670
+ ## 2026-10-23 — the slim night child (lane N1, step 1)
2671
+
2672
+ - **Every child is slim**: `--tools ""` and `--system-prompt NIGHT_SYSTEM_PROMPT`, on the
2673
+ dream, the reflection, the tagging child, the catch-up child and the plain retry
2674
+ (`planNightChild`, the one place they are all planned). Owner, 10-23: "worth testing and
2675
+ replacing system prompt, and removing unused tools as long as we're sure we don't need
2676
+ them." Across every night transcript (Sept–10-21) the only built-in tool a child called
2677
+ was `ToolSearch`, to load our deferred tools.
2678
+ - **Checked first, on 2.1.309, against a temp store** (one trivial `claude -p` each way,
2679
+ `--setting-sources project` in a temp directory so no user setting or hook loaded):
2680
+ master's child offered nine built-ins (`ToolSearch`, `CronDelete`, `CronList`,
2681
+ `ScheduleWakeup`, `PushNotification`, `ListAgents`, `ExitWorktree`, `DesignSync`,
2682
+ `ReportFindings` — none in `NIGHT_DENIED_TOOLS`) and our ten tools deferred; it called
2683
+ `ToolSearch` to load `recall`, then `recall`. Its first call was 6,903 tokens, 9,253 after
2684
+ the load. The slim child's `init` listed our ten tools and nothing else, and it called
2685
+ `recall` on its first turn. Claude Code's docs say the same: with `ToolSearch` denied or
2686
+ left out of `--tools`, MCP tools load up front.
2687
+ - **Up front means all of them**: the slim child offered all ten began at 29,842 tokens —
2688
+ the ten definitions are ~84k characters (`remember` and `session_end` ~18k each). So a
2689
+ child is now denied every tool of ours it is not granted (`NIGHT_SERVED_TOOLS`, pinned to
2690
+ the server's `TOOL_NAMES` by a test rather than imported, so the hook does not load the
2691
+ tool registry), and a denied tool is not offered. Per act, what is offered up front:
2692
+ dream ~24k characters (dream, self_page, recall), reflection ~37k (+ reflect), tags ~10k
2693
+ (dream), catch-up ~18k (session_end). The fat child paid for the same definitions once
2694
+ `ToolSearch` loaded them, plus ~6.5k of host prompt and built-ins and a turn per load.
2695
+ - **The system prompt** says only where the child is and what holds whatever the act; the
2696
+ act itself comes on stdin as before. Fixed words, so argv is fine. Nothing the host does
2697
+ with an oversized result depends on the prompt: the cut is reported in the `stream-json`
2698
+ output either way (`readNightSpills`), and the file a cut points to was never readable
2699
+ (`Read` denied).
2700
+ - **The plain retry keeps both flags.** `--system-prompt` is in print mode since 1.0 and
2701
+ `--tools` since before 2.1.0; no night has run on a host older than 2.1.284. A host that
2702
+ refused them would end the night as `--no-session-persistence` would (a quick exit on the
2703
+ row). Dropping them on the retry instead is one line, if a host ever does.
2704
+ - **`NIGHT_DENIED_TOOLS` stays, as the second fence**, with the eight unlisted built-ins
2705
+ above added for a host that ignored `--tools`.
2706
+ - Not measured: the real night's base (user settings, plugins and the user's CLAUDE.md load
2707
+ in a night child; the check above left them out), and whether `--system-prompt` changes
2708
+ what of the user's CLAUDE.md reaches the child. A model night after release, or the
2709
+ coordinator's `childUsage` per child, says.
@@ -43,14 +43,11 @@ import { canonicalScope, installedVersion, isEntrypoint, readSession } from "../
43
43
  import { openLog } from "../../log/index.js";
44
44
  import type { LogEvent, ProcessLog } from "../../log/index.js";
45
45
  import { resolveZone, todayIn } from "../../../core/time.js";
46
- import { TUNABLES, loadConfig, withBudgetDefault, withEmbedderDefault } from "../../config.js";
46
+ import { loadConfig, withBudgetDefault, withEmbedderDefault } from "../../config.js";
47
47
  import type { AdapterConfig } from "../../config.js";
48
48
  import { HOOKS, openAdapter } from "../index.js";
49
- import { STOP_HUMAN_LINE, plainLine, withoutDream, withoutDreamNote, withoutPlain } from "../hooks.js";
50
- import type { PlainReminder } from "../../../core/counterpart.js";
51
- import type { DreamTold, HookInput, HookName } from "../hooks.js";
49
+ import type { HookInput, HookName } from "../hooks.js";
52
50
  import { NIGHT_RUN_ENV } from "../night-run.js";
53
- import type { DreamOffer } from "../../../core/dream/index.js";
54
51
  import {
55
52
  CONFIG_REFUSED,
56
53
  CONFIG_UNREADABLE,
@@ -84,66 +81,9 @@ import { claimDelivery, deliveryClaimKey, finishClaim, firesOnce } from "../clai
84
81
  * constant each, shared with `hooks.ts`, which measures the same envelope
85
82
  * before it decides what rides beside the wake (`../envelope.ts`).
86
83
  */
87
- import { HOST_SESSION_START, HOST_USER_PROMPT_SUBMIT, envelopeJson } from "../envelope.js";
88
- export { HOST_SESSION_START, HOST_USER_PROMPT_SUBMIT } from "../envelope.js";
89
-
90
- /**
91
- * WHAT THE JSON FORM MUST FIT: EACH FIELD, NOT THE WHOLE ENVELOPE (measured
92
- * 2026-10-10 on Claude Code 2.1.296; adapter NOTES, "The notice is capped").
93
- *
94
- * The host's cap (https://code.claude.com/docs/en/hooks#json-output): "A hook's
95
- * `additionalContext`, `systemMessage`, and `initialUserMessage` strings, and
96
- * its plain stdout, are capped at 10,000 characters … For JSON output, each
97
- * field is measured separately; plain stdout is measured whole." Measured: a
98
- * 10,488-character envelope in this hook's own shape (`systemMessage` 376,
99
- * `additionalContext` 9,910) and a 12,637-character escape-heavy one both
100
- * parsed, every field whole; a field past 10,000 is previewed and the JSON
101
- * still parses. So the JSON form's escaping costs nothing: what must fit is
102
- * the model's text and the person's line, each under `TUNABLES.HOST_OUTPUT_CHARS`
103
- * (the one place the host's number lives), in characters, as the host counts.
104
- *
105
- * Until then (2026-09-14) the rule was 9,500 characters of WHOLE envelope —
106
- * read from the same docs as fatal past 10,000, since a previewed object would
107
- * no longer parse — so on a full-wake day the notice was dropped though both
108
- * fields fit. Now the notice is kept whenever both fields fit, and the fallback
109
- * is still the plain wake: a notice that does not fit is dropped, never the
110
- * memory, and `counterparts doctor` still prints it.
111
- */
112
- function fieldsFit(context: string, message: string): boolean {
113
- return context.length <= TUNABLES.HOST_OUTPUT_CHARS && message.length <= TUNABLES.HOST_OUTPUT_CHARS;
114
- }
115
-
116
- /**
117
- * HOW A DUE STOP ASK LEAVES THIS PROCESS — ONE shape (owner, 2026-09-24).
118
- *
119
- * Exit 0 and one JSON object on stdout:
120
- *
121
- * {"systemMessage": <the person's line>,
122
- * "hookSpecificOutput": {"hookEventName": "Stop", "additionalContext": <the model's ask>}}
123
- *
124
- * The host's reference (https://code.claude.com/docs/en/hooks, read
125
- * 2026-09-24), Stop decision control: `hookSpecificOutput.additionalContext` is
126
- * "Non-error feedback for Claude. The conversation continues so Claude can act
127
- * on it, but unlike `decision: "block"` it is shown in the transcript as hook
128
- * feedback rather than a hook error" — and "It keeps the conversation going
129
- * through the same loop protections as `decision: "block"`, namely the
130
- * `stop_hook_active` input and the 8-consecutive-continuation cap". It stands
131
- * alone: no `decision` beside it.
132
- *
133
- * WHY THIS ONE. B1 (2026-09-23) built two shapes behind a `stopAskShape`
134
- * switch — the JSON `decision: "block"` and the day-0 stderr + exit 2 — and the
135
- * owner looked at both in a real terminal on 0.3.0: both printed the model's
136
- * two lines as `Stop hook error: …`, so both read as an error. This is the
137
- * third route, the one the docs call non-error; the switch and both earlier
138
- * shapes are gone. A `claude-code.json` that still carries `stopAskShape` is
139
- * read fine, the key ignored and named among the old settings (`config.ts`).
140
- *
141
- * What the person sees is NOT only their own line: the host's 2.1.281 bundle
142
- * renders an additionalContext on Stop under "Ran 1 stop hook" as
143
- * `Stop hook feedback: <ask>`, in the notice colour rather than the error one.
144
- * Quieter, not silent. `../NOTES.md` §"The Stop ask's shapes" has the record.
145
- */
146
- export const HOST_STOP = "Stop";
84
+ import { HOST_SESSION_START, HOST_STOP, HOST_USER_PROMPT_SUBMIT, deliverTurn, hostDelivery } from "../envelope.js";
85
+ export { HOST_SESSION_START, HOST_STOP, HOST_USER_PROMPT_SUBMIT, deliverTurn, hostDelivery } from "../envelope.js";
86
+ export type { Delivery, UpdateNoticeDoors } from "../envelope.js";
147
87
 
148
88
  /** The host's event names, mapped to this adapter's. Host trivia, by definition. */
149
89
  const HOST_HOOKS: Record<string, HookName> = {
@@ -1128,186 +1068,6 @@ export function attendedOf(raw: string | undefined): { attended?: boolean } {
1128
1068
  return {};
1129
1069
  }
1130
1070
 
1131
- /** The two adapter doors `deliverTurn` needs — structural, so a test can
1132
- * hand it doors that throw. */
1133
- export interface UpdateNoticeDoors {
1134
- updateNotice(input: HookInput): string | null;
1135
- markUpdateNotice(input: HookInput): boolean;
1136
- /**
1137
- * Claim plain reminders this delivery is certainly about to show, returning
1138
- * the ones claimed (`ClaudeCodeAdapter#claimPlain`). Absent: nothing can be
1139
- * claimed, so nothing is shown and every one waits for a later turn.
1140
- */
1141
- claimPlain?(input: HookInput, due: readonly PlainReminder[]): readonly PlainReminder[];
1142
- /**
1143
- * Claim the day's dream line this delivery is certainly about to show
1144
- * (`ClaudeCodeAdapter#claimDream`). Absent: nothing can be claimed, so the
1145
- * line is not shown and waits for a later prompt.
1146
- */
1147
- claimDream?(input: HookInput, offer: DreamOffer): boolean;
1148
- /**
1149
- * Claim a HELD dream line — a run a session nobody watched started — this
1150
- * delivery is certainly about to show (`ClaudeCodeAdapter#claimHeld`,
1151
- * 2026-10-01). Absent: nothing can be claimed, so it waits.
1152
- */
1153
- claimHeld?(input: HookInput, run: string): boolean;
1154
- /** Claim the one-time line about `auto` set back to `ask` (`ClaudeCodeAdapter#claimDreamNote`). */
1155
- claimDreamNote?(input: HookInput): boolean;
1156
- /**
1157
- * Record what this delivery left for later for want of ROOM — `plain`
1158
- * reminders (how many), the `dream` offer, the `update-notice`
1159
- * (`ClaudeCodeAdapter#noteGaveWay`). Absent: nothing is recorded.
1160
- */
1161
- noteGaveWay?(input: HookInput, part: string, count: number): void;
1162
- }
1163
-
1164
- /**
1165
- * THIS EVENT'S OUTPUT, WITH PLAIN REMINDERS AND THE UPDATE NOTICE FOLDED IN
1166
- * FAIL-OPEN (roadmap E; #187 re-review, N4; 2026-09-26 review).
1167
- *
1168
- * PLAIN REMINDERS FIRST, and under the update notice's own rule — MARK ONLY
1169
- * WHAT IS CERTAINLY LEAVING. A plain beat is spent once and never comes back,
1170
- * so it is claimed only after the envelope is known to carry its line to the
1171
- * terminal, and it goes ahead of every other notice (the doctor's red line
1172
- * returns at the next start; the beat would not). A turn with no room — a full
1173
- * wake at SessionStart — claims nothing and strips the lines from the model's
1174
- * context too (`withoutPlain`), so the first prompt, whose envelope is small,
1175
- * says them instead. A line whose claim is lost to another process is stripped
1176
- * the same way.
1177
- *
1178
- * Then the update notice: the delivery without it is the answer whenever
1179
- * anything about it goes wrong — a door that throws, a mark that will not
1180
- * land, an envelope with no room for it — so it can never cost a line that
1181
- * already fit. It is MARKED only once it is certainly leaving and SHOWN only if
1182
- * the mark landed, so it never repeats and is never marked-but-lost; a turn
1183
- * whose recall leaves no room marks nothing and tries again next turn.
1184
- */
1185
- export function deliverTurn(
1186
- name: HookName,
1187
- result: {
1188
- injection: string | null;
1189
- ask: string | null;
1190
- notices?: readonly string[];
1191
- plain?: readonly PlainReminder[];
1192
- dream?: DreamTold;
1193
- dreamNote?: { notice: string; context: string };
1194
- },
1195
- payload: Record<string, unknown>,
1196
- /** SessionStart's priority-ordered notices (after any plain reminders), or
1197
- * null. At a prompt, null: the plain lines come from `result.plain`. */
1198
- notices: readonly (string | null)[] | null,
1199
- doors: UpdateNoticeDoors,
1200
- input: HookInput,
1201
- ): Delivery {
1202
- let r = result;
1203
- let ordered = notices;
1204
- let deferred: Delivery["dropped"] = null;
1205
- const due = result.plain ?? [];
1206
- if (due.length > 0) {
1207
- // The longest run, in order, whose lines the envelope carries: a day with
1208
- // more plain items than room says what fits and keeps the rest for later.
1209
- let fits = 0;
1210
- for (let k = due.length; k > 0; k--) {
1211
- const probe = hostDelivery(name, r, payload, [due.slice(0, k).map(plainLine).join("\n")]);
1212
- if (probe.dropped === null) {
1213
- fits = k;
1214
- break;
1215
- }
1216
- if (k === due.length) deferred = probe.dropped;
1217
- }
1218
- let claimed: readonly PlainReminder[] = [];
1219
- if (fits > 0) {
1220
- try {
1221
- claimed = doors.claimPlain?.(input, due.slice(0, fits)) ?? [];
1222
- } catch {
1223
- claimed = [];
1224
- }
1225
- }
1226
- // By the beat's identity, not the object's: a door may hand back copies.
1227
- const beat = (x: PlainReminder): string => `${x.memoryId} ${x.windowKey} ${x.beat}`;
1228
- const kept = new Set(claimed.map(beat));
1229
- const shownPlain = due.filter((d) => kept.has(beat(d)));
1230
- // WHAT GAVE WAY, as delivered: the reminders the envelope had no room for
1231
- // (a lost claim race is not room, and is recorded by `claimPlain`).
1232
- if (fits < due.length) gaveWay(doors, input, "plain", due.length - fits);
1233
- r = withoutPlain(r, due.filter((d) => !kept.has(beat(d))));
1234
- if (shownPlain.length > 0) ordered = [shownPlain.map(plainLine).join("\n"), ...(notices ?? [])];
1235
- }
1236
- // THE DAY'S DREAM LINE (2026-09-29), after the plain reminders and under
1237
- // their rule: an ask is CLAIMED only once the envelope is known to carry the
1238
- // person's line, and without room it waits — its model line stripped too, so
1239
- // the model never answers a question the person was not shown. A line whose
1240
- // day is already claimed (the headless run has started) keeps its model line
1241
- // and only loses the terminal one.
1242
- const told = r.dream;
1243
- if (told !== undefined) {
1244
- const probe = hostDelivery(name, r, payload, [...(ordered ?? []), told.notice]);
1245
- let showDream = false;
1246
- if (probe.dropped === null) {
1247
- if (told.held !== undefined) {
1248
- try {
1249
- showDream = doors.claimHeld?.(input, told.held) ?? false;
1250
- } catch {
1251
- showDream = false;
1252
- }
1253
- } else if (told.offer === null) showDream = true;
1254
- else {
1255
- try {
1256
- showDream = doors.claimDream?.(input, told.offer) ?? false;
1257
- } catch {
1258
- showDream = false;
1259
- }
1260
- }
1261
- } else {
1262
- if (deferred === null) deferred = probe.dropped;
1263
- gaveWay(doors, input, "dream", 1);
1264
- }
1265
- if (showDream) ordered = [...(ordered ?? []), told.notice];
1266
- else if (told.offer !== null || told.held !== undefined) r = withoutDream(r);
1267
- }
1268
- // THE ONE-TIME RESET LINE (owner decision A), under the same rule.
1269
- const note = r.dreamNote;
1270
- if (note !== undefined) {
1271
- const probe = hostDelivery(name, r, payload, [...(ordered ?? []), note.notice]);
1272
- let shownNote = false;
1273
- if (probe.dropped === null) {
1274
- try {
1275
- shownNote = doors.claimDreamNote?.(input) ?? false;
1276
- } catch {
1277
- shownNote = false;
1278
- }
1279
- } else if (deferred === null) {
1280
- deferred = probe.dropped;
1281
- }
1282
- if (shownNote) ordered = [...(ordered ?? []), note.notice];
1283
- else r = withoutDreamNote(r);
1284
- }
1285
- const shown = hostDelivery(name, r, payload, ordered);
1286
- const base = shown.dropped === null && deferred !== null ? { ...shown, dropped: deferred } : shown;
1287
- if (name !== "user-prompt-submit") return base;
1288
- try {
1289
- const update = doors.updateNotice(input);
1290
- if (update === null) return base;
1291
- const carried = hostDelivery(name, r, payload, [...(ordered ?? []), update]);
1292
- if (carried.dropped !== null) {
1293
- gaveWay(doors, input, "update-notice", 1);
1294
- return { ...base, dropped: base.dropped ?? carried.dropped };
1295
- }
1296
- return doors.markUpdateNotice(input) ? carried : base;
1297
- } catch {
1298
- return base;
1299
- }
1300
- }
1301
-
1302
- /** `doors.noteGaveWay`, fail-open: a record that cannot be made costs nothing. */
1303
- function gaveWay(doors: UpdateNoticeDoors, input: HookInput, part: string, count: number): void {
1304
- try {
1305
- doors.noteGaveWay?.(input, part, count);
1306
- } catch {
1307
- /* bookkeeping */
1308
- }
1309
- }
1310
-
1311
1071
  /**
1312
1072
  * SessionStart's stamp on a session that OPENS, and nothing else: run AFTER the
1313
1073
  * wake is written (`main`), and swallowed if it throws — the stamp is
@@ -1323,160 +1083,6 @@ export function stampWhenOpened(payload: Record<string, unknown>, stamp: () => u
1323
1083
  }
1324
1084
  }
1325
1085
 
1326
- /**
1327
- * How each hook's output reaches the model on THIS host — measured, not
1328
- * assumed (scar §2.18), on day 0 of the parallel run (2026-09-03):
1329
- *
1330
- * - SessionStart / UserPromptSubmit: plain stdout with exit 0 is added to the
1331
- * model's context. The wake (8,859 B) arrived that way.
1332
- * - Stop: plain stdout with exit 0 reaches NOBODY. An ask written that way
1333
- * was recorded (`adapter.episode.ask asked:true`) and never seen. The one
1334
- * channel proven on this host is the blocking one bansai has used all along:
1335
- * the text on STDERR and exit code 2, which the host feeds back to the model
1336
- * as "Stop hook feedback" and lets it continue. The host then re-fires Stop
1337
- * with `stop_hook_active: true`; that re-fire must ask NOTHING or the ask
1338
- * loops forever (v1's anti-loop, kept here for the same reason).
1339
- * **Since 2026-09-24 the ask leaves by the host's documented NON-ERROR
1340
- * route instead** (`HOST_STOP` above): exit 0, the model's ask as
1341
- * `hookSpecificOutput.additionalContext`, one line for the person as
1342
- * `systemMessage`. Same continuation, same re-fire, same refusal of it.
1343
- *
1344
- * **The fourth channel, added 2026-09-14 for I32: `systemMessage`.** Documented
1345
- * at https://code.claude.com/docs/en/hooks (formerly
1346
- * docs.claude.com/en/docs/claude-code/hooks) and measured by the owner's own
1347
- * probe on 2026-09-11: a SessionStart hook that exits 0 and prints JSON with a
1348
- * top-level `systemMessage` gets that text DISPLAYED in the terminal
1349
- * (`SessionStart:startup says: …`), non-blocking, while `additionalContext` and
1350
- * stderr do not show. The doc also states the rule that makes this safe or
1351
- * dangerous depending on which form you print: **when stdout parses as JSON the
1352
- * raw stdout is NOT also added to context** — only the JSON's fields are. So the
1353
- * wake must ride ENTIRELY in `hookSpecificOutput.additionalContext`, byte for
1354
- * byte what plain stdout would have carried, and a day with nothing red prints
1355
- * the plain form it has printed since day 0 rather than a JSON wrapper nobody
1356
- * has measured on this host.
1357
- *
1358
- * Pure, so the test proves the channel choice without a process. `dropped` is
1359
- * how a pure function reports the one thing it cannot do itself: the caller
1360
- * turns it into the ring row that makes a silent terminal explicable.
1361
- */
1362
- export interface Delivery {
1363
- readonly stdout: string;
1364
- readonly stderr: string;
1365
- /** Always 0 since 2026-09-24: no event leaves by exit 2 any more. */
1366
- readonly exitCode: 0;
1367
- /** Non-null when a notice was left out to keep the wake whole — all of them,
1368
- * or (with several) the lower ones that no longer fit. */
1369
- readonly dropped: { readonly noticeChars: number; readonly envelopeChars: number; readonly limitChars: number } | null;
1370
- /**
1371
- * THE PLAIN FALLBACK, CHECKED (2026-09-29, audit item 9). Set when the plain
1372
- * stdout this prints is itself past the host's cap (`HOST_OUTPUT_CHARS`), so
1373
- * the host will show a preview in its place. A TRIPWIRE, not a cut: by here
1374
- * the asks are already marked as delivered and this function cannot tell a
1375
- * wake from an ask, so it reports and the caller records it. The adapter's
1376
- * one budget per envelope is what keeps it from happening; what can still
1377
- * reach it is a wake composed past the cap by a misconfigured budget.
1378
- */
1379
- readonly overCap?: { readonly chars: number; readonly limitChars: number };
1380
- }
1381
-
1382
- /** The plain form of an envelope, with the over-cap tripwire read. */
1383
- function plainOut(out: string, dropped: Delivery["dropped"]): Delivery {
1384
- const chars = out.length;
1385
- return chars > TUNABLES.HOST_OUTPUT_CHARS
1386
- ? { stdout: out, stderr: "", exitCode: 0, dropped, overCap: { chars, limitChars: TUNABLES.HOST_OUTPUT_CHARS } }
1387
- : { stdout: out, stderr: "", exitCode: 0, dropped };
1388
- }
1389
-
1390
- export function hostDelivery(
1391
- name: HookName,
1392
- result: { injection: string | null; ask: string | null },
1393
- payload: Record<string, unknown>,
1394
- /**
1395
- * The owner-facing line(s), or null: SessionStart's doctor notice and
1396
- * registry line, UserPromptSubmit's update notice (roadmap E); every other
1397
- * event ignores it. At SessionStart a LIST is a priority order (review M1):
1398
- * each is added only while the envelope still fits, so a lower line can never
1399
- * cost a higher one its place. At a prompt the lines are ALL OR NOTHING —
1400
- * joined into one `systemMessage`, or all dropped — which is what lets
1401
- * `deliverTurn` mark only an envelope that carried them; since 2026-09-26 that is plain reminders and the update notice.
1402
- */
1403
- notice: string | null | readonly (string | null)[] = null,
1404
- ): Delivery {
1405
- const ask = result.ask !== null && result.ask.length > 0 ? result.ask : null;
1406
- if (name !== "stop") {
1407
- const out = [result.injection ?? "", ask ?? ""].filter((s) => s.length > 0).join("\n\n");
1408
- const notices = (typeof notice === "string" || notice === null ? [notice] : notice).filter(
1409
- (n): n is string => n !== null && n.length > 0,
1410
- );
1411
- if (name === "session-start" && notices.length > 0) {
1412
- const envelopeOf = (message: string): string => envelopeJson(HOST_SESSION_START, message, out);
1413
- // THE WAKE WINS. Each field must fit the host's cap on its own
1414
- // (`fieldsFit`): a wake past it is previewed in either form, and then the
1415
- // plain form is printed and `overCap` says so. The notices go in in the
1416
- // order given, each only while the person's field still fits.
1417
- // `envelopeChars` stays what it was, the whole object's length — a fact
1418
- // for the record, no longer the test.
1419
- const kept: string[] = [];
1420
- const left: string[] = [];
1421
- for (const n of notices) {
1422
- if (fieldsFit(out, [...kept, n].join("\n"))) kept.push(n);
1423
- else left.push(n);
1424
- }
1425
- const dropped =
1426
- left.length === 0
1427
- ? null
1428
- : {
1429
- noticeChars: left.join("\n").length,
1430
- envelopeChars: envelopeOf(notices.join("\n")).length,
1431
- limitChars: TUNABLES.HOST_OUTPUT_CHARS,
1432
- };
1433
- if (kept.length === 0) return plainOut(out, dropped);
1434
- return { stdout: envelopeOf(kept.join("\n")), stderr: "", exitCode: 0, dropped };
1435
- }
1436
- // THE UPDATE NOTICE, AT A PROMPT (roadmap E, 2026-09-23) — the same
1437
- // envelope and the same rule: the turn's recall rides whole in
1438
- // `additionalContext` or the notice waits. A turn with no recall prints the
1439
- // `systemMessage` alone rather than an empty context field. A prompt with
1440
- // no notice prints what it always has — plain text, or nothing. More than
1441
- // one line would be JOINED into the one `systemMessage` an object carries,
1442
- // never one replacing another, and dropped all together or not at all —
1443
- // not SessionStart's priority order; since 2026-09-26 the plain reminders and the update notice (`deliverTurn` tries the two together and falls back to the first alone).
1444
- if (name === "user-prompt-submit" && notices.length > 0) {
1445
- const message = notices.join("\n");
1446
- const envelope = JSON.stringify({
1447
- systemMessage: message,
1448
- ...(out.length === 0
1449
- ? {}
1450
- : { hookSpecificOutput: { hookEventName: HOST_USER_PROMPT_SUBMIT, additionalContext: out } }),
1451
- });
1452
- if (!fieldsFit(out, message)) {
1453
- return plainOut(out, { noticeChars: message.length, envelopeChars: envelope.length, limitChars: TUNABLES.HOST_OUTPUT_CHARS });
1454
- }
1455
- return { stdout: envelope, stderr: "", exitCode: 0, dropped: null };
1456
- }
1457
- return plainOut(out, null);
1458
- }
1459
- // The re-fire is refused twice on purpose: the adapter asks nothing on it, and
1460
- // this channel would not carry it even if something did.
1461
- if (payload["stop_hook_active"] === true || ask === null) {
1462
- return { stdout: "", stderr: "", exitCode: 0, dropped: null };
1463
- }
1464
- // EXIT 0, and NO `decision`: `additionalContext` on Stop continues the turn on
1465
- // its own, as non-error feedback (the docblock at `HOST_STOP`). Exit 2 would
1466
- // make STDERR a blocking error again, and a `decision: "block"` beside it
1467
- // would bring back the `Stop hook error:` line this route exists to avoid.
1468
- // One line, no trailing newline, so the whole of stdout is the object. The
1469
- // ask is ~430 characters, far inside the host's 10,000-character cap.
1470
- return {
1471
- stdout: JSON.stringify({
1472
- systemMessage: STOP_HUMAN_LINE,
1473
- hookSpecificOutput: { hookEventName: HOST_STOP, additionalContext: ask },
1474
- }),
1475
- stderr: "",
1476
- exitCode: 0,
1477
- dropped: null,
1478
- };
1479
- }
1480
1086
 
1481
1087
  /** True only when this file is the process entry point — so a test may import
1482
1088
  * `toHookInput` and `hostConfig` without the script running itself. */