counterparts 0.3.31 → 0.3.33

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 (79) hide show
  1. package/CHANGELOG.md +102 -1
  2. package/package.json +1 -1
  3. package/src/adapters/claude-code/INTERFACE-GAPS.md +20 -0
  4. package/src/adapters/claude-code/NOTES.md +20 -0
  5. package/src/adapters/claude-code/bin/hook.ts +5 -399
  6. package/src/adapters/claude-code/doctor-host.ts +22 -0
  7. package/src/adapters/claude-code/doctor-self-page.ts +41 -1
  8. package/src/adapters/claude-code/doctor-upgrades.ts +34 -3
  9. package/src/adapters/claude-code/doctor.ts +42 -1
  10. package/src/adapters/claude-code/envelope.ts +407 -2
  11. package/src/adapters/claude-code/hooks.ts +68 -3
  12. package/src/adapters/claude-code/index.ts +7 -0
  13. package/src/adapters/claude-code/night-run.ts +18 -3
  14. package/src/adapters/cli/commands-note.ts +9 -0
  15. package/src/adapters/cli/commands-readings.ts +26 -2
  16. package/src/adapters/cli/commands-self.ts +84 -1
  17. package/src/adapters/cli/commands-shared.ts +6 -0
  18. package/src/adapters/cli/commands.ts +17 -7
  19. package/src/adapters/cli/help.ts +7 -0
  20. package/src/adapters/cli/install.ts +4 -1
  21. package/src/adapters/cli/mechanisms.ts +526 -2
  22. package/src/adapters/config.ts +7 -0
  23. package/src/adapters/dashboard/activity.ts +3 -0
  24. package/src/adapters/dashboard/web/narrate.ts +14 -2
  25. package/src/adapters/dashboard/web/views/archive-words.ts +2 -0
  26. package/src/adapters/host-wiring.ts +109 -10
  27. package/src/adapters/lifecycle.ts +2 -0
  28. package/src/adapters/mcp/server-words.ts +1 -1
  29. package/src/adapters/mcp/server.ts +13 -1
  30. package/src/adapters/mcp/tools.ts +10 -4
  31. package/src/adapters/plugin.ts +17 -3
  32. package/src/core/counterpart-boundary.ts +3 -0
  33. package/src/core/counterpart-events.ts +14 -1
  34. package/src/core/counterpart.ts +70 -3
  35. package/src/core/dream/CONTRACT.md +8 -0
  36. package/src/core/dream/NOTES.md +9 -1
  37. package/src/core/dream/index.ts +22 -3
  38. package/src/core/dream/reflect.ts +184 -23
  39. package/src/core/dream/tags.ts +79 -8
  40. package/src/core/dream/tunables.ts +14 -4
  41. package/src/core/leaving.ts +2 -0
  42. package/src/core/onboarding.ts +6 -5
  43. package/src/core/recall/CONTRACT.md +44 -0
  44. package/src/core/recall/NOTES.md +36 -0
  45. package/src/core/recall/activate.ts +30 -8
  46. package/src/core/recall/gate.ts +25 -4
  47. package/src/core/recall/index.ts +156 -9
  48. package/src/core/recall/prime.ts +64 -22
  49. package/src/core/recall/probe.ts +5 -2
  50. package/src/core/recall/rated.ts +25 -10
  51. package/src/core/recall/render.ts +79 -11
  52. package/src/core/recall/session.ts +20 -1
  53. package/src/core/recall/tunables.ts +60 -0
  54. package/src/core/retrieval.ts +19 -1
  55. package/src/core/schemas/CONTRACT.md +18 -3
  56. package/src/core/schemas/NOTES.md +98 -0
  57. package/src/core/schemas/index.ts +369 -5
  58. package/src/core/schemas/tags.ts +185 -5
  59. package/src/core/schemas/tunables.ts +12 -0
  60. package/src/core/schemas/types.ts +21 -0
  61. package/src/core/self/CONTRACT.md +7 -0
  62. package/src/core/self/NOTES.md +186 -0
  63. package/src/core/self/identity.ts +86 -2
  64. package/src/core/self/index.ts +10 -2
  65. package/src/core/self/measures.ts +161 -0
  66. package/src/core/self/tunables.ts +95 -0
  67. package/src/core/self/work.ts +10 -0
  68. package/src/core/self/writer.ts +8 -1
  69. package/src/core/sleep/CONTRACT.md +9 -1
  70. package/src/core/sleep/consolidate.ts +7 -4
  71. package/src/core/sleep/tags.ts +4 -1
  72. package/src/core/sleep/types.ts +3 -2
  73. package/src/core/store/CONTRACT.md +5 -2
  74. package/src/core/store/NOTES.md +25 -0
  75. package/src/core/store/errors.ts +2 -0
  76. package/src/core/store/index.ts +115 -12
  77. package/src/core/store/operational.ts +173 -8
  78. package/src/core/store/owner-op-seam.ts +67 -1
  79. package/src/core/store/reads-memories.ts +95 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,106 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.33 — 2026-10-23
4
+
5
+ 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.
6
+
7
+ - **One name, one card again.** Once, the night merges pairs of cards that share a name, left by a
8
+ race fixed in 0.3.31 (the author's store had 50 pairs). It archives the younger card of each pair
9
+ under the older one, and leaves alone any pair that differs in any way. While both cards were live,
10
+ a memory naming the name was linked to neither. The older card now gains those links: on a copy
11
+ of the author's store (10-23), 50 pairs merged, none left alone, and 239 memories gained 338 links.
12
+ - `counterparts doctor`'s v14 upgrade line says how many it merged and linked.
13
+ - `counterparts dream --undo-twins` puts the cards back. The links stay, because they are true. The
14
+ cost: the name is held twice again, so new memories naming it link to neither card, and the night
15
+ won't merge them again.
16
+ - **A card is no longer called a person or a place just because of how it was born.** "Counterparts"
17
+ had been filed as a place and "Anthropic" as a person, from a single memory each. Only your own
18
+ card is a person without anyone judging it now. Once, the night hands the cards the upgrade sorted
19
+ that way back to its kinds question, which a model answers.
20
+ - **A night's dream takes in more of the day's new memories.** The list of new memories the
21
+ dream is handed may run to 16,000 characters (was 12,000), and each new memory comes with its
22
+ 4 nearest older memories (was 6). On the 10-22 night that is 64 new memories instead of 44,
23
+ for about 1,300 more tokens, with nothing else left out; fewer memories come with their whole text
24
+ (11 instead of 20). An experiment, checked 2026-10-29.
25
+ - **`counterparts note` takes tags:** `--tags garden,katie`. They are kept the way a session's tags
26
+ are, and the console says which it kept and which it left off.
27
+ - **`counterparts dream --undo-tags` takes back a night's tagging:** the newest night's by default,
28
+ or a named night and every night since. It removes the tags, tag merges and card kinds that night
29
+ set. Your own tags stay.
30
+ - **Marking a weekly reminder done through `remember` closes this week's occurrence** on the day the
31
+ session sees, even when the store's clock is a day behind.
32
+ - **`counterparts mechanisms` says how often a settled thing comes back.** A new line under the
33
+ mechanisms: of the memories changed or corrected before this week, how many a session drew on
34
+ the old side of again (changed and corrected apart: a corrected one is archived, so little can
35
+ reach it), how many came up again (a new disagreement, or a new memory saying the old thing),
36
+ and how many were only shown, split by the build that wrote them. `--json` prints the short
37
+ view as JSON, with example ids.
38
+ - **For a host built on the package:** `counterparts/claude-code` now exports `deliverTurn`
39
+ (what a hook prints on a turn, and the reminders it claims only once they are certainly
40
+ shown), `hostDelivery`, and `expansionIdsOf` (the recall ids a turn's transcript expands).
41
+ With them come `envelopeJson`, `HOST_SESSION_START`, `HOST_USER_PROMPT_SUBMIT` and `HOST_STOP`
42
+ (`counterparts/claude-code`), `settledReading` and `settledLines` (`counterparts/cli`, the
43
+ mechanisms line above), and `birthKindSubjectKind` and `deterministicSubjectKind`
44
+ (`counterparts/store`). Nothing was removed.
45
+
46
+ ## 0.3.32 — 2026-10-22
47
+
48
+ 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.
49
+
50
+ - **The sidebar is a plugin of its own: `counterparts-sidebar`.** `counterparts` is now the
51
+ memory alone (hooks, memory server, commands); the pane beside the chat comes with
52
+ `/plugin install counterparts-sidebar@counterparts`, which installs `counterparts` too
53
+ if it isn't there. If you already have the plugin, `claude plugin update
54
+ counterparts@counterparts` moves you to memory alone and the sidebar goes until you
55
+ install it; installing the sidebar before that update stops and tells you to run it, so
56
+ you never get two panes. The sidebar starts with the default view, theme and avatar.
57
+ With the npm install, adding the sidebar plugin gives one pane and every memory tool
58
+ once, as before.
59
+ - **Doctor beside the sidebar plugin.** With the npm install, the `counterparts` plugin and
60
+ the `counterparts-sidebar` plugin (the way to get the sidebar with the npm install), doctor's
61
+ Claude Code line is green now: it says the plugin is installed for the sidebar, which needs
62
+ it, and stands down. It is amber only when both installs really run (a plugin build that
63
+ doesn't stand down), and then it says to update the plugin, never to uninstall it. The
64
+ plugin's one session-start line there says the same: nothing needs to change.
65
+ - **The first meeting's close** names `/counterparts` only where a sidebar answers it: with
66
+ the sidebar plugin (installed, on, and with a `counterparts` it accepts), or a
67
+ `counterparts` plugin from before the split. That now includes the npm install beside
68
+ the sidebar plugin.
69
+ - **"Open" now means someone owes an answer.** A memory is marked open only for a question to
70
+ you, a check with a date, or a promise; a bug note, a design note or a fact is kept without
71
+ the open flag. The end-of-session ask says so too.
72
+ - **The end-of-session ask names that session's own open items**, by title, up to five, so
73
+ closing one is a glance at a line rather than a search. A session with nothing open sees the
74
+ ask as before.
75
+ - **Open items nobody has touched in three weeks stop being carried** (an experiment). One with
76
+ no date and not a question you were asked, untouched for 21 lived days, leaves the wake's
77
+ "Still open" and its count, and the nightly reflection stops being offered it. It is not
78
+ closed: recall still finds it, and using it (rating it, drawing on it) or revising it carries
79
+ it again; only seeing it again in a footnote does not. The morning share says how many left,
80
+ once, never the list.
81
+ - **What I believe about something comes up when you mention it.** When a message names a person,
82
+ project or topic I hold beliefs about, the strongest two or three appear in their own short
83
+ block beside the usual footnotes, each with how sure I am and how many memories back it. Rating
84
+ one counts as using it, never as evidence for it.
85
+ - **A project's folder opens with what I hold about the project** (an experiment): a short line of
86
+ its strongest beliefs at the foot of the wake, only when there is room left.
87
+ - **Tags help warm up related memories.** Memories sharing a tag with what a session is using get
88
+ a small head start in recall, beside the links that already do.
89
+ - **Doctor names the builds this store has run.** Each new version, the first time it
90
+ opens the store, notes the day it arrived, and what it writes (memories, the night's
91
+ rows, the log) carries its version, so a later look can say which build did what.
92
+ Doctor's new green Builds line lists the last three. Nothing else changes; a `"build"`
93
+ key now shows wherever a row is printed raw (`--json`, exports, the dashboard's raw rows).
94
+ - **The core from beliefs, built and off.** With `self.CORE_FROM_BELIEFS` on, the night's
95
+ reflection would state as settled in the core only what a well-backed belief about me or
96
+ us says. It is off (a code tunable, not a setting), so nothing about the core changes in
97
+ this release.
98
+ - **For code that embeds Counterparts:** new exports, nothing removed. `counterparts`
99
+ adds `beliefCoreCandidates`, `coreBeliefFloors`, `coreBeliefMiss`, `coreFromBeliefs` and
100
+ `livedSupportDays`; `counterparts/store` adds `BUILD_LOG_PREFIX`, `BUILD_UNKNOWN`,
101
+ `buildLogKeys`, `parseBuildLog`, `readBuildFrom`, `runningBuild`, `setRunningBuild`,
102
+ `setSettingsInForce`, `settingsInForce` and `withBuild`.
103
+
3
104
  ## 0.3.31 — 2026-10-22
4
105
 
5
106
  This release changes the store's format (v13 to v14), so **after installing, quit the dashboard and every open Claude Code session, then start them again**: one left running from before the update keeps the old code against the upgraded store and stops working on it (the dashboard answers with errors) until it is restarted; an older version that opens the store afresh refuses it plainly. The first open saves a copy of your store before upgrading it, and doctor gains one green line saying what the upgrade did. Going back to 0.3.30 is `counterparts rollback` (it puts that copy back; anything written since is set aside, not deleted), then 0.3.30's install and `counterparts connect` as it prints. What you will see: the dashboard has a subjects tab, a page for every person, project, place and topic your memories name, under a tag cloud. Memories can carry a few tags, and each night tidies them and, in a short separate step on a small model, tags memories that have none and sorts cards into person, project, place or topic. The night's reflection and dream start forming beliefs from real memories; nothing shows them in sessions, the wake or the core yet. Related folders can be one project (`counterparts project join`, or a yes when the morning share asks), and craft learned in one folder takes turns in every folder's "Work here"; work from another project needs a slightly stronger match to come up while you talk. Two fixes: one nightly cycle at a time per store, and a name no longer gets two cards (cards already doubled stay doubled for now). The night's tag work and the beliefs are each one switch in the tunables (`schemas.TAGS_NIGHT`, `schemas.BELIEFS_BIRTH`), both on. Store v14, cache v7 unchanged; no wiring change, so `counterparts connect` is not needed after upgrading.
@@ -67,7 +168,7 @@ This release changes the store's format (v13 to v14), so **after installing, qui
67
168
  belief with a memory that fits, note a memory that goes against one, or write a few new
68
169
  ones, each resting on real memories and starting weak. A belief that met more against
69
170
  it than for it can be let go. Beliefs are still not shown in sessions, the wake or the
70
- core. The owner can turn this off with one setting.
171
+ core. Off: `BELIEFS_BIRTH` in the schemas tunables (a code tunable, not a setting).
71
172
  - **Beliefs from the dream, from the moment, and the owner's word.** The dream may now
72
173
  suggest a belief it sees across several memories; it never makes one, and the morning's
73
174
  reflection keeps it or lets it go. A session can write one in the moment, rarely, from
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "counterparts",
3
- "version": "0.3.31",
3
+ "version": "0.3.33",
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": {
@@ -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,23 @@ 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`.
@@ -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. */