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,1228 @@
1
+ /**
2
+ * `counterparts start-fresh` — beginning again without losing what came before.
3
+ *
4
+ * **What it is for.** The owner is about to use this system as a stranger would:
5
+ * a blank store, the QUICKSTART followed literally, every rough edge collected,
6
+ * fixed, and then started over again (plan §2 ruling 6, "cut-over carries
7
+ * NOTHING"). Doing that by hand is five steps
8
+ * (`docs/plan-step3-the-floor-2026-09-17.md` §2 step 5) with seventeen thousand
9
+ * private memories on the other side of a typo. This is those steps, once, with
10
+ * the guards written down.
11
+ *
12
+ * **THE ONE RULE, and everything below is a way of keeping it: it never deletes,
13
+ * and it never opens the old store.** Not for writing, not for reading, not
14
+ * read-only — a WAL store's `-wal` holds committed pages until somebody
15
+ * checkpoints it, and an opener is somebody. The old store is moved by a single
16
+ * `rename(2)` and then left exactly as it was, byte for byte, including its
17
+ * sidecars. Nothing in this file calls `Store.open`, `openDb`, `rm`, `unlink` or
18
+ * `cp` on anything at all. The only mutating call it makes is `rename`.
19
+ *
20
+ * Which is also why the command works on CUT-OVER DAY, when the running build
21
+ * REFUSES the store on disk by name (`STORE_PRE_ROWS`, F5): a rename does not
22
+ * care what floor a directory is on. For the same reason the question "is there
23
+ * a store here?" is asked as **does this directory exist and hold anything**,
24
+ * never `storeExists()` — that one looks for the canonical database by NAME, and
25
+ * the name changes with the floor, so on cut-over day it would answer "no store
26
+ * here" about the very store this command exists to protect.
27
+ *
28
+ * **Why the configuration decides which store, and `--dir` is refused.** The
29
+ * store that matters is the one the HOOKS and the MCP SERVER open, and that is
30
+ * `dataDir` in `claude-code.json` — nothing else. A `--dir` on this command line
31
+ * would be a second answer to "which store", which is the `--dirr` scar
32
+ * (`commands.ts#COMMAND_FLAGS`) pointed at the most dangerous verb in the
33
+ * package. So it is refused by name rather than quietly ignored.
34
+ *
35
+ * **Why the new store lands at the SAME path.** The floor plan's step 5 made a
36
+ * `store-v2` beside the old one and re-ran `claude mcp add`. Parking in place
37
+ * instead means `dataDir` does not move, so the configuration is kept
38
+ * byte-for-byte, the MCP registration (`-e COUNTERPARTS_DATA_DIR=<store>`) still
39
+ * names the right path, and there is no re-registration step to forget — which
40
+ * was named as failure mode (b) of the clean cut.
41
+ *
42
+ * **What a kill can leave behind.** The snapshots directory is parked FIRST and
43
+ * the store SECOND, so the only window in which the configuration names a
44
+ * directory that is not there is between the store's rename and the blank
45
+ * store's creation, which is two syscalls wide — and the rollback lines are
46
+ * printed BEFORE the first rename, so even a kill inside that window leaves the
47
+ * way back on the screen. A later run reads the ground and finishes.
48
+ */
49
+ import {
50
+ existsSync,
51
+ lstatSync,
52
+ readFileSync,
53
+ readdirSync,
54
+ realpathSync,
55
+ renameSync,
56
+ statSync,
57
+ } from "node:fs";
58
+ import { homedir } from "node:os";
59
+ import { basename, dirname, isAbsolute, join, parse as parsePath, resolve } from "node:path";
60
+
61
+ // `preRowsMarkersIn` reads FILENAMES and opens nothing — which is the only
62
+ // reason this module may call it. It is how the plan can say which floor the
63
+ // store being parked is on without going anywhere near its database.
64
+ import {
65
+ PRE_ROWS_READABLE_BY,
66
+ assertSafeDataDir,
67
+ dateOf,
68
+ isWithin,
69
+ preRowsMarkersIn,
70
+ } from "../../core/store/index.js";
71
+ import { SESSIONS_DIR } from "../sessions.js";
72
+
73
+ /** The infix a parked directory wears: `store.parked-2026-09-20`. */
74
+ export const PARKED_INFIX = "parked";
75
+
76
+ /** And the one the BLANK store wears when a rollback parks it in turn. */
77
+ export const BLANK_INFIX = "blank";
78
+
79
+ /**
80
+ * How recently something must have touched the store for this command to call
81
+ * it open.
82
+ *
83
+ * It is short on purpose. A crashed session leaves a record behind, and a
84
+ * window measured in hours (`sessions.ts#SESSION_TTL_MS` is four of them) would
85
+ * lock the owner out of his own cut-over until it expired. Ten minutes is long
86
+ * enough that a session anybody is actually using has touched a boundary or a
87
+ * `-wal` inside it, and short enough that yesterday's crash is not an obstacle.
88
+ *
89
+ * **It is a floor on the evidence, never a proof of the absence.** A Claude Code
90
+ * session sitting idle with its MCP server attached writes nothing and is
91
+ * invisible here. That is exactly why the confirmation below exists and says so
92
+ * in those words: the check catches the obvious case, the human catches the
93
+ * rest.
94
+ */
95
+ export const OPEN_WINDOW_MS = 10 * 60_000;
96
+
97
+ // ── what is on the ground ───────────────────────────────────────────────────
98
+
99
+ export interface DirSighting {
100
+ readonly path: string;
101
+ /** The directory is there. `lstat`, so a symlink counts as present. */
102
+ readonly present: boolean;
103
+ /** It is a symbolic link rather than a directory. Refused; see `parkRefusal`. */
104
+ readonly symlink: boolean;
105
+ /** How many entries it holds. 0 for an absent one, and for an empty one. */
106
+ readonly entries: number;
107
+ }
108
+
109
+ /**
110
+ * Is there something here, and what is it? FLOOR-AGNOSTIC BY CONSTRUCTION: it
111
+ * asks the filesystem, never the store, so an old-floor store, a half-restored
112
+ * copy and a store from a build nobody has written yet all read the same.
113
+ */
114
+ export function sight(path: string): DirSighting {
115
+ let stat;
116
+ try {
117
+ stat = lstatSync(path);
118
+ } catch {
119
+ return { path, present: false, symlink: false, entries: 0 };
120
+ }
121
+ if (stat.isSymbolicLink()) return { path, present: true, symlink: true, entries: 0 };
122
+ if (!stat.isDirectory()) return { path, present: true, symlink: false, entries: 0 };
123
+ let entries = 0;
124
+ try {
125
+ entries = readdirSync(path).length;
126
+ } catch {
127
+ // Unreadable is not empty. Treated as holding something, which is the
128
+ // direction that parks rather than overwrites.
129
+ entries = 1;
130
+ }
131
+ return { path, present: true, symlink: false, entries };
132
+ }
133
+
134
+ /**
135
+ * Why this directory may not be parked, or null.
136
+ *
137
+ * Every clause is the same mistake in a different costume: a path that turns
138
+ * out to name somewhere that matters. The forbidden-root check runs on BOTH
139
+ * spellings — the path as the configuration wrote it, and the path it actually
140
+ * reaches — which is the lesson the F2 adversarial review taught
141
+ * (`adapters/snapshots.ts#assertRotatableDir`): `assertSafeDataDir` is pure
142
+ * string math and follows no links, so a `dataDir` that is a symlink into
143
+ * `~/.bansai` clears it on the written spelling alone.
144
+ *
145
+ * A SYMLINK IS REFUSED OUTRIGHT rather than followed or renamed. Renaming a
146
+ * symlink moves the LINK: the real store would stay where it is, unparked,
147
+ * while a fresh empty directory appeared at the name the configuration points
148
+ * at — the old memories still live, still written to by anything holding them
149
+ * open, and no longer reachable by the configuration. That is the one outcome
150
+ * worse than refusing.
151
+ */
152
+ export function parkRefusal(
153
+ label: string,
154
+ path: string,
155
+ configPath: string,
156
+ home: string = homedir(),
157
+ ): string | null {
158
+ const written = resolve(path);
159
+ // As WRITTEN first, so the sentence names what the owner typed...
160
+ const forbidden = forbiddenRefusal(label, written);
161
+ if (forbidden !== null) return forbidden;
162
+ // ...and then as it RESOLVES, which is the spelling that decides where a
163
+ // rename would actually land.
164
+ const real = realpathDeep(written);
165
+ const forbiddenReal = forbiddenRefusal(label, real);
166
+ if (forbiddenReal !== null) return forbiddenReal;
167
+
168
+ if (real === parsePath(real).root) {
169
+ return `refused: the ${label} resolves to a filesystem root (${real}). Nothing here will rename that.`;
170
+ }
171
+ if (real === realpathDeep(home)) {
172
+ return `refused: the ${label} resolves to your home directory (${real}). Nothing here will rename that.`;
173
+ }
174
+ if (isWithin(written, configPath)) {
175
+ return (
176
+ `refused: the ${label} at ${written} CONTAINS the configuration ${configPath}. ` +
177
+ "Parking it would move the file that says where your memory is, and the hooks would " +
178
+ "read a path that is no longer there. The store belongs one level below the " +
179
+ "configuration (`install` puts it there); move it before starting fresh."
180
+ );
181
+ }
182
+ const seen = sight(path);
183
+ if (seen.symlink) {
184
+ let target = "somewhere else";
185
+ try {
186
+ target = realpathDeep(written);
187
+ } catch {
188
+ /* the sentence is about the link, not the target */
189
+ }
190
+ return (
191
+ `refused: the ${label} at ${written} is a SYMBOLIC LINK (to ${target}). ` +
192
+ "Renaming a link moves the link and leaves the real directory exactly where it is — " +
193
+ "so the memories would stay live, still open to anything holding them, and no longer " +
194
+ "reachable from your configuration. Park the real directory by hand, or point " +
195
+ `"dataDir" at it directly.`
196
+ );
197
+ }
198
+ return null;
199
+ }
200
+
201
+ function forbiddenRefusal(label: string, path: string): string | null {
202
+ try {
203
+ assertSafeDataDir(path);
204
+ return null;
205
+ } catch (err) {
206
+ const root =
207
+ err !== null && typeof err === "object" && "detail" in err
208
+ ? String((err as { detail: Record<string, unknown> }).detail["root"] ?? "a live store")
209
+ : "a live store";
210
+ return (
211
+ `refused by name: the ${label} (${path}) is inside ${root}. ` +
212
+ "That is a live memory this package never touches — not to read it, not to move it, " +
213
+ "not to rename it (CLAUDE.md, the second safety rule)."
214
+ );
215
+ }
216
+ }
217
+
218
+ /**
219
+ * THE ONE GUARD RING, and the reason it is one function.
220
+ *
221
+ * The confirmation review found `--undo` renaming directories inside `~/.bansai`
222
+ * — one command after the forward direction refused the same path, in those
223
+ * exact words, on the same screen. Not because the refusals were wrong, but
224
+ * because `--undo` was new code that called none of them. Two directions, two
225
+ * sets of checks, and only one of them maintained.
226
+ *
227
+ * So there is one function now, and **every path either direction would rename
228
+ * goes through it**: the store, a parked store read out of a record, a parked
229
+ * snapshots folder. It is the whole battery in the order that matters —
230
+ * present, absolute, not a forbidden root by either spelling, not a filesystem
231
+ * root, not the home directory, not a directory containing the configuration,
232
+ * not a symlink.
233
+ *
234
+ * `source` is where the path came from, because the sentence differs: a bad
235
+ * `dataDir` is a configuration to fix; a bad recorded path is a row in a
236
+ * database that should not have been trusted.
237
+ */
238
+ export function pathGuard(
239
+ label: string,
240
+ written: string,
241
+ configPath: string,
242
+ home: string = homedir(),
243
+ source = "the configuration",
244
+ ): string | null {
245
+ const raw = written.trim();
246
+ if (raw.length === 0) {
247
+ return `refused: ${source} gives no path for the ${label}, so there is nothing to act on.`;
248
+ }
249
+ if (!isAbsolute(raw)) {
250
+ return (
251
+ `refused: ${source} names "${raw}" as the ${label}, which is not an absolute path. ` +
252
+ "`install` always writes an absolute one, and for a reason: the hook, the worker and " +
253
+ "the MCP server are launched by a host from a working directory nobody chose, so a " +
254
+ "relative path names a different directory in every one of them — and this would act " +
255
+ `on whatever happened to sit at that name in ITS working directory (${resolve(raw)}). ` +
256
+ "A leading `~` is a shell's idea, not a path."
257
+ );
258
+ }
259
+ return parkRefusal(label, raw, configPath, home);
260
+ }
261
+
262
+ /**
263
+ * Why this path is not a PARKED SIBLING of that store, or null.
264
+ *
265
+ * **The record is a row in a database.** `store.previous.parked` lives in the
266
+ * new store's `meta` table, and anything that can open the store can write it —
267
+ * the review rewrote it to `~/.bansai/store` and watched `--undo` rename v1's
268
+ * live memory onto `dataDir`, and to `dirname(storeDir)` to get a directory
269
+ * planned into its own child. A value read back out of a store is data, never
270
+ * an instruction.
271
+ *
272
+ * So the shape is pinned rather than trusted: it must sit in the SAME directory
273
+ * as the store, and its name must be exactly the name this package writes —
274
+ * `<base>.parked-<date>` with an optional `-N`. `planUndo`'s own fallback only
275
+ * ever produces those; this makes a recorded value obey the rule the fallback
276
+ * already obeys.
277
+ */
278
+ export function parkedSiblingRefusal(
279
+ label: string,
280
+ candidate: string,
281
+ beside: string,
282
+ base: string,
283
+ ): string | null {
284
+ const path = resolve(candidate);
285
+ if (dirname(path) !== resolve(beside)) {
286
+ return (
287
+ `refused: the ${label} recorded in this store is ${path}, which does not sit beside ` +
288
+ `${resolve(beside)}. A record is a row in a database, not an instruction — anything it ` +
289
+ "names that is not a parked directory of this store is not a thing to rename."
290
+ );
291
+ }
292
+ const escaped = base.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
293
+ const pattern = new RegExp(`^${escaped}\\.${PARKED_INFIX}-\\d{4}-\\d{2}-\\d{2}(-\\d+)?$`);
294
+ if (!pattern.test(basename(path))) {
295
+ return (
296
+ `refused: the ${label} recorded in this store is ${path}, and '${basename(path)}' is ` +
297
+ `not a name this package writes — those are '${base}.${PARKED_INFIX}-<date>' with an ` +
298
+ "optional '-N'. A record is a row in a database; this will not rename something " +
299
+ "because a row said to."
300
+ );
301
+ }
302
+ return null;
303
+ }
304
+
305
+ /**
306
+ * The real path of a directory that may not exist yet — the same helper
307
+ * `adapters/snapshots.ts` carries, and for the same reason: `resolve` follows no
308
+ * links and `realpathSync` throws on a path that is not there, and both cases
309
+ * are ordinary here (macOS spells `$TMPDIR` through a symlink, and the
310
+ * snapshots directory does not exist before the first copy).
311
+ */
312
+ export function realpathDeep(path: string): string {
313
+ const resolved = resolve(path);
314
+ let head = resolved;
315
+ const tail: string[] = [];
316
+ for (;;) {
317
+ try {
318
+ // `realpathSync` is a READ of a path, never an open of a database.
319
+ const real = realpathSync(head);
320
+ return tail.length === 0 ? real : join(real, ...tail);
321
+ } catch {
322
+ const parent = dirname(head);
323
+ if (parent === head) return resolved;
324
+ tail.unshift(basename(head));
325
+ head = parent;
326
+ }
327
+ }
328
+ }
329
+
330
+ // ── the parked name ─────────────────────────────────────────────────────────
331
+
332
+ /**
333
+ * `<path>.<infix>-<date>`, with `-2`, `-3` … if that is taken.
334
+ *
335
+ * The date is the store's own UTC calendar date (`dateOf`), the same spelling
336
+ * every other date in this tree uses, so a parked directory sorts beside the
337
+ * snapshots and the journal entries of the day it was parked.
338
+ *
339
+ * `taken` is injected so the choice is provable without a filesystem, and so a
340
+ * caller can ask the question twice — once when it prints the plan and once
341
+ * after the human has confirmed it, because a name that was free before
342
+ * somebody went to make coffee may not be free after (scar §2.13).
343
+ */
344
+ export function parkedPath(
345
+ path: string,
346
+ infix: string,
347
+ date: string,
348
+ taken: (candidate: string) => boolean = existsSync,
349
+ ): string {
350
+ const base = `${resolve(path)}.${infix}-${date}`;
351
+ if (!taken(base)) return base;
352
+ for (let n = 2; n < 1000; n += 1) {
353
+ const candidate = `${base}-${String(n)}`;
354
+ if (!taken(candidate)) return candidate;
355
+ }
356
+ // A thousand parked stores in one day is not a case worth guessing at.
357
+ throw new Error(`no free parked name beside ${path} for ${date}`);
358
+ }
359
+
360
+ // ── who has it open ─────────────────────────────────────────────────────────
361
+
362
+ export interface OpenSign {
363
+ /** `session <id>` or the sidecar's file name. */
364
+ readonly what: string;
365
+ /** Where it was seen, in plain words. */
366
+ readonly where: string;
367
+ readonly agoMs: number;
368
+ }
369
+
370
+ export interface Liveness {
371
+ /** Evidence good enough to REFUSE on: a session the host has not ended whose
372
+ * hooks ran inside the window. */
373
+ readonly signs: readonly OpenSign[];
374
+ /** Evidence good enough to SAY, and not to refuse on: something wrote to the
375
+ * store recently, which may well have been the reader's own last command. */
376
+ readonly recent: readonly OpenSign[];
377
+ /** True when the sessions directory could not be read at all — not a refusal:
378
+ * an unreadable registry is no evidence either way, and the confirmation is
379
+ * what stands between this command and an open session regardless. */
380
+ readonly unreadable: boolean;
381
+ }
382
+
383
+ /**
384
+ * Cheap, honest evidence that something still has this store open — split into
385
+ * what is worth REFUSING on and what is only worth SAYING.
386
+ *
387
+ * Two sources, both READS OF METADATA — a `readdir`, a `stat`, and one small
388
+ * JSON file per live session. Neither opens a database.
389
+ *
390
+ * 1. **The live-session registry** (`<store>/sessions/<id>.json`): host state
391
+ * the hooks leave for the MCP server. A record with no `endedAt` whose last
392
+ * boundary is inside the window is a session whose hooks — and whose MCP
393
+ * server — are very likely still attached. **This is the refusal.**
394
+ *
395
+ * 2. **A fresh `-shm`.** Measured on this build, 2026-09-20: under `bun:sqlite`
396
+ * the `-wal` and the `-shm` SURVIVE a clean close — a store that nothing has
397
+ * open still has both, with the mtime of whatever last wrote. So a fresh
398
+ * `-shm` does NOT mean a connection is open; it means something wrote
399
+ * recently, and on this command line the likeliest something is the
400
+ * owner's own `doctor` a minute ago. Refusing on it made `start-fresh`
401
+ * refuse itself in testing. It is reported, in the sentence above the
402
+ * confirmation, and it is not a refusal. Matched by SUFFIX, never by
403
+ * database name, because the name changes with the floor.
404
+ *
405
+ * What neither can see is said out loud wherever they are printed: an idle open
406
+ * session writes nothing at all.
407
+ */
408
+ export function readLiveness(
409
+ storeDir: string,
410
+ now: number,
411
+ windowMs: number = OPEN_WINDOW_MS,
412
+ ): Liveness {
413
+ const signs: OpenSign[] = [];
414
+ const recent: OpenSign[] = [];
415
+ let unreadable = false;
416
+
417
+ const sessions = join(storeDir, SESSIONS_DIR);
418
+ let names: string[];
419
+ try {
420
+ names = readdirSync(sessions);
421
+ } catch {
422
+ names = [];
423
+ // An ABSENT sessions directory is ordinary — a store nothing has ever run
424
+ // against has none. `unreadable` is reserved for one that is THERE and
425
+ // would not list, because that is the source that could have answered and
426
+ // did not.
427
+ unreadable = existsSync(sessions);
428
+ }
429
+ for (const name of names) {
430
+ if (!name.endsWith(".json")) continue;
431
+ let raw: unknown;
432
+ try {
433
+ raw = JSON.parse(readFileSync(join(sessions, name), "utf8"));
434
+ } catch {
435
+ continue;
436
+ }
437
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) continue;
438
+ const rec = raw as Record<string, unknown>;
439
+ if (rec["endedAt"] !== null && rec["endedAt"] !== undefined) continue;
440
+ const last = rec["lastBoundaryAt"];
441
+ if (typeof last !== "number") continue;
442
+ const agoMs = now - last;
443
+ if (agoMs > windowMs || agoMs < -windowMs) continue;
444
+ const id = typeof rec["sessionId"] === "string" ? rec["sessionId"] : name.replace(/\.json$/, "");
445
+ const scope = typeof rec["scope"] === "string" ? rec["scope"] : "an unrecorded directory";
446
+ signs.push({ what: `session ${id}`, where: scope, agoMs });
447
+ }
448
+
449
+ for (const path of sidecarCandidates(storeDir)) {
450
+ try {
451
+ const agoMs = now - statSync(path).mtimeMs;
452
+ if (agoMs > windowMs || agoMs < -windowMs) continue;
453
+ recent.push({ what: basename(path), where: dirname(path), agoMs });
454
+ } catch {
455
+ continue;
456
+ }
457
+ }
458
+ return { signs, recent, unreadable };
459
+ }
460
+
461
+ /** Every `-shm` at the top of the store and inside `cache/`. Suffix, never name:
462
+ * the database is renamed by the floor and this check must not go with it. */
463
+ function sidecarCandidates(storeDir: string): string[] {
464
+ const out: string[] = [];
465
+ for (const dir of [storeDir, join(storeDir, "cache")]) {
466
+ try {
467
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
468
+ if (entry.isFile() && entry.name.endsWith("-shm")) out.push(join(dir, entry.name));
469
+ }
470
+ } catch {
471
+ continue;
472
+ }
473
+ }
474
+ return out;
475
+ }
476
+
477
+ // ── the plan ────────────────────────────────────────────────────────────────
478
+
479
+ export interface ParkStep {
480
+ /** What is being moved, in the words the output uses. */
481
+ readonly label: string;
482
+ readonly from: string;
483
+ readonly to: string;
484
+ }
485
+
486
+ export type StartFreshShape =
487
+ /** A store is there and will be parked. The ordinary case. */
488
+ | "park"
489
+ /** Nothing to park: no store directory, or an empty one. It is just an install. */
490
+ | "nothing-to-park"
491
+ /** The store directory is gone and something is parked beside it: a previous
492
+ * run was interrupted between the rename and the creation. Finish it. */
493
+ | "resume";
494
+
495
+ export interface StartFreshPlan {
496
+ readonly shape: StartFreshShape;
497
+ readonly configPath: string;
498
+ readonly configPresent: boolean;
499
+ readonly storeDir: string;
500
+ readonly date: string;
501
+ /** Snapshots first, store second. Empty for `nothing-to-park` and `resume`. */
502
+ readonly parks: readonly ParkStep[];
503
+ /** Already-parked directories a resume found, for the report. */
504
+ readonly alreadyParked: readonly string[];
505
+ /** The snapshots directory, when it is the one beside the store. */
506
+ readonly snapshotsDir: string | null;
507
+ /** Said when `snapshots.dir` points somewhere this command will not touch. */
508
+ readonly snapshotsElsewhere: string | null;
509
+ /**
510
+ * Why the snapshots folder beside the store is being LEFT rather than parked,
511
+ * or null when there is nothing to say. A symlinked `snapshots` used to refuse
512
+ * the whole command (review m2) — symlinking a backup folder onto an external
513
+ * disk is an ordinary thing to have done, and there is no way through except
514
+ * editing the configuration. It is now treated exactly as a configured
515
+ * `snapshots.dir` is: left alone, and said out loud. The store still moves.
516
+ */
517
+ readonly snapshotsLeft: string | null;
518
+ /** Part-built `store.new-<pid>` siblings an interrupted run left behind.
519
+ * Named, never adopted and never deleted (confirmation review MINOR-5). */
520
+ readonly strayTempStores: readonly string[];
521
+ /** How many entries the store being parked holds. `--yes` is refused on a
522
+ * non-empty one (review m1's corollary): the typed confirmation is the only
523
+ * instrument that can catch an idle dashboard. */
524
+ readonly storeEntries: number;
525
+ /**
526
+ * The pre-rows marker filenames found in the store being parked, or empty.
527
+ *
528
+ * This is **cut-over day, named**: a store holding `prose/`, `versions/` or
529
+ * `operational.sqlite` was written by a build before F5, and the build
530
+ * running this command refuses to open it (`STORE_PRE_ROWS`). That refusal is
531
+ * the right one and this command never reaches it — but a reader who has just
532
+ * seen it from `status` or from a hook deserves to be told that this is the
533
+ * same fact, and that it is the reason parking rather than touching is the
534
+ * whole move. Filenames only; nothing is opened to learn it.
535
+ */
536
+ readonly preRowsMarkers: readonly string[];
537
+ readonly liveness: Liveness;
538
+ readonly refusal: string | null;
539
+ }
540
+
541
+ export interface PlanInput {
542
+ readonly configPath: string;
543
+ readonly configPresent: boolean;
544
+ /** `dataDir` exactly as the configuration holds it. */
545
+ readonly dataDir: string | undefined;
546
+ /** `snapshots.dir` from the configuration, when it names one. */
547
+ readonly snapshotsConfigured: string | undefined;
548
+ readonly now: number;
549
+ readonly home?: string;
550
+ /** Injected by the tests that prove the name choice without a filesystem. */
551
+ readonly taken?: (candidate: string) => boolean;
552
+ }
553
+
554
+ /**
555
+ * Read the ground, decide the renames, and collect every reason not to.
556
+ *
557
+ * Pure but for the reads: it stats, lists and parses, and it changes nothing.
558
+ * `commands.ts` calls it TWICE — once to print, once after the confirmation —
559
+ * so it must be safe to call as often as anyone likes.
560
+ */
561
+ export function planStartFresh(input: PlanInput): StartFreshPlan {
562
+ const date = dateOf(input.now);
563
+ const home = input.home ?? homedir();
564
+ const configPath = resolve(input.configPath);
565
+ const empty = {
566
+ shape: "nothing-to-park" as StartFreshShape,
567
+ configPath,
568
+ configPresent: input.configPresent,
569
+ date,
570
+ parks: [] as ParkStep[],
571
+ alreadyParked: [] as string[],
572
+ snapshotsDir: null,
573
+ snapshotsElsewhere: null,
574
+ snapshotsLeft: null,
575
+ strayTempStores: [] as string[],
576
+ storeEntries: 0,
577
+ preRowsMarkers: [] as string[],
578
+ liveness: { signs: [], recent: [], unreadable: false } as Liveness,
579
+ };
580
+
581
+ // A CONFIGURATION THAT IS THERE AND NAMES NO STORE IS A REFUSAL, not a guess.
582
+ // The hooks fall back to `COUNTERPARTS_DATA_DIR` when the file names no store
583
+ // (`claude-code/bin/hook.ts`), so "the store the hooks open" is a fact about
584
+ // somebody's shell rather than about this file — and guessing `<base>/store`
585
+ // would park a directory nobody pointed at.
586
+ if (input.configPresent && (input.dataDir === undefined || input.dataDir.trim().length === 0)) {
587
+ return {
588
+ ...empty,
589
+ storeDir: "",
590
+ refusal:
591
+ `refused: ${configPath} names no "dataDir", so there is no way to know which store your ` +
592
+ "hooks open — with that key absent they fall back to $COUNTERPARTS_DATA_DIR, which is a " +
593
+ 'fact about a shell rather than about this file. Add "dataDir": "<absolute path>" to the ' +
594
+ "configuration first (that is what `counterparts install` writes), then run this again.",
595
+ };
596
+ }
597
+
598
+ // A `dataDir` THAT IS NOT ABSOLUTE IS REFUSED BY NAME (review M5).
599
+ //
600
+ // `resolve()` is relative to the PROCESS WORKING DIRECTORY and does not expand
601
+ // `~`, and `loadConfig` accepts any string — so `"relative-store"` renamed an
602
+ // unrelated directory that happened to sit in the shell's cwd and reported
603
+ // success, and `"~/.counterparts/store"` created a literal `~` directory and
604
+ // left the real store untouched and unmentioned. Both were measured. A path
605
+ // that means a different directory in every process that reads it is not a
606
+ // path this command will act on.
607
+ const written = input.dataDir === undefined ? "" : input.dataDir.trim();
608
+ const storeDir = written.length > 0 && isAbsolute(written) ? resolve(written) : "";
609
+
610
+ // No configuration at all: a machine that has never had an install. Nothing
611
+ // is parked, and the command is an ordinary first `install` that says so.
612
+ if (!input.configPresent) {
613
+ return { ...empty, storeDir, refusal: null };
614
+ }
615
+
616
+ // THE SHARED RING (`pathGuard`), so this direction and `--undo` cannot drift.
617
+ const refusal = pathGuard("store", written, configPath, home, `${configPath}'s "dataDir"`);
618
+ if (refusal !== null) {
619
+ return { ...empty, storeDir, shape: "park", refusal };
620
+ }
621
+
622
+ const store = sight(storeDir);
623
+ // WHERE THE SNAPSHOTS ARE IS THE SNAPSHOT MODULE'S QUESTION, asked in its own
624
+ // words rather than by rebuilding the rule here: the default is a sibling of
625
+ // the store, and a configured `snapshots.dir` is a directory the OWNER pointed
626
+ // at, which this command leaves alone and says so.
627
+ const beside = join(dirname(storeDir), "snapshots");
628
+ const configured = input.snapshotsConfigured;
629
+ const snapshotsElsewhere =
630
+ configured !== undefined && configured.trim().length > 0 && resolve(configured) !== beside
631
+ ? resolve(configured)
632
+ : null;
633
+ const snapshotsDir =
634
+ snapshotsElsewhere === null && basename(storeDir) === "store" ? beside : null;
635
+
636
+ const taken = input.taken ?? existsSync;
637
+
638
+ if (!store.present || store.entries === 0) {
639
+ // Nothing to park. Two readings, and the difference matters to the reader:
640
+ // a store that was never there, and one a previous run already moved.
641
+ const parked = siblingsParked(storeDir, taken);
642
+ return {
643
+ ...empty,
644
+ storeDir,
645
+ snapshotsDir,
646
+ snapshotsElsewhere,
647
+ shape: parked.length > 0 && !store.present ? "resume" : "nothing-to-park",
648
+ alreadyParked: parked,
649
+ storeEntries: store.entries,
650
+ refusal: null,
651
+ };
652
+ }
653
+
654
+ // WHY THE SNAPSHOTS FOLDER IS NEVER A REASON TO REFUSE THE WHOLE COMMAND
655
+ // (review m2). It used to be: a symlinked `~/.counterparts/snapshots` — an
656
+ // external disk, an ordinary arrangement — refused everything, and the only
657
+ // way through was editing the configuration. A snapshots folder this command
658
+ // will not move is now treated exactly as a `snapshots.dir` pointed elsewhere
659
+ // is: LEFT, and said out loud. The memory still moves, which is what the
660
+ // owner came for; the copies stay where they are, which costs nothing but a
661
+ // sentence.
662
+ const snapshotsSeen = snapshotsDir === null ? null : sight(snapshotsDir);
663
+ let snapshotsLeft: string | null = null;
664
+ let parkSnapshots = false;
665
+ if (snapshotsDir !== null && snapshotsSeen !== null && snapshotsSeen.present) {
666
+ const why = parkRefusal("snapshots directory", snapshotsDir, configPath, home);
667
+ if (why !== null) {
668
+ snapshotsLeft = why;
669
+ } else {
670
+ // BOTH devices, before anything moves (review SHOULD 3). Only the store's
671
+ // was compared, so a snapshots folder on another filesystem would have
672
+ // failed its rename mid-run rather than refusing up front — and the store
673
+ // is parked first only in the order, not in the decision.
674
+ const cross = sameFilesystemRefusal(snapshotsDir);
675
+ if (cross !== null) snapshotsLeft = cross;
676
+ else parkSnapshots = true;
677
+ }
678
+ }
679
+
680
+ const crossDevice = sameFilesystemRefusal(storeDir);
681
+ if (crossDevice !== null) {
682
+ return {
683
+ ...empty,
684
+ storeDir,
685
+ snapshotsDir,
686
+ snapshotsElsewhere,
687
+ snapshotsLeft,
688
+ shape: "park",
689
+ refusal: crossDevice,
690
+ };
691
+ }
692
+
693
+ // ONE SUFFIX FOR BOTH (review n3). The two used to pick `-N` independently,
694
+ // so a second run the same day could leave `store.parked-D-2` beside
695
+ // `snapshots.parked-D` — a pair that does not read as a pair. The suffix is
696
+ // chosen once, against BOTH names, so they always match.
697
+ const suffix = pairedSuffix(
698
+ [storeDir, ...(parkSnapshots && snapshotsDir !== null ? [snapshotsDir] : [])],
699
+ date,
700
+ taken,
701
+ );
702
+ const parks: ParkStep[] = [];
703
+ // SNAPSHOTS FIRST. A kill between the two renames then leaves the
704
+ // configuration pointing at a store that is still there — the harmless order.
705
+ if (parkSnapshots && snapshotsDir !== null) {
706
+ parks.push({ label: "snapshots", from: snapshotsDir, to: `${snapshotsDir}${suffix}` });
707
+ }
708
+ parks.push({ label: "store", from: storeDir, to: `${storeDir}${suffix}` });
709
+
710
+ return {
711
+ shape: "park",
712
+ configPath,
713
+ configPresent: input.configPresent,
714
+ storeDir,
715
+ date,
716
+ parks,
717
+ alreadyParked: [],
718
+ snapshotsDir,
719
+ snapshotsElsewhere,
720
+ snapshotsLeft,
721
+ strayTempStores: strayTempStoresBeside(storeDir),
722
+ storeEntries: store.entries,
723
+ // Names only. Never an open — that is the whole point of the refusal this
724
+ // reading is about.
725
+ preRowsMarkers: preRowsMarkersIn(storeDir),
726
+ liveness: readLiveness(storeDir, input.now),
727
+ refusal: null,
728
+ };
729
+ }
730
+
731
+ /**
732
+ * Why this rename cannot be atomic, or null.
733
+ *
734
+ * `rename(2)` is atomic within one filesystem and fails with `EXDEV` across
735
+ * two. A store that is itself a mount point — an external disk, a network
736
+ * volume, a container bind — is exactly that case, and the alternative
737
+ * (copy-then-delete) is the one thing this command may never do. So it is
738
+ * measured BEFORE anything moves, by comparing device numbers, and refused with
739
+ * the reason rather than discovered halfway through.
740
+ */
741
+ export function sameFilesystemRefusal(storeDir: string): string | null {
742
+ let here: number;
743
+ let parent: number;
744
+ try {
745
+ here = statSync(storeDir).dev;
746
+ parent = statSync(dirname(storeDir)).dev;
747
+ } catch (err) {
748
+ return `refused: could not read ${storeDir} or its parent (${String((err as Error).message ?? err)}).`;
749
+ }
750
+ if (here === parent) return null;
751
+ return (
752
+ `refused: ${storeDir} is on a different filesystem from ${dirname(storeDir)}, so moving it ` +
753
+ "beside itself would be a COPY followed by a DELETE rather than one atomic rename — and this " +
754
+ "command does not delete, ever. Move the store by hand with a tool you trust, verify the copy, " +
755
+ `and point "dataDir" at whatever you want the new store to be.`
756
+ );
757
+ }
758
+
759
+ /**
760
+ * The ONE suffix both parked directories wear — `.parked-<date>`, with `-2`,
761
+ * `-3` … when any of the names it would produce is taken.
762
+ *
763
+ * Asked of every path at once rather than of each in turn, so the store and its
764
+ * snapshots always land on matching names (review n3).
765
+ */
766
+ export function pairedSuffix(
767
+ paths: readonly string[],
768
+ date: string,
769
+ taken: (candidate: string) => boolean = existsSync,
770
+ ): string {
771
+ const free = (suffix: string): boolean => paths.every((p) => !taken(`${resolve(p)}${suffix}`));
772
+ const base = `.${PARKED_INFIX}-${date}`;
773
+ if (free(base)) return base;
774
+ for (let n = 2; n < 1000; n += 1) {
775
+ if (free(`${base}-${String(n)}`)) return `${base}-${String(n)}`;
776
+ }
777
+ throw new Error(`no free parked suffix for ${date}`);
778
+ }
779
+
780
+ /** `store.new-*` siblings — what an interrupted run leaves. REPORTED only:
781
+ * `freeTempStore` never returns a name that exists, so one of these can never
782
+ * become somebody's store, and nothing here removes it. */
783
+ export function strayTempStoresBeside(storeDir: string): string[] {
784
+ const out: string[] = [];
785
+ try {
786
+ const prefix = `${basename(storeDir)}.new-`;
787
+ for (const entry of readdirSync(dirname(storeDir))) {
788
+ if (entry.startsWith(prefix)) out.push(join(dirname(storeDir), entry));
789
+ }
790
+ } catch {
791
+ return out;
792
+ }
793
+ return out.sort();
794
+ }
795
+
796
+ /** Parked siblings of a store path, newest name last. Used only to REPORT. */
797
+ function siblingsParked(storeDir: string, taken: (c: string) => boolean): string[] {
798
+ const out: string[] = [];
799
+ try {
800
+ const prefix = `${basename(storeDir)}.${PARKED_INFIX}-`;
801
+ for (const entry of readdirSync(dirname(storeDir))) {
802
+ if (entry.startsWith(prefix)) out.push(join(dirname(storeDir), entry));
803
+ }
804
+ } catch {
805
+ return out;
806
+ }
807
+ return out.filter((p) => taken(p)).sort();
808
+ }
809
+
810
+ // ── doing it ────────────────────────────────────────────────────────────────
811
+
812
+ /**
813
+ * The filesystem, injected — ONE call, so a test can fail step N deterministically
814
+ * and then prove that what is on disk is either the before or the after and never
815
+ * a third thing.
816
+ */
817
+ export interface StartFreshOps {
818
+ readonly rename: (from: string, to: string) => void;
819
+ }
820
+
821
+ export const REAL_OPS: StartFreshOps = {
822
+ rename: (from, to) => {
823
+ renameSync(from, to);
824
+ },
825
+ };
826
+
827
+ export interface ParkOutcome {
828
+ readonly done: readonly ParkStep[];
829
+ /** The step that failed, when one did. */
830
+ readonly failed: ParkStep | null;
831
+ readonly error: string | null;
832
+ }
833
+
834
+ /**
835
+ * Perform the renames, in order, stopping at the first failure.
836
+ *
837
+ * It does exactly as many `rename` calls as there are steps and nothing else:
838
+ * no mkdir, no chmod, no cleanup, no attempt to undo a rename that worked. An
839
+ * "undo" here would be a second rename of a directory whose state nobody has
840
+ * re-read, which is how a recovery path destroys what the failure left intact.
841
+ * The caller prints what was done and what was not, and the rollback lines it
842
+ * printed before starting are still correct.
843
+ */
844
+ export function park(steps: readonly ParkStep[], ops: StartFreshOps = REAL_OPS): ParkOutcome {
845
+ const done: ParkStep[] = [];
846
+ for (const step of steps) {
847
+ try {
848
+ ops.rename(step.from, step.to);
849
+ done.push(step);
850
+ } catch (err) {
851
+ const code =
852
+ err !== null && typeof err === "object" && typeof (err as { code?: unknown }).code === "string"
853
+ ? `${(err as { code: string }).code}: `
854
+ : "";
855
+ return { done, failed: step, error: `${code}${String((err as Error).message ?? err)}` };
856
+ }
857
+ }
858
+ return { done, failed: null, error: null };
859
+ }
860
+
861
+ // ── what the owner reads ────────────────────────────────────────────────────
862
+
863
+ /** The plan, in the order it will happen. One line per rename, paths in full. */
864
+ export function planLines(plan: StartFreshPlan, landing?: string): string[] {
865
+ const out: string[] = [];
866
+ out.push(`Configuration: ${plan.configPath}${plan.configPresent ? "" : " (not there yet)"}`);
867
+ // THE STORE LINE IS NEVER BLANK (review B1). It used to be, on the arm where
868
+ // there was no configuration — and directly below it the install printed
869
+ // "Store already present at …/store", naming the live store. Two sentences on
870
+ // one screen contradicting each other, with the second one the true one.
871
+ out.push(`Store: ${plan.storeDir.length > 0 ? plan.storeDir : (landing ?? "(unknown)")}`);
872
+ out.push("");
873
+ if (plan.shape === "nothing-to-park") {
874
+ out.push(
875
+ plan.configPresent
876
+ ? "Nothing to park: the store your configuration names is not there, or is empty."
877
+ : "There is no configuration at that path, so there is nothing to park and nothing",
878
+ );
879
+ if (!plan.configPresent) {
880
+ out.push("this command can call your memory. It will do an ordinary first install at the");
881
+ out.push("store path above — and refuse if anything at all is already there.");
882
+ } else {
883
+ out.push("So this is an ordinary first install, and it says so rather than pretending");
884
+ out.push("it moved something.");
885
+ }
886
+ return out;
887
+ }
888
+ if (plan.shape === "resume") {
889
+ out.push("A previous run was interrupted: the store directory is gone and these are");
890
+ out.push("parked beside it —");
891
+ for (const p of plan.alreadyParked) out.push(` ${p}`);
892
+ out.push("");
893
+ out.push("Nothing will be moved. This run only creates the blank store at the path");
894
+ out.push("your configuration names, which is what that run had left to do.");
895
+ return out;
896
+ }
897
+ out.push("It will rename, in this order — one atomic rename each, nothing copied,");
898
+ out.push("nothing deleted, and the old store is never opened:");
899
+ for (const step of plan.parks) {
900
+ out.push(` ${step.from}`);
901
+ out.push(` -> ${step.to}`);
902
+ }
903
+ out.push("");
904
+ out.push("Then it will create a blank store at:");
905
+ out.push(` ${plan.storeDir}`);
906
+ if (plan.strayTempStores.length > 0) {
907
+ out.push("");
908
+ out.push(" Beside your store are part-built stores from interrupted runs:");
909
+ for (const stray of plan.strayTempStores) out.push(` ${stray}`);
910
+ out.push(" Nothing reads them, nothing here will use one, and nothing here will remove");
911
+ out.push(" one. Move them aside whenever you like.");
912
+ }
913
+ if (plan.preRowsMarkers.length > 0) {
914
+ out.push("");
915
+ out.push(" This store is on the OLD FLOOR — it keeps its memories in files");
916
+ out.push(` (${plan.preRowsMarkers.join(", ")}).`);
917
+ out.push(" This build cannot open it and refuses to try, by name, which is exactly why");
918
+ out.push(" moving it is the right thing to do with it: a rename does not care what floor");
919
+ out.push(` a directory is on. The build that still reads it is tagged ${PRE_ROWS_READABLE_BY}.`);
920
+ }
921
+ if (plan.snapshotsElsewhere !== null) {
922
+ out.push("");
923
+ out.push(` Snapshots are configured at ${plan.snapshotsElsewhere}, which is a directory`);
924
+ out.push(" you pointed at rather than one this layout owns, so it is LEFT ALONE — and so");
925
+ out.push(" is any `mirror`. The new store's rotation will share that folder with what is");
926
+ out.push(" already in it: copies of an OLD-FLOOR store are recognised there and never");
927
+ out.push(" deleted or counted, but copies this floor wrote do count toward `keep`, so the");
928
+ out.push(" new store's oldest could rotate out sooner than you expect.");
929
+ } else if (plan.snapshotsLeft !== null) {
930
+ out.push("");
931
+ out.push(` The snapshots folder at ${plan.snapshotsDir ?? ""} is LEFT WHERE IT IS.`);
932
+ out.push(` ${plan.snapshotsLeft}`);
933
+ out.push(" That is a reason not to MOVE it, not a reason to stop: your memory still");
934
+ out.push(" moves, and the copies stay exactly where they are. The new store's rotation");
935
+ out.push(" will share that folder with what is already in it.");
936
+ } else if (plan.snapshotsDir === null) {
937
+ out.push("");
938
+ out.push(" No snapshots directory belongs to this layout (the store is not named");
939
+ out.push(" 'store' under a base directory), so there is none to park.");
940
+ }
941
+ return out;
942
+ }
943
+
944
+ /** The configuration's side of it — today, always "nothing changes". */
945
+ export function configLines(plan: StartFreshPlan): string[] {
946
+ if (!plan.configPresent) {
947
+ return [
948
+ ` ${plan.configPath}: will be CREATED by the install below.`,
949
+ ];
950
+ }
951
+ return [
952
+ ` ${plan.configPath}: unchanged — "dataDir" already names ${plan.storeDir},`,
953
+ " and the blank store is created at that same path. Nothing in the file is",
954
+ " rewritten, so your credentials file, your ceiling and every other value",
955
+ " stay exactly as they are, byte for byte.",
956
+ ];
957
+ }
958
+
959
+ /**
960
+ * THE WAY BACK, AS SHELL LINES — and every one of them GUARDED, because plain
961
+ * `mv` does the worst possible thing here.
962
+ *
963
+ * Measured on macOS (review M3): `mv src dst` where `dst` is an existing
964
+ * DIRECTORY does not refuse and does not overwrite — it moves `src` INSIDE
965
+ * `dst`, exit 0. `mv -n` behaves identically. On the real layout that put the
966
+ * owner's parked memory at `store/store.parked-<date>`, and the live store then
967
+ * stopped opening at all (`LAYOUT_UNCLASSIFIED`). Nothing was lost, and nothing
968
+ * about that is obvious at 11pm.
969
+ *
970
+ * So each line tests its destination first and says what it is refusing.
971
+ * Everything is double-quoted, so a path with a space in it survives the
972
+ * copy-paste this text exists to be.
973
+ *
974
+ * `counterparts start-fresh --undo` does the same thing with the same
975
+ * discipline and without the shell; these lines are the by-hand fallback, and
976
+ * they are printed because a way back that depends on the program that just
977
+ * moved your memory is not much of a way back.
978
+ */
979
+ export function rollbackLines(
980
+ plan: StartFreshPlan,
981
+ taken: (candidate: string) => boolean = existsSync,
982
+ opts: { readonly parkTheBlankStore?: boolean } = {},
983
+ ): string[] {
984
+ if (plan.parks.length === 0) return [];
985
+ const out: string[] = [];
986
+ // LINE 1 IS ONLY TRUE ONCE A BLANK STORE IS THERE (confirmation review
987
+ // NIT-3). The install now runs BEFORE the parks, so a run interrupted during
988
+ // it leaves the MEMORY at the store path — and line 1 would park it under a
989
+ // name that says it is the empty one. Before anything moves, that line is
990
+ // conditional and says so; afterwards, `printWayBack` emits it only when the
991
+ // store actually moved.
992
+ if (opts.parkTheBlankStore !== false) {
993
+ out.push(guardedMove(plan.storeDir, parkedPath(plan.storeDir, BLANK_INFIX, plan.date, taken)));
994
+ }
995
+ for (const step of [...plan.parks].reverse()) out.push(guardedMove(step.to, step.from));
996
+ return out;
997
+ }
998
+
999
+ /** One `mv` that refuses instead of nesting. Exported so the test can parse the
1000
+ * printed line back out of real output and run it against a destination that
1001
+ * exists — which is the only way to prove the guard rather than the intent. */
1002
+ export function guardedMove(from: string, to: string): string {
1003
+ // The destination appears twice — once as an argument, once INSIDE the
1004
+ // message — so it is escaped twice over in different ways: `shell()` wraps it
1005
+ // in its own quotes, and `inner()` only escapes, because a second pair of
1006
+ // quotes inside an already-quoted string is how a path with a space in it
1007
+ // comes out mangled in the one sentence that has to be readable.
1008
+ // `if/then/else`, not `[ -e … ] && echo … || mv …`. Two reasons, and the
1009
+ // second is the sharp one. It exits NON-ZERO on a refusal, so a pasted block
1010
+ // stops at a `set -e` and a reader's `&&` chain does not sail past it
1011
+ // (confirmation review NIT-2). And the `&&/||` form has a trap of its own:
1012
+ // if the `echo` ever failed, the `||` would run the `mv` — the one thing the
1013
+ // guard exists to prevent.
1014
+ return (
1015
+ ` if [ -e ${shell(to)} ]; then echo "REFUSING: ${inner(to)} already exists — ` +
1016
+ `mv would put the source INSIDE it" >&2; false; else mv ${shell(from)} ${shell(to)}; fi`
1017
+ );
1018
+ }
1019
+
1020
+ /** Escaped for use INSIDE an already-quoted shell string; adds no quotes. */
1021
+ function inner(path: string): string {
1022
+ return path.replace(/(["\\$`])/g, "\\$1");
1023
+ }
1024
+
1025
+ /** Always double-quoted: these lines are printed to be pasted, and a path with
1026
+ * a space in it is not a reason for the way back to break. */
1027
+ function shell(path: string): string {
1028
+ return `"${path.replace(/(["\\$`])/g, "\\$1")}"`;
1029
+ }
1030
+
1031
+ // ── the way back, as a command ──────────────────────────────────────────────
1032
+
1033
+ export interface UndoStep {
1034
+ readonly label: string;
1035
+ readonly from: string;
1036
+ readonly to: string;
1037
+ }
1038
+
1039
+ export interface UndoPlan {
1040
+ readonly storeDir: string;
1041
+ /** The parked store this would put back. */
1042
+ readonly parked: string | null;
1043
+ /** A parked snapshots folder this will NOT move, because one is already back
1044
+ * at the live name. Left, and said — never merged. */
1045
+ readonly snapshotsLeft?: string | null;
1046
+ /** Every parked sibling found, for the report when there is more than one. */
1047
+ readonly candidates: readonly string[];
1048
+ readonly steps: readonly UndoStep[];
1049
+ /** True when the store being restored was written before this build's floor —
1050
+ * on cut-over day, undoing also means re-detaching the checkout. */
1051
+ readonly preRows: boolean;
1052
+ readonly refusal: string | null;
1053
+ }
1054
+
1055
+ /**
1056
+ * The reverse of a run: park the blank store, put the parked one back, put the
1057
+ * snapshots back. Same discipline as the forward direction — one `rename` each,
1058
+ * nothing deleted, nothing opened, and a destination that already exists is a
1059
+ * REFUSAL rather than a merge.
1060
+ *
1061
+ * `parked` is normally read from the new store's own `store.previous.parked`
1062
+ * record, which names the directory THIS run parked. When that cannot be had —
1063
+ * an unopenable store, a record a kill never wrote — the caller passes null and
1064
+ * this falls back to the siblings on disk, refusing when there is more than one
1065
+ * rather than guessing (review M4: guessing picked an empty shell).
1066
+ */
1067
+ export function planUndo(input: {
1068
+ /** `dataDir` EXACTLY as the configuration holds it — the guard needs the
1069
+ * written spelling, not a resolved one. */
1070
+ readonly storeDir: string;
1071
+ readonly parked: string | null;
1072
+ readonly configPath: string;
1073
+ readonly now: number;
1074
+ readonly home?: string;
1075
+ readonly taken?: (candidate: string) => boolean;
1076
+ }): UndoPlan {
1077
+ const taken = input.taken ?? existsSync;
1078
+ const home = input.home ?? homedir();
1079
+ const configPath = resolve(input.configPath);
1080
+ const storeDir = isAbsolute(input.storeDir.trim())
1081
+ ? resolve(input.storeDir.trim())
1082
+ : input.storeDir.trim();
1083
+ const date = dateOf(input.now);
1084
+ const candidates = isAbsolute(storeDir) ? siblingsParked(storeDir, taken) : [];
1085
+ const empty = {
1086
+ storeDir,
1087
+ parked: null,
1088
+ candidates,
1089
+ steps: [],
1090
+ snapshotsLeft: null,
1091
+ preRows: false,
1092
+ };
1093
+
1094
+ // ── THE SAME RING THE FORWARD DIRECTION RUNS (confirmation review BLOCKER-1)
1095
+ //
1096
+ // This is the whole finding. `--undo` used to go from `resolve(dataDir)`
1097
+ // straight to `existsSync` and `renameSync`, so a configuration the forward
1098
+ // command refuses BY NAME one command earlier — `dataDir` inside `~/.bansai` —
1099
+ // was renamed twice by the command whose job is being the safe way back.
1100
+ const storeRefusal = pathGuard(
1101
+ "store",
1102
+ input.storeDir,
1103
+ configPath,
1104
+ home,
1105
+ `${configPath}'s "dataDir"`,
1106
+ );
1107
+ if (storeRefusal !== null) return { ...empty, refusal: storeRefusal };
1108
+
1109
+ let parked = input.parked === null ? null : resolve(input.parked);
1110
+ if (parked === null) {
1111
+ if (candidates.length === 0) {
1112
+ return {
1113
+ ...empty,
1114
+ refusal:
1115
+ `refused: nothing beside ${storeDir} is a parked store, and the store that is there ` +
1116
+ "carries no record of one. There is nothing to undo.",
1117
+ };
1118
+ }
1119
+ if (candidates.length > 1) {
1120
+ return {
1121
+ ...empty,
1122
+ refusal:
1123
+ `refused: ${String(candidates.length)} parked stores sit beside ${storeDir} and the ` +
1124
+ "store that is there does not say which one it replaced, so this will not guess — " +
1125
+ "guessing is how an empty shell gets named as somebody's memory. They are:\n" +
1126
+ candidates.map((c) => ` ${c}`).join("\n") +
1127
+ "\n Move the one you want back by hand; the printed lines from the run that made " +
1128
+ "it are the exact way, and each is guarded.",
1129
+ };
1130
+ }
1131
+ parked = candidates[0] ?? null;
1132
+ }
1133
+ if (parked === null || !taken(parked)) {
1134
+ return { ...empty, refusal: `refused: ${String(parked)} is not there.` };
1135
+ }
1136
+
1137
+ // THE RECORDED PATH GOES THROUGH THE RING TOO, and then through the shape
1138
+ // rule — a row in a database may name anything at all.
1139
+ const parkedRefusal =
1140
+ pathGuard("parked store", parked, configPath, home, "the record in this store") ??
1141
+ parkedSiblingRefusal("parked store", parked, dirname(storeDir), basename(storeDir));
1142
+ if (parkedRefusal !== null) return { ...empty, refusal: parkedRefusal };
1143
+
1144
+ const steps: UndoStep[] = [];
1145
+ const store = sight(storeDir);
1146
+ if (store.present) {
1147
+ // THE BLANK STORE IS PARKED, NEVER REMOVED — the same rule as everything
1148
+ // else here. An undo that deleted would be the one delete in the command.
1149
+ steps.push({
1150
+ label: "the store that is there now",
1151
+ from: storeDir,
1152
+ to: parkedPath(storeDir, BLANK_INFIX, date, taken),
1153
+ });
1154
+ }
1155
+ steps.push({ label: "your parked memory", from: parked, to: storeDir });
1156
+
1157
+ // The snapshots that went with it, by the suffix the store wears.
1158
+ const suffix = basename(parked).slice(basename(storeDir).length);
1159
+ const snapshots = join(dirname(storeDir), "snapshots");
1160
+ const parkedSnapshots = `${snapshots}${suffix}`;
1161
+ let snapshotsLeft: string | null = null;
1162
+ // The snapshots folder is derived from the store's own suffix rather than
1163
+ // recorded, so it cannot be steered — but it is a rename, so it goes through
1164
+ // the same two checks anyway. A refusal here LEAVES it (m2's lesson) rather
1165
+ // than stopping the store from coming back.
1166
+ const snapshotsRefusal =
1167
+ pathGuard("parked snapshots", parkedSnapshots, configPath, home, "this store's layout") ??
1168
+ parkedSiblingRefusal("parked snapshots", parkedSnapshots, dirname(storeDir), "snapshots");
1169
+ if (taken(parkedSnapshots) && snapshotsRefusal !== null) {
1170
+ snapshotsLeft = parkedSnapshots;
1171
+ } else if (taken(parkedSnapshots)) {
1172
+ if (taken(snapshots)) {
1173
+ // Something put a snapshots folder back while the blank store was live —
1174
+ // the rotation does, at the first boundary. Moving the parked one onto it
1175
+ // would be the merge this command refuses everywhere else, and refusing
1176
+ // the WHOLE undo over a folder of copies would be m2's mistake again. It
1177
+ // is left, and said.
1178
+ snapshotsLeft = parkedSnapshots;
1179
+ } else {
1180
+ steps.push({ label: "its snapshots", from: parkedSnapshots, to: snapshots });
1181
+ }
1182
+ }
1183
+
1184
+ return {
1185
+ storeDir,
1186
+ parked,
1187
+ candidates,
1188
+ steps,
1189
+ snapshotsLeft,
1190
+ // Filenames only. Nothing is opened, here least of all.
1191
+ preRows: preRowsMarkersIn(parked).length > 0,
1192
+ refusal: null,
1193
+ };
1194
+ }
1195
+
1196
+ /** What `--undo` prints before it moves anything. */
1197
+ export function undoLines(plan: UndoPlan): string[] {
1198
+ const out = [`Store: ${plan.storeDir}`, `Parked: ${plan.parked ?? "(none found)"}`, ""];
1199
+ if (plan.steps.length === 0) return out;
1200
+ out.push("It will rename, in this order — one atomic rename each, nothing copied,");
1201
+ out.push("nothing deleted, and nothing opened:");
1202
+ for (const step of plan.steps) {
1203
+ out.push(` ${step.label}`);
1204
+ out.push(` ${step.from}`);
1205
+ out.push(` -> ${step.to}`);
1206
+ }
1207
+ if (plan.snapshotsLeft !== undefined && plan.snapshotsLeft !== null) {
1208
+ out.push("");
1209
+ out.push(` ${plan.snapshotsLeft} is LEFT WHERE IT IS: a snapshots`);
1210
+ out.push(" folder is already back at the live name, and moving one onto the other is");
1211
+ out.push(" the merge this refuses everywhere else. Your copies are in both.");
1212
+ }
1213
+ if (plan.preRows) {
1214
+ out.push("");
1215
+ out.push(" THE STORE COMING BACK IS ON THE OLD FLOOR. This build cannot open it, so");
1216
+ out.push(" putting it back is only half the undo: the checkout has to go back too —");
1217
+ out.push(` tools/deploy-checkout.sh --repo <your checkout> --ref ${PRE_ROWS_READABLE_BY}`);
1218
+ out.push(" and then restart Claude Code. Until that happens every session will stand");
1219
+ out.push(" down against this store, loudly and harmlessly.");
1220
+ }
1221
+ return out;
1222
+ }
1223
+
1224
+ /** What the confirmation asks to be typed back: the parked store's own name. */
1225
+ export function confirmationWord(plan: StartFreshPlan): string {
1226
+ const store = plan.parks.find((p) => p.label === "store");
1227
+ return store === undefined ? "" : basename(store.to);
1228
+ }