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,1069 @@
1
+ /**
2
+ * The daily rotating snapshot — and the only mechanism in this package that
3
+ * DELETES a copy of the owner's memory.
4
+ *
5
+ * **Why it is here and not in the core.** The store exports no delete of any
6
+ * kind (store CONTRACT §5 G2), and rotation is a delete. So the deciding — is
7
+ * today's copy already made, how many are kept, which ones go — lives in an
8
+ * adapter, where a person can read the whole rule in one file.
9
+ *
10
+ * **What it copies is not decided here.** It calls `cli/snapshot.ts#snapshot`
11
+ * unchanged, which copies exactly `Store.backupSet()`. That matters more than it
12
+ * looks: v1 hand-maintained a second allowlist, it landed hours before the
13
+ * episode directory existed, and the canonical journal was silently absent from
14
+ * every backup for three weeks (scar §2.11). A database-only snapshot here would
15
+ * re-enact that on today's floor, where the prose files are canonical.
16
+ *
17
+ * **THE TWO THINGS THAT CAN HURT SOMEONE**, and the shape of each defence:
18
+ *
19
+ * 1. *Rotation deletes.* It deletes only directories sitting DIRECTLY inside
20
+ * the resolved snapshots directory whose names match the one pattern this
21
+ * module writes (`snapshotName`); it reads the directory with `Dirent`s, so
22
+ * a symlink is never followed out; it refuses the whole rotation if that
23
+ * directory resolves inside the store, contains the store, is a filesystem
24
+ * root or is the home directory itself; it never deletes the copy just
25
+ * taken; it never rotates at all after a copy that FAILED — losing the
26
+ * oldest good backup on the day you could not make a new one is the worst
27
+ * outcome available here; and a `keep` that is not a positive integer falls
28
+ * back to the default rather than meaning "delete everything".
29
+ *
30
+ * 2. *A half-copy must never count as a snapshot.* The worker runs under a
31
+ * watchdog and the copy is synchronous, so the process can be killed
32
+ * mid-copy with no chance to clean up. Every copy is therefore written to a
33
+ * `.partial-…` name inside the snapshots directory and RENAMED into place
34
+ * when it completes — one atomic step. An interrupted copy is not counted
35
+ * toward `keep`, does not satisfy "today's exists", is never a rotation
36
+ * candidate (its name does not match), and is swept up by a later run once
37
+ * it is old enough that no live run could still be writing it.
38
+ *
39
+ * **It never throws** (cli CONTRACT §5 G8, and the worker's degrade-don't-abort
40
+ * rule): a snapshot problem must not take a consolidation cycle down. Every
41
+ * failure is a field in the report and, where it is worth a durable record, a
42
+ * `snapshot.failed` row.
43
+ *
44
+ * **Which skips leave a row, and which do not.** A row at every session boundary
45
+ * is a flood, not a record, so: `already-today` writes nothing — today's
46
+ * `snapshot.taken` row IS the record; `attempts-exhausted` writes nothing — the
47
+ * `snapshot.failed` rows it counted are; `no-default-dir` writes nothing,
48
+ * because it is a configuration fact rather than an event and doctor says it in
49
+ * words. Everything that stopped a copy that should have happened — a refused
50
+ * directory, a failed copy, a failed rename, an aborted run — is a
51
+ * `snapshot.failed` row carrying its `reason` and the `step` it died at.
52
+ */
53
+ import { cpSync, readdirSync, realpathSync, renameSync, rmSync, statSync } from "node:fs";
54
+ import { homedir } from "node:os";
55
+ import { basename, dirname, join, parse, resolve } from "node:path";
56
+
57
+ import type { Counterpart } from "../core/counterpart.js";
58
+ import {
59
+ SNAPSHOT_FAILED_EVENT,
60
+ SNAPSHOT_ROTATED_EVENT,
61
+ SNAPSHOT_TAKEN_EVENT,
62
+ } from "../core/counterpart.js";
63
+ import {
64
+ DEFAULT_STORE_SUBDIR,
65
+ LAYOUT,
66
+ PRE_ROWS_MARKERS,
67
+ assertSafeDataDir,
68
+ dateOf,
69
+ isWithin,
70
+ } from "../core/store/index.js";
71
+ import { paths } from "../core/store/index.js";
72
+ import type { Store } from "../core/store/index.js";
73
+ import { openDb } from "../core/store/db.js";
74
+
75
+ import { assertSafeTarget, snapshot, snapshotName } from "./cli/snapshot.js";
76
+
77
+ /**
78
+ * The canonical database's FILE NAME, taken from the store's own path helper
79
+ * rather than typed here — F5 renames it to `counterparts.sqlite`, and a second
80
+ * spelling of it in this file would be a verification that quietly stopped
81
+ * verifying on the day the floor changed.
82
+ */
83
+ const DATABASE_NAME = basename(paths.operational("."));
84
+
85
+ /** The directory the copies live in, beside the store rather than inside it. */
86
+ export const SNAPSHOTS_DIR_NAME = "snapshots";
87
+
88
+ /** How many copies are kept. Owner's ruling, 2026-09-18. */
89
+ export const DEFAULT_KEEP = 14;
90
+
91
+ /**
92
+ * The prefix a copy wears while it is being written. It starts with a dot so it
93
+ * sorts and reads as "not one of the snapshots", and it can never collide with
94
+ * `snapshotName`, whose output starts with a digit.
95
+ */
96
+ export const PARTIAL_PREFIX = ".partial-";
97
+
98
+ /**
99
+ * And the whole shape of one, not just its prefix — `<prefix><instant>-<pid>`.
100
+ * The sweep deletes what matches this and nothing else, so a person's own
101
+ * `.partial-my-own-thing` in a directory they pointed `snapshots.dir` at is left
102
+ * alone (F2 review, MINOR-7).
103
+ */
104
+ export const PARTIAL_NAME_RE = /^\.partial-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d+$/;
105
+
106
+ /**
107
+ * How old an abandoned `.partial-…` directory must be before a later run removes
108
+ * it. Comfortably past the worker's watchdog (`claude-code/config.ts` TUNABLES,
109
+ * 5 minutes), because the one thing this must not do is delete the directory a
110
+ * CONCURRENT run is still writing into.
111
+ *
112
+ * It is fixed while `watchdogMs` is configurable, so a host that set a watchdog
113
+ * longer than this could in principle have a partial swept out from under a live
114
+ * copy. The direction is safe: that run's rename then fails, its `snapshot.failed`
115
+ * row says so, and — because a failed copy never rotates — nothing old is lost.
116
+ */
117
+ export const PARTIAL_STALE_MS = 30 * 60_000;
118
+
119
+ /**
120
+ * How many times a day a failing copy is retried. A copy of this store is tens
121
+ * of megabytes and thousands of files, the worker runs at every session
122
+ * boundary, and a persistent failure (a full disk, a permission) would otherwise
123
+ * pay that cost dozens of times between midnight and midnight. Three attempts is
124
+ * enough for a transient lock and cheap enough for a permanent one.
125
+ */
126
+ export const MAX_ATTEMPTS_PER_DAY = 3;
127
+
128
+ /**
129
+ * The name pattern rotation is allowed to delete — `snapshotName`'s output, and
130
+ * nothing else. It is written here rather than derived so that widening the
131
+ * DELETE side takes a deliberate edit to this line.
132
+ */
133
+ export const SNAPSHOT_NAME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z$/;
134
+
135
+ export interface SnapshotsConfig {
136
+ /** Where the copies go. Absent ⇒ beside the store; see `resolveSnapshotsDir`. */
137
+ readonly dir?: string;
138
+ readonly keep?: number;
139
+ /** A second location that receives the same copy, with its own rotation. */
140
+ readonly mirror?: string;
141
+ }
142
+
143
+ export type SnapshotReason =
144
+ | "taken"
145
+ | "observer"
146
+ | "already-today"
147
+ | "no-default-dir"
148
+ | "attempts-exhausted"
149
+ | "aborted"
150
+ | "refused"
151
+ | "failed";
152
+
153
+ export interface RotationReport {
154
+ /** The snapshot names that were deleted, oldest first. */
155
+ readonly deleted: readonly string[];
156
+ /** How many snapshots remain, including the one just taken. */
157
+ readonly kept: number;
158
+ /** The oldest snapshot still there, by name, or null when there are none. */
159
+ readonly oldest: string | null;
160
+ /** Abandoned `.partial-…` directories this pass removed. */
161
+ readonly cleaned: number;
162
+ /** Copies whose name is more than a day ahead of the clock — a clock-skewed
163
+ * boundary's, kept but counted, because they hold a `keep` slot forever. */
164
+ readonly future: number;
165
+ /** Correctly-named directories the layout rule does not recognise as copies.
166
+ * Never deleted, never counted toward `keep` — and never silent. */
167
+ readonly unrecognised: readonly string[];
168
+ /** Copies of a PRE-ROWS store — the owner's snapshots from before the floor.
169
+ * Never deleted, never counted toward `keep`, and named so they are not a
170
+ * mystery sitting in the one directory he relies on (review B, MAJOR-2). */
171
+ readonly preRows: readonly string[];
172
+ readonly errors: readonly string[];
173
+ }
174
+
175
+ export interface SnapshotRunReport {
176
+ readonly reason: SnapshotReason;
177
+ /** The resolved snapshots directory, or null when none could be resolved. */
178
+ readonly dir: string | null;
179
+ /** The name of the copy this run made, or null when it made none. */
180
+ readonly name: string | null;
181
+ readonly files: number;
182
+ readonly ms: number;
183
+ readonly rotation: RotationReport | null;
184
+ /** The mirror's own result, or null when no mirror is configured. */
185
+ readonly mirror: {
186
+ readonly ok: boolean;
187
+ readonly why: string;
188
+ /** The step a failed mirror died at, for its own durable row. Null when it
189
+ * worked. Never `copy`/`rename`/`verify` — the mirror must not spend the
190
+ * primary's daily attempt budget. */
191
+ readonly step: string | null;
192
+ readonly rotation: RotationReport | null;
193
+ } | null;
194
+ /** Everything that went wrong, in the order it went wrong. */
195
+ readonly errors: readonly string[];
196
+ }
197
+
198
+ const EMPTY_ROTATION: RotationReport = {
199
+ deleted: [],
200
+ kept: 0,
201
+ oldest: null,
202
+ cleaned: 0,
203
+ future: 0,
204
+ unrecognised: [],
205
+ preRows: [],
206
+ errors: [],
207
+ };
208
+
209
+ // ── where the copies go ─────────────────────────────────────────────────────
210
+
211
+ /**
212
+ * The snapshots directory for this store, and the rule that chose it.
213
+ *
214
+ * The default is a SIBLING of the store directory — `~/.counterparts/snapshots`
215
+ * for the owner — and that is deliberate on two counts: `assertSafeTarget`
216
+ * refuses a destination inside the store, and a destination inside would land an
217
+ * unclassified top-level path that `assertLayout()` then refuses at every open.
218
+ *
219
+ * **The default only applies inside the layout this package creates.** The base
220
+ * directory belongs to the host adapters and the store sits one level below it
221
+ * (`store/paths.ts` DEFAULT_STORE_SUBDIR, owner ruling 2026-09-04). A store
222
+ * somebody pointed at an arbitrary directory has no base directory, and helping
223
+ * ourselves to a sibling of it would write tens of megabytes into a directory
224
+ * this package does not own. That case resolves to null and doctor says so in
225
+ * words; `snapshots.dir` in the configuration names one explicitly.
226
+ *
227
+ * `dataDir` is the one this adapter was HANDED. Never `$HOME`, so a hermetic
228
+ * test cannot reach a real `~/.counterparts` however it is run.
229
+ */
230
+ export function resolveSnapshotsDir(
231
+ dataDir: string,
232
+ configured?: string,
233
+ ): { dir: string | null; reason: "configured" | "beside-the-store" | "no-default-dir" } {
234
+ if (configured !== undefined && configured.trim().length > 0) {
235
+ return { dir: resolve(configured), reason: "configured" };
236
+ }
237
+ const store = resolve(dataDir);
238
+ if (basename(store) !== DEFAULT_STORE_SUBDIR) {
239
+ return { dir: null, reason: "no-default-dir" };
240
+ }
241
+ return { dir: join(dirname(store), SNAPSHOTS_DIR_NAME), reason: "beside-the-store" };
242
+ }
243
+
244
+ /**
245
+ * THE GUARD ON THE DIRECTORY ROTATION IS ALLOWED TO DELETE INSIDE.
246
+ *
247
+ * Every refusal here is about the same mistake in a different costume: a
248
+ * configured path that turns out to name somewhere that matters. So both sides
249
+ * are resolved — and REALPATHED where the directory already exists, because
250
+ * `resolve` does not follow symlinks and a symlinked `snapshots` pointing at
251
+ * `$HOME` would pass a string comparison while rotation walked the home
252
+ * directory. A symlink to an external volume is a legitimate arrangement and
253
+ * still works; it is the TARGET that is judged.
254
+ *
255
+ * **THE LIVE-STORE REFUSAL RUNS ON THE REALPATH, AND IT USED TO RUN ON THE NAME**
256
+ * (found by the F2 adversarial review, 2026-09-18). `assertSafeDataDir` is pure
257
+ * string math — it resolves and compares against `~/.bansai` and
258
+ * `~/.claude-engram` and follows no links — so applying it before the realpath
259
+ * meant a `snapshots.dir` that was a SYMLINK into v1's live memory cleared the
260
+ * one guard this repository's first safety rule is about, and the directory was
261
+ * handed back as rotatable. The copy was refused further down, but `cleanPartials`
262
+ * runs before that and would have swept inside the forbidden tree. It is checked
263
+ * on BOTH spellings now: the path as written, and the path it actually reaches.
264
+ *
265
+ * `refuse` is that check, injectable for ONE reason — `os.homedir()` cannot be
266
+ * moved under bun, so the forbidden roots cannot be relocated into a temp tree,
267
+ * and the only honest way to prove the ORDER hermetically is to hand the guard a
268
+ * stand-in and assert which spelling it was called with. Production never passes
269
+ * it.
270
+ *
271
+ * Throws. Every caller in this file is inside a try.
272
+ */
273
+ export function assertRotatableDir(
274
+ storeDir: string,
275
+ dir: string,
276
+ refuse: (path: string) => string = assertSafeDataDir,
277
+ ): string {
278
+ // As WRITTEN first — a path literally under a forbidden root is refused by the
279
+ // name it was given, so the message names what the owner typed...
280
+ refuse(dir);
281
+ // ...and then as it RESOLVES, which is the spelling that decides where a
282
+ // delete would actually land.
283
+ const real = refuse(realpathDeep(dir));
284
+ const store = realpathDeep(storeDir);
285
+ // The two absolutes first, so each gets the refusal that names it. A
286
+ // filesystem root also CONTAINS the store, and the containment message would
287
+ // be true and useless.
288
+ if (real === parse(real).root) {
289
+ throw new Error(`refusing a filesystem root as a snapshots directory: ${real}`);
290
+ }
291
+ if (real === realpathDeep(homedir())) {
292
+ throw new Error(`refusing the home directory as a snapshots directory: ${real}`);
293
+ }
294
+ if (isWithin(store, real)) {
295
+ throw new Error(`refusing to keep snapshots inside the store they copy: ${real}`);
296
+ }
297
+ if (isWithin(real, store)) {
298
+ throw new Error(`refusing a snapshots directory that contains the store: ${real}`);
299
+ }
300
+ return real;
301
+ }
302
+
303
+ /**
304
+ * The real path of a directory that may not exist yet.
305
+ *
306
+ * `resolve` does not follow symlinks and `realpathSync` throws on a path that is
307
+ * not there — and BOTH cases are ordinary here: the snapshots directory does not
308
+ * exist before the first run, and on macOS the directory a test or a `$TMPDIR`
309
+ * names is very often a symlink. Comparing one side realpathed against the other
310
+ * side merely resolved is how a containment check says "no" to a path that is
311
+ * the same directory. So: realpath the deepest ancestor that DOES exist, and put
312
+ * the rest back on.
313
+ */
314
+ function realpathDeep(path: string): string {
315
+ const resolved = resolve(path);
316
+ let head = resolved;
317
+ const tail: string[] = [];
318
+ for (;;) {
319
+ try {
320
+ const real = realpathSync(head);
321
+ return tail.length === 0 ? real : join(real, ...tail);
322
+ } catch {
323
+ const parent = dirname(head);
324
+ // Nothing on this path exists. The resolved form is the whole answer.
325
+ if (parent === head) return resolved;
326
+ tail.unshift(basename(head));
327
+ head = parent;
328
+ }
329
+ }
330
+ }
331
+
332
+ // ── the run ─────────────────────────────────────────────────────────────────
333
+
334
+ export interface SnapshotRunInput {
335
+ /** The open counterpart. Its store is copied; its seam records the run. */
336
+ readonly counterpart: Counterpart;
337
+ readonly config?: SnapshotsConfig;
338
+ /** The data directory this adapter was handed. The default location hangs off
339
+ * it, never off `$HOME`. */
340
+ readonly dataDir: string;
341
+ /** Injected so a test pins the day and the name without touching the clock. */
342
+ readonly now?: number;
343
+ /** The calendar date this run is about, UTC. Defaults to `now`'s. */
344
+ readonly date?: string;
345
+ /** The worker's watchdog. Aborted ⇒ no copy is started. */
346
+ readonly signal?: AbortSignal;
347
+ }
348
+
349
+ /**
350
+ * One run: decide, copy, rotate, record. Never throws.
351
+ *
352
+ * ORDER IS THE DESIGN. The copy happens first and lands under a partial name;
353
+ * the rename is the moment it becomes a snapshot; rotation runs only after a
354
+ * copy that succeeded; and the `snapshot.taken` row is written LAST, after the
355
+ * copy — which means **a snapshot never contains its own record**. It appears in
356
+ * the next one. That is the honest arrangement: a row written before the copy
357
+ * would be a record of a copy that had not happened yet.
358
+ */
359
+ export function runSnapshot(input: SnapshotRunInput): SnapshotRunReport {
360
+ const started = Date.now();
361
+ const errors: string[] = [];
362
+ const now = input.now ?? started;
363
+ // THE RUN'S DATE IS THE FIRST HALF OF EVERY NAME THIS MODULE WRITES, so a
364
+ // caller that handed in something that is not a calendar date would build a
365
+ // name matching neither of the two load-bearing patterns: never recognised as
366
+ // a snapshot, so a full copy at every boundary; never rotated; and its partial
367
+ // never swept (second F2 review, MINOR-a). No caller can do that today — the
368
+ // worker derives the date from the clock — but a `--date` flag on the worker
369
+ // is one line away, and this project has them elsewhere.
370
+ const asked = input.date;
371
+ const date = asked !== undefined && /^\d{4}-\d{2}-\d{2}$/.test(asked) ? asked : dateOf(now);
372
+ if (asked !== undefined && asked !== date) {
373
+ errors.push(`"${asked}" is not a calendar date; this run is filed under ${date}`);
374
+ }
375
+ const counterpart = input.counterpart;
376
+ const store: Store = counterpart.store;
377
+
378
+ if (counterpart.observer) {
379
+ // An instrument that leaves a directory behind is the thing §15 G3 is about.
380
+ // The runner already refuses under observer before it opens a store, so
381
+ // nothing reaches this today — but `noteAdapterEvent` standing the ROW down
382
+ // while the copy still wrote tens of megabytes to disk was a stand-down in
383
+ // name only (F2 review, MINOR-6).
384
+ return done("observer", null, null, 0, null, null, errors, started);
385
+ }
386
+
387
+ const resolved = resolveSnapshotsDir(input.dataDir, input.config?.dir);
388
+ if (resolved.dir === null) {
389
+ // No row: a store outside this package's layout is a configuration fact, and
390
+ // one row per boundary for a thing that will never change is a flood.
391
+ // `doctor.ts#snapshotFindings` says it in words instead.
392
+ return done("no-default-dir", null, null, 0, null, null, errors, started);
393
+ }
394
+
395
+ let dir: string;
396
+ try {
397
+ dir = assertRotatableDir(store.dir, resolved.dir);
398
+ } catch (err) {
399
+ const why = messageOf(err);
400
+ errors.push(why);
401
+ // Deduped per calendar date: a refused directory refuses identically at
402
+ // every boundary, and the count belongs nowhere.
403
+ note(counterpart, SNAPSHOT_FAILED_EVENT, { date, step: "resolve", reason: why }, `${SNAPSHOT_FAILED_EVENT}:resolve:${date}`);
404
+ return done("refused", resolved.dir, null, 0, null, null, errors, started);
405
+ }
406
+
407
+ // Sweep up whatever a killed run left behind BEFORE anything else looks at the
408
+ // directory, so a stale partial cannot be mistaken for anything and the count
409
+ // of what was cleaned reaches the report even on a day that takes no copy.
410
+ const cleaned = cleanPartials(dir, now, errors);
411
+
412
+ if (todaysSnapshot(dir, date) !== null) {
413
+ return done("already-today", dir, null, 0, withCleaned(cleaned), null, errors, started);
414
+ }
415
+ const attempts = failedAttemptsToday(store, date);
416
+ if (attempts.saturated) {
417
+ // The read could not see today's rows, so the cap's answer is a guess. It
418
+ // guesses "exhausted" — the fail-closed direction — and SAYS SO durably,
419
+ // because `attempts-exhausted` writes no row of its own and a permanent
420
+ // silent stop is the failure this project keeps writing scars about.
421
+ note(
422
+ counterpart,
423
+ SNAPSHOT_FAILED_EVENT,
424
+ { date, step: "attempts", reason: "attempt-window-unreadable" },
425
+ `${SNAPSHOT_FAILED_EVENT}:attempts:${date}`,
426
+ );
427
+ errors.push("the failure window was too full to read; treating the day's attempts as spent");
428
+ return done("attempts-exhausted", dir, null, 0, withCleaned(cleaned), null, errors, started);
429
+ }
430
+ if (attempts.count >= MAX_ATTEMPTS_PER_DAY) {
431
+ return done("attempts-exhausted", dir, null, 0, withCleaned(cleaned), null, errors, started);
432
+ }
433
+ if (input.signal?.aborted === true) {
434
+ // The watchdog already fired. Starting a copy of the whole store here is
435
+ // exactly the copy most likely to be killed halfway. `step: "aborted"`, not
436
+ // `"copy"`: no copy was attempted, so this must not spend the day's budget
437
+ // (F2 review, MINOR-1 — three watchdog overruns cost the whole day's backup).
438
+ note(counterpart, SNAPSHOT_FAILED_EVENT, { date, step: "aborted", reason: "aborted" }, undefined);
439
+ errors.push("aborted before the copy started");
440
+ return done("aborted", dir, null, 0, withCleaned(cleaned), null, errors, started);
441
+ }
442
+
443
+ // THE NAME'S DAY IS THE ROW'S DAY, always. `snapshotName` spells an instant,
444
+ // and a run that starts at 23:59:59 and copies at 00:00:01 would otherwise
445
+ // file the copy under tomorrow while the row said today — so "today's exists"
446
+ // would never find it and yesterday would end with no copy at all (F2 review,
447
+ // N-2). The time of day is the real instant; only the date is pinned — so a
448
+ // copy taken at 00:00:05 on the 19th for a run about the 18th reads
449
+ // `2026-09-18T00-00-05-000Z`, which looks odd and is harmless: sorting is by
450
+ // date and there is at most one copy per date.
451
+ const name = `${date}T${snapshotName(now).slice(11)}`;
452
+ const copy = copyInto(store, dir, name, errors);
453
+ if (!copy.ok) {
454
+ note(counterpart, SNAPSHOT_FAILED_EVENT, { date, step: copy.step, reason: copy.why }, undefined);
455
+ // NO ROTATION after a failed copy. Deleting the oldest good backup on the
456
+ // day no new one could be made is the one outcome worth refusing outright.
457
+ return done("failed", dir, null, 0, withCleaned(cleaned), null, errors, started);
458
+ }
459
+
460
+ const rotation = rotate(dir, input.config?.keep, name, cleaned, errors, now);
461
+ const mirror = mirrorTo(store, dir, name, input.config?.mirror, input.config?.keep, now, errors);
462
+
463
+ note(
464
+ counterpart,
465
+ SNAPSHOT_TAKEN_EVENT,
466
+ {
467
+ date,
468
+ name,
469
+ files: copy.files,
470
+ ms: Date.now() - started,
471
+ kept: rotation.kept,
472
+ oldest: rotation.oldest,
473
+ deleted: rotation.deleted.length,
474
+ mirror: mirror === null ? "off" : mirror.ok ? "ok" : "failed",
475
+ // The mirror's reason rides on this row too: "failed" with no why is the
476
+ // half-record this project keeps finding in v1.
477
+ mirrorWhy: mirror === null || mirror.ok ? null : mirror.why,
478
+ // Named directories the layout rule does not recognise: kept, never
479
+ // rotated, and never silent about it.
480
+ unrecognised: rotation.unrecognised.length,
481
+ unrecognisedNames: rotation.unrecognised.length === 0 ? null : fewOf(rotation.unrecognised),
482
+ },
483
+ undefined,
484
+ );
485
+ // A MIRROR THAT FAILED GETS ITS OWN ROW. The `snapshot.taken` row carries
486
+ // `mirror: "failed"` and the reason, but the fired view reads failures by
487
+ // NAME, and a second copy that has been silently broken for a month is exactly
488
+ // the thing this track exists to make visible. Its `step` is never one the
489
+ // daily attempt cap counts: the primary landed, and the mirror must not spend
490
+ // tomorrow's budget for it.
491
+ if (mirror !== null && !mirror.ok) {
492
+ note(
493
+ counterpart,
494
+ SNAPSHOT_FAILED_EVENT,
495
+ { date, step: mirror.step ?? "mirror", reason: mirror.why },
496
+ `${SNAPSHOT_FAILED_EVENT}:mirror:${date}`,
497
+ );
498
+ }
499
+ // Only when something actually went (scar §2.4: every discard says what and
500
+ // how much). A daily row saying "nothing was deleted" would make a store that
501
+ // has not filled up yet read like a rotation that is working.
502
+ if (rotation.deleted.length > 0) {
503
+ note(
504
+ counterpart,
505
+ SNAPSHOT_ROTATED_EVENT,
506
+ {
507
+ date,
508
+ keep: keepOf(input.config?.keep),
509
+ deleted: rotation.deleted.length,
510
+ names: [...rotation.deleted],
511
+ // A clock-skewed name holds a `keep` slot forever, so it is on the row
512
+ // that discards rather than left to be noticed as a missing day.
513
+ future: rotation.future,
514
+ unrecognised: rotation.unrecognised.length,
515
+ unrecognisedNames: rotation.unrecognised.length === 0 ? null : fewOf(rotation.unrecognised),
516
+ kept: rotation.kept,
517
+ oldest: rotation.oldest,
518
+ },
519
+ undefined,
520
+ );
521
+ }
522
+ return done("taken", dir, name, copy.files, rotation, mirror, errors, started);
523
+ }
524
+
525
+ function done(
526
+ reason: SnapshotReason,
527
+ dir: string | null,
528
+ name: string | null,
529
+ files: number,
530
+ rotation: RotationReport | null,
531
+ mirror: SnapshotRunReport["mirror"],
532
+ errors: readonly string[],
533
+ started: number,
534
+ ): SnapshotRunReport {
535
+ return { reason, dir, name, files, ms: Date.now() - started, rotation, mirror, errors: [...errors] };
536
+ }
537
+
538
+ function withCleaned(cleaned: number): RotationReport {
539
+ return { ...EMPTY_ROTATION, cleaned };
540
+ }
541
+
542
+ // ── the copy, and the rename that makes it a snapshot ───────────────────────
543
+
544
+ /**
545
+ * Copy the store into `<dir>/.partial-<name>` and rename it to `<dir>/<name>`.
546
+ *
547
+ * The rename is the whole point: it is one step, so a process killed at any
548
+ * instant leaves either a partial directory (which is not a snapshot by name and
549
+ * will be swept) or a complete one. There is no in-between state that counts.
550
+ */
551
+ function copyInto(
552
+ store: Store,
553
+ dir: string,
554
+ name: string,
555
+ errors: string[],
556
+ ): { ok: true; files: number } | { ok: false; step: string; why: string } {
557
+ // The pid makes the partial name unique to THIS process, so two runs that
558
+ // overlap cannot write into each other's directory.
559
+ const partial = join(dir, `${PARTIAL_PREFIX}${name}-${String(process.pid)}`);
560
+ const report = snapshot(store, partial);
561
+ if (!report.ok) {
562
+ const why = report.errors.join("; ") || "the copy reported no detail";
563
+ errors.push(why);
564
+ try {
565
+ rmSync(partial, { recursive: true, force: true });
566
+ } catch (err) {
567
+ errors.push(`could not remove the failed partial copy: ${messageOf(err)}`);
568
+ }
569
+ return { ok: false, step: "copy", why };
570
+ }
571
+ const files = report.copied.reduce((n, entry) => n + entry.files, 0);
572
+ // THE COPY IS LOOKED AT BEFORE THE RENAME MAKES IT A SNAPSHOT (F2 review,
573
+ // MINOR-9). `report.ok` means only that no entry reported an error — and
574
+ // `copyTree` returns 0 files and `ok: true` for a source that is not there, so
575
+ // a structurally empty directory would have taken the name, counted toward
576
+ // `keep`, satisfied "today's exists" and pushed a real copy out on day 15.
577
+ const bad = verifyCopy(partial, files);
578
+ if (bad !== null) {
579
+ errors.push(bad);
580
+ try {
581
+ rmSync(partial, { recursive: true, force: true });
582
+ } catch {
583
+ /* the sweep will get it */
584
+ }
585
+ return { ok: false, step: "verify", why: bad };
586
+ }
587
+ try {
588
+ renameSync(partial, join(dir, name));
589
+ } catch (err) {
590
+ const why = messageOf(err);
591
+ errors.push(why);
592
+ try {
593
+ rmSync(partial, { recursive: true, force: true });
594
+ } catch {
595
+ /* the sweep will get it */
596
+ }
597
+ return { ok: false, step: "rename", why };
598
+ }
599
+ return { ok: true, files };
600
+ }
601
+
602
+ /**
603
+ * Is what was just written actually a copy? The cheapest honest questions, asked
604
+ * once, on a directory nothing else can see yet: it holds files at all, the
605
+ * database is there and not empty, and SQLite itself says the database is sound.
606
+ *
607
+ * `PRAGMA quick_check` rather than `integrity_check`: it is the one SQLite
608
+ * recommends for exactly this — it skips the expensive index cross-checks and
609
+ * still reads every page, which on a freshly vacuumed few-megabyte file is
610
+ * milliseconds. Returns the reason on failure, null when the copy is good.
611
+ */
612
+ export function verifyCopy(partial: string, files: number): string | null {
613
+ if (files === 0) return "the copy landed no files at all";
614
+ const db = join(partial, DATABASE_NAME);
615
+ let size: number;
616
+ try {
617
+ size = statSync(db).size;
618
+ } catch {
619
+ return `the copy holds no ${DATABASE_NAME}`;
620
+ }
621
+ if (size === 0) return `the copy's ${DATABASE_NAME} is empty`;
622
+ let handle;
623
+ try {
624
+ handle = openDb(db);
625
+ const row = handle.get<Record<string, string>>("PRAGMA quick_check");
626
+ const verdict = row === undefined ? null : Object.values(row)[0];
627
+ return verdict === "ok" ? null : `the copy's database did not verify: ${verdict ?? "no answer"}`;
628
+ } catch (err) {
629
+ return `the copy's database would not open: ${messageOf(err)}`;
630
+ } finally {
631
+ // A `finally` that throws REPLACES the return and propagates — out of
632
+ // `copyInto`, out of `runSnapshot`, past "it never throws" (second F2
633
+ // review, MINOR-c). The runner's own try would catch it, but that is belt
634
+ // and braces rather than the structural promise this module makes.
635
+ try {
636
+ handle?.close();
637
+ } catch {
638
+ /* a handle that will not close has already told us what it could */
639
+ }
640
+ }
641
+ }
642
+
643
+ /**
644
+ * The mirror — a second location that receives the same copy and rotates on its
645
+ * own terms. **A mirror failure is reported, never fatal**: the snapshot beside
646
+ * the store has already landed, and losing the second copy is not worth losing
647
+ * the first.
648
+ *
649
+ * It is copied from the finished primary rather than taken from the store a
650
+ * second time. Two reasons: the two locations then hold BYTE-IDENTICAL copies of
651
+ * one instant rather than two snapshots taken minutes apart, and the store is
652
+ * read once instead of twice. This does not cross scar §2.11's line — that rule
653
+ * is about copying a CANONICAL database as a file. The database inside a
654
+ * finished snapshot is a `VACUUM INTO` output that no process holds open.
655
+ */
656
+ function mirrorTo(
657
+ store: Store,
658
+ dir: string,
659
+ name: string,
660
+ configured: string | undefined,
661
+ keep: number | undefined,
662
+ now: number,
663
+ errors: string[],
664
+ ): SnapshotRunReport["mirror"] {
665
+ if (configured === undefined || configured.trim().length === 0) return null;
666
+ let verifyFailed = false;
667
+ try {
668
+ const target = assertRotatableDir(store.dir, configured);
669
+ // A SECOND LOCATION HAS TO BE A SECOND LOCATION (second F2 review, MINOR-e).
670
+ // A mirror nested inside the primary directory dies with the same disk while
671
+ // silently doubling local storage, and the outer rotation cannot see it —
672
+ // its name does not match — so nothing ever says there are two trees. A
673
+ // mirror EQUAL to it used to fail with a raw `ENOTEMPTY` from the rename.
674
+ // Realpaths, because that is the only spelling that settles it.
675
+ if (target === dir) {
676
+ throw new Error(`the mirror is the snapshots directory itself: ${target}`);
677
+ }
678
+ if (isWithin(dir, target)) {
679
+ throw new Error(`the mirror is inside the snapshots directory, so it is not a second place: ${target}`);
680
+ }
681
+ if (isWithin(target, dir)) {
682
+ throw new Error(`the mirror contains the snapshots directory, so it is not a second place: ${target}`);
683
+ }
684
+ // The same guard the primary copy passes through, on the FULL destination.
685
+ assertSafeTarget(store.dir, join(target, name));
686
+ const partial = join(target, `${PARTIAL_PREFIX}${name}-${String(process.pid)}`);
687
+ cleanPartials(target, now, errors);
688
+ try {
689
+ cpSync(join(dir, name), partial, { recursive: true });
690
+ // VERIFIED LIKE THE PRIMARY (second F2 review, MINOR-b). A `cpSync` that
691
+ // throws is cleaned up below; one that returns having written a truncated
692
+ // tree — a filling mirror volume is the obvious case — would otherwise be
693
+ // renamed into place, counted toward the mirror's own `keep`, and rotate a
694
+ // good copy out of it on day 15. The mirror is the copy you reach for when
695
+ // the primary is gone.
696
+ const bad = verifyCopy(partial, countFiles(partial));
697
+ if (bad !== null) {
698
+ verifyFailed = true;
699
+ throw new Error(`the mirrored copy did not verify: ${bad}`);
700
+ }
701
+ renameSync(partial, join(target, name));
702
+ } catch (err) {
703
+ try {
704
+ rmSync(partial, { recursive: true, force: true });
705
+ } catch {
706
+ /* the sweep will get it */
707
+ }
708
+ throw err;
709
+ }
710
+ const rotation = rotate(target, keep, name, 0, errors, now);
711
+ return { ok: true, why: "mirrored", step: null, rotation };
712
+ } catch (err) {
713
+ const why = messageOf(err);
714
+ errors.push(`mirror: ${why}`);
715
+ return { ok: false, why, step: verifyFailed ? "mirror-verify" : "mirror", rotation: null };
716
+ }
717
+ }
718
+
719
+ // ── rotation: the part that deletes ─────────────────────────────────────────
720
+
721
+ /** `keep`, defended. Anything that is not a positive whole number is a
722
+ * misconfiguration, and the safe reading of one is the default — never zero,
723
+ * which would mean "delete them all". */
724
+ export function keepOf(keep: number | undefined): number {
725
+ return keep !== undefined && Number.isInteger(keep) && keep > 0 ? keep : DEFAULT_KEEP;
726
+ }
727
+
728
+ /**
729
+ * Keep the newest `keep`, delete the rest OLDEST FIRST, and say what went.
730
+ *
731
+ * Sorted by NAME, never by mtime: the names are ISO instants, so they sort
732
+ * chronologically by construction, and an mtime is a property of the filesystem
733
+ * that a copy, a restore or a `touch` can rewrite.
734
+ *
735
+ * `dir` has already been through `assertRotatableDir`. `justTaken` is excluded
736
+ * from the candidates explicitly — it is the newest by name and could not be
737
+ * chosen anyway, but a rule this consequential should not rest on an ordering.
738
+ */
739
+ export function rotate(
740
+ dir: string,
741
+ keep: number | undefined,
742
+ justTaken: string | null,
743
+ cleaned: number,
744
+ errors: string[],
745
+ now: number = Date.now(),
746
+ ): RotationReport {
747
+ const limit = keepOf(keep);
748
+ const read = readSnapshotsDir(dir);
749
+ const names = read.names;
750
+ const deleted: string[] = [];
751
+ const rotationErrors: string[] = [];
752
+ // Newest last. Everything before the final `limit` entries goes, oldest first.
753
+ const doomed = names.slice(0, Math.max(0, names.length - limit));
754
+ for (const name of doomed) {
755
+ if (name === justTaken) continue;
756
+ try {
757
+ rmSync(join(dir, name), { recursive: true, force: true });
758
+ deleted.push(name);
759
+ } catch (err) {
760
+ const why = `could not remove ${name}: ${messageOf(err)}`;
761
+ rotationErrors.push(why);
762
+ errors.push(why);
763
+ }
764
+ }
765
+ const remaining = names.filter((n) => !deleted.includes(n));
766
+ return {
767
+ deleted,
768
+ kept: remaining.length,
769
+ oldest: remaining[0] ?? null,
770
+ cleaned,
771
+ future: futureNamesIn(remaining, now).length,
772
+ unrecognised: read.unrecognised,
773
+ preRows: read.preRows,
774
+ errors: rotationErrors,
775
+ };
776
+ }
777
+
778
+ /**
779
+ * The snapshots in a directory, sorted oldest first — and the one place that
780
+ * decides what COUNTS as a snapshot, which is the same decision as what rotation
781
+ * may delete.
782
+ *
783
+ * `readdirSync(..., { withFileTypes: true })` reports the entry's OWN type, so a
784
+ * symlink is `isSymbolicLink()` and never `isDirectory()`: a link pointing
785
+ * anywhere at all is skipped rather than followed, and rotation cannot walk out
786
+ * of this directory.
787
+ */
788
+ export function snapshotNamesIn(dir: string): string[] {
789
+ return readSnapshotsDir(dir).names;
790
+ }
791
+
792
+ /**
793
+ * The same reading, with "the directory is not there or would not open" kept
794
+ * apart from "the directory is empty". Doctor needs those two apart — one is a
795
+ * store that has not taken a copy yet, the other is copies that have gone
796
+ * missing — and this module's own callers do not care.
797
+ */
798
+ export function readSnapshotsDir(dir: string): SnapshotsDirRead {
799
+ let entries;
800
+ try {
801
+ entries = readdirSync(dir, { withFileTypes: true });
802
+ } catch {
803
+ // A directory that does not exist yet holds no snapshots. Not an error.
804
+ return { names: [], readable: false, unrecognised: [], preRows: [] };
805
+ }
806
+ const names: string[] = [];
807
+ const unrecognised: string[] = [];
808
+ const preRows: string[] = [];
809
+ for (const entry of entries) {
810
+ if (!entry.isDirectory()) continue;
811
+ if (!SNAPSHOT_NAME_RE.test(entry.name)) continue;
812
+ // AND IT HAS TO LOOK LIKE ONE WE WROTE (F2 review, MINOR-7). Inside the
813
+ // default directory this is belt and braces — the package made every entry
814
+ // there. It earns its keep the moment somebody points `snapshots.dir` or
815
+ // `mirror` at a directory of their own, shared with another tool: the delete
816
+ // rule becomes "a directory this package wrote" rather than "a directory
817
+ // whose name looks like one". Classified top-level names only, read from the
818
+ // store's own LAYOUT so the check cannot go stale when the floor changes.
819
+ //
820
+ // A REJECTION IS COUNTED AND NAMED, NEVER JUST SKIPPED (second F2 review,
821
+ // MAJOR-A). Because `LAYOUT` is read at runtime, this rule can change
822
+ // underneath copies that already exist — a floor change, or a copy somebody
823
+ // partly cleaned out — and a rejected directory is invisible to rotation, to
824
+ // "today's exists", to `kept`, to `oldest` and to every row. Permanent
825
+ // uncounted residue in the one directory the owner relies on is the same
826
+ // silence this module exists to remove, one level down. The rule stays as
827
+ // strict; it just says what it did.
828
+ const kind = copyKind(join(dir, entry.name));
829
+ if (kind === "pre-rows") {
830
+ // A copy of the owner's old floor. Kept, counted, named — and never
831
+ // rotated, because this build cannot open it to know what is in it.
832
+ preRows.push(entry.name);
833
+ continue;
834
+ }
835
+ if (kind === "not-a-copy") {
836
+ unrecognised.push(entry.name);
837
+ continue;
838
+ }
839
+ names.push(entry.name);
840
+ }
841
+ return {
842
+ names: names.sort(),
843
+ readable: true,
844
+ unrecognised: unrecognised.sort(),
845
+ preRows: preRows.sort(),
846
+ };
847
+ }
848
+
849
+ export interface SnapshotsDirRead {
850
+ readonly names: string[];
851
+ readonly readable: boolean;
852
+ /** Correctly-named directories that hold nothing the store's layout
853
+ * classifies. Kept — we never delete what we cannot prove we made — but
854
+ * counted, so "not rotated" can never mean "nobody noticed". */
855
+ readonly unrecognised: string[];
856
+ /** Copies of a PRE-ROWS store: they hold `operational.sqlite`, `prose/` or
857
+ * `versions/`. A copy, of a floor this build cannot open — so never deleted,
858
+ * never counted toward `keep`, and named rather than left a mystery in the
859
+ * one directory the owner relies on (review B, MAJOR-2). */
860
+ readonly preRows: string[];
861
+ }
862
+
863
+ /** How many files a finished copy holds — the mirror's input to `verifyCopy`,
864
+ * which the primary gets for free from `snapshot()`'s own report. */
865
+ function countFiles(dir: string): number {
866
+ let n = 0;
867
+ try {
868
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
869
+ n += entry.isDirectory() ? countFiles(join(dir, entry.name)) : 1;
870
+ }
871
+ } catch {
872
+ /* an unreadable copy counts as nothing, which `verifyCopy` refuses */
873
+ }
874
+ return n;
875
+ }
876
+
877
+ /** The first few of a list, and how many more — for a row or a line that must
878
+ * stay readable however long the list is. */
879
+ function fewOf(names: readonly string[], limit = 3): string {
880
+ if (names.length <= limit) return names.join(", ");
881
+ return `${names.slice(0, limit).join(", ")} and ${String(names.length - limit)} more`;
882
+ }
883
+
884
+ /**
885
+ * Is this directory a copy of a store THIS BUILD WROTE — the only kind rotation
886
+ * may ever delete?
887
+ *
888
+ * Two questions, and the second one is review B's MAJOR-2. The first: does it
889
+ * hold a top-level name the store's current `LAYOUT` classifies? A person's own
890
+ * folder wearing a snapshot-shaped name does not.
891
+ *
892
+ * **The second: is it a PRE-ROWS copy?** `LAYOUT` is read at runtime, and F5
893
+ * took `prose`, `versions` and `operational.sqlite` out of it — but left
894
+ * `spans`, which was in the old backup set too and which the owner's live store
895
+ * fills every day. So a real v5 snapshot holds `spans/` and was RECOGNISED, and
896
+ * therefore rotatable. F2 went live on the v5 store, so `~/.counterparts/
897
+ * snapshots/` fills with v5 copies; cut-over then mints a fresh store at the
898
+ * same path, which resolves to the SAME snapshots directory; fourteen daily
899
+ * boundaries later every one of the owner's pre-rows copies is deleted as an
900
+ * ordinary rotation. Those folders are the only copy of those words.
901
+ *
902
+ * So a directory holding any `PRE_ROWS_MARKERS` entry is never ours to delete,
903
+ * whatever else it holds. It is not "unrecognised" either — it is a copy, of a
904
+ * floor this build cannot open — and it gets its own channel so the sentence
905
+ * the owner reads can say which it is.
906
+ */
907
+ function copyKind(path: string): "ours" | "pre-rows" | "not-a-copy" {
908
+ let entries: string[];
909
+ try {
910
+ entries = readdirSync(path);
911
+ } catch {
912
+ return "not-a-copy"; // unreadable is not "ours"
913
+ }
914
+ if (entries.some((e) => PRE_ROWS_MARKERS.includes(e))) return "pre-rows";
915
+ for (const entry of entries) {
916
+ if (LAYOUT.some((e) => (e.match === "prefix" ? entry.startsWith(e.name) : entry === e.name))) {
917
+ return "ours";
918
+ }
919
+ }
920
+ return "not-a-copy";
921
+ }
922
+
923
+ /**
924
+ * Snapshots whose name is more than a day in the FUTURE (F2 review, MINOR-5).
925
+ *
926
+ * One clock-skewed boundary — a laptop waking with a bad RTC — plants a name
927
+ * that sorts newest forever, occupies a `keep` slot permanently, and quietly
928
+ * leaves the owner with thirteen days of history instead of fourteen. They are
929
+ * NOT deleted here: a copy is a copy, and guessing that a name is wrong is not a
930
+ * reason to destroy the bytes behind it. They are COUNTED and reported, so the
931
+ * "silently" is gone.
932
+ */
933
+ export function futureNamesIn(names: readonly string[], now: number): string[] {
934
+ // COMPARED AS CALENDAR DATES, not as instants. Doctor asks this question with
935
+ // midnight today and rotation asks it with the live clock, and an instant
936
+ // cutoff made the two disagree by up to a day — one surface saying "1 dated in
937
+ // the future" while the other's row said none (second F2 review, MINOR-f).
938
+ // Every caller on the same day now gets the same answer.
939
+ const cutoff = dateOf(now + 86_400_000);
940
+ return names.filter((n) => n.slice(0, 10) > cutoff);
941
+ }
942
+
943
+ /** Today's snapshot, by name, or null. The names are UTC ISO instants, so the
944
+ * calendar date is their first ten characters — the same UTC day every other
945
+ * date in this store is spelled in. */
946
+ export function todaysSnapshot(dir: string, date: string): string | null {
947
+ for (const name of snapshotNamesIn(dir)) {
948
+ if (name.startsWith(`${date}T`)) return name;
949
+ }
950
+ return null;
951
+ }
952
+
953
+ /**
954
+ * Remove `.partial-…` directories a killed run left behind — but only ones old
955
+ * enough that no live run could still be writing into them. A sweep that deleted
956
+ * a fresh partial would be this module destroying its own concurrent copy.
957
+ */
958
+ export function cleanPartials(dir: string, now: number, errors: string[]): number {
959
+ let entries;
960
+ try {
961
+ entries = readdirSync(dir, { withFileTypes: true });
962
+ } catch {
963
+ return 0;
964
+ }
965
+ let cleaned = 0;
966
+ for (const entry of entries) {
967
+ if (!entry.isDirectory()) continue;
968
+ if (!PARTIAL_NAME_RE.test(entry.name)) continue;
969
+ const path = join(dir, entry.name);
970
+ try {
971
+ // ABSOLUTE, so a partial whose mtime is in the FUTURE — the same
972
+ // clock-skew family as a future-dated copy — is not kept forever by a
973
+ // negative age that is always under the bound (second F2 review, NIT-2).
974
+ if (Math.abs(now - statSync(path).mtimeMs) < PARTIAL_STALE_MS) continue;
975
+ // A PARTIAL HOLDING PRE-ROWS NAMES IS STILL NOT OURS TO DELETE.
976
+ //
977
+ // B-MAJOR-2's rule — a directory holding any `PRE_ROWS_MARKERS` entry is
978
+ // never ours — was applied to finished copies and not here, and this was
979
+ // the one path left that still deleted pre-rows bytes (review f5c,
980
+ // NIT-3). A partial is by definition incomplete, so in principle it is a
981
+ // half-copy nobody wants; but "in principle" is exactly the confidence
982
+ // that deleted three weeks of journal in v1, and the cost of keeping one
983
+ // is a directory. It stops being counted as cleaned, and the rotation's
984
+ // `preRows` channel names it.
985
+ if (copyKind(path) === "pre-rows") continue;
986
+ rmSync(path, { recursive: true, force: true });
987
+ cleaned += 1;
988
+ } catch (err) {
989
+ errors.push(`could not remove an abandoned copy ${entry.name}: ${messageOf(err)}`);
990
+ }
991
+ }
992
+ return cleaned;
993
+ }
994
+
995
+ // ── the durable record ──────────────────────────────────────────────────────
996
+
997
+ /**
998
+ * How many copy attempts already failed today. The cap's input.
999
+ *
1000
+ * `eventLog` is `ORDER BY seq ASC LIMIT`, so a read that comes back FULL is the
1001
+ * OLDEST rows and today's are exactly the ones missing — the same trap
1002
+ * `doctor.ts#newestRows` carries a paragraph about. It bites hardest under the
1003
+ * failure this project has already lived through: a frozen lived-day clock (I32)
1004
+ * leaves every row inside one `day`, the window fills, and the cap silently
1005
+ * reads zero forever. So the limit is generous, and a read that REACHES it is
1006
+ * treated as exhausted rather than as zero — the fail-closed direction, and the
1007
+ * cheap one, because the thing being refused is a retry rather than a backup.
1008
+ */
1009
+ const FAILED_READ_LIMIT = 1000;
1010
+
1011
+ function failedAttemptsToday(
1012
+ store: Store,
1013
+ date: string,
1014
+ ): { count: number; saturated: boolean } {
1015
+ try {
1016
+ const livedDay = store.livedDay();
1017
+ // A lived day is never longer than a calendar day, so two lived days back
1018
+ // certainly covers today's rows whichever side of a cycle they landed on.
1019
+ const rows = store.eventLog({
1020
+ name: SNAPSHOT_FAILED_EVENT,
1021
+ sinceDay: Math.max(0, livedDay - 2),
1022
+ limit: FAILED_READ_LIMIT,
1023
+ });
1024
+ if (rows.length >= FAILED_READ_LIMIT) return { count: MAX_ATTEMPTS_PER_DAY, saturated: true };
1025
+ let n = 0;
1026
+ for (const row of rows) {
1027
+ if (row.payload === null) continue;
1028
+ try {
1029
+ const p: unknown = JSON.parse(row.payload);
1030
+ if (p === null || typeof p !== "object") continue;
1031
+ const rec = p as Record<string, unknown>;
1032
+ // Only a failed COPY counts against the cap: a refused directory, an
1033
+ // aborted watchdog and an unreadable window all cost nothing to re-check,
1034
+ // and capping on them would hide a fixed one (F2 review, MINOR-1).
1035
+ if (
1036
+ rec["date"] === date &&
1037
+ (rec["step"] === "copy" || rec["step"] === "rename" || rec["step"] === "verify")
1038
+ ) {
1039
+ n += 1;
1040
+ }
1041
+ } catch {
1042
+ /* an unparseable row is not an attempt */
1043
+ }
1044
+ }
1045
+ return { count: n, saturated: false };
1046
+ } catch {
1047
+ // A store that cannot be read is not a store that has used up its attempts.
1048
+ return { count: 0, saturated: false };
1049
+ }
1050
+ }
1051
+
1052
+ /** One durable row, and never a throw: a failed record may not turn a failed
1053
+ * step into a failed process. */
1054
+ function note(
1055
+ counterpart: Counterpart,
1056
+ name: typeof SNAPSHOT_TAKEN_EVENT | typeof SNAPSHOT_FAILED_EVENT | typeof SNAPSHOT_ROTATED_EVENT,
1057
+ data: Record<string, unknown>,
1058
+ dedupKey: string | undefined,
1059
+ ): void {
1060
+ try {
1061
+ counterpart.noteAdapterEvent(name, data, dedupKey === undefined ? {} : { dedupKey });
1062
+ } catch {
1063
+ /* §5 G8 */
1064
+ }
1065
+ }
1066
+
1067
+ function messageOf(err: unknown): string {
1068
+ return err instanceof Error ? err.message : String(err);
1069
+ }