counterparts 0.2.0 → 0.3.0

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 (96) hide show
  1. package/README.md +87 -367
  2. package/docs/QUICKSTART.md +83 -1584
  3. package/docs/README.md +86 -0
  4. package/docs/module-map.md +1 -0
  5. package/package.json +5 -2
  6. package/src/adapters/claude-code/CONTRACT.md +151 -18
  7. package/src/adapters/claude-code/INTERFACE-GAPS.md +138 -2
  8. package/src/adapters/claude-code/NOTES.md +452 -0
  9. package/src/adapters/claude-code/bin/hook.ts +221 -49
  10. package/src/adapters/claude-code/bin/runner.ts +220 -101
  11. package/src/adapters/claude-code/config.ts +202 -279
  12. package/src/adapters/claude-code/doctor.ts +713 -421
  13. package/src/adapters/claude-code/embed-client.ts +165 -557
  14. package/src/adapters/claude-code/hooks.ts +409 -116
  15. package/src/adapters/claude-code/index.ts +7 -59
  16. package/src/adapters/claude-code/page-writer.ts +24 -4
  17. package/src/adapters/claude-code/spawn.ts +6 -7
  18. package/src/adapters/claude-code/transcript.ts +204 -10
  19. package/src/adapters/claude-code/vectors.ts +108 -24
  20. package/src/adapters/cli/CONTRACT.md +123 -3
  21. package/src/adapters/cli/INTERFACE-GAPS.md +45 -2
  22. package/src/adapters/cli/NOTES.md +265 -1
  23. package/src/adapters/cli/bin/counterparts.ts +9 -9
  24. package/src/adapters/cli/commands.ts +494 -436
  25. package/src/adapters/cli/help.ts +22 -27
  26. package/src/adapters/cli/index.ts +0 -2
  27. package/src/adapters/cli/install.ts +102 -89
  28. package/src/adapters/cli/removal.ts +1 -1
  29. package/src/adapters/cli/report.ts +25 -2
  30. package/src/adapters/cli/uninstall.ts +182 -34
  31. package/src/adapters/cli/wire.ts +232 -35
  32. package/src/adapters/dashboard/INTERFACE-GAPS.md +14 -2
  33. package/src/adapters/dashboard/activity.ts +4 -1
  34. package/src/adapters/dashboard/bin/dashboard.ts +1 -1
  35. package/src/adapters/dashboard/registries.ts +16 -1
  36. package/src/adapters/dashboard/resolve.ts +4 -4
  37. package/src/adapters/dashboard/source.ts +8 -2
  38. package/src/adapters/dashboard/web/flow.ts +6 -0
  39. package/src/adapters/dashboard/web/narrate.ts +66 -14
  40. package/src/adapters/dashboard/web/reveal.ts +6 -6
  41. package/src/adapters/dashboard/web/views.ts +12 -4
  42. package/src/adapters/fired.ts +20 -5
  43. package/src/adapters/mcp/CONTRACT.md +73 -1
  44. package/src/adapters/mcp/INTERFACE-GAPS.md +51 -1
  45. package/src/adapters/mcp/NOTES.md +389 -0
  46. package/src/adapters/mcp/bin/serve.ts +24 -35
  47. package/src/adapters/mcp/deliberate.ts +22 -0
  48. package/src/adapters/mcp/index.ts +26 -2
  49. package/src/adapters/mcp/server.ts +425 -49
  50. package/src/adapters/mcp/tools.ts +32 -7
  51. package/src/adapters/mcp/write-up.ts +454 -0
  52. package/src/adapters/sessions.ts +1353 -0
  53. package/src/core/counterpart.ts +32 -8
  54. package/src/core/embed/CONTRACT.md +85 -0
  55. package/src/core/embed/NOTES.md +93 -0
  56. package/src/core/embed/static.ts +622 -0
  57. package/src/core/encode/INTERFACE-GAPS.md +17 -0
  58. package/src/core/encode/NOTES.md +78 -0
  59. package/src/core/encode/secrets.ts +309 -9
  60. package/src/core/handoff/INTERFACE-GAPS.md +13 -1
  61. package/src/core/recall/CONTRACT.md +15 -3
  62. package/src/core/recall/INTERFACE-GAPS.md +94 -0
  63. package/src/core/recall/NOTES.md +49 -0
  64. package/src/core/recall/activate.ts +37 -3
  65. package/src/core/recall/index.ts +22 -1
  66. package/src/core/recall/session.ts +32 -0
  67. package/src/core/recall/tunables.ts +99 -2
  68. package/src/core/remember/CONTRACT.md +51 -7
  69. package/src/core/remember/INTERFACE-GAPS.md +111 -1
  70. package/src/core/remember/NOTES.md +221 -1
  71. package/src/core/remember/index.ts +28 -0
  72. package/src/core/remember/owes.ts +532 -0
  73. package/src/core/remember/owner-strike-seam.ts +34 -2
  74. package/src/core/remember/proposals.ts +25 -6
  75. package/src/core/remember/retention.ts +154 -0
  76. package/src/core/remember/spans.ts +53 -12
  77. package/src/core/remember/tunables.ts +8 -0
  78. package/src/core/remember/write-up-seam.ts +104 -0
  79. package/src/core/self/CONTRACT.md +16 -13
  80. package/src/core/self/INTERFACE-GAPS.md +8 -1
  81. package/src/core/self/NOTES.md +123 -1
  82. package/src/core/self/calendar.ts +81 -0
  83. package/src/core/self/episodes.ts +158 -36
  84. package/src/core/self/identity.ts +2 -2
  85. package/src/core/self/index.ts +88 -20
  86. package/src/core/self/tunables.ts +18 -46
  87. package/src/core/self/writer.ts +58 -9
  88. package/src/core/store/CONTRACT.md +16 -1
  89. package/src/core/store/NOTES.md +293 -0
  90. package/src/core/store/cache.ts +585 -27
  91. package/src/core/store/db.ts +97 -0
  92. package/src/core/store/index.ts +570 -13
  93. package/tools/install-loop/run.sh +52 -71
  94. package/src/adapters/claude-code/credentials.ts +0 -199
  95. package/src/adapters/claude-code/interpret-client.ts +0 -395
  96. package/src/adapters/cli/keys.ts +0 -503
@@ -35,11 +35,10 @@ import {
35
35
  } from "../../scopes.js";
36
36
  import type { ScopeRead, ScopeVerdict } from "../../scopes.js";
37
37
  import { canonicalScope, readSession } from "../../sessions.js";
38
- import { loadConfig } from "../config.js";
38
+ import { loadConfig, withEmbedderDefault } from "../config.js";
39
39
  import type { AdapterConfig } from "../config.js";
40
- import { loadCredentials, permissionWarning } from "../credentials.js";
41
- import type { CredentialLoad } from "../credentials.js";
42
40
  import { HOOKS, openAdapter } from "../index.js";
41
+ import { STOP_HUMAN_LINE } from "../hooks.js";
43
42
  import type { HookInput, HookName } from "../hooks.js";
44
43
  import {
45
44
  CONFIG_REFUSED,
@@ -60,6 +59,12 @@ import { readTranscript } from "../transcript.js";
60
59
  */
61
60
  export const HOST_SESSION_START = "SessionStart";
62
61
 
62
+ /**
63
+ * The same, for the second event that carries one since roadmap E
64
+ * (2026-09-23): the update notice, at a prompt (`hostDelivery`).
65
+ */
66
+ export const HOST_USER_PROMPT_SUBMIT = "UserPromptSubmit";
67
+
63
68
  /**
64
69
  * THE MOST STDOUT THIS HOOK MAY PRINT AS JSON, and why the number is 9,500.
65
70
  *
@@ -82,11 +87,43 @@ export const HOST_SESSION_START = "SessionStart";
82
87
  */
83
88
  export const ENVELOPE_MAX_CHARS = 9500;
84
89
 
90
+ /**
91
+ * HOW A DUE STOP ASK LEAVES THIS PROCESS — ONE shape (owner, 2026-09-24).
92
+ *
93
+ * Exit 0 and one JSON object on stdout:
94
+ *
95
+ * {"systemMessage": <the person's line>,
96
+ * "hookSpecificOutput": {"hookEventName": "Stop", "additionalContext": <the model's ask>}}
97
+ *
98
+ * The host's reference (https://code.claude.com/docs/en/hooks, read
99
+ * 2026-09-24), Stop decision control: `hookSpecificOutput.additionalContext` is
100
+ * "Non-error feedback for Claude. The conversation continues so Claude can act
101
+ * on it, but unlike `decision: "block"` it is shown in the transcript as hook
102
+ * feedback rather than a hook error" — and "It keeps the conversation going
103
+ * through the same loop protections as `decision: "block"`, namely the
104
+ * `stop_hook_active` input and the 8-consecutive-continuation cap". It stands
105
+ * alone: no `decision` beside it.
106
+ *
107
+ * WHY THIS ONE. B1 (2026-09-23) built two shapes behind a `stopAskShape`
108
+ * switch — the JSON `decision: "block"` and the day-0 stderr + exit 2 — and the
109
+ * owner looked at both in a real terminal on 0.3.0: both printed the model's
110
+ * two lines as `Stop hook error: …`, so both read as an error. This is the
111
+ * third route, the one the docs call non-error; the switch and both earlier
112
+ * shapes are gone. A `claude-code.json` that still carries `stopAskShape` is
113
+ * read fine, the key ignored and named among the old settings (`config.ts`).
114
+ *
115
+ * What the person sees is NOT only their own line: the host's 2.1.281 bundle
116
+ * renders an additionalContext on Stop under "Ran 1 stop hook" as
117
+ * `Stop hook feedback: <ask>`, in the notice colour rather than the error one.
118
+ * Quieter, not silent. `../NOTES.md` §"The Stop ask's shapes" has the record.
119
+ */
120
+ export const HOST_STOP = "Stop";
121
+
85
122
  /** The host's event names, mapped to this adapter's. Host trivia, by definition. */
86
123
  const HOST_HOOKS: Record<string, HookName> = {
87
124
  [HOST_SESSION_START]: "session-start",
88
- UserPromptSubmit: "user-prompt-submit",
89
- Stop: "stop",
125
+ [HOST_USER_PROMPT_SUBMIT]: "user-prompt-submit",
126
+ [HOST_STOP]: "stop",
90
127
  SessionEnd: "session-end",
91
128
  PreCompact: "pre-compact",
92
129
  };
@@ -114,22 +151,11 @@ async function readStdin(): Promise<string> {
114
151
  }
115
152
 
116
153
  /**
117
- * The configuration this process runs on, AND the credential load it performed.
118
- *
119
- * The credentials are read HERE, at the process entry point, before anything
120
- * asks for a key: the spawner's `base` env is `process.env`, the two clients
121
- * read `process.env`, and the capability report reads `process.env` — so the gap
122
- * must be filled before any of them look. Measured day 0 of the parallel run:
123
- * this host's hook processes carry neither name, so without this line the worker
124
- * refuses every spawn and the embedder never opens.
125
- *
126
- * `env` is injected so a test can prove the whole path over a fresh object
127
- * instead of mutating the suite's own process.
154
+ * The configuration this process runs on.
128
155
  */
129
156
  export function hostConfig(
130
157
  path = CONFIG_PATH,
131
- env: NodeJS.ProcessEnv = process.env,
132
- ): { config: AdapterConfig; credentials: CredentialLoad; reason: string } {
158
+ ): { config: AdapterConfig; reason: string } {
133
159
  let raw: unknown;
134
160
  try {
135
161
  raw = JSON.parse(readFileSync(path, "utf8"));
@@ -140,9 +166,6 @@ export function hostConfig(
140
166
  }
141
167
  const load = loadConfig(raw);
142
168
  const loaded = load.config;
143
- // Only a configuration we UNDERSTOOD names a file. An unreadable one resolves
144
- // to `{ observer: true }` above, and an observer opens no credential.
145
- const credentials = loadCredentials(loaded.credentialsFile, env);
146
169
  // The data dir is RESOLVED here and carried explicitly, so the spawner has a
147
170
  // value to pin onto the child (scar §2.13). Leaving it undefined would make
148
171
  // the parent and the child resolve it independently, from an environment
@@ -150,9 +173,10 @@ export function hostConfig(
150
173
  // `reason` travels out so the caller can tell "we understood this" from "we
151
174
  // stood down because we did not" — the difference matters only for a config
152
175
  // somebody NAMED (`namedUnreadableRefusal`).
176
+ // THE EMBEDDER DEFAULT (config.ts#resolveEmbedder): an absent block is the
177
+ // local table.
153
178
  return {
154
- config: { ...loaded, dataDir: loaded.dataDir ?? dataDir() },
155
- credentials,
179
+ config: withEmbedderDefault({ ...loaded, dataDir: loaded.dataDir ?? dataDir() }),
156
180
  reason: load.reason,
157
181
  };
158
182
  }
@@ -352,6 +376,8 @@ export function toHookInput(
352
376
  scope,
353
377
  turns: transcript.turns,
354
378
  expansions: transcript.expansions,
379
+ // A named transcript that would not read is not an empty conversation.
380
+ ...(transcriptPath !== undefined && !transcript.ok ? { turnsUnread: true } : {}),
355
381
  // THE PATH ITSELF, beside the parse of it. The delivery check reads the head
356
382
  // of the same file for the attachment `parseTranscript` deliberately skips
357
383
  // (`hooks.ts#checkWakeArrival`), and a parsed turn list cannot answer for
@@ -596,11 +622,17 @@ async function runHook(
596
622
  // for one turn. So: one line, on SessionStart ONLY (UserPromptSubmit fires
597
623
  // every turn and this is a warning, not a nag), AFTER the `off` return above
598
624
  // so that the silence of an off directory stays byte-for-byte.
599
- if (name === "session-start") {
600
- const trouble = describeScopeTrouble(read, scopesPath(choice.path));
601
- if (trouble !== null) process.stderr.write(`${trouble}\n`);
602
- }
603
- const { config: loaded, credentials, reason } = hostConfig(choice.path);
625
+ //
626
+ // AND WHERE THE OWNER CAN SEE IT (I40, 2026-09-23). stderr from a hook that
627
+ // exits 0 goes to the host's debug log and nowhere else, so this line was
628
+ // written for nobody. It now rides the SessionStart `systemMessage` — the
629
+ // channel the doctor notice already uses, and the one the owner's probe
630
+ // measured displaying (`SAYS_SO_HOOKS`) — AFTER that notice and only if it
631
+ // still fits (`hostDelivery`'s priority order). The stderr copy stays, for the
632
+ // debug log and for the morning the envelope has no room for it.
633
+ const trouble = name === "session-start" ? describeScopeTrouble(read, scopesPath(choice.path)) : null;
634
+ if (trouble !== null) process.stderr.write(`${trouble}\n`);
635
+ const { config: loaded, reason } = hostConfig(choice.path);
604
636
  // THE THIRD ARM, and it is answered BEFORE anything reads under `dataDir`: a
605
637
  // named file that parses but whose fields do not typecheck resolves to
606
638
  // observer, and an observer with no `dataDir` reads the DEFAULT store.
@@ -651,23 +683,16 @@ async function runHook(
651
683
  // running on an observer CONFIG are untouched by any of this.
652
684
  const config: AdapterConfig =
653
685
  verdict.mode === "observer" ? { ...loaded, observer: true } : loaded;
654
- // A file the group or the world can read is WARNED about, by mode, and never
655
- // refused: the owner's machine, the owner's call (§5 G2 — a throw here would
656
- // fail the host over a permission bit).
657
- const warning = permissionWarning(config.credentialsFile, credentials);
658
- if (warning !== null) process.stderr.write(`${warning}\n`);
659
686
  const adapter = openAdapter(config, {
660
687
  command: process.execPath,
661
688
  args: ["run", RUNNER_PATH],
662
- credentials,
663
689
  // WHICH FILE THIS RUN READ, carried into the adapter so it can be RECORDED:
664
690
  // a hook cannot print to the owner (its stdout is the model's context), so
665
691
  // the answer goes into the session registry record and the event ring
666
692
  // instead. It is also pinned onto the worker's environment, so the child
667
693
  // reads the same file its parent did rather than resolving one of its own.
668
694
  configPath: choice.path,
669
- // The verdict travels IN, for the same reason the credentials do: it is a
670
- // fact about this process's startup, decided before anything opened, and
695
+ // The verdict travels IN: it is a fact about this process's startup, decided before anything opened, and
671
696
  // the adapter's jobs with it are to record it and — when it is `unset` — to
672
697
  // ask the question once (G41).
673
698
  scope: verdict,
@@ -692,8 +717,21 @@ async function runHook(
692
717
  // user-prompt-submit: the owner asked for a warning, not a nag. `notice()`
693
718
  // is red-only, bounded, and returns null rather than throwing, so the line
694
719
  // below cannot change what the wake does on a healthy day.
695
- const notice = name === "session-start" ? adapter.notice(input) : null;
696
- const delivery = hostDelivery(name, result, payload, notice);
720
+ // In PRIORITY order (review M1): the doctor notice first, because it has no
721
+ // other route to the owner; the registry line second, because it also has
722
+ // stderr. A line that does not fit is left out, never the wake.
723
+ //
724
+ // AND THE UPDATE NOTICE AT A PROMPT (roadmap E, 2026-09-23), fail-open
725
+ // (`deliverTurn`): once per session, when the MCP server this session talks
726
+ // to runs an older build than this installed one.
727
+ const delivery = deliverTurn(
728
+ name,
729
+ result,
730
+ payload,
731
+ name === "session-start" ? [adapter.notice(input), trouble] : null,
732
+ adapter,
733
+ input,
734
+ );
697
735
  // A notice the envelope could not carry leaves a row rather than nothing:
698
736
  // "the terminal said nothing" and "there was nothing to say" are different
699
737
  // facts about the same morning (scar §2.4).
@@ -707,11 +745,79 @@ async function runHook(
707
745
  }
708
746
  if (delivery.stderr.length > 0) process.stderr.write(delivery.stderr);
709
747
  process.exitCode = delivery.exitCode;
748
+ // EVERYTHING BELOW IS AFTER THE WRITE, on purpose (#187 re-review, N4): the
749
+ // wake and the turn's recall are already out, so nothing here can cost
750
+ // them. A SESSION THAT OPENS is stamped with the build that saw it open —
751
+ // never a compaction, which is the same session and server carrying on.
752
+ stampWhenOpened(payload, () => adapter.stampOpened(input));
753
+ // The update notice's decisions, where a person can find them (the host's
754
+ // debug log): its ring rows die with this process otherwise. Written only
755
+ // on a turn that had something to decide — due, shown, dropped, failed.
756
+ if (name === "user-prompt-submit") {
757
+ for (const e of [...adapter.events("adapter.update.notice"), ...adapter.events("adapter.notice.dropped")]) {
758
+ process.stderr.write(`[counterparts] ${e.name}: ${JSON.stringify(e.data)}\n`);
759
+ }
760
+ }
710
761
  } finally {
711
762
  adapter.counterpart.close();
712
763
  }
713
764
  }
714
765
 
766
+ /** The two adapter doors `deliverTurn` needs — structural, so a test can
767
+ * hand it doors that throw. */
768
+ export interface UpdateNoticeDoors {
769
+ updateNotice(input: HookInput): string | null;
770
+ markUpdateNotice(input: HookInput): boolean;
771
+ }
772
+
773
+ /**
774
+ * THIS EVENT'S OUTPUT, WITH THE UPDATE NOTICE FOLDED IN FAIL-OPEN (roadmap E;
775
+ * #187 re-review, N4).
776
+ *
777
+ * The plain delivery is computed first and is the answer whenever anything
778
+ * about the notice goes wrong: a door that throws, a mark that will not land.
779
+ * The notice is MARKED only once it is certainly leaving — after the envelope
780
+ * is known to carry it — and SHOWN only if the mark landed, so it never repeats
781
+ * and is never marked-but-lost; a turn whose recall leaves no room drops it,
782
+ * marks nothing, and tries again next turn. Every event but
783
+ * `user-prompt-submit` is exactly `hostDelivery`.
784
+ */
785
+ export function deliverTurn(
786
+ name: HookName,
787
+ result: { injection: string | null; ask: string | null },
788
+ payload: Record<string, unknown>,
789
+ sessionStartNotices: readonly (string | null)[] | null,
790
+ doors: UpdateNoticeDoors,
791
+ input: HookInput,
792
+ ): Delivery {
793
+ const plain = hostDelivery(name, result, payload, sessionStartNotices);
794
+ if (name !== "user-prompt-submit") return plain;
795
+ try {
796
+ const update = doors.updateNotice(input);
797
+ if (update === null) return plain;
798
+ const carried = hostDelivery(name, result, payload, update);
799
+ if (carried.dropped !== null) return carried;
800
+ return doors.markUpdateNotice(input) ? carried : plain;
801
+ } catch {
802
+ return plain;
803
+ }
804
+ }
805
+
806
+ /**
807
+ * SessionStart's stamp on a session that OPENS, and nothing else: run AFTER the
808
+ * wake is written (`main`), and swallowed if it throws — the stamp is
809
+ * bookkeeping for the update notice, and a failed one costs that notice its
810
+ * precision, never the wake (#187 re-review, N4).
811
+ */
812
+ export function stampWhenOpened(payload: Record<string, unknown>, stamp: () => unknown): void {
813
+ if (!opensASession(payload)) return;
814
+ try {
815
+ stamp();
816
+ } catch {
817
+ /* bookkeeping; see above */
818
+ }
819
+ }
820
+
715
821
  /**
716
822
  * How each hook's output reaches the model on THIS host — measured, not
717
823
  * assumed (scar §2.18), on day 0 of the parallel run (2026-09-03):
@@ -725,6 +831,10 @@ async function runHook(
725
831
  * as "Stop hook feedback" and lets it continue. The host then re-fires Stop
726
832
  * with `stop_hook_active: true`; that re-fire must ask NOTHING or the ask
727
833
  * loops forever (v1's anti-loop, kept here for the same reason).
834
+ * **Since 2026-09-24 the ask leaves by the host's documented NON-ERROR
835
+ * route instead** (`HOST_STOP` above): exit 0, the model's ask as
836
+ * `hookSpecificOutput.additionalContext`, one line for the person as
837
+ * `systemMessage`. Same continuation, same re-fire, same refusal of it.
728
838
  *
729
839
  * **The fourth channel, added 2026-09-14 for I32: `systemMessage`.** Documented
730
840
  * at https://code.claude.com/docs/en/hooks (formerly
@@ -747,8 +857,10 @@ async function runHook(
747
857
  export interface Delivery {
748
858
  readonly stdout: string;
749
859
  readonly stderr: string;
750
- readonly exitCode: 0 | 2;
751
- /** Non-null when the notice was dropped to keep the wake whole. */
860
+ /** Always 0 since 2026-09-24: no event leaves by exit 2 any more. */
861
+ readonly exitCode: 0;
862
+ /** Non-null when a notice was left out to keep the wake whole — all of them,
863
+ * or (with several) the lower ones that no longer fit. */
752
864
  readonly dropped: { readonly noticeChars: number; readonly envelopeChars: number; readonly limitChars: number } | null;
753
865
  }
754
866
 
@@ -756,27 +868,73 @@ export function hostDelivery(
756
868
  name: HookName,
757
869
  result: { injection: string | null; ask: string | null },
758
870
  payload: Record<string, unknown>,
759
- /** The owner-facing warning, or null. Only SessionStart carries one. */
760
- notice: string | null = null,
871
+ /**
872
+ * The owner-facing line(s), or null: SessionStart's doctor notice and
873
+ * registry line, UserPromptSubmit's update notice (roadmap E); every other
874
+ * event ignores it. At SessionStart a LIST is a priority order (review M1):
875
+ * each is added only while the envelope still fits, so a lower line can never
876
+ * cost a higher one its place. At a prompt the lines are ALL OR NOTHING —
877
+ * joined into one `systemMessage`, or all dropped — which is what lets
878
+ * `deliverTurn` mark only an envelope that carried them; today there is one.
879
+ */
880
+ notice: string | null | readonly (string | null)[] = null,
761
881
  ): Delivery {
762
882
  const ask = result.ask !== null && result.ask.length > 0 ? result.ask : null;
763
883
  if (name !== "stop") {
764
884
  const out = [result.injection ?? "", ask ?? ""].filter((s) => s.length > 0).join("\n\n");
765
- if (name === "session-start" && notice !== null && notice.length > 0) {
766
- const envelope = JSON.stringify({
767
- systemMessage: notice,
768
- hookSpecificOutput: { hookEventName: HOST_SESSION_START, additionalContext: out },
769
- });
885
+ const notices = (typeof notice === "string" || notice === null ? [notice] : notice).filter(
886
+ (n): n is string => n !== null && n.length > 0,
887
+ );
888
+ if (name === "session-start" && notices.length > 0) {
889
+ const envelopeOf = (message: string): string =>
890
+ JSON.stringify({
891
+ systemMessage: message,
892
+ hookSpecificOutput: { hookEventName: HOST_SESSION_START, additionalContext: out },
893
+ });
770
894
  // THE WAKE WINS. Over `ENVELOPE_MAX_CHARS` the host would replace this
771
895
  // whole string with a preview, the JSON would stop parsing, and the
772
896
  // session would start with no memory at all — a worse outcome than not
773
897
  // seeing the warning, which `counterparts doctor` prints on request.
898
+ // And the notices go in in the order given, each only if it still fits.
899
+ const kept: string[] = [];
900
+ const left: string[] = [];
901
+ for (const n of notices) {
902
+ if (envelopeOf([...kept, n].join("\n")).length <= ENVELOPE_MAX_CHARS) kept.push(n);
903
+ else left.push(n);
904
+ }
905
+ const dropped =
906
+ left.length === 0
907
+ ? null
908
+ : {
909
+ noticeChars: left.join("\n").length,
910
+ envelopeChars: envelopeOf(notices.join("\n")).length,
911
+ limitChars: ENVELOPE_MAX_CHARS,
912
+ };
913
+ if (kept.length === 0) return { stdout: out, stderr: "", exitCode: 0, dropped };
914
+ return { stdout: envelopeOf(kept.join("\n")), stderr: "", exitCode: 0, dropped };
915
+ }
916
+ // THE UPDATE NOTICE, AT A PROMPT (roadmap E, 2026-09-23) — the same
917
+ // envelope and the same rule: the turn's recall rides whole in
918
+ // `additionalContext` or the notice waits. A turn with no recall prints the
919
+ // `systemMessage` alone rather than an empty context field. A prompt with
920
+ // no notice prints what it always has — plain text, or nothing. More than
921
+ // one line would be JOINED into the one `systemMessage` an object carries,
922
+ // never one replacing another, and dropped all together or not at all —
923
+ // not SessionStart's priority order; today the update notice is the only one.
924
+ if (name === "user-prompt-submit" && notices.length > 0) {
925
+ const message = notices.join("\n");
926
+ const envelope = JSON.stringify({
927
+ systemMessage: message,
928
+ ...(out.length === 0
929
+ ? {}
930
+ : { hookSpecificOutput: { hookEventName: HOST_USER_PROMPT_SUBMIT, additionalContext: out } }),
931
+ });
774
932
  if (envelope.length > ENVELOPE_MAX_CHARS) {
775
933
  return {
776
934
  stdout: out,
777
935
  stderr: "",
778
936
  exitCode: 0,
779
- dropped: { noticeChars: notice.length, envelopeChars: envelope.length, limitChars: ENVELOPE_MAX_CHARS },
937
+ dropped: { noticeChars: message.length, envelopeChars: envelope.length, limitChars: ENVELOPE_MAX_CHARS },
780
938
  };
781
939
  }
782
940
  return { stdout: envelope, stderr: "", exitCode: 0, dropped: null };
@@ -788,7 +946,21 @@ export function hostDelivery(
788
946
  if (payload["stop_hook_active"] === true || ask === null) {
789
947
  return { stdout: "", stderr: "", exitCode: 0, dropped: null };
790
948
  }
791
- return { stdout: "", stderr: ask, exitCode: 2, dropped: null };
949
+ // EXIT 0, and NO `decision`: `additionalContext` on Stop continues the turn on
950
+ // its own, as non-error feedback (the docblock at `HOST_STOP`). Exit 2 would
951
+ // make STDERR a blocking error again, and a `decision: "block"` beside it
952
+ // would bring back the `Stop hook error:` line this route exists to avoid.
953
+ // One line, no trailing newline, so the whole of stdout is the object. The
954
+ // ask is ~430 characters, far inside the host's 10,000-character cap.
955
+ return {
956
+ stdout: JSON.stringify({
957
+ systemMessage: STOP_HUMAN_LINE,
958
+ hookSpecificOutput: { hookEventName: HOST_STOP, additionalContext: ask },
959
+ }),
960
+ stderr: "",
961
+ exitCode: 0,
962
+ dropped: null,
963
+ };
792
964
  }
793
965
 
794
966
  /** True only when this file is the process entry point — so a test may import