counterparts 0.3.11 → 0.3.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/CHANGELOG.md +326 -0
  2. package/docs/QUICKSTART.md +5 -0
  3. package/docs/README.md +2 -2
  4. package/docs/module-map.md +3 -3
  5. package/package.json +1 -1
  6. package/src/adapters/claude-code/CONTRACT.md +36 -10
  7. package/src/adapters/claude-code/INTERFACE-GAPS.md +116 -16
  8. package/src/adapters/claude-code/NOTES.md +182 -0
  9. package/src/adapters/claude-code/bin/hook.ts +46 -12
  10. package/src/adapters/claude-code/bin/runner.ts +7 -1
  11. package/src/adapters/claude-code/doctor.ts +632 -18
  12. package/src/adapters/claude-code/hooks.ts +61 -16
  13. package/src/adapters/claude-code/index.ts +11 -0
  14. package/src/adapters/claude-code/night-run.ts +150 -14
  15. package/src/adapters/claude-code/transcript.ts +268 -1
  16. package/src/adapters/cli/CONTRACT.md +5 -0
  17. package/src/adapters/cli/INTERFACE-GAPS.md +8 -4
  18. package/src/adapters/cli/NOTES.md +111 -0
  19. package/src/adapters/cli/commands.ts +134 -92
  20. package/src/adapters/cli/dream-core.ts +57 -42
  21. package/src/adapters/cli/export.ts +320 -21
  22. package/src/adapters/cli/help.ts +2 -1
  23. package/src/adapters/cli/index.ts +1 -0
  24. package/src/adapters/cli/install.ts +39 -7
  25. package/src/adapters/cli/mechanisms.ts +7 -1
  26. package/src/adapters/cli/uninstall.ts +13 -5
  27. package/src/adapters/cli/wire.ts +189 -63
  28. package/src/adapters/config.ts +2 -0
  29. package/src/adapters/dashboard/INTERFACE-GAPS.md +10 -1
  30. package/src/adapters/dashboard/NOTES.md +79 -0
  31. package/src/adapters/dashboard/registries.ts +34 -2
  32. package/src/adapters/dashboard/web/README.md +19 -14
  33. package/src/adapters/dashboard/web/actions.ts +23 -1
  34. package/src/adapters/dashboard/web/flow.ts +14 -0
  35. package/src/adapters/dashboard/web/lanes.ts +10 -0
  36. package/src/adapters/dashboard/web/narrate.ts +88 -2
  37. package/src/adapters/dashboard/web/pages/flow/sections/fired.js +1 -0
  38. package/src/adapters/dashboard/web/pages/health/sections/checks.js +2 -0
  39. package/src/adapters/dashboard/web/pages/health/sections/wake.js +3 -1
  40. package/src/adapters/dashboard/web/pages/memories/memories.css +17 -4
  41. package/src/adapters/dashboard/web/pages/memories/row.js +37 -21
  42. package/src/adapters/dashboard/web/pages/memories/sections/search.js +279 -60
  43. package/src/adapters/dashboard/web/pages/memories/state.js +2 -1
  44. package/src/adapters/dashboard/web/server.ts +0 -5
  45. package/src/adapters/dashboard/web/shared/memory-marks.css +7 -0
  46. package/src/adapters/dashboard/web/shared/memory-marks.js +33 -0
  47. package/src/adapters/dashboard/web/shared/memory-modal.js +5 -3
  48. package/src/adapters/dashboard/web/views/health.ts +21 -3
  49. package/src/adapters/dashboard/web/views/search.ts +4 -45
  50. package/src/adapters/dashboard/web/views.ts +2 -2
  51. package/src/adapters/fired.ts +430 -28
  52. package/src/adapters/host-wiring.ts +300 -0
  53. package/src/adapters/hosts.ts +11 -0
  54. package/src/adapters/lifecycle.ts +42 -2
  55. package/src/adapters/log/index.ts +9 -0
  56. package/src/adapters/mcp/CONTRACT.md +151 -11
  57. package/src/adapters/mcp/INTERFACE-GAPS.md +24 -2
  58. package/src/adapters/mcp/NOTES.md +313 -1
  59. package/src/adapters/mcp/bin/serve.ts +74 -1
  60. package/src/adapters/mcp/deliberate.ts +169 -651
  61. package/src/adapters/mcp/facts.ts +1094 -0
  62. package/src/adapters/mcp/index.ts +25 -7
  63. package/src/adapters/mcp/meaning.ts +1610 -0
  64. package/src/adapters/mcp/server.ts +835 -150
  65. package/src/adapters/mcp/stdio.ts +3 -1
  66. package/src/adapters/mcp/stood-down.ts +51 -0
  67. package/src/adapters/mcp/tools.ts +167 -41
  68. package/src/adapters/plugin-run.sh +133 -0
  69. package/src/adapters/plugin.ts +329 -0
  70. package/src/adapters/sessions.ts +18 -4
  71. package/src/core/associate/CONTRACT.md +2 -1
  72. package/src/core/associate/INTERFACE-GAPS.md +6 -1
  73. package/src/core/associate/NOTES.md +45 -0
  74. package/src/core/briefing.ts +12 -3
  75. package/src/core/contradictions.ts +184 -0
  76. package/src/core/counterpart.ts +797 -51
  77. package/src/core/dream/CONTRACT.md +36 -4
  78. package/src/core/dream/INTERFACE-GAPS.md +29 -6
  79. package/src/core/dream/NOTES.md +107 -0
  80. package/src/core/dream/feeling-weeks.ts +198 -0
  81. package/src/core/dream/index.ts +109 -18
  82. package/src/core/dream/reflect.ts +346 -87
  83. package/src/core/dream/tunables.ts +24 -4
  84. package/src/core/encode/INTERFACE-GAPS.md +3 -1
  85. package/src/core/encode/NOTES.md +7 -0
  86. package/src/core/encode/words.ts +45 -0
  87. package/src/core/fit/INTERFACE-GAPS.md +8 -2
  88. package/src/core/fit/NOTES.md +39 -1
  89. package/src/core/fit/index.ts +40 -0
  90. package/src/core/handoff/CONTRACT.md +37 -2
  91. package/src/core/handoff/INTERFACE-GAPS.md +10 -0
  92. package/src/core/handoff/NOTES.md +72 -0
  93. package/src/core/handoff/index.ts +214 -12
  94. package/src/core/handoff/last-here.ts +6 -4
  95. package/src/core/mint.ts +12 -2
  96. package/src/core/physics/CONTRACT.md +14 -2
  97. package/src/core/physics/NOTES.md +33 -1
  98. package/src/core/physics/index.ts +28 -5
  99. package/src/core/prospective/CONTRACT.md +45 -6
  100. package/src/core/prospective/INTERFACE-GAPS.md +4 -0
  101. package/src/core/prospective/NOTES.md +138 -0
  102. package/src/core/prospective/derive.ts +33 -5
  103. package/src/core/prospective/index.ts +90 -5
  104. package/src/core/prospective/windows.ts +72 -1
  105. package/src/core/recall/CONTRACT.md +31 -12
  106. package/src/core/recall/INTERFACE-GAPS.md +28 -4
  107. package/src/core/recall/NOTES.md +70 -1
  108. package/src/core/recall/feeling-ask.ts +10 -1
  109. package/src/core/recall/index.ts +3 -1
  110. package/src/core/recall/probe.ts +58 -0
  111. package/src/core/recall/session.ts +46 -2
  112. package/src/core/recall/time-ask.ts +487 -0
  113. package/src/core/remember/CONTRACT.md +4 -1
  114. package/src/core/remember/INTERFACE-GAPS.md +9 -1
  115. package/src/core/remember/NOTES.md +8 -0
  116. package/src/core/remember/proposals.ts +47 -5
  117. package/src/core/revision.ts +18 -1
  118. package/src/core/schemas/CONTRACT.md +21 -1
  119. package/src/core/schemas/INTERFACE-GAPS.md +20 -2
  120. package/src/core/schemas/NOTES.md +144 -0
  121. package/src/core/schemas/aliases.ts +55 -5
  122. package/src/core/schemas/index.ts +93 -1
  123. package/src/core/schemas/types.ts +2 -0
  124. package/src/core/self/CONTRACT.md +32 -5
  125. package/src/core/self/INTERFACE-GAPS.md +7 -2
  126. package/src/core/self/NOTES.md +102 -1
  127. package/src/core/self/behind.ts +43 -3
  128. package/src/core/self/briefing.ts +12 -2
  129. package/src/core/self/chapter-address.ts +254 -0
  130. package/src/core/self/episodes.ts +27 -0
  131. package/src/core/self/index.ts +83 -8
  132. package/src/core/self/page.ts +88 -0
  133. package/src/core/self/tunables.ts +5 -0
  134. package/src/core/self/work.ts +35 -2
  135. package/src/core/self/writer.ts +30 -0
  136. package/src/core/sleep/INTERFACE-GAPS.md +22 -3
  137. package/src/core/sleep/NOTES.md +20 -1
  138. package/src/core/sleep/consolidate.ts +59 -7
  139. package/src/core/sleep/index.ts +3 -0
  140. package/src/core/sleep/prune.ts +6 -2
  141. package/src/core/sleep/types.ts +7 -0
  142. package/src/core/store/CONTRACT.md +16 -0
  143. package/src/core/store/NOTES.md +66 -0
  144. package/src/core/store/feelings.ts +14 -1
  145. package/src/core/store/index.ts +483 -16
  146. package/src/core/store/operational.ts +95 -2
  147. package/src/core/store/owner-op-seam.ts +23 -0
  148. package/src/core/time.ts +152 -0
  149. package/tools/install-loop/run.sh +48 -12
  150. package/src/adapters/dashboard/web/pages/memories/fold.js +0 -53
@@ -0,0 +1,329 @@
1
+ /**
2
+ * THE CLAUDE CODE PLUGIN'S SEAM — prototype, 2026-10-09.
3
+ *
4
+ * Counterparts can reach Claude Code two ways now. The npm way: `npm i -g
5
+ * counterparts`, then `counterparts install`, which writes the store and its
6
+ * configuration and wires the host by editing `~/.claude/settings.json` and
7
+ * running `claude mcp add`. The plugin way: Claude Code fetches this
8
+ * repository as a plugin (`.claude-plugin/plugin.json` at its root), runs the
9
+ * five hooks `hooks/hooks.json` names and the MCP server `plugin.json` names,
10
+ * and nothing in the person's settings is edited by us at all.
11
+ *
12
+ * Both launch the SAME entry points (`claude-code/bin/hook.ts`,
13
+ * `mcp/bin/serve.ts`) through `plugin-run.sh`. This file is the few things
14
+ * that differ when the launcher is the plugin's:
15
+ *
16
+ * 1. **Knowing it.** `CLAUDE_PLUGIN_ROOT` is set by Claude Code on the
17
+ * plugin's own hook and server processes, and it is THIS package's root
18
+ * exactly when the plugin is this copy of Counterparts. Equality, not
19
+ * presence: the variable is inherited by children, and a settings-wired
20
+ * hook of a different install must never mistake itself for the plugin.
21
+ * 2. **Not firing twice.** A person with the npm wiring AND the plugin gets
22
+ * every hook twice (Claude Code merges hooks from settings and plugins
23
+ * and runs them all) and two memory servers (plugin servers are deduped
24
+ * only by identical command). The npm installs already out there cannot
25
+ * learn about the plugin, so the rule has to live on THIS side: **the
26
+ * plugin stands down wherever the npm wiring is live** — hooks for
27
+ * hooks, the server for the server — and says once, at session start,
28
+ * how to move (`counterparts disconnect`). Same store either way, so
29
+ * moving loses nothing.
30
+ * 3. **First run without a terminal.** The npm way creates the store and
31
+ * `~/.counterparts/claude-code.json` at `install`. A plugin has no
32
+ * install step we run, so the first hook or server to start runs that
33
+ * same `install` (non-interactive, `--no-connect`: it writes OUR two
34
+ * things and touches no host file), under a lock so the hook and the
35
+ * server racing at session start produce one install, not two. The
36
+ * layout is therefore exactly the npm one, which is what makes moving
37
+ * between the two a non-event.
38
+ */
39
+ import { spawnSync } from "node:child_process";
40
+ import { createHash } from "node:crypto";
41
+ import { existsSync, mkdirSync, readdirSync, realpathSync, rmdirSync, statSync } from "node:fs";
42
+ import { tmpdir } from "node:os";
43
+ import { basename, dirname, join, resolve } from "node:path";
44
+ import { fileURLToPath } from "node:url";
45
+
46
+ import { implicitConfigRefusal } from "./config-path.js";
47
+ import type { ConfigChoice } from "./config-path.js";
48
+ import type { NpmWiring } from "./host-wiring.js";
49
+ import { CLI_SCRIPT, scriptArgs } from "./runtime.js";
50
+
51
+ /** Set by Claude Code on a plugin's hook, MCP and LSP processes. */
52
+ export const PLUGIN_ROOT_ENV = "CLAUDE_PLUGIN_ROOT";
53
+ /**
54
+ * The plugin's persistent directory — and the memory is deliberately NOT in
55
+ * it. Claude Code deletes `~/.claude/plugins/data/<id>/` when the plugin is
56
+ * uninstalled from its last scope (unless `--keep-data`), and a memory that an
57
+ * uninstall erases is not one anybody agreed to. The store stays where the
58
+ * npm install puts it, `~/.counterparts/store`, which is also what lets a
59
+ * person move between the two installs without moving anything.
60
+ */
61
+ export const PLUGIN_DATA_ENV = "CLAUDE_PLUGIN_DATA";
62
+
63
+ /** This package's root — the directory holding `package.json` and, in this
64
+ * repository, `.claude-plugin/`. */
65
+ export const PACKAGE_ROOT = fileURLToPath(new URL("../../", import.meta.url));
66
+
67
+ function realOrResolved(path: string): string {
68
+ try {
69
+ return realpathSync(path);
70
+ } catch {
71
+ return resolve(path);
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Is this process the plugin's? True when Claude Code's `CLAUDE_PLUGIN_ROOT`
77
+ * names this very package. Both sides are realpath'd: macOS spells one
78
+ * directory `/var/…` and `/private/var/…`, and a plugin added from a symlinked
79
+ * checkout is the same plugin.
80
+ */
81
+ export function runningAsPlugin(
82
+ env: Record<string, string | undefined>,
83
+ packageRoot: string = PACKAGE_ROOT,
84
+ ): boolean {
85
+ const named = (env[PLUGIN_ROOT_ENV] ?? "").trim();
86
+ if (named.length === 0) return false;
87
+ return realOrResolved(named) === realOrResolved(packageRoot);
88
+ }
89
+
90
+ /** `~/…` for a path under the home directory, for a line a person reads. */
91
+ function tildeOf(path: string, home: string): string {
92
+ const h = resolve(home);
93
+ const p = resolve(path);
94
+ return p === h ? "~" : p.startsWith(`${h}/`) ? `~${p.slice(h.length)}` : p;
95
+ }
96
+
97
+ /** What the plugin's hook does about the npm wiring, and what it says. */
98
+ export interface PluginGate {
99
+ readonly standDown: boolean;
100
+ /** One line for the owner at session start, or null. */
101
+ readonly line: string | null;
102
+ }
103
+
104
+ /**
105
+ * THE HOOKS' RULE: live npm hooks win. A DEAD npm entry (its runtime or script
106
+ * gone — an uninstalled package, a deleted checkout) runs nothing, so the
107
+ * plugin carries on and says the stale lines are there.
108
+ */
109
+ export function hookGate(wiring: NpmWiring, home: string): PluginGate {
110
+ const live = wiring.hooks.find((h) => h.live);
111
+ if (live !== undefined) {
112
+ return {
113
+ standDown: true,
114
+ line:
115
+ `Counterparts is installed twice: the npm install's hooks in ${tildeOf(live.file, home)} and this plugin. ` +
116
+ "The plugin is standing down so nothing is captured twice. To keep only the plugin, run " +
117
+ "`counterparts disconnect` and restart Claude Code; the memory is the same either way.",
118
+ };
119
+ }
120
+ const dead = wiring.hooks[0];
121
+ if (dead !== undefined) {
122
+ return {
123
+ standDown: false,
124
+ line:
125
+ `Counterparts: ${tildeOf(dead.file, home)} still names an old Counterparts hook that no longer runs. ` +
126
+ "The plugin is keeping your memory; remove those entries to quiet them.",
127
+ };
128
+ }
129
+ return { standDown: false, line: null };
130
+ }
131
+
132
+ /**
133
+ * THE SERVER'S RULE: a live `counterparts` registration in the user or local
134
+ * scope wins. The words become the stood-down server's `instructions`, which
135
+ * is the only thing a model sees of a server with no tools.
136
+ */
137
+ export function mcpGate(wiring: NpmWiring, home: string): { readonly standDown: boolean; readonly instructions: string | null } {
138
+ const live = wiring.mcp.find((m) => m.live);
139
+ if (live === undefined) return { standDown: false, instructions: null };
140
+ return {
141
+ standDown: true,
142
+ instructions:
143
+ `This plugin's Counterparts server is standing down: the npm install already registers a ` +
144
+ `"counterparts" memory server (${live.scope} scope, ${tildeOf(live.file, home)}), and two servers ` +
145
+ "over one memory would offer every tool twice. Use that server's tools. To use the plugin's " +
146
+ "instead, run `counterparts disconnect` and restart Claude Code.",
147
+ };
148
+ }
149
+
150
+ // ── first run ───────────────────────────────────────────────────────────────
151
+
152
+ /**
153
+ * `joined`: absent when this process looked, made by a CONCURRENT first run
154
+ * (the hook and the server start together) while this one waited. It is still
155
+ * this session's first run, so it carries the same line as `created`.
156
+ */
157
+ export type FirstRunState = "existed" | "created" | "joined" | "skipped" | "failed";
158
+
159
+ export interface FirstRun {
160
+ readonly state: FirstRunState;
161
+ /** One line for the owner at session start, or null when there is nothing
162
+ * to say (an existing install, a skipped one). */
163
+ readonly line: string | null;
164
+ /** Why it failed or was skipped, for stderr. */
165
+ readonly detail?: string;
166
+ }
167
+
168
+ /** How long a waiting process gives the one holding the lock. An install is a
169
+ * directory, an empty database and a small JSON file: well under a second on
170
+ * the machines measured, so twenty is generous and still inside Claude
171
+ * Code's thirty-second MCP start-up window. */
172
+ export const FIRST_RUN_WAIT_MS = 20_000;
173
+ /** A lock older than this is a process that died holding it. */
174
+ export const FIRST_RUN_STALE_MS = 120_000;
175
+ /** The install's own ceiling, as a child process. */
176
+ export const FIRST_RUN_TIMEOUT_MS = 60_000;
177
+
178
+ /**
179
+ * Where the lock lives: the system temp directory, keyed by the configuration
180
+ * path — never inside `~/.counterparts`, where a leftover lock directory would
181
+ * be one more entry for `doctor` and `start-fresh` to have an opinion about.
182
+ */
183
+ export function firstRunLockPath(configPath: string, tmp: string = tmpdir()): string {
184
+ const key = createHash("sha256").update(resolve(configPath)).digest("hex").slice(0, 16);
185
+ return join(tmp, `counterparts-first-run-${key}.lock`);
186
+ }
187
+
188
+ /**
189
+ * A MEMORY SET ASIDE BESIDE THE ONE ABOUT TO BE MADE (review of #328).
190
+ * `counterparts uninstall --park` leaves `<base>.parked-<date>[-N]` next to
191
+ * where the configuration lives (`cli/install.ts#parkedNameParts`, which also
192
+ * checks the date is a real day; the shape is enough here). A non-interactive
193
+ * install walks past one and makes a blank store beside it, and says so on
194
+ * stdout (review M4: "a second store the person does not know about") — but
195
+ * the first run drops that stdout, so the line it hands the wake has to say it
196
+ * instead. Named only: nothing here opens, moves or counts it.
197
+ */
198
+ export function parkedBeside(base: string): string[] {
199
+ const dir = dirname(resolve(base));
200
+ const prefix = `${basename(resolve(base))}.parked-`;
201
+ try {
202
+ return readdirSync(dir)
203
+ .filter((n) => n.startsWith(prefix) && /^\d{4}-\d{2}-\d{2}(-\d+)?$/.test(n.slice(prefix.length)))
204
+ .sort()
205
+ .map((n) => join(dir, n));
206
+ } catch {
207
+ return [];
208
+ }
209
+ }
210
+
211
+ function sleepSync(ms: number): void {
212
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
213
+ }
214
+
215
+ export interface FirstRunInput {
216
+ readonly choice: ConfigChoice;
217
+ readonly env: Record<string, string | undefined>;
218
+ readonly home: string;
219
+ /** The runtime that runs the console: this process's own, by default. */
220
+ readonly runtime?: string;
221
+ readonly cliScript?: string;
222
+ readonly lockPath?: string;
223
+ readonly waitMs?: number;
224
+ readonly staleMs?: number;
225
+ readonly now?: () => number;
226
+ }
227
+
228
+ /**
229
+ * Make sure the store and the default configuration exist, the way
230
+ * `counterparts install` makes them — by running it.
231
+ *
232
+ * SKIPPED, and nothing written, when a configuration was NAMED (`--config`,
233
+ * `COUNTERPARTS_CONFIG`: somebody chose a file, and a missing one is that
234
+ * entry point's refusal to make) or when the explicit-dir guard is armed (it
235
+ * refuses the implicit default by design; `config-path.ts#implicitConfigRefusal`).
236
+ *
237
+ * The console is SPAWNED rather than imported: adapters do not import each
238
+ * other, and the console is the one place that knows how an install is made
239
+ * ("invent no second install path"). Its output is captured and dropped — a
240
+ * hook's stdout is the model's context, and a server's is the JSON-RPC wire.
241
+ */
242
+ export function ensureFirstRun(input: FirstRunInput): FirstRun {
243
+ const { choice, env } = input;
244
+ if (choice.source !== "default") return { state: "skipped", line: null, detail: `configuration named by ${choice.source}` };
245
+ if (existsSync(choice.path)) return { state: "existed", line: null };
246
+ const guard = implicitConfigRefusal(choice, env);
247
+ if (guard !== null) return { state: "skipped", line: null, detail: guard };
248
+
249
+ const now = input.now ?? ((): number => Date.now());
250
+ const lock = input.lockPath ?? firstRunLockPath(choice.path);
251
+ const waitMs = input.waitMs ?? FIRST_RUN_WAIT_MS;
252
+ const staleMs = input.staleMs ?? FIRST_RUN_STALE_MS;
253
+ const base = dirname(choice.path);
254
+ const parked = parkedBeside(base);
255
+ const created: FirstRun = {
256
+ state: "created",
257
+ line:
258
+ `Counterparts: first run — a new memory was set up at ${tildeOf(base, input.home)}. ` +
259
+ "It stays on this computer." +
260
+ (parked.length === 0
261
+ ? ""
262
+ : ` A memory set aside earlier is still at ${parked.map((p) => tildeOf(p, input.home)).join(", ")}, untouched; ` +
263
+ "the new one does not include it."),
264
+ };
265
+
266
+ const take = (): boolean => {
267
+ try {
268
+ mkdirSync(lock);
269
+ return true;
270
+ } catch (err) {
271
+ if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
272
+ return false;
273
+ }
274
+ };
275
+
276
+ let held = take();
277
+ if (!held) {
278
+ // Somebody else is installing. Wait for the configuration to appear; a
279
+ // lock older than `staleMs` is a dead process's, and is taken over once.
280
+ const until = now() + waitMs;
281
+ while (!held) {
282
+ if (existsSync(choice.path)) return { ...created, state: "joined" };
283
+ let age = 0;
284
+ try {
285
+ age = now() - statSync(lock).mtimeMs;
286
+ } catch {
287
+ age = 0;
288
+ }
289
+ if (age > staleMs) {
290
+ try {
291
+ rmdirSync(lock);
292
+ } catch {
293
+ // Gone already, or not ours to remove; `take` below decides.
294
+ }
295
+ }
296
+ held = take();
297
+ if (held) break;
298
+ if (now() >= until) {
299
+ return { state: "failed", line: null, detail: `timed out after ${String(waitMs)} ms waiting for another first run (${lock})` };
300
+ }
301
+ sleepSync(100);
302
+ }
303
+ }
304
+ try {
305
+ // The one who waited may find it done the moment it gets the lock.
306
+ if (existsSync(choice.path)) return { ...created, state: "joined" };
307
+ const runtime = input.runtime ?? process.execPath;
308
+ const script = input.cliScript ?? CLI_SCRIPT;
309
+ const res = spawnSync(runtime, [...scriptArgs(script, runtime), "install", "--no-connect"], {
310
+ env: env as NodeJS.ProcessEnv,
311
+ encoding: "utf8",
312
+ timeout: FIRST_RUN_TIMEOUT_MS,
313
+ stdio: ["ignore", "pipe", "pipe"],
314
+ });
315
+ if (res.status === 0 && existsSync(choice.path)) return created;
316
+ const why = (String(res.stderr ?? "").trim().split("\n").pop() ?? "") || (res.error?.message ?? `exit ${String(res.status)}`);
317
+ return {
318
+ state: "failed",
319
+ line: `Counterparts could not set up its memory on first run (${why.slice(0, 200)}). Memory is off for this session.`,
320
+ detail: why,
321
+ };
322
+ } finally {
323
+ try {
324
+ rmdirSync(lock);
325
+ } catch {
326
+ // Already gone: nothing to release.
327
+ }
328
+ }
329
+ }
@@ -76,6 +76,8 @@ import {
76
76
  import { join, resolve } from "node:path";
77
77
  import { fileURLToPath } from "node:url";
78
78
 
79
+ import { wireChars } from "../core/fit/index.js";
80
+
79
81
  import {
80
82
  NO_HOST_EVIDENCE,
81
83
  planRetention,
@@ -1009,7 +1011,7 @@ export const UPDATE_NOTICE = `Counterparts was updated. ${RECONNECT_REMEDY}`;
1009
1011
  export const CHANGED_NOTICE = `Counterparts was changed to an older version. ${RECONNECT_REMEDY}`;
1010
1012
 
1011
1013
  /** A plain `x.y.z` compare; anything else is "not newer". */
1012
- function versionNewer(a: string | null, b: string | null): boolean {
1014
+ export function versionNewer(a: string | null, b: string | null): boolean {
1013
1015
  if (a === null || b === null) return false;
1014
1016
  const pa = /^(\d+)\.(\d+)\.(\d+)$/.exec(a);
1015
1017
  const pb = /^(\d+)\.(\d+)\.(\d+)$/.exec(b);
@@ -1939,13 +1941,25 @@ export function writeUpParts(entries: readonly WriteUpEntry[], chunkBytes: numbe
1939
1941
  return writeUpPartsDated(entries, chunkBytes).map((p) => p.text);
1940
1942
  }
1941
1943
 
1944
+ /**
1945
+ * WHAT A PIECE OF A PART COSTS (2026-10-02, review of #315): the larger of its
1946
+ * UTF-8 bytes and its wire cost as it leaves — escaped inside the result's
1947
+ * JSON, a non-ASCII character as three (`fit/wireChars`) — so a part sized at
1948
+ * `chunkBytes` never meets the MCP server's net (`fit/TOOL_RESULT_CEILING`)
1949
+ * however many quotes and newlines it carries. Escaping is per character, so
1950
+ * the cost of a joined text is the sum of its pieces'.
1951
+ */
1952
+ function partCost(text: string): number {
1953
+ return Math.max(Buffer.byteLength(text, "utf8"), wireChars(JSON.stringify(text)) - 2);
1954
+ }
1955
+
1942
1956
  /**
1943
1957
  * The same parts, each with the capture time of its latest entry — what dates
1944
1958
  * the day a write-up of that part records as LIVED (`happened_on`, 2026-10-01).
1945
1959
  */
1946
1960
  export function writeUpPartsDated(entries: readonly WriteUpEntry[], chunkBytes: number): { text: string; lastAt: number }[] {
1947
1961
  const size = Math.max(1, Math.floor(chunkBytes));
1948
- const sep = Buffer.byteLength(WRITE_UP_SEPARATOR, "utf8");
1962
+ const sep = partCost(WRITE_UP_SEPARATOR);
1949
1963
  const parts: { text: string; lastAt: number }[] = [];
1950
1964
  let cur = "";
1951
1965
  let curBytes = 0;
@@ -1962,7 +1976,7 @@ export function writeUpPartsDated(entries: readonly WriteUpEntry[], chunkBytes:
1962
1976
  (entry.jot ? `${WRITE_UP_JOT_MARK} ` : "") +
1963
1977
  (entry.reply === true ? `${WRITE_UP_REPLY_MARK} ` : "") +
1964
1978
  entry.text;
1965
- const bytes = Buffer.byteLength(rendered, "utf8");
1979
+ const bytes = partCost(rendered);
1966
1980
  if (cur.length > 0 && curBytes + sep + bytes <= size) {
1967
1981
  cur += WRITE_UP_SEPARATOR + rendered;
1968
1982
  curBytes += sep + bytes;
@@ -1980,7 +1994,7 @@ export function writeUpPartsDated(entries: readonly WriteUpEntry[], chunkBytes:
1980
1994
  let slice = "";
1981
1995
  let sliceBytes = 0;
1982
1996
  for (const ch of rendered) {
1983
- const b = Buffer.byteLength(ch, "utf8");
1997
+ const b = partCost(ch);
1984
1998
  if (sliceBytes + b > size && slice.length > 0) {
1985
1999
  parts.push({ text: slice, lastAt: entry.at });
1986
2000
  slice = "";
@@ -125,7 +125,8 @@ for `recall/`; telemetry by reference.
125
125
  writers) · **E7** (observers train nothing) · **E8** (base-level decay on lived days) ·
126
126
  **§2.1** (multi-writer structured state needs a transaction) · **§2.2** (a removed id must
127
127
  stop conducting; supersede retargets edges too — v1's `gist.merge` set `merged_into` and
128
- nothing re-pointed the edges, so successors started cold) · **§2.4** (no success telemetry
128
+ nothing re-pointed the edges, so successors started cold. So do a dream merge and, since
129
+ 2026-10-09, a regrown chapter copy, NOTES §15) · **§2.4** (no success telemetry
129
130
  for a publish that did not land) · **§2.8** (credit weights ship measured or disabled) ·
130
131
  **§2.17** (edges have an exit path — eviction — and its count is reported).
131
132
 
@@ -123,6 +123,10 @@ counts and ids sitting in `sessions/association/claims/`.
123
123
  ## 4. Nobody calls `retargetOnSupersede` — supersede does not know about edges
124
124
 
125
125
  **Closed 2026-09-24** — `counterpart.ts` injects `retargetOnSupersede` into both `supersede` callers (`Schemas.open`'s `retarget`, and `applyRevision` in `core/revision.ts`).
126
+ The same callback reaches a dream merge (`Dreams`' `retarget`, 2026-09-26) and, since
127
+ 2026-10-09, a regrown chapter copy (`Self`'s `retarget`; the copies archived before then
128
+ are carried once at open, NOTES §15). A bare `Store.supersede` or `Store.archive` still
129
+ carries nothing.
126
130
 
127
131
  **Owner:** `store/` and whoever owns revision (scar §2.2: "supersede retargets edges
128
132
  too — v1's `gist.merge` set `merged_into` and nothing re-pointed the edges, so
@@ -241,7 +245,8 @@ be its own design.
241
245
 
242
246
  ## 12. A dream's lookups never reach the credit pass (noted 2026-09-28)
243
247
 
244
- **Owner:** the Claude Code adapter (`transcript.ts`, `hooks.ts#creditAtBoundary`).
248
+ **Owner:** the Claude Code adapter (`transcript.ts`, `hooks.ts#creditAtBoundary` — in
249
+ `adapters/lifecycle.ts` since #292, 2026-09-30).
245
250
  **Have:** index co-credit works where the lookups are in the session's own transcript:
246
251
  the hook flattens every `recall ids:[…]` batch in a reply's slice into the credit pass's
247
252
  expansions (tested, `association-build2.test.ts` › "5."). **Gap:** the nightly run —
@@ -411,3 +411,48 @@ referenced × surfaced pair conducts on its first meeting — "shown beside" lin
411
411
  accumulate across boundaries; the credit pass passes no surfaced member in any case, and
412
412
  one loud slot a turn means surfaced × surfaced cannot occur in one reply. The fixture
413
413
  contract §4 asks for is `association-build2.test.ts` › "6.".
414
+
415
+ ## 15. Regrown chapter copies carry their links (2026-10-09)
416
+
417
+ The association diagnosis of 10-02 (measured on a copy of the owner's store) found 324
418
+ of 1,200 edge rows with an archived endpoint: 260 on chapter copies archived
419
+ `episode-regrown`, 54 on dream-merge originals, 10 on corrected memories. Read against the
420
+ code:
421
+
422
+ - **Regrown copies were the gap.** `Self#ingestEpisode` mints a new copy when its chapter
423
+ grows and archives the old one, and nothing handed the old copy's links on. Now `Self`
424
+ takes a `retarget` callback (SEAMS E, the way `schemas/` and `dream/` do; `self/` may
425
+ not import this module) and calls it per archived copy, after the archive, so one stale
426
+ copy's tie to another is not carried. The composition root wires it to
427
+ `retargetOnSupersede`, the merge rule unchanged: the old copy's live outgoing weights as
428
+ they stand on the day, `max` with what the new copy has, both directions, capped. A
429
+ throw costs the links, never the copy (`self.episode.relink.failed`).
430
+ - **Dream merges and corrections were not.** Both already go through
431
+ `retargetOnSupersede` (`dream/index.ts`, `revision.ts`). Their 64 rows are the
432
+ originals' own, left in place by design (this module has no delete); the merged or
433
+ corrected memory holds the carried copies.
434
+ - **The links already stranded are carried once.** `Counterpart#relinkRegrownCopies` runs
435
+ at open, latched in meta (`REGROWN_RELINK_META`) like the v12 subject backfill: it reads
436
+ the edge table (not the store), finds each source archived `episode-regrown`, and hands
437
+ its links to the chapter's live copy (`origin_ref`), or counts it `noLiveCopy` when the
438
+ chapter has none. A link that has faded below the floor since carries nothing. Writer
439
+ only; fail-open, tried again next open; idempotent if cut short. A carry whose write
440
+ failed (the edge module answers `failed` rather than throwing) leaves the pass
441
+ unlatched, so a store that keeps failing re-reads its edge table at every open until
442
+ one pass lands, as the v12 backfill would.
443
+ - *Review of #329.* A copy a removal has taken dark (its edge rows still waiting for the
444
+ chase) carries nothing and is counted `removed`: its links must not outlive the chase on
445
+ the live copy. The live copies come from one `store.copiesOf` read, not a
446
+ `list({ originRef })` per chapter (`origin_ref` has no index). Measured on synthetic
447
+ stores at open: about 800 memories and 1,800 edge rows (130 pairs stranded), the pass
448
+ went from 120–340 ms to about 50 ms; about 15,000 memories and 12,000 edge rows, from
449
+ 2.8–3.4 s to about 0.3 s. Most of what is left is one `linkMany` per copy. Every later
450
+ open pays one meta read.
451
+ - *Known limits, the merge rule's own:* only the old copy's outgoing rows are read, so a
452
+ row written one way into it would not carry (co-use, contiguity and a dream's links all
453
+ write both ways today), and contiguity's forward-over-back difference becomes the
454
+ stronger outgoing weight both ways. The carry writes through `linkMany`, not the flush,
455
+ so the per-node cap applies at the next flush that touches the copy, not at the carry.
456
+ The archived copy's rows stay until they decay to the floor and a flush sweeps them, so
457
+ a re-run of the 10-02 count will still find them for a while; count what the live copy
458
+ holds, not what the archived one still has.
@@ -20,6 +20,8 @@
20
20
  * are already built; only the source was borrowed).
21
21
  */
22
22
  import type { RenderFn } from "./sleep/index.js";
23
+ import { readableRecurrence } from "./time.js";
24
+ import type { Recurrence } from "./time.js";
23
25
 
24
26
  /** Structurally `Self`, so this file imports no class. */
25
27
  export interface BriefingRenderer {
@@ -33,7 +35,9 @@ export interface BriefingRenderer {
33
35
 
34
36
  /** Structurally `Prospective.horizon()`. */
35
37
  export interface HorizonSource {
36
- horizon(input: { at: string; day?: number }): { items: readonly { memoryId: string; eventDate?: string }[] };
38
+ horizon(input: { at: string; day?: number }): {
39
+ items: readonly { memoryId: string; eventDate?: string; anchor?: string; recurring?: Recurrence }[];
40
+ };
37
41
  }
38
42
 
39
43
  export interface RendererOptions {
@@ -60,8 +64,13 @@ export function selfRenderer(self: BriefingRenderer, opts: RendererOptions = {})
60
64
  ? undefined
61
65
  : opts.prospective
62
66
  .horizon({ at: opts.at, day: ctx.day })
63
- // The date it is due rides along, so the line can say it (2026-10-01).
64
- .items.map((i) => (i.eventDate === undefined ? { id: i.memoryId } : { id: i.memoryId, due: i.eventDate }));
67
+ // The date it is due rides along, so the line can say it (2026-10-01),
68
+ // and how often it comes round when it repeats (2026-10-09).
69
+ .items.map((i) => {
70
+ if (i.eventDate === undefined) return { id: i.memoryId };
71
+ const every = i.anchor === undefined || i.recurring === undefined ? "" : readableRecurrence(i.anchor, i.recurring);
72
+ return every === "" ? { id: i.memoryId, due: i.eventDate } : { id: i.memoryId, due: i.eventDate, every };
73
+ });
65
74
  const result = self.boundary({
66
75
  day: ctx.day,
67
76
  budgetBytes: ctx.budgetBytes,