counterparts 0.3.0 → 0.3.2

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 (207) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/docs/module-map.md +2 -0
  3. package/package.json +2 -1
  4. package/src/adapters/claude-code/CONTRACT.md +2 -1
  5. package/src/adapters/claude-code/NOTES.md +90 -2
  6. package/src/adapters/claude-code/bin/hook.ts +17 -2
  7. package/src/adapters/claude-code/bin/runner.ts +4 -1
  8. package/src/adapters/claude-code/config.ts +23 -0
  9. package/src/adapters/claude-code/doctor.ts +148 -26
  10. package/src/adapters/claude-code/hooks.ts +37 -12
  11. package/src/adapters/claude-code/index.ts +2 -0
  12. package/src/adapters/claude-code/standdown.ts +12 -1
  13. package/src/adapters/claude-code/transcript.ts +79 -6
  14. package/src/adapters/cli/INTERFACE-GAPS.md +4 -0
  15. package/src/adapters/cli/commands.ts +209 -61
  16. package/src/adapters/cli/export.ts +27 -3
  17. package/src/adapters/cli/help.ts +22 -8
  18. package/src/adapters/cli/install.ts +3 -5
  19. package/src/adapters/cli/mechanisms.ts +295 -0
  20. package/src/adapters/cli/repair-dates.ts +3 -1
  21. package/src/adapters/cli/snapshot.ts +4 -27
  22. package/src/adapters/dashboard/CONTRACT.md +13 -9
  23. package/src/adapters/dashboard/INTERFACE-GAPS.md +4 -0
  24. package/src/adapters/dashboard/NOTES.md +3 -2
  25. package/src/adapters/dashboard/activity.ts +2 -1
  26. package/src/adapters/dashboard/bin/dashboard.ts +18 -3
  27. package/src/adapters/dashboard/upgrade.ts +23 -0
  28. package/src/adapters/dashboard/web/README.md +153 -0
  29. package/src/adapters/dashboard/web/actions.ts +631 -0
  30. package/src/adapters/dashboard/web/app.html +40 -1703
  31. package/src/adapters/dashboard/web/app.js +55 -0
  32. package/src/adapters/dashboard/web/mechanisms/association/index.js +15 -0
  33. package/src/adapters/dashboard/web/mechanisms/association/panel.js +17 -0
  34. package/src/adapters/dashboard/web/mechanisms/consolidation/index.js +15 -0
  35. package/src/adapters/dashboard/web/mechanisms/consolidation/panel.js +23 -0
  36. package/src/adapters/dashboard/web/mechanisms/decay/index.js +15 -0
  37. package/src/adapters/dashboard/web/mechanisms/decay/panel.js +45 -0
  38. package/src/adapters/dashboard/web/mechanisms/emotional/index.js +15 -0
  39. package/src/adapters/dashboard/web/mechanisms/episodic-semantic/index.js +15 -0
  40. package/src/adapters/dashboard/web/mechanisms/index.js +60 -0
  41. package/src/adapters/dashboard/web/mechanisms/interference/index.js +15 -0
  42. package/src/adapters/dashboard/web/mechanisms/picture.js +28 -0
  43. package/src/adapters/dashboard/web/mechanisms/prospective/index.js +15 -0
  44. package/src/adapters/dashboard/web/mechanisms/reconsolidation/index.js +15 -0
  45. package/src/adapters/dashboard/web/mechanisms/reconsolidation/panel.js +15 -0
  46. package/src/adapters/dashboard/web/mechanisms/regions.js +30 -0
  47. package/src/adapters/dashboard/web/mechanisms/retrieval/index.js +15 -0
  48. package/src/adapters/dashboard/web/mechanisms/retrieval/panel.js +20 -0
  49. package/src/adapters/dashboard/web/mechanisms/salience/index.js +15 -0
  50. package/src/adapters/dashboard/web/mechanisms/salience/panel.js +14 -0
  51. package/src/adapters/dashboard/web/mechanisms/schema/index.js +15 -0
  52. package/src/adapters/dashboard/web/narrate.ts +10 -10
  53. package/src/adapters/dashboard/web/pages/flow/flow.css +38 -0
  54. package/src/adapters/dashboard/web/pages/flow/index.js +117 -0
  55. package/src/adapters/dashboard/web/pages/flow/sections/blind.js +12 -0
  56. package/src/adapters/dashboard/web/pages/flow/sections/detail.js +45 -0
  57. package/src/adapters/dashboard/web/pages/flow/sections/diagram.js +291 -0
  58. package/src/adapters/dashboard/web/pages/flow/sections/feed.js +11 -0
  59. package/src/adapters/dashboard/web/pages/flow/sections/fired.js +41 -0
  60. package/src/adapters/dashboard/web/pages/flow/sections/heatmap.js +25 -0
  61. package/src/adapters/dashboard/web/pages/flow/sections/records.js +24 -0
  62. package/src/adapters/dashboard/web/pages/flow/sections/symmetry.js +17 -0
  63. package/src/adapters/dashboard/web/pages/flow/state.js +3 -0
  64. package/src/adapters/dashboard/web/pages/health/health.css +93 -0
  65. package/src/adapters/dashboard/web/pages/health/index.js +41 -0
  66. package/src/adapters/dashboard/web/pages/health/sections/archive.js +84 -0
  67. package/src/adapters/dashboard/web/pages/health/sections/checks.js +172 -0
  68. package/src/adapters/dashboard/web/pages/health/sections/cycle.js +37 -0
  69. package/src/adapters/dashboard/web/pages/health/sections/verify.js +54 -0
  70. package/src/adapters/dashboard/web/pages/home/brain.js +375 -0
  71. package/src/adapters/dashboard/web/pages/home/home.css +134 -0
  72. package/src/adapters/dashboard/web/pages/home/index.js +84 -0
  73. package/src/adapters/dashboard/web/pages/home/sections/explorer.js +206 -0
  74. package/src/adapters/dashboard/web/pages/home/sections/hero.js +22 -0
  75. package/src/adapters/dashboard/web/pages/home/sections/live-activity.js +25 -0
  76. package/src/adapters/dashboard/web/pages/home/sections/recent-chapters.js +13 -0
  77. package/src/adapters/dashboard/web/pages/home/sections/tiles.js +52 -0
  78. package/src/adapters/dashboard/web/pages/memories/index.js +75 -0
  79. package/src/adapters/dashboard/web/pages/memories/memories.css +143 -0
  80. package/src/adapters/dashboard/web/pages/memories/sections/constellation.js +178 -0
  81. package/src/adapters/dashboard/web/pages/memories/sections/kinds.js +42 -0
  82. package/src/adapters/dashboard/web/pages/memories/sections/list.js +114 -0
  83. package/src/adapters/dashboard/web/pages/memories/sections/search.js +102 -0
  84. package/src/adapters/dashboard/web/pages/memories/sections/tools.js +155 -0
  85. package/src/adapters/dashboard/web/pages/memories/state.js +22 -0
  86. package/src/adapters/dashboard/web/pages/self/diff.js +79 -0
  87. package/src/adapters/dashboard/web/pages/self/index.js +43 -0
  88. package/src/adapters/dashboard/web/pages/self/markdown.js +61 -0
  89. package/src/adapters/dashboard/web/pages/self/sections/journal.js +32 -0
  90. package/src/adapters/dashboard/web/pages/self/sections/page.js +149 -0
  91. package/src/adapters/dashboard/web/pages/self/sections/settling.js +150 -0
  92. package/src/adapters/dashboard/web/pages/self/sections/stories.js +47 -0
  93. package/src/adapters/dashboard/web/pages/self/sections/wake.js +74 -0
  94. package/src/adapters/dashboard/web/pages/self/self.css +182 -0
  95. package/src/adapters/dashboard/web/server.ts +305 -28
  96. package/src/adapters/dashboard/web/shared/absence.js +14 -0
  97. package/src/adapters/dashboard/web/shared/actions.js +48 -0
  98. package/src/adapters/dashboard/web/shared/api.js +17 -0
  99. package/src/adapters/dashboard/web/shared/base.css +34 -0
  100. package/src/adapters/dashboard/web/shared/canvas.js +68 -0
  101. package/src/adapters/dashboard/web/shared/colors.js +6 -0
  102. package/src/adapters/dashboard/web/shared/dom.js +4 -0
  103. package/src/adapters/dashboard/web/shared/event-modal.js +25 -0
  104. package/src/adapters/dashboard/web/shared/fonts/OFL-courier-prime.txt +93 -0
  105. package/src/adapters/dashboard/web/shared/fonts/OFL-outfit.txt +93 -0
  106. package/src/adapters/dashboard/web/shared/fonts/courier-prime-latin-400.woff2 +0 -0
  107. package/src/adapters/dashboard/web/shared/fonts/courier-prime-latin-700.woff2 +0 -0
  108. package/src/adapters/dashboard/web/shared/fonts/outfit-latin-wght.woff2 +0 -0
  109. package/src/adapters/dashboard/web/shared/format.js +31 -0
  110. package/src/adapters/dashboard/web/shared/layout.css +32 -0
  111. package/src/adapters/dashboard/web/shared/memory-modal.js +124 -0
  112. package/src/adapters/dashboard/web/shared/modal.css +24 -0
  113. package/src/adapters/dashboard/web/shared/modal.js +22 -0
  114. package/src/adapters/dashboard/web/shared/state.js +12 -0
  115. package/src/adapters/dashboard/web/shared/tip.css +4 -0
  116. package/src/adapters/dashboard/web/shared/tip.js +12 -0
  117. package/src/adapters/dashboard/web/shared/tokens.css +50 -0
  118. package/src/adapters/dashboard/web/shared/type.css +52 -0
  119. package/src/adapters/dashboard/web/shared/utilities.css +5 -0
  120. package/src/adapters/dashboard/web/shared/vendor/MIT-three.txt +21 -0
  121. package/src/adapters/dashboard/web/shared/vendor/three.module.min.js +6 -0
  122. package/src/adapters/dashboard/web/shared/widgets/bar.css +9 -0
  123. package/src/adapters/dashboard/web/shared/widgets/card.css +6 -0
  124. package/src/adapters/dashboard/web/shared/widgets/chapters.js +15 -0
  125. package/src/adapters/dashboard/web/shared/widgets/chart.css +4 -0
  126. package/src/adapters/dashboard/web/shared/widgets/confirm.css +31 -0
  127. package/src/adapters/dashboard/web/shared/widgets/confirm.js +52 -0
  128. package/src/adapters/dashboard/web/shared/widgets/feed.css +13 -0
  129. package/src/adapters/dashboard/web/shared/widgets/feed.js +41 -0
  130. package/src/adapters/dashboard/web/shared/widgets/light.css +4 -0
  131. package/src/adapters/dashboard/web/shared/widgets/light.js +15 -0
  132. package/src/adapters/dashboard/web/shared/widgets/rows.css +7 -0
  133. package/src/adapters/dashboard/web/shared/widgets/table.css +17 -0
  134. package/src/adapters/dashboard/web/shared/widgets/tiles.css +14 -0
  135. package/src/adapters/dashboard/web/shell/pages.js +15 -0
  136. package/src/adapters/dashboard/web/shell/pulse.js +86 -0
  137. package/src/adapters/dashboard/web/shell/tabs.js +49 -0
  138. package/src/adapters/dashboard/web/static.ts +76 -0
  139. package/src/adapters/dashboard/web/views/activity.ts +80 -0
  140. package/src/adapters/dashboard/web/views/archive-words.ts +57 -0
  141. package/src/adapters/dashboard/web/views/flow-view.ts +217 -0
  142. package/src/adapters/dashboard/web/views/health.ts +328 -0
  143. package/src/adapters/dashboard/web/views/mechanism-panel.ts +370 -0
  144. package/src/adapters/dashboard/web/views/mechanisms.ts +302 -0
  145. package/src/adapters/dashboard/web/views/memories.ts +342 -0
  146. package/src/adapters/dashboard/web/views/memory.ts +210 -0
  147. package/src/adapters/dashboard/web/views/meta.ts +64 -0
  148. package/src/adapters/dashboard/web/views/mind.ts +729 -0
  149. package/src/adapters/dashboard/web/views/overview.ts +282 -0
  150. package/src/adapters/dashboard/web/views/pulse.ts +19 -0
  151. package/src/adapters/dashboard/web/views/rows.ts +207 -0
  152. package/src/adapters/dashboard/web/views/search.ts +62 -0
  153. package/src/adapters/dashboard/web/views/shared.ts +161 -0
  154. package/src/adapters/dashboard/web/views.ts +34 -1724
  155. package/src/adapters/fired.ts +138 -31
  156. package/src/adapters/mcp/INTERFACE-GAPS.md +4 -1
  157. package/src/adapters/mcp/NOTES.md +43 -0
  158. package/src/adapters/mcp/bin/serve.ts +9 -1
  159. package/src/adapters/mcp/index.ts +7 -0
  160. package/src/adapters/mcp/server.ts +167 -6
  161. package/src/adapters/mcp/tools.ts +42 -0
  162. package/src/adapters/mcp/write-up.ts +1 -1
  163. package/src/adapters/sessions.ts +18 -1
  164. package/src/adapters/snapshots.ts +71 -39
  165. package/src/core/associate/INTERFACE-GAPS.md +8 -0
  166. package/src/core/counterpart.ts +86 -7
  167. package/src/core/encode/INTERFACE-GAPS.md +12 -0
  168. package/src/core/feelings-wheel.ts +218 -0
  169. package/src/core/handoff/INTERFACE-GAPS.md +2 -0
  170. package/src/core/mint.ts +14 -2
  171. package/src/core/prospective/INTERFACE-GAPS.md +14 -0
  172. package/src/core/prospective/windows.ts +10 -48
  173. package/src/core/recall/INTERFACE-GAPS.md +6 -0
  174. package/src/core/remember/INTERFACE-GAPS.md +10 -0
  175. package/src/core/schemas/INTERFACE-GAPS.md +8 -0
  176. package/src/core/schemas/NOTES.md +118 -1
  177. package/src/core/schemas/index.ts +330 -40
  178. package/src/core/schemas/tunables.ts +23 -0
  179. package/src/core/schemas/types.ts +64 -1
  180. package/src/core/self/CONTRACT.md +3 -0
  181. package/src/core/self/INTERFACE-GAPS.md +10 -0
  182. package/src/core/self/NOTES.md +33 -2
  183. package/src/core/self/calendar.ts +7 -78
  184. package/src/core/self/episodes.ts +52 -12
  185. package/src/core/self/index.ts +40 -12
  186. package/src/core/self/writer.ts +22 -22
  187. package/src/core/sleep/NOTES.md +36 -0
  188. package/src/core/sleep/cycle.ts +38 -3
  189. package/src/core/sleep/fade.ts +76 -0
  190. package/src/core/sleep/index.ts +4 -1
  191. package/src/core/sleep/prune.ts +8 -1
  192. package/src/core/sleep/tunables.ts +5 -0
  193. package/src/core/sleep/types.ts +24 -0
  194. package/src/core/store/CONTRACT.md +36 -7
  195. package/src/core/store/NOTES.md +197 -0
  196. package/src/core/store/errors.ts +22 -0
  197. package/src/core/store/feelings.ts +182 -0
  198. package/src/core/store/index.ts +339 -45
  199. package/src/core/store/operational.ts +240 -22
  200. package/src/core/store/owner-op-seam.ts +13 -3
  201. package/src/core/store/paths.ts +15 -1
  202. package/src/core/store/pre-migration.ts +258 -0
  203. package/src/core/store/prose.ts +8 -1
  204. package/src/core/store/render.ts +3 -0
  205. package/src/core/time.ts +374 -0
  206. package/src/core/types.ts +13 -0
  207. package/src/adapters/dashboard/web/brain.html +0 -463
@@ -0,0 +1,258 @@
1
+ /**
2
+ * The copy taken before a schema migration changes box 2.
3
+ *
4
+ * `openOperational` calls `snapshotBeforeMigration` inside the migrating
5
+ * transaction, after it has taken the write lock and re-read the version — so
6
+ * of several processes opening an old store at once, only the one that wins the
7
+ * lock copies and migrates; the rest find it current and do neither.
8
+ *
9
+ * The copy is the database only, through `VACUUM INTO` on its own connection
10
+ * (a read, so it sees the last committed state: the store before the
11
+ * migration). The migration changes nothing else in the store, so nothing else
12
+ * needs rolling back. It lands in the same snapshots directory the daily copies
13
+ * use, named `<instant>-pre-migration-v<from>-to-v<to>`, and the daily rotation
14
+ * keeps it apart from its own count (`adapters/snapshots.ts`).
15
+ *
16
+ * If the copy cannot be made, the caller does not migrate.
17
+ */
18
+ import { existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, renameSync, statSync } from "node:fs";
19
+ import { utcDate } from "../time.js";
20
+ import { basename, dirname, join, resolve } from "node:path";
21
+
22
+ import { openDb } from "./db.js";
23
+ import { DATABASE_FILE, assertSafeDataDir, defaultSnapshotsDir, forbiddenRoots, isWithin } from "./paths.js";
24
+
25
+ /** The marker in a pre-migration copy's name. */
26
+ export const PRE_MIGRATION_TAG = "pre-migration";
27
+
28
+ /** `2026-09-24T10-00-00-000Z-pre-migration-v6-to-v7`. The instant sorts first. */
29
+ export const PRE_MIGRATION_NAME_RE =
30
+ /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-pre-migration-v[0-9A-Za-z]+-to-v[0-9A-Za-z]+$/;
31
+
32
+ /** The version out of a pre-migration name, as `{ from, to }`, or null. */
33
+ export function preMigrationVersions(name: string): { from: string; to: string } | null {
34
+ if (!PRE_MIGRATION_NAME_RE.test(name)) return null;
35
+ const m = /-pre-migration-v([0-9A-Za-z]+)-to-v([0-9A-Za-z]+)$/.exec(name);
36
+ return m === null ? null : { from: m[1] ?? "", to: m[2] ?? "" };
37
+ }
38
+
39
+ /** A version stamp as it can appear in a directory name. */
40
+ function stampForName(stamp: string): string {
41
+ const clean = stamp.replace(/[^0-9A-Za-z]/g, "");
42
+ return clean.length > 0 ? clean : "unknown";
43
+ }
44
+
45
+ export function preMigrationName(at: number, from: string, to: number | string): string {
46
+ const instant = new Date(at).toISOString().replace(/[:.]/g, "-");
47
+ return `${instant}-${PRE_MIGRATION_TAG}-v${stampForName(from)}-to-v${stampForName(String(to))}`;
48
+ }
49
+
50
+ /**
51
+ * `VACUUM INTO` on its own connection. The destination must not exist — SQLite
52
+ * refuses to overwrite, which is the right default for a snapshot: a backup that
53
+ * silently replaces yesterday's is one crash away from being no backup at all.
54
+ *
55
+ * Moved here from `adapters/cli/snapshot.ts` (which still exports it) so the
56
+ * store can copy itself before a migration.
57
+ */
58
+ export function vacuumInto(
59
+ source: string,
60
+ destination: string,
61
+ ): { ok: true } | { ok: false; error: string } {
62
+ if (!existsSync(source)) return { ok: false, error: "no canonical database at source" };
63
+ if (existsSync(destination)) {
64
+ return { ok: false, error: `destination already exists: ${destination}` };
65
+ }
66
+ let db;
67
+ try {
68
+ db = openDb(source);
69
+ // Single-quoted SQL literal: the path is escaped for SQL, never interpolated
70
+ // into a shell, because nothing here shells out.
71
+ db.exec(`VACUUM INTO '${destination.replace(/'/g, "''")}'`);
72
+ return { ok: true };
73
+ } catch (err) {
74
+ return { ok: false, error: String((err as Error).message ?? err) };
75
+ } finally {
76
+ db?.close();
77
+ }
78
+ }
79
+
80
+ /** The real path of a directory that may not exist yet: the deepest existing
81
+ * ancestor realpathed, the rest put back on. Shared with `adapters/snapshots.ts`. */
82
+ export function realpathDeep(path: string): string {
83
+ const resolved = resolve(path);
84
+ let head = resolved;
85
+ const tail: string[] = [];
86
+ for (;;) {
87
+ try {
88
+ lstatSync(head);
89
+ const real = realpathSync(head);
90
+ return tail.length === 0 ? real : join(real, ...tail);
91
+ } catch {
92
+ const parent = dirname(head);
93
+ if (parent === head) return resolved;
94
+ tail.unshift(basename(head));
95
+ head = parent;
96
+ }
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Where a pre-migration copy of the database at `dbPath` would go: the named
102
+ * directory, else the default beside the store. Null when there is neither.
103
+ */
104
+ export function preMigrationDir(dbPath: string, configured?: string): string | null {
105
+ if (configured !== undefined && configured.trim().length > 0) return resolve(configured);
106
+ return defaultSnapshotsDir(dirname(dbPath));
107
+ }
108
+
109
+ /**
110
+ * The checks a copy's destination has to pass, without writing anything:
111
+ * there is one, it is not under a live v1 store, and it is neither inside the
112
+ * store nor around it. Returns the resolved directory; throws a plain reason.
113
+ * Doctor asks the same question before a session does.
114
+ */
115
+ export function assertPreMigrationTarget(dbPath: string, dir: string | null): string {
116
+ if (dir === null) {
117
+ throw new Error(
118
+ "there is no snapshots directory for a store outside the usual <base>/store layout; name one (the snapshotsDir option, or snapshots.dir in the host configuration)",
119
+ );
120
+ }
121
+ const storeDir = realpathDeep(dirname(dbPath));
122
+ // Checked as written and as it resolves, so a link into a live v1 store is refused too.
123
+ assertSafeDataDir(dir);
124
+ const real = realpathDeep(dir);
125
+ assertSafeDataDir(real);
126
+ for (const root of forbiddenRoots()) {
127
+ if (isWithin(realpathDeep(root), real)) throw new Error(`refusing a snapshots directory inside ${root}`);
128
+ }
129
+ if (isWithin(storeDir, real)) throw new Error(`the snapshots directory is inside the store: ${real}`);
130
+ if (isWithin(real, storeDir)) throw new Error(`the snapshots directory contains the store: ${real}`);
131
+ return real;
132
+ }
133
+
134
+ export interface PreMigrationInput {
135
+ /** The live database file. */
136
+ readonly dbPath: string;
137
+ /** Where the copy goes; null when none was configured and there is no default. */
138
+ readonly dir: string | null;
139
+ /** The stamp found on disk, and the version about to be written. */
140
+ readonly from: string;
141
+ readonly to: number;
142
+ }
143
+
144
+ export interface PreMigrationCopy {
145
+ /** The copy's directory name inside the snapshots directory. */
146
+ readonly name: string;
147
+ /** True when an earlier copy for this upgrade was used instead of a new one. */
148
+ readonly reused: boolean;
149
+ }
150
+
151
+ /**
152
+ * Copy the database into `<dir>/<pre-migration name>` and return that name —
153
+ * or the name of a copy already there for the same upgrade (`reusableCopy`).
154
+ * Throws with a plain reason when it cannot; the caller then does not migrate.
155
+ *
156
+ * Named by the wall clock, never an injected one: a replayed or fixed clock
157
+ * would collide with its own earlier copy, or name one rotation removes at once.
158
+ *
159
+ * Written under a `.partial-<instant>-<pid>` name and renamed into place, like
160
+ * the daily copies, so a killed process leaves a partial the daily sweep
161
+ * removes rather than something that looks like a snapshot.
162
+ */
163
+ export function snapshotBeforeMigration(input: PreMigrationInput): PreMigrationCopy {
164
+ const dir = assertPreMigrationTarget(input.dbPath, input.dir);
165
+ const now = Date.now();
166
+ const earlier = reusableCopy(dir, input.dbPath, input.from, input.to, now);
167
+ if (earlier !== null) return { name: earlier, reused: true };
168
+
169
+ const name = preMigrationName(now, input.from, input.to);
170
+ const instant = new Date(now).toISOString().replace(/[:.]/g, "-");
171
+ const partial = join(dir, `.partial-${instant}-${String(process.pid)}`);
172
+ // A failure below leaves the partial where it is: the store deletes nothing,
173
+ // and the daily sweep removes a stale partial by this name.
174
+ mkdirSync(partial, { recursive: true });
175
+ const copy = vacuumInto(input.dbPath, join(partial, DATABASE_FILE));
176
+ if (!copy.ok) throw new Error(copy.error);
177
+ const bad = checkCopy(join(partial, DATABASE_FILE), input.from);
178
+ if (bad !== null) throw new Error(bad);
179
+ renameSync(partial, join(dir, name));
180
+ return { name, reused: false };
181
+ }
182
+
183
+ /**
184
+ * A copy for this same upgrade that is already on disk and still good enough,
185
+ * so a migration that keeps failing AFTER its copy does not take a new full
186
+ * copy at every open. Good enough means: its database is there, and either it
187
+ * was taken today (UTC) or the live database has not been written since it was
188
+ * taken (neither the file nor its `-wal` is newer than the copy's instant).
189
+ *
190
+ * A copy only takes its final name after it verified, so the name is the proof.
191
+ */
192
+ function reusableCopy(dir: string, dbPath: string, from: string, to: number, now: number): string | null {
193
+ let names: string[];
194
+ try {
195
+ names = readdirSync(dir);
196
+ } catch {
197
+ return null;
198
+ }
199
+ const want = { from: stampForName(from), to: stampForName(String(to)) };
200
+ // The folder names begin with a UTC instant, so "today" here is the UTC day.
201
+ const today = utcDate(now);
202
+ const lastWrite = Math.max(mtimeOf(dbPath), mtimeOf(`${dbPath}-wal`));
203
+ const candidates = names
204
+ .filter((n) => {
205
+ const v = preMigrationVersions(n);
206
+ return v !== null && v.from === want.from && v.to === want.to;
207
+ })
208
+ .sort()
209
+ .reverse();
210
+ for (const name of candidates) {
211
+ try {
212
+ if (statSync(join(dir, name, DATABASE_FILE)).size === 0) continue;
213
+ } catch {
214
+ continue;
215
+ }
216
+ if (name.slice(0, 10) === today) return name;
217
+ const taken = instantOf(name);
218
+ if (taken !== null && lastWrite < taken) return name;
219
+ }
220
+ return null;
221
+ }
222
+
223
+ function mtimeOf(path: string): number {
224
+ try {
225
+ return statSync(path).mtimeMs;
226
+ } catch {
227
+ return 0;
228
+ }
229
+ }
230
+
231
+ /** `2026-09-24T10-00-00-000Z-…` → its epoch milliseconds, or null. */
232
+ function instantOf(name: string): number | null {
233
+ const m = /^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z/.exec(name);
234
+ if (m === null) return null;
235
+ const at = Date.parse(`${m[1]}T${m[2]}:${m[3]}:${m[4]}.${m[5]}Z`);
236
+ return Number.isFinite(at) ? at : null;
237
+ }
238
+
239
+ /** Is the copy a sound database still carrying the old stamp? Null when it is. */
240
+ function checkCopy(path: string, from: string): string | null {
241
+ let db;
242
+ try {
243
+ db = openDb(path);
244
+ const row = db.get<Record<string, string>>("PRAGMA quick_check");
245
+ const verdict = row === undefined ? null : Object.values(row)[0];
246
+ if (verdict !== "ok") return `the copy did not verify: ${verdict ?? "no answer"}`;
247
+ const stamp = db.get<{ value: string }>("SELECT value FROM meta WHERE key = 'schemaVersion'")?.value;
248
+ return stamp === from ? null : `the copy carries schema ${stamp ?? "none"}, expected ${from}`;
249
+ } catch (err) {
250
+ return `the copy would not open: ${String((err as Error).message ?? err)}`;
251
+ } finally {
252
+ try {
253
+ db?.close();
254
+ } catch {
255
+ /* nothing more to learn from it */
256
+ }
257
+ }
258
+ }
@@ -39,7 +39,14 @@ export interface ProseDoc {
39
39
  title?: string;
40
40
  /** When it happened, at stated precision: `2026`, `2026-08`, or `2026-08-25`. Never rounded. */
41
41
  happenedOn?: string;
42
- /** When it was learned (ISO date). Supersession reasoning needs it. */
42
+ /**
43
+ * The calendar date this memory is ABOUT — a reminder's date — as the person
44
+ * said it: `2026-10-15`, `2026-10`, `2026`, or `2026-10-20..2026-10-31`
45
+ * (`core/time.ts`). Schema v7's `event_date`. Never a moment, never rounded.
46
+ */
47
+ eventDate?: string;
48
+ /** When it was learned (ISO date). Supersession reasoning needs it. Since
49
+ * 2026-09-25 the LOCAL date of the row's `created_at`; UTC before. */
43
50
  learnedOn: string;
44
51
  /** Which lived day it was born on — the decay clock's integer (scar E8). */
45
52
  bornDay: number;
@@ -29,6 +29,7 @@ interface Payload {
29
29
  type: ProseType;
30
30
  title?: string;
31
31
  happenedOn?: string;
32
+ eventDate?: string;
32
33
  learnedOn: string;
33
34
  bornDay: number;
34
35
  meta: Record<string, unknown>;
@@ -44,6 +45,7 @@ function toPayload(doc: ProseDoc): Payload {
44
45
  };
45
46
  if (doc.title !== undefined) p.title = doc.title;
46
47
  if (doc.happenedOn !== undefined) p.happenedOn = doc.happenedOn;
48
+ if (doc.eventDate !== undefined) p.eventDate = doc.eventDate;
47
49
  return p;
48
50
  }
49
51
 
@@ -52,6 +54,7 @@ function humanLines(p: Payload): string[] {
52
54
  const lines = [`id: ${p.id}`, `type: ${p.type}`];
53
55
  if (p.title !== undefined) lines.push(`title: ${oneLine(p.title)}`);
54
56
  if (p.happenedOn !== undefined) lines.push(`happened: ${p.happenedOn}`);
57
+ if (p.eventDate !== undefined) lines.push(`date: ${p.eventDate}`);
55
58
  lines.push(`learned: ${p.learnedOn}`, `bornDay: ${p.bornDay}`);
56
59
  return lines;
57
60
  }
@@ -0,0 +1,374 @@
1
+ /**
2
+ * TIME — the one module that converts (docs/time.md, agreed with the owner
3
+ * 2026-09-25).
4
+ *
5
+ * Two kinds of time, and they are never mixed:
6
+ *
7
+ * - **A moment** — UTC milliseconds since the epoch, taken from the store's one
8
+ * clock (`store.now()`). `created_at`, an event's `at`, a version's
9
+ * `archived_at`. Shown in the person's zone, converted HERE, at display time.
10
+ * - **A calendar date a person says** — plain text as written: `2026-10-15`,
11
+ * `2026-10`, `2026`, or a range `2026-10-20..2026-10-31`. Never turned into a
12
+ * moment: "Oct 15" stored as midnight UTC is Oct 14 in Montana, and a month has
13
+ * no moment to pick at all.
14
+ *
15
+ * The third clock, the LIVED day (`store.livedDay()`, `physics/clock.ts`), is a
16
+ * counter of days actually used and is not a calendar; nothing here moves it.
17
+ *
18
+ * Every conversion between the two kinds lives in this file: a moment's local
19
+ * date, a moment's local clock line, "today" in a zone, and the arithmetic and
20
+ * comparison of calendar dates. `test/time.test.ts` scans `src/` for code that
21
+ * builds dates by hand (`toISOString().slice(0, 10)`, the `getUTC*` and local
22
+ * `Date` getters, `Date.UTC`) outside this file and a short allow-list.
23
+ *
24
+ * **The zone** is an IANA name (`America/Denver`), never an offset, so daylight
25
+ * saving is the zone rules' job. `resolveZone(configured)` is the config's
26
+ * `timeZone` when it names a real zone, else the machine's CURRENT zone, read
27
+ * per call: a laptop that flies to New York shows New York time the next time
28
+ * anything asks. Pure given `(at, zone)`: nothing here reads the ambient clock
29
+ * except `todayIn`'s default, and a store passes its own `now()`.
30
+ *
31
+ * Folded in 2026-09-25: `self/calendar.ts` (B3's local-day helper, 2026-09-23),
32
+ * which re-exports from here so its callers are unchanged, and the calendar
33
+ * arithmetic `prospective/windows.ts` did with the UTC getters.
34
+ */
35
+
36
+ // ── zones ────────────────────────────────────────────────────────────────────
37
+
38
+ /** The zone every conversion falls back to when the machine will not say. */
39
+ export const FALLBACK_ZONE = "UTC";
40
+
41
+ const formatters = new Map<string, Intl.DateTimeFormat>();
42
+
43
+ /** One formatter per (zone, shape), because building one costs ~50 µs. */
44
+ function formatter(zone: string, shape: "date" | "clock"): Intl.DateTimeFormat {
45
+ const key = `${shape}|${zone}`;
46
+ let f = formatters.get(key);
47
+ if (f === undefined) {
48
+ f =
49
+ shape === "date"
50
+ ? new Intl.DateTimeFormat("en-US", {
51
+ timeZone: zone,
52
+ year: "numeric",
53
+ month: "2-digit",
54
+ day: "2-digit",
55
+ weekday: "short",
56
+ })
57
+ : new Intl.DateTimeFormat("en-US", {
58
+ timeZone: zone,
59
+ year: "numeric",
60
+ month: "2-digit",
61
+ day: "2-digit",
62
+ weekday: "short",
63
+ hour: "numeric",
64
+ minute: "2-digit",
65
+ hour12: true,
66
+ timeZoneName: "short",
67
+ });
68
+ formatters.set(key, f);
69
+ }
70
+ return f;
71
+ }
72
+
73
+ /** Is `name` an IANA zone this runtime knows? `"America/Denver"`, `"UTC"`. */
74
+ export function isZone(name: unknown): name is string {
75
+ if (typeof name !== "string" || name.trim().length === 0 || name.length > 64) return false;
76
+ // A NAME, never an offset (review N5): the runtime accepts "+05:30", but an
77
+ // offset has no daylight-saving rules, which is the reason zones are names.
78
+ if (!/^[A-Za-z]/.test(name)) return false;
79
+ try {
80
+ new Intl.DateTimeFormat("en-US", { timeZone: name });
81
+ return true;
82
+ } catch {
83
+ return false;
84
+ }
85
+ }
86
+
87
+ /** The machine's zone as it stands right now — what `TZ` sets for a process. */
88
+ export function machineZone(): string {
89
+ try {
90
+ const z = new Intl.DateTimeFormat().resolvedOptions().timeZone;
91
+ return isZone(z) ? z : FALLBACK_ZONE;
92
+ } catch {
93
+ return FALLBACK_ZONE;
94
+ }
95
+ }
96
+
97
+ /**
98
+ * The zone to convert in: the configured one when it is a real zone, else the
99
+ * machine's current one. A misspelt config value is a caller's mistake, and its
100
+ * safe reading is the machine's own day rather than a throw inside a hook — the
101
+ * doctor line names the zone in use, which is where the owner sees it.
102
+ */
103
+ export function resolveZone(configured?: string | null): string {
104
+ return configured !== undefined && configured !== null && isZone(configured) ? configured : machineZone();
105
+ }
106
+
107
+ // ── a moment, in a zone ──────────────────────────────────────────────────────
108
+
109
+ interface Parts {
110
+ year: string;
111
+ month: string;
112
+ day: string;
113
+ weekday: string;
114
+ hour: string;
115
+ minute: string;
116
+ dayPeriod: string;
117
+ timeZoneName: string;
118
+ }
119
+
120
+ function partsOf(at: number, zone: string, shape: "date" | "clock"): Parts | null {
121
+ const d = new Date(at);
122
+ if (!Number.isFinite(d.getTime())) return null;
123
+ let raw: Intl.DateTimeFormatPart[];
124
+ try {
125
+ raw = formatter(zone, shape).formatToParts(d);
126
+ } catch {
127
+ if (zone === FALLBACK_ZONE) return null;
128
+ return partsOf(at, FALLBACK_ZONE, shape);
129
+ }
130
+ const out: Record<string, string> = {};
131
+ for (const p of raw) out[p.type] = p.value;
132
+ return {
133
+ year: (out["year"] ?? "").padStart(4, "0"),
134
+ month: out["month"] ?? "",
135
+ day: out["day"] ?? "",
136
+ weekday: out["weekday"] ?? "",
137
+ hour: out["hour"] ?? "",
138
+ minute: out["minute"] ?? "",
139
+ dayPeriod: (out["dayPeriod"] ?? "").toLowerCase(),
140
+ timeZoneName: out["timeZoneName"] ?? "",
141
+ };
142
+ }
143
+
144
+ /**
145
+ * `YYYY-MM-DD` — the calendar day the moment `at` falls on in `zone` (default:
146
+ * the machine's current zone). Empty for a moment that is not a number. An
147
+ * unknown zone name reads as the machine's zone, as `resolveZone` would.
148
+ */
149
+ export function localDate(at: number, zone?: string): string {
150
+ const z = zone === undefined || !isZoneCached(zone) ? machineZone() : zone;
151
+ const p = partsOf(at, z, "date");
152
+ return p === null ? "" : `${p.year}-${p.month}-${p.day}`;
153
+ }
154
+
155
+ /**
156
+ * The moment as a person reads it on a clock: `Thu 25 Sep 2026, 1:40 pm MDT`.
157
+ * The zone's own short name (`MDT`, `EDT`, or `GMT+2` where the runtime has no
158
+ * abbreviation), so a reader who travelled can see which clock it is.
159
+ */
160
+ export function localClock(at: number, zone?: string): string {
161
+ const z = zone === undefined || !isZoneCached(zone) ? machineZone() : zone;
162
+ const p = partsOf(at, z, "clock");
163
+ if (p === null) return "";
164
+ const mo = MONTHS[Number(p.month) - 1] ?? p.month;
165
+ return `${p.weekday} ${String(Number(p.day))} ${mo} ${p.year}, ${p.hour}:${p.minute} ${p.dayPeriod} ${p.timeZoneName}`.trim();
166
+ }
167
+
168
+ /** Today's `YYYY-MM-DD` in `zone`. A store passes its own clock; the default is
169
+ * the ambient one, for an adapter with no store open. */
170
+ export function todayIn(zone?: string, at: number = Date.now()): string {
171
+ return localDate(at, zone);
172
+ }
173
+
174
+ /**
175
+ * The UTC calendar date of a moment. For the few places that still name things
176
+ * by the UTC day on purpose (a snapshot folder, a parked directory's suffix —
177
+ * each says why) and for reading rows written before 2026-09-25, whose
178
+ * `learned_on` was UTC. A person's day is `localDate`.
179
+ */
180
+ export function utcDate(at: number): string {
181
+ const d = new Date(at);
182
+ return Number.isFinite(d.getTime()) ? d.toISOString().slice(0, 10) : "";
183
+ }
184
+
185
+ /** A moment as an ISO-8601 UTC instant (`2026-09-25T19:40:00.000Z`) — a log
186
+ * line's or a file name's spelling of a moment, never a person's. */
187
+ export function isoInstant(at: number): string {
188
+ const d = new Date(at);
189
+ return Number.isFinite(d.getTime()) ? d.toISOString() : "";
190
+ }
191
+
192
+ const zoneOk = new Map<string, boolean>();
193
+ function isZoneCached(zone: string): boolean {
194
+ let ok = zoneOk.get(zone);
195
+ if (ok === undefined) {
196
+ ok = isZone(zone);
197
+ zoneOk.set(zone, ok);
198
+ }
199
+ return ok;
200
+ }
201
+
202
+ // ── calendar dates, as a person says them ────────────────────────────────────
203
+
204
+ /** How much a stated date says. A range is two days, inclusive. */
205
+ export type CalendarPrecision = "day" | "month" | "year" | "range";
206
+
207
+ /** A stated calendar date, read: the text as written and the days it covers. */
208
+ export interface CalendarDate {
209
+ /** Exactly as stated — never widened, never narrowed (prospective §12 G4). */
210
+ readonly text: string;
211
+ readonly precision: CalendarPrecision;
212
+ /** First day covered, `YYYY-MM-DD`. */
213
+ readonly first: string;
214
+ /** Last day covered, inclusive. */
215
+ readonly last: string;
216
+ }
217
+
218
+ const DAY_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
219
+ const MONTH_RE = /^(\d{4})-(\d{2})$/;
220
+ const YEAR_RE = /^(\d{4})$/;
221
+ /** The range separator: `2026-10-20..2026-10-31`. */
222
+ export const RANGE_SEP = "..";
223
+ const DAY_MS = 86_400_000;
224
+
225
+ const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] as const;
226
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] as const;
227
+
228
+ function pad2(n: number): string {
229
+ return String(n).padStart(2, "0");
230
+ }
231
+
232
+ /**
233
+ * A `YYYY-MM-DD` as a count of days, for arithmetic ONLY. The day is read as
234
+ * the label it is — never as a moment in any zone — so the arithmetic uses the
235
+ * proleptic Gregorian day count directly and needs no `Date` at all.
236
+ */
237
+ function dayNumber(y: number, m: number, d: number): number {
238
+ // Days from civil, after Howard Hinnant's algorithm: exact for every year.
239
+ const yy = m <= 2 ? y - 1 : y;
240
+ const era = Math.floor(yy / 400);
241
+ const yoe = yy - era * 400;
242
+ const mp = (m + 9) % 12;
243
+ const doy = Math.floor((153 * mp + 2) / 5) + d - 1;
244
+ const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
245
+ return era * 146097 + doe - 719468;
246
+ }
247
+
248
+ function fromDayNumber(z: number): string {
249
+ const zz = z + 719468;
250
+ const era = Math.floor(zz / 146097);
251
+ const doe = zz - era * 146097;
252
+ const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);
253
+ const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
254
+ const mp = Math.floor((5 * doy + 2) / 153);
255
+ const d = doy - Math.floor((153 * mp + 2) / 5) + 1;
256
+ const m = mp < 10 ? mp + 3 : mp - 9;
257
+ const y = yoe + era * 400 + (m <= 2 ? 1 : 0);
258
+ return `${String(y).padStart(4, "0")}-${pad2(m)}-${pad2(d)}`;
259
+ }
260
+
261
+ function daysInMonth(y: number, m: number): number {
262
+ return dayNumber(m === 12 ? y + 1 : y, m === 12 ? 1 : m + 1, 1) - dayNumber(y, m, 1);
263
+ }
264
+
265
+ /** The day count of a real `YYYY-MM-DD`, or null (`2026-02-30` is not a day). */
266
+ function dayOf(ymd: string): number | null {
267
+ const m = DAY_RE.exec(ymd);
268
+ if (m === null) return null;
269
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
270
+ if (y < 1 || mo < 1 || mo > 12 || d < 1 || d > daysInMonth(y, mo)) return null;
271
+ return dayNumber(y, mo, d);
272
+ }
273
+
274
+ /** Is `ymd` a whole, real calendar day? */
275
+ export function isDay(ymd: unknown): ymd is string {
276
+ return typeof ymd === "string" && dayOf(ymd) !== null;
277
+ }
278
+
279
+ /**
280
+ * Read a stated calendar date: a day, a month, a year, or a range of two days
281
+ * (`2026-10-20..2026-10-31`, inclusive, first ≤ last). Null for anything else —
282
+ * a refusal with a shape, never a guess.
283
+ */
284
+ export function parseCalendarDate(text: unknown): CalendarDate | null {
285
+ if (typeof text !== "string") return null;
286
+ const s = text.trim();
287
+ if (s.includes(RANGE_SEP)) {
288
+ const [a, b, ...rest] = s.split(RANGE_SEP);
289
+ if (rest.length > 0 || a === undefined || b === undefined) return null;
290
+ const x = dayOf(a);
291
+ const y = dayOf(b);
292
+ if (x === null || y === null || y < x) return null;
293
+ return { text: s, precision: "range", first: a, last: b };
294
+ }
295
+ if (dayOf(s) !== null) return { text: s, precision: "day", first: s, last: s };
296
+ const mm = MONTH_RE.exec(s);
297
+ if (mm !== null) {
298
+ const [y, mo] = [Number(mm[1]), Number(mm[2])];
299
+ if (y < 1 || mo < 1 || mo > 12) return null;
300
+ return { text: s, precision: "month", first: `${mm[1]}-${mm[2]}-01`, last: `${mm[1]}-${mm[2]}-${pad2(daysInMonth(y, mo))}` };
301
+ }
302
+ const yy = YEAR_RE.exec(s);
303
+ if (yy !== null && Number(yy[1]) >= 1) return { text: s, precision: "year", first: `${yy[1]}-01-01`, last: `${yy[1]}-12-31` };
304
+ return null;
305
+ }
306
+
307
+ /** Is `text` a calendar date this module can read? */
308
+ export function isCalendarDate(text: unknown): text is string {
309
+ return parseCalendarDate(text) !== null;
310
+ }
311
+
312
+ /** `ymd` moved by `n` days. Throws on a malformed day — a caller's bug. */
313
+ export function addDays(ymd: string, n: number): string {
314
+ const d = dayOf(ymd);
315
+ if (d === null) throw new Error(`addDays: not a calendar day: ${ymd}`);
316
+ return fromDayNumber(d + n);
317
+ }
318
+
319
+ /** Calendar days from `a` to `b`; negative when `b` is earlier. Throws on a malformed day. */
320
+ export function daysBetween(a: string, b: string): number {
321
+ const x = dayOf(a);
322
+ const y = dayOf(b);
323
+ if (x === null || y === null) throw new Error(`daysBetween: not calendar days: ${a}, ${b}`);
324
+ return y - x;
325
+ }
326
+
327
+ /** First and last day of a stated `YYYY-MM`, or null. */
328
+ export function monthBounds(month: string): { first: string; last: string } | null {
329
+ const c = parseCalendarDate(month);
330
+ return c !== null && c.precision === "month" ? { first: c.first, last: c.last } : null;
331
+ }
332
+
333
+ /**
334
+ * Order two stated dates by the first day each covers, then by the last — so a
335
+ * month sorts beside its first day rather than before every day of the year the
336
+ * way the raw strings would (`'2026-10' < '2026-01-05'` is false, and
337
+ * `'2026-10' < '2026-10-01'` is true). Unreadable text sorts last, by text.
338
+ */
339
+ export function compareCalendarDates(a: string, b: string): number {
340
+ const x = parseCalendarDate(a);
341
+ const y = parseCalendarDate(b);
342
+ if (x === null || y === null) return x === null && y === null ? a.localeCompare(b) : x === null ? 1 : -1;
343
+ if (x.first !== y.first) return x.first < y.first ? -1 : 1;
344
+ if (x.last !== y.last) return x.last < y.last ? -1 : 1;
345
+ return 0;
346
+ }
347
+
348
+ /** Does the stated date cover any day from `from` to `to` (inclusive, `YYYY-MM-DD`)? */
349
+ export function calendarOverlaps(date: string, from: string, to: string): boolean {
350
+ const c = parseCalendarDate(date);
351
+ return c !== null && c.first <= to && c.last >= from;
352
+ }
353
+
354
+ /** Does the stated date cover the day `ymd`? */
355
+ export function calendarCovers(date: string, ymd: string): boolean {
356
+ return calendarOverlaps(date, ymd, ymd);
357
+ }
358
+
359
+ /**
360
+ * A `YYYY-MM-DD` as a person reads it: `Tue 23 Sep 2026`. Empty for anything
361
+ * that is not a whole, real day — a `2026-08` or a typo is not padded into a day
362
+ * it never named. The string is already a calendar day, so no zone is involved.
363
+ */
364
+ export function readableDate(ymd: string): string {
365
+ const d = dayOf(ymd.trim());
366
+ if (d === null) return "";
367
+ const [y, mo, dd] = ymd.trim().split("-").map(Number) as [number, number, number];
368
+ // Day 0 of the count (1970-01-01) was a Thursday.
369
+ const weekday = WEEKDAYS[(((d + 4) % 7) + 7) % 7];
370
+ return `${weekday} ${String(dd)} ${MONTHS[mo - 1]} ${String(y)}`;
371
+ }
372
+
373
+ /** Legacy name (`self/calendar.ts`, 2026-09-23): the local date of a moment. */
374
+ export const calendarDate = localDate;
package/src/core/types.ts CHANGED
@@ -29,6 +29,19 @@ export const MEMORY_SOURCES = [
29
29
  ] as const;
30
30
  export type MemorySource = (typeof MEMORY_SOURCES)[number];
31
31
 
32
+ /**
33
+ * A model id as the host reports it (`claude-opus-5-5`, `claude-opus-5-5[1m]`),
34
+ * and nothing else: it is printed into a chapter heading and stored on a row
35
+ * (`memories.model`, schema v7), so no spaces, no `·`, no `<synthetic>`.
36
+ * Anything that fails this is treated as unknown.
37
+ *
38
+ * Moved here from `self/episodes.ts` on 2026-09-25 so `store/` can screen the
39
+ * column with the same test the chapter heading uses; `self/` re-exports it.
40
+ */
41
+ export function isModelId(value: unknown): value is string {
42
+ return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:\[\]-]{0,63}$/.test(value);
43
+ }
44
+
32
45
  /** Four dimensions, 0-1, fixed at encoding. novelty is null for a blind write
33
46
  * (no schema context existed) — recorded, never defaulted (scar §2.9). */
34
47
  export interface Salience {