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,275 @@
1
+ /**
2
+ * The runtime adapter: `bun:sqlite` under Bun, `node:sqlite` under Node.
3
+ *
4
+ * Deliberately the smallest interface the store needs — exec / prepare / run /
5
+ * get / all / transaction / close. Both drivers accept positional `?` parameters
6
+ * and return plain row objects, so only construction actually differs.
7
+ *
8
+ * Booleans and `undefined` are normalized here: node:sqlite rejects both, bun:sqlite
9
+ * accepts them. Normalizing at the seam keeps the two runtimes behaviorally identical.
10
+ */
11
+ import { existsSync } from "node:fs";
12
+ import { createRequire } from "node:module";
13
+ import { StoreError } from "./errors.js";
14
+
15
+ export type SqlValue = string | number | bigint | null | Uint8Array;
16
+ export type SqlParam = SqlValue | boolean | undefined;
17
+ export type Row = Record<string, SqlValue>;
18
+
19
+ export interface Statement {
20
+ run(...params: SqlParam[]): void;
21
+ get<T = Row>(...params: SqlParam[]): T | undefined;
22
+ all<T = Row>(...params: SqlParam[]): T[];
23
+ }
24
+
25
+ export interface Db {
26
+ readonly path: string;
27
+ readonly driver: "bun:sqlite" | "node:sqlite";
28
+ exec(sql: string): void;
29
+ prepare(sql: string): Statement;
30
+ run(sql: string, ...params: SqlParam[]): void;
31
+ get<T = Row>(sql: string, ...params: SqlParam[]): T | undefined;
32
+ all<T = Row>(sql: string, ...params: SqlParam[]): T[];
33
+ /** BEGIN/COMMIT at depth 0, SAVEPOINT/RELEASE when nested. Throws ⇒ rolls back. */
34
+ transaction<T>(fn: () => T): T;
35
+ close(): void;
36
+ }
37
+
38
+ interface RawStatement {
39
+ run(...p: SqlValue[]): unknown;
40
+ get(...p: SqlValue[]): unknown;
41
+ all(...p: SqlValue[]): unknown;
42
+ }
43
+ interface RawDb {
44
+ exec(sql: string): unknown;
45
+ prepare(sql: string): RawStatement;
46
+ close(): unknown;
47
+ }
48
+
49
+ const require_ = createRequire(import.meta.url);
50
+
51
+ export function runtimeIsBun(): boolean {
52
+ return typeof (globalThis as { Bun?: unknown }).Bun !== "undefined";
53
+ }
54
+
55
+ function openRaw(path: string): { raw: RawDb; driver: Db["driver"] } {
56
+ if (runtimeIsBun()) {
57
+ try {
58
+ const { Database } = require_("bun:sqlite") as {
59
+ Database: new (p: string, o?: unknown) => RawDb;
60
+ };
61
+ return { raw: new Database(path, { create: true }), driver: "bun:sqlite" };
62
+ } catch (cause) {
63
+ throw new StoreError("SQLITE_UNAVAILABLE", {
64
+ driver: "bun:sqlite",
65
+ reason: String((cause as Error).message ?? cause),
66
+ });
67
+ }
68
+ }
69
+ try {
70
+ const { DatabaseSync } = require_("node:sqlite") as {
71
+ DatabaseSync: new (p: string, o?: unknown) => RawDb;
72
+ };
73
+ return { raw: new DatabaseSync(path), driver: "node:sqlite" };
74
+ } catch (cause) {
75
+ // node:sqlite landed in Node 22 (behind a flag) and is on by default from 23.4.
76
+ // package.json declares engines.node >= 22; say so rather than failing vaguely.
77
+ throw new StoreError("SQLITE_UNAVAILABLE", {
78
+ driver: "node:sqlite",
79
+ nodeVersionFloor: "22",
80
+ running: process.versions.node,
81
+ reason: String((cause as Error).message ?? cause),
82
+ });
83
+ }
84
+ }
85
+
86
+ function norm(params: SqlParam[]): SqlValue[] {
87
+ return params.map((p) => {
88
+ if (p === undefined) return null;
89
+ if (typeof p === "boolean") return p ? 1 : 0;
90
+ return p;
91
+ });
92
+ }
93
+
94
+ /**
95
+ * How long a connection waits for someone else's write lock before giving up.
96
+ * TUNABLE.
97
+ *
98
+ * Without it SQLite fails INSTANTLY with "database is locked", which is how a
99
+ * live `counterparts backup` threw while a session held an open write
100
+ * transaction (live-verify 2026-08-25) — and CLI CONTRACT §5 G8 says a backup
101
+ * never throws. Brief contention between the console and a background worker is
102
+ * normal and should WAIT; a lock held for five seconds is a real problem and
103
+ * should still be reported rather than waited on forever.
104
+ */
105
+ export const BUSY_TIMEOUT_MS = 5000;
106
+
107
+ export interface OpenDbOptions {
108
+ /**
109
+ * Convert the file to WAL when it is not already in it. A WRITER asks; nobody
110
+ * else does.
111
+ *
112
+ * Reading the journal mode is free; CHANGING it is a write that takes the
113
+ * database's exclusive lock. An opener that converted a file it had only come
114
+ * to read would be writing at open — the observer's stand-down (contract §5),
115
+ * and the shape of the lock incident I38. So the default is false, and it is
116
+ * the default that matters: `vacuumInto` opens the SOURCE of a backup with
117
+ * this, and `adapters/cli` opens box 3 read-only for a census.
118
+ */
119
+ readonly wal?: boolean;
120
+ }
121
+
122
+ /**
123
+ * Put the file in WAL, and only if it is not there already.
124
+ *
125
+ * WAL because several processes hold this one small database open at once — the
126
+ * session hooks, a long-running MCP server, the nightly worker, the dashboard —
127
+ * and in WAL a reader no longer blocks the writer. Its permanent `-wal`/`-shm`
128
+ * sidecars are classified: `LAYOUT`'s database entry matches by PREFIX (§5 G11),
129
+ * which is why the reason NOTES §9 gave for DELETE no longer holds.
130
+ *
131
+ * THE READ COMES FIRST because the set is a write: on a store already in WAL —
132
+ * every open after the first — this statement pair touches nothing.
133
+ *
134
+ * A CONTENDED conversion is not an error, and what contention COSTS depends on
135
+ * who is holding the lock (measured, bun:sqlite 1.3):
136
+ *
137
+ * - against a WRITER (another connection inside a write transaction) the busy
138
+ * handler does not run: it fails in about a millisecond, and the open
139
+ * continues in whatever mode the file is in. The next open tries again.
140
+ * - against a READER (a shared lock) the busy handler DOES run, so the open
141
+ * WAITS for the reader and then converts. A short read costs that read; a
142
+ * reader that outlasts `BUSY_TIMEOUT_MS` costs the whole five seconds and
143
+ * leaves the file as it was.
144
+ *
145
+ * So the one-time converting open can wait, once, up to the busy timeout. Every
146
+ * open after it reads `wal` and returns without a statement. A hook must not die
147
+ * because the worker happened to be committing, and it does not.
148
+ *
149
+ * ONLY the locked case is swallowed. This statement is also the first one that
150
+ * reads the file's header, so "not a database" arrives here — and a caller that
151
+ * opens a corrupt box 3 to count its vectors has to fail closed rather than be
152
+ * handed a handle (`cli` verify --rebuild's guard).
153
+ */
154
+ function convertToWal(db: Db): void {
155
+ const current = db.get<{ journal_mode: string }>("PRAGMA journal_mode")?.journal_mode;
156
+ if (current !== undefined && current.toLowerCase() === "wal") return;
157
+ try {
158
+ db.get("PRAGMA journal_mode = WAL");
159
+ } catch (err) {
160
+ if (!isLocked(err)) throw err;
161
+ // Contended. The file keeps the mode it has, and this connection works in it.
162
+ }
163
+ }
164
+
165
+ /**
166
+ * SQLITE_BUSY / SQLITE_LOCKED, under either driver's spelling of it.
167
+ *
168
+ * Exported since H1: the hook's stand-down path asks the same question at the
169
+ * other end of the same failure — a contended database is a TRANSIENT fault, and
170
+ * it is told apart from a store that will not open at all by exactly this test.
171
+ * One copy, so the two cannot come to disagree about what "busy" looks like.
172
+ */
173
+ export function isLocked(err: unknown): boolean {
174
+ const code = (err as { code?: unknown } | null | undefined)?.code;
175
+ if (typeof code === "string" && (code.startsWith("SQLITE_BUSY") || code.startsWith("SQLITE_LOCKED"))) {
176
+ return true;
177
+ }
178
+ const message = String((err as Error)?.message ?? err);
179
+ return message.includes("database is locked") || message.includes("database table is locked");
180
+ }
181
+
182
+ /**
183
+ * The journal mode a database file is in, on its own connection — opened, read,
184
+ * closed, converting nothing. What `counterparts verify` and `doctor` print.
185
+ *
186
+ * An absent file answers `absent` rather than being CREATED by the question
187
+ * (`openDb` opens with `create: true`). The handle is read-WRITE, like every
188
+ * other handle this codebase takes: a read-only one would refuse a WAL store
189
+ * whose sidecars are missing, and turning a census into a failure to answer a
190
+ * one-word question is the wrong trade.
191
+ */
192
+ export function journalModeOf(path: string): string {
193
+ if (!existsSync(path)) return "absent";
194
+ const db = openDb(path);
195
+ try {
196
+ return db.get<{ journal_mode: string }>("PRAGMA journal_mode")?.journal_mode ?? "unknown";
197
+ } finally {
198
+ db.close();
199
+ }
200
+ }
201
+
202
+ export function openDb(path: string, opts: OpenDbOptions = {}): Db {
203
+ const { raw, driver } = openRaw(path);
204
+ let depth = 0;
205
+ let savepointSeq = 0;
206
+
207
+ const exec = (sql: string): void => {
208
+ raw.exec(sql);
209
+ };
210
+
211
+ const prepare = (sql: string): Statement => {
212
+ const st = raw.prepare(sql);
213
+ return {
214
+ run: (...p) => {
215
+ st.run(...norm(p));
216
+ },
217
+ get: <T>(...p: SqlParam[]) => (st.get(...norm(p)) ?? undefined) as T | undefined,
218
+ all: <T>(...p: SqlParam[]) => (st.all(...norm(p)) ?? []) as T[],
219
+ };
220
+ };
221
+
222
+ const db: Db = {
223
+ path,
224
+ driver,
225
+ exec,
226
+ prepare,
227
+ run: (sql, ...p) => prepare(sql).run(...p),
228
+ get: <T>(sql: string, ...p: SqlParam[]) => prepare(sql).get<T>(...p),
229
+ all: <T>(sql: string, ...p: SqlParam[]) => prepare(sql).all<T>(...p),
230
+ transaction<T>(fn: () => T): T {
231
+ const outer = depth === 0;
232
+ const name = `cp_sp_${++savepointSeq}`;
233
+ exec(outer ? "BEGIN IMMEDIATE" : `SAVEPOINT ${name}`);
234
+ depth += 1;
235
+ try {
236
+ const result = fn();
237
+ exec(outer ? "COMMIT" : `RELEASE ${name}`);
238
+ return result;
239
+ } catch (err) {
240
+ try {
241
+ if (outer) exec("ROLLBACK");
242
+ else {
243
+ exec(`ROLLBACK TO ${name}`);
244
+ exec(`RELEASE ${name}`);
245
+ }
246
+ } catch {
247
+ // A rollback that itself fails must not mask the original reason.
248
+ }
249
+ throw err;
250
+ } finally {
251
+ depth -= 1;
252
+ }
253
+ },
254
+ close: () => {
255
+ raw.close();
256
+ },
257
+ };
258
+
259
+ // FIRST, before any other statement on this connection (finding I39): every
260
+ // pragma below can contend for a lock, and without the timeout SQLite fails
261
+ // them INSTANTLY. The journal-mode statement used to run here with zero wait,
262
+ // inside another writer's commit window — which is where "database is locked"
263
+ // came from. Set on every connection, including the short-lived one
264
+ // `VACUUM INTO` opens for a backup (§5 G8, live-verify 2026-08-25).
265
+ exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
266
+ // Foreign keys are OFF by default in SQLite; referential integrity is enforced by
267
+ // the store (contract §5 G4), so turn them on before anything is written.
268
+ exec("PRAGMA foreign_keys = ON");
269
+ if (opts.wal === true) convertToWal(db);
270
+ // FULL, not WAL's usual NORMAL: that is a durability ruling for the owner to
271
+ // make, not a cleanup to make on the way past. TUNABLE — the one knob here
272
+ // that trades fsyncs for commit speed.
273
+ exec("PRAGMA synchronous = FULL");
274
+ return db;
275
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * One error type for the whole store, carrying a stable machine-readable code.
3
+ *
4
+ * Why a code and not a message: contract §5 G10 — telemetry is content-by-reference,
5
+ * "error messages included". A code plus ids/counts can be logged; a message that
6
+ * quotes prose cannot. Callers (and tests) assert the reason, never the prose.
7
+ */
8
+ export type StoreErrorCode =
9
+ | "OBSERVER_REFUSED"
10
+ | "DATA_DIR_FORBIDDEN"
11
+ /**
12
+ * `COUNTERPARTS_REQUIRE_EXPLICIT_DIR=1` is set and nothing named a data dir —
13
+ * no `dir`, no `COUNTERPARTS_DATA_DIR` — so `dataDir()` refused to hand back
14
+ * `~/.counterparts/store` (`paths.ts`). `detail` carries `{ guard, dir, remedy }`:
15
+ * the variable that refused, the directory it would have opened, and how to
16
+ * name one. On the owner's machine that directory is his live memory, and on
17
+ * 2026-09-05 a caller reached it by passing the wrong option name.
18
+ */
19
+ | "IMPLICIT_DEFAULT_DIR_REFUSED"
20
+ /**
21
+ * `COUNTERPARTS_REQUIRE_EXPLICIT_DIR` holds a value the guard will not guess
22
+ * at — not blank, not one of `EXPLICIT_DIR_ARMING_VALUES`. Thrown at the
23
+ * guard's decision point instead of falling open: the #80 review measured
24
+ * `=true`, `=yes`, `=on` and `= 1` all silently resolving the default, which
25
+ * is the one failure direction a safety guard may not have. `detail` carries
26
+ * `{ guard, value, accepted }`.
27
+ */
28
+ | "EXPLICIT_DIR_GUARD_MALFORMED"
29
+ /**
30
+ * The row handed to a read is not the row that was asked for
31
+ * (`walk-seam.ts`). Kept from the file floor, where a prose file and its row
32
+ * could disagree about which memory it was; it is now the guard on the
33
+ * caller-supplied `row` a walking read takes to save a second lookup.
34
+ */
35
+ | "PROSE_PAYLOAD_MISMATCH"
36
+ | "PROSE_BODY_INVALID"
37
+ | "PROSE_META_UNSERIALIZABLE"
38
+ /**
39
+ * The `meta` COLUMN does not parse as JSON. Only a hand-edited database can
40
+ * hold one — every writer goes through `serializeMeta`.
41
+ */
42
+ | "MEMORY_META_MALFORMED"
43
+ /**
44
+ * **The row is there and its words are not**: `body` is empty while
45
+ * `content_hash` still names the words that were in it.
46
+ *
47
+ * It replaces `PROSE_FILE_MISSING`, which said the same thing about a file.
48
+ * The two halves of the test are the point: a blank body BESIDE a blank hash
49
+ * is a tombstone — the owner removed this, and the deny-list answers by name
50
+ * (`REMOVED`) — while a blank body beside a real hash is a row whose words
51
+ * went missing underneath the store. No write path in this module produces
52
+ * it; `put` and `revise` both refuse an empty body.
53
+ *
54
+ * `detail` carries `{ id }` and no path, because on this floor there is no
55
+ * file to restore. Doctor's Store-open finding already has the no-path arm.
56
+ */
57
+ | "MEMORY_BODY_MISSING"
58
+ | "ID_MALFORMED"
59
+ | "ID_UNKNOWN"
60
+ | "ID_CYCLE"
61
+ | "ID_CHAIN_TOO_DEEP"
62
+ | "ID_DANGLING"
63
+ | "ID_TAKEN"
64
+ /**
65
+ * The owner removed this id. The deny-list answering before the prose does —
66
+ * a NAMED refusal, never the ENOENT of a chased file (§16 G12).
67
+ * `detail` carries `{ id, by: "owner" }`: the code is the wire shape every
68
+ * consumer switches on, the actor is the story it tells.
69
+ */
70
+ | "REMOVED"
71
+ /** A chase was attempted on an id no removal record has taken dark (§16 G10). */
72
+ | "REMOVAL_NOT_DARK"
73
+ /** The owner-op capability was never granted for this store. */
74
+ | "OWNER_OP_UNGRANTED"
75
+ /**
76
+ * A restore was attempted on a row the dedup pass did not archive. The
77
+ * un-archive door exists to undo ONE thing — `archived_reason: "merged"` —
78
+ * and a door that also un-archives prunes, revisions and removals would be
79
+ * the general resurrection verb the store deliberately does not have.
80
+ */
81
+ | "UNMERGE_NOT_A_MERGE"
82
+ /**
83
+ * The row has a successor. Restoring it would put two live versions in one
84
+ * revision chain, which is the state `resolve` exists to make impossible.
85
+ */
86
+ | "UNMERGE_SUPERSEDED"
87
+ | "VERSION_UNKNOWN"
88
+ | "CLOCK_BACKWARDS"
89
+ /** An instrument opened a store that does not exist yet, or is a schema behind:
90
+ * initializing it would be writing at open, which an observer may not do. */
91
+ | "STORE_UNINITIALIZED"
92
+ /** A store written by a NEWER build: refused rather than stamped backwards. */
93
+ | "SCHEMA_AHEAD"
94
+ /**
95
+ * **A store written before the floor**: `operational.sqlite`, `prose/` or
96
+ * `versions/` is at its top level, so its words are in ~16,000 markdown files
97
+ * this build has no code to read (schema v6, 2026-09-20).
98
+ *
99
+ * Refused BY NAME, in `Store`'s constructor, before any transaction and
100
+ * before any directory is created — because the alternative is the one thing
101
+ * in this rebuild that could make a store unreadable. `openOperational`
102
+ * migrates anything below `SCHEMA_VERSION`; reaching it with a v5 store would
103
+ * have added `body` NULL to every row, orphaned every prose file, stamped the
104
+ * store v6, and left it unreadable by the build that CAN read it too.
105
+ *
106
+ * There is no migration, on purpose (owner ruling 6, 2026-09-18: the cut-over
107
+ * carries nothing and he starts as a new user). `detail` carries
108
+ * `{ dir, found, expected, readableBy }` — `readableBy` names the tag whose
109
+ * build still opens it, so the sentence ends in a thing to do rather than in
110
+ * a dead end. The old store is untouched and stays on disk.
111
+ */
112
+ | "STORE_PRE_ROWS"
113
+ | "SQLITE_UNAVAILABLE"
114
+ | "LAYOUT_UNCLASSIFIED";
115
+
116
+ export class StoreError extends Error {
117
+ readonly code: StoreErrorCode;
118
+ /** Ids / counts only. Never body text (contract §5 G10). */
119
+ readonly detail: Readonly<Record<string, string | number | boolean | null>>;
120
+
121
+ constructor(
122
+ code: StoreErrorCode,
123
+ detail: Record<string, string | number | boolean | null> = {},
124
+ ) {
125
+ super(`${code} ${JSON.stringify(detail)}`);
126
+ this.name = "StoreError";
127
+ this.code = code;
128
+ this.detail = detail;
129
+ }
130
+ }
131
+
132
+ export function isStoreError(e: unknown, code?: StoreErrorCode): e is StoreError {
133
+ return e instanceof StoreError && (code === undefined || e.code === code);
134
+ }