counterparts 0.3.12 → 0.3.13

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 (116) hide show
  1. package/CHANGELOG.md +184 -0
  2. package/docs/module-map.md +1 -1
  3. package/package.json +1 -1
  4. package/src/adapters/claude-code/CONTRACT.md +36 -10
  5. package/src/adapters/claude-code/INTERFACE-GAPS.md +116 -16
  6. package/src/adapters/claude-code/NOTES.md +131 -0
  7. package/src/adapters/claude-code/bin/hook.ts +35 -2
  8. package/src/adapters/claude-code/doctor.ts +155 -21
  9. package/src/adapters/claude-code/hooks.ts +49 -7
  10. package/src/adapters/claude-code/index.ts +11 -0
  11. package/src/adapters/claude-code/night-run.ts +133 -12
  12. package/src/adapters/claude-code/transcript.ts +268 -1
  13. package/src/adapters/cli/CONTRACT.md +5 -0
  14. package/src/adapters/cli/INTERFACE-GAPS.md +8 -4
  15. package/src/adapters/cli/NOTES.md +111 -0
  16. package/src/adapters/cli/commands.ts +65 -14
  17. package/src/adapters/cli/dream-core.ts +57 -42
  18. package/src/adapters/cli/export.ts +320 -21
  19. package/src/adapters/cli/index.ts +1 -0
  20. package/src/adapters/cli/install.ts +39 -7
  21. package/src/adapters/cli/mechanisms.ts +7 -1
  22. package/src/adapters/cli/uninstall.ts +13 -5
  23. package/src/adapters/cli/wire.ts +189 -63
  24. package/src/adapters/dashboard/INTERFACE-GAPS.md +10 -1
  25. package/src/adapters/dashboard/NOTES.md +79 -0
  26. package/src/adapters/dashboard/registries.ts +10 -2
  27. package/src/adapters/dashboard/web/README.md +19 -14
  28. package/src/adapters/dashboard/web/actions.ts +23 -1
  29. package/src/adapters/dashboard/web/flow.ts +4 -1
  30. package/src/adapters/dashboard/web/lanes.ts +3 -0
  31. package/src/adapters/dashboard/web/narrate.ts +30 -2
  32. package/src/adapters/dashboard/web/pages/flow/sections/fired.js +1 -0
  33. package/src/adapters/dashboard/web/pages/memories/memories.css +17 -4
  34. package/src/adapters/dashboard/web/pages/memories/row.js +37 -21
  35. package/src/adapters/dashboard/web/pages/memories/sections/search.js +279 -60
  36. package/src/adapters/dashboard/web/pages/memories/state.js +2 -1
  37. package/src/adapters/dashboard/web/server.ts +0 -5
  38. package/src/adapters/dashboard/web/shared/memory-marks.css +7 -0
  39. package/src/adapters/dashboard/web/shared/memory-marks.js +33 -0
  40. package/src/adapters/dashboard/web/shared/memory-modal.js +5 -3
  41. package/src/adapters/dashboard/web/views/health.ts +1 -1
  42. package/src/adapters/dashboard/web/views/search.ts +4 -45
  43. package/src/adapters/dashboard/web/views.ts +2 -2
  44. package/src/adapters/fired.ts +410 -25
  45. package/src/adapters/host-wiring.ts +300 -0
  46. package/src/adapters/lifecycle.ts +14 -0
  47. package/src/adapters/log/index.ts +2 -0
  48. package/src/adapters/mcp/CONTRACT.md +33 -3
  49. package/src/adapters/mcp/INTERFACE-GAPS.md +24 -2
  50. package/src/adapters/mcp/NOTES.md +136 -0
  51. package/src/adapters/mcp/bin/serve.ts +30 -0
  52. package/src/adapters/mcp/facts.ts +13 -1
  53. package/src/adapters/mcp/meaning.ts +208 -13
  54. package/src/adapters/mcp/server.ts +87 -15
  55. package/src/adapters/mcp/stdio.ts +3 -1
  56. package/src/adapters/mcp/stood-down.ts +51 -0
  57. package/src/adapters/mcp/tools.ts +27 -7
  58. package/src/adapters/plugin-run.sh +133 -0
  59. package/src/adapters/plugin.ts +329 -0
  60. package/src/core/associate/CONTRACT.md +2 -1
  61. package/src/core/associate/INTERFACE-GAPS.md +6 -1
  62. package/src/core/associate/NOTES.md +45 -0
  63. package/src/core/briefing.ts +12 -3
  64. package/src/core/contradictions.ts +184 -0
  65. package/src/core/counterpart.ts +451 -18
  66. package/src/core/dream/CONTRACT.md +5 -2
  67. package/src/core/dream/INTERFACE-GAPS.md +29 -6
  68. package/src/core/dream/NOTES.md +21 -0
  69. package/src/core/dream/index.ts +33 -1
  70. package/src/core/dream/reflect.ts +20 -5
  71. package/src/core/encode/INTERFACE-GAPS.md +3 -1
  72. package/src/core/fit/INTERFACE-GAPS.md +8 -2
  73. package/src/core/fit/NOTES.md +5 -2
  74. package/src/core/fit/index.ts +4 -1
  75. package/src/core/handoff/CONTRACT.md +37 -2
  76. package/src/core/handoff/INTERFACE-GAPS.md +10 -0
  77. package/src/core/handoff/NOTES.md +66 -0
  78. package/src/core/handoff/index.ts +214 -12
  79. package/src/core/mint.ts +8 -2
  80. package/src/core/physics/CONTRACT.md +11 -1
  81. package/src/core/physics/NOTES.md +30 -0
  82. package/src/core/physics/index.ts +26 -4
  83. package/src/core/prospective/CONTRACT.md +45 -6
  84. package/src/core/prospective/INTERFACE-GAPS.md +4 -0
  85. package/src/core/prospective/NOTES.md +138 -0
  86. package/src/core/prospective/derive.ts +33 -5
  87. package/src/core/prospective/index.ts +90 -5
  88. package/src/core/prospective/windows.ts +72 -1
  89. package/src/core/recall/CONTRACT.md +6 -2
  90. package/src/core/recall/INTERFACE-GAPS.md +28 -4
  91. package/src/core/recall/NOTES.md +57 -1
  92. package/src/core/recall/probe.ts +58 -0
  93. package/src/core/recall/session.ts +27 -3
  94. package/src/core/recall/time-ask.ts +116 -18
  95. package/src/core/remember/CONTRACT.md +4 -1
  96. package/src/core/remember/INTERFACE-GAPS.md +9 -1
  97. package/src/core/remember/proposals.ts +38 -5
  98. package/src/core/revision.ts +5 -0
  99. package/src/core/schemas/CONTRACT.md +13 -1
  100. package/src/core/schemas/INTERFACE-GAPS.md +20 -2
  101. package/src/core/schemas/NOTES.md +127 -0
  102. package/src/core/schemas/types.ts +2 -0
  103. package/src/core/self/CONTRACT.md +15 -4
  104. package/src/core/self/INTERFACE-GAPS.md +7 -2
  105. package/src/core/self/NOTES.md +49 -0
  106. package/src/core/self/briefing.ts +12 -2
  107. package/src/core/self/index.ts +82 -8
  108. package/src/core/self/page.ts +88 -0
  109. package/src/core/sleep/INTERFACE-GAPS.md +22 -3
  110. package/src/core/sleep/NOTES.md +11 -0
  111. package/src/core/sleep/prune.ts +6 -2
  112. package/src/core/store/NOTES.md +14 -0
  113. package/src/core/store/index.ts +107 -0
  114. package/src/core/time.ts +152 -0
  115. package/tools/install-loop/run.sh +48 -12
  116. package/src/adapters/dashboard/web/pages/memories/fold.js +0 -53
@@ -639,6 +639,12 @@ export class ClaudeCodeAdapter extends Lifecycle {
639
639
  // core change (`AdapterDurableEventName`) and this fact is about
640
640
  // exactly the moment that row describes.
641
641
  scopeRegistry: this.scopeTrouble,
642
+ // WHETHER ANYBODY COULD BE TOLD ANYTHING HERE (review of #337): the
643
+ // same test that decides whether this session is handed plain
644
+ // reminders. The `fired` report's plain-due check reads it, so a day
645
+ // only the headless run or `claude -p` came is not a day a reminder
646
+ // could have been said.
647
+ interactive: isInteractive(input) && input.nightRun !== true,
642
648
  });
643
649
  // THE QUESTION RIDES BESIDE THE WAKE, NEVER INSIDE IT, and only if it
644
650
  // FITS.
@@ -1067,14 +1073,16 @@ export class ClaudeCodeAdapter extends Lifecycle {
1067
1073
 
1068
1074
  /**
1069
1075
  * THE HAND-BACK OF A HEADLESS RUN THAT ENDED — the dream's line, then the
1070
- * morning share if there is one — claimed once across every session. Empty
1071
- * when there is nothing to hand back, or another prompt already did.
1076
+ * morning share if there is one, then the host's cut if the run's transcript
1077
+ * showed one (2026-10-09) — claimed once across every session. Empty when
1078
+ * there is nothing to hand back, or another prompt already did.
1072
1079
  */
1073
1080
  private nightHandBack(input: HookInput): string[] {
1074
1081
  const dreams = this.counterpart.dreams;
1075
1082
  const night = dreams.nightRun();
1076
1083
  if (night === null || night.state === "started" || night.state === "could-not-start") return [];
1077
- if (night.dream === null && night.reflection === null) return [];
1084
+ // A run the host cut is told even when it journaled nothing: the cut may be why.
1085
+ if (night.dream === null && night.reflection === null && (night.spills ?? 0) === 0) return [];
1078
1086
  // A READ on the per-prompt path once it is handed: nothing is written again.
1079
1087
  if (night.handedAt !== undefined) return [];
1080
1088
  const claimed = dreams.claimNightHandBack(night.run, input.sessionId);
@@ -1089,6 +1097,8 @@ export class ClaudeCodeAdapter extends Lifecycle {
1089
1097
  const share = this.counterpart.reflections.carryLine({ session: input.sessionId, reflection: night.reflection });
1090
1098
  if (share !== null) out.push(share);
1091
1099
  }
1100
+ const spill = dreams.nightSpillLine(night);
1101
+ if (spill !== null) out.push(spill);
1092
1102
  this.emit("adapter.night.handed", { run: night.run, lines: out.length });
1093
1103
  return out;
1094
1104
  }
@@ -1210,6 +1220,14 @@ export class ClaudeCodeAdapter extends Lifecycle {
1210
1220
  // withholds is the ASK, which is delivery: an ask from a system the
1211
1221
  // owner is not talking to today is exactly the double-voice G3 forbids.
1212
1222
  const deliver = this.deliveryVerdict("stop", input);
1223
+ // THE WAKE'S ARRIVAL, closed here when the first prompt could not
1224
+ // (2026-10-08): the host writes the transcript only after that prompt, so
1225
+ // the end of the first turn is where every session can be read. Muted
1226
+ // sessions are not checked, for the prompt's reason. The check marks a
1227
+ // record that exists and never makes one; a session the boundary above
1228
+ // just sealed (no record before it) has one with no sentinel, and says
1229
+ // `no-wake-expected` — what its second prompt used to say.
1230
+ if (deliver) this.checkWakeArrival(input, { final: true });
1213
1231
  // THE AUTHORED FRONT DOOR, first: the experiencer writes its own memories
1214
1232
  // while it still has the pen, and the sweep the worker spawns below is
1215
1233
  // only the fallback for the day nobody got to (contract §4). The ask goes
@@ -1340,14 +1358,26 @@ export class ClaudeCodeAdapter extends Lifecycle {
1340
1358
 
1341
1359
  /**
1342
1360
  * DID THE WAKE THIS SESSION COMPOSED REACH THE SESSION? — once, at the first
1343
- * prompt, and never again for this session.
1361
+ * prompt or the end of the first turn, and never again for this session.
1344
1362
  *
1345
1363
  * **Why here and not at the end.** Nothing inside the SessionStart hook can
1346
1364
  * know what the host did with its return value, and SessionEnd's hooks share
1347
- * 1.5 s between them. The first `UserPromptSubmit` is the earliest moment the
1348
- * host has written the record of its own injection, and it is once per session
1365
+ * 1.5 s between them. The first `UserPromptSubmit` was the earliest moment the
1366
+ * host had written the record of its own injection, and it is once per session
1349
1367
  * rather than once per turn.
1350
1368
  *
1369
+ * **And at the first Stop when the prompt was too early (2026-10-08).** Since
1370
+ * about 09-25 Claude Code creates the transcript only after the first prompt
1371
+ * is handled, so the prompt found no file and nearly every session's row said
1372
+ * `not-found` / `absent` — about a file that existed a moment later. A wake was
1373
+ * expected and there is no file: the prompt records nothing and leaves the
1374
+ * question open, and the next prompt or the first Stop (`final`) asks again.
1375
+ * The Stop is the bound: by the end of a turn the host has written the file,
1376
+ * so one that is still absent there will not appear, and the row says
1377
+ * `absent` once rather than the session asking at every turn. The Stop has
1378
+ * already read the whole transcript to capture the turn; this head read is
1379
+ * 256 KiB at most beside it.
1380
+ *
1351
1381
  * **What it reads.** The head of the host's transcript, bounded
1352
1382
  * (`transcript.ts#readWakeArrival`): this package's SessionStart attachment
1353
1383
  * carries what the hook printed beside what the host says it injected, and the
@@ -1364,7 +1394,7 @@ export class ClaudeCodeAdapter extends Lifecycle {
1364
1394
  * retroactive-capture guard reads that same absence to detect, and a record
1365
1395
  * written from here would take that evidence away.
1366
1396
  */
1367
- private checkWakeArrival(input: HookInput): void {
1397
+ private checkWakeArrival(input: HookInput, opts: { readonly final?: boolean } = {}): void {
1368
1398
  if (this.observer) return;
1369
1399
  if (input.sessionId.length === 0) return;
1370
1400
  const started = this.nowFn();
@@ -1382,9 +1412,21 @@ export class ClaudeCodeAdapter extends Lifecycle {
1382
1412
  // the row says so rather than reporting a wake that was never composed.
1383
1413
  const arrival =
1384
1414
  expected === null ? NO_ARRIVAL : readWakeArrival(input.transcriptPath, { expect: expected });
1415
+ // Not written yet: no row and no mark, so the next prompt or the Stop
1416
+ // reads again (above). The ring says it waited, for whoever debugs it.
1417
+ if (expected !== null && arrival.reason === "absent" && opts.final !== true) {
1418
+ this.emit("adapter.wake.check.deferred", {
1419
+ transcript: arrival.reason,
1420
+ pathGiven: input.transcriptPath !== undefined,
1421
+ elapsedMs: this.nowFn() - started,
1422
+ });
1423
+ return;
1424
+ }
1385
1425
  const outcome = wakeOutcome(expected, arrival);
1386
1426
  this.record(WAKE_DELIVERED_EVENT, input, {
1387
1427
  outcome,
1428
+ // Which hook answered: the first prompt, or the end of the first turn.
1429
+ checkedAt: opts.final === true ? "stop" : "prompt",
1388
1430
  // `ok` and `delivered` say the same thing under the two names this row's
1389
1431
  // readers already look for.
1390
1432
  ok: outcome === "delivered",
@@ -95,6 +95,7 @@ export {
95
95
  planNightChild,
96
96
  planNightRunner,
97
97
  readKind,
98
+ readNightSpills,
98
99
  runNight,
99
100
  } from "./night-run.js";
100
101
  export type { NightChildPlan, NightKind, NightRunInput, NightRunnerPlan, NightStarter } from "./night-run.js";
@@ -114,19 +115,29 @@ export type { BackfillReport, LagReport } from "./vectors.js";
114
115
 
115
116
  export {
116
117
  COUNTERPARTS_HOOK_COMMAND,
118
+ COUNTERPARTS_TOOL,
117
119
  FOREIGN_MARKERS,
118
120
  NO_ARRIVAL,
121
+ SPILL_MAX_BYTES,
119
122
  WAKE_HEAD_MAX_BYTES,
120
123
  WAKE_HEAD_MAX_LINES,
121
124
  attributePeers,
122
125
  classifyBlock,
126
+ hostConfigDir,
127
+ hostTranscriptPath,
128
+ parseToolSpills,
123
129
  parseTranscript,
130
+ readToolSpills,
124
131
  readTranscript,
125
132
  readWakeArrival,
133
+ spillOf,
126
134
  } from "./transcript.js";
127
135
  export type {
128
136
  PeerAttribution,
129
137
  SentinelSighting,
138
+ Spill,
139
+ SpillShape,
140
+ ToolSpills,
130
141
  TranscriptRead,
131
142
  WakeArrival,
132
143
  } from "./transcript.js";
@@ -37,7 +37,9 @@
37
37
  * - the child starts in a NEUTRAL directory, the store's own, so no
38
38
  * project's CLAUDE.md, hooks or MCP servers load; the launching session's
39
39
  * directory reaches the MCP server as its pinned scope instead;
40
- * - `--max-turns` bounds it beside the watchdog.
40
+ * - `--max-turns` bounds it beside the watchdog;
41
+ * - `--session-id` names its session with a UUID this process chose
42
+ * (2026-10-09), so its transcript can be read once it exits.
41
43
  * What is left and not allowed stops at a prompt nobody can answer, which is
42
44
  * the direction this should fail in. The parent's stance variables are
43
45
  * removed from its environment; this package's own values are written last.
@@ -53,8 +55,9 @@
53
55
  * hook's, so no corroboration is lost. The child starts in the STORE's own
54
56
  * directory, a neutral one (owner decision B, `planNightChild`), without the
55
57
  * host's `CLAUDE_PROJECT_DIR`; the session's directory reaches it only as
56
- * `COUNTERPARTS_SCOPE`. The child's own session id — minted by the host after this process
57
- * is gone — is flagged QUIET (`NIGHT_RUN_ENV`): our hooks inside it capture
58
+ * `COUNTERPARTS_SCOPE`. The child's own session id — chosen after the hook is
59
+ * gone, by the waiting process (`--session-id`, since 2026-10-09; the host
60
+ * minted it before) — is flagged QUIET (`NIGHT_RUN_ENV`): our hooks inside it capture
58
61
  * nothing and ask nothing (`hooks.ts`), so it owes no write-up either.
59
62
  *
60
63
  * Proved against a STUB executable only. What a real machine must show — the
@@ -62,9 +65,10 @@
62
65
  * server binding as above, the host not refusing a nested `claude` — is
63
66
  * written in the PR, not claimed here.
64
67
  */
68
+ import { randomUUID } from "node:crypto";
65
69
  import { fileURLToPath } from "node:url";
66
70
 
67
- import { Counterpart } from "../../core/counterpart.js";
71
+ import { Counterpart, MCP_SPILLED_EVENT } from "../../core/counterpart.js";
68
72
  import type { CounterpartEvent } from "../../core/counterpart.js";
69
73
  import type { NightPart, NightRun } from "../../core/dream/index.js";
70
74
  import { CONFIG_ENV as CONFIG_PATH_ENV } from "../config-path.js";
@@ -77,6 +81,8 @@ import { TUNABLES } from "../config.js";
77
81
  import type { AdapterConfig } from "../config.js";
78
82
  import { DEFAULT_HOST_COMMAND, KILL_GRACE_MS, PERMISSION_MODE, REAP_GRACE_MS, startChild } from "./child.js";
79
83
  import { CATCH_UP_TOOLS, runCatchUp } from "./night-catch-up.js";
84
+ import { hostConfigDir, hostTranscriptPath, readToolSpills } from "./transcript.js";
85
+ import type { ToolSpills } from "./transcript.js";
80
86
  import type { ChildPlan, ChildResult } from "./child.js";
81
87
  import { DATA_DIR_ENV, SCOPE_ENV, SESSION_ENV, WATCHDOG_ENV } from "../spawn.js";
82
88
  import type { SpawnPlan } from "../spawn.js";
@@ -177,7 +183,16 @@ export function nightMaxTurns(config: AdapterConfig): number {
177
183
  * scope from it before its own directory) and the markers that say "inside a
178
184
  * Claude Code session" (a host may refuse to start a session inside another).
179
185
  */
180
- export const HOST_SESSION_ENV = ["CLAUDE_PROJECT_DIR", "CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT"] as const;
186
+ export const HOST_SESSION_ENV = [
187
+ "CLAUDE_PROJECT_DIR",
188
+ "CLAUDECODE",
189
+ "CLAUDE_CODE_ENTRYPOINT",
190
+ // The plugin's own two (2026-10-09, `adapters/plugin.ts`): a hook the plugin
191
+ // launched carries them, and the child's hooks and server must learn whether
192
+ // THEY are the plugin's from the child's host, never from this one.
193
+ "CLAUDE_PLUGIN_ROOT",
194
+ "CLAUDE_PLUGIN_DATA",
195
+ ] as const;
181
196
 
182
197
  export type NightKind = { readonly kind: "night" } | { readonly kind: "reflection"; readonly dream: string };
183
198
 
@@ -285,6 +300,12 @@ export interface NightChildInput {
285
300
  /** Its turn ceiling and watchdog; absent, the night's own (`nightMaxTurns`, `nightTimeoutMs`). */
286
301
  readonly maxTurns?: number;
287
302
  readonly timeoutMs?: number;
303
+ /**
304
+ * The child's OWN session id, a fresh UUID (`--session-id`), so its
305
+ * transcript can be found by name once it exits (2026-10-09, U14 item 3).
306
+ * Absent, the host mints one (the catch-up child).
307
+ */
308
+ readonly hostSession?: string;
288
309
  }
289
310
 
290
311
  /**
@@ -318,6 +339,7 @@ export function planNightChild(input: NightChildInput): NightChildPlan {
318
339
  }),
319
340
  "--strict-mcp-config",
320
341
  ...(model === undefined ? [] : ["--model", model]),
342
+ ...(input.hostSession === undefined || input.hostSession.length === 0 ? [] : ["--session-id", input.hostSession]),
321
343
  ];
322
344
  const plan = (ok: boolean, reason: NightChildRefusal | "ready"): NightChildPlan => ({
323
345
  ok,
@@ -378,6 +400,12 @@ export interface NightRunInput {
378
400
  readonly start?: NightStarter;
379
401
  /** TESTS ONLY: the catch-up child's starter (`night-catch-up.ts`); absent, a real child. */
380
402
  readonly startCatchUp?: NightStarter;
403
+ /**
404
+ * Where the host keeps its sessions (`<dir>/projects/…`), for the read of
405
+ * the child's transcript; absent, the child's `CLAUDE_CONFIG_DIR` or
406
+ * `~/.claude` (`transcript.ts#hostConfigDir`).
407
+ */
408
+ readonly hostConfigDir?: string;
381
409
  readonly now?: () => number;
382
410
  /** The process log's (`adapters/log/`), for what the store does not write. */
383
411
  readonly onEvent?: (e: CounterpartEvent) => void;
@@ -387,7 +415,11 @@ export interface NightRunInput {
387
415
  * RUN THE NIGHT, headless: compose, start, wait, record. Never throws; the
388
416
  * record it returns is the one it wrote. What happened is read from the exit
389
417
  * and from the STORE (a dream journaled, a reflection finished) — never from
390
- * the child's output, which is prose nobody here should parse.
418
+ * the child's output, which is prose nobody here should parse. One thing more
419
+ * is read from the HOST's record of the child, its transcript (2026-10-09):
420
+ * whether the host cut any of our tool results to a preview — markers the host
421
+ * writes in place of a result, matched there and nowhere else
422
+ * (`transcript.ts#readToolSpills`).
391
423
  */
392
424
  export async function runNight(input: NightRunInput): Promise<NightRun> {
393
425
  const now = input.now ?? ((): number => Date.now());
@@ -421,7 +453,7 @@ export async function runNight(input: NightRunInput): Promise<NightRun> {
421
453
  }
422
454
  return run;
423
455
  };
424
- const ended = (fields: Pick<NightRun, "state" | "reason" | "detail" | "code"> & Partial<Pick<NightRun, "dream" | "reflection" | "parts">>): NightRun =>
456
+ const ended = (fields: Pick<NightRun, "state" | "reason" | "detail" | "code"> & Partial<Pick<NightRun, "dream" | "reflection" | "parts" | "transcript" | "spills">>): NightRun =>
425
457
  record({ ...base(null), endedAt: now(), dream: null, reflection: null, ...fields });
426
458
 
427
459
  if (input.kind.kind === "night") {
@@ -477,7 +509,10 @@ export async function runNight(input: NightRunInput): Promise<NightRun> {
477
509
  } catch (err) {
478
510
  return ended({ state: "could-not-start", reason: "refused", detail: err instanceof Error ? err.name : "UNKNOWN", code: null });
479
511
  }
480
- const plan = planNightChild({
512
+ // THE CHILD'S OWN SESSION, CHOSEN HERE (2026-10-09): so its transcript can
513
+ // be found by name once it exits, and read for the host's cut.
514
+ const hostSession = randomUUID();
515
+ const childInput: NightChildInput = {
481
516
  config: input.config,
482
517
  run: input.run,
483
518
  prompt,
@@ -486,16 +521,56 @@ export async function runNight(input: NightRunInput): Promise<NightRun> {
486
521
  ...(input.configPath === undefined ? {} : { configPath: input.configPath }),
487
522
  ...(input.baseEnv === undefined ? {} : { baseEnv: input.baseEnv }),
488
523
  ...(input.command === undefined ? {} : { command: input.command }),
489
- });
524
+ };
525
+ const plan = planNightChild({ ...childInput, hostSession });
490
526
  if (!plan.ok) return ended({ state: "could-not-start", reason: "refused", detail: plan.reason, code: null });
527
+ const where = { configDir: input.hostConfigDir ?? hostConfigDir(plan.env), id: hostSession, ...(plan.cwd === undefined ? {} : { cwd: plan.cwd }) };
491
528
 
529
+ const start = input.start ?? ((p: ChildPlan) => startChild(p));
492
530
  let result: ChildResult;
531
+ // Whether the child that ran was the one named (review of #330, below).
532
+ let named = true;
493
533
  try {
494
- result = await (input.start ?? ((p: ChildPlan) => startChild(p)))(plan);
534
+ const childAt = now();
535
+ result = await start(plan);
536
+ // A HOST THAT REFUSED THE NAME (review of #330): `--session-id` is read
537
+ // for telemetry only, and the night must not be lost to it. A host too
538
+ // old for the flag, or one that dropped it, exits at once on its argument
539
+ // list — nothing begun, no transcript under the name. Exactly that is
540
+ // retried ONCE without the flag, its cut left unchecked (`absent`). The
541
+ // child's output is discarded (`child.ts`), so the refusal is read from
542
+ // what it left: a quick non-zero exit, no transcript, nothing in the store.
543
+ if (
544
+ result.spawnCode === undefined &&
545
+ result.code !== null &&
546
+ result.code !== 0 &&
547
+ !result.timedOut &&
548
+ now() - childAt < TUNABLES.NIGHT_QUICK_EXIT_MS &&
549
+ hostTranscriptPath(where) === null &&
550
+ !begunSince(input.open, childAt, input.session)
551
+ ) {
552
+ named = false;
553
+ result = await start(planNightChild(childInput));
554
+ }
495
555
  } catch (err) {
496
556
  return ended({ state: "could-not-start", reason: "spawn-failed", detail: err instanceof Error ? err.name : "UNKNOWN", code: null });
497
557
  }
498
558
  const ms = now() - startedAt;
559
+ const neverStarted = result.spawnCode !== undefined || (result.code === null && !result.timedOut && result.error !== null);
560
+
561
+ // WHAT THE HOST CUT (2026-10-09, U14 item 3), read from the child's own
562
+ // transcript — the host's record of what the model saw, not the child's
563
+ // prose. A child that never started left none; one started without its
564
+ // name left none this process can find.
565
+ const spill: ToolSpills | null = neverStarted ? null : named ? readNightSpills(where) : { reason: "absent", results: 0, spills: [], corrupt: 0, short: false };
566
+ if (spill !== null) {
567
+ input.onEvent?.({
568
+ at: now(),
569
+ name: "adapter.night.spill",
570
+ ref: input.run,
571
+ data: { transcript: spill.reason, results: spill.results, spills: spill.spills.length, short: spill.short, corrupt: spill.corrupt, ...(named ? {} : { named: false }) },
572
+ });
573
+ }
499
574
 
500
575
  // WHAT THE RUN DID, from the store.
501
576
  let dream: string | null = null;
@@ -516,6 +591,10 @@ export async function runNight(input: NightRunInput): Promise<NightRun> {
516
591
  const reflected = reflections.find((r) => r.state === "reflected");
517
592
  reflection = reflected?.id ?? null;
518
593
  dream = journaled?.id ?? reflected?.dream_id ?? (input.kind.kind === "reflection" && reflected !== undefined ? input.kind.dream : null);
594
+ // One row per result the host cut (`counterpart.ts#MCP_SPILLED_EVENT`).
595
+ for (const s of spill?.spills ?? []) {
596
+ c.noteAdapterEvent(MCP_SPILLED_EVENT, { run: input.run, tool: s.tool, phase: s.phase, shape: s.shape, said: s.said });
597
+ }
519
598
  } finally {
520
599
  // THE WAKE CATCHES UP TO THE RUN (2026-09-30), whatever state it ended
521
600
  // in: the page it wrote, the dream's merges. Nothing else follows it —
@@ -538,9 +617,14 @@ export async function runNight(input: NightRunInput): Promise<NightRun> {
538
617
  // whatever the exit said, which rides along as the reason.
539
618
  const parts: NightPart[] = [...(writerRan ? ["writer" as const] : []), ...(dreamed ? ["dream" as const] : []), ...(reflection !== null ? ["reflection" as const] : [])];
540
619
  const complete = input.kind.kind === "reflection" ? reflection !== null : parts.includes("dream") && reflection !== null;
541
- const found = { dream, reflection, parts };
620
+ const found = {
621
+ dream,
622
+ reflection,
623
+ parts,
624
+ ...(spill === null ? {} : { transcript: spill.reason, ...(spill.reason === "read" ? { spills: spill.spills.length } : {}) }),
625
+ };
542
626
 
543
- if (result.spawnCode !== undefined || (result.code === null && !result.timedOut && result.error !== null)) {
627
+ if (neverStarted) {
544
628
  const missing = result.spawnCode === "ENOENT";
545
629
  return ended({ state: "could-not-start", reason: missing ? "no-claude" : "spawn-failed", detail: result.spawnCode ?? result.error, code: null });
546
630
  }
@@ -560,6 +644,43 @@ export async function runNight(input: NightRunInput): Promise<NightRun> {
560
644
  return ended({ state: "failed", reason: "unfinished", detail: null, code: 0, ...found });
561
645
  }
562
646
 
647
+ /**
648
+ * THE CHILD'S TRANSCRIPT, READ FOR THE HOST'S CUT (2026-10-09, U14 item 3):
649
+ * found by the session id this process chose (`hostTranscriptPath`), judged by
650
+ * `readToolSpills` — `absent` when the host did not write it where it keeps
651
+ * sessions, said apart from a clean read. Never throws.
652
+ */
653
+ export function readNightSpills(input: { configDir: string; id: string; cwd?: string }): ToolSpills {
654
+ try {
655
+ const path = hostTranscriptPath(input);
656
+ return readToolSpills(path);
657
+ } catch {
658
+ return { reason: "unreadable", results: 0, spills: [], corrupt: 0, short: false };
659
+ }
660
+ }
661
+
662
+ /**
663
+ * DID A CHILD BEGIN ANYTHING since `at` — a dream, a reflection, the page
664
+ * writer's phase (the same reads as `runNight`'s own)? A store that will not
665
+ * open answers yes: a second child is never started on a guess.
666
+ */
667
+ function begunSince(open: () => Counterpart, at: number, session: string): boolean {
668
+ try {
669
+ const c = open();
670
+ try {
671
+ return (
672
+ c.store.dreams({ sinceAt: at, limit: 1 }).length > 0 ||
673
+ c.store.reflections({ limit: 5 }).some((r) => r.started_at >= at) ||
674
+ c.pageWriterRuns({ limit: 20 }).some((r) => r.at >= at && r.session === session)
675
+ );
676
+ } finally {
677
+ c.close();
678
+ }
679
+ } catch {
680
+ return true;
681
+ }
682
+ }
683
+
563
684
  /** The store as the run's process opens it — the hook's options, no embedder.
564
685
  * `onEvent` is the process log's (`adapters/log/`), when there is one. */
565
686
  export function openNightCounterpart(config: AdapterConfig, onEvent?: (e: CounterpartEvent) => void): Counterpart {