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,494 @@
1
+ /**
2
+ * Where the data dir is, what lives in it, and which of it is backed up.
3
+ *
4
+ * `dataDir()` reads the environment AT CALL TIME (never at module load) so a test
5
+ * can redirect it per test — the hermetic-test rule in CLAUDE.md depends on this.
6
+ */
7
+ import { existsSync, readdirSync, statSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { join, resolve, relative, isAbsolute } from "node:path";
10
+ import { StoreError, isStoreError } from "./errors.js";
11
+
12
+ export const DATA_DIR_ENV = "COUNTERPARTS_DATA_DIR";
13
+ /**
14
+ * THE EXPLICIT-DIR GUARD. Armed (`1`, `true` or `on`), it makes `dataDir()` REFUSE
15
+ * its fallback instead of returning `~/.counterparts/store`: a caller who named
16
+ * no directory — no `dir`, no `COUNTERPARTS_DATA_DIR` — gets
17
+ * `IMPLICIT_DEFAULT_DIR_REFUSED` and nothing opens. Unset — or set to `0`, `false`
18
+ * or `off` — nothing changes. A value that is neither is REFUSED rather than
19
+ * read as off (`EXPLICIT_DIR_ARMING_VALUES` below).
20
+ *
21
+ * Why it exists (LAUNCH-STATUS I21, owner ruling 2026-09-05): on the owner's
22
+ * machine the fallback IS his live memory, and a library caller reached it
23
+ * overnight by passing the wrong option name — `dir` was undefined, the default
24
+ * answered, and nine titles were read out of the live store. `.counterparts`
25
+ * cannot go on `FORBIDDEN_ROOT_NAMES` (the store must open its own default), so
26
+ * the guard is opt-in: OFF by default so every installed host behaves exactly as
27
+ * before, ON wherever this repo's own tooling runs — `test/preload.ts`, the demo
28
+ * seeder, the visual loop, the recall bench, and the agent shells the owner
29
+ * ruled it into. The install loop deliberately UNSETS it inside its clean room
30
+ * (`tools/install-loop/run.sh`): its fake HOME makes the default throwaway, and
31
+ * it measures a stranger's environment, which has no such variable.
32
+ *
33
+ * `adapters/config-path.ts#implicitConfigRefusal` is the same guard at the other
34
+ * door: a default-sourced `~/.counterparts/claude-code.json` NAMES a store, so the
35
+ * hook, the worker and the MCP server reach the live one without ever calling
36
+ * `dataDir()`, and `install` writes under that base.
37
+ */
38
+ export const REQUIRE_EXPLICIT_DIR_ENV = "COUNTERPARTS_REQUIRE_EXPLICIT_DIR";
39
+ export const DEFAULT_DATA_DIR_NAME = ".counterparts";
40
+ /**
41
+ * The STORE sits one level below the base dir. The base dir belongs to the host
42
+ * adapters (configuration, credentials); the store classifies every top-level
43
+ * entry it holds and refuses an unclassified one at open (§5 G11), so a store
44
+ * that IS the base dir cannot open once a host has written its config there.
45
+ * Ruled by the owner 2026-09-04 after the launch inventory reproduced it.
46
+ */
47
+ export const DEFAULT_STORE_SUBDIR = "store";
48
+
49
+ /**
50
+ * The canonical database's file name (owner ruling 5, 2026-09-18).
51
+ *
52
+ * It was `operational.sqlite` while the memories themselves were markdown files
53
+ * beside it and the database held "the operational bits". Once the bodies are
54
+ * rows the name stops being true, and a name that lies is a name somebody will
55
+ * one day act on. There is no migration to worry about: the cut-over starts a
56
+ * blank store, and a directory holding the OLD name is refused by name before
57
+ * anything opens it (`STORE_PRE_ROWS`, `store/index.ts`).
58
+ *
59
+ * Spelled once. `LAYOUT` and `paths.operational` both read it, and
60
+ * `adapters/snapshots.ts` takes it from `basename(paths.operational("."))`
61
+ * rather than typing it a second time.
62
+ */
63
+ export const DATABASE_FILE = "counterparts.sqlite";
64
+
65
+ /**
66
+ * Roots this repo may never write into: v1's live memory and its ancestor.
67
+ * (CLAUDE.md "never touch the live stores"; scar §2.13 — a path guard resolves
68
+ * both sides before it compares, so `~/.bansai/../.bansai/x` is caught too.)
69
+ */
70
+ export const FORBIDDEN_ROOT_NAMES = [".bansai", ".claude-engram"] as const;
71
+
72
+ export function forbiddenRoots(): string[] {
73
+ const home = homedir();
74
+ return FORBIDDEN_ROOT_NAMES.map((n) => resolve(join(home, n)));
75
+ }
76
+
77
+ /** True when `child` is `parent` or lives underneath it. Both sides resolved first. */
78
+ export function isWithin(parent: string, child: string): boolean {
79
+ const rel = relative(resolve(parent), resolve(child));
80
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
81
+ }
82
+
83
+ /** Throws rather than returning a path that points at a live v1 store. */
84
+ export function assertSafeDataDir(dir: string): string {
85
+ const resolved = resolve(dir);
86
+ for (const root of forbiddenRoots()) {
87
+ if (isWithin(root, resolved)) {
88
+ throw new StoreError("DATA_DIR_FORBIDDEN", { root });
89
+ }
90
+ }
91
+ return resolved;
92
+ }
93
+
94
+ /**
95
+ * THE THREE READINGS OF THE SWITCH. Whitespace is trimmed and case is ignored on
96
+ * all of them; blank is absent.
97
+ *
98
+ * - `EXPLICIT_DIR_ARMING_VALUES` — the guard is on. It is a SUPERSET of the two
99
+ * `COUNTERPARTS_OBSERVER` accepts (`cli/commands.ts`,
100
+ * `mcp/bin/serve.ts#launchOptions` both match `"1"` and `"true"` exactly), so
101
+ * a person who exports `=true` by analogy IS protected. `COUNTERPARTS_OBSERVER`
102
+ * is deliberately NOT widened to match from here: it is read on the live MCP
103
+ * server's launch path, which this change promises to leave instruction-for-
104
+ * instruction identical, and giving it a fail-closed arm is its own ruling.
105
+ * - `EXPLICIT_DIR_DISARMING_VALUES` — the guard is off, exactly as if the
106
+ * variable were unset. A guard whose `=0` REFUSED would trip the shell of the
107
+ * person it protects, which is the surprising direction; `off` means off
108
+ * (owner ruling on the #80 review round).
109
+ * - anything else non-blank is REFUSED, never ignored. The #80 review measured
110
+ * `=true`, `=yes`, `=on` and `= 1` all falling silently to the default under
111
+ * the first draft, and falling open is the one failure direction a safety
112
+ * guard may not have. Junk is not "off"; junk is a question this will not
113
+ * answer.
114
+ */
115
+ export const EXPLICIT_DIR_ARMING_VALUES: readonly string[] = ["1", "true", "on"];
116
+ export const EXPLICIT_DIR_DISARMING_VALUES: readonly string[] = ["0", "false", "off"];
117
+
118
+ export type ExplicitDirSetting =
119
+ /** Armed; `value` is the trimmed text that armed it, so a refusal can quote it as typed. */
120
+ | { readonly armed: true; readonly value: string }
121
+ /** Not armed: `malformed` is null when the variable is absent, blank or a disarming value, else the text the guard refuses to guess at. */
122
+ | { readonly armed: false; readonly malformed: string | null };
123
+
124
+ /** What the variable says, read without judgement. Pure; never throws. */
125
+ export function explicitDirSetting(
126
+ env: Record<string, string | undefined> = process.env,
127
+ ): ExplicitDirSetting {
128
+ const value = (env[REQUIRE_EXPLICIT_DIR_ENV] ?? "").trim();
129
+ if (value.length === 0) return { armed: false, malformed: null };
130
+ const word = value.toLowerCase();
131
+ if (EXPLICIT_DIR_ARMING_VALUES.includes(word)) return { armed: true, value };
132
+ if (EXPLICIT_DIR_DISARMING_VALUES.includes(word)) return { armed: false, malformed: null };
133
+ return { armed: false, malformed: value };
134
+ }
135
+
136
+ /**
137
+ * True when the guard is armed. THROWS `EXPLICIT_DIR_GUARD_MALFORMED` on a value
138
+ * it will not guess at — this is the guard's decision point, and it is exactly
139
+ * where falling open would cost a live store. A caller who wants the reading
140
+ * without the throw uses `explicitDirSetting`.
141
+ */
142
+ export function explicitDirRequired(env: Record<string, string | undefined> = process.env): boolean {
143
+ const setting = explicitDirSetting(env);
144
+ if (!setting.armed && setting.malformed !== null) {
145
+ throw new StoreError("EXPLICIT_DIR_GUARD_MALFORMED", {
146
+ guard: REQUIRE_EXPLICIT_DIR_ENV,
147
+ value: setting.malformed,
148
+ accepted: EXPLICIT_DIR_ARMING_VALUES.join("|"),
149
+ off: EXPLICIT_DIR_DISARMING_VALUES.join("|"),
150
+ });
151
+ }
152
+ return setting.armed;
153
+ }
154
+
155
+ /** The sentence for a value the guard refuses to guess at. One copy, so the two doors say the same thing. */
156
+ export function explicitDirMalformedRefusal(value: string): string {
157
+ return (
158
+ `refused: ${REQUIRE_EXPLICIT_DIR_ENV} is set to '${value}', which this will not guess at — it arms on ` +
159
+ `${EXPLICIT_DIR_ARMING_VALUES.join(", ")} and stands down on ${EXPLICIT_DIR_DISARMING_VALUES.join(", ")} ` +
160
+ "(case and surrounding whitespace ignored), and a safety guard fails closed on anything else. " +
161
+ "Unset it, set it to 1, or set it to 0."
162
+ );
163
+ }
164
+
165
+ /**
166
+ * The guard's two refusals as ONE SENTENCE, for a surface that has a reader —
167
+ * the console, the dashboard, the hook, the worker, the MCP server. `remedy` is
168
+ * that surface's OWN way of naming a store: the console has `--dir`, the hook
169
+ * has a field in the file it was pointed at, and a remedy that names a flag the
170
+ * reader does not have is worse than none (#80 review). Null for any other
171
+ * error, so a caller falls through to its usual rendering.
172
+ */
173
+ export function describeGuardRefusal(err: unknown, remedy: string): string | null {
174
+ if (isStoreError(err, "IMPLICIT_DEFAULT_DIR_REFUSED")) {
175
+ return (
176
+ `refused: ${String(err.detail["guard"])} and no store was named, so this would have opened the ` +
177
+ `default data dir, ${String(err.detail["dir"])} — on a machine with an install, somebody's live ` +
178
+ `memory. ${remedy}`
179
+ );
180
+ }
181
+ if (isStoreError(err, "EXPLICIT_DIR_GUARD_MALFORMED")) {
182
+ return explicitDirMalformedRefusal(String(err.detail["value"]));
183
+ }
184
+ return null;
185
+ }
186
+
187
+ /** The path the fallback WOULD return — so a refusal can name it without resolving it. */
188
+ export function defaultDataDir(): string {
189
+ return join(homedir(), DEFAULT_DATA_DIR_NAME, DEFAULT_STORE_SUBDIR);
190
+ }
191
+
192
+ /**
193
+ * The data directory for THIS call. Resolution order:
194
+ * 1. `COUNTERPARTS_DATA_DIR` (read now, not at import)
195
+ * 2. `~/.counterparts/store` (the base dir minus its host-adapter files) —
196
+ * unless `COUNTERPARTS_REQUIRE_EXPLICIT_DIR` is armed, which refuses it by
197
+ * name; a value that neither arms nor is blank is refused too
198
+ * (`explicitDirRequired`).
199
+ *
200
+ * `env` defaults to the process's own and is injectable for the one caller that
201
+ * carries an environment of its own (`cli/commands.ts#resolveDir`, whose tests
202
+ * pass one) — so the guard is provable without mutating `process.env`. It is
203
+ * read from THAT object only: a `run(argv, { env: {} })` is unarmed for that
204
+ * call whatever `process.env` says (`NOTES.md` 2026-09-05, the observation).
205
+ *
206
+ * The env-set case returns FIRST, before the guard is so much as read: a process
207
+ * launched with the variable (the live MCP server) runs exactly the instructions
208
+ * it ran before the guard existed — and a malformed guard value beside a named
209
+ * store is not consulted either, because the guard's only question is about
210
+ * the fallback.
211
+ */
212
+ export function dataDir(env: Record<string, string | undefined> = process.env): string {
213
+ const fromEnv = env[DATA_DIR_ENV];
214
+ if (fromEnv && fromEnv.trim().length > 0) return assertSafeDataDir(fromEnv);
215
+ const fallback = defaultDataDir();
216
+ const setting = explicitDirSetting(env);
217
+ if (setting.armed) {
218
+ throw new StoreError("IMPLICIT_DEFAULT_DIR_REFUSED", {
219
+ guard: `${REQUIRE_EXPLICIT_DIR_ENV}=${setting.value}`,
220
+ dir: fallback,
221
+ remedy: `name the store: pass dir (--dir on a command line, "dataDir" in a host configuration), or set ${DATA_DIR_ENV}`,
222
+ });
223
+ }
224
+ // Fails closed: a value this cannot read refuses here, where falling open
225
+ // would have handed back the live store.
226
+ explicitDirRequired(env);
227
+ return assertSafeDataDir(fallback);
228
+ }
229
+
230
+ /**
231
+ * Contract §5 G11: every top-level path in the data directory is classified —
232
+ * in the backup set, or on an explicit exclusion list. A new directory that is
233
+ * not listed here fails `layout.test`'s totality assertion.
234
+ *
235
+ * `match: "prefix"` covers SQLite's journal sidecars (`-journal`, `-wal`, `-shm`)
236
+ * without leaving them unclassified.
237
+ */
238
+ export interface LayoutEntry {
239
+ readonly name: string;
240
+ readonly match: "exact" | "prefix";
241
+ readonly backup: boolean;
242
+ readonly why: string;
243
+ }
244
+
245
+ export const LAYOUT: readonly LayoutEntry[] = [
246
+ {
247
+ name: DATABASE_FILE,
248
+ match: "prefix",
249
+ backup: true,
250
+ why: "Box 2 — the canonical database. The memories themselves live here since the floor (schema v6): bodies, their archived versions, and every structured field. Backed up as a database, never rebuilt.",
251
+ },
252
+ {
253
+ name: "cache",
254
+ match: "exact",
255
+ backup: false,
256
+ why: "Box 3 — rebuildable embeddings/FTS. Never backed up; its loss is a re-index.",
257
+ },
258
+ {
259
+ name: "spans",
260
+ match: "exact",
261
+ backup: true,
262
+ why: "remember/'s capture buffer: lived experience awaiting encoding; not reconstructible.",
263
+ },
264
+ {
265
+ name: "journal",
266
+ match: "exact",
267
+ // NOT BACKED UP, since 2026-09-20 (f6f7 review MAJOR-5). It was PROPOSED
268
+ // `true` — a directory the owner is invited to read should ride along with
269
+ // a copy of the store — and changed to `false` in review, inside the same
270
+ // PR, the same day: F6 never landed on master with the flag set, and a
271
+ // reader of this comment should not go looking for a window where it was.
272
+ // What the review measured is the cost the proposal would have had: every
273
+ // snapshot held every episode's words as plain greppable markdown, so a
274
+ // removal that emptied the live store byte for byte left the removed
275
+ // chapter readable in fourteen copies — and a database inside an old
276
+ // snapshot is a file somebody must know to open, while a `.md` inside one
277
+ // is a search result, a Spotlight hit, a synced folder's problem.
278
+ //
279
+ // It costs NOTHING to stop copying it, which is the whole argument: the
280
+ // files are DERIVED. The snapshot carries the rows; the first backfill pass
281
+ // on a restored store writes every file again, and `test/cli.test.ts`
282
+ // proves that on a store with more episodes than one ordinary pass's
283
+ // budget. Scar §2.11 is not in play — that scar is about losing the
284
+ // CANONICAL journal from every backup for three weeks, and this journal is
285
+ // canonical in the database.
286
+ //
287
+ // Still CLASSIFIED, which is the half of §2.11 that does apply: an
288
+ // unclassified top-level path refuses the store at open, and
289
+ // `snapshots.ts#looksCopied` keys on classification rather than on this
290
+ // flag, so rotation of copies already on disk is unaffected. CONTRACT §5
291
+ // G11 says that in its own words now — classified and backed up are two
292
+ // questions, and this entry is the example.
293
+ backup: false,
294
+ why: "The counterpart's diary, ALSO written as markdown files as each chapter lands (owner, 2026-09-17 §15 item 9) — a COPY, kept because plain files outlive the system that wrote them. The chapters themselves are rows like every other memory, so this directory is derived: it is not backed up, and a restored store regenerates every file from its rows at the next boundary. Deliberately excluded rather than merely absent: copying it put removed episodes' words into every rotating snapshot as plain greppable markdown (f6f7 review MAJOR-5).",
295
+ },
296
+ {
297
+ name: "sessions",
298
+ match: "exact",
299
+ backup: false,
300
+ why: "adapters/sessions.ts — the live-session registry a host's hooks leave for its tools, plus the notes one process leaves another inside it: adapters/expansions.ts' handle log and associate/pending.ts' co-activation deltas (sessions/association/). Host state, not memory: no content, and its loss costs a lazy bind or one pass's reinforcement, never a memory. New state of that kind goes INSIDE this directory rather than beside it, because `assertLayout()` runs in the store's constructor and a store opened by code that predates the name would refuse to open at all.",
301
+ },
302
+ ];
303
+
304
+ /**
305
+ * The ONE database sidecar that holds no content of its own: the `-shm`, WAL's
306
+ * shared index, which every connection writes read-marks into — a read-only one
307
+ * included. The suites that hash a store directory and mean "nothing wrote"
308
+ * skip this and nothing else (2026-09-18, when box 2 and box 3 went to WAL).
309
+ *
310
+ * **The `-wal` is deliberately not here.** Committed pages live in it until a
311
+ * checkpoint moves them into the file, so a write that landed since the last
312
+ * checkpoint is IN the `-wal` and nowhere else; a hash that skipped it would
313
+ * pass over exactly the write it exists to catch. **Nor is the `-journal`**:
314
+ * one beside the database means a rollback-mode writer is mid-transaction, and
315
+ * during the changeover that writer is a process on the build before this one —
316
+ * which is a thing those suites should see, not skip.
317
+ *
318
+ * `classifyTopLevel` covers all three by prefix. That is a different question,
319
+ * about what the layout allows.
320
+ */
321
+ export function isDatabaseSidecar(name: string): boolean {
322
+ return name.endsWith("-shm");
323
+ }
324
+
325
+ export function classifyTopLevel(name: string): LayoutEntry | undefined {
326
+ return LAYOUT.find((e) =>
327
+ e.match === "exact" ? e.name === name : name.startsWith(e.name),
328
+ );
329
+ }
330
+
331
+ /** Throws on the first unclassified top-level entry (contract §5 G11). */
332
+ export function assertLayoutClassified(names: readonly string[]): void {
333
+ for (const name of names) {
334
+ if (!classifyTopLevel(name)) {
335
+ throw new StoreError("LAYOUT_UNCLASSIFIED", { name });
336
+ }
337
+ }
338
+ }
339
+
340
+ /**
341
+ * Two boxes, two files. There is nothing else to address.
342
+ *
343
+ * `prose`, `proseKind`, `proseFile`, `versions`, `versionsFor`, `versionFile`
344
+ * and `tmp` went with the floor (schema v6), along with `PROSE_DIR`, `stored.*`,
345
+ * `resolveStoredPath`, `relativizeStoredPath` and `isCanonicalRelativePath` —
346
+ * the placement rules that existed to keep a store self-contained while its
347
+ * rows named files (§5 G15, finding I22, and four review rounds of edge cases
348
+ * about blank pointers, absolute pre-v5 rows and `../ESCAPE/...`).
349
+ *
350
+ * The PROPERTY they defended survives and is now structural rather than
351
+ * enforced: a row IS its memory, so a copied store cannot read or delete
352
+ * another store's words, because there are no words outside the database to
353
+ * reach. `test/store-portable.test.ts` still proves it, with the mechanism gone.
354
+ *
355
+ * `tools/parallel/legacy-paths.ts` keeps the two resolvers, for the read-only
356
+ * instruments that still read the owner's pre-rows store.
357
+ */
358
+ export const paths = {
359
+ operational: (dir: string) => join(dir, DATABASE_FILE),
360
+ cacheDir: (dir: string) => join(dir, "cache"),
361
+ cache: (dir: string) => join(dir, "cache", "cache.sqlite"),
362
+ } as const;
363
+
364
+ /**
365
+ * THE PRE-ROWS MARKERS — what a store written before the floor leaves at its
366
+ * top level, and the evidence `STORE_PRE_ROWS` refuses on (`store/index.ts`).
367
+ *
368
+ * The FILENAME is the evidence, deliberately, rather than the schema version
369
+ * inside the database. Reading the version would mean OPENING the old file, and
370
+ * since F1 the owner's live store is in WAL: if that open were the last
371
+ * connection, closing it checkpoints and removes the `-wal`, so the act of
372
+ * asking would move the bytes of the very store the refusal exists to leave
373
+ * untouched. A directory holding any of these three was written by a build that
374
+ * kept its memories in files, and that is all the refusal needs to know.
375
+ *
376
+ * All three, not just the database: a store whose database was moved or deleted
377
+ * by hand still has ~16,000 prose files in it, and minting a blank v6 store on
378
+ * top of them would bury the one copy of those words.
379
+ */
380
+ export const PRE_ROWS_MARKERS: readonly string[] = ["operational.sqlite", "prose", "versions"];
381
+
382
+ /** The tag whose build still opens a pre-rows store. A git ref, so every
383
+ * sentence that carries it says what to do with it. */
384
+ export const PRE_ROWS_READABLE_BY = "floor/v5-last";
385
+
386
+ /**
387
+ * EVERY pre-rows name present in `dir`, sidecars included — not just the first.
388
+ *
389
+ * Two reasons it is a sweep rather than a `.find`. A refusal that says
390
+ * `found: "operational.sqlite"` and never mentions the 16,000 files under
391
+ * `prose/` has named the least interesting half (review A, NIT-1). And a
392
+ * directory whose main database was moved by hand, leaving only
393
+ * `operational.sqlite-wal` / `-shm`, was not seen as pre-rows at all: the
394
+ * constructor mkdir'd `cache/`, `openOperational` minted `counterparts.sqlite`,
395
+ * and only then did `assertLayout` refuse — on the wrong evidence, after the
396
+ * one write that landed in a pre-rows directory ahead of the refusal (A,
397
+ * MINOR-4).
398
+ *
399
+ * The exact `existsSync` pass stays exactly as it was, because it is what
400
+ * catches `Prose/` and `OPERATIONAL.SQLITE` on a case-insensitive filesystem
401
+ * (measured); the sidecar sweep is added BESIDE it. A stale
402
+ * `operational.sqlite-journal` from a pre-F1 store is caught too.
403
+ *
404
+ * Reads names only. Nothing is opened.
405
+ */
406
+ export function preRowsMarkersIn(dir: string): string[] {
407
+ const found = PRE_ROWS_MARKERS.filter((name) => existsSync(join(dir, name)));
408
+ let entries: string[] = [];
409
+ try {
410
+ entries = readdirSync(dir);
411
+ } catch {
412
+ return found;
413
+ }
414
+ for (const entry of entries) {
415
+ const lower = entry.toLowerCase();
416
+ if (!PRE_ROWS_MARKERS.some((m) => lower.startsWith(`${m}-`))) continue;
417
+ if (!found.includes(entry)) found.push(entry);
418
+ }
419
+ return found;
420
+ }
421
+
422
+ /**
423
+ * Are the pre-rows directories EMPTY — i.e. did an old build just mkdir them,
424
+ * or is this a store with words in it?
425
+ *
426
+ * This is the question that decides whether a remedy may say "delete these".
427
+ * The PRE-FLOOR build's `Store` constructor — the one tagged `floor/v5-last`,
428
+ * and what a stale worktree or an un-deployed checkout still runs — mkdirs
429
+ * `prose/`, `versions/` and `tmp/` before
430
+ * it reaches `assertLayout()`, so ONE old-build hook on a v6 store leaves all
431
+ * three behind EMPTY — and from then on this build refuses its own store (A,
432
+ * MAJOR-1). Removing them is exactly right there, and a catastrophe beside a
433
+ * real v5 store somebody has hand-copied a `counterparts.sqlite` into.
434
+ *
435
+ * **It answers by LISTING, never by opening.** Reviewer A's measurement — that
436
+ * nothing here opens the old database — is the promise this whole door rests
437
+ * on, and a row count would break it: on a post-F1 store most of the owner's
438
+ * recent words are in the `-wal`, and an open-and-close can checkpoint it away.
439
+ * An empty `prose/` is a sufficient answer and costs no handle.
440
+ */
441
+ export function preRowsLeftoversAreEmpty(dir: string): boolean {
442
+ const holdsAFile = (at: string): boolean => {
443
+ let names: string[];
444
+ try {
445
+ names = readdirSync(at);
446
+ } catch {
447
+ return false;
448
+ }
449
+ for (const name of names) {
450
+ const full = join(at, name);
451
+ try {
452
+ if (statSync(full).isDirectory() ? holdsAFile(full) : true) return true;
453
+ } catch {
454
+ /* vanished underneath the walk; it is not a file we can see */
455
+ }
456
+ }
457
+ return false;
458
+ };
459
+ return !["prose", "versions"].some((d) => holdsAFile(join(dir, d)));
460
+ }
461
+
462
+ /**
463
+ * The pre-rows refusal as ONE SENTENCE a person can act on, for any surface
464
+ * that has a reader — the console, the hook, doctor, the dashboard.
465
+ *
466
+ * It exists for the same reason `describeGuardRefusal` does, and it is the same
467
+ * shape: `remedy` is the surface's OWN way of naming a store. Before it, every
468
+ * console door printed the bare code and a JSON blob, and the one instruction
469
+ * the owner was given — "Run: counterparts doctor" — printed the same blob
470
+ * (A, MINOR-3). Null for any other error, so a caller falls through.
471
+ */
472
+ export function describePreRowsRefusal(err: unknown, remedy: string): string | null {
473
+ if (!isStoreError(err, "STORE_PRE_ROWS")) return null;
474
+ const detail = err.detail;
475
+ const dir = typeof detail["dir"] === "string" ? detail["dir"] : String(detail["path"] ?? "");
476
+ const found = String(detail["found"] ?? "");
477
+ const own = typeof detail["remedy"] === "string" ? detail["remedy"] : null;
478
+ // WHAT `found` IS depends on WHICH lock refused. The filename door names the
479
+ // old names it saw; the SHAPE door names the schema version it read out of a
480
+ // database already wearing the current name, and rendering that as a filename
481
+ // printed "it keeps its memories in files (5)" (review f5c, NIT-1).
482
+ const shape = detail["reason"] === "no-body-column";
483
+ const what = shape
484
+ ? `it is a schema v${found} database under this build's own filename`
485
+ : `it keeps its memories in files (${found})`;
486
+ return (
487
+ `refused: ${dir} was written before this build's floor — ${what}, ` +
488
+ `and this build keeps them in the database. NOTHING WAS TOUCHED. ` +
489
+ (own ??
490
+ `The build that reads it is tagged ${PRE_ROWS_READABLE_BY}: check it out ` +
491
+ `(git checkout ${PRE_ROWS_READABLE_BY}) to open this store, or name a store this build wrote.`) +
492
+ ` ${remedy}`
493
+ );
494
+ }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * The document shape a memory is READ as, and the two guards that keep it
3
+ * honest on the way into a row.
4
+ *
5
+ * Until the floor (schema v6) this file was box 1: a markdown parser, a stager,
6
+ * an archiver, and ~16,000 files under `prose/`. The memory is now the ROW —
7
+ * `memories.title`, `.body`, `.meta` — so the parser has nothing to parse and
8
+ * the stager nothing to stage. `ProseDoc` survives unchanged as the read shape,
9
+ * which is the seam that let the whole brain layer above `store/` not notice
10
+ * the floor move; `render.ts` keeps the markdown, one direction only, as the
11
+ * EXPORT format. Nothing reads it back.
12
+ *
13
+ * What is left here is what the row still needs:
14
+ *
15
+ * - `ProseDoc` / `ProseType` / `ID_PREFIX` — the shape and the id families;
16
+ * - `hashText` — the one content-address function (contract §3);
17
+ * - `assertJsonSafe` — the G6 guard, now over the `meta` COLUMN. A function,
18
+ * an `undefined`, a symbol or a `NaN` in meta is silent data loss whether
19
+ * it is dropped on the way into a file or on the way into a TEXT column,
20
+ * and v1's named incident (a parser silently dropping tier, frequency,
21
+ * provenance and aliases on rewrite) is the reason it is checked at all.
22
+ */
23
+ import { createHash } from "node:crypto";
24
+ import { StoreError } from "./errors.js";
25
+
26
+ export type ProseType = "memory" | "episode" | "schema";
27
+ export const PROSE_TYPES: readonly ProseType[] = ["memory", "episode", "schema"];
28
+
29
+ /** Type prefix per family. Ids are immutable, never reused, type-prefixed (G2). */
30
+ export const ID_PREFIX: Record<ProseType, string> = {
31
+ memory: "mem",
32
+ episode: "epi",
33
+ schema: "sch",
34
+ };
35
+
36
+ export interface ProseDoc {
37
+ id: string;
38
+ type: ProseType;
39
+ title?: string;
40
+ /** When it happened, at stated precision: `2026`, `2026-08`, or `2026-08-25`. Never rounded. */
41
+ happenedOn?: string;
42
+ /** When it was learned (ISO date). Supersession reasoning needs it. */
43
+ learnedOn: string;
44
+ /** Which lived day it was born on — the decay clock's integer (scar E8). */
45
+ bornDay: number;
46
+ /** Unrecognized / module-specific fields. Survives the row round-trip
47
+ * untouched (G6): the column holds the JSON verbatim. */
48
+ meta: Record<string, unknown>;
49
+ /** The interpretation. This *is* the memory. */
50
+ body: string;
51
+ }
52
+
53
+ /** The one content-address function (contract §3): span, run record, body all join here. */
54
+ export function hashText(text: string): string {
55
+ return createHash("sha256").update(text, "utf8").digest("hex").slice(0, 16);
56
+ }
57
+
58
+ /**
59
+ * An id that can be a row's primary key and a filename in an export.
60
+ *
61
+ * The slash and whitespace refusal predates the floor — it kept an id from
62
+ * inventing a directory under `prose/` — and it is kept because
63
+ * `render.ts` writes `<id>.md` on the way out and because an id with a newline
64
+ * in it makes every log line ambiguous.
65
+ */
66
+ export function assertIdWellFormed(id: unknown): asserts id is string {
67
+ if (typeof id !== "string" || id.length === 0 || /\s|\//.test(id)) {
68
+ throw new StoreError("ID_MALFORMED", { id: String(id) });
69
+ }
70
+ }
71
+
72
+ /**
73
+ * `meta` as the column holds it: JSON, verbatim, refused rather than truncated
74
+ * when it cannot survive the round trip (G6, G7 — "content that could break the
75
+ * parser is rejected loudly, never truncated").
76
+ */
77
+ export function serializeMeta(meta: Record<string, unknown>, id: string): string {
78
+ // A value JSON silently DROPS (a function, undefined, a symbol) or silently
79
+ // transforms (bigint throws, NaN becomes null) is metadata loss on rewrite —
80
+ // v1's named incident. Refuse it here, before it reaches the column.
81
+ assertJsonSafe(meta, id, "meta");
82
+ try {
83
+ return JSON.stringify(meta) ?? "{}";
84
+ } catch (cause) {
85
+ throw new StoreError("PROSE_META_UNSERIALIZABLE", {
86
+ id,
87
+ reason: String((cause as Error).message ?? cause),
88
+ });
89
+ }
90
+ }
91
+
92
+ /** The column read back. A column that will not parse is a hand-edited database. */
93
+ export function parseMeta(raw: string, id: string): Record<string, unknown> {
94
+ let parsed: unknown;
95
+ try {
96
+ parsed = JSON.parse(raw);
97
+ } catch (cause) {
98
+ throw new StoreError("MEMORY_META_MALFORMED", {
99
+ id,
100
+ reason: String((cause as Error).message ?? cause),
101
+ });
102
+ }
103
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)
104
+ ? (parsed as Record<string, unknown>)
105
+ : {};
106
+ }
107
+
108
+ /** Depth-first: every value must survive JSON.stringify → JSON.parse unchanged. */
109
+ export function assertJsonSafe(value: unknown, id: string, path: string): void {
110
+ const t = typeof value;
111
+ if (value === null || t === "string" || t === "boolean") return;
112
+ if (t === "number") {
113
+ if (!Number.isFinite(value as number)) {
114
+ throw new StoreError("PROSE_META_UNSERIALIZABLE", { id, path, reason: "non-finite-number" });
115
+ }
116
+ return;
117
+ }
118
+ if (Array.isArray(value)) {
119
+ value.forEach((v, i) => assertJsonSafe(v, id, `${path}[${i}]`));
120
+ return;
121
+ }
122
+ if (t === "object") {
123
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
124
+ assertJsonSafe(v, id, `${path}.${k}`);
125
+ }
126
+ return;
127
+ }
128
+ throw new StoreError("PROSE_META_UNSERIALIZABLE", { id, path, reason: `type-${t}` });
129
+ }
130
+
131
+ /**
132
+ * The body as it will be STORED, and the rule for whether it may be stored at
133
+ * all. One function, both write doors (`put` and `revise`), so the two cannot
134
+ * come to disagree about what an empty memory is.
135
+ *
136
+ * **It NORMALISES rather than refusing** (review B, MINOR-4). A lone surrogate —
137
+ * `"lead \uD800 alone"` — round-trips through SQLite as U+FFFD, so the
138
+ * `content_hash` computed in memory from the original string stopped addressing
139
+ * the row's own body: the one input that broke the invariant the whole floor
140
+ * leans on, and the one the kill test asserts. Refusing was the other option and
141
+ * is the wrong one here: the crash-fallback sweep TRUNCATES transcript text to a
142
+ * budget and can cut a surrogate pair in half, so a refusal would silently drop
143
+ * that memory rather than store it slightly changed. Normalising keeps the
144
+ * memory and keeps `hashText(stored) === row.content_hash` total.
145
+ *
146
+ * **Whitespace-only is empty** (review B, MINOR-5). `put("")` was refused and
147
+ * `put(" ")` was not, so a memory whose body is one space could land and render
148
+ * as an empty memory everywhere — the exact thing closing `revise("")` was for.
149
+ * The MCP `note` door already refused whitespace-only at its own door; this
150
+ * makes the rule the same at every door. A NUL-only body goes the same way.
151
+ */
152
+ export function bodyForStorage(body: unknown, id: string): string {
153
+ if (typeof body !== "string") {
154
+ throw new StoreError("PROSE_BODY_INVALID", { id, reason: "not-a-string" });
155
+ }
156
+ // The round trip SQLite will perform, performed here first, so the hash is
157
+ // taken over the bytes that actually land.
158
+ const stored = Buffer.from(body, "utf8").toString("utf8");
159
+ // `\0` is whitespace to nobody, so it is named rather than trimmed: a body
160
+ // that is only NUL bytes reads as empty everywhere it is shown.
161
+ if (stored.replace(/\0/g, "").trim().length === 0) {
162
+ throw new StoreError("PROSE_BODY_INVALID", { id, reason: "empty" });
163
+ }
164
+ return stored;
165
+ }