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,610 @@
1
+ /**
2
+ * Box 2 — the canonical operational database. One small SQLite file holding the
3
+ * physics fields, the band cache, superseded-version rows, edges, prospective
4
+ * entries, the removal record, and meta/clock state.
5
+ *
6
+ * Canonical, NOT a cache: it is backed up as a database and never "rebuilt". The
7
+ * rebuild contract belongs to box 3 alone (contract §4, owner rescope 1).
8
+ *
9
+ * Every multi-row mutation is wrapped in a transaction by the seam in `index.ts`.
10
+ */
11
+ import type { Band, Kind, MemoryPhysics, Salience } from "../types.js";
12
+ import type { Db, Row } from "./db.js";
13
+ import { openDb } from "./db.js";
14
+ import { StoreError } from "./errors.js";
15
+ import { PRE_ROWS_READABLE_BY } from "./paths.js";
16
+ import type { ProseType } from "./prose.js";
17
+
18
+ /**
19
+ * Bumped to 6 (2026-09-20, the floor): **the memory IS the row.** `title`,
20
+ * `body`, `meta` and `confidential` are columns on `memories`; a version row
21
+ * carries its own `title`/`body`/`meta` plus the two provenance dates; and
22
+ * `memories.prose_path` and `versions.path` are GONE, because there are no
23
+ * files for them to name. Markdown became an export (`render.ts`).
24
+ *
25
+ * **There is no migration from v5, and there must not be one.** A v5 store's
26
+ * bodies are ~16,000 markdown files this build cannot see; adding `body` through
27
+ * `ADDED_COLUMNS` would "migrate" the owner's live memory into a store with
28
+ * every body NULL, every prose file orphaned, stamped v6 — and unreadable by the
29
+ * old build too. So a pre-rows store is refused BY NAME, before any transaction
30
+ * and before any directory is created, in `Store`'s constructor
31
+ * (`STORE_PRE_ROWS`). The cut-over carries nothing: the owner starts blank
32
+ * (ruling 6, 2026-09-18), and the old store stays on disk, byte-identical.
33
+ *
34
+ * Version 5 (2026-09-05, finding I22) made the two path columns store-relative;
35
+ * both columns are gone with this bump and the conversion with them. Version 4
36
+ * (2026-08-29, the mint-source doctrine) added `source` + three `origin_*`
37
+ * columns on `memories`. Version 3 was the box-2 chase (`removal_tombstone`);
38
+ * version 2 was SEAMS items B + K (`gate_session` and `events`).
39
+ *
40
+ * Migration is still ADDITIVE and idempotent for whatever comes after v6: the
41
+ * DDL below is `CREATE TABLE IF NOT EXISTS`, and columns added after a table
42
+ * first shipped live in `ADDED_COLUMNS`, applied by `ensureAddedColumns` — a
43
+ * `pragma table_info` check, then `ALTER TABLE ADD COLUMN` for whatever is
44
+ * missing, inside the same one-transaction migrate-at-open. A fresh open and a
45
+ * migrated open MUST converge on the identical schema; a test asserts
46
+ * table_info equality.
47
+ */
48
+ export const SCHEMA_VERSION = 6;
49
+ /**
50
+ * The oldest schema an OBSERVER may open without a migration having run.
51
+ *
52
+ * v5 earned a floor below itself because its only change was the SPELLING of
53
+ * two path columns, which every v5 reader resolved both ways. v6 has no such
54
+ * exemption and cannot have one: a v5 store keeps its words in files this build
55
+ * has no code to read, so an instrument opening one would report an empty store
56
+ * rather than an unreadable one. The floor is therefore the version itself, and
57
+ * the refusal a reader actually meets is `STORE_PRE_ROWS`, which names the last
58
+ * build that CAN read it (`floor/v5-last`) instead of asking for a migration
59
+ * that does not exist.
60
+ */
61
+ export const OBSERVER_READ_FLOOR = 6;
62
+ /** Retention for superseded-version rows, in LIVED days. TUNABLE (module-map ruling 2).
63
+ *
64
+ * Owner ruling 1, 2026-09-18: the prune STAYS, at 90. It now deletes the words
65
+ * themselves rather than a note about a file — his steer was simple, elegant
66
+ * working-memory mechanics over keeping everything, and losing some history
67
+ * after a month or two is an acceptable price. Our own store sets it high for
68
+ * debugging. `store/NOTES.md` carries what changed underneath the number. */
69
+ export const DEFAULT_RETENTION_DAYS = 90;
70
+
71
+ /**
72
+ * THE TOMBSTONE SHAPE — what a chased row looks like once the owner-op seam has
73
+ * blanked it (`owner-op-seam.ts#chaseRemoved`).
74
+ *
75
+ * It was "the pointers are blank" while the words were in a file; now the words
76
+ * are the columns, so it is the columns that are blanked, and the pair is the
77
+ * predicate: an empty body AND an empty content hash. Both halves matter. A row
78
+ * whose body is empty while the hash still names words that were there is NOT a
79
+ * tombstone — it is a row whose words went missing underneath the store, which
80
+ * is the `MEMORY_BODY_MISSING` fault, and reading the two as one condition would
81
+ * turn a disk event into a silent "the owner removed this".
82
+ *
83
+ * Spelled once, here, because three modules ask it: the store's own reads, the
84
+ * console's removal read-back, and `schemas/index.ts`, whose skip is what keeps
85
+ * a session starting after a removal (#139).
86
+ */
87
+ export function rowTombstoned(row: Pick<MemoryRow, "body" | "content_hash">): boolean {
88
+ return row.body === "" && row.content_hash === "";
89
+ }
90
+
91
+ const DDL: readonly string[] = [
92
+ `CREATE TABLE IF NOT EXISTS meta (
93
+ key TEXT PRIMARY KEY,
94
+ value TEXT NOT NULL
95
+ )`,
96
+ `CREATE TABLE IF NOT EXISTS memories (
97
+ id TEXT PRIMARY KEY,
98
+ type TEXT NOT NULL,
99
+ kind TEXT NOT NULL,
100
+ band TEXT NOT NULL,
101
+ band_day INTEGER NOT NULL,
102
+ novelty REAL,
103
+ relevance REAL NOT NULL,
104
+ emotional REAL NOT NULL,
105
+ predictive REAL NOT NULL,
106
+ claimed REAL,
107
+ birth_day INTEGER NOT NULL,
108
+ uses REAL NOT NULL DEFAULT 0,
109
+ last_used_day INTEGER NOT NULL,
110
+ reinforced_days INTEGER NOT NULL DEFAULT 0,
111
+ consolidated INTEGER NOT NULL DEFAULT 0,
112
+ promoted_identity INTEGER NOT NULL DEFAULT 0,
113
+ protected INTEGER NOT NULL DEFAULT 0,
114
+ pressure REAL NOT NULL DEFAULT 0,
115
+ last_challenged_day INTEGER,
116
+ archived INTEGER NOT NULL DEFAULT 0,
117
+ archived_reason TEXT,
118
+ superseded_by TEXT REFERENCES memories(id),
119
+ revision INTEGER NOT NULL DEFAULT 0,
120
+ content_hash TEXT NOT NULL,
121
+ learned_on TEXT NOT NULL,
122
+ happened_on TEXT,
123
+ source TEXT,
124
+ origin_session TEXT,
125
+ origin_scope TEXT,
126
+ origin_ref TEXT,
127
+ -- v6: the memory itself. prose_path is gone; there is no file.
128
+ title TEXT,
129
+ body TEXT NOT NULL,
130
+ -- The payload's meta, VERBATIM JSON. One column, not columns: 28 distinct
131
+ -- keys are in use across src/ and tools/, the set is open, and contract §3's
132
+ -- "unrecognized fields survive parse -> serialize untouched" (G6, v1's named
133
+ -- incident) is satisfied for free by storing the text as given.
134
+ meta TEXT NOT NULL DEFAULT '{}',
135
+ -- The one key promoted OUT of that JSON, because it is a GATE: a gate that
136
+ -- must parse JSON on every read is a gate that will one day fail open
137
+ -- (confidentialByMeta, the one truth table, computes it at every write).
138
+ confidential INTEGER NOT NULL DEFAULT 0
139
+ )`,
140
+ `CREATE INDEX IF NOT EXISTS memories_band ON memories (band, archived)`,
141
+ `CREATE INDEX IF NOT EXISTS memories_kind ON memories (kind, archived)`,
142
+ `CREATE TABLE IF NOT EXISTS versions (
143
+ memory_id TEXT NOT NULL REFERENCES memories(id),
144
+ seq INTEGER NOT NULL,
145
+ reason TEXT NOT NULL,
146
+ version_day INTEGER NOT NULL,
147
+ archived_at INTEGER NOT NULL,
148
+ content_hash TEXT NOT NULL,
149
+ successor_id TEXT REFERENCES memories(id),
150
+ -- v6: the archived words themselves, where path used to name a file.
151
+ title TEXT,
152
+ body TEXT NOT NULL,
153
+ meta TEXT NOT NULL DEFAULT '{}',
154
+ -- The two PROVENANCE dates as they stood in this version. Not in the floor
155
+ -- plan; added because the code disagreed with it. revise({learnedOn}) is
156
+ -- a change to canonical content and keeps its prior version like any other
157
+ -- (see index.ts#revise), and with the dates taken from the LIVE row instead a
158
+ -- corrected date would have silently rewritten every version behind it.
159
+ learned_on TEXT NOT NULL DEFAULT '',
160
+ happened_on TEXT,
161
+ PRIMARY KEY (memory_id, seq)
162
+ )`,
163
+ `CREATE TABLE IF NOT EXISTS edges (
164
+ src TEXT NOT NULL REFERENCES memories(id),
165
+ dst TEXT NOT NULL REFERENCES memories(id),
166
+ weight REAL NOT NULL,
167
+ last_day INTEGER NOT NULL,
168
+ PRIMARY KEY (src, dst)
169
+ )`,
170
+ `CREATE TABLE IF NOT EXISTS prospective (
171
+ memory_id TEXT NOT NULL REFERENCES memories(id),
172
+ window_key TEXT NOT NULL,
173
+ event_date TEXT NOT NULL,
174
+ precision TEXT NOT NULL,
175
+ state TEXT NOT NULL,
176
+ fires INTEGER NOT NULL DEFAULT 0,
177
+ last_fired_day INTEGER,
178
+ PRIMARY KEY (memory_id, window_key)
179
+ )`,
180
+ // SEAMS item B — per-session gate state, ONE ROW PER RECORD.
181
+ //
182
+ // It replaces `recall/`'s `meta` row at `recall.gate.<sessionId>`, which was a
183
+ // JSON document read-modify-written by two writers (a turn's `recall()` and a
184
+ // late `resolveUse()` from the boundary, in different processes) — scar §2.1's
185
+ // exact shape, arriving inside a transactional database because the transaction
186
+ // was around the wrong span. A row per record means a late writer inserts ITS
187
+ // record and can no longer drop anybody else's.
188
+ //
189
+ // `kind` is open on purpose: `surfaced` and `credited` are recall's, `window` is
190
+ // where prospective's offered-window keys land (prospective/INTERFACE-GAPS.md §3
191
+ // — brake 3 of four, currently in-process), and `scalar` carries the row-level
192
+ // fields (turn counter, refractory, carried cues) that are not per-memory.
193
+ `CREATE TABLE IF NOT EXISTS gate_session (
194
+ session_id TEXT NOT NULL,
195
+ kind TEXT NOT NULL,
196
+ ref TEXT NOT NULL,
197
+ turn INTEGER NOT NULL,
198
+ tier TEXT,
199
+ trains INTEGER,
200
+ value TEXT,
201
+ last_day INTEGER NOT NULL,
202
+ PRIMARY KEY (session_id, kind, ref)
203
+ )`,
204
+ `CREATE INDEX IF NOT EXISTS gate_session_day ON gate_session (last_day)`,
205
+ // SEAMS item K — the durable event log.
206
+ //
207
+ // `schemas/`'s revision story kept its pressure increments in an in-memory ring:
208
+ // the pressure number survived a restart and the story of how it got there did
209
+ // not (schemas/INTERFACE-GAPS.md §1), and constitution line 16 says the owner
210
+ // can see what changed and why. `sleep/`'s prune/promotion/merge records have the
211
+ // same shape (sleep/INTERFACE-GAPS.md §3).
212
+ //
213
+ // `dedup_key` is what reconciles an APPEND-ONLY log with sleep's §5 G3 replay
214
+ // idempotence: a record that must land at most once ever carries one, and the
215
+ // partial unique index makes the second append a no-op. Telemetry passes null
216
+ // (SQLite treats NULLs as distinct), so ordinary increments still accumulate.
217
+ //
218
+ // Payload is content-BY-REFERENCE: ids, hashes, counts, scores. Never body text.
219
+ // memory_id/ref is deliberately NOT a foreign key — a record outlives its row.
220
+ `CREATE TABLE IF NOT EXISTS events (
221
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
222
+ at INTEGER NOT NULL,
223
+ day INTEGER NOT NULL,
224
+ name TEXT NOT NULL,
225
+ ref TEXT,
226
+ dedup_key TEXT,
227
+ payload TEXT
228
+ )`,
229
+ `CREATE UNIQUE INDEX IF NOT EXISTS events_dedup ON events (dedup_key) WHERE dedup_key IS NOT NULL`,
230
+ `CREATE INDEX IF NOT EXISTS events_name ON events (name, ref)`,
231
+ `CREATE INDEX IF NOT EXISTS events_day ON events (day)`,
232
+ // The removal record. Append-only, canonical, and deliberately carries NO body and
233
+ // NO content hash (§16 G9: hashing low-entropy content would leak what was removed).
234
+ // memory_id is deliberately NOT a foreign key — the record must outlive the row.
235
+ `CREATE TABLE IF NOT EXISTS removal_record (
236
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
237
+ memory_id TEXT NOT NULL,
238
+ stage TEXT NOT NULL,
239
+ at INTEGER NOT NULL,
240
+ actor TEXT NOT NULL,
241
+ reason TEXT
242
+ )`,
243
+ // What the chase leaves behind: the skeleton of a removed memory, so that
244
+ // "everything permanent is enumerable and inspectable" survives the one
245
+ // operation that ends permanence (scar §2.19 from the other side — a removed
246
+ // protected element must show as `[removed]`, never vanish from the list).
247
+ //
248
+ // Same content rule as the record itself (§16 G9): ids, flags, counts and a
249
+ // timestamp. NO title, NO body, NO content hash — a hash of low-entropy
250
+ // content is brute-forceable, which would make the tombstone a leak of the
251
+ // thing it marks. `superseded_by` is kept because an id is an address, not
252
+ // content, and a successor's lineage must not dangle.
253
+ //
254
+ // Deliberately NOT foreign-keyed: the tombstone outlives the row it describes.
255
+ `CREATE TABLE IF NOT EXISTS removal_tombstone (
256
+ memory_id TEXT PRIMARY KEY,
257
+ type TEXT NOT NULL,
258
+ kind TEXT NOT NULL,
259
+ band TEXT NOT NULL,
260
+ protected INTEGER NOT NULL,
261
+ promoted_identity INTEGER NOT NULL,
262
+ superseded_by TEXT,
263
+ versions INTEGER NOT NULL,
264
+ edges INTEGER NOT NULL,
265
+ prospective INTEGER NOT NULL,
266
+ gate_rows INTEGER NOT NULL,
267
+ at INTEGER NOT NULL
268
+ )`,
269
+ ];
270
+
271
+ export interface MemoryRow extends Row {
272
+ id: string;
273
+ type: ProseType;
274
+ kind: Kind;
275
+ band: Band;
276
+ band_day: number;
277
+ novelty: number | null;
278
+ relevance: number;
279
+ emotional: number;
280
+ predictive: number;
281
+ claimed: number | null;
282
+ birth_day: number;
283
+ uses: number;
284
+ last_used_day: number;
285
+ reinforced_days: number;
286
+ consolidated: number;
287
+ promoted_identity: number;
288
+ protected: number;
289
+ pressure: number;
290
+ last_challenged_day: number | null;
291
+ archived: number;
292
+ archived_reason: string | null;
293
+ superseded_by: string | null;
294
+ revision: number;
295
+ content_hash: string;
296
+ learned_on: string;
297
+ happened_on: string | null;
298
+ /** Who minted this memory (engine-set at the seam; mint.ts `ClaimChannel`,
299
+ * plus "migrated" from the v1 importer). NULL = a pre-v4 row whose
300
+ * provenance was never recorded — rendered "unrecorded", never defaulted. */
301
+ source: string | null;
302
+ origin_session: string | null;
303
+ origin_scope: string | null;
304
+ /** The proposal / trace id this memory was minted from. Ids only, never text. */
305
+ origin_ref: string | null;
306
+ /** v6: the memory itself, and the two fields that travel with it. */
307
+ title: string | null;
308
+ body: string;
309
+ /** `ProseDoc.meta` as verbatim JSON (G6). Parsed once, at the read seam. */
310
+ meta: string;
311
+ /** `confidentialByMeta(meta)` at the last write. A column, never re-derived
312
+ * per call site: the confidentiality class is a gate (CONTRACT §5 G13). */
313
+ confidential: number;
314
+ }
315
+
316
+ export interface VersionRow extends Row {
317
+ memory_id: string;
318
+ seq: number;
319
+ reason: string;
320
+ version_day: number;
321
+ archived_at: number;
322
+ content_hash: string;
323
+ successor_id: string | null;
324
+ title: string | null;
325
+ body: string;
326
+ meta: string;
327
+ learned_on: string;
328
+ happened_on: string | null;
329
+ }
330
+
331
+ export interface EdgeRow extends Row {
332
+ src: string;
333
+ dst: string;
334
+ weight: number;
335
+ last_day: number;
336
+ }
337
+
338
+ export interface ProspectiveRow extends Row {
339
+ memory_id: string;
340
+ window_key: string;
341
+ event_date: string;
342
+ precision: string;
343
+ state: string;
344
+ fires: number;
345
+ last_fired_day: number | null;
346
+ }
347
+
348
+ export interface GateSessionRow extends Row {
349
+ session_id: string;
350
+ kind: string;
351
+ ref: string;
352
+ turn: number;
353
+ tier: string | null;
354
+ trains: number | null;
355
+ value: string | null;
356
+ last_day: number;
357
+ }
358
+
359
+ export interface EventRow extends Row {
360
+ seq: number;
361
+ at: number;
362
+ day: number;
363
+ name: string;
364
+ ref: string | null;
365
+ dedup_key: string | null;
366
+ payload: string | null;
367
+ }
368
+
369
+ export interface RemovalRow extends Row {
370
+ seq: number;
371
+ memory_id: string;
372
+ stage: string;
373
+ at: number;
374
+ actor: string;
375
+ reason: string | null;
376
+ }
377
+
378
+ export interface TombstoneRow extends Row {
379
+ memory_id: string;
380
+ type: ProseType;
381
+ kind: Kind;
382
+ band: Band;
383
+ protected: number;
384
+ promoted_identity: number;
385
+ superseded_by: string | null;
386
+ versions: number;
387
+ edges: number;
388
+ prospective: number;
389
+ gate_rows: number;
390
+ at: number;
391
+ }
392
+
393
+ export interface OpenOperationalOptions {
394
+ /**
395
+ * May this open CREATE or MIGRATE the database? False for an instrument: an
396
+ * observer that ran the DDL would be writing at open — which is both a
397
+ * stand-down violation and, in the field, the reason `counterparts backup`
398
+ * threw "database is locked" while a session held a write transaction
399
+ * (live-verify 2026-08-25). Defaults to true.
400
+ */
401
+ readonly initialize?: boolean;
402
+ /** Written once, at creation only. Ignored for an already-initialized store. */
403
+ readonly retentionDays?: number;
404
+ }
405
+
406
+ /**
407
+ * Does `memories` carry the column that holds a memory's words?
408
+ *
409
+ * The one question that tells a pre-rows database from a v6 one, whatever its
410
+ * stamp says. A `PRAGMA` on an open handle; no rows read, nothing written.
411
+ * A file with no `memories` table at all (a fresh one) answers false, which is
412
+ * why the caller asks it only about a database that already has a version.
413
+ */
414
+ function hasBodyColumn(db: Db): boolean {
415
+ try {
416
+ return db.all<{ name: string }>("PRAGMA table_info(memories)").some((c) => c.name === "body");
417
+ } catch {
418
+ return false;
419
+ }
420
+ }
421
+
422
+ /**
423
+ * Is the database at `path` a PRE-ROWS one wearing the current filename?
424
+ *
425
+ * The second lock's question, asked without a `Store` — for the two console
426
+ * doors that open box 3 directly and so never meet `openOperational` at all
427
+ * (`migrate-cache`, and `verify --rebuild`'s census). Review f5c measured both
428
+ * running to completion on a v5 database renamed to `counterparts.sqlite`, and
429
+ * `migrate-cache --apply` would rewrite and VACUUM ~17,000 documents' index in
430
+ * a store this build has declared it cannot read.
431
+ *
432
+ * Opening it is safe HERE in a way it is not at the filename door: this file is
433
+ * already named `counterparts.sqlite`, so it is not the owner's parked v5 store
434
+ * with a `-wal` full of his words — that one is caught by name, before anything
435
+ * opens. `wal: false`, one PRAGMA and one SELECT, closed immediately.
436
+ *
437
+ * False for a file that is not there, is not a database, or is a healthy v6 one.
438
+ */
439
+ export function isPreRowsDatabase(path: string): boolean {
440
+ let db;
441
+ try {
442
+ db = openDb(path, { wal: false });
443
+ const found = readSchemaVersion(db);
444
+ if (found === null) return false;
445
+ const n = Number.parseInt(found, 10);
446
+ return Number.isFinite(n) && n < SCHEMA_VERSION && !hasBodyColumn(db);
447
+ } catch {
448
+ return false;
449
+ } finally {
450
+ try {
451
+ db?.close();
452
+ } catch {
453
+ /* nothing to say about a handle that will not close */
454
+ }
455
+ }
456
+ }
457
+
458
+ /** The schema version recorded in the file, or null if there is not one yet. */
459
+ function readSchemaVersion(db: Db): string | null {
460
+ try {
461
+ return db.get<{ value: string }>("SELECT value FROM meta WHERE key = 'schemaVersion'")?.value ?? null;
462
+ } catch {
463
+ return null; // no meta table: a fresh file
464
+ }
465
+ }
466
+
467
+ /**
468
+ * Open box 2, and write NOTHING when it is already current.
469
+ *
470
+ * The steady state is the common case — the same shape `openCache` uses — and it
471
+ * matters more here, because a write at open takes SQLite's write lock, so a
472
+ * read-only caller could be refused (or refuse someone else) purely by opening.
473
+ */
474
+ export function openOperational(path: string, opts: OpenOperationalOptions = {}): Db {
475
+ // A WRITER converts the file to WAL; an instrument reads the mode and leaves
476
+ // it, for the same reason it does not run the DDL — changing the journal mode
477
+ // takes the write lock (`db.ts#convertToWal`).
478
+ const db = openDb(path, { wal: opts.initialize !== false });
479
+ const found = readSchemaVersion(db);
480
+ if (found === String(SCHEMA_VERSION)) return db;
481
+ // A store from a NEWER build must never be stamped backwards: v4 is the
482
+ // first version doing column surgery, and "migrating" a future file would
483
+ // mean rewriting state this build does not understand (PR-2 review nit).
484
+ if (found !== null && Number.parseInt(found, 10) > SCHEMA_VERSION) {
485
+ db.close();
486
+ throw new StoreError("SCHEMA_AHEAD", { path, expected: SCHEMA_VERSION, found });
487
+ }
488
+ if (opts.initialize === false) {
489
+ // A store at or above the read floor is readable as it stands (see
490
+ // OBSERVER_READ_FLOOR); the migration waits for a writer.
491
+ if (found !== null && Number.parseInt(found, 10) >= OBSERVER_READ_FLOOR) return db;
492
+ db.close();
493
+ throw new StoreError("STORE_UNINITIALIZED", {
494
+ path,
495
+ expected: SCHEMA_VERSION,
496
+ found: found ?? "none",
497
+ });
498
+ }
499
+ // ── THE SECOND LOCK, and it is a real one ──────────────────────────────────
500
+ //
501
+ // The filename door in `Store`'s constructor is the FIRST lock, and it is the
502
+ // only one that ever fires on a store that still has its directory. This one
503
+ // catches the store that walked past it: a v5 database wearing the v6 NAME.
504
+ // `mv operational.sqlite counterparts.sqlite` is the first thing a person
505
+ // tries, and with `prose/` and `versions/` moved aside too the constructor
506
+ // sees nothing to refuse.
507
+ //
508
+ // Past here the old code did what it does for anything below SCHEMA_VERSION:
509
+ // ran the DDL (`CREATE TABLE IF NOT EXISTS`, so the v5 `memories` table keeps
510
+ // its shape and gains NO `body` column), ran `ensureAddedColumns` (a no-op,
511
+ // the list is empty) — and then STAMPED the file v6. After that this build
512
+ // reads no body and the old build refuses it `SCHEMA_AHEAD` for ever;
513
+ // recovering it means hand-editing `meta` with sqlite3. Reviewer A measured
514
+ // exactly that (`adversarial-review-f5a`, MAJOR-2), and it is the one outcome
515
+ // this whole phase exists to prevent.
516
+ //
517
+ // **Keyed on the SHAPE, not on the version.** A bare `found < SCHEMA_VERSION`
518
+ // would be wrong: a genuinely v6-shaped database whose stamp was lowered by
519
+ // hand must still migrate forward, and three tests say so. What distinguishes
520
+ // a pre-rows database is that `memories` has no `body` column — ask that.
521
+ //
522
+ // The WAL argument that put the FIRST lock on filenames does not apply here:
523
+ // this build opened the file itself several statements ago.
524
+ if (found !== null && Number.parseInt(found, 10) < SCHEMA_VERSION && !hasBodyColumn(db)) {
525
+ db.close();
526
+ throw new StoreError("STORE_PRE_ROWS", {
527
+ path,
528
+ found,
529
+ expected: SCHEMA_VERSION,
530
+ reason: "no-body-column",
531
+ readableBy: PRE_ROWS_READABLE_BY,
532
+ });
533
+ }
534
+ db.transaction(() => {
535
+ for (const sql of DDL) db.exec(sql);
536
+ ensureAddedColumns(db);
537
+ const put = db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");
538
+ put.run("livedDay", "0");
539
+ put.run("lastActiveDate", "");
540
+ put.run("retentionDays", String(opts.retentionDays ?? DEFAULT_RETENTION_DAYS));
541
+ // Last, and REPLACE not IGNORE: the version row is the latch the next open
542
+ // reads, so it must be written only after the DDL it describes has run.
543
+ db.run("INSERT OR REPLACE INTO meta (key, value) VALUES ('schemaVersion', ?)", String(SCHEMA_VERSION));
544
+ });
545
+ return db;
546
+ }
547
+
548
+ /**
549
+ * Columns added to a table AFTER it first shipped. `CREATE TABLE IF NOT EXISTS`
550
+ * cannot grow an existing table, so a pre-existing store gains these here —
551
+ * checked against `pragma table_info` and added one `ALTER TABLE` at a time,
552
+ * inside the migrate-at-open transaction. Idempotent by construction, and a
553
+ * fresh CREATE must list the same columns so both paths converge (a test
554
+ * asserts table_info equality between a fresh open and a migrated one).
555
+ */
556
+ export const ADDED_COLUMNS: readonly { table: string; column: string; ddl: string }[] = [
557
+ // EMPTY at v6, and that is the floor's safety rule rather than an accident.
558
+ //
559
+ // A pre-v6 store is refused by name before anything opens it, so nothing here
560
+ // can reach one — and the v6 columns must NOT be listed: `body` added through
561
+ // this path to a v5 store would be NULL on every row while the words sat in
562
+ // files this build cannot see, and the store would be stamped v6 and
563
+ // unreadable by the build that can (`SCHEMA_VERSION` above, `STORE_PRE_ROWS`).
564
+ //
565
+ // The mechanism stays for whatever v7 adds additively to a v6 store.
566
+ ];
567
+
568
+ function ensureAddedColumns(db: Db): void {
569
+ const byTable = new Map<string, Set<string>>();
570
+ for (const spec of ADDED_COLUMNS) {
571
+ let have = byTable.get(spec.table);
572
+ if (have === undefined) {
573
+ have = new Set(
574
+ db.all<{ name: string }>(`PRAGMA table_info(${spec.table})`).map((r) => r.name),
575
+ );
576
+ byTable.set(spec.table, have);
577
+ }
578
+ if (!have.has(spec.column)) db.exec(spec.ddl);
579
+ }
580
+ }
581
+
582
+ export function rowToSalience(row: MemoryRow): Salience {
583
+ return {
584
+ novelty: row.novelty,
585
+ relevance: row.relevance,
586
+ emotional: row.emotional,
587
+ predictive: row.predictive,
588
+ // The author's claimed FLOOR, kept beside the dimensions so `sal(m)` stays
589
+ // reproducible from stored state alone (physics §5.1). Never defaulted.
590
+ claimed: row.claimed,
591
+ };
592
+ }
593
+
594
+ export function rowToPhysics(row: MemoryRow): MemoryPhysics {
595
+ return {
596
+ kind: row.kind,
597
+ salience: rowToSalience(row),
598
+ birthDay: row.birth_day,
599
+ uses: row.uses,
600
+ lastUsedDay: row.last_used_day,
601
+ // Distinct lived days that credited a use — `uses` is a weighted sum and
602
+ // cannot reconstruct it (physics §5.3/§5.5). Absent reads as 0.
603
+ reinforcedDays: row.reinforced_days,
604
+ consolidated: row.consolidated === 1,
605
+ promotedIdentity: row.promoted_identity === 1,
606
+ protected: row.protected === 1,
607
+ pressure: row.pressure,
608
+ lastChallengedDay: row.last_challenged_day,
609
+ };
610
+ }