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
@@ -14,10 +14,10 @@
14
14
  */
15
15
  import { readFileSync } from "node:fs";
16
16
  import { homedir } from "node:os";
17
- import { resolve } from "node:path";
17
+ import { join, resolve } from "node:path";
18
18
  import { fileURLToPath } from "node:url";
19
19
 
20
- import { DATA_DIR_ENV, dataDir, describeGuardRefusal } from "../../../core/store/index.js";
20
+ import { DATABASE_FILE, DATA_DIR_ENV, dataDir, describeGuardRefusal, isStoreError } from "../../../core/store/index.js";
21
21
  import {
22
22
  defaultConfigPath,
23
23
  implicitConfigRefusal,
@@ -51,14 +51,20 @@ import { NIGHT_RUN_ENV } from "../night-run.js";
51
51
  import {
52
52
  CONFIG_REFUSED,
53
53
  CONFIG_UNREADABLE,
54
+ aheadWriter,
54
55
  classifyStandDown,
55
56
  decideSay,
57
+ newerStoreSay,
56
58
  readMark,
57
59
  writeMark,
58
60
  } from "../standdown.js";
61
+ import { CODE_TAB_ENTRYPOINT } from "../../hosts.js";
62
+ import { newerStoreWords } from "../../update-words.js";
59
63
  import type { SaysSoHook, StandDownFault } from "../standdown.js";
60
64
  import { readTranscript } from "../transcript.js";
61
65
  import { BINARY, entryScript, scriptArgs } from "../../runtime.js";
66
+ import { usePrivateUmask } from "../../private-umask.js";
67
+ import { tightenInstallBase } from "../../private-base.js";
62
68
  import type { Binary } from "../../runtime.js";
63
69
  import { noteNpmLive, npmWiringForGate } from "../../npm-live.js";
64
70
  import {
@@ -70,6 +76,7 @@ import {
70
76
  installRoute,
71
77
  markTwiceSaid,
72
78
  pluginOrigin,
79
+ recordedForThisCopy,
73
80
  runningAsPlugin,
74
81
  takeFirstRunNotice,
75
82
  twiceNoticePath,
@@ -566,8 +573,11 @@ interface Said {
566
573
  * ONE LINE ON STDERR ALWAYS — AND, WHEN THIS WAS A FAULT, ONE RED LINE WHERE
567
574
  * THE OWNER WILL SEE IT.
568
575
  *
569
- * Exit code is untouched (0, always) and nothing else is injected: no wake, no
570
- * context, just the `systemMessage` the host displays. WHAT to say and WHETHER
576
+ * Exit code is untouched (0, always) and no wake is injected: just the
577
+ * `systemMessage` the host displays — and, for the one fault that has a line
578
+ * for the model (`StandDownFault.say`: a memory a newer Counterparts upgraded),
579
+ * that line as `additionalContext`, so the model does not act as if it
580
+ * remembers. WHAT to say and WHETHER
571
581
  * to say it is `standdown.ts#decideSay`'s, which is the rule that tells a store
572
582
  * that will not open from a database that was merely busy; this function is the
573
583
  * process end of it — the two channels, the mark, and the ordering.
@@ -592,10 +602,61 @@ function standDown(
592
602
  // still one this session has met, and the count is what decides the next one.
593
603
  writeMark(dataDir, said.sessionId, decision.mark);
594
604
  if (decision.message === null) return;
595
- process.stdout.write(JSON.stringify({ systemMessage: decision.message }));
605
+ // A FAULT WITH A LINE FOR THE MODEL TOO (U1a: a memory a newer Counterparts
606
+ // upgraded) rides the envelope the paused notice does (`sayPaused`): the
607
+ // person's line as `systemMessage`, the model's as `additionalContext`.
608
+ process.stdout.write(
609
+ decision.model === null
610
+ ? JSON.stringify({ systemMessage: decision.message })
611
+ : hostDelivery(said.hook, { injection: decision.model, ask: null }, {}, [decision.message]).stdout,
612
+ );
596
613
  said.wroteStdout = true;
597
614
  }
598
615
 
616
+ /**
617
+ * THE STAND-DOWN'S WORDS FOR A STORE A NEWER COUNTERPARTS UPGRADED (U1a,
618
+ * 2026-10-27), or the fault unchanged. The step is this copy's route's
619
+ * (`update-words.ts#newerStoreWords`): a hook is the code installed at its own
620
+ * path, so on npm a store ahead of it means the install is the older one
621
+ * (update); on the plugin it is the folder Claude Code loaded for this window,
622
+ * and `installed_plugins.json` says whether `/reload-plugins` would load a
623
+ * newer one (reload) or not (update first). Read only when the fault is this
624
+ * one; never throws — a fact it cannot read gives the update words.
625
+ *
626
+ * THE WRITER TOO (F1, after the review of #666): reload only into a record at
627
+ * least as new as the version that upgraded the memory. The store refused to
628
+ * open, so its wake stamp is read from the database file on its own
629
+ * connection (`standdown.ts#aheadWriter`): the path the refusal named, else
630
+ * the configured store's (the cache's refusal names none). Read off the npm
631
+ * route only, as the server does — npm's step is the update either way.
632
+ */
633
+ function withNewerStoreWords(
634
+ fault: StandDownFault | null,
635
+ payload: Record<string, unknown>,
636
+ err: unknown,
637
+ storeDir: string | undefined,
638
+ ): StandDownFault | null {
639
+ if (fault === null || fault.code !== "SCHEMA_AHEAD") return fault;
640
+ try {
641
+ const route = installRoute(process.env);
642
+ const cwd = process.env["CLAUDE_PROJECT_DIR"] ?? eventDirectory(payload);
643
+ const loaded = installedVersion();
644
+ const named = isStoreError(err) ? err.detail["path"] : undefined;
645
+ const dbPath = typeof named === "string" ? named : storeDir === undefined ? null : join(storeDir, DATABASE_FILE);
646
+ const words = newerStoreWords({
647
+ route,
648
+ who: "hook",
649
+ loaded,
650
+ recorded: route === "npm" ? null : recordedForThisCopy({ home: homedir(), env: process.env, cwd }),
651
+ writer: route === "npm" ? null : aheadWriter(dbPath, loaded),
652
+ codeTab: (process.env["CLAUDE_CODE_ENTRYPOINT"] ?? "") === CODE_TAB_ENTRYPOINT,
653
+ });
654
+ return newerStoreSay(fault, words);
655
+ } catch {
656
+ return fault;
657
+ }
658
+ }
659
+
599
660
  /**
600
661
  * A configuration refusal as a REASON clause. `config-path.ts` writes its
601
662
  * sentences to stand alone on stderr, so each opens with `refused: ` — which
@@ -708,7 +769,7 @@ async function main(): Promise<void> {
708
769
  const remedy = `Set "dataDir" in ${choice.path}, or set ${DATA_DIR_ENV}.`;
709
770
  standDown(said, {
710
771
  line: describeGuardRefusal(err, remedy) ?? detail,
711
- fault: classifyStandDown(err),
772
+ fault: withNewerStoreWords(classifyStandDown(err), payload, err, said.dataDir),
712
773
  marker: true,
713
774
  });
714
775
  }
@@ -837,6 +898,8 @@ async function runHook(
837
898
  // From here the configuration was understood, so the store it names is the one
838
899
  // a stand-down may leave its once-per-session mark under.
839
900
  said.dataDir = loaded.dataDir;
901
+ // The install's base directory, private (R1, `private-base.ts`): once a session.
902
+ if (name === "session-start" && loaded.dataDir !== undefined) tightenInstallBase(choice.path, loaded.dataDir);
840
903
  // THE SESSION'S OWN DIRECTORY — the one everything this event captures will be
841
904
  // FILED under, whatever directory the agent's shell has wandered into. It is
842
905
  // resolved here rather than above because its first source is the session
@@ -1096,6 +1159,7 @@ export function isEntryPoint(argv1: string | undefined, url: string, binary: Bin
1096
1159
  /** Run the hook and exit — what this file does as a script, and what the
1097
1160
  * single binary's `hook` mode calls. */
1098
1161
  export function start(): void {
1162
+ usePrivateUmask();
1099
1163
  void main().then(
1100
1164
  () => process.exit(process.exitCode === 2 ? 2 : 0),
1101
1165
  (err: unknown) => {
@@ -13,6 +13,7 @@
13
13
  */
14
14
  import { implicitConfigRefusal, namedConfigRefusal, namedUnreadableRefusal } from "../../config-path.js";
15
15
  import { openLog } from "../../log/index.js";
16
+ import { usePrivateUmask } from "../../private-umask.js";
16
17
  import { nightChildrenWords } from "../../../core/dream/index.js";
17
18
 
18
19
  import { NIGHT_KIND_ENV, NIGHT_RUN_ENV, openNightCounterpart, readKind, runNight } from "../night-run.js";
@@ -90,6 +91,7 @@ function standDown(config: Parameters<typeof openNightCounterpart>[0], run: stri
90
91
  /** The nightly run, then exit — what this file does as a script, and what the
91
92
  * single binary's `nightly` mode calls. */
92
93
  export function start(): void {
94
+ usePrivateUmask();
93
95
  void main().then(
94
96
  () => process.exit(0),
95
97
  (err: unknown) => {
@@ -84,7 +84,9 @@ import { dataDir, describeGuardRefusal } from "../../../core/store/index.js";
84
84
  import type { Store } from "../../../core/store/index.js";
85
85
  import { hostSessionEvidence, installedVersion, writeUpSources } from "../../sessions.js";
86
86
  import { openLog } from "../../log/index.js";
87
- import { BINARY } from "../../runtime.js";
87
+ import { BINARY, TRANSPILED } from "../../runtime.js";
88
+ import { installRoute } from "../../plugin.js";
89
+ import { usePrivateUmask } from "../../private-umask.js";
88
90
  import type { Binary } from "../../runtime.js";
89
91
 
90
92
  import {
@@ -105,6 +107,8 @@ import { DATA_DIR_ENV, SCOPE_ENV, SESSION_ENV, WATCHDOG_ENV } from "../../spawn.
105
107
  import { backfillVectors, laggedSemantic } from "../vectors.js";
106
108
  import type { BackfillReport, LagReport } from "../vectors.js";
107
109
  import { removeSidebarStatus, sidebarInstalled, writeSidebarStatus } from "../../sidebar-status.js";
110
+ import { askedOff, claudeAutoUpdate, pluginMarket, runUpdateCheck } from "../../update-check.js";
111
+ import type { FetchLike, UpdateCheckReport } from "../../update-check.js";
108
112
  import type { SidebarWrite } from "../../sidebar-status.js";
109
113
  import { runSnapshot } from "../../snapshots.js";
110
114
  import type { SnapshotRunReport } from "../../snapshots.js";
@@ -157,6 +161,9 @@ export interface RunReport {
157
161
  /** The sidebar's status file (`adapters/sidebar-status.ts`), written after the
158
162
  * store closed; absent when the run was not asked to (no configuration path). */
159
163
  readonly sidebar?: SidebarWrite;
164
+ /** The daily update check (`adapters/update-check.ts`), after the store
165
+ * closed; absent when the run was not asked to (no configuration path). */
166
+ readonly updates?: UpdateCheckReport;
160
167
  }
161
168
 
162
169
  /** What the retention step came to on one worker run. */
@@ -328,6 +335,17 @@ export async function runOnce(input: {
328
335
  /** The configuration this run read: the sidebar's status file is written
329
336
  * beside it once the run is done (`adapters/sidebar-status.ts`). Absent: none. */
330
337
  sidebarConfigPath?: string;
338
+ /** THE DAILY UPDATE CHECK (U1b): the configuration this run read (its
339
+ * `updates.json` goes beside it), the fetch to make the one request with,
340
+ * and the environment its switches are read from. Absent: no check — a
341
+ * test, an embedder, or the directory flavor (`runtime.ts#TRANSPILED`). */
342
+ updateCheck?: {
343
+ readonly configPath: string;
344
+ readonly fetch: FetchLike;
345
+ readonly env: Record<string, string | undefined>;
346
+ /** Claude Code keeps this plugin updated itself: no request. */
347
+ readonly autoUpdate?: boolean;
348
+ };
331
349
  onEvent?: (name: string, data: Record<string, string | number | boolean | null>) => void;
332
350
  }): Promise<RunReport> {
333
351
  const { config } = input;
@@ -366,6 +384,10 @@ export async function runOnce(input: {
366
384
  // or a replay with a pinned date would dedup against the wall clock instead.
367
385
  // The person's day, in the store's zone (docs/time.md; UTC before 2026-09-25).
368
386
  const today = input.date ?? counterpart.store.today();
387
+ // Read now, while the store is open: the update check runs after `close()`
388
+ // (it needs no store, and holds none open across its network wait).
389
+ // Fail closed: a store that will not say whether the person said stop is read as stop.
390
+ const updatesAsked = input.updateCheck === undefined ? false : askedOff(counterpart.store, { failClosed: true });
369
391
 
370
392
  let lag: LagReport | null = null;
371
393
  let backfill: BackfillReport | null = null;
@@ -576,7 +598,31 @@ export async function runOnce(input: {
576
598
  });
577
599
  emit("runner.sidebar", { written: sidebar.written, reason: sidebar.reason, bytes: sidebar.bytes, ms: sidebar.ms });
578
600
  }
579
- return { ...result, snapshot: snapshotReport, retention: retentionReport, ...(sidebar === undefined ? {} : { sidebar }) };
601
+ // 6. THE DAILY UPDATE CHECK (U1b, 2026-10-28), after the store closed and
602
+ // beside the sidebar's file: at most one GET of npm's `/latest` a day,
603
+ // carrying nothing about the person (`adapters/update-check.ts`). It never
604
+ // throws, and the watchdog's signal ends it with the run.
605
+ let updates: UpdateCheckReport | undefined;
606
+ if (input.updateCheck !== undefined) {
607
+ updates = await runUpdateCheck({
608
+ configPath: input.updateCheck.configPath,
609
+ config,
610
+ asked: updatesAsked,
611
+ env: input.updateCheck.env,
612
+ date: today,
613
+ fetch: input.updateCheck.fetch,
614
+ ...(input.signal === undefined ? {} : { signal: input.signal }),
615
+ ...(input.updateCheck.autoUpdate === true ? { autoUpdate: true } : {}),
616
+ });
617
+ emit("runner.updates", { reason: updates.reason, switch: updates.switch, code: updates.code ?? null, latest: updates.latest ?? null });
618
+ }
619
+ return {
620
+ ...result,
621
+ snapshot: snapshotReport,
622
+ retention: retentionReport,
623
+ ...(sidebar === undefined ? {} : { sidebar }),
624
+ ...(updates === undefined ? {} : { updates }),
625
+ };
580
626
  }
581
627
 
582
628
  /**
@@ -736,6 +782,9 @@ async function main(): Promise<void> {
736
782
  ...(pinnedScope() === null ? {} : { scope: pinnedScope() as string }),
737
783
  // Only where the sidebar is installed (the plugin); otherwise an old file goes.
738
784
  ...(sidebarWanted ? { sidebarConfigPath: choice.path } : {}),
785
+ // The update check: never in the directory flavor, which reads nothing
786
+ // of Claude Code's and sends nothing anywhere (`runtime.ts#TRANSPILED`).
787
+ ...(TRANSPILED ? {} : { updateCheck: workerUpdateCheck(choice.path) }),
739
788
  onEvent: (name, data) => log.event({ name, data }),
740
789
  });
741
790
  log.end(report.reason, { swept: report.swept, minted: report.minted, code: report.code });
@@ -747,9 +796,22 @@ async function main(): Promise<void> {
747
796
  }
748
797
  }
749
798
 
799
+ /**
800
+ * What this process's update check needs: the configuration's path, the
801
+ * runtime's own `fetch`, this environment, and whether Claude Code keeps this
802
+ * plugin updated itself (read only for a plugin copy).
803
+ */
804
+ function workerUpdateCheck(configPath: string): NonNullable<Parameters<typeof runOnce>[0]["updateCheck"]> {
805
+ const env = process.env;
806
+ const market = installRoute(env) === "plugin" ? pluginMarket({ home: homedir(), env }) : null;
807
+ const autoUpdate = market !== null && market !== "synced" && claudeAutoUpdate({ home: homedir(), env, market });
808
+ return { configPath, fetch: (url, init) => fetch(url, init), env, ...(autoUpdate ? { autoUpdate: true } : {}) };
809
+ }
810
+
750
811
  /** One worker run, then exit — what this file does as a script, and what the
751
812
  * single binary's `runner` mode calls. */
752
813
  export function start(): void {
814
+ usePrivateUmask();
753
815
  void main().then(
754
816
  () => process.exit(0),
755
817
  (err: unknown) => {
@@ -0,0 +1,211 @@
1
+ /**
2
+ * WHY A NIGHT CHILD FAILED, IN ONE SHORT LINE (2026-10-27, R4).
3
+ *
4
+ * Night run nrn_8f332b7d176d (10-27) failed: every child exited 1 in a few
5
+ * seconds with no tokens, and the row said only "claude exited with an error
6
+ * (exit 1)". The children run with `--no-session-persistence`, so there is no
7
+ * transcript, and nothing of what the host said was kept: the cause was
8
+ * unrecoverable. (It was a sign-in lost mid-run — the owner switched Claude
9
+ * Code accounts.)
10
+ *
11
+ * What a failed child said is read from what is ALREADY read of it, no new
12
+ * flag: its own `stream-json` `result` line when its output is kept (the
13
+ * night's named children), else a line of its STDERR (every child).
14
+ * Measured on 2.1.311 with no sign-in: `claude -p` writes
15
+ * `Not logged in · Please run /login` to STDOUT (a `result` line with
16
+ * `is_error: true`, `subtype: "success"`, `terminal_reason: "api_error"`
17
+ * under `stream-json`; the bare line in text mode) and nothing to STDERR; an
18
+ * unknown flag goes to STDERR (`error: unknown option '--x'`).
19
+ *
20
+ * A result's own TEXT is read only when it is the host's API error (review of
21
+ * #656): `terminal_reason: "api_error"`, an `api_error_status`, or the
22
+ * measured signed-out shape (`subtype: "success"` with `is_error`). Any other
23
+ * error result (`error_max_turns`, `error_during_execution`) may carry the
24
+ * model's own words, so only its subtype and status are kept, with the STDERR
25
+ * line beside them.
26
+ *
27
+ * The line is bounded (`CHILD_ERROR_MAX`), one line, home paths shortened to
28
+ * `~`, and SCRUBBED by shape, not by known names (`scrubSecrets`).
29
+ */
30
+ import { homedir } from "node:os";
31
+
32
+ import type { ChildResult } from "./child.js";
33
+
34
+ /** **CAL.** The most of a failure's line kept, characters. */
35
+ export const CHILD_ERROR_MAX = 300;
36
+
37
+ const REDACTED = "[redacted]";
38
+
39
+ /** A label that names a credential: `token`, `access_token`, `x-api-key`, `api key`, `pw`, …. */
40
+ const LABEL = String.raw`[A-Za-z_-]*(?:token|key|secret|password|passwd|pwd|pw|credentials?)|api[ _-]?key`;
41
+
42
+ /**
43
+ * SCRUB A LINE OF ANYTHING TOKEN- OR KEY-SHAPED, by pattern:
44
+ * - `Authorization` with its value, scheme included (`Basic …`, `Bearer …`);
45
+ * everything after `Cookie:`/`Cookie=` (each name=value in it); the word
46
+ * after `Bearer`;
47
+ * - the value after a credential label — bare, JSON or quoted
48
+ * (`token=v`, `{"token":"v"}`, `"access_token": "v"`, `'pw': 'v'`) — with
49
+ * `:` or `=`; and with only a space (`x-api-key abc1…`, `api key abc1…`)
50
+ * when the value has a digit in it or is 16+ characters, so
51
+ * "Invalid API key provided" stays words;
52
+ * - known prefixes: `sk-…`, GitHub `ghp_`/`gho_`/`ghu_`/`ghs_`/`ghr_`/
53
+ * `github_pat_…`, Slack `xox?-…`, AWS `AKIA…`;
54
+ * - any run of 20+ characters from `[A-Za-z0-9_\-.+/=]` with a digit in it
55
+ * (keys, OAuth and JWT tokens, request ids, long hashes — and, over-eager
56
+ * by design, a long path or host name with a digit).
57
+ * Ordinary words, short numbers (`401`, `exit 1`) and punctuation stay.
58
+ */
59
+ export function scrubSecrets(text: string): string {
60
+ return (
61
+ text
62
+ .replace(/\b(authorization)(["']?\s*[:=]\s*["']?|\s+)(?:(?:basic|bearer|token|digest|negotiate)\s+)?[^\s"']+/gi, (_m, label: string, sep: string) => `${label}${sep}${REDACTED}`)
63
+ .replace(/\b(cookie)(["']?\s*[:=]\s*)[^"'\n]*/gi, (_m, label: string, sep: string) => `${label}${sep}${REDACTED}`)
64
+ .replace(/\b(bearer)(\s+)[^\s"']{6,}/gi, (_m, label: string, sep: string) => `${label}${sep}${REDACTED}`)
65
+ .replace(new RegExp(String.raw`\b(${LABEL})(["']?\s*[:=]\s*["']?)[^\s"']+`, "gi"), (_m, label: string, sep: string) => `${label}${sep}${REDACTED}`)
66
+ .replace(new RegExp(String.raw`\b(${LABEL})(\s+)([^\s"']{6,})`, "gi"), (m, label: string, sep: string, value: string) =>
67
+ /\d/.test(value) || value.length >= 16 ? `${label}${sep}${REDACTED}` : m,
68
+ )
69
+ .replace(/\bsk-[A-Za-z0-9_-]{8,}/g, REDACTED)
70
+ .replace(/\b(?:gh[pousr]_|github_pat_)[A-Za-z0-9_]{10,}/g, REDACTED)
71
+ .replace(/\bxox[a-z]-[A-Za-z0-9-]{8,}/g, REDACTED)
72
+ .replace(/\bAKIA[0-9A-Z]{12,}/g, REDACTED)
73
+ .replace(/[A-Za-z0-9_\-.+/=]{20,}/g, (run) => (/\d/.test(run) ? REDACTED : run))
74
+ );
75
+ }
76
+
77
+ /** Home directories shortened to `~`: this user's, and any `/Users/<name>` or `/home/<name>`. */
78
+ function shortenHomes(text: string): string {
79
+ let out = text;
80
+ const home = homedir();
81
+ if (home.length > 1) out = out.split(home).join("~");
82
+ return out.replace(/\/(?:Users|home)\/[^/\s"':]+/g, "~");
83
+ }
84
+
85
+ /** One line: ANSI and OSC sequences and control characters out, whitespace collapsed, home paths shortened, scrubbed, bounded. */
86
+ export function oneLine(text: string): string {
87
+ const flat = text
88
+ // eslint-disable-next-line no-control-regex
89
+ .replace(/\u001b\][^\u0007\u001b]*(\u0007|\u001b\\)/g, "")
90
+ // eslint-disable-next-line no-control-regex
91
+ .replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, "")
92
+ // eslint-disable-next-line no-control-regex
93
+ .replace(/[\u0000-\u001f\u007f]+/g, " ")
94
+ .replace(/\s+/g, " ")
95
+ .trim();
96
+ const clean = scrubSecrets(shortenHomes(flat));
97
+ return clean.length <= CHILD_ERROR_MAX ? clean : `${clean.slice(0, CHILD_ERROR_MAX - 1).trimEnd()}…`;
98
+ }
99
+
100
+ /** What the last `result` line says of a failure. */
101
+ interface ResultSaid {
102
+ readonly label: string;
103
+ /** The host's own error text, when the result is its API error; null otherwise. */
104
+ readonly text: string | null;
105
+ /** The result is the host's API error (`terminal_reason: "api_error"`). */
106
+ readonly api: boolean;
107
+ readonly status: number | string | null;
108
+ }
109
+
110
+ /** The child's last `result` line, when it says it is an error. */
111
+ function resultError(output: string | undefined): ResultSaid | null {
112
+ const lines = (output ?? "").split("\n");
113
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
114
+ const line = lines[i] as string;
115
+ if (!line.includes('"result"')) continue;
116
+ let o: Record<string, unknown>;
117
+ try {
118
+ const parsed: unknown = JSON.parse(line);
119
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) continue;
120
+ o = parsed as Record<string, unknown>;
121
+ } catch {
122
+ continue;
123
+ }
124
+ if (o["type"] !== "result") continue;
125
+ // The LAST result decides: a successful one says nothing of a failure
126
+ // (its text is the model's prose), and the STDERR line is read instead.
127
+ const rawSubtype = typeof o["subtype"] === "string" ? o["subtype"] : "";
128
+ const isError = o["is_error"] === true;
129
+ if (!isError && (rawSubtype === "" || rawSubtype === "success")) return null;
130
+ const api = o["terminal_reason"] === "api_error";
131
+ const rawStatus = o["api_error_status"];
132
+ const status = typeof rawStatus === "number" || (typeof rawStatus === "string" && rawStatus.length > 0) ? rawStatus : null;
133
+ // `subtype` says `success` on an error result (2.1.311, signed out): no label then.
134
+ const subtype = rawSubtype.length > 0 && rawSubtype !== "success" ? rawSubtype : null;
135
+ const reason = typeof o["terminal_reason"] === "string" && o["terminal_reason"].length > 0 ? o["terminal_reason"] : (subtype ?? "error");
136
+ const label = `${reason}${status === null ? "" : ` ${String(status)}`}`;
137
+ // ITS TEXT ONLY WHEN IT IS THE HOST'S API ERROR (review of #656).
138
+ const hostError = api || status !== null || (rawSubtype === "success" && isError);
139
+ const text = hostError && typeof o["result"] === "string" && o["result"].trim().length > 0 ? o["result"] : null;
140
+ return { label, text, api, status };
141
+ }
142
+ return null;
143
+ }
144
+
145
+ /** The STDERR line that says why: the last one that reads as an error, else the last non-empty one. */
146
+ function stderrLine(stderr: string | undefined): string | null {
147
+ const lines = (stderr ?? "").split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
148
+ if (lines.length === 0) return null;
149
+ const telling = lines.filter((l) => /error|denied|invalid|failed|not logged/i.test(l));
150
+ return (telling.length > 0 ? telling[telling.length - 1] : lines[lines.length - 1]) as string;
151
+ }
152
+
153
+ /** Why a child failed: one scrubbed line, and whether it reads as a lost sign-in. */
154
+ export interface ChildFailure {
155
+ readonly line: string;
156
+ /**
157
+ * A LOST SIGN-IN (R4 addendum, narrowed by review of #656): read only from
158
+ * the host's own words — an API-error result (`terminal_reason:
159
+ * "api_error"`, or an `api_error_status` of 401) or the STDERR line — never
160
+ * from any other result's text.
161
+ */
162
+ readonly signedOut: boolean;
163
+ }
164
+
165
+ /**
166
+ * WHY THE CHILD FAILED, or null: its `stream-json` API-error result when its
167
+ * output was kept and ends in one; another error result's subtype and status,
168
+ * with the STDERR line beside them; else the STDERR line. Null for a child
169
+ * that exited 0, was stopped by a watchdog, or said nothing. Never throws.
170
+ */
171
+ export function childFailure(result: Pick<ChildResult, "code" | "timedOut" | "output" | "stderr">): ChildFailure | null {
172
+ try {
173
+ if (result.timedOut || result.code === null || result.code === 0) return null;
174
+ const said = resultError(result.output);
175
+ const err = stderrLine(result.stderr);
176
+ let raw: string | null;
177
+ let signedOut = false;
178
+ if (said !== null && said.text !== null) {
179
+ raw = `${said.label}: ${said.text}`;
180
+ signedOut = said.status === 401 || said.status === "401" || (said.api && signedOutShaped(said.text));
181
+ } else if (said !== null) {
182
+ raw = err === null ? said.label : `${said.label} — ${err}`;
183
+ signedOut = said.status === 401 || said.status === "401" || (err !== null && signedOutShaped(err));
184
+ } else {
185
+ raw = err;
186
+ signedOut = err !== null && signedOutShaped(err);
187
+ }
188
+ if (raw === null) return null;
189
+ const line = oneLine(raw);
190
+ return line.length === 0 ? null : { line, signedOut };
191
+ } catch {
192
+ return null;
193
+ }
194
+ }
195
+
196
+ /** The line alone (`childFailure`), or null. */
197
+ export function childErrorText(result: Pick<ChildResult, "code" | "timedOut" | "output" | "stderr">): string | null {
198
+ return childFailure(result)?.line ?? null;
199
+ }
200
+
201
+ /**
202
+ * DOES A HOST ERROR READ AS A LOST SIGN-IN (2026-10-27, R4 addendum; narrowed
203
+ * by review of #656)? "not logged in", "please run /login", "401
204
+ * Unauthorized" or "unauthorized", `authentication_error`, an invalid API
205
+ * key, an OAuth token expired, revoked or invalid. Not a bare "401" or a bare
206
+ * "OAuth": "retry after 401 seconds" and "the OAuth flow" are not a sign-in.
207
+ */
208
+ export function signedOutShaped(text: string | null | undefined): boolean {
209
+ if (text === null || text === undefined || text.length === 0) return false;
210
+ return /not logged in|logged out|please run \/login|\b401 unauthori[sz]ed|\bunauthori[sz]ed\b|authentication_error|authentication (failed|required)|invalid[ _-]?(x-)?api[ _-]?key|oauth[ _-]?token[^.]{0,40}\b(expired|revoked|invalid)\b|\btoken (has )?(expired|been revoked|revoked)\b/i.test(text);
211
+ }
@@ -16,6 +16,8 @@
16
16
  */
17
17
  import { spawn } from "node:child_process";
18
18
 
19
+ import { withHostUmask } from "../private-umask.js";
20
+
19
21
  /**
20
22
  * The host CLI a windowless child runs — always this one, resolved on the
21
23
  * child's PATH. It was once overridable by `pageWriter.command` in the
@@ -46,6 +48,10 @@ export interface ChildResult {
46
48
  readonly output?: string;
47
49
  /** True when the child wrote more than was kept. */
48
50
  readonly outputShort?: boolean;
51
+ /** The tail of what the child wrote to STDERR (2026-10-27, R4): at most
52
+ * `STDERR_TAIL_BYTES`, the last of it, raw. Read only for why a child
53
+ * failed (`child-error.ts`), and scrubbed there before it goes anywhere. */
54
+ readonly stderr?: string;
49
55
  }
50
56
 
51
57
  /** WHAT `startChild` NEEDS OF A PLAN. */
@@ -70,6 +76,9 @@ export interface ChildPlan {
70
76
  /** **CAL.** The most of a child's STDOUT kept in memory; the rest is drained unread. */
71
77
  export const OUTPUT_MAX_BYTES = 64 * 1024 * 1024;
72
78
 
79
+ /** **CAL.** The most of a child's STDERR kept: its last few KB, enough for the line that says why it stopped. */
80
+ export const STDERR_TAIL_BYTES = 8 * 1024;
81
+
73
82
  /**
74
83
  * HOW LONG A CHILD GETS TO DIE POLITELY before it is killed, and how long after
75
84
  * that before this stops waiting for the OS to confirm it.
@@ -100,16 +109,23 @@ export async function startChild(plan: ChildPlan, abort?: AbortSignal): Promise<
100
109
  let outputShort = false;
101
110
  const output = (): Pick<ChildResult, "output" | "outputShort"> =>
102
111
  plan.captureOutput === true ? { output: Buffer.concat(chunks).toString("utf8"), ...(outputShort ? { outputShort } : {}) } : {};
112
+ // THE TAIL OF STDERR (2026-10-27, R4): always piped and drained, only its
113
+ // last `STDERR_TAIL_BYTES` kept — a host's complaint about its arguments
114
+ // is there and nowhere else.
115
+ let errTail: Buffer = Buffer.alloc(0);
116
+ const stderr = (): Pick<ChildResult, "stderr"> => (errTail.length === 0 ? {} : { stderr: errTail.toString("utf8") });
103
117
  const done = (r: ChildResult): void => {
104
118
  if (settled) return;
105
119
  settled = true;
106
120
  for (const t of timers) clearTimeout(t);
107
121
  off?.();
108
- resolve({ ...r, ...output() });
122
+ resolve({ ...r, ...output(), ...stderr() });
109
123
  };
110
124
  let child: ReturnType<typeof spawn>;
111
125
  try {
112
- child = spawn(plan.command, [...plan.args], {
126
+ // Under the umask this process was started with (`private-umask.ts`):
127
+ // the child is another program, writing its own files.
128
+ child = withHostUmask(() => spawn(plan.command, [...plan.args], {
113
129
  // DETACHED ONLY SO THERE IS A PROCESS GROUP TO KILL. The caller still
114
130
  // awaits this child — `unref` is deliberately not called — so a child
115
131
  // whose outcome nobody can record is still impossible. What `detached`
@@ -120,10 +136,10 @@ export async function startChild(plan: ChildPlan, abort?: AbortSignal): Promise<
120
136
  // command line is readable by every process on the machine through
121
137
  // `ps` (S2 review, NIT-2). `claude -p` with no positional prompt reads
122
138
  // stdin.
123
- stdio: ["pipe", plan.captureOutput === true ? "pipe" : "ignore", "ignore"],
139
+ stdio: ["pipe", plan.captureOutput === true ? "pipe" : "ignore", "pipe"],
124
140
  env: { ...plan.env },
125
141
  ...(plan.cwd === undefined ? {} : { cwd: plan.cwd }),
126
- });
142
+ }));
127
143
  } catch (err) {
128
144
  // A runtime that refuses synchronously rather than by `error` (a command
129
145
  // that is not there, on some runtimes): the same answer, now.
@@ -141,6 +157,10 @@ export async function startChild(plan: ChildPlan, abort?: AbortSignal): Promise<
141
157
  chunks.push(part);
142
158
  kept += part.length;
143
159
  });
160
+ child.stderr?.on("data", (chunk: Buffer) => {
161
+ const both = errTail.length === 0 ? chunk : Buffer.concat([errTail, chunk]);
162
+ errTail = both.length > STDERR_TAIL_BYTES ? both.subarray(both.length - STDERR_TAIL_BYTES) : both;
163
+ });
144
164
  try {
145
165
  child.stdin?.end(plan.stdin);
146
166
  } catch {
@@ -203,12 +223,11 @@ export async function startChild(plan: ChildPlan, abort?: AbortSignal): Promise<
203
223
  // A PIPED STDOUT can outlive the child (2026-10-12): `close` waits for every
204
224
  // holder of the pipe, and a helper the host left behind would hold the run
205
225
  // until the watchdog. The exit, then a short grace for the last of the
206
- // output, is the end.
207
- if (plan.captureOutput === true) {
208
- child.on("exit", (exit, sig) => {
209
- timers.push(arm(() => ended(exit, sig), REAP_GRACE_MS));
210
- });
211
- }
226
+ // output, is the end. STDERR is piped for every child since 2026-10-27
227
+ // (R4), so this holds for every child.
228
+ child.on("exit", (exit, sig) => {
229
+ timers.push(arm(() => ended(exit, sig), REAP_GRACE_MS));
230
+ });
212
231
  });
213
232
  }
214
233
 
@@ -5,6 +5,7 @@ import { dirname, join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { finding } from "./doctor-finding.js";
7
7
  import type { Finding } from "./doctor-finding.js";
8
+ import { withHostUmask } from "../private-umask.js";
8
9
 
9
10
  // ── which checkout is running ───────────────────────────────────────────────
10
11
 
@@ -116,7 +117,8 @@ export const CHECKOUT_BUDGET_MS = 1000;
116
117
 
117
118
  function gitIn(root: string, remainingMs: () => number, env: NodeJS.ProcessEnv): GitRunner {
118
119
  return (args: readonly string[]): GitResult => {
119
- const res = spawnSync("git", ["-C", root, ...args], {
120
+ // Under the umask this process was started with (`private-umask.ts`).
121
+ const res = withHostUmask(() => spawnSync("git", ["-C", root, ...args], {
120
122
  timeout: remainingMs(),
121
123
  encoding: "utf8",
122
124
  windowsHide: true,
@@ -126,7 +128,7 @@ function gitIn(root: string, remainingMs: () => number, env: NodeJS.ProcessEnv):
126
128
  // prove the budget against a spawn that actually blocks. Passing
127
129
  // `process.env` is what inheriting already meant.
128
130
  env,
129
- });
131
+ }));
130
132
  if (res.error !== undefined && res.error !== null) {
131
133
  const code = (res.error as NodeJS.ErrnoException).code ?? "";
132
134
  return { ok: false, out: "", failed: code === "ETIMEDOUT" ? "timeout" : "missing" };
@@ -90,6 +90,37 @@ export interface HostReading {
90
90
  * would read it: which halves it would stand down for. Null when there is
91
91
  * none it would believe; absent when not read. */
92
92
  readonly npmMarker?: { readonly hooks: boolean; readonly server: boolean } | null;
93
+ /** A settings file read keeps Counterparts Online out of Claude Code
94
+ * (`deniedMcpServers`, R1); absent when not read. */
95
+ readonly deny?: boolean;
96
+ }
97
+
98
+ /**
99
+ * COUNTERPARTS ONLINE KEPT OUT OF CLAUDE CODE (2026-10-27, R1). Claude Code
100
+ * loads a person's claude.ai connectors into every session, so this install
101
+ * beside a hosted connector would be two memories over two stores. `connect`
102
+ * writes the one `deniedMcpServers` entry; this line says whether it is there.
103
+ *
104
+ * Only beside npm wiring: with nothing of ours connected the Claude Code line
105
+ * already says to run `connect`, and a plugin-only install has no `connect`
106
+ * to run (it would wire the host twice), so neither gets a line here.
107
+ */
108
+ export function denyFindings(reading: HostReading): Finding[] {
109
+ if (reading.deny === undefined) return [];
110
+ if (reading.events.length === 0 && !reading.mcp) return [];
111
+ if (reading.deny) {
112
+ return [finding("online-deny", "green", "Online", "Counterparts Online's claude.ai connector is kept out of Claude Code (deniedMcpServers)", "", { deny: true })];
113
+ }
114
+ return [
115
+ finding(
116
+ "online-deny",
117
+ "amber",
118
+ "Online",
119
+ "Counterparts Online is not kept out of Claude Code: a claude.ai connector to it would load into every session as a second memory over a different store",
120
+ "Run: counterparts connect — it backs up ~/.claude/settings.json and adds the one deniedMcpServers entry, leaving everything else as it is.",
121
+ { deny: false },
122
+ ),
123
+ ];
93
124
  }
94
125
 
95
126
  /** How a Runtime row names where a command was wired: `desktop` is Claude