counterparts 0.3.11 → 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 (150) hide show
  1. package/CHANGELOG.md +326 -0
  2. package/docs/QUICKSTART.md +5 -0
  3. package/docs/README.md +2 -2
  4. package/docs/module-map.md +3 -3
  5. package/package.json +1 -1
  6. package/src/adapters/claude-code/CONTRACT.md +36 -10
  7. package/src/adapters/claude-code/INTERFACE-GAPS.md +116 -16
  8. package/src/adapters/claude-code/NOTES.md +182 -0
  9. package/src/adapters/claude-code/bin/hook.ts +46 -12
  10. package/src/adapters/claude-code/bin/runner.ts +7 -1
  11. package/src/adapters/claude-code/doctor.ts +632 -18
  12. package/src/adapters/claude-code/hooks.ts +61 -16
  13. package/src/adapters/claude-code/index.ts +11 -0
  14. package/src/adapters/claude-code/night-run.ts +150 -14
  15. package/src/adapters/claude-code/transcript.ts +268 -1
  16. package/src/adapters/cli/CONTRACT.md +5 -0
  17. package/src/adapters/cli/INTERFACE-GAPS.md +8 -4
  18. package/src/adapters/cli/NOTES.md +111 -0
  19. package/src/adapters/cli/commands.ts +134 -92
  20. package/src/adapters/cli/dream-core.ts +57 -42
  21. package/src/adapters/cli/export.ts +320 -21
  22. package/src/adapters/cli/help.ts +2 -1
  23. package/src/adapters/cli/index.ts +1 -0
  24. package/src/adapters/cli/install.ts +39 -7
  25. package/src/adapters/cli/mechanisms.ts +7 -1
  26. package/src/adapters/cli/uninstall.ts +13 -5
  27. package/src/adapters/cli/wire.ts +189 -63
  28. package/src/adapters/config.ts +2 -0
  29. package/src/adapters/dashboard/INTERFACE-GAPS.md +10 -1
  30. package/src/adapters/dashboard/NOTES.md +79 -0
  31. package/src/adapters/dashboard/registries.ts +34 -2
  32. package/src/adapters/dashboard/web/README.md +19 -14
  33. package/src/adapters/dashboard/web/actions.ts +23 -1
  34. package/src/adapters/dashboard/web/flow.ts +14 -0
  35. package/src/adapters/dashboard/web/lanes.ts +10 -0
  36. package/src/adapters/dashboard/web/narrate.ts +88 -2
  37. package/src/adapters/dashboard/web/pages/flow/sections/fired.js +1 -0
  38. package/src/adapters/dashboard/web/pages/health/sections/checks.js +2 -0
  39. package/src/adapters/dashboard/web/pages/health/sections/wake.js +3 -1
  40. package/src/adapters/dashboard/web/pages/memories/memories.css +17 -4
  41. package/src/adapters/dashboard/web/pages/memories/row.js +37 -21
  42. package/src/adapters/dashboard/web/pages/memories/sections/search.js +279 -60
  43. package/src/adapters/dashboard/web/pages/memories/state.js +2 -1
  44. package/src/adapters/dashboard/web/server.ts +0 -5
  45. package/src/adapters/dashboard/web/shared/memory-marks.css +7 -0
  46. package/src/adapters/dashboard/web/shared/memory-marks.js +33 -0
  47. package/src/adapters/dashboard/web/shared/memory-modal.js +5 -3
  48. package/src/adapters/dashboard/web/views/health.ts +21 -3
  49. package/src/adapters/dashboard/web/views/search.ts +4 -45
  50. package/src/adapters/dashboard/web/views.ts +2 -2
  51. package/src/adapters/fired.ts +430 -28
  52. package/src/adapters/host-wiring.ts +300 -0
  53. package/src/adapters/hosts.ts +11 -0
  54. package/src/adapters/lifecycle.ts +42 -2
  55. package/src/adapters/log/index.ts +9 -0
  56. package/src/adapters/mcp/CONTRACT.md +151 -11
  57. package/src/adapters/mcp/INTERFACE-GAPS.md +24 -2
  58. package/src/adapters/mcp/NOTES.md +313 -1
  59. package/src/adapters/mcp/bin/serve.ts +74 -1
  60. package/src/adapters/mcp/deliberate.ts +169 -651
  61. package/src/adapters/mcp/facts.ts +1094 -0
  62. package/src/adapters/mcp/index.ts +25 -7
  63. package/src/adapters/mcp/meaning.ts +1610 -0
  64. package/src/adapters/mcp/server.ts +835 -150
  65. package/src/adapters/mcp/stdio.ts +3 -1
  66. package/src/adapters/mcp/stood-down.ts +51 -0
  67. package/src/adapters/mcp/tools.ts +167 -41
  68. package/src/adapters/plugin-run.sh +133 -0
  69. package/src/adapters/plugin.ts +329 -0
  70. package/src/adapters/sessions.ts +18 -4
  71. package/src/core/associate/CONTRACT.md +2 -1
  72. package/src/core/associate/INTERFACE-GAPS.md +6 -1
  73. package/src/core/associate/NOTES.md +45 -0
  74. package/src/core/briefing.ts +12 -3
  75. package/src/core/contradictions.ts +184 -0
  76. package/src/core/counterpart.ts +797 -51
  77. package/src/core/dream/CONTRACT.md +36 -4
  78. package/src/core/dream/INTERFACE-GAPS.md +29 -6
  79. package/src/core/dream/NOTES.md +107 -0
  80. package/src/core/dream/feeling-weeks.ts +198 -0
  81. package/src/core/dream/index.ts +109 -18
  82. package/src/core/dream/reflect.ts +346 -87
  83. package/src/core/dream/tunables.ts +24 -4
  84. package/src/core/encode/INTERFACE-GAPS.md +3 -1
  85. package/src/core/encode/NOTES.md +7 -0
  86. package/src/core/encode/words.ts +45 -0
  87. package/src/core/fit/INTERFACE-GAPS.md +8 -2
  88. package/src/core/fit/NOTES.md +39 -1
  89. package/src/core/fit/index.ts +40 -0
  90. package/src/core/handoff/CONTRACT.md +37 -2
  91. package/src/core/handoff/INTERFACE-GAPS.md +10 -0
  92. package/src/core/handoff/NOTES.md +72 -0
  93. package/src/core/handoff/index.ts +214 -12
  94. package/src/core/handoff/last-here.ts +6 -4
  95. package/src/core/mint.ts +12 -2
  96. package/src/core/physics/CONTRACT.md +14 -2
  97. package/src/core/physics/NOTES.md +33 -1
  98. package/src/core/physics/index.ts +28 -5
  99. package/src/core/prospective/CONTRACT.md +45 -6
  100. package/src/core/prospective/INTERFACE-GAPS.md +4 -0
  101. package/src/core/prospective/NOTES.md +138 -0
  102. package/src/core/prospective/derive.ts +33 -5
  103. package/src/core/prospective/index.ts +90 -5
  104. package/src/core/prospective/windows.ts +72 -1
  105. package/src/core/recall/CONTRACT.md +31 -12
  106. package/src/core/recall/INTERFACE-GAPS.md +28 -4
  107. package/src/core/recall/NOTES.md +70 -1
  108. package/src/core/recall/feeling-ask.ts +10 -1
  109. package/src/core/recall/index.ts +3 -1
  110. package/src/core/recall/probe.ts +58 -0
  111. package/src/core/recall/session.ts +46 -2
  112. package/src/core/recall/time-ask.ts +487 -0
  113. package/src/core/remember/CONTRACT.md +4 -1
  114. package/src/core/remember/INTERFACE-GAPS.md +9 -1
  115. package/src/core/remember/NOTES.md +8 -0
  116. package/src/core/remember/proposals.ts +47 -5
  117. package/src/core/revision.ts +18 -1
  118. package/src/core/schemas/CONTRACT.md +21 -1
  119. package/src/core/schemas/INTERFACE-GAPS.md +20 -2
  120. package/src/core/schemas/NOTES.md +144 -0
  121. package/src/core/schemas/aliases.ts +55 -5
  122. package/src/core/schemas/index.ts +93 -1
  123. package/src/core/schemas/types.ts +2 -0
  124. package/src/core/self/CONTRACT.md +32 -5
  125. package/src/core/self/INTERFACE-GAPS.md +7 -2
  126. package/src/core/self/NOTES.md +102 -1
  127. package/src/core/self/behind.ts +43 -3
  128. package/src/core/self/briefing.ts +12 -2
  129. package/src/core/self/chapter-address.ts +254 -0
  130. package/src/core/self/episodes.ts +27 -0
  131. package/src/core/self/index.ts +83 -8
  132. package/src/core/self/page.ts +88 -0
  133. package/src/core/self/tunables.ts +5 -0
  134. package/src/core/self/work.ts +35 -2
  135. package/src/core/self/writer.ts +30 -0
  136. package/src/core/sleep/INTERFACE-GAPS.md +22 -3
  137. package/src/core/sleep/NOTES.md +20 -1
  138. package/src/core/sleep/consolidate.ts +59 -7
  139. package/src/core/sleep/index.ts +3 -0
  140. package/src/core/sleep/prune.ts +6 -2
  141. package/src/core/sleep/types.ts +7 -0
  142. package/src/core/store/CONTRACT.md +16 -0
  143. package/src/core/store/NOTES.md +66 -0
  144. package/src/core/store/feelings.ts +14 -1
  145. package/src/core/store/index.ts +483 -16
  146. package/src/core/store/operational.ts +95 -2
  147. package/src/core/store/owner-op-seam.ts +23 -0
  148. package/src/core/time.ts +152 -0
  149. package/tools/install-loop/run.sh +48 -12
  150. package/src/adapters/dashboard/web/pages/memories/fold.js +0 -53
@@ -46,6 +46,10 @@
46
46
  */
47
47
  import {
48
48
  CHECKOUT_EVENT,
49
+ ENVELOPE_GAVE_WAY_EVENT,
50
+ ENVELOPE_OVERCAP_EVENT,
51
+ INJECTION_OVERBUDGET_EVENT,
52
+ NOTICE_DROPPED_EVENT,
49
53
  PRIMACY_DELIVER_EVENT,
50
54
  PRIMACY_STANDDOWN_EVENT,
51
55
  WAKE_DELIVERED_EVENT,
@@ -620,7 +624,7 @@ export class ClaudeCodeAdapter extends Lifecycle {
620
624
  if (budget !== undefined && sent > budget) {
621
625
  // Exceeding a reported limit is an EVENT, never silent degradation. The
622
626
  // bundle still goes: truncated-and-detectable beats absent.
623
- this.emit("adapter.injection.overbudget", { bytes: sent, budget });
627
+ this.noteDeliveryWarning(INJECTION_OVERBUDGET_EVENT, { hook: "session-start", bytes: sent, budget }, input);
624
628
  }
625
629
  this.record(WAKE_INJECTED_EVENT, input, {
626
630
  ok: woke.ok,
@@ -635,6 +639,12 @@ export class ClaudeCodeAdapter extends Lifecycle {
635
639
  // core change (`AdapterDurableEventName`) and this fact is about
636
640
  // exactly the moment that row describes.
637
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,
638
648
  });
639
649
  // THE QUESTION RIDES BESIDE THE WAKE, NEVER INSIDE IT, and only if it
640
650
  // FITS.
@@ -731,7 +741,7 @@ export class ClaudeCodeAdapter extends Lifecycle {
731
741
  need,
732
742
  form: room.form,
733
743
  });
734
- this.emit("adapter.envelope.gave-way", { hook: "session-start", part: "question", form: room.form });
744
+ this.noteDeliveryWarning(ENVELOPE_GAVE_WAY_EVENT, { hook: "session-start", part: "question", form: room.form }, input);
735
745
  return "";
736
746
  }
737
747
  // The mark is a SECOND write of the same phase rather than a field folded
@@ -798,7 +808,7 @@ export class ClaudeCodeAdapter extends Lifecycle {
798
808
  if (text.trim().length === 0) {
799
809
  return { ...out, ok: true, reason: "empty-prompt", injection: `${this.nowLine()}${context.length === 0 ? "" : `\n${context.trimEnd()}`}`, ...told };
800
810
  }
801
- const budgetBytes = this.recallRoom(context, [
811
+ const budgetBytes = this.recallRoom(input, context, [
802
812
  ...plain.notices,
803
813
  ...(dream.told === null ? [] : [dream.told.notice]),
804
814
  ...(dream.note === null ? [] : [dream.note.notice]),
@@ -852,7 +862,7 @@ export class ClaudeCodeAdapter extends Lifecycle {
852
862
  * which gives way. Undefined means "recall's own default" (nothing to
853
863
  * shrink); a number is the configured budget or less.
854
864
  */
855
- private recallRoom(context: string, personLines: readonly string[]): number | undefined {
865
+ private recallRoom(input: HookInput, context: string, personLines: readonly string[]): number | undefined {
856
866
  const configured = this.config.injectionBudgetBytes;
857
867
  const base = configured ?? RECALL_TUNABLES.BUDGET_BYTES;
858
868
  const json = personLines.length > 0;
@@ -867,7 +877,7 @@ export class ClaudeCodeAdapter extends Lifecycle {
867
877
  : Buffer.byteLength(lead, "utf8");
868
878
  const room = Math.max(0, limit - extras);
869
879
  if (room >= base) return configured;
870
- this.emit("adapter.envelope.gave-way", { hook: "user-prompt-submit", part: "recall", budget: room, base });
880
+ this.noteDeliveryWarning(ENVELOPE_GAVE_WAY_EVENT, { hook: "user-prompt-submit", part: "recall", budget: room, base }, input);
871
881
  return room;
872
882
  }
873
883
 
@@ -1063,14 +1073,16 @@ export class ClaudeCodeAdapter extends Lifecycle {
1063
1073
 
1064
1074
  /**
1065
1075
  * THE HAND-BACK OF A HEADLESS RUN THAT ENDED — the dream's line, then the
1066
- * morning share if there is one — claimed once across every session. Empty
1067
- * 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.
1068
1079
  */
1069
1080
  private nightHandBack(input: HookInput): string[] {
1070
1081
  const dreams = this.counterpart.dreams;
1071
1082
  const night = dreams.nightRun();
1072
1083
  if (night === null || night.state === "started" || night.state === "could-not-start") return [];
1073
- 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 [];
1074
1086
  // A READ on the per-prompt path once it is handed: nothing is written again.
1075
1087
  if (night.handedAt !== undefined) return [];
1076
1088
  const claimed = dreams.claimNightHandBack(night.run, input.sessionId);
@@ -1085,6 +1097,8 @@ export class ClaudeCodeAdapter extends Lifecycle {
1085
1097
  const share = this.counterpart.reflections.carryLine({ session: input.sessionId, reflection: night.reflection });
1086
1098
  if (share !== null) out.push(share);
1087
1099
  }
1100
+ const spill = dreams.nightSpillLine(night);
1101
+ if (spill !== null) out.push(spill);
1088
1102
  this.emit("adapter.night.handed", { run: night.run, lines: out.length });
1089
1103
  return out;
1090
1104
  }
@@ -1206,6 +1220,14 @@ export class ClaudeCodeAdapter extends Lifecycle {
1206
1220
  // withholds is the ASK, which is delivery: an ask from a system the
1207
1221
  // owner is not talking to today is exactly the double-voice G3 forbids.
1208
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 });
1209
1231
  // THE AUTHORED FRONT DOOR, first: the experiencer writes its own memories
1210
1232
  // while it still has the pen, and the sweep the worker spawns below is
1211
1233
  // only the fallback for the day nobody got to (contract §4). The ask goes
@@ -1336,14 +1358,26 @@ export class ClaudeCodeAdapter extends Lifecycle {
1336
1358
 
1337
1359
  /**
1338
1360
  * DID THE WAKE THIS SESSION COMPOSED REACH THE SESSION? — once, at the first
1339
- * prompt, and never again for this session.
1361
+ * prompt or the end of the first turn, and never again for this session.
1340
1362
  *
1341
1363
  * **Why here and not at the end.** Nothing inside the SessionStart hook can
1342
1364
  * know what the host did with its return value, and SessionEnd's hooks share
1343
- * 1.5 s between them. The first `UserPromptSubmit` is the earliest moment the
1344
- * 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
1345
1367
  * rather than once per turn.
1346
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
+ *
1347
1381
  * **What it reads.** The head of the host's transcript, bounded
1348
1382
  * (`transcript.ts#readWakeArrival`): this package's SessionStart attachment
1349
1383
  * carries what the hook printed beside what the host says it injected, and the
@@ -1360,7 +1394,7 @@ export class ClaudeCodeAdapter extends Lifecycle {
1360
1394
  * retroactive-capture guard reads that same absence to detect, and a record
1361
1395
  * written from here would take that evidence away.
1362
1396
  */
1363
- private checkWakeArrival(input: HookInput): void {
1397
+ private checkWakeArrival(input: HookInput, opts: { readonly final?: boolean } = {}): void {
1364
1398
  if (this.observer) return;
1365
1399
  if (input.sessionId.length === 0) return;
1366
1400
  const started = this.nowFn();
@@ -1378,9 +1412,21 @@ export class ClaudeCodeAdapter extends Lifecycle {
1378
1412
  // the row says so rather than reporting a wake that was never composed.
1379
1413
  const arrival =
1380
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
+ }
1381
1425
  const outcome = wakeOutcome(expected, arrival);
1382
1426
  this.record(WAKE_DELIVERED_EVENT, input, {
1383
1427
  outcome,
1428
+ // Which hook answered: the first prompt, or the end of the first turn.
1429
+ checkedAt: opts.final === true ? "stop" : "prompt",
1384
1430
  // `ok` and `delivered` say the same thing under the two names this row's
1385
1431
  // readers already look for.
1386
1432
  ok: outcome === "delivered",
@@ -1567,13 +1613,13 @@ export class ClaudeCodeAdapter extends Lifecycle {
1567
1613
  * looking like a healthy morning. Ids and counts only, like every other row.
1568
1614
  */
1569
1615
  noteNoticeDropped(chars: { noticeChars: number; envelopeChars: number; limitChars: number }): void {
1570
- this.emit("adapter.notice.dropped", { ...chars });
1616
+ this.noteDeliveryWarning(NOTICE_DROPPED_EVENT, { ...chars });
1571
1617
  }
1572
1618
 
1573
1619
  /** RECORD THAT EVEN THE PLAIN FORM WAS PAST THE HOST'S CAP
1574
1620
  * (`bin/hook.ts#Delivery.overCap`, 2026-09-29). Counts only. */
1575
1621
  noteOverCap(chars: { chars: number; limitChars: number }): void {
1576
- this.emit("adapter.envelope.overcap", { ...chars });
1622
+ this.noteDeliveryWarning(ENVELOPE_OVERCAP_EVENT, { ...chars });
1577
1623
  }
1578
1624
 
1579
1625
  /** RECORD WHAT THE DELIVERY LEFT FOR LATER for want of room — plain
@@ -1581,8 +1627,7 @@ export class ClaudeCodeAdapter extends Lifecycle {
1581
1627
  * Recorded where it happened, so the event says what was actually
1582
1628
  * delivered (review of #285, S2). Counts only. */
1583
1629
  noteGaveWay(input: HookInput, part: string, count: number): void {
1584
- void input;
1585
- this.emit("adapter.envelope.gave-way", { hook: "delivery", part, count });
1630
+ this.noteDeliveryWarning(ENVELOPE_GAVE_WAY_EVENT, { hook: "delivery", part, count }, input);
1586
1631
  }
1587
1632
 
1588
1633
  /**
@@ -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,19 +65,24 @@
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";
71
75
  import { scriptArgs } from "../runtime.js";
72
- import { OBSERVER_ENV } from "../stance-env.js";
76
+ import { TOOL_RESULT_CEILING } from "../../core/fit/index.js";
77
+ import { installedVersion } from "../sessions.js";
78
+ import { OBSERVER_ENV, OWNER_ENV } from "../stance-env.js";
73
79
 
74
80
  import { TUNABLES } from "../config.js";
75
81
  import type { AdapterConfig } from "../config.js";
76
82
  import { DEFAULT_HOST_COMMAND, KILL_GRACE_MS, PERMISSION_MODE, REAP_GRACE_MS, startChild } from "./child.js";
77
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";
78
86
  import type { ChildPlan, ChildResult } from "./child.js";
79
87
  import { DATA_DIR_ENV, SCOPE_ENV, SESSION_ENV, WATCHDOG_ENV } from "../spawn.js";
80
88
  import type { SpawnPlan } from "../spawn.js";
@@ -87,6 +95,8 @@ import type { SpawnPlan } from "../spawn.js";
87
95
  export const NIGHT_RUN_ENV = "COUNTERPARTS_NIGHT_RUN";
88
96
  /** What the run does: `night` (writer, dream, reflection) or `reflection:<dream id>`. */
89
97
  export const NIGHT_KIND_ENV = "COUNTERPARTS_NIGHT_KIND";
98
+ /** Claude Code's own name for its MCP result token line (2026-10-02). */
99
+ export const MCP_TOKENS_ENV = "MAX_MCP_OUTPUT_TOKENS";
90
100
 
91
101
  /**
92
102
  * THE FOUR TOOLS THE RUN MAY CALL, as the host names MCP tools — the dream
@@ -150,7 +160,12 @@ export const NIGHT_MCP_SCRIPT = fileURLToPath(new URL("../mcp/bin/serve.ts", imp
150
160
  * a session id.
151
161
  */
152
162
  export function nightMcpConfig(input: { runtime: string; dataDir: string; configPath?: string; session: string; scope: string }): string {
153
- const env: Record<string, string> = { [DATA_DIR_ENV]: input.dataDir };
163
+ // NOT THE OWNER'S, SAID (2026-10-02): a server Claude Code starts is the
164
+ // owner's by default now, and `claude -p` is Claude Code. The headless run
165
+ // keeps the stance it always had — confidential memories stay out of its
166
+ // bundles and its write-ups close no thread opened elsewhere — until that
167
+ // is decided on its own.
168
+ const env: Record<string, string> = { [DATA_DIR_ENV]: input.dataDir, [OWNER_ENV]: "0" };
154
169
  if (input.configPath !== undefined && input.configPath.length > 0) env[CONFIG_PATH_ENV] = input.configPath;
155
170
  if (input.session.length > 0) env[SESSION_ENV] = input.session;
156
171
  if (input.scope.length > 0) env[SCOPE_ENV] = input.scope;
@@ -168,7 +183,16 @@ export function nightMaxTurns(config: AdapterConfig): number {
168
183
  * scope from it before its own directory) and the markers that say "inside a
169
184
  * Claude Code session" (a host may refuse to start a session inside another).
170
185
  */
171
- 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;
172
196
 
173
197
  export type NightKind = { readonly kind: "night" } | { readonly kind: "reflection"; readonly dream: string };
174
198
 
@@ -276,6 +300,12 @@ export interface NightChildInput {
276
300
  /** Its turn ceiling and watchdog; absent, the night's own (`nightMaxTurns`, `nightTimeoutMs`). */
277
301
  readonly maxTurns?: number;
278
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;
279
309
  }
280
310
 
281
311
  /**
@@ -309,6 +339,7 @@ export function planNightChild(input: NightChildInput): NightChildPlan {
309
339
  }),
310
340
  "--strict-mcp-config",
311
341
  ...(model === undefined ? [] : ["--model", model]),
342
+ ...(input.hostSession === undefined || input.hostSession.length === 0 ? [] : ["--session-id", input.hostSession]),
312
343
  ];
313
344
  const plan = (ok: boolean, reason: NightChildRefusal | "ready"): NightChildPlan => ({
314
345
  ok,
@@ -337,6 +368,11 @@ export function planNightChild(input: NightChildInput): NightChildPlan {
337
368
  for (const k of HOST_SESSION_ENV) delete env[k];
338
369
  env[DATA_DIR_ENV] = input.config.dataDir;
339
370
  env[NIGHT_RUN_ENV] = input.run;
371
+ // THE TOKEN LINE, PINNED (2026-10-02): the env var outranks the host's remote
372
+ // flag, so a flag that lowered it cannot spill a result the caps sized for
373
+ // 25,000 tokens (`fit/TOOL_RESULT_CEILING`). The 50,000-character line has
374
+ // no such pin.
375
+ env[MCP_TOKENS_ENV] = String(TOOL_RESULT_CEILING.HOST_TOKENS);
340
376
  if (input.session.length > 0) env[SESSION_ENV] = input.session;
341
377
  if (input.scope.length > 0) env[SCOPE_ENV] = input.scope;
342
378
  if (input.configPath !== undefined && input.configPath.length > 0) env[CONFIG_PATH_ENV] = input.configPath;
@@ -364,6 +400,12 @@ export interface NightRunInput {
364
400
  readonly start?: NightStarter;
365
401
  /** TESTS ONLY: the catch-up child's starter (`night-catch-up.ts`); absent, a real child. */
366
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;
367
409
  readonly now?: () => number;
368
410
  /** The process log's (`adapters/log/`), for what the store does not write. */
369
411
  readonly onEvent?: (e: CounterpartEvent) => void;
@@ -373,7 +415,11 @@ export interface NightRunInput {
373
415
  * RUN THE NIGHT, headless: compose, start, wait, record. Never throws; the
374
416
  * record it returns is the one it wrote. What happened is read from the exit
375
417
  * and from the STORE (a dream journaled, a reflection finished) — never from
376
- * 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`).
377
423
  */
378
424
  export async function runNight(input: NightRunInput): Promise<NightRun> {
379
425
  const now = input.now ?? ((): number => Date.now());
@@ -407,7 +453,7 @@ export async function runNight(input: NightRunInput): Promise<NightRun> {
407
453
  }
408
454
  return run;
409
455
  };
410
- 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 =>
411
457
  record({ ...base(null), endedAt: now(), dream: null, reflection: null, ...fields });
412
458
 
413
459
  if (input.kind.kind === "night") {
@@ -463,7 +509,10 @@ export async function runNight(input: NightRunInput): Promise<NightRun> {
463
509
  } catch (err) {
464
510
  return ended({ state: "could-not-start", reason: "refused", detail: err instanceof Error ? err.name : "UNKNOWN", code: null });
465
511
  }
466
- 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 = {
467
516
  config: input.config,
468
517
  run: input.run,
469
518
  prompt,
@@ -472,16 +521,56 @@ export async function runNight(input: NightRunInput): Promise<NightRun> {
472
521
  ...(input.configPath === undefined ? {} : { configPath: input.configPath }),
473
522
  ...(input.baseEnv === undefined ? {} : { baseEnv: input.baseEnv }),
474
523
  ...(input.command === undefined ? {} : { command: input.command }),
475
- });
524
+ };
525
+ const plan = planNightChild({ ...childInput, hostSession });
476
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 }) };
477
528
 
529
+ const start = input.start ?? ((p: ChildPlan) => startChild(p));
478
530
  let result: ChildResult;
531
+ // Whether the child that ran was the one named (review of #330, below).
532
+ let named = true;
479
533
  try {
480
- 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
+ }
481
555
  } catch (err) {
482
556
  return ended({ state: "could-not-start", reason: "spawn-failed", detail: err instanceof Error ? err.name : "UNKNOWN", code: null });
483
557
  }
484
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
+ }
485
574
 
486
575
  // WHAT THE RUN DID, from the store.
487
576
  let dream: string | null = null;
@@ -502,6 +591,10 @@ export async function runNight(input: NightRunInput): Promise<NightRun> {
502
591
  const reflected = reflections.find((r) => r.state === "reflected");
503
592
  reflection = reflected?.id ?? null;
504
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
+ }
505
598
  } finally {
506
599
  // THE WAKE CATCHES UP TO THE RUN (2026-09-30), whatever state it ended
507
600
  // in: the page it wrote, the dream's merges. Nothing else follows it —
@@ -524,9 +617,14 @@ export async function runNight(input: NightRunInput): Promise<NightRun> {
524
617
  // whatever the exit said, which rides along as the reason.
525
618
  const parts: NightPart[] = [...(writerRan ? ["writer" as const] : []), ...(dreamed ? ["dream" as const] : []), ...(reflection !== null ? ["reflection" as const] : [])];
526
619
  const complete = input.kind.kind === "reflection" ? reflection !== null : parts.includes("dream") && reflection !== null;
527
- 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
+ };
528
626
 
529
- if (result.spawnCode !== undefined || (result.code === null && !result.timedOut && result.error !== null)) {
627
+ if (neverStarted) {
530
628
  const missing = result.spawnCode === "ENOENT";
531
629
  return ended({ state: "could-not-start", reason: missing ? "no-claude" : "spawn-failed", detail: result.spawnCode ?? result.error, code: null });
532
630
  }
@@ -546,6 +644,43 @@ export async function runNight(input: NightRunInput): Promise<NightRun> {
546
644
  return ended({ state: "failed", reason: "unfinished", detail: null, code: 0, ...found });
547
645
  }
548
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
+
549
684
  /** The store as the run's process opens it — the hook's options, no embedder.
550
685
  * `onEvent` is the process log's (`adapters/log/`), when there is one. */
551
686
  export function openNightCounterpart(config: AdapterConfig, onEvent?: (e: CounterpartEvent) => void): Counterpart {
@@ -557,6 +692,7 @@ export function openNightCounterpart(config: AdapterConfig, onEvent?: (e: Counte
557
692
  ...(config.timeZone === undefined ? {} : { timeZone: config.timeZone }),
558
693
  ...(config.pageWriter?.mode === undefined ? {} : { pageWriterMode: config.pageWriter.mode }),
559
694
  ...(config.identity === undefined ? {} : { identity: { name: config.identity.name, aliases: [...(config.identity.aliases ?? [])] } }),
695
+ build: installedVersion(),
560
696
  ...(onEvent === undefined ? {} : { onEvent }),
561
697
  });
562
698
  }