counterparts 0.3.37 → 0.3.39

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 (129) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/README.md +2 -1
  3. package/docs/QUICKSTART.md +14 -8
  4. package/docs/module-map.md +4 -2
  5. package/package.json +9 -1
  6. package/src/adapters/claude-code/CONTRACT.md +26 -4
  7. package/src/adapters/claude-code/NOTES.md +116 -0
  8. package/src/adapters/claude-code/bin/hook.ts +70 -6
  9. package/src/adapters/claude-code/bin/nightly.ts +2 -0
  10. package/src/adapters/claude-code/bin/runner.ts +64 -2
  11. package/src/adapters/claude-code/child-error.ts +211 -0
  12. package/src/adapters/claude-code/child.ts +29 -10
  13. package/src/adapters/claude-code/doctor-checkout.ts +4 -2
  14. package/src/adapters/claude-code/doctor-host.ts +31 -0
  15. package/src/adapters/claude-code/doctor-meaning.ts +200 -0
  16. package/src/adapters/claude-code/doctor-modes.ts +115 -0
  17. package/src/adapters/claude-code/doctor-open.ts +12 -2
  18. package/src/adapters/claude-code/doctor-self-page.ts +2 -0
  19. package/src/adapters/claude-code/doctor-write-ups.ts +84 -19
  20. package/src/adapters/claude-code/doctor.ts +199 -23
  21. package/src/adapters/claude-code/hooks.ts +162 -11
  22. package/src/adapters/claude-code/index.ts +15 -0
  23. package/src/adapters/claude-code/night-catch-up.ts +25 -5
  24. package/src/adapters/claude-code/night-run.ts +86 -11
  25. package/src/adapters/claude-code/stale-windows.ts +160 -0
  26. package/src/adapters/claude-code/standdown.ts +70 -3
  27. package/src/adapters/cli/INTERFACE-GAPS.md +14 -0
  28. package/src/adapters/cli/NOTES.md +25 -0
  29. package/src/adapters/cli/bin/counterparts.ts +4 -2
  30. package/src/adapters/cli/commands-dashboard.ts +8 -5
  31. package/src/adapters/cli/commands-install.ts +12 -14
  32. package/src/adapters/cli/commands.ts +5 -2
  33. package/src/adapters/cli/coverage.ts +28 -6
  34. package/src/adapters/cli/help.ts +6 -1
  35. package/src/adapters/cli/index.ts +2 -0
  36. package/src/adapters/cli/install.ts +24 -1
  37. package/src/adapters/cli/mechanisms.ts +31 -8
  38. package/src/adapters/cli/rollback.ts +3 -3
  39. package/src/adapters/cli/snapshot.ts +4 -4
  40. package/src/adapters/cli/ui.ts +10 -0
  41. package/src/adapters/cli/uninstall.ts +16 -74
  42. package/src/adapters/cli/wire.ts +227 -33
  43. package/src/adapters/config.ts +23 -0
  44. package/src/adapters/dashboard/bin/dashboard.ts +2 -0
  45. package/src/adapters/dashboard/registries.ts +1 -1
  46. package/src/adapters/dashboard/web/mechanisms/index.js +2 -0
  47. package/src/adapters/dashboard/web/mechanisms/schema/index.js +9 -6
  48. package/src/adapters/dashboard/web/mechanisms/schema/panel.js +14 -0
  49. package/src/adapters/dashboard/web/narrate.ts +10 -3
  50. package/src/adapters/dashboard/web/views/mechanism-panel.ts +44 -0
  51. package/src/adapters/dashboard/web/views/mechanisms.ts +13 -1
  52. package/src/adapters/expansions.ts +4 -3
  53. package/src/adapters/fired.ts +29 -0
  54. package/src/adapters/host-wiring.ts +56 -1
  55. package/src/adapters/hosts.ts +51 -0
  56. package/src/adapters/lifecycle.ts +4 -2
  57. package/src/adapters/mcp/CONTRACT.md +26 -3
  58. package/src/adapters/mcp/INTERFACE-GAPS.md +11 -0
  59. package/src/adapters/mcp/NOTES.md +149 -0
  60. package/src/adapters/mcp/bin/serve.ts +83 -4
  61. package/src/adapters/mcp/chat-wake.ts +111 -0
  62. package/src/adapters/mcp/deliberate.ts +5 -2
  63. package/src/adapters/mcp/index.ts +3 -1
  64. package/src/adapters/mcp/nights.ts +434 -9
  65. package/src/adapters/mcp/protocol.ts +11 -2
  66. package/src/adapters/mcp/server-args.ts +6 -0
  67. package/src/adapters/mcp/server-options.ts +19 -2
  68. package/src/adapters/mcp/server-self-tools.ts +23 -8
  69. package/src/adapters/mcp/server-session-end.ts +5 -3
  70. package/src/adapters/mcp/server-words.ts +218 -4
  71. package/src/adapters/mcp/server.ts +524 -56
  72. package/src/adapters/mcp/tools.ts +266 -12
  73. package/src/adapters/mechanism-evidence.ts +90 -15
  74. package/src/adapters/owned-names.ts +105 -0
  75. package/src/adapters/plugin.ts +34 -7
  76. package/src/adapters/private-base.ts +175 -0
  77. package/src/adapters/private-umask.ts +71 -0
  78. package/src/adapters/remote/CONTRACT.md +75 -0
  79. package/src/adapters/remote/INTERFACE-GAPS.md +20 -0
  80. package/src/adapters/remote/NOTES.md +80 -0
  81. package/src/adapters/remote/bin/serve-http.ts +258 -0
  82. package/src/adapters/remote/call-log.ts +206 -0
  83. package/src/adapters/remote/http.ts +500 -0
  84. package/src/adapters/sessions.ts +121 -7
  85. package/src/adapters/snapshots.ts +3 -3
  86. package/src/adapters/spawn.ts +13 -6
  87. package/src/adapters/update-check.ts +870 -0
  88. package/src/adapters/update-words.ts +230 -0
  89. package/src/core/counterpart-deposit.ts +35 -2
  90. package/src/core/counterpart-sweep.ts +7 -1
  91. package/src/core/counterpart-types.ts +7 -0
  92. package/src/core/counterpart.ts +185 -23
  93. package/src/core/coverage/CONTRACT.md +12 -5
  94. package/src/core/coverage/NOTES.md +40 -1
  95. package/src/core/coverage/index.ts +73 -14
  96. package/src/core/coverage/tunables.ts +15 -1
  97. package/src/core/dream/CONTRACT.md +47 -9
  98. package/src/core/dream/NOTES.md +115 -0
  99. package/src/core/dream/index.ts +51 -6
  100. package/src/core/dream/recalled.ts +90 -0
  101. package/src/core/dream/reflect.ts +156 -25
  102. package/src/core/dream/tunables.ts +61 -0
  103. package/src/core/handoff/CONTRACT.md +8 -1
  104. package/src/core/handoff/NOTES.md +52 -0
  105. package/src/core/handoff/last-here.ts +52 -0
  106. package/src/core/mint.ts +8 -1
  107. package/src/core/onboarding.ts +35 -8
  108. package/src/core/recall/CONTRACT.md +11 -0
  109. package/src/core/reconsolidation.ts +2 -1
  110. package/src/core/remember/CONTRACT.md +2 -1
  111. package/src/core/remember/owes.ts +7 -1
  112. package/src/core/remember/proposals.ts +41 -1
  113. package/src/core/schemas/CONTRACT.md +4 -2
  114. package/src/core/self/INTERFACE-GAPS.md +20 -0
  115. package/src/core/self/briefing.ts +37 -1
  116. package/src/core/self/identity.ts +54 -4
  117. package/src/core/self/index.ts +69 -4
  118. package/src/core/self/work.ts +20 -0
  119. package/src/core/self/writer.ts +15 -1
  120. package/src/core/store/CONTRACT.md +28 -2
  121. package/src/core/store/NOTES.md +97 -2
  122. package/src/core/store/db.ts +24 -1
  123. package/src/core/store/index.ts +28 -2
  124. package/src/core/store/operational.ts +37 -1
  125. package/src/core/store/pre-migration.ts +6 -2
  126. package/src/core/store/private.ts +319 -0
  127. package/src/core/store/shapes.ts +6 -0
  128. package/src/core/types.ts +28 -0
  129. package/tools/install-loop/run.sh +3 -0
@@ -460,6 +460,12 @@ export interface CatchUpReport {
460
460
  readonly bytes: number;
461
461
  readonly ms: number;
462
462
  readonly code: number | null;
463
+ /** Why the last child failed (2026-10-27, R4): one scrubbed line of what it
464
+ * said (`child-error.ts`); null when it did not fail, or said nothing, and
465
+ * on rows from before. */
466
+ readonly detail: string | null;
467
+ /** That line reads as a lost sign-in, from the host's own words (`child-error.ts#ChildFailure`). Absent otherwise. */
468
+ readonly signedOut?: true;
463
469
  /** Children started (2026-10-11). */
464
470
  readonly batches: number;
465
471
  /** What stopped the run while something was still owed: the parts ceiling
@@ -553,7 +559,7 @@ export interface CatchUpInput {
553
559
  }
554
560
 
555
561
  /** One child, started and waited on: what became of it. */
556
- async function runChild(input: CatchUpInput, plan: CatchUpPlan, prompt: string): Promise<{ state: CatchUpReport["state"]; code: number | null }> {
562
+ async function runChild(input: CatchUpInput, plan: CatchUpPlan, prompt: string): Promise<{ state: CatchUpReport["state"]; code: number | null; detail: string | null; signedOut?: true }> {
557
563
  // THE ASK (2026-10-20): the batch's prompt, filed under its runner, with
558
564
  // the write-up's own turns and watchdog.
559
565
  const ask = seatAsk("catch-up", {
@@ -565,11 +571,14 @@ async function runChild(input: CatchUpInput, plan: CatchUpPlan, prompt: string):
565
571
  });
566
572
  try {
567
573
  const answer = await input.seat.answer(ask);
568
- if (answer.refused !== null) return { state: "could-not-start", code: null };
574
+ if (answer.refused !== null) return { state: "could-not-start", code: null, detail: null };
569
575
  const state = !answer.started ? "could-not-start" : answer.timedOut ? "timed-out" : answer.code === 0 ? "done" : "failed";
570
- return { state, code: answer.code };
576
+ // What a failed child said, where the seat reports it (Claude Code's: `NightAnswer.failure`).
577
+ const said = (answer as { failure?: unknown }).failure;
578
+ const failed = state === "failed" && typeof said === "string" && said.length > 0;
579
+ return { state, code: answer.code, detail: failed ? said : null, ...(failed && (answer as { signedOut?: unknown }).signedOut === true ? { signedOut: true as const } : {}) };
571
580
  } catch {
572
- return { state: "could-not-start", code: null };
581
+ return { state: "could-not-start", code: null, detail: null };
573
582
  }
574
583
  }
575
584
 
@@ -587,6 +596,8 @@ export async function runCatchUp(input: CatchUpInput): Promise<CatchUpReport | n
587
596
  let batches = 0;
588
597
  let state: CatchUpReport["state"] = "done";
589
598
  let code: number | null = null;
599
+ let detail: string | null = null;
600
+ let signedOut = false;
590
601
  let parts = 0;
591
602
  let passed = 0;
592
603
  let unread = 0;
@@ -660,6 +671,8 @@ export async function runCatchUp(input: CatchUpInput): Promise<CatchUpReport | n
660
671
  }
661
672
  const child = await runChild(input, plan, prompt);
662
673
  code = child.code;
674
+ detail = child.detail;
675
+ signedOut = child.signedOut === true;
663
676
  let m: ReturnType<typeof measure> | null = null;
664
677
  try {
665
678
  const c = input.open();
@@ -710,6 +723,8 @@ export async function runCatchUp(input: CatchUpInput): Promise<CatchUpReport | n
710
723
  bytes,
711
724
  ms: endedAt - startedAt,
712
725
  code,
726
+ detail,
727
+ ...(signedOut ? { signedOut: true as const } : {}),
713
728
  batches,
714
729
  limit,
715
730
  ...over,
@@ -747,6 +762,8 @@ function record(input: CatchUpInput, report: CatchUpReport, open?: Counterpart):
747
762
  bytes: report.bytes,
748
763
  ms: report.ms,
749
764
  code: report.code,
765
+ ...(report.detail === null ? {} : { detail: report.detail }),
766
+ ...(report.signedOut === true ? { signedOut: true } : {}),
750
767
  batches: report.batches,
751
768
  limit: report.limit,
752
769
  };
@@ -802,6 +819,8 @@ export function catchUpOf(
802
819
  bytes: n("bytes"),
803
820
  ms: n("ms"),
804
821
  code: typeof p["code"] === "number" ? (p["code"] as number) : null,
822
+ detail: typeof p["detail"] === "string" && p["detail"].length > 0 ? p["detail"] : null,
823
+ ...(p["signedOut"] === true ? { signedOut: true as const } : {}),
805
824
  partsLeft: typeof p["partsLeft"] === "number" ? (p["partsLeft"] as number) : null,
806
825
  batches: typeof p["batches"] === "number" ? (p["batches"] as number) : 1,
807
826
  limit: p["limit"] === "parts" || p["limit"] === "time" ? p["limit"] : null,
@@ -826,6 +845,7 @@ export function catchUpWords(
826
845
  readonly limit?: CatchUpReport["limit"];
827
846
  readonly passed?: number;
828
847
  readonly unread?: number;
848
+ readonly detail?: string | null;
829
849
  },
830
850
  ): string {
831
851
  const n = (k: number, one: string, many: string): string => `${String(k)} ${k === 1 ? one : many}`;
@@ -837,7 +857,7 @@ export function catchUpWords(
837
857
  r.state === "timed-out"
838
858
  ? " before its watchdog stopped it"
839
859
  : r.state === "failed"
840
- ? " before it failed"
860
+ ? ` before it failed${typeof r.detail === "string" && r.detail.length > 0 ? ` (${r.detail})` : ""}`
841
861
  : r.state === "partial"
842
862
  ? " — it stopped before the rest (a usage limit, or it gave up)"
843
863
  : "";
@@ -93,7 +93,7 @@ import { join } from "node:path";
93
93
 
94
94
  import { Counterpart, MCP_SPILLED_EVENT, seatAsk } from "../../core/counterpart.js";
95
95
  import type { CounterpartEvent, Seat, SeatAnswer, SeatAsk, SeatTool } from "../../core/counterpart.js";
96
- import { CATCH_UP_ONLY_REASONS, nightUsageOf, tagsBundle, tagsPrompt } from "../../core/dream/index.js";
96
+ import { CATCH_UP_ONLY_REASONS, DREAM_TUNABLES, nightUsageOf, tagsBundle, tagsPrompt } from "../../core/dream/index.js";
97
97
  import type { NightTokens } from "../../core/dream/index.js";
98
98
  import { addDays, isDay, localDate } from "../../core/time.js";
99
99
  import { TUNABLES as SCHEMAS_TUNABLES } from "../../core/schemas/index.js";
@@ -110,6 +110,8 @@ import type { AdapterConfig } from "../config.js";
110
110
  import { DEFAULT_HOST_COMMAND, KILL_GRACE_MS, PERMISSION_MODE, REAP_GRACE_MS, startChild } from "./child.js";
111
111
  import { runCatchUp } from "./night-catch-up.js";
112
112
  import type { CatchUpReport } from "./night-catch-up.js";
113
+ import { childFailure } from "./child-error.js";
114
+ import type { ChildFailure } from "./child-error.js";
113
115
  import { childUsage, parseToolSpills } from "./transcript.js";
114
116
  import type { ToolSpills } from "./transcript.js";
115
117
  import type { ChildPlan, ChildResult } from "./child.js";
@@ -301,9 +303,18 @@ export const HOST_SESSION_ENV = [
301
303
  /**
302
304
  * The whole night — or, with `dreamSkipped` (2026-10-11), its catch-up alone:
303
305
  * started because write-ups from an earlier day are owed while the dream is
304
- * not due (`Dreams#catchUpOffer`) — or the reflection alone.
306
+ * not due (`Dreams#catchUpOffer`) — or the reflection alone. `owedAsNew` (S2
307
+ * review, 2026-10-26): a whole night the gate would have run as its catch-up
308
+ * alone, made whole because the write-ups owed were counted as new
309
+ * (`dream.OWED_COUNTS_AS_NEW`); it dreams only if its catch-up delivers them.
305
310
  */
306
- export type NightKind = { readonly kind: "night"; readonly dreamSkipped?: CatchUpOnlyReason } | { readonly kind: "reflection"; readonly dream: string };
311
+ export type NightKind =
312
+ | { readonly kind: "night"; readonly dreamSkipped?: CatchUpOnlyReason; readonly owedAsNew?: true }
313
+ | { readonly kind: "reflection"; readonly dream: string };
314
+
315
+ /** `NIGHT_KIND_ENV`'s value for a whole night made so by owed write-ups. An
316
+ * older `readKind` reads it as the whole night, the forgiving direction. */
317
+ export const OWED_AS_NEW_KIND = "night:owed-as-new";
307
318
 
308
319
  /** A child of the run (2026-10-11): the page writer and the dream, or the reflection. */
309
320
  export type NightChild = NightChildRun["child"];
@@ -311,13 +322,15 @@ export type NightChild = NightChildRun["child"];
311
322
  /** `night`, `catch-up:<why the dream is skipped>` or `reflection:<id>`, for `NIGHT_KIND_ENV`. */
312
323
  export function kindValue(k: NightKind): string {
313
324
  if (k.kind === "reflection") return `reflection:${k.dream}`;
314
- return k.dreamSkipped === undefined ? "night" : `catch-up:${k.dreamSkipped}`;
325
+ if (k.dreamSkipped !== undefined) return `catch-up:${k.dreamSkipped}`;
326
+ return k.owedAsNew === true ? OWED_AS_NEW_KIND : "night";
315
327
  }
316
328
 
317
329
  /** The reverse, forgiving: anything unreadable is the whole night. */
318
330
  export function readKind(raw: string | undefined): NightKind {
319
331
  const v = (raw ?? "").trim();
320
332
  if (v.startsWith("reflection:") && v.length > "reflection:".length) return { kind: "reflection", dream: v.slice("reflection:".length) };
333
+ if (v === OWED_AS_NEW_KIND) return { kind: "night", owedAsNew: true };
321
334
  const why = v.startsWith("catch-up:") ? v.slice("catch-up:".length) : "";
322
335
  if ((CATCH_UP_ONLY_REASONS as readonly string[]).includes(why)) return { kind: "night", dreamSkipped: why as CatchUpOnlyReason };
323
336
  return { kind: "night" };
@@ -707,6 +720,16 @@ export async function runNight(input: NightRunInput): Promise<NightRun> {
707
720
  // earlier day were owed while the dream was not due. Its dream and its
708
721
  // reflection are skipped, and the row says why — never a failed dream.
709
722
  if (input.kind.dreamSkipped !== undefined) return catchUpOnlyEnd(input, report, children, ended, (d) => (date = d));
723
+ // MADE WHOLE BY OWED WRITE-UPS (S2 review, 2026-10-26): the hook counted
724
+ // each owed session as one new memory before the catch-up ran. Read the
725
+ // queue again now: when what the catch-up wrote did not bring it to
726
+ // `MIN_NEW` — a seat that refused or failed it, a writer that found
727
+ // nothing — the night ends as the catch-up alone, as the gate would have
728
+ // run it, rather than buying a writer, a dream and a reflection on too
729
+ // little new, every night the debt stays owed.
730
+ if (input.kind.owedAsNew === true && !dreamDueAfterCatchUp(input)) {
731
+ return catchUpOnlyEnd({ ...input, kind: { kind: "night", dreamSkipped: "too-little-new" } }, report, children, ended, (d) => (date = d));
732
+ }
710
733
  }
711
734
 
712
735
  // A STORE THAT WILL NOT OPEN is not opened a second time just to say so:
@@ -823,7 +846,6 @@ export async function runNight(input: NightRunInput): Promise<NightRun> {
823
846
  const tags = await tagsAfter(input.open, seat, (text) => seatAsk("tags", { prompt: text, run: input.run, session: input.session, scope: input.scope, limits: { turns: TUNABLES.NIGHT_TAGS_MAX_TURNS, ms: TUNABLES.NIGHT_TAGS_MS } }), input.session);
824
847
  if (tags !== null) children.push(tags);
825
848
  }
826
- const ms = now() - startedAt;
827
849
  // THE RUN'S EXIT, from its children: stopped if any was stopped; the first
828
850
  // non-zero exit, else the last child's. Its code is that child's own (a
829
851
  // stopped child has none), never another child's.
@@ -921,15 +943,26 @@ export async function runNight(input: NightRunInput): Promise<NightRun> {
921
943
  ...(requeued === null ? {} : { requeued }),
922
944
  };
923
945
 
946
+ // WHAT THE FAILING CHILD SAID (2026-10-27, R4): one scrubbed line, or null.
947
+ const failure = result.failure ?? null;
924
948
  if (complete) return ended({ state: "done", reason: null, detail: null, code: exitCode, ...found });
925
949
  if (parts.length > 0) {
926
950
  const reason = result.timedOut ? "watchdog" : exitCode !== 0 ? "exit" : "unfinished";
927
- return ended({ state: "partial", reason, detail: result.timedOut ? result.error : null, code: exitCode, ...found });
951
+ return ended({ state: "partial", reason, detail: result.timedOut ? result.error : exitCode !== 0 ? failure : null, code: exitCode, ...found });
928
952
  }
929
953
  if (result.timedOut) return ended({ state: "timed-out", reason: "watchdog", detail: result.error, code: exitCode, ...found });
930
954
  if (exitCode !== 0) {
931
- if (!began && ms < TUNABLES.NIGHT_QUICK_EXIT_MS) return ended({ state: "could-not-start", reason: "quick-exit", detail: null, code: exitCode });
932
- return ended({ state: "failed", reason: "exit", detail: null, code: exitCode, ...found });
955
+ // SIGNED OUT (2026-10-27, R4 addendum): the host lost its sign-in — on
956
+ // 10-27 an account switched mid-run. Said plainly, as a run that could
957
+ // not start, so the next session asks (`Dreams#fellBack`). Only when it
958
+ // BEGAN NOTHING (review of #656): `fellBack` asks on any could-not-start,
959
+ // and a dream that began is resumed headless instead.
960
+ if (!began && result.signedOut === true) return ended({ state: "could-not-start", reason: "signed-out", detail: failure, code: exitCode, ...found });
961
+ // QUICK, by the failing child's own time (2026-10-27, R4): the run's
962
+ // counted the catch-up before it, and a 55-second catch-up turned three
963
+ // 3-second exits into `exit` rather than `quick-exit` (nrn_8f332b7d176d).
964
+ if (!began && result.ms < TUNABLES.NIGHT_QUICK_EXIT_MS) return ended({ state: "could-not-start", reason: "quick-exit", detail: failure, code: exitCode });
965
+ return ended({ state: "failed", reason: "exit", detail: failure, code: exitCode, ...found });
933
966
  }
934
967
  // What it began could not be read: said as such, never as nothing.
935
968
  if (unread !== null) return ended({ state: "failed", reason: "unread", detail: unread, code: exitCode });
@@ -947,6 +980,24 @@ export async function runNight(input: NightRunInput): Promise<NightRun> {
947
980
  * `done` when it did what it could (its own row says how much), the child's
948
981
  * failure when it could not start, failed or was stopped. Never throws.
949
982
  */
983
+ /**
984
+ * A NIGHT MADE WHOLE BY OWED WRITE-UPS, after its catch-up: is the dream's
985
+ * queue at `MIN_NEW` now? Read on the run's own date. False when the store
986
+ * will not answer: the night falls back to what the gate would have run.
987
+ */
988
+ function dreamDueAfterCatchUp(input: NightRunInput): boolean {
989
+ try {
990
+ const c = input.open();
991
+ try {
992
+ return c.dreams.queuedNew(input.date ?? c.store.today()) >= DREAM_TUNABLES.MIN_NEW;
993
+ } finally {
994
+ c.close();
995
+ }
996
+ } catch {
997
+ return false;
998
+ }
999
+ }
1000
+
950
1001
  function catchUpOnlyEnd(
951
1002
  input: NightRunInput,
952
1003
  report: CatchUpReport | null,
@@ -973,8 +1024,14 @@ function catchUpOnlyEnd(
973
1024
  return ended({ state: "could-not-start", reason: "spawn-failed", detail: "catch-up", code: null });
974
1025
  case "timed-out":
975
1026
  return ended({ state: "timed-out", reason: "watchdog", detail: "catch-up", code });
976
- case "failed":
977
- return ended({ state: "failed", reason: "exit", detail: "catch-up", code });
1027
+ case "failed": {
1028
+ // What its child said (2026-10-27, R4), after the word that says whose.
1029
+ const said = report?.detail ?? null;
1030
+ const detail = said === null ? "catch-up" : `catch-up: ${said}`;
1031
+ // The catch-up alone begins no dream: its child's own sign-in reading decides.
1032
+ if (report?.signedOut === true) return ended({ state: "could-not-start", reason: "signed-out", detail, code });
1033
+ return ended({ state: "failed", reason: "exit", detail, code });
1034
+ }
978
1035
  default:
979
1036
  return ended({ state: "done", reason: null, detail: null, code, parts: [] });
980
1037
  }
@@ -997,6 +1054,15 @@ export interface NightAnswer extends SeatAnswer {
997
1054
  * it said none; absent from a seat that does not report usage.
998
1055
  */
999
1056
  readonly usage?: NightTokens | null;
1057
+ /**
1058
+ * WHY IT FAILED (2026-10-27, R4): one scrubbed line from what the child
1059
+ * said — its `stream-json` error result, else its last STDERR line
1060
+ * (`child-error.ts#childFailure`). Absent when it exited 0, was stopped,
1061
+ * or said nothing.
1062
+ */
1063
+ readonly failure?: string;
1064
+ /** The failure reads as a lost sign-in, from the host's own words (`ChildFailure.signedOut`). */
1065
+ readonly signedOut?: true;
1000
1066
  }
1001
1067
 
1002
1068
  /**
@@ -1069,6 +1135,8 @@ export function claudeCodeSeat(input: ClaudeCodeSeatInput): Seat<ClaudeCodeAnswe
1069
1135
  const at = now();
1070
1136
  const result = await (input.startCatchUp ?? ((p: ChildPlan) => startChild(p)))(check);
1071
1137
  const neverStarted = neverStartedOf(result);
1138
+ // Its output is not kept (it is prose): what it said of a failure is its STDERR.
1139
+ const failure = neverStarted ? null : childFailure(result);
1072
1140
  return {
1073
1141
  refused: null,
1074
1142
  started: !neverStarted,
@@ -1077,6 +1145,7 @@ export function claudeCodeSeat(input: ClaudeCodeSeatInput): Seat<ClaudeCodeAnswe
1077
1145
  error: result.error,
1078
1146
  ms: now() - at,
1079
1147
  ...(result.spawnCode === undefined ? {} : { spawnCode: result.spawnCode }),
1148
+ ...(failure === null ? {} : { failure: failure.line, ...(failure.signedOut ? { signedOut: true as const } : {}) }),
1080
1149
  result,
1081
1150
  spill: null,
1082
1151
  };
@@ -1096,6 +1165,7 @@ export function claudeCodeSeat(input: ClaudeCodeSeatInput): Seat<ClaudeCodeAnswe
1096
1165
  ms: out.ms,
1097
1166
  ...(out.result.spawnCode === undefined ? {} : { spawnCode: out.result.spawnCode }),
1098
1167
  ...(out.hostSession === undefined ? {} : { hostSession: out.hostSession }),
1168
+ ...(out.failure === null ? {} : { failure: out.failure.line, ...(out.failure.signedOut ? { signedOut: true as const } : {}) }),
1099
1169
  usage: out.usage,
1100
1170
  result: out.result,
1101
1171
  spill: out.spill,
@@ -1119,6 +1189,8 @@ interface NightChildOutcome {
1119
1189
  readonly hostSession?: string;
1120
1190
  /** What it spent, from its own `result` line; null when it said none. */
1121
1191
  readonly usage: NightTokens | null;
1192
+ /** Why it failed, one scrubbed line, and whether it reads as a lost sign-in (`childFailure`); null when it did not fail, or said nothing. */
1193
+ readonly failure: ChildFailure | null;
1122
1194
  }
1123
1195
 
1124
1196
  /** The row's line for a child that ran. */
@@ -1129,6 +1201,7 @@ function childRunOf(child: NightChild, out: NightAnswer): NightChildRun {
1129
1201
  ms: out.ms,
1130
1202
  ...(out.timedOut ? { timedOut: true as const } : {}),
1131
1203
  ...(out.hostSession === undefined || out.hostSession.length === 0 ? {} : { hostSession: out.hostSession }),
1204
+ ...(out.failure === undefined || out.failure.length === 0 ? {} : { detail: out.failure }),
1132
1205
  };
1133
1206
  }
1134
1207
 
@@ -1184,6 +1257,8 @@ async function runNightChild(
1184
1257
  // WHAT IT SPENT (2026-10-23), from the same output: its last `result` line.
1185
1258
  // A child stopped mid-stream, or retried plain, said none.
1186
1259
  const usage = neverStarted ? null : childUsage(result.output);
1260
+ // WHY IT FAILED (2026-10-27, R4), from the same output or its STDERR.
1261
+ const failure = neverStarted ? null : childFailure(result);
1187
1262
  // ITS RAW OUTPUT, KEPT FOR A DEVELOPER (2026-10-23, `debug.nightTranscripts`,
1188
1263
  // off by default): never on a plain retry, which kept no output.
1189
1264
  if (childInput.config.debug?.nightTranscripts === true && childInput.child !== undefined && named) {
@@ -1199,7 +1274,7 @@ async function runNightChild(
1199
1274
  }
1200
1275
  // Recorded only when the child that ran is the one named: a plain retry
1201
1276
  // ran under an id its host chose, which this process never learns.
1202
- return { result, ms, neverStarted, spill, usage, ...(named && !neverStarted ? { hostSession } : {}) };
1277
+ return { result, ms, neverStarted, spill, usage, failure, ...(named && !neverStarted ? { hostSession } : {}) };
1203
1278
  }
1204
1279
 
1205
1280
  /**
@@ -0,0 +1,160 @@
1
+ /**
2
+ * OLDER WINDOWS AFTER AN UPGRADE, said once by the first watched wake that
3
+ * finds them (U1a, 2026-10-27).
4
+ *
5
+ * When a newer Counterparts upgrades the memory, every Claude Code window
6
+ * opened before it keeps running the old code — its MCP server (npm and
7
+ * plugin), and its hooks too (plugin) — and from then on refuses or stands
8
+ * down. Each of those says so in its own window (`update-words.ts`), but only
9
+ * when somebody uses it, and a person returning to a window left open
10
+ * overnight meets a refusal with no warning. The window that opened on the
11
+ * new memory is the one place that can see the others: every running server
12
+ * leaves its build in the session registry (`sessions.ts#readServerRecords`),
13
+ * so the believed-live ones (`serverBelieved`) whose schema stamps are older
14
+ * than this code's are the windows to reload.
15
+ *
16
+ * Counted by HOST PROCESS (`hostPid`), not by server: one window can hold
17
+ * more than one record. This window's own host is left out (the hook's
18
+ * parent): it is the one being told. Claude Desktop's app server (place
19
+ * `claude-desktop:`) is named apart, in its own words.
20
+ *
21
+ * EACH WINDOW'S OWN STEP (review of #666): a server record says how its copy
22
+ * came and whether it runs in Desktop's Code tab (`ServerRecord.route`,
23
+ * `codeTab`), so a plugin window is told to reload and an npm one to
24
+ * reconnect, whoever is telling. A record from a build before that says
25
+ * neither, and is read with the caller's fallback (`fallback`): this
26
+ * window's route on Claude Code, both routes from Desktop's server. Windows
27
+ * on different routes get both routes' steps.
28
+ *
29
+ * Said once per store version (`STALE_WINDOWS_TOLD_KEY`, read first, then
30
+ * claimed with `Store.updateMeta`, so two windows starting together say it
31
+ * once and a told line writes nothing), and only at a start a person is
32
+ * watching — the caller's rule, W1's: not the nightly run, `-p`, a compaction
33
+ * or a resume, which would spend it on nobody. Whoever upgraded the memory
34
+ * (this window, the nightly run, Desktop, the console), the line is the same.
35
+ */
36
+ import { CACHE_SCHEMA_VERSION, SCHEMA_VERSION } from "../../core/store/index.js";
37
+ import type { Store } from "../../core/store/index.js";
38
+ import { DESKTOP_HOST, DESKTOP_SCOPE, isPseudoScope, wordingFor } from "../hosts.js";
39
+ import type { InstallRoute } from "../plugin.js";
40
+ import { pidAlive, readServerRecords, serverBelieved } from "../sessions.js";
41
+ import { windowStep } from "../update-words.js";
42
+
43
+ /** The store version the line was last said for (`<store>.<cache>`). */
44
+ export const STALE_WINDOWS_TOLD_KEY = "adapter.update.staleWindows.told";
45
+
46
+ /** What the line is introduced by, for the model: now, not "when it fits" — the person is about to use those windows. */
47
+ export const STALE_WINDOWS_LEAD = "Counterparts — tell your person now:";
48
+
49
+ export interface StaleWindows {
50
+ /** Distinct host processes running a server older than this code. */
51
+ readonly windows: number;
52
+ /** Claude Desktop's own server is one of them. */
53
+ readonly desktop: boolean;
54
+ /** The route those windows' step is for: theirs when they share one, else `either`. */
55
+ readonly route: InstallRoute;
56
+ /** Every one of those windows is in Desktop's Code tab. */
57
+ readonly codeTab: boolean;
58
+ }
59
+
60
+ /** What a window that does not say is taken to be. */
61
+ export interface WindowFallback {
62
+ readonly route: InstallRoute | undefined;
63
+ readonly codeTab: boolean;
64
+ }
65
+
66
+ /**
67
+ * The older servers still running against this store, by window. Reads the
68
+ * registry only; never throws (nothing readable is nothing found).
69
+ */
70
+ export function staleWindows(input: {
71
+ readonly dataDir: string;
72
+ readonly now: number;
73
+ readonly fallback: WindowFallback;
74
+ readonly alive?: (pid: number) => boolean;
75
+ /** A server's own pid, left out (Desktop's wake asks from inside one). */
76
+ readonly selfPid?: number;
77
+ /** The asking window's host process, left out (the hook's parent). */
78
+ readonly selfHostPid?: number;
79
+ }): StaleWindows {
80
+ const none: StaleWindows = { windows: 0, desktop: false, route: input.fallback.route ?? "either", codeTab: input.fallback.codeTab };
81
+ try {
82
+ const alive = input.alive ?? pidAlive;
83
+ const older = readServerRecords(input.dataDir).filter(
84
+ (r) =>
85
+ r.pid !== input.selfPid &&
86
+ (r.build.storeSchema < SCHEMA_VERSION || r.build.cacheSchema < CACHE_SCHEMA_VERSION) &&
87
+ serverBelieved(r.pid, r.refreshedAt, input.now, alive),
88
+ );
89
+ const windows = new Map<number, { route: InstallRoute; codeTab: boolean }>();
90
+ for (const r of older) {
91
+ if (isPseudoScope(r.scope) || r.hostPid === input.selfHostPid) continue;
92
+ const seen = windows.get(r.hostPid);
93
+ const route = r.route ?? input.fallback.route ?? "either";
94
+ const codeTab = r.route === undefined ? input.fallback.codeTab : r.codeTab === true;
95
+ windows.set(r.hostPid, seen === undefined ? { route, codeTab } : { route: seen.route === route ? route : "either", codeTab: seen.codeTab && codeTab });
96
+ }
97
+ const each = [...windows.values()];
98
+ const routes = new Set(each.map((w) => w.route));
99
+ return {
100
+ windows: each.length,
101
+ desktop: older.some((r) => r.scope === DESKTOP_SCOPE),
102
+ route: routes.size === 1 ? (each[0]?.route ?? "either") : "either",
103
+ codeTab: each.length > 0 && each.every((w) => w.codeTab),
104
+ };
105
+ } catch {
106
+ return none;
107
+ }
108
+ }
109
+
110
+ /** The sentence, from what was found. Pure. */
111
+ export function staleWindowsWords(found: StaleWindows): string | null {
112
+ if (found.windows === 0 && !found.desktop) return null;
113
+ const parts: string[] = [];
114
+ const step = windowStep(found.route, found.codeTab);
115
+ if (found.windows === 1) {
116
+ parts.push(`1 Claude Code window opened before that can't use it until it's reloaded: there, ${step}.`);
117
+ } else if (found.windows > 1) {
118
+ parts.push(`${String(found.windows)} Claude Code windows opened before that can't use it until they're reloaded: in each, ${step}.`);
119
+ }
120
+ if (found.desktop) {
121
+ const quit = wordingFor(DESKTOP_HOST).reconnectFirst;
122
+ parts.push(`Claude Desktop, open since before that, can't use it until you ${quit.charAt(0).toLowerCase()}${quit.slice(1)}.`);
123
+ }
124
+ return `${STALE_WINDOWS_LEAD} "My memory was just upgraded to a newer version. ${parts.join(" ")}"`;
125
+ }
126
+
127
+ /**
128
+ * THE WAKE'S LINE, or null: older servers found, and this store version not
129
+ * told yet — claimed here, so it is said by exactly one wake. The caller
130
+ * decides the start is watched. Never throws: a claim that cannot be written
131
+ * is no line (the next watched wake tries again).
132
+ */
133
+ export function staleWindowsLine(input: {
134
+ readonly store: Store;
135
+ readonly fallback: WindowFallback;
136
+ readonly now: number;
137
+ readonly alive?: (pid: number) => boolean;
138
+ readonly selfPid?: number;
139
+ readonly selfHostPid?: number;
140
+ }): { readonly line: string; readonly found: StaleWindows } | null {
141
+ try {
142
+ const tag = `${String(SCHEMA_VERSION)}.${String(CACHE_SCHEMA_VERSION)}`;
143
+ // Told already: nothing to read further, and nothing written.
144
+ if (input.store.getMeta(STALE_WINDOWS_TOLD_KEY) === tag) return null;
145
+ const found = staleWindows({
146
+ dataDir: input.store.dir,
147
+ now: input.now,
148
+ fallback: input.fallback,
149
+ ...(input.alive === undefined ? {} : { alive: input.alive }),
150
+ ...(input.selfPid === undefined ? {} : { selfPid: input.selfPid }),
151
+ ...(input.selfHostPid === undefined ? {} : { selfHostPid: input.selfHostPid }),
152
+ });
153
+ const line = staleWindowsWords(found);
154
+ if (line === null) return null;
155
+ const claimed = input.store.updateMeta(STALE_WINDOWS_TOLD_KEY, (current) => (current === tag ? undefined : tag));
156
+ return claimed === tag ? { line, found } : null;
157
+ } catch {
158
+ return null;
159
+ }
160
+ }
@@ -34,11 +34,15 @@ import { homedir } from "node:os";
34
34
  import { join } from "node:path";
35
35
 
36
36
  import { isLocked } from "../../core/store/db.js";
37
- import { assertSafeDataDir, isStoreError } from "../../core/store/index.js";
37
+ import { WAKE_BUILD_KEY } from "../../core/self/behind.js";
38
+ import { assertSafeDataDir, isStoreError, peekMeta } from "../../core/store/index.js";
38
39
  import type { StoreErrorCode } from "../../core/store/index.js";
40
+ import { versionCore } from "../host-wiring.js";
39
41
  import { SESSIONS_DIR, isSessionId } from "../sessions.js";
42
+ import { coreNewer } from "../update-words.js";
40
43
 
41
- /** The last words of every stand-down message, and the only ones never cut. */
44
+ /** The last words of every general stand-down message, and the only ones never cut
45
+ * (a fault with its own words, `StandDownFault.say`, ends in its own step instead). */
42
46
  export const STANDDOWN_TAIL = "Run: counterparts doctor";
43
47
 
44
48
  /**
@@ -77,6 +81,13 @@ export interface StandDownFault {
77
81
  /** One clause of plain words. Never memory text; a path is allowed. */
78
82
  readonly reason: string;
79
83
  readonly kind: StandDownKind;
84
+ /**
85
+ * THE WORDS, when this fault has its own for both readers
86
+ * (`newerStoreSay`, U1a): the person's line in place of
87
+ * `standDownMessage`'s, and a line for the model, so it does not act as if
88
+ * it remembers. Absent: the general red line, to the person only.
89
+ */
90
+ readonly say?: { readonly person: string; readonly model: string };
80
91
  }
81
92
 
82
93
  /** The configuration a caller NAMED could not be honoured (`config-path.ts`). */
@@ -301,6 +312,7 @@ function tildeHome(text: string, home: string = homedir()): string {
301
312
  * error message, and error messages in this codebase carry codes, ids and paths.
302
313
  */
303
314
  export function standDownMessage(fault: StandDownFault): string {
315
+ if (fault.say !== undefined) return fault.say.person;
304
316
  const reason = tildeHome(oneLine(fault.reason));
305
317
  const said =
306
318
  reason.length <= STANDDOWN_REASON_MAX_CHARS
@@ -309,6 +321,52 @@ export function standDownMessage(fault: StandDownFault): string {
309
321
  return `Counterparts memory is OFF for this session: ${said} (${fault.code}). ${STANDDOWN_TAIL}`;
310
322
  }
311
323
 
324
+ /**
325
+ * A MEMORY A NEWER COUNTERPARTS UPGRADED (`SCHEMA_AHEAD`, U1a, 2026-10-27).
326
+ *
327
+ * The general line ends "Run: counterparts doctor", and the commonest way here
328
+ * is a plugin update in another window: this window's hooks keep the old
329
+ * folder until `/reload-plugins`, and a plugin install has no `counterparts`
330
+ * command at all. So this fault says the step instead, in the route's words
331
+ * (`update-words.ts#newerStoreWords`, the same sentence the MCP server's
332
+ * refusal is built from), to the person — and to the model too, the paused
333
+ * notice's pattern, so it does not act as if it remembers. Said as often as
334
+ * any persistent fault (`decideSay`). `words` is the whole sentence.
335
+ */
336
+ export function newerStoreSay(fault: StandDownFault, words: string): StandDownFault {
337
+ const lower = `${words.charAt(0).toLowerCase()}${words.slice(1)}`;
338
+ return {
339
+ ...fault,
340
+ say: {
341
+ person: `Counterparts memory is OFF in this window: ${lower}`,
342
+ model:
343
+ `Counterparts memory is off in this window: ${lower} Until then no memories are loaded and nothing said ` +
344
+ "here is remembered. Don't act as if you remember earlier sessions; tell the person this step.",
345
+ },
346
+ };
347
+ }
348
+
349
+ /**
350
+ * THE VERSION THAT UPGRADED A MEMORY THIS COPY REFUSED (F1, 2026-10-27, after
351
+ * the review of #666): the wake's build stamp, read on its own connection
352
+ * from the database the store refused (`store#peekMeta`) — the store would not
353
+ * open, so there is no `Store#getMeta` to ask. The MCP server's rule exactly
354
+ * (`mcp/server.ts#newerStoreRoute`): only a version-shaped stamp, and only
355
+ * when it is newer than this copy, so the plugin's reload is said only into a
356
+ * record at least as new as the writer (`update-words.ts#newerStoreStep`).
357
+ * Null when there is no path (the cache's own `SCHEMA_AHEAD` names none), no
358
+ * stamp, or nothing newer; never throws.
359
+ */
360
+ export function aheadWriter(dbPath: string | null, loaded: string | null): string | null {
361
+ if (dbPath === null || dbPath.length === 0) return null;
362
+ try {
363
+ const wrote = versionCore(peekMeta(dbPath, WAKE_BUILD_KEY));
364
+ return coreNewer(wrote, loaded) ? wrote : null;
365
+ } catch {
366
+ return null;
367
+ }
368
+ }
369
+
312
370
  /**
313
371
  * THE TWO THINGS A BUSY DATABASE SAYS, and neither of them says OFF.
314
372
  *
@@ -503,6 +561,9 @@ export type SaysSoHook = "session-start" | "user-prompt-submit";
503
561
  export interface SayDecision {
504
562
  /** The message to display, or null to stay on stderr alone. */
505
563
  readonly message: string | null;
564
+ /** The model's line, said exactly when `message` is and the fault has one
565
+ * (`StandDownFault.say`); else null. */
566
+ readonly model: string | null;
506
567
  /** The mark this event leaves. Written whether or not anything was said — a
507
568
  * transient nobody was told about is still one this session has met. */
508
569
  readonly mark: StandDownMark;
@@ -549,7 +610,11 @@ export function decideSay(
549
610
  };
550
611
  if (fault.kind === "persistent") {
551
612
  const say = hook === "session-start" || !base.told;
552
- return { message: say ? standDownMessage(fault) : null, mark: { ...base, told: base.told || say } };
613
+ return {
614
+ message: say ? standDownMessage(fault) : null,
615
+ model: say ? (fault.say?.model ?? null) : null,
616
+ mark: { ...base, told: base.told || say },
617
+ };
553
618
  }
554
619
  const count = was.count + 1;
555
620
  // THE ESCALATION OUTRANKS THE SOFT LINE, and is its own once: a session that
@@ -558,6 +623,7 @@ export function decideSay(
558
623
  if (count >= TRANSIENT_ESCALATE_AFTER && !was.escalated) {
559
624
  return {
560
625
  message: busyWedgedMessage(count),
626
+ model: null,
561
627
  mark: { ...base, transient: { count, at: now, told: true, escalated: true } },
562
628
  };
563
629
  }
@@ -568,6 +634,7 @@ export function decideSay(
568
634
  ? BUSY_SESSION_START_MESSAGE
569
635
  : BUSY_TURN_MESSAGE
570
636
  : null,
637
+ model: null,
571
638
  mark: { ...base, transient: { count, at: now, told: was.told || say, escalated: was.escalated } },
572
639
  };
573
640
  }
@@ -417,3 +417,17 @@ really closes; a hook turn measured the same before and after. `store/NOTES.md`,
417
417
  writes `dreams/` (each journal and its change log) and `reflections/` (each entry and
418
418
  morning share) beside the memories. What a dream was shown and what undoing it needs
419
419
  stay in the database, which the database export and `backup` copy whole.
420
+
421
+ ## Counterparts Online beside this install (2026-10-27, R1)
422
+
423
+ - **Claude Desktop's chat loads claude.ai connectors too, and has no deny list we know of.**
424
+ `connect` keeps the hosted connector out of Claude Code with one `deniedMcpServers` entry
425
+ (`wire.ts#mergeDeny`), but a person with this install's Desktop entry (`install --host
426
+ claude-desktop`) and the hosted connector gets two memories in Desktop's chat, over two
427
+ stores. Desktop's Code tab takes connectors from the app as well, where settings files do
428
+ not apply. Needs its own answer; not built.
429
+ - **That a `serverUrl` entry alone keeps a claude.ai connector out is not proven here.**
430
+ The trial config that worked had a `serverName` entry beside it. The check is `/mcp` in a
431
+ Claude Code session once the hosted connector is added (a RUNBOOK §7 step at deploy).
432
+ - **A plugin-only install gets no deny entry and no doctor line for it.** The plugin wires
433
+ nothing in `settings.json`, and its `connect` would wire the host a second time.