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,229 @@
1
+ /**
2
+ * `counterparts self-page` — the owner's door to the written page.
3
+ *
4
+ * The page is the prose the wake now leads with, and constitution 6 says the
5
+ * owner owns the data, in prose they can read and hand-edit in any editor. This
6
+ * is the console half of that: read it, write it whole from a file or from
7
+ * stdin, list what it used to say, and print any one of those versions.
8
+ *
9
+ * **Rendering only.** Every rule about the page — the caps, the gate battery,
10
+ * the durable row, the refusals — lives on the one core seam
11
+ * (`core/self/index.ts#revisePage`), and this file decides nothing of its own.
12
+ * A console that re-implemented a cap would be a second cap.
13
+ *
14
+ * **Reading is allowed under observer; writing is not.** The write refuses at
15
+ * the seam, in the sentence every other write refuses in, which is why
16
+ * `self-page` is not on `OWNER_OPS` — see the note there. An instrument must be
17
+ * able to answer "what does the page say", because that is the first question
18
+ * anyone asks when the wake looks wrong.
19
+ */
20
+ import { readFileSync } from "node:fs";
21
+
22
+ import type { Counterpart } from "../../core/counterpart.js";
23
+ import { PAGE_TEMPLATE, pageSections } from "../../core/self/index.js";
24
+ import type { PageVersion, SelfPage } from "../../core/self/index.js";
25
+
26
+ /** What a read prints when the store holds no page. Honest, and not a page. */
27
+ export const NO_PAGE_LINES: readonly string[] = [
28
+ "No page has been written here yet — still forming.",
29
+ "",
30
+ "A page is written by a woken session (the `self_page` tool), by the nightly",
31
+ "writer, or by you:",
32
+ "",
33
+ " counterparts self-page --write --file <path> --reason \"why\"",
34
+ " … | counterparts self-page --write --stdin --reason \"why\"",
35
+ "",
36
+ "A blank page to start from:",
37
+ "",
38
+ ...PAGE_TEMPLATE.trimEnd().split("\n").map((l) => ` ${l}`),
39
+ "",
40
+ "If a page was written here and cleared, its versions are still listed —",
41
+ "until a new page is written, which then becomes the one this command reads:",
42
+ " counterparts self-page --versions · counterparts self-page --restore <seq>",
43
+ ];
44
+
45
+ export function pageLines(page: SelfPage, stale: boolean, versions: number): string[] {
46
+ const parts = pageSections(page.body);
47
+ const when = page.revisedOn === "" ? "an unrecorded date" : page.revisedOn;
48
+ const head = [
49
+ `Who I am — ${page.bytes} bytes, version ${page.version}, last revised ${when}` +
50
+ `${page.by === null ? "" : ` by ${page.by}`}${stale ? " — STALE" : ""}.`,
51
+ ...(page.reason === null ? [] : [`Last change: ${page.reason}`]),
52
+ ...(versions === 0
53
+ ? ["No earlier versions yet."]
54
+ : [`${versions} earlier version${versions === 1 ? "" : "s"} — 'self-page --versions'.`]),
55
+ ...(parts.headed ? [] : ["(No `## Core` / `## Lately` headings — printed as it stands.)"]),
56
+ "",
57
+ ];
58
+ return [...head, ...page.body.split("\n")];
59
+ }
60
+
61
+ /**
62
+ * The version log, labelled by the write that PRODUCED each body.
63
+ *
64
+ * `store.revise` records the REPLACING write's reason on the row it archives, so
65
+ * printing `VersionRow.reason` straight through labelled the first page with the
66
+ * second write's words while the current page's own `Last change:` line was
67
+ * right — the same word meaning opposite things on two surfaces (adversarial
68
+ * review M3). `self/#pageVersions` reads the producing write off the durable
69
+ * rows; this prints it, with the replacing reason named for what it is, and in
70
+ * BYTES like every other page surface rather than in characters (m8).
71
+ */
72
+ export function versionLines(versions: readonly PageVersion[]): string[] {
73
+ if (versions.length === 0) return ["No earlier versions: the page has been written once, or not at all."];
74
+ return [
75
+ `${versions.length} earlier version${versions.length === 1 ? "" : "s"}, newest first.`,
76
+ " seq · lived day · size · who wrote it and why · what replaced it",
77
+ "",
78
+ ...versions.map((v) => {
79
+ const size = v.bytes === null ? "unreadable" : `${v.bytes} bytes`;
80
+ const wrote =
81
+ v.reason === null
82
+ ? "(unrecorded)"
83
+ : `${v.by === null ? "" : `${v.by}: `}${v.reason}`;
84
+ return (
85
+ ` ${String(v.seq).padStart(4)} lived day ${String(v.day).padStart(4)} ` +
86
+ `${size.padEnd(12)} ${wrote} ← replaced by: ${v.replacedBy}`
87
+ );
88
+ }),
89
+ "",
90
+ "One of them in full: 'self-page --version <seq>'.",
91
+ "Put one back: 'self-page --restore <seq>' — itself a version, itself undoable.",
92
+ ];
93
+ }
94
+
95
+ /** The body a write is given: a file, or standard input. Never a flag value —
96
+ * a page on the command line is a page in shell history. */
97
+ export function bodyFrom(
98
+ flags: { file?: string | boolean | undefined; stdin?: string | boolean | undefined },
99
+ readStdin: () => string,
100
+ ): { body: string } | { error: string; missing?: boolean } {
101
+ const from = typeof flags.file === "string" ? flags.file : null;
102
+ const stdin = flags.stdin === true || typeof flags.stdin === "string";
103
+ if (from !== null && stdin) {
104
+ return { error: "--file and --stdin both name where the page comes from; pass one." };
105
+ }
106
+ if (from === null && !stdin) {
107
+ return { error: "--write needs the page: --file <path>, or --stdin." };
108
+ }
109
+ if (from !== null) {
110
+ try {
111
+ return { body: readFileSync(from, "utf8") };
112
+ } catch (err) {
113
+ // A file that is not THERE is a command line that is wrong; a file that is
114
+ // there and will not open is the machine failing. `EXIT.failed` exists for
115
+ // the second, and the caller reads `missing` to tell them apart (n5).
116
+ const code = (err as NodeJS.ErrnoException).code ?? "";
117
+ return {
118
+ error: `could not read ${from}: ${String((err as Error).message ?? err)}`,
119
+ missing: code === "ENOENT",
120
+ };
121
+ }
122
+ }
123
+ return { body: readStdin() };
124
+ }
125
+
126
+ export interface WrittenLines {
127
+ readonly lines: string[];
128
+ readonly ok: boolean;
129
+ }
130
+
131
+ /** What the console says about a write, accepted or not. */
132
+ export function writeLines(
133
+ written: ReturnType<Counterpart["revisePage"]>,
134
+ wakeCap: number,
135
+ ): WrittenLines {
136
+ if (!written.written) {
137
+ switch (written.reason) {
138
+ case "observer":
139
+ return {
140
+ lines: ["refused: this console is in observer stance: an instrument reads the page and does not change it."],
141
+ ok: false,
142
+ };
143
+ case "too-large":
144
+ return {
145
+ lines: [
146
+ `refused: the page is ${written.bytes} bytes, past the hard limit. Refused rather than cut — what gets cut at write time is the only copy.`,
147
+ ],
148
+ ok: false,
149
+ };
150
+ case "empty":
151
+ return { lines: ["refused: a page has to say something."], ok: false };
152
+ case "forged-markers":
153
+ return {
154
+ lines: [
155
+ "refused: the page carries the wake's own structural markers (`<!-- counterparts:wake`). Those lines are the bundle's bookkeeping; a page that contains them reads, to the next session, as the end of its memory.",
156
+ ],
157
+ ok: false,
158
+ };
159
+ case "version-moved":
160
+ return {
161
+ lines: [
162
+ `refused: the page has moved on since the version you named — it is at version ${written.current === null ? "?" : written.current.version} now.`,
163
+ "Nothing was written. Read it again ('counterparts self-page'), fold in what you meant to change, and write that.",
164
+ ],
165
+ ok: false,
166
+ };
167
+ case "no-page":
168
+ return {
169
+ lines: [
170
+ "refused: you named a version, and there is no page here at all — nobody wrote over you. Drop --if-version to write the first one.",
171
+ ],
172
+ ok: false,
173
+ };
174
+ case "page-appeared":
175
+ return {
176
+ lines: [
177
+ `refused: you wrote as if there were no page, and there is one — version ${written.current === null ? "?" : written.current.version}.`,
178
+ "Nothing was written. Read it first ('counterparts self-page'), then write with that version.",
179
+ ],
180
+ ok: false,
181
+ };
182
+ case "no-such-version":
183
+ return { lines: ["refused: there is no version by that number."], ok: false };
184
+ default:
185
+ return {
186
+ lines: [
187
+ `refused: the gate battery turned it away${written.gate === null ? "" : ` (${written.gate.gate}: ${written.gate.reason})`}.`,
188
+ ],
189
+ ok: false,
190
+ };
191
+ }
192
+ }
193
+ if (written.reason === "cleared") {
194
+ return {
195
+ lines: [
196
+ `Cleared the page — the ${written.bytes} bytes that were there are kept as version ${written.version}.`,
197
+ // TRUE NOW: the clear is a revision of the same row, so the history is
198
+ // this row's for good and a restore revises it back. The first design
199
+ // archived the row and the restore minted a fresh one, which orphaned
200
+ // the very versions this line was promising.
201
+ `The wake goes back to what it showed before a page existed. Put it back with: counterparts self-page --restore ${written.version}.`,
202
+ ],
203
+ ok: true,
204
+ };
205
+ }
206
+ return {
207
+ lines: [
208
+ `${written.reason === "created" ? "Wrote" : "Revised"} the page — ${written.bytes} bytes, version ${written.version}.`,
209
+ // THE GATE CHANGED IT, and the owner is told (adversarial review m1). He
210
+ // wrote a file from his editor; what is stored is not that file, and this
211
+ // is the one row read aloud at the start of every session.
212
+ ...(written.redacted === null
213
+ ? []
214
+ : [
215
+ `NOTE: the gate redacted the page before storing it (${written.redacted.gate}) — ${written.redacted.bytesBefore} bytes in, ${written.bytes} out. Read it back before you rely on it: counterparts self-page.`,
216
+ ]),
217
+ ...(written.warning === null
218
+ ? []
219
+ : [
220
+ `warning: past the wake's ${wakeCap}-byte cap, so the wake will show a cut of it with a marker. The page itself is kept whole.`,
221
+ ]),
222
+ // The briefing phase is cadenced once per LIVED day, so "the next
223
+ // boundary" is not the whole truth: a boundary that has already rendered
224
+ // today renders nothing, and the page waits. `rebrief` is the lever.
225
+ "It reaches the wake at the next boundary that re-renders it — once per lived day. To put it there now: counterparts rebrief.",
226
+ ],
227
+ ok: true,
228
+ };
229
+ }
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Copying a store safely — the sharpest scar in this adapter's list (§2.11).
3
+ *
4
+ * **A canonical database is never file-copied.** v1 copied its SQLite file with
5
+ * no checkpoint, and it was harmless *because the database was a declared
6
+ * rebuildable cache*. Rescope 1 removed exactly that mitigation: box 2 is
7
+ * canonical now, so the same flaw is canonical-data loss. Here the database is
8
+ * copied by `VACUUM INTO`, which is SQLite's own consistent-snapshot operation:
9
+ * it takes a read transaction, so a writer holding an uncommitted transaction
10
+ * cannot tear the copy — the snapshot contains the last committed state and
11
+ * nothing half-written. `test/cli.test.ts` proves it by holding an open write
12
+ * transaction across the copy and reading the result back.
13
+ *
14
+ * **Scope is asserted against the layout, not documented** (§5 G5). `LAYOUT` in
15
+ * `store/paths.ts` classifies every top-level path as backed-up or explicitly
16
+ * excluded, and `Store.assertLayout()` throws on anything unclassified. This
17
+ * module copies exactly `Store.backupSet()` — so adding a directory to the data
18
+ * dir without classifying it breaks the build, and adding one that IS classified
19
+ * changes the backup automatically. v1's allowlist landed hours before the
20
+ * episode directory existed and silently omitted the canonical journal for three
21
+ * weeks; a hand-maintained second list here would re-create that bug exactly.
22
+ *
23
+ * **Nothing throws at the caller** (§5 G8). A backup problem must not block a
24
+ * consolidation cycle, so every failure is a row in the report.
25
+ */
26
+ import {
27
+ copyFileSync,
28
+ existsSync,
29
+ lstatSync,
30
+ mkdirSync,
31
+ readdirSync,
32
+ realpathSync,
33
+ statSync,
34
+ } from "node:fs";
35
+ import { basename, dirname, join, resolve } from "node:path";
36
+
37
+ import { openDb } from "../../core/store/db.js";
38
+ import {
39
+ DATABASE_FILE,
40
+ LAYOUT,
41
+ assertSafeDataDir,
42
+ forbiddenRoots,
43
+ isWithin,
44
+ paths,
45
+ } from "../../core/store/index.js";
46
+ import type { Store } from "../../core/store/index.js";
47
+
48
+ export type CopyMethod = "vacuum-into" | "file-tree" | "skipped";
49
+
50
+ export interface CopiedEntry {
51
+ readonly name: string;
52
+ readonly method: CopyMethod;
53
+ readonly ok: boolean;
54
+ readonly files: number;
55
+ readonly why: string;
56
+ }
57
+
58
+ export interface SnapshotReport {
59
+ readonly ok: boolean;
60
+ readonly target: string;
61
+ readonly copied: readonly CopiedEntry[];
62
+ /** Every classified-but-excluded path, with the reason from the layout. */
63
+ readonly excluded: readonly { name: string; why: string }[];
64
+ readonly errors: readonly string[];
65
+ }
66
+
67
+ /**
68
+ * A path with every SYMLINK ON THE WAY TO IT resolved — the leaf itself usually
69
+ * does not exist yet, so the nearest existing ancestor is realpath'd and the
70
+ * tail is rejoined.
71
+ *
72
+ * Why it exists (f6f7 review MAJOR-4, measured): `resolve()` normalises `..` but
73
+ * never reads the filesystem, so a target reached through a link into the store
74
+ * was judged "outside" and written anyway — a whole export tree, memories and
75
+ * all, landed inside `<store>/journal/`.
76
+ *
77
+ * A DANGLING link is refused here by name rather than left to `mkdirSync`,
78
+ * which throws a raw `EEXIST` on one. A guard that holds because of an errno is
79
+ * not a guard, and "file already exists" is not a sentence about safety.
80
+ */
81
+ function realOf(path: string, what: string): string {
82
+ const full = resolve(path);
83
+ const tail: string[] = [];
84
+ let at = full;
85
+ for (;;) {
86
+ let entry;
87
+ try {
88
+ entry = lstatSync(at);
89
+ } catch {
90
+ const up = dirname(at);
91
+ // The filesystem root cannot be missing; stop rather than loop.
92
+ if (up === at) return full;
93
+ tail.unshift(basename(at));
94
+ at = up;
95
+ continue;
96
+ }
97
+ if (entry.isSymbolicLink() && !existsSync(at)) {
98
+ throw new Error(
99
+ `refusing a ${what} that is a dangling symlink: ${at} points at something that does not exist`,
100
+ );
101
+ }
102
+ try {
103
+ return join(realpathSync(at), ...tail);
104
+ } catch {
105
+ return full;
106
+ }
107
+ }
108
+ }
109
+
110
+ /**
111
+ * The destination guard (§5 G3, scar §2.13). BOTH SIDES ARE RESOLVED — through
112
+ * `..` AND through symlinks — BEFORE THEY ARE COMPARED. v1's migration guard was
113
+ * a raw string comparison, and `--out ~/.bansai/` with a trailing slash pointed
114
+ * it at the live store and mass-wrote about 11,000 files.
115
+ *
116
+ * **Both sides, and the forbidden roots too.** On macOS `$TMPDIR` is itself
117
+ * reached through a link (`/var` → `/private/var`), so realpath'ing one side
118
+ * only would stop every "inside the store" case from being detected and make a
119
+ * fake-`HOME` test of the v1 roots pass vacuously.
120
+ *
121
+ * Two refusals people forget, and now a third: a destination INSIDE the data
122
+ * directory would put the copy in the tree it is copying, which both recurses
123
+ * and lands an unclassified top-level path in the store; a destination that
124
+ * CONTAINS the store is the same problem upside down; and a destination whose
125
+ * link lands in `~/.bansai` or `~/.claude-engram` is v1's live memory reached
126
+ * the one way `assertSafeDataDir` alone cannot see.
127
+ */
128
+ export function assertSafeTarget(dataDir: string, target: string): string {
129
+ // The plain-path v1-root refusal first, on the path as typed: it is the
130
+ // sentence the owner gets for `--out ~/.bansai/`, and it should not change
131
+ // shape because a link was involved.
132
+ assertSafeDataDir(target);
133
+ const resolvedTarget = realOf(target, "destination");
134
+ const resolvedSource = realOf(dataDir, "store");
135
+ // …and again on the resolved path, so a link whose DESTINATION is inside a
136
+ // live v1 store is refused by the same rule that refuses the path itself.
137
+ assertSafeDataDir(resolvedTarget);
138
+ for (const root of forbiddenRoots()) {
139
+ if (isWithin(realOf(root, "store"), resolvedTarget)) {
140
+ throw new Error(`refusing a destination inside ${root}: ${resolvedTarget}`);
141
+ }
142
+ }
143
+ if (isWithin(resolvedSource, resolvedTarget)) {
144
+ throw new Error(
145
+ `refusing to write a copy inside the store it is copying: ${resolvedTarget}`,
146
+ );
147
+ }
148
+ if (isWithin(resolvedTarget, resolvedSource)) {
149
+ throw new Error(`refusing a destination that contains the store: ${resolvedTarget}`);
150
+ }
151
+ // The TYPED path is what comes back, not the realpath'd one: every caller
152
+ // prints it and every test names it, and telling the owner his export went to
153
+ // `/private/var/…` when he typed `/var/…` is a different kind of confusing.
154
+ return resolve(target);
155
+ }
156
+
157
+ function copyTree(from: string, to: string): number {
158
+ if (!existsSync(from)) return 0;
159
+ const stat = statSync(from);
160
+ if (!stat.isDirectory()) {
161
+ mkdirSync(join(to, ".."), { recursive: true });
162
+ copyFileSync(from, to);
163
+ return 1;
164
+ }
165
+ mkdirSync(to, { recursive: true });
166
+ let files = 0;
167
+ for (const name of readdirSync(from)) {
168
+ files += copyTree(join(from, name), join(to, name));
169
+ }
170
+ return files;
171
+ }
172
+
173
+ /**
174
+ * Snapshot a store into `target`. The database goes through `VACUUM INTO`; every
175
+ * other backed-up path is an ordinary file-tree copy, which is correct for plain
176
+ * files and correct for prose.
177
+ *
178
+ * `store` is passed so the copy is made against the SAME layout the store
179
+ * asserted at open — not against a directory listing this module took on its
180
+ * own, which could disagree.
181
+ */
182
+ export function snapshot(store: Store, target: string): SnapshotReport {
183
+ const copied: CopiedEntry[] = [];
184
+ const excluded: { name: string; why: string }[] = [];
185
+ const errors: string[] = [];
186
+ let resolvedTarget: string;
187
+ try {
188
+ resolvedTarget = assertSafeTarget(store.dir, target);
189
+ // The layout is re-asserted here, not assumed from open: a directory that
190
+ // appeared since the store opened must be classified before it is skipped.
191
+ store.assertLayout();
192
+ mkdirSync(resolvedTarget, { recursive: true });
193
+ } catch (err) {
194
+ return {
195
+ ok: false,
196
+ target,
197
+ copied: [],
198
+ excluded: [],
199
+ errors: [String((err as Error).message ?? err)],
200
+ };
201
+ }
202
+
203
+ const backupSet = new Set(store.backupSet());
204
+ for (const entry of LAYOUT) {
205
+ if (!backupSet.has(entry.name)) {
206
+ excluded.push({ name: entry.name, why: entry.why });
207
+ continue;
208
+ }
209
+ const from = join(store.dir, entry.name);
210
+ const to = join(resolvedTarget, entry.name);
211
+ // The canonical database, and only it, takes the database's own route.
212
+ // Matched against the layout's own spelling of the name, never a literal:
213
+ // the file was `operational.sqlite` until the floor moved the bodies into
214
+ // it, and a second spelling here would have quietly sent the canonical
215
+ // database down the file-copy path on the day it was renamed (§2.11).
216
+ if (entry.name === DATABASE_FILE) {
217
+ const result = vacuumInto(paths.operational(store.dir), to);
218
+ copied.push({
219
+ name: entry.name,
220
+ method: "vacuum-into",
221
+ ok: result.ok,
222
+ files: result.ok ? 1 : 0,
223
+ why: result.ok
224
+ ? "Copied through SQLite's own consistent-snapshot path, never as a file copy (scar §2.11)."
225
+ : result.error,
226
+ });
227
+ if (!result.ok) errors.push(`${entry.name}: ${result.error}`);
228
+ continue;
229
+ }
230
+ try {
231
+ const files = copyTree(from, to);
232
+ copied.push({
233
+ name: entry.name,
234
+ method: "file-tree",
235
+ ok: true,
236
+ files,
237
+ why: entry.why,
238
+ });
239
+ } catch (err) {
240
+ const message = String((err as Error).message ?? err);
241
+ copied.push({ name: entry.name, method: "file-tree", ok: false, files: 0, why: message });
242
+ errors.push(`${entry.name}: ${message}`);
243
+ }
244
+ }
245
+
246
+ return { ok: errors.length === 0, target: resolvedTarget, copied, excluded, errors };
247
+ }
248
+
249
+ /**
250
+ * `VACUUM INTO` on its own connection. The destination must not exist — SQLite
251
+ * refuses to overwrite, which is the right default for a snapshot: a backup that
252
+ * silently replaces yesterday's is one crash away from being no backup at all.
253
+ */
254
+ export function vacuumInto(
255
+ source: string,
256
+ destination: string,
257
+ ): { ok: true } | { ok: false; error: string } {
258
+ if (!existsSync(source)) return { ok: false, error: "no canonical database at source" };
259
+ if (existsSync(destination)) {
260
+ return { ok: false, error: `destination already exists: ${destination}` };
261
+ }
262
+ let db;
263
+ try {
264
+ db = openDb(source);
265
+ // Single-quoted SQL literal: the path is escaped for SQL, never interpolated
266
+ // into a shell, because nothing here shells out.
267
+ db.exec(`VACUUM INTO '${destination.replace(/'/g, "''")}'`);
268
+ return { ok: true };
269
+ } catch (err) {
270
+ return { ok: false, error: String((err as Error).message ?? err) };
271
+ } finally {
272
+ db?.close();
273
+ }
274
+ }
275
+
276
+ /** A snapshot directory name that sorts chronologically and never collides. */
277
+ export function snapshotName(at: number): string {
278
+ return new Date(at).toISOString().replace(/[:.]/g, "-");
279
+ }