counterparts 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/CONSTITUTION.md +68 -0
  2. package/LICENSE +21 -0
  3. package/README.md +348 -0
  4. package/docs/ELI5.md +84 -0
  5. package/docs/QUICKSTART.md +1258 -0
  6. package/docs/module-map.md +81 -0
  7. package/package.json +63 -0
  8. package/src/adapters/claude-code/CONTRACT.md +606 -0
  9. package/src/adapters/claude-code/INTERFACE-GAPS.md +655 -0
  10. package/src/adapters/claude-code/NOTES.md +1055 -0
  11. package/src/adapters/claude-code/bin/hook.ts +820 -0
  12. package/src/adapters/claude-code/bin/runner.ts +522 -0
  13. package/src/adapters/claude-code/config.ts +778 -0
  14. package/src/adapters/claude-code/credentials.ts +199 -0
  15. package/src/adapters/claude-code/doctor.ts +2557 -0
  16. package/src/adapters/claude-code/embed-client.ts +617 -0
  17. package/src/adapters/claude-code/hooks.ts +2240 -0
  18. package/src/adapters/claude-code/index.ts +224 -0
  19. package/src/adapters/claude-code/interpret-client.ts +395 -0
  20. package/src/adapters/claude-code/page-writer.ts +462 -0
  21. package/src/adapters/claude-code/primacy.ts +162 -0
  22. package/src/adapters/claude-code/spawn.ts +241 -0
  23. package/src/adapters/claude-code/standdown.ts +536 -0
  24. package/src/adapters/claude-code/transcript.ts +661 -0
  25. package/src/adapters/claude-code/vectors.ts +415 -0
  26. package/src/adapters/cli/CONTRACT.md +255 -0
  27. package/src/adapters/cli/INTERFACE-GAPS.md +350 -0
  28. package/src/adapters/cli/NOTES.md +936 -0
  29. package/src/adapters/cli/bin/counterparts.ts +74 -0
  30. package/src/adapters/cli/commands.ts +6095 -0
  31. package/src/adapters/cli/export.ts +766 -0
  32. package/src/adapters/cli/index.ts +103 -0
  33. package/src/adapters/cli/install.ts +670 -0
  34. package/src/adapters/cli/removal.ts +1186 -0
  35. package/src/adapters/cli/repair-dates.ts +659 -0
  36. package/src/adapters/cli/self-page.ts +229 -0
  37. package/src/adapters/cli/snapshot.ts +279 -0
  38. package/src/adapters/cli/start-fresh.ts +1228 -0
  39. package/src/adapters/config-path.ts +342 -0
  40. package/src/adapters/dashboard/CONTRACT.md +67 -0
  41. package/src/adapters/dashboard/INTERFACE-GAPS.md +139 -0
  42. package/src/adapters/dashboard/NOTES.md +474 -0
  43. package/src/adapters/dashboard/activity.ts +121 -0
  44. package/src/adapters/dashboard/ansi.ts +82 -0
  45. package/src/adapters/dashboard/bin/dashboard.ts +479 -0
  46. package/src/adapters/dashboard/browse.ts +298 -0
  47. package/src/adapters/dashboard/identity.ts +182 -0
  48. package/src/adapters/dashboard/index.ts +183 -0
  49. package/src/adapters/dashboard/layout.ts +149 -0
  50. package/src/adapters/dashboard/registries.ts +291 -0
  51. package/src/adapters/dashboard/resolve.ts +206 -0
  52. package/src/adapters/dashboard/source.ts +48 -0
  53. package/src/adapters/dashboard/status.ts +327 -0
  54. package/src/adapters/dashboard/stories.ts +194 -0
  55. package/src/adapters/dashboard/web/app.html +1731 -0
  56. package/src/adapters/dashboard/web/brain.html +463 -0
  57. package/src/adapters/dashboard/web/fired.ts +31 -0
  58. package/src/adapters/dashboard/web/flow.ts +457 -0
  59. package/src/adapters/dashboard/web/narrate.ts +1042 -0
  60. package/src/adapters/dashboard/web/reveal.ts +135 -0
  61. package/src/adapters/dashboard/web/server.ts +287 -0
  62. package/src/adapters/dashboard/web/views.ts +1744 -0
  63. package/src/adapters/expansions.ts +569 -0
  64. package/src/adapters/fired.ts +1580 -0
  65. package/src/adapters/mcp/CONTRACT.md +240 -0
  66. package/src/adapters/mcp/INTERFACE-GAPS.md +271 -0
  67. package/src/adapters/mcp/NOTES.md +205 -0
  68. package/src/adapters/mcp/bin/serve.ts +349 -0
  69. package/src/adapters/mcp/deliberate.ts +619 -0
  70. package/src/adapters/mcp/index.ts +101 -0
  71. package/src/adapters/mcp/protocol.ts +170 -0
  72. package/src/adapters/mcp/server.ts +1740 -0
  73. package/src/adapters/mcp/stdio.ts +56 -0
  74. package/src/adapters/mcp/tools.ts +779 -0
  75. package/src/adapters/scopes.ts +657 -0
  76. package/src/adapters/sessions.ts +402 -0
  77. package/src/adapters/snapshots.ts +1069 -0
  78. package/src/adapters/stance-env.ts +137 -0
  79. package/src/core/associate/CONTRACT.md +118 -0
  80. package/src/core/associate/INTERFACE-GAPS.md +173 -0
  81. package/src/core/associate/NOTES.md +194 -0
  82. package/src/core/associate/buffer.ts +66 -0
  83. package/src/core/associate/edges.ts +188 -0
  84. package/src/core/associate/index.ts +570 -0
  85. package/src/core/associate/pending.ts +383 -0
  86. package/src/core/associate/spread.ts +149 -0
  87. package/src/core/associate/tunables.ts +123 -0
  88. package/src/core/bridge.ts +272 -0
  89. package/src/core/briefing.ts +67 -0
  90. package/src/core/counterpart.ts +3855 -0
  91. package/src/core/encode/CONTRACT.md +151 -0
  92. package/src/core/encode/INTERFACE-GAPS.md +135 -0
  93. package/src/core/encode/NOTES.md +146 -0
  94. package/src/core/encode/aliases.ts +71 -0
  95. package/src/core/encode/battery.ts +284 -0
  96. package/src/core/encode/chunk.ts +265 -0
  97. package/src/core/encode/emotion.ts +119 -0
  98. package/src/core/encode/floor.ts +76 -0
  99. package/src/core/encode/index.ts +100 -0
  100. package/src/core/encode/precision.ts +162 -0
  101. package/src/core/encode/preselect.ts +269 -0
  102. package/src/core/encode/salience.ts +108 -0
  103. package/src/core/encode/secrets.ts +265 -0
  104. package/src/core/encode/tunables.ts +99 -0
  105. package/src/core/encode/types.ts +286 -0
  106. package/src/core/encode/words.ts +75 -0
  107. package/src/core/handoff/CONTRACT.md +199 -0
  108. package/src/core/handoff/INTERFACE-GAPS.md +166 -0
  109. package/src/core/handoff/NOTES.md +206 -0
  110. package/src/core/handoff/index.ts +957 -0
  111. package/src/core/mint.ts +279 -0
  112. package/src/core/observer.ts +28 -0
  113. package/src/core/physics/CONTRACT.md +341 -0
  114. package/src/core/physics/NOTES.md +155 -0
  115. package/src/core/physics/clock.ts +51 -0
  116. package/src/core/physics/index.ts +1054 -0
  117. package/src/core/prospective/CONTRACT.md +137 -0
  118. package/src/core/prospective/INTERFACE-GAPS.md +112 -0
  119. package/src/core/prospective/NOTES.md +160 -0
  120. package/src/core/prospective/derive.ts +188 -0
  121. package/src/core/prospective/index.ts +1030 -0
  122. package/src/core/prospective/tunables.ts +72 -0
  123. package/src/core/prospective/windows.ts +187 -0
  124. package/src/core/recall/CONTRACT.md +326 -0
  125. package/src/core/recall/INTERFACE-GAPS.md +163 -0
  126. package/src/core/recall/NOTES.md +472 -0
  127. package/src/core/recall/activate.ts +521 -0
  128. package/src/core/recall/cues.ts +275 -0
  129. package/src/core/recall/gate.ts +441 -0
  130. package/src/core/recall/index.ts +692 -0
  131. package/src/core/recall/probe.ts +239 -0
  132. package/src/core/recall/reference.ts +201 -0
  133. package/src/core/recall/render.ts +285 -0
  134. package/src/core/recall/session.ts +403 -0
  135. package/src/core/recall/tunables.ts +329 -0
  136. package/src/core/remember/CONTRACT.md +293 -0
  137. package/src/core/remember/INTERFACE-GAPS.md +189 -0
  138. package/src/core/remember/NOTES.md +373 -0
  139. package/src/core/remember/fallback.ts +452 -0
  140. package/src/core/remember/index.ts +103 -0
  141. package/src/core/remember/owner-strike-seam.ts +479 -0
  142. package/src/core/remember/proposals.ts +609 -0
  143. package/src/core/remember/spans.ts +1310 -0
  144. package/src/core/remember/tunables.ts +111 -0
  145. package/src/core/remember/updates.ts +198 -0
  146. package/src/core/retrieval.ts +96 -0
  147. package/src/core/revision.ts +441 -0
  148. package/src/core/schemas/CONTRACT.md +190 -0
  149. package/src/core/schemas/INTERFACE-GAPS.md +172 -0
  150. package/src/core/schemas/NOTES.md +260 -0
  151. package/src/core/schemas/aliases.ts +160 -0
  152. package/src/core/schemas/index.ts +1459 -0
  153. package/src/core/schemas/tunables.ts +44 -0
  154. package/src/core/schemas/types.ts +387 -0
  155. package/src/core/self/CONTRACT.md +459 -0
  156. package/src/core/self/INTERFACE-GAPS.md +284 -0
  157. package/src/core/self/NOTES.md +1057 -0
  158. package/src/core/self/briefing.ts +980 -0
  159. package/src/core/self/episodes.ts +483 -0
  160. package/src/core/self/freeze.ts +103 -0
  161. package/src/core/self/identity.ts +604 -0
  162. package/src/core/self/index.ts +2130 -0
  163. package/src/core/self/journal-file.ts +760 -0
  164. package/src/core/self/page.ts +404 -0
  165. package/src/core/self/tunables.ts +244 -0
  166. package/src/core/self/writer.ts +714 -0
  167. package/src/core/sleep/CONTRACT.md +298 -0
  168. package/src/core/sleep/INTERFACE-GAPS.md +262 -0
  169. package/src/core/sleep/NOTES.md +770 -0
  170. package/src/core/sleep/briefing.ts +86 -0
  171. package/src/core/sleep/consolidate.ts +241 -0
  172. package/src/core/sleep/cycle.ts +598 -0
  173. package/src/core/sleep/decay.ts +237 -0
  174. package/src/core/sleep/dedup.ts +373 -0
  175. package/src/core/sleep/index.ts +112 -0
  176. package/src/core/sleep/log.ts +116 -0
  177. package/src/core/sleep/markers.ts +164 -0
  178. package/src/core/sleep/prune.ts +170 -0
  179. package/src/core/sleep/strength-cache.ts +176 -0
  180. package/src/core/sleep/tunables.ts +135 -0
  181. package/src/core/sleep/types.ts +542 -0
  182. package/src/core/store/CONTRACT.md +446 -0
  183. package/src/core/store/NOTES.md +1068 -0
  184. package/src/core/store/cache.ts +709 -0
  185. package/src/core/store/db.ts +275 -0
  186. package/src/core/store/errors.ts +134 -0
  187. package/src/core/store/index.ts +2450 -0
  188. package/src/core/store/operational.ts +610 -0
  189. package/src/core/store/owner-op-seam.ts +428 -0
  190. package/src/core/store/paths.ts +494 -0
  191. package/src/core/store/prose.ts +165 -0
  192. package/src/core/store/render.ts +87 -0
  193. package/src/core/store/walk-seam.ts +78 -0
  194. package/src/core/types.ts +68 -0
  195. package/tools/install-loop/run.sh +1063 -0
@@ -0,0 +1,670 @@
1
+ /**
2
+ * `counterparts install` — the cold-start command.
3
+ *
4
+ * It exists because a stranger's first five minutes were, until this file, five
5
+ * hand-written files: the store, the adapter's configuration, the credential
6
+ * file at 0600, a hooks block in the host's settings, and an MCP registration.
7
+ * Four of those are OURS and one is the HOST'S, and the split is the whole
8
+ * design of this command:
9
+ *
10
+ * - **Ours, so we write them**: the data directory, `claude-code.json` BESIDE
11
+ * it, and an empty `credentials.env` at 0600. Nothing here is a host file
12
+ * and nothing here belongs to another program.
13
+ * - **The host's, so we only PRINT them**: the `settings.json` hooks block and
14
+ * the `claude mcp add` line. An installer that edits somebody's editor
15
+ * configuration without being asked is the same class of surprise as a
16
+ * memory layer that writes without being asked. `install` never opens
17
+ * `~/.claude/settings.json` — not to read it, not to back it up, not at all.
18
+ *
19
+ * Three rules the code below mechanizes:
20
+ *
21
+ * 1. **The config sits BESIDE the store, never inside it.** `store/paths.ts`
22
+ * classifies every top-level entry of the data dir and `assertLayout()`
23
+ * refuses an unclassified one (§5 G11), so `claude-code.json` inside the
24
+ * data dir is a store that will not open. Hence the default layout:
25
+ * `~/.counterparts/` holds the config and the credentials, and the store
26
+ * is `~/.counterparts/store`.
27
+ * 2. **Nothing existing is overwritten without `--force`.** A second
28
+ * `install` on a live machine reports what it found and changes nothing —
29
+ * the same idempotence `init` already has, extended to the two files.
30
+ * 3. **No ceiling is invented** (scar §2.18). `injectionBudgetBytes` is
31
+ * written only when `--budget` says what it is; without it the config is
32
+ * written without the key and the printed steps say so out loud.
33
+ */
34
+ import {
35
+ chmodSync,
36
+ existsSync,
37
+ mkdirSync,
38
+ readFileSync,
39
+ realpathSync,
40
+ statSync,
41
+ writeFileSync,
42
+ } from "node:fs";
43
+ import { homedir, tmpdir } from "node:os";
44
+ import { dirname, join, resolve } from "node:path";
45
+ import { fileURLToPath } from "node:url";
46
+
47
+ /** The store directory under the base. Named, because three files agree on it. */
48
+ export const DEFAULT_STORE_DIR = "store";
49
+
50
+ // The two credential NAMES, taken from the adapter that defines them rather
51
+ // than retyped here — a template that named a third variable, or misspelled one
52
+ // of these, would be a file the loader silently ignores and counts. The same
53
+ // direction `mcp/bin/serve.ts` already takes for the same reason.
54
+ import { API_KEY_ENV, EMBED_KEY_ENV } from "../claude-code/config.js";
55
+ import { loadCredentials } from "../claude-code/credentials.js";
56
+ import { CONFIG_ENV, CONFIG_FLAG, defaultConfigPath } from "../config-path.js";
57
+ import { DEFAULT_DATA_DIR_NAME, isWithin } from "../../core/store/index.js";
58
+
59
+ /** The five host events one executable serves (`claude-code/bin/hook.ts`). */
60
+ export const HOST_EVENTS = [
61
+ "SessionStart",
62
+ "UserPromptSubmit",
63
+ "Stop",
64
+ "SessionEnd",
65
+ "PreCompact",
66
+ ] as const;
67
+
68
+ /** The installed executables, by the names `package.json#bin` gives them. */
69
+ export const BIN = {
70
+ cli: "counterparts",
71
+ hook: "counterparts-hook",
72
+ mcp: "counterparts-mcp",
73
+ dashboard: "counterparts-dashboard",
74
+ } as const;
75
+
76
+ /** The name the MCP server is registered under, and the one `status` reports. */
77
+ export const MCP_SERVER_NAME = "counterparts";
78
+
79
+ /**
80
+ * THE TWO ENTRY SCRIPTS, ABSOLUTE, resolved from THIS file's location — never
81
+ * from a working directory and never from a name on a PATH.
82
+ *
83
+ * This is scar §2.18 again, in its sharpest form. `credentials.ts` measured, on
84
+ * day 0 of the parallel run, that this host's hook processes carry neither of
85
+ * the owner's exported API keys: **the host's process environment is not the
86
+ * login shell's**. The same sentence is true of `PATH`. `counterparts-hook` is
87
+ * a shim whose shebang is `#!/usr/bin/env bun`, so a host that launches hooks
88
+ * without `~/.bun/bin` on PATH gets "command not found" on every event — a
89
+ * memory that is simply never there, with nothing on screen to say why.
90
+ *
91
+ * So the printed commands name the RUNTIME and the SCRIPT by absolute path,
92
+ * which is what the live host has run since 2026-09-03 and what `hook.ts`
93
+ * already does for its own worker (`command: process.execPath, args: ["run",
94
+ * RUNNER_PATH]`). The short names stay on PATH for a human at a terminal; they
95
+ * are not what goes into a host's configuration.
96
+ */
97
+ export const HOOK_SCRIPT = fileURLToPath(new URL("../claude-code/bin/hook.ts", import.meta.url));
98
+ export const MCP_SCRIPT = fileURLToPath(new URL("../mcp/bin/serve.ts", import.meta.url));
99
+
100
+ /** Double-quote a path so a shell keeps it whole. Paths with `"` are refused
101
+ * by being escaped rather than silently mangled. */
102
+ export function shellQuote(path: string): string {
103
+ return `"${path.replace(/(["\\$`])/g, "\\$1")}"`;
104
+ }
105
+
106
+ /** `<runtime> run <script>` — the shape both printed host commands take. */
107
+ export function runCommand(script: string, exe: string = process.execPath): string {
108
+ return `${shellQuote(exe)} run ${shellQuote(script)}`;
109
+ }
110
+
111
+ /**
112
+ * The hook command the host is told to run — and the ONE case where it carries
113
+ * a flag.
114
+ *
115
+ * The default path IS the rule (`adapters/config-path.ts`): a hooks block that
116
+ * spelled out `--config "$HOME/.counterparts/claude-code.json"` would teach a
117
+ * reader that the flag is part of the wiring, and would then be wrong the moment
118
+ * they moved a home directory. So the flag is printed only when this install put
119
+ * the configuration somewhere the hooks would not find on their own, and the
120
+ * output says why (`commands.ts#installCommand`).
121
+ */
122
+ export function hookCommand(configPath?: string, exe: string = process.execPath): string {
123
+ const base = runCommand(HOOK_SCRIPT, exe);
124
+ return configPath === undefined || configPath.length === 0
125
+ ? base
126
+ : `${base} ${CONFIG_FLAG} ${shellQuote(configPath)}`;
127
+ }
128
+
129
+ export const CONFIG_FILE = "claude-code.json";
130
+ export const CREDENTIALS_FILE = "credentials.env";
131
+
132
+ export interface InstallLayout {
133
+ /** The directory holding the config, the credentials, and the store. */
134
+ readonly base: string;
135
+ /** The data dir itself — a SUBDIRECTORY of `base`, never `base` (rule 1). */
136
+ readonly store: string;
137
+ readonly config: string;
138
+ readonly credentials: string;
139
+ }
140
+
141
+ /**
142
+ * Where an install lands, from the flags and the environment — resolved, never
143
+ * guessed halfway.
144
+ *
145
+ * **`--dir` never moves the base.** `claude-code/bin/hook.ts` and `bin/runner.ts`
146
+ * read `~/.counterparts/claude-code.json` unless something NAMES another file —
147
+ * `--config <absolute path>`, else `COUNTERPARTS_CONFIG`
148
+ * (`adapters/config-path.ts`) — and they fall back to `COUNTERPARTS_DATA_DIR`
149
+ * only when the configuration they read names no store. A hook that finds no
150
+ * config stands down and exits 0 (the Stop ask's exit 2 is the one deliberate
151
+ * non-zero), so a config nothing points them at is a config the ambient half
152
+ * never finds and never complains about. The cold-stranger review of 2026-09-04
153
+ * found exactly that: `--dir` produced a working store, a correct config and
154
+ * correct printed hooks, and an ambient half permanently blind, with nothing on
155
+ * screen to say so.
156
+ *
157
+ * So `--dir` (and `COUNTERPARTS_DATA_DIR`) move the STORE and only the store;
158
+ * `dataDir` in the config is how the hooks are told where it went. `--config`
159
+ * moves the CONFIGURATION — and with it the credentials file beside it and the
160
+ * default store beneath it — and then the printed hooks block and `claude mcp
161
+ * add` line carry it, because a file nothing points at is the failure above.
162
+ *
163
+ * The default store is `~/.counterparts/store`, deliberately NOT `dataDir()`'s
164
+ * `~/.counterparts` — that is the directory holding the two unclassifiable
165
+ * files, and rule 1 is why.
166
+ */
167
+ export function installLayout(
168
+ dirFlag: string | undefined,
169
+ env: Record<string, string | undefined>,
170
+ home = homedir(),
171
+ configPath?: string,
172
+ ): InstallLayout {
173
+ const named =
174
+ dirFlag !== undefined && dirFlag.length > 0
175
+ ? dirFlag
176
+ : (env["COUNTERPARTS_DATA_DIR"] ?? "").trim().length > 0
177
+ ? (env["COUNTERPARTS_DATA_DIR"] as string)
178
+ : undefined;
179
+ // `--config` (or `COUNTERPARTS_CONFIG`) moves the whole BASE — the config, the
180
+ // credentials beside it, and, when no `--dir` says otherwise, the store
181
+ // beneath it. Splitting them would put a scratch install's credentials file in
182
+ // `~/.counterparts/`, which is the live one on the owner's machine; an install
183
+ // that writes there because it was pointed somewhere else is the accident this
184
+ // flag exists to prevent.
185
+ const base =
186
+ configPath === undefined || configPath.length === 0
187
+ ? join(home, DEFAULT_DATA_DIR_NAME)
188
+ : dirname(resolve(configPath));
189
+ const store = named === undefined ? join(base, DEFAULT_STORE_DIR) : resolve(named);
190
+ return {
191
+ base,
192
+ store,
193
+ config:
194
+ configPath === undefined || configPath.length === 0
195
+ ? join(base, CONFIG_FILE)
196
+ : resolve(configPath),
197
+ credentials: join(base, CREDENTIALS_FILE),
198
+ };
199
+ }
200
+
201
+ /**
202
+ * Why this store cannot hold this install's configuration, or null when it can.
203
+ *
204
+ * The one case: a `--dir` that IS `~/.counterparts`, or any ancestor of it, puts
205
+ * `claude-code.json` and `credentials.env` inside the data dir, and the layout
206
+ * totality check (§5 G11) refuses an unclassified top-level entry at open. The
207
+ * store would be created and then never open again. Caught before anything is
208
+ * written, and named.
209
+ */
210
+ export function layoutRefusal(layout: InstallLayout): string | null {
211
+ if (!isWithin(layout.store, layout.config)) return null;
212
+ return (
213
+ `refused: the configuration lives at ${layout.config}, which would sit INSIDE the ` +
214
+ `data dir ${layout.store}. The store's layout check refuses an unclassified file at ` +
215
+ `open (§5 G11), so that store would never open again. Choose a --dir that is not ` +
216
+ `${layout.base} or an ancestor of it — ${join(layout.base, DEFAULT_STORE_DIR)} is the default.`
217
+ );
218
+ }
219
+
220
+ /**
221
+ * The roots this machine hands out for THROWAWAY files: `os.tmpdir()`, the three
222
+ * variables that set it, and `/tmp`. Each is listed twice — as spelled and as
223
+ * realpath'd — because macOS spells the same directory `/var/folders/…` and
224
+ * `/private/var/folders/…` depending on who asked, and a prefix test that knows
225
+ * only one of the two silently answers "no".
226
+ */
227
+ export function tempRoots(env: Record<string, string | undefined> = process.env): string[] {
228
+ const out: string[] = [];
229
+ const add = (value: string): void => {
230
+ if (!out.includes(value)) out.push(value);
231
+ };
232
+ for (const raw of [tmpdir(), env["TMPDIR"], env["TMP"], env["TEMP"], "/tmp"]) {
233
+ if (typeof raw !== "string" || raw.trim().length === 0) continue;
234
+ const abs = resolve(raw.trim());
235
+ add(abs);
236
+ try {
237
+ add(realpathSync(abs));
238
+ } catch {
239
+ // A root that is not there cannot contain anything; nothing to add.
240
+ }
241
+ }
242
+ return out;
243
+ }
244
+
245
+ /** True when `path` is one of the temp roots or lives under one. */
246
+ function underTempRoot(path: string, roots: readonly string[]): boolean {
247
+ const abs = resolve(path);
248
+ return roots.some((root) => isWithin(root, abs));
249
+ }
250
+
251
+ /**
252
+ * Why this install may not write THE DEFAULT CONFIGURATION, or null.
253
+ *
254
+ * The one case, and it is a scar rather than a theory: on 2026-09-04 a suite run
255
+ * that had lost `test/preload.ts`'s home mock resolved the real
256
+ * `~/.counterparts/claude-code.json` and rewrote its `dataDir` to a temp path.
257
+ * The file is the one the hook, the worker and the MCP server read with NO flag,
258
+ * so from that moment the owner's live memory was a directory the OS was free to
259
+ * delete — and it recorded nothing for three days before anyone noticed. A
260
+ * throwaway store must never become the live default.
261
+ *
262
+ * So: the default configuration file will not be written with a `dataDir` under
263
+ * a temp root. `--config <somewhere else>` is the way through, and it moves the
264
+ * credentials and the store with it (`installLayout`), which is the whole point
265
+ * — a scratch install should be scratch all the way down.
266
+ *
267
+ * THE THIRD CLAUSE, and why the clean room still works: the refusal also
268
+ * requires that the CONFIGURATION not be under a temp root. `tools/install-loop/run.sh`
269
+ * installs into a fake `$HOME` beneath `$TMPDIR` with no `--config` at all, so
270
+ * its default config and its store are both throwaway and both under the same
271
+ * base — a stranger's install, correctly measured, not a live default pointed at
272
+ * a temp store. Keying on the store alone would refuse the loop; keying on the
273
+ * pair is what "the REAL default path" means on a machine where the temp dir can
274
+ * hold a whole home. Test-suite installs are in the same position (the mocked
275
+ * home is minted under `os.tmpdir()`), which is why this is provable only with
276
+ * an injected home outside the temp tree.
277
+ *
278
+ * Not bypassable by `--force`: `--force` says "overwrite the file I named", and
279
+ * the file this refuses to write is one nobody named.
280
+ */
281
+ export function throwawayDefaultRefusal(
282
+ layout: InstallLayout,
283
+ env: Record<string, string | undefined> = process.env,
284
+ home: string = homedir(),
285
+ ): string | null {
286
+ const defaultConfig = defaultConfigPath(home);
287
+ if (resolve(layout.config) !== defaultConfig) return null;
288
+ const roots = tempRoots(env);
289
+ if (!underTempRoot(layout.store, roots)) return null;
290
+ if (underTempRoot(defaultConfig, roots)) return null;
291
+ return (
292
+ `refused: this would write the DEFAULT configuration, ${defaultConfig}, with a data dir ` +
293
+ `under the system temp directory (${layout.store}). That file is the one the hook, the ` +
294
+ "worker and the MCP server read when nothing names another, so a throwaway store would " +
295
+ "become this machine's live memory and the real one would stop being written to. " +
296
+ `Name a scratch install instead: ` +
297
+ `${CONFIG_FLAG} <absolute path outside ${join(home, DEFAULT_DATA_DIR_NAME)}>, which moves the ` +
298
+ "configuration, the credentials and the store together. A permanent store outside the temp " +
299
+ "dir is the other way through."
300
+ );
301
+ }
302
+
303
+ export interface ConfigInput {
304
+ readonly layout: InstallLayout;
305
+ readonly budgetBytes?: number;
306
+ readonly name?: string;
307
+ readonly embedder?: boolean;
308
+ }
309
+
310
+ /**
311
+ * The adapter configuration this install writes. Absolute paths only: the file
312
+ * is read by three processes the owner never launches by hand (the hook, the
313
+ * worker, the MCP server), and `~` is a shell's idea, not a path.
314
+ */
315
+ export function configObject(input: ConfigInput): Record<string, unknown> {
316
+ const out: Record<string, unknown> = {
317
+ dataDir: input.layout.store,
318
+ credentialsFile: input.layout.credentials,
319
+ owner: true,
320
+ };
321
+ // Scar §2.18: written only when a number was SUPPLIED. There is no default
322
+ // for a host's ceiling anywhere in this package and this is not the place
323
+ // there starts being one.
324
+ if (input.budgetBytes !== undefined) out["injectionBudgetBytes"] = input.budgetBytes;
325
+ if (input.name !== undefined && input.name.length > 0) out["identity"] = { name: input.name };
326
+ // The egress knob. Absent means absent: no client is built and no socket
327
+ // opens, whatever a key in the environment says.
328
+ if (input.embedder === true) out["embedder"] = { enabled: true };
329
+ return out;
330
+ }
331
+
332
+ /**
333
+ * WHICH honored credential names an existing file actually holds. NAMES ONLY.
334
+ *
335
+ * THE 2026-09-04 INCIDENT, second half (I32). A forced install rewrote the
336
+ * owner's `credentials.env` with the template below. The file went from two keys
337
+ * to zero, the detached worker was refused at every boundary for a week, and the
338
+ * store's clock stopped while every visible surface read healthy. `--force` is
339
+ * consent to replace a file you are re-installing; it is not consent to destroy
340
+ * a secret that cannot be regenerated from anything on this machine.
341
+ *
342
+ * It reuses `loadCredentials` rather than parsing the file a second time — the
343
+ * quoting, the `export ` prefix, the CRLF, the first-occurrence rule are all
344
+ * there, and a second parser is how the two would come to disagree about what
345
+ * counts as a key. The scratch environment it fills is DISCARDED on this line:
346
+ * nothing from it is returned, printed, emitted or compared. What comes back is
347
+ * the list of NAMES, which is all any caller needs.
348
+ */
349
+ export function credentialsHeld(path: string): string[] {
350
+ if (!existsSync(path)) return [];
351
+ const scratch: NodeJS.ProcessEnv = {};
352
+ try {
353
+ // `loaded` is "the file answered this name"; with an empty scratch env
354
+ // nothing can be `skippedPresent`, so this is the file's whole content.
355
+ return loadCredentials(path, scratch).loaded;
356
+ } catch {
357
+ // An unreadable file holds nothing we can vouch for; the ordinary write
358
+ // path decides what happens to it.
359
+ return [];
360
+ }
361
+ }
362
+
363
+ /** The template written into a fresh `credentials.env`. Names, never values. */
364
+ export function credentialsTemplate(): string {
365
+ return [
366
+ "# Counterparts reads exactly two names from this file, and only to fill a",
367
+ "# gap: a value already exported in the environment always wins.",
368
+ "#",
369
+ `# ${API_KEY_ENV}=... the crash-recovery sweep's one model call.`,
370
+ "# Without it the worker still runs the day — clock,",
371
+ "# flush, cycle, briefing — and SKIPS the sweep, so a",
372
+ "# crashed session's spans stay uninterpreted.",
373
+ `# ${EMBED_KEY_ENV}=... embeddings. Without it (or without`,
374
+ '# "embedder": { "enabled": true } in',
375
+ "# claude-code.json) recall is lexical-only.",
376
+ "#",
377
+ "# Anything else in this file is ignored and counted. Keep it 0600.",
378
+ "",
379
+ ].join("\n");
380
+ }
381
+
382
+ /** The hooks block to paste into `~/.claude/settings.json`. Printed, never written. */
383
+ export function settingsBlock(hookCommand = runCommand(HOOK_SCRIPT)): string {
384
+ const hooks: Record<string, unknown> = {};
385
+ for (const event of HOST_EVENTS) {
386
+ hooks[event] = [{ hooks: [{ type: "command", command: hookCommand }] }];
387
+ }
388
+ return JSON.stringify({ hooks }, null, 2);
389
+ }
390
+
391
+ /**
392
+ * The MCP registration line. Printed, never run — it edits the host's config.
393
+ *
394
+ * A non-default configuration travels as `-e COUNTERPARTS_CONFIG=…`, not as a
395
+ * flag, and that is the whole reason the environment variable exists: this host
396
+ * launches MCP servers from a STATIC registration, and `-e` is the channel that
397
+ * registration has. It sits beside `COUNTERPARTS_DATA_DIR` because the two names
398
+ * answer different questions — which store, and whose keys.
399
+ */
400
+ export function mcpCommand(
401
+ store: string,
402
+ serve = runCommand(MCP_SCRIPT),
403
+ configPath?: string,
404
+ ): string {
405
+ const config =
406
+ configPath === undefined || configPath.length === 0
407
+ ? ""
408
+ : ` -e ${CONFIG_ENV}=${shellQuote(configPath)}`;
409
+ return `claude mcp add ${MCP_SERVER_NAME} -s user -e COUNTERPARTS_DATA_DIR=${shellQuote(store)}${config} -- ${serve}`;
410
+ }
411
+
412
+ /**
413
+ * Why `--budget` cannot be used, or null — `install`'s own rule, exported so
414
+ * there is ONE of it.
415
+ *
416
+ * `start-fresh` hands `install` the ceiling it read out of the configuration,
417
+ * and `loadConfig` accepts any finite positive number while this requires a
418
+ * whole one. A fractional `injectionBudgetBytes` therefore loaded fine
419
+ * everywhere else and refused inside `install` — which, before the order
420
+ * changed, happened AFTER both directories had been parked (N1 review M1). A
421
+ * caller that wants to know in advance asks the same function `install` asks.
422
+ */
423
+ export function budgetRefusal(value: string): string | null {
424
+ const n = Number(value);
425
+ if (!Number.isInteger(n) || n <= 0) {
426
+ return `refused: --budget takes a positive whole number of bytes, not '${value}'.`;
427
+ }
428
+ return null;
429
+ }
430
+
431
+ export type WroteWhat = "created" | "kept" | "replaced";
432
+
433
+ export interface FileResult {
434
+ readonly path: string;
435
+ readonly what: WroteWhat;
436
+ /** Octal mode after the call, for the credential file's 0600 report. */
437
+ readonly mode?: string;
438
+ }
439
+
440
+ /** Write `text` at `path` unless it is already there and `--force` was not given. */
441
+ export function writeOnce(
442
+ path: string,
443
+ text: string,
444
+ opts: { force: boolean; mode?: number },
445
+ ): FileResult {
446
+ const present = existsSync(path);
447
+ if (present && !opts.force) {
448
+ return { path, what: "kept", ...modeOf(path) };
449
+ }
450
+ mkdirSync(dirname(path), { recursive: true });
451
+ writeFileSync(path, text, opts.mode === undefined ? {} : { mode: opts.mode });
452
+ // `writeFileSync`'s mode is a CREATION mode and the umask applies; an
453
+ // existing file keeps the mode it had. Both cases are fixed here, so "0600"
454
+ // is a fact about the file rather than about the call that made it.
455
+ if (opts.mode !== undefined) chmodSync(path, opts.mode);
456
+ return { path, what: present ? "replaced" : "created", ...modeOf(path) };
457
+ }
458
+
459
+ function modeOf(path: string): { mode?: string } {
460
+ try {
461
+ return { mode: (statSync(path).mode & 0o777).toString(8).padStart(3, "0") };
462
+ } catch {
463
+ return {};
464
+ }
465
+ }
466
+
467
+ // ── did the two printed steps actually take (2026-09-20, finding 4) ─────────
468
+
469
+ /**
470
+ * READ THE HOST'S OWN FILES and say whether what `install` printed is there.
471
+ *
472
+ * `install` prints the hooks block and the `claude mcp add` line and applies
473
+ * neither — correctly, because they edit somebody else's editor configuration.
474
+ * Nothing then checked them, so a user who pasted the block into a project
475
+ * settings file instead of the user one, or who never restarted, got a fully
476
+ * green `doctor` and total silence. The failure mode of this product is
477
+ * silence, and QUICKSTART §4 says as much about a hook that stands down.
478
+ *
479
+ * It lives HERE and not in `doctor.ts` because it is the other half of what
480
+ * this file prints: the block and the line are `settingsBlock` and
481
+ * `mcpCommand`, and the names they use — `HOST_EVENTS`, `MCP_SERVER_NAME` — are
482
+ * this module's. `doctor.ts` grades the reading and holds none of that
483
+ * vocabulary, exactly as it already takes `checkout` and `open` from its caller.
484
+ *
485
+ * **READ-ONLY, AND EVERY ANSWER NAMES THE FILES IT READ.** None of these paths
486
+ * is ours. `~/.claude.json` in particular is the host's own state file, which
487
+ * its documentation describes as one the host writes for itself — so it may
488
+ * move, and the line must then read "I looked here and did not find it", never
489
+ * "you did not install it". `CLAUDE_CONFIG_DIR` relocates both, checked first.
490
+ *
491
+ * Hooks MERGE across the host's settings files, so all four places a block can
492
+ * land are read and the answer is their union: finding the command in a project
493
+ * file is still finding it, and the line says where it looked.
494
+ *
495
+ * Verified against the host's documentation on 2026-09-20. True for now.
496
+ */
497
+ export interface HostRead {
498
+ readonly expected: readonly string[];
499
+ readonly events: readonly string[];
500
+ /**
501
+ * Events whose hook command NAMES A PATH THAT IS NOT THERE (2026-09-20).
502
+ *
503
+ * A settings block left over from a checkout that has since been deleted or
504
+ * renamed matches the command mark perfectly and fails at every session
505
+ * start. Reading it as installed is the one outcome this whole finding was
506
+ * added to prevent: GREEN while nothing fires. These are a subset of
507
+ * `events` — the block IS installed — and they are graded as a fault.
508
+ */
509
+ readonly stale: readonly { event: string; path: string }[];
510
+ readonly settingsRead: readonly string[];
511
+ /** Files that exist and could not be opened or parsed — a different fact from
512
+ * "there is no such file", and the one the MCP file already got a flag for. */
513
+ readonly settingsUnreadable: readonly string[];
514
+ readonly mcp: boolean;
515
+ readonly mcpName: string;
516
+ readonly mcpFile: string;
517
+ readonly mcpUnreadable: boolean;
518
+ }
519
+
520
+ /**
521
+ * What a hook command of ours looks like, wherever it was installed from — a
522
+ * global install, a clone, or a worktree.
523
+ *
524
+ * ANCHORED AT A TOKEN BOUNDARY, not a bare substring (2026-09-20): the first
525
+ * version matched any command merely *mentioning* the name, so `echo
526
+ * counterparts-hook` read as an installed hook. It still cannot resolve an
527
+ * arbitrary shell command — that is out of scope, and deliberately so — but it
528
+ * no longer matches prose.
529
+ */
530
+ export const HOOK_COMMAND_MARK =
531
+ /(^|[\s"'=/\\])counterparts-hook(\s|$|")|claude-code[/\\]bin[/\\]hook\.ts/;
532
+
533
+ /**
534
+ * The absolute path a hook command runs, when it names one — the first token
535
+ * that looks like a path, or the argument after a runtime like `bun`.
536
+ *
537
+ * Deliberately narrow: it answers "does this file exist" for the shapes
538
+ * `install` prints and the shapes a clone produces, and returns null for
539
+ * anything else rather than guessing. A null is never reported as stale.
540
+ */
541
+ export function hookTargetPath(command: string): string | null {
542
+ const tokens = command.trim().split(/\s+/);
543
+ for (const raw of tokens) {
544
+ const token = raw.replace(/^["']|["']$/g, "");
545
+ if (!token.startsWith("/")) continue;
546
+ // The runtime itself (…/bin/bun) is not the hook; keep looking for the
547
+ // script it was handed.
548
+ if (/\.(ts|js|mjs|cjs)$/.test(token)) return token;
549
+ if (/counterparts-hook$/.test(token)) return token;
550
+ }
551
+ return null;
552
+ }
553
+
554
+ /** The host's settings files that can carry a user's hooks, in merge order. */
555
+ export function hostSettingsFiles(base: string, cwd: string): string[] {
556
+ return [
557
+ join(base, ".claude", "settings.json"),
558
+ join(base, ".claude", "settings.local.json"),
559
+ join(cwd, ".claude", "settings.json"),
560
+ join(cwd, ".claude", "settings.local.json"),
561
+ ];
562
+ }
563
+
564
+ /**
565
+ * Where a `-s user` MCP registration lands. `CLAUDE_CONFIG_DIR` moves it.
566
+ *
567
+ * **A SYMLINK OUT OF THE BASE IS FOLLOWED, and the name printed is the link.**
568
+ * It is the user's own symlink on the user's own machine and the read is
569
+ * read-only, so the blast radius is nil — but this module promises that every
570
+ * answer names the file it read, and after a symlink that promise is only
571
+ * half-kept. Stated here rather than refused: refusing would break a real setup
572
+ * (a dotfiles repository) to fix a wording problem, and resolving the target to
573
+ * print it would make the line harder to read for everyone else.
574
+ */
575
+ export function hostMcpFile(base: string): string {
576
+ return join(base, ".claude.json");
577
+ }
578
+
579
+ /** The base both live under: `CLAUDE_CONFIG_DIR` when set, else the home dir. */
580
+ export function hostConfigBase(home: string, env: Record<string, string | undefined>): string {
581
+ const moved = (env["CLAUDE_CONFIG_DIR"] ?? "").trim();
582
+ return moved.length > 0 ? moved : home;
583
+ }
584
+
585
+ /**
586
+ * Three outcomes, not two (2026-09-20): `absent`, `unreadable` and `read`.
587
+ *
588
+ * The first version collapsed "does not exist", "cannot be opened" and "is not
589
+ * JSON" into one falsy answer, so a mode-000 `settings.json` — or a DIRECTORY
590
+ * with that name — dropped out of the report with no trace at all. The MCP file
591
+ * already had a flag for exactly this; the settings files did not.
592
+ */
593
+ function readJsonFile(path: string): {
594
+ state: "absent" | "unreadable" | "read";
595
+ value: Record<string, unknown>;
596
+ } {
597
+ if (!existsSync(path)) return { state: "absent", value: {} };
598
+ try {
599
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
600
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)
601
+ ? { state: "read", value: parsed as Record<string, unknown> }
602
+ : { state: "unreadable", value: {} };
603
+ } catch {
604
+ return { state: "unreadable", value: {} };
605
+ }
606
+ }
607
+
608
+ export function readHost(
609
+ home: string,
610
+ cwd: string,
611
+ env: Record<string, string | undefined> = process.env,
612
+ ): HostRead {
613
+ const base = hostConfigBase(home, env);
614
+ const events = new Set<string>();
615
+ const live = new Set<string>();
616
+ const stale = new Map<string, string>();
617
+ const settingsRead: string[] = [];
618
+ const settingsUnreadable: string[] = [];
619
+ for (const path of hostSettingsFiles(base, cwd)) {
620
+ const read = readJsonFile(path);
621
+ if (read.state === "unreadable") settingsUnreadable.push(path);
622
+ if (read.state !== "read") continue;
623
+ settingsRead.push(path);
624
+ const hooks = read.value["hooks"];
625
+ if (hooks === null || typeof hooks !== "object" || Array.isArray(hooks)) continue;
626
+ for (const [event, entries] of Object.entries(hooks as Record<string, unknown>)) {
627
+ if (!Array.isArray(entries)) continue;
628
+ for (const entry of entries as unknown[]) {
629
+ if (entry === null || typeof entry !== "object") continue;
630
+ const inner = (entry as Record<string, unknown>)["hooks"];
631
+ if (!Array.isArray(inner)) continue;
632
+ for (const h of inner as unknown[]) {
633
+ if (h === null || typeof h !== "object") continue;
634
+ const command = (h as Record<string, unknown>)["command"];
635
+ if (typeof command !== "string" || !HOOK_COMMAND_MARK.test(command)) continue;
636
+ events.add(event);
637
+ // A BLOCK THAT NAMES A PATH THAT IS NOT THERE fails at every session
638
+ // start, silently. One event can carry several entries, so a live one
639
+ // anywhere wins and a stale one is only reported when nothing on that
640
+ // event resolves.
641
+ const target = hookTargetPath(command);
642
+ if (target === null || existsSync(target)) live.add(event);
643
+ else stale.set(event, target);
644
+ }
645
+ }
646
+ }
647
+ }
648
+ const mcpFile = hostMcpFile(base);
649
+ const mcpRead = readJsonFile(mcpFile);
650
+ const servers = mcpRead.value["mcpServers"];
651
+ const mcp =
652
+ servers !== null &&
653
+ typeof servers === "object" &&
654
+ !Array.isArray(servers) &&
655
+ MCP_SERVER_NAME in (servers as Record<string, unknown>);
656
+ return {
657
+ expected: [...HOST_EVENTS],
658
+ events: [...events].sort(),
659
+ stale: [...stale.entries()]
660
+ .filter(([event]) => !live.has(event))
661
+ .map(([event, path]) => ({ event, path }))
662
+ .sort((a, b) => (a.event < b.event ? -1 : 1)),
663
+ settingsRead,
664
+ settingsUnreadable,
665
+ mcp,
666
+ mcpName: MCP_SERVER_NAME,
667
+ mcpFile,
668
+ mcpUnreadable: mcpRead.state === "unreadable",
669
+ };
670
+ }