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.
- package/CONSTITUTION.md +68 -0
- package/LICENSE +21 -0
- package/README.md +348 -0
- package/docs/ELI5.md +84 -0
- package/docs/QUICKSTART.md +1258 -0
- package/docs/module-map.md +81 -0
- package/package.json +63 -0
- package/src/adapters/claude-code/CONTRACT.md +606 -0
- package/src/adapters/claude-code/INTERFACE-GAPS.md +655 -0
- package/src/adapters/claude-code/NOTES.md +1055 -0
- package/src/adapters/claude-code/bin/hook.ts +820 -0
- package/src/adapters/claude-code/bin/runner.ts +522 -0
- package/src/adapters/claude-code/config.ts +778 -0
- package/src/adapters/claude-code/credentials.ts +199 -0
- package/src/adapters/claude-code/doctor.ts +2557 -0
- package/src/adapters/claude-code/embed-client.ts +617 -0
- package/src/adapters/claude-code/hooks.ts +2240 -0
- package/src/adapters/claude-code/index.ts +224 -0
- package/src/adapters/claude-code/interpret-client.ts +395 -0
- package/src/adapters/claude-code/page-writer.ts +462 -0
- package/src/adapters/claude-code/primacy.ts +162 -0
- package/src/adapters/claude-code/spawn.ts +241 -0
- package/src/adapters/claude-code/standdown.ts +536 -0
- package/src/adapters/claude-code/transcript.ts +661 -0
- package/src/adapters/claude-code/vectors.ts +415 -0
- package/src/adapters/cli/CONTRACT.md +255 -0
- package/src/adapters/cli/INTERFACE-GAPS.md +350 -0
- package/src/adapters/cli/NOTES.md +936 -0
- package/src/adapters/cli/bin/counterparts.ts +74 -0
- package/src/adapters/cli/commands.ts +6095 -0
- package/src/adapters/cli/export.ts +766 -0
- package/src/adapters/cli/index.ts +103 -0
- package/src/adapters/cli/install.ts +670 -0
- package/src/adapters/cli/removal.ts +1186 -0
- package/src/adapters/cli/repair-dates.ts +659 -0
- package/src/adapters/cli/self-page.ts +229 -0
- package/src/adapters/cli/snapshot.ts +279 -0
- package/src/adapters/cli/start-fresh.ts +1228 -0
- package/src/adapters/config-path.ts +342 -0
- package/src/adapters/dashboard/CONTRACT.md +67 -0
- package/src/adapters/dashboard/INTERFACE-GAPS.md +139 -0
- package/src/adapters/dashboard/NOTES.md +474 -0
- package/src/adapters/dashboard/activity.ts +121 -0
- package/src/adapters/dashboard/ansi.ts +82 -0
- package/src/adapters/dashboard/bin/dashboard.ts +479 -0
- package/src/adapters/dashboard/browse.ts +298 -0
- package/src/adapters/dashboard/identity.ts +182 -0
- package/src/adapters/dashboard/index.ts +183 -0
- package/src/adapters/dashboard/layout.ts +149 -0
- package/src/adapters/dashboard/registries.ts +291 -0
- package/src/adapters/dashboard/resolve.ts +206 -0
- package/src/adapters/dashboard/source.ts +48 -0
- package/src/adapters/dashboard/status.ts +327 -0
- package/src/adapters/dashboard/stories.ts +194 -0
- package/src/adapters/dashboard/web/app.html +1731 -0
- package/src/adapters/dashboard/web/brain.html +463 -0
- package/src/adapters/dashboard/web/fired.ts +31 -0
- package/src/adapters/dashboard/web/flow.ts +457 -0
- package/src/adapters/dashboard/web/narrate.ts +1042 -0
- package/src/adapters/dashboard/web/reveal.ts +135 -0
- package/src/adapters/dashboard/web/server.ts +287 -0
- package/src/adapters/dashboard/web/views.ts +1744 -0
- package/src/adapters/expansions.ts +569 -0
- package/src/adapters/fired.ts +1580 -0
- package/src/adapters/mcp/CONTRACT.md +240 -0
- package/src/adapters/mcp/INTERFACE-GAPS.md +271 -0
- package/src/adapters/mcp/NOTES.md +205 -0
- package/src/adapters/mcp/bin/serve.ts +349 -0
- package/src/adapters/mcp/deliberate.ts +619 -0
- package/src/adapters/mcp/index.ts +101 -0
- package/src/adapters/mcp/protocol.ts +170 -0
- package/src/adapters/mcp/server.ts +1740 -0
- package/src/adapters/mcp/stdio.ts +56 -0
- package/src/adapters/mcp/tools.ts +779 -0
- package/src/adapters/scopes.ts +657 -0
- package/src/adapters/sessions.ts +402 -0
- package/src/adapters/snapshots.ts +1069 -0
- package/src/adapters/stance-env.ts +137 -0
- package/src/core/associate/CONTRACT.md +118 -0
- package/src/core/associate/INTERFACE-GAPS.md +173 -0
- package/src/core/associate/NOTES.md +194 -0
- package/src/core/associate/buffer.ts +66 -0
- package/src/core/associate/edges.ts +188 -0
- package/src/core/associate/index.ts +570 -0
- package/src/core/associate/pending.ts +383 -0
- package/src/core/associate/spread.ts +149 -0
- package/src/core/associate/tunables.ts +123 -0
- package/src/core/bridge.ts +272 -0
- package/src/core/briefing.ts +67 -0
- package/src/core/counterpart.ts +3855 -0
- package/src/core/encode/CONTRACT.md +151 -0
- package/src/core/encode/INTERFACE-GAPS.md +135 -0
- package/src/core/encode/NOTES.md +146 -0
- package/src/core/encode/aliases.ts +71 -0
- package/src/core/encode/battery.ts +284 -0
- package/src/core/encode/chunk.ts +265 -0
- package/src/core/encode/emotion.ts +119 -0
- package/src/core/encode/floor.ts +76 -0
- package/src/core/encode/index.ts +100 -0
- package/src/core/encode/precision.ts +162 -0
- package/src/core/encode/preselect.ts +269 -0
- package/src/core/encode/salience.ts +108 -0
- package/src/core/encode/secrets.ts +265 -0
- package/src/core/encode/tunables.ts +99 -0
- package/src/core/encode/types.ts +286 -0
- package/src/core/encode/words.ts +75 -0
- package/src/core/handoff/CONTRACT.md +199 -0
- package/src/core/handoff/INTERFACE-GAPS.md +166 -0
- package/src/core/handoff/NOTES.md +206 -0
- package/src/core/handoff/index.ts +957 -0
- package/src/core/mint.ts +279 -0
- package/src/core/observer.ts +28 -0
- package/src/core/physics/CONTRACT.md +341 -0
- package/src/core/physics/NOTES.md +155 -0
- package/src/core/physics/clock.ts +51 -0
- package/src/core/physics/index.ts +1054 -0
- package/src/core/prospective/CONTRACT.md +137 -0
- package/src/core/prospective/INTERFACE-GAPS.md +112 -0
- package/src/core/prospective/NOTES.md +160 -0
- package/src/core/prospective/derive.ts +188 -0
- package/src/core/prospective/index.ts +1030 -0
- package/src/core/prospective/tunables.ts +72 -0
- package/src/core/prospective/windows.ts +187 -0
- package/src/core/recall/CONTRACT.md +326 -0
- package/src/core/recall/INTERFACE-GAPS.md +163 -0
- package/src/core/recall/NOTES.md +472 -0
- package/src/core/recall/activate.ts +521 -0
- package/src/core/recall/cues.ts +275 -0
- package/src/core/recall/gate.ts +441 -0
- package/src/core/recall/index.ts +692 -0
- package/src/core/recall/probe.ts +239 -0
- package/src/core/recall/reference.ts +201 -0
- package/src/core/recall/render.ts +285 -0
- package/src/core/recall/session.ts +403 -0
- package/src/core/recall/tunables.ts +329 -0
- package/src/core/remember/CONTRACT.md +293 -0
- package/src/core/remember/INTERFACE-GAPS.md +189 -0
- package/src/core/remember/NOTES.md +373 -0
- package/src/core/remember/fallback.ts +452 -0
- package/src/core/remember/index.ts +103 -0
- package/src/core/remember/owner-strike-seam.ts +479 -0
- package/src/core/remember/proposals.ts +609 -0
- package/src/core/remember/spans.ts +1310 -0
- package/src/core/remember/tunables.ts +111 -0
- package/src/core/remember/updates.ts +198 -0
- package/src/core/retrieval.ts +96 -0
- package/src/core/revision.ts +441 -0
- package/src/core/schemas/CONTRACT.md +190 -0
- package/src/core/schemas/INTERFACE-GAPS.md +172 -0
- package/src/core/schemas/NOTES.md +260 -0
- package/src/core/schemas/aliases.ts +160 -0
- package/src/core/schemas/index.ts +1459 -0
- package/src/core/schemas/tunables.ts +44 -0
- package/src/core/schemas/types.ts +387 -0
- package/src/core/self/CONTRACT.md +459 -0
- package/src/core/self/INTERFACE-GAPS.md +284 -0
- package/src/core/self/NOTES.md +1057 -0
- package/src/core/self/briefing.ts +980 -0
- package/src/core/self/episodes.ts +483 -0
- package/src/core/self/freeze.ts +103 -0
- package/src/core/self/identity.ts +604 -0
- package/src/core/self/index.ts +2130 -0
- package/src/core/self/journal-file.ts +760 -0
- package/src/core/self/page.ts +404 -0
- package/src/core/self/tunables.ts +244 -0
- package/src/core/self/writer.ts +714 -0
- package/src/core/sleep/CONTRACT.md +298 -0
- package/src/core/sleep/INTERFACE-GAPS.md +262 -0
- package/src/core/sleep/NOTES.md +770 -0
- package/src/core/sleep/briefing.ts +86 -0
- package/src/core/sleep/consolidate.ts +241 -0
- package/src/core/sleep/cycle.ts +598 -0
- package/src/core/sleep/decay.ts +237 -0
- package/src/core/sleep/dedup.ts +373 -0
- package/src/core/sleep/index.ts +112 -0
- package/src/core/sleep/log.ts +116 -0
- package/src/core/sleep/markers.ts +164 -0
- package/src/core/sleep/prune.ts +170 -0
- package/src/core/sleep/strength-cache.ts +176 -0
- package/src/core/sleep/tunables.ts +135 -0
- package/src/core/sleep/types.ts +542 -0
- package/src/core/store/CONTRACT.md +446 -0
- package/src/core/store/NOTES.md +1068 -0
- package/src/core/store/cache.ts +709 -0
- package/src/core/store/db.ts +275 -0
- package/src/core/store/errors.ts +134 -0
- package/src/core/store/index.ts +2450 -0
- package/src/core/store/operational.ts +610 -0
- package/src/core/store/owner-op-seam.ts +428 -0
- package/src/core/store/paths.ts +494 -0
- package/src/core/store/prose.ts +165 -0
- package/src/core/store/render.ts +87 -0
- package/src/core/store/walk-seam.ts +78 -0
- package/src/core/types.ts +68 -0
- package/tools/install-loop/run.sh +1063 -0
|
@@ -0,0 +1,2450 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The store seam.
|
|
3
|
+
*
|
|
4
|
+
* TWO boxes behind one object, since the floor (schema v6, 2026-09-20):
|
|
5
|
+
* 2. canonical — `counterparts.sqlite` (box 2, `operational.ts`)
|
|
6
|
+
* 3. rebuildable — `cache/cache.sqlite` (box 3, `cache.ts`)
|
|
7
|
+
*
|
|
8
|
+
* Box 1 — `prose/**.md`, one markdown file per memory — is gone. `memories`
|
|
9
|
+
* carries `title`, `body` and `meta`, and `versions` carries its own copy of the
|
|
10
|
+
* three, so a memory and its history are one row and one transaction. Markdown
|
|
11
|
+
* is an EXPORT (`render.ts`), and `ProseDoc` is still the read shape, which is
|
|
12
|
+
* why `physics/`, `recall/`, `associate/`, `prospective/`, `encode/` and most of
|
|
13
|
+
* `sleep/` never learned the floor moved.
|
|
14
|
+
*
|
|
15
|
+
* What that buys, in the words of the scars it closes: a crash can no longer
|
|
16
|
+
* leave a row whose words are missing (there is no window between "commit the
|
|
17
|
+
* row" and "publish the file"), removing a memory is one transaction rather than
|
|
18
|
+
* a file chase, a backup is one file, and a copied store cannot read or delete
|
|
19
|
+
* the source store's words because there are none outside the database (I22,
|
|
20
|
+
* whose mechanism is deleted and whose criterion is kept).
|
|
21
|
+
*
|
|
22
|
+
* Every write crosses `mutate()`: it checks the observer stance FIRST, then opens a
|
|
23
|
+
* transaction on box 2. That ordering is the point — an instrument refuses before it
|
|
24
|
+
* has staged a byte, and a future caller inherits the refusal instead of having to
|
|
25
|
+
* remember it (observer-mode.md G3, contract §5 G1).
|
|
26
|
+
*
|
|
27
|
+
* There is no delete/remove/unlink/rm export or method anywhere in this module, for
|
|
28
|
+
* prose or anything else. Removal is an owner operation on a structurally distinct
|
|
29
|
+
* path — see `owner-op-seam.ts`; the store's half of it is the append-only removal
|
|
30
|
+
* record plus the deny-list consulted at load and rebuild (§16 G1, G7, G12).
|
|
31
|
+
*
|
|
32
|
+
* The deny-list is consulted HERE, at the seam, so every module inherits the
|
|
33
|
+
* refusal instead of having to remember it: `read`/`readProse`/`physicsOf`/
|
|
34
|
+
* `readVersion` raise a named `REMOVED` rather than an ENOENT on a chased file,
|
|
35
|
+
* `resolve` stops at a removed id instead of dangling past it, and `put` refuses
|
|
36
|
+
* to reuse one. `row()` is the deliberate exception — it is the raw box-2
|
|
37
|
+
* accessor, and an instrument reading the skeleton of a removed memory is how the
|
|
38
|
+
* owner sees that something WAS here (constitution 16).
|
|
39
|
+
*/
|
|
40
|
+
import { existsSync, mkdirSync, readdirSync } from "node:fs";
|
|
41
|
+
import { join } from "node:path";
|
|
42
|
+
import { randomBytes } from "node:crypto";
|
|
43
|
+
import type { Band, Kind, MemoryPhysics, MemorySource, Salience } from "../types.js";
|
|
44
|
+
import { creditUse } from "../physics/index.js";
|
|
45
|
+
import type { CreditOutcome, UseTier } from "../physics/index.js";
|
|
46
|
+
import type { Db } from "./db.js";
|
|
47
|
+
import { StoreError } from "./errors.js";
|
|
48
|
+
import { isObserver } from "../observer.js";
|
|
49
|
+
import type { Stance } from "../observer.js";
|
|
50
|
+
import {
|
|
51
|
+
DEFAULT_RETENTION_DAYS,
|
|
52
|
+
SCHEMA_VERSION,
|
|
53
|
+
openOperational,
|
|
54
|
+
rowToPhysics,
|
|
55
|
+
rowTombstoned,
|
|
56
|
+
} from "./operational.js";
|
|
57
|
+
import type {
|
|
58
|
+
EdgeRow,
|
|
59
|
+
EventRow,
|
|
60
|
+
GateSessionRow,
|
|
61
|
+
MemoryRow,
|
|
62
|
+
ProspectiveRow,
|
|
63
|
+
RemovalRow,
|
|
64
|
+
TombstoneRow,
|
|
65
|
+
VersionRow,
|
|
66
|
+
} from "./operational.js";
|
|
67
|
+
import { grantOwnerOps } from "./owner-op-seam.js";
|
|
68
|
+
import {
|
|
69
|
+
DATABASE_FILE,
|
|
70
|
+
LAYOUT,
|
|
71
|
+
PRE_ROWS_READABLE_BY,
|
|
72
|
+
assertLayoutClassified,
|
|
73
|
+
assertSafeDataDir,
|
|
74
|
+
dataDir,
|
|
75
|
+
paths,
|
|
76
|
+
preRowsLeftoversAreEmpty,
|
|
77
|
+
preRowsMarkersIn,
|
|
78
|
+
} from "./paths.js";
|
|
79
|
+
import {
|
|
80
|
+
ID_PREFIX,
|
|
81
|
+
assertIdWellFormed,
|
|
82
|
+
bodyForStorage,
|
|
83
|
+
hashText,
|
|
84
|
+
parseMeta,
|
|
85
|
+
serializeMeta,
|
|
86
|
+
} from "./prose.js";
|
|
87
|
+
import type { ProseDoc, ProseType } from "./prose.js";
|
|
88
|
+
import {
|
|
89
|
+
DEFAULT_LENGTH_NORM,
|
|
90
|
+
deindexDoc,
|
|
91
|
+
docFrequency,
|
|
92
|
+
embeddingCount,
|
|
93
|
+
indexDoc,
|
|
94
|
+
nearest,
|
|
95
|
+
nearestVectors,
|
|
96
|
+
openCache,
|
|
97
|
+
resetCache,
|
|
98
|
+
searchIndex,
|
|
99
|
+
setEmbedding,
|
|
100
|
+
} from "./cache.js";
|
|
101
|
+
import type { Hit, LengthNorm } from "./cache.js";
|
|
102
|
+
|
|
103
|
+
export * from "./errors.js";
|
|
104
|
+
export * from "../observer.js";
|
|
105
|
+
export * from "./paths.js";
|
|
106
|
+
export * from "./prose.js";
|
|
107
|
+
export * from "./render.js";
|
|
108
|
+
export type { Db, Statement } from "./db.js";
|
|
109
|
+
export type {
|
|
110
|
+
MemoryRow,
|
|
111
|
+
VersionRow,
|
|
112
|
+
EdgeRow,
|
|
113
|
+
EventRow,
|
|
114
|
+
GateSessionRow,
|
|
115
|
+
ProspectiveRow,
|
|
116
|
+
RemovalRow,
|
|
117
|
+
TombstoneRow,
|
|
118
|
+
} from "./operational.js";
|
|
119
|
+
export {
|
|
120
|
+
ADDED_COLUMNS,
|
|
121
|
+
DEFAULT_RETENTION_DAYS,
|
|
122
|
+
isPreRowsDatabase,
|
|
123
|
+
OBSERVER_READ_FLOOR,
|
|
124
|
+
SCHEMA_VERSION,
|
|
125
|
+
rowToPhysics,
|
|
126
|
+
rowTombstoned,
|
|
127
|
+
} from "./operational.js";
|
|
128
|
+
export {
|
|
129
|
+
tokenize,
|
|
130
|
+
cosine,
|
|
131
|
+
CACHE_SCHEMA_VERSION,
|
|
132
|
+
DEFAULT_LENGTH_NORM,
|
|
133
|
+
backfillLengths,
|
|
134
|
+
avgDocLen,
|
|
135
|
+
convertVectorBatch,
|
|
136
|
+
countNonFinite,
|
|
137
|
+
decodeVector,
|
|
138
|
+
encodeVector,
|
|
139
|
+
vectorFormats,
|
|
140
|
+
} from "./cache.js";
|
|
141
|
+
export type { ConvertBatchReport, Hit, LengthNorm, VectorFormatCensus } from "./cache.js";
|
|
142
|
+
// The seam's TYPES travel as one unit (cli/INTERFACE-GAPS §3). The chase itself
|
|
143
|
+
// does not: `chaseRemoved` is importable only from `owner-op-seam.js`, by the one
|
|
144
|
+
// directory the caller-universality test allows (§16 G1–G2).
|
|
145
|
+
export type {
|
|
146
|
+
ChaseReport,
|
|
147
|
+
OwnerRemovalOutcome,
|
|
148
|
+
OwnerRemovalPort,
|
|
149
|
+
OwnerRemovalRequest,
|
|
150
|
+
} from "./owner-op-seam.js";
|
|
151
|
+
|
|
152
|
+
/** Telemetry: ids, hashes, counts, kinds, tiers. Never body text (§5 G10). */
|
|
153
|
+
export interface StoreEvent {
|
|
154
|
+
at: number;
|
|
155
|
+
name: string;
|
|
156
|
+
ref?: string;
|
|
157
|
+
data?: Record<string, string | number | boolean | null>;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Text in, vector out — or NULL when this embedder has no vector for this text.
|
|
162
|
+
*
|
|
163
|
+
* The null arm is load-bearing and was added when the first real embedder was
|
|
164
|
+
* built (`adapters/claude-code/embed-client.ts`). Every production embedder is a
|
|
165
|
+
* network client behind a cache, and `put`/`rebuildCache` are synchronous: a
|
|
166
|
+
* lookup that misses has nothing to return. The two dishonest alternatives are
|
|
167
|
+
* both worse — throwing fails a write over a rebuildable cache, and returning
|
|
168
|
+
* `[]` writes a dim-0 row that `cosine` reads as 0.0 similarity, which is a lie
|
|
169
|
+
* with a number on it. A miss is counted (`unrecomputed`), exactly as a
|
|
170
|
+
* missing embedder already was, and `tools/replay/INTERFACE-GAPS §4` asks for
|
|
171
|
+
* the same shape ("a cache miss must be a counted `not-exercised`").
|
|
172
|
+
*/
|
|
173
|
+
export type Embedder = (text: string) => number[] | null;
|
|
174
|
+
|
|
175
|
+
export interface StoreOptions extends Stance {
|
|
176
|
+
/** Defaults to `dataDir()` — resolved at call time, so tests redirect via env. */
|
|
177
|
+
dir?: string;
|
|
178
|
+
/** Retention for superseded-version rows, in LIVED days. TUNABLE; default 90. */
|
|
179
|
+
retentionDays?: number;
|
|
180
|
+
/** Optional; without it, embeddings are declared un-recomputed at rebuild. */
|
|
181
|
+
embed?: Embedder;
|
|
182
|
+
/**
|
|
183
|
+
* THE PROVENANCE CLOCK (LAUNCH-STATUS §I7, `NOTES.md` 2026-09-05).
|
|
184
|
+
*
|
|
185
|
+
* The session's wall clock, injected. Everything this store records about
|
|
186
|
+
* WHEN IN THE WORLD something happened — `learnedOn`, event `at`, a version's
|
|
187
|
+
* `archived_at`, a removal record's `at` — reads THIS and never the ambient
|
|
188
|
+
* `Date.now`. The PHYSICS clock is a different clock and stays where it is:
|
|
189
|
+
* `livedDay()` counts days the owner actually lived, advanced by
|
|
190
|
+
* `advanceClock()`, and no wall-clock instant moves it.
|
|
191
|
+
*
|
|
192
|
+
* Defaults to `Date.now`, so a host that injects nothing behaves exactly as
|
|
193
|
+
* before. A seeder, a replay harness and a migration pass one.
|
|
194
|
+
*/
|
|
195
|
+
now?: () => number;
|
|
196
|
+
onEvent?: (event: StoreEvent) => void;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export interface PutInput {
|
|
200
|
+
/** Optional; generated when absent. Never reused — a taken id is a hard error. */
|
|
201
|
+
id?: string;
|
|
202
|
+
type: ProseType;
|
|
203
|
+
kind: Kind;
|
|
204
|
+
body: string;
|
|
205
|
+
title?: string;
|
|
206
|
+
happenedOn?: string;
|
|
207
|
+
learnedOn?: string;
|
|
208
|
+
meta?: Record<string, unknown>;
|
|
209
|
+
band?: Band;
|
|
210
|
+
salience?: Partial<Salience>;
|
|
211
|
+
physics?: Partial<Omit<MemoryPhysics, "kind" | "salience">>;
|
|
212
|
+
/** Who is minting (engine-set upstream; see `types.MemorySource`). Absent
|
|
213
|
+
* writes NULL — "unrecorded" — never a defaulted claim of authorship. */
|
|
214
|
+
source?: MemorySource;
|
|
215
|
+
/** Light provenance: ids only, never text (F9, owner ruling 2026-08-29).
|
|
216
|
+
* Mirrored into the prose doc's meta so the document is self-describing.
|
|
217
|
+
*
|
|
218
|
+
* `spanHash` is the buffer's own hash of the span this memory WAS — a jot's
|
|
219
|
+
* own words — and it is here so removal can chase that line by identity
|
|
220
|
+
* rather than by re-deriving it from the body (cli/INTERFACE-GAPS §9). It
|
|
221
|
+
* lives in the prose meta and NOWHERE ELSE on purpose: a hash of low-entropy
|
|
222
|
+
* content is brute-forceable (§16 G9), and the prose document is the one
|
|
223
|
+
* carrier a removal destroys, so the pointer dies with the thing it points
|
|
224
|
+
* at instead of outliving it in a box-2 column. */
|
|
225
|
+
origin?: { session?: string; scope?: string; ref?: string; spanHash?: string };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* A memory's confidentiality class, from its `meta`.
|
|
230
|
+
*
|
|
231
|
+
* The truth table lives HERE, beside the writes that carry it, because it is a
|
|
232
|
+
* gate: `recall/activate.ts#isConfidential` is the same answer by the same
|
|
233
|
+
* function, so the surfacing boundary and `StoredMemory.confidential` can never
|
|
234
|
+
* disagree. Since the floor it is also evaluated ONCE PER WRITE and stored in
|
|
235
|
+
* `memories.confidential`, so the gate no longer parses JSON on every read —
|
|
236
|
+
* a gate that re-parses at every call site is a gate that will one day fail
|
|
237
|
+
* open. The function stays the single definition both the column and the
|
|
238
|
+
* boundary are computed from.
|
|
239
|
+
*/
|
|
240
|
+
export function confidentialByMeta(meta: Readonly<Record<string, unknown>>): boolean {
|
|
241
|
+
if (meta["confidential"] === true) return true;
|
|
242
|
+
const klass = meta["confidentiality"];
|
|
243
|
+
return typeof klass === "string" && klass !== "" && klass !== "open" && klass !== "normal";
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export interface StoredMemory {
|
|
247
|
+
doc: ProseDoc;
|
|
248
|
+
physics: MemoryPhysics;
|
|
249
|
+
band: Band;
|
|
250
|
+
bandDay: number;
|
|
251
|
+
archived: boolean;
|
|
252
|
+
archivedReason: string | null;
|
|
253
|
+
supersededBy: string | null;
|
|
254
|
+
revision: number;
|
|
255
|
+
contentHash: string;
|
|
256
|
+
/** The confidentiality class, read off the ROW's column (written from
|
|
257
|
+
* `confidentialByMeta` at every write). Carried on the read so a caller gates
|
|
258
|
+
* on a boolean rather than on JSON it had to re-interpret. */
|
|
259
|
+
confidential: boolean;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export interface PruneReport {
|
|
263
|
+
pruned: number;
|
|
264
|
+
cutoffDay: number;
|
|
265
|
+
retentionDays: number;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* What one bounded sweep of the durable event log did, and what it left. The
|
|
270
|
+
* sweep is capped per pass, so `pruned` and `eligible` are different numbers
|
|
271
|
+
* and both are reported: a report that said only how many rows went could not
|
|
272
|
+
* tell "the backlog is cleared" from "the cap was hit" (scar §2.4).
|
|
273
|
+
*/
|
|
274
|
+
export interface EventPruneReport extends PruneReport {
|
|
275
|
+
/** Unlatched rows older than the window when the sweep began. */
|
|
276
|
+
eligible: number;
|
|
277
|
+
/** Eligible rows the cap left for the next pass. Zero means the window is clean. */
|
|
278
|
+
remaining: number;
|
|
279
|
+
/** The per-pass cap in force, or null when the caller set none. */
|
|
280
|
+
limit: number | null;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* The durable event log, counted without being touched — what `verify` prints
|
|
285
|
+
* and what an observer's cycle report is computed from. Every number here is a
|
|
286
|
+
* read; nothing in it crosses the write seam.
|
|
287
|
+
*/
|
|
288
|
+
export interface EventLogCensus {
|
|
289
|
+
/** Rows held, latched and unlatched. */
|
|
290
|
+
rows: number;
|
|
291
|
+
/** Rows carrying a `dedup_key` — records, kept at any age. */
|
|
292
|
+
latched: number;
|
|
293
|
+
/** The oldest row's lived day and wall-clock instant, or null on an empty log. */
|
|
294
|
+
oldestDay: number | null;
|
|
295
|
+
oldestAt: number | null;
|
|
296
|
+
newestDay: number | null;
|
|
297
|
+
/** `livedDay - retentionDays`: rows with `day` strictly below it are past the window. */
|
|
298
|
+
cutoffDay: number;
|
|
299
|
+
retentionDays: number;
|
|
300
|
+
/** Unlatched rows past the window — what the next sweep would delete, before its cap. */
|
|
301
|
+
eligible: number;
|
|
302
|
+
/** Latched rows past the window — kept by kind, and counted so "kept" is a number. */
|
|
303
|
+
latchedPastCutoff: number;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export interface RebuildReport {
|
|
307
|
+
indexed: number;
|
|
308
|
+
skippedDenied: number;
|
|
309
|
+
/**
|
|
310
|
+
* Rows that are canonical but not live — archived, or a superseded head. The
|
|
311
|
+
* text index is the index OF THE LIVE STORE (`cache.ts#deindexDoc`), so a
|
|
312
|
+
* rebuild reproduces exactly what `archive`/`supersede` maintain. COUNTED,
|
|
313
|
+
* not silent: `counterparts verify --rebuild` accounts for every canonical
|
|
314
|
+
* row, and a skip that did not appear in the arithmetic would read as a
|
|
315
|
+
* mismatch (I13).
|
|
316
|
+
*/
|
|
317
|
+
skippedArchived: number;
|
|
318
|
+
unrecomputed: number;
|
|
319
|
+
/** Contract §5 G8: what rebuild cannot recompute is DECLARED, with owner + repair. */
|
|
320
|
+
declared: { what: string; owner: string; repair: string }[];
|
|
321
|
+
/** Vectors kept across the rebuild (`keepVectors`), and vectors dropped as
|
|
322
|
+
* no longer canonical — removed ids and orphans. Both zero by default. */
|
|
323
|
+
keptVectors: number;
|
|
324
|
+
droppedVectors: number;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
export interface RebuildOptions {
|
|
328
|
+
/**
|
|
329
|
+
* Re-index the TOKEN side without dropping `embeddings`.
|
|
330
|
+
*
|
|
331
|
+
* Off by default, because the default is the older and louder claim: box 3 is
|
|
332
|
+
* rebuildable and a rebuild rebuilds it. It exists because that claim prices
|
|
333
|
+
* the four tables the same when they are not — a vector costs a paid network
|
|
334
|
+
* call and a console with no embedder cannot replace one at any price
|
|
335
|
+
* (`adapters/cli/NOTES.md`, 2026-09-04, the follow-up filed by PR #43's
|
|
336
|
+
* review). With it on, a vector whose memory is still canonical survives, a
|
|
337
|
+
* vector for a removed or orphaned id is deleted, and a row whose embedder
|
|
338
|
+
* misses keeps the vector it had instead of counting as `unrecomputed`.
|
|
339
|
+
*
|
|
340
|
+
* **A row that already has a vector is not re-embedded**, even when an
|
|
341
|
+
* embedder is wired: keep means keep, and the caller that wants fresh vectors
|
|
342
|
+
* wants a plain `rebuildCache()`. Rows with NO vector are embedded as usual.
|
|
343
|
+
*/
|
|
344
|
+
keepVectors?: boolean;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export interface EdgeInput {
|
|
348
|
+
src: string;
|
|
349
|
+
dst: string;
|
|
350
|
+
weight: number;
|
|
351
|
+
day: number;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
export interface ProspectiveInput {
|
|
355
|
+
memoryId: string;
|
|
356
|
+
windowKey: string;
|
|
357
|
+
eventDate: string;
|
|
358
|
+
precision: "day" | "month" | "year";
|
|
359
|
+
state: "armed" | "fired" | "suppressed" | "expired";
|
|
360
|
+
fires?: number;
|
|
361
|
+
lastFiredDay?: number | null;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* One per-session gate record (SEAMS item B). A ROW, never a re-serialized
|
|
366
|
+
* document: two writers on one session each insert their own record, so a late
|
|
367
|
+
* `resolveUse()` can no longer drop a turn's `recall()` records (scar §2.1).
|
|
368
|
+
*/
|
|
369
|
+
export interface GateRecordInput {
|
|
370
|
+
sessionId: string;
|
|
371
|
+
/** `surfaced` / `credited` (recall), `window` (prospective), `scalar` (row state). */
|
|
372
|
+
kind: string;
|
|
373
|
+
/** Memory id, window key, or — for `scalar` — the field name. */
|
|
374
|
+
ref: string;
|
|
375
|
+
turn: number;
|
|
376
|
+
lastDay: number;
|
|
377
|
+
tier?: string | null;
|
|
378
|
+
/** False when the memory arrived only through ambiguous handles (recall §9 G5). */
|
|
379
|
+
trains?: boolean | null;
|
|
380
|
+
/** JSON for `scalar` records. Never body text (§5 G10). */
|
|
381
|
+
value?: string | null;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* One durable event (SEAMS item K). Content-BY-REFERENCE: ids, hashes, counts,
|
|
386
|
+
* scores, kinds, tiers — never body text, never a user turn.
|
|
387
|
+
*
|
|
388
|
+
* `dedupKey` is the replay latch: an event carrying one lands AT MOST ONCE, ever
|
|
389
|
+
* (sleep §5 G3 — "every day-gated concern is idempotent under replay"), and
|
|
390
|
+
* `appendEvent` returns 0 when the latch held. Telemetry omits it and accumulates.
|
|
391
|
+
*/
|
|
392
|
+
export interface EventInput {
|
|
393
|
+
name: string;
|
|
394
|
+
day: number;
|
|
395
|
+
ref?: string | null;
|
|
396
|
+
dedupKey?: string | null;
|
|
397
|
+
payload?: Record<string, unknown> | null;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
export interface RankingRow {
|
|
401
|
+
id: string;
|
|
402
|
+
strength: number;
|
|
403
|
+
band: Band;
|
|
404
|
+
day: number;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* One removed memory, as it survives: an address, what family it belonged to,
|
|
409
|
+
* what it WAS (protected? identity band?), and counts of what the chase took.
|
|
410
|
+
* No title, no body, no content hash — the same rule as the record (§16 G9).
|
|
411
|
+
*/
|
|
412
|
+
export interface Tombstone {
|
|
413
|
+
readonly id: string;
|
|
414
|
+
readonly type: ProseType;
|
|
415
|
+
readonly kind: Kind;
|
|
416
|
+
readonly band: Band;
|
|
417
|
+
/** Permanent ink at the moment it was removed — why it still shows in the list. */
|
|
418
|
+
readonly wasProtected: boolean;
|
|
419
|
+
readonly wasPromotedIdentity: boolean;
|
|
420
|
+
readonly supersededBy: string | null;
|
|
421
|
+
readonly stage: RemovalNote["stage"];
|
|
422
|
+
readonly at: number;
|
|
423
|
+
/** True while a stripped skeleton row survives to carry lineage pointers. */
|
|
424
|
+
readonly rowSurvives: boolean;
|
|
425
|
+
readonly chased: {
|
|
426
|
+
readonly versions: number;
|
|
427
|
+
readonly edges: number;
|
|
428
|
+
readonly prospective: number;
|
|
429
|
+
readonly gateRows: number;
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/** No body, no content hash — hashing low-entropy content leaks it (§16 G9). */
|
|
434
|
+
export interface RemovalNote {
|
|
435
|
+
memoryId: string;
|
|
436
|
+
stage: "requested" | "dark" | "chased" | "complete";
|
|
437
|
+
actor: string;
|
|
438
|
+
reason?: string;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Every method that can change durable state. The totality test asserts this list
|
|
443
|
+
* equals the set of sites that consult the observer predicate, and that each one
|
|
444
|
+
* refuses under observer (observer-mode.md G6: every stand-down is observable).
|
|
445
|
+
*/
|
|
446
|
+
/**
|
|
447
|
+
* The backfill's give-up counter: `embed.failed.<id>` in box 2's meta, and the
|
|
448
|
+
* number of ITEM-ATTRIBUTABLE failures after which `missingVectors` stops
|
|
449
|
+
* offering that id.
|
|
450
|
+
*
|
|
451
|
+
* **Only the failures the provider blamed on the item itself may move it** — a
|
|
452
|
+
* 400 the bisector narrowed down to one input (`ChunkFailure.item`). A 429, a
|
|
453
|
+
* 5xx, a dropped socket, an aborted watchdog or a malformed body says nothing
|
|
454
|
+
* about WHICH input is bad, and counting those was I33 inverted: three bad
|
|
455
|
+
* boundaries in a row would retire a whole healthy window and `unembeddedCount`
|
|
456
|
+
* — the coverage watch — would then read COMPLETE while those memories stayed
|
|
457
|
+
* blind. Three rather than one because even a 400 can be answered for a reason
|
|
458
|
+
* that is not the text.
|
|
459
|
+
*
|
|
460
|
+
* Written by whoever runs the backfill (`adapters/claude-code/vectors.ts`),
|
|
461
|
+
* cleared the moment an id embeds, and cleared wholesale by
|
|
462
|
+
* `counterparts verify --retry-skipped` — which is the remedy a repaired title
|
|
463
|
+
* needs, because a skipped id is never offered again and so can never clear
|
|
464
|
+
* itself. Meta keys only — no schema bump (precedent: `sleep.pruned.<id>`).
|
|
465
|
+
*/
|
|
466
|
+
export const EMBED_FAILED_PREFIX = "embed.failed.";
|
|
467
|
+
export const EMBED_SKIP_AFTER = 3;
|
|
468
|
+
|
|
469
|
+
export const WRITE_METHODS = [
|
|
470
|
+
"put",
|
|
471
|
+
"putMany",
|
|
472
|
+
"revise",
|
|
473
|
+
"supersede",
|
|
474
|
+
"archive",
|
|
475
|
+
"updatePhysics",
|
|
476
|
+
"reinforce",
|
|
477
|
+
"setBand",
|
|
478
|
+
"link",
|
|
479
|
+
"linkMany",
|
|
480
|
+
"setProspective",
|
|
481
|
+
"advanceClock",
|
|
482
|
+
"setMeta",
|
|
483
|
+
"setMetaMany",
|
|
484
|
+
"setGateRecords",
|
|
485
|
+
"pruneGateSessions",
|
|
486
|
+
"appendEvent",
|
|
487
|
+
"pruneEvents",
|
|
488
|
+
"setRanking",
|
|
489
|
+
"pruneSupersededVersions",
|
|
490
|
+
"appendRemovalRecord",
|
|
491
|
+
"rebuildCache",
|
|
492
|
+
"pruneDeadIndex",
|
|
493
|
+
"embedOne",
|
|
494
|
+
] as const;
|
|
495
|
+
|
|
496
|
+
export type WriteMethod = (typeof WRITE_METHODS)[number];
|
|
497
|
+
|
|
498
|
+
const MAX_CHAIN = 32;
|
|
499
|
+
const EVENT_RING = 500;
|
|
500
|
+
|
|
501
|
+
/** What `list()` and `countMemories()` both select on — one filter, one WHERE. */
|
|
502
|
+
export interface MemoryFilter {
|
|
503
|
+
type?: ProseType;
|
|
504
|
+
kind?: Kind;
|
|
505
|
+
band?: Band;
|
|
506
|
+
archived?: boolean;
|
|
507
|
+
/**
|
|
508
|
+
* WHO WROTE IT — the mint-source doctrine's column (`authored`, `fallback`,
|
|
509
|
+
* `episode`, `migrated`). Nullable in the schema on purpose, so a filter on a
|
|
510
|
+
* source never matches a row that predates the doctrine, which is what a
|
|
511
|
+
* caller asking "how many did the author write" wants.
|
|
512
|
+
*/
|
|
513
|
+
source?: string;
|
|
514
|
+
/**
|
|
515
|
+
* BORN ON OR AFTER this calendar date, `YYYY-MM-DD` — a string comparison,
|
|
516
|
+
* which is exact for that spelling. Undated rows carry `learned_on = ''`
|
|
517
|
+
* (`self/briefing.ts`) and are excluded by the same comparison, which is
|
|
518
|
+
* right: a row with no date is not a row born in a window.
|
|
519
|
+
*/
|
|
520
|
+
learnedOnFrom?: string;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function memoryWhere(filter: MemoryFilter): { clause: string; args: (string | number)[] } {
|
|
524
|
+
const where: string[] = [];
|
|
525
|
+
const args: (string | number)[] = [];
|
|
526
|
+
if (filter.type) {
|
|
527
|
+
where.push("type = ?");
|
|
528
|
+
args.push(filter.type);
|
|
529
|
+
}
|
|
530
|
+
if (filter.kind) {
|
|
531
|
+
where.push("kind = ?");
|
|
532
|
+
args.push(filter.kind);
|
|
533
|
+
}
|
|
534
|
+
if (filter.band) {
|
|
535
|
+
where.push("band = ?");
|
|
536
|
+
args.push(filter.band);
|
|
537
|
+
}
|
|
538
|
+
if (filter.archived !== undefined) {
|
|
539
|
+
where.push("archived = ?");
|
|
540
|
+
args.push(filter.archived ? 1 : 0);
|
|
541
|
+
}
|
|
542
|
+
if (filter.source !== undefined) {
|
|
543
|
+
where.push("source = ?");
|
|
544
|
+
args.push(filter.source);
|
|
545
|
+
}
|
|
546
|
+
if (filter.learnedOnFrom !== undefined) {
|
|
547
|
+
where.push("learned_on >= ?");
|
|
548
|
+
args.push(filter.learnedOnFrom);
|
|
549
|
+
}
|
|
550
|
+
return { clause: where.length ? `WHERE ${where.join(" AND ")}` : "", args };
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
export class Store {
|
|
554
|
+
readonly dir: string;
|
|
555
|
+
readonly observer: boolean;
|
|
556
|
+
readonly retentionDays: number;
|
|
557
|
+
private readonly ops: Db;
|
|
558
|
+
private readonly cache: Db;
|
|
559
|
+
private readonly embed: Embedder | undefined;
|
|
560
|
+
/** The provenance clock (§I7). The ONE `Date.now` in this file is its default. */
|
|
561
|
+
private readonly nowFn: () => number;
|
|
562
|
+
private readonly onEvent: ((e: StoreEvent) => void) | undefined;
|
|
563
|
+
private readonly ring: StoreEvent[] = [];
|
|
564
|
+
|
|
565
|
+
private constructor(opts: StoreOptions) {
|
|
566
|
+
// The guard runs on EVERY path, explicit or defaulted — an explicit `dir`
|
|
567
|
+
// reaching mkdirSync unchecked is how a test once deposited a skeleton
|
|
568
|
+
// inside the live v1 store (found by the caller-universality build, fixed
|
|
569
|
+
// at this root the same day).
|
|
570
|
+
this.dir = assertSafeDataDir(opts.dir ?? dataDir());
|
|
571
|
+
this.observer = isObserver(opts);
|
|
572
|
+
this.retentionDays = opts.retentionDays ?? DEFAULT_RETENTION_DAYS;
|
|
573
|
+
this.embed = opts.embed;
|
|
574
|
+
this.nowFn = opts.now ?? Date.now;
|
|
575
|
+
this.onEvent = opts.onEvent;
|
|
576
|
+
|
|
577
|
+
// ── THE PRE-ROWS REFUSAL, AND IT IS THE FIRST THING THAT HAPPENS ───────
|
|
578
|
+
//
|
|
579
|
+
// Before `fresh`, before the first `mkdirSync`, before `openOperational`,
|
|
580
|
+
// before `assertLayout` — because every one of those writes something, and
|
|
581
|
+
// the whole promise of this refusal is that a store written by an older
|
|
582
|
+
// floor is left BYTE-IDENTICAL by an attempt to open it.
|
|
583
|
+
//
|
|
584
|
+
// The hazard it closes is the one thing in this rebuild that could destroy
|
|
585
|
+
// the owner's live memory. `openOperational` migrates any store below
|
|
586
|
+
// `SCHEMA_VERSION`; a v5 store reaching it would get `body` NULL on every
|
|
587
|
+
// row while its words sat in ~16,000 markdown files this build cannot see,
|
|
588
|
+
// and it would then be stamped v6 — unreadable by the build that CAN read
|
|
589
|
+
// it. There is no migration and there is not going to be one (owner ruling
|
|
590
|
+
// 6): the cut-over carries nothing and he starts as a new user.
|
|
591
|
+
//
|
|
592
|
+
// ORDER MATTERS TWICE OVER. `assertLayout()` would also refuse a v5 store,
|
|
593
|
+
// on the unclassified `prose/` — but only after the database had been
|
|
594
|
+
// opened and a blank `counterparts.sqlite` minted beside the old one, and a
|
|
595
|
+
// refusal that names the layout instead of the floor is the wrong sentence
|
|
596
|
+
// for somebody looking at three weeks of memory.
|
|
597
|
+
//
|
|
598
|
+
// It reads FILENAMES, never the old database (`preRowsMarkersIn`): since F1
|
|
599
|
+
// the live store is in WAL, so an open-and-close to read its schema version
|
|
600
|
+
// could checkpoint and remove its `-wal` — moving the bytes of the store
|
|
601
|
+
// this exists to leave alone. `openOperational` carries the SECOND lock,
|
|
602
|
+
// for a v5 database wearing the v6 name, where the file is already open and
|
|
603
|
+
// that argument no longer applies.
|
|
604
|
+
const preRows = preRowsMarkersIn(this.dir);
|
|
605
|
+
if (preRows.length > 0) {
|
|
606
|
+
throw new StoreError("STORE_PRE_ROWS", {
|
|
607
|
+
dir: this.dir,
|
|
608
|
+
// ALL of them, not the first: a refusal that named only
|
|
609
|
+
// `operational.sqlite` never mentioned the 16,000 files under `prose/`,
|
|
610
|
+
// which is the part the owner would want named.
|
|
611
|
+
found: preRows.join(", "),
|
|
612
|
+
expected: SCHEMA_VERSION,
|
|
613
|
+
...preRowsRemedy(this.dir, preRows),
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// AN INSTRUMENT WRITES NOTHING AT OPEN when there is a store to read.
|
|
618
|
+
//
|
|
619
|
+
// The old constructor ran the DDL and four meta upserts on every open,
|
|
620
|
+
// whatever the stance — and a write at open takes SQLite's write lock, which
|
|
621
|
+
// is how a live `counterparts backup` threw "database is locked" while a
|
|
622
|
+
// session held an open transaction (live-verify 2026-08-25; CLI CONTRACT §5
|
|
623
|
+
// G8 says a backup never throws). An up-to-date store now opens clean, and a
|
|
624
|
+
// store that is a schema BEHIND refuses under observer by name rather than
|
|
625
|
+
// migrating itself out from under the process that owns it.
|
|
626
|
+
//
|
|
627
|
+
// An ABSENT store refuses under observer too (cli INTERFACE-GAPS §7, closed
|
|
628
|
+
// 2026-08-26). There is no lock to contend for there — but "an instrument
|
|
629
|
+
// that MINTS a data dir by looking at one is a wart" (`statusCommand`), and
|
|
630
|
+
// a stood-down hook with an unreadable config was exactly the caller that
|
|
631
|
+
// would quietly deposit a skeleton store on a machine that had none. Same
|
|
632
|
+
// named refusal as the schema-behind case: to a reader, "not created yet"
|
|
633
|
+
// and "not migrated yet" are one condition — nothing here to read.
|
|
634
|
+
const fresh = !existsSync(paths.operational(this.dir));
|
|
635
|
+
if (this.observer && fresh) {
|
|
636
|
+
throw new StoreError("STORE_UNINITIALIZED", {
|
|
637
|
+
path: paths.operational(this.dir),
|
|
638
|
+
expected: SCHEMA_VERSION,
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
// ONE DIRECTORY, either way: box 3's. `prose/`, `versions/` and `tmp/` went
|
|
642
|
+
// with the floor — the canonical box is a single file SQLite makes itself,
|
|
643
|
+
// and there is nothing left to stage. Box 3's container is made even under
|
|
644
|
+
// observer, and only because it is DECLARED rebuildable: an instrument
|
|
645
|
+
// needs somewhere to open the cache, and materializing the cache's own
|
|
646
|
+
// directory changes no canonical state and takes no canonical lock.
|
|
647
|
+
mkdirSync(paths.cacheDir(this.dir), { recursive: true });
|
|
648
|
+
this.ops = openOperational(paths.operational(this.dir), {
|
|
649
|
+
initialize: !this.observer,
|
|
650
|
+
retentionDays: this.retentionDays,
|
|
651
|
+
});
|
|
652
|
+
this.cache = openCache(paths.cache(this.dir));
|
|
653
|
+
// The owner-op capability. Handed to the seam module, never to a caller:
|
|
654
|
+
// holding a Store gives you no way to destroy anything, and `ownerMutate`
|
|
655
|
+
// routes the chase through the same stance check every write crosses.
|
|
656
|
+
grantOwnerOps(this, {
|
|
657
|
+
dir: this.dir,
|
|
658
|
+
ownerMutate: (site, fn) => {
|
|
659
|
+
this.assertWritable(site);
|
|
660
|
+
return this.ops.transaction(() => fn(this.ops));
|
|
661
|
+
},
|
|
662
|
+
rawRow: (id) => this.row(id),
|
|
663
|
+
isDenied: (id) => this.isDenied(id),
|
|
664
|
+
// The narrowest possible route to box 3, and the LEXICAL half only: it
|
|
665
|
+
// rewrites `doc_tokens` / `doc_lens` for one id from that id's own prose,
|
|
666
|
+
// and leaves the `embeddings` row exactly where it is (`indexDoc` writes a
|
|
667
|
+
// vector only when it is HANDED one, and it is not handed one here). A
|
|
668
|
+
// restore must never make a paid embedding call, and it must never drop a
|
|
669
|
+
// vector it cannot recompute.
|
|
670
|
+
//
|
|
671
|
+
// It exists because `archive()` is on its way to DEINDEXING (PR #64,
|
|
672
|
+
// `overnight/df-live-rows`, counts document frequency over live rows by
|
|
673
|
+
// removing archived rows from the index). Without this, whichever of the
|
|
674
|
+
// two lands second leaves `unarchiveMerged` restoring a row that is live,
|
|
675
|
+
// listed in `beliefs(entity)`, and invisible to lexical recall — with no
|
|
676
|
+
// cheap repair, since a cache rebuild without an embedder drops every
|
|
677
|
+
// vector on the store. Harmless on a master where `archive()` still
|
|
678
|
+
// leaves the index alone: re-indexing an already-indexed row from its own
|
|
679
|
+
// prose is a write of the same rows.
|
|
680
|
+
reindexLexical: (id) => {
|
|
681
|
+
const row = this.row(id);
|
|
682
|
+
if (row === undefined) return;
|
|
683
|
+
indexDoc(this.cache, id, indexTextOf(row.title, row.body));
|
|
684
|
+
},
|
|
685
|
+
});
|
|
686
|
+
this.assertLayout();
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
static open(opts: StoreOptions = {}): Store {
|
|
690
|
+
return new Store(opts);
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
close(): void {
|
|
694
|
+
this.ops.close();
|
|
695
|
+
this.cache.close();
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
// ── the seam ───────────────────────────────────────────────────────────────
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* The one place a write becomes durable. Stance first, transaction second: an
|
|
702
|
+
* observer refuses before any staging, and a partial multi-row change is
|
|
703
|
+
* impossible because box 2 rolls back as a unit.
|
|
704
|
+
*/
|
|
705
|
+
private mutate<T>(site: WriteMethod, fn: () => T): T {
|
|
706
|
+
this.assertWritable(site);
|
|
707
|
+
return this.ops.transaction(fn);
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
/** `chaseRemoved` and `unarchiveMerged` are not Store methods — they are the
|
|
711
|
+
* owner-op seam's, and they cross the same stance check, which is why their
|
|
712
|
+
* site names are spelled here. */
|
|
713
|
+
private assertWritable(site: WriteMethod | "chaseRemoved" | "unarchiveMerged"): void {
|
|
714
|
+
if (this.observer) {
|
|
715
|
+
// Telemetry is the deliberate exception: a stood-down instrument must be
|
|
716
|
+
// distinguishable from a broken hook (observer-mode.md G5/G6, scar §2.4).
|
|
717
|
+
this.emit("store.observer.standdown", undefined, { site });
|
|
718
|
+
throw new StoreError("OBSERVER_REFUSED", { site });
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
private emit(
|
|
723
|
+
name: string,
|
|
724
|
+
ref?: string,
|
|
725
|
+
data?: Record<string, string | number | boolean | null>,
|
|
726
|
+
): void {
|
|
727
|
+
const event: StoreEvent = { at: this.nowFn(), name };
|
|
728
|
+
if (ref !== undefined) event.ref = ref;
|
|
729
|
+
if (data !== undefined) event.data = data;
|
|
730
|
+
this.ring.push(event);
|
|
731
|
+
if (this.ring.length > EVENT_RING) this.ring.shift();
|
|
732
|
+
this.onEvent?.(event);
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
/**
|
|
736
|
+
* The provenance clock's instant, and the calendar date it falls on.
|
|
737
|
+
*
|
|
738
|
+
* TWO CLOCKS, and this is the second one. `livedDay()` above is the physics
|
|
739
|
+
* clock — how much EXPERIENCE has passed, which is what decay and
|
|
740
|
+
* consolidation run on. These two say WHEN IN THE WORLD, which is what a
|
|
741
|
+
* memory's provenance is made of. A caller that wants "the date this store
|
|
742
|
+
* thinks it is" asks here rather than reading the ambient clock, so a seeded,
|
|
743
|
+
* replayed or migrated store dates its rows by the run it is replaying.
|
|
744
|
+
*
|
|
745
|
+
* UTC, like every other date this codebase writes (the hooks' own
|
|
746
|
+
* `new Date().toISOString().slice(0, 10)`, `sleep/cycle.ts#todayDate`). Local
|
|
747
|
+
* dating is a separate question with a separate answer; see NOTES 2026-09-05.
|
|
748
|
+
*/
|
|
749
|
+
now(): number {
|
|
750
|
+
return this.nowFn();
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
today(): string {
|
|
754
|
+
return dateOf(this.nowFn());
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
/** Copies, ordered oldest first. Optionally filtered by name. */
|
|
758
|
+
events(name?: string): StoreEvent[] {
|
|
759
|
+
return this.ring.filter((e) => name === undefined || e.name === name).map((e) => ({ ...e }));
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/** Contract §5 G11: a top-level path nobody classified fails loudly. */
|
|
763
|
+
assertLayout(): void {
|
|
764
|
+
assertLayoutClassified(readdirSync(this.dir));
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
backupSet(): string[] {
|
|
768
|
+
return LAYOUT.filter((e) => e.backup).map((e) => e.name);
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
// ── writes ─────────────────────────────────────────────────────────────────
|
|
772
|
+
|
|
773
|
+
put(input: PutInput): string {
|
|
774
|
+
const doc = this.mutate("put", () => this.insertOne(input));
|
|
775
|
+
this.indexOne(doc);
|
|
776
|
+
this.emit("store.put", doc.id, { type: doc.type, kind: input.kind, hash: hashText(doc.body) });
|
|
777
|
+
return doc.id;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
/**
|
|
781
|
+
* Atomic by default: one bad input and NOTHING lands. `isolate: true` opts into
|
|
782
|
+
* per-item persistence isolation (§16 G6) — the failure is logged and skipped and
|
|
783
|
+
* the rest persist. Two different promises; the caller picks, out loud.
|
|
784
|
+
*/
|
|
785
|
+
putMany(inputs: readonly PutInput[], opts: { isolate?: boolean } = {}): string[] {
|
|
786
|
+
const landed = this.mutate("putMany", () => {
|
|
787
|
+
const out: { doc: ProseDoc; input: PutInput }[] = [];
|
|
788
|
+
for (const input of inputs) {
|
|
789
|
+
try {
|
|
790
|
+
// A SAVEPOINT PER ITEM under `isolate`, not a bare call. The insert
|
|
791
|
+
// used to be preceded by a file stage that validated everything
|
|
792
|
+
// first, so a throw happened before any row was written; now the
|
|
793
|
+
// validation and the INSERT are in the same method, and a failure
|
|
794
|
+
// after the INSERT — a constraint, a foreign key, anything a later
|
|
795
|
+
// reviewer adds below it — would otherwise be swallowed here and
|
|
796
|
+
// COMMITTED by the outer transaction. `Db.transaction` nests as
|
|
797
|
+
// SAVEPOINT / ROLLBACK TO, so per-item isolation is structural
|
|
798
|
+
// (§16 G6) rather than a property of the current line order.
|
|
799
|
+
out.push({ doc: this.isolatedInsert(input, opts.isolate === true), input });
|
|
800
|
+
} catch (err) {
|
|
801
|
+
if (!opts.isolate) throw err;
|
|
802
|
+
this.emit("store.put.skipped", input.id, {
|
|
803
|
+
reason: err instanceof StoreError ? err.code : "UNKNOWN",
|
|
804
|
+
});
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
return out;
|
|
808
|
+
});
|
|
809
|
+
for (const s of landed) {
|
|
810
|
+
this.indexOne(s.doc);
|
|
811
|
+
this.emit("store.put", s.doc.id, {
|
|
812
|
+
type: s.doc.type,
|
|
813
|
+
kind: s.input.kind,
|
|
814
|
+
hash: hashText(s.doc.body),
|
|
815
|
+
});
|
|
816
|
+
}
|
|
817
|
+
return landed.map((s) => s.doc.id);
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
/** `insertOne`, inside its own savepoint when the caller asked for isolation. */
|
|
821
|
+
private isolatedInsert(input: PutInput, isolate: boolean): ProseDoc {
|
|
822
|
+
return isolate ? this.ops.transaction(() => this.insertOne(input)) : this.insertOne(input);
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
/**
|
|
826
|
+
* In-place content revision. The prior version is written in the SAME
|
|
827
|
+
* transaction as the update (§16 G4) — not before it, because there is no
|
|
828
|
+
* longer a before: the version is a row, not a file copied out of the way.
|
|
829
|
+
*
|
|
830
|
+
* `learnedOn` / `happenedOn` are the PROVENANCE half, and they travel this same
|
|
831
|
+
* door on purpose (§I7, `NOTES.md` 2026-09-05): correcting a date is a change to
|
|
832
|
+
* canonical content, so it keeps the prior version exactly the way a body change
|
|
833
|
+
* does — constitution 7, nothing is silently overwritten and the old date stays
|
|
834
|
+
* readable in the version. **That is why `versions` carries `learned_on` and
|
|
835
|
+
* `happened_on` of its own**, which the floor plan did not ask for: with the
|
|
836
|
+
* dates read off the live row instead, one correction would have silently
|
|
837
|
+
* rewritten every version behind it.
|
|
838
|
+
*/
|
|
839
|
+
revise(
|
|
840
|
+
id: string,
|
|
841
|
+
patch: {
|
|
842
|
+
body?: string;
|
|
843
|
+
title?: string;
|
|
844
|
+
meta?: Record<string, unknown>;
|
|
845
|
+
learnedOn?: string;
|
|
846
|
+
happenedOn?: string;
|
|
847
|
+
reason?: string;
|
|
848
|
+
},
|
|
849
|
+
): number {
|
|
850
|
+
const { doc, seq, hash } = this.mutate("revise", () => {
|
|
851
|
+
const row = this.requireRow(id);
|
|
852
|
+
const prior = this.docOf(row);
|
|
853
|
+
const seq = row.revision + 1;
|
|
854
|
+
// THE PRIOR VERSION, WORDS AND ALL, IN THE SAME TRANSACTION. It used to be
|
|
855
|
+
// a file copied into `versions/<id>/` before the new text was staged, with
|
|
856
|
+
// a `wx` collision loop and a crash window between the two; it is now a
|
|
857
|
+
// row written beside the update, so "an overwrite keeps the prior version"
|
|
858
|
+
// is a property of the transaction rather than of the ordering (§5 G5).
|
|
859
|
+
this.ops.run(
|
|
860
|
+
`INSERT INTO versions
|
|
861
|
+
(memory_id, seq, reason, version_day, archived_at, content_hash, successor_id,
|
|
862
|
+
title, body, meta, learned_on, happened_on)
|
|
863
|
+
VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?)`,
|
|
864
|
+
id,
|
|
865
|
+
seq,
|
|
866
|
+
patch.reason ?? "revise",
|
|
867
|
+
this.livedDay(),
|
|
868
|
+
this.nowFn(),
|
|
869
|
+
row.content_hash,
|
|
870
|
+
row.title,
|
|
871
|
+
row.body,
|
|
872
|
+
row.meta,
|
|
873
|
+
row.learned_on,
|
|
874
|
+
row.happened_on,
|
|
875
|
+
);
|
|
876
|
+
const next: ProseDoc = {
|
|
877
|
+
...prior,
|
|
878
|
+
body: patch.body ?? prior.body,
|
|
879
|
+
meta: patch.meta ? { ...prior.meta, ...patch.meta } : prior.meta,
|
|
880
|
+
};
|
|
881
|
+
if (patch.title !== undefined) next.title = patch.title;
|
|
882
|
+
if (patch.learnedOn !== undefined) next.learnedOn = patch.learnedOn;
|
|
883
|
+
if (patch.happenedOn !== undefined) next.happenedOn = patch.happenedOn;
|
|
884
|
+
// THE SAME RULE AS `put`, through the same function. `patch.body ?? ...`
|
|
885
|
+
// accepts `""` happily, and on this floor that would write the one state
|
|
886
|
+
// no write path may produce — a row whose hash names words its body no
|
|
887
|
+
// longer holds, which every read answers as `MEMORY_BODY_MISSING` and
|
|
888
|
+
// which takes the next session's `Schemas.open` down on a schema row.
|
|
889
|
+
// Whitespace-only and a lone surrogate go through it too.
|
|
890
|
+
next.body = bodyForStorage(next.body, id);
|
|
891
|
+
const nextHash = hashText(next.body);
|
|
892
|
+
this.ops.run(
|
|
893
|
+
`UPDATE memories
|
|
894
|
+
SET content_hash = ?, revision = ?, title = ?, body = ?, meta = ?,
|
|
895
|
+
confidential = ?, learned_on = ?, happened_on = ?
|
|
896
|
+
WHERE id = ?`,
|
|
897
|
+
nextHash,
|
|
898
|
+
seq,
|
|
899
|
+
next.title ?? null,
|
|
900
|
+
next.body,
|
|
901
|
+
serializeMeta(next.meta, id),
|
|
902
|
+
// RECOMPUTED, never carried: a revision that patches `meta` can turn
|
|
903
|
+
// the confidentiality gate on or off, and a column that went stale
|
|
904
|
+
// against its own truth table is a gate that fails open silently.
|
|
905
|
+
confidentialByMeta(next.meta) ? 1 : 0,
|
|
906
|
+
next.learnedOn,
|
|
907
|
+
next.happenedOn ?? null,
|
|
908
|
+
id,
|
|
909
|
+
);
|
|
910
|
+
return { doc: next, seq, hash: nextHash };
|
|
911
|
+
});
|
|
912
|
+
this.indexOne(doc);
|
|
913
|
+
this.emit("store.revise", id, { seq, hash });
|
|
914
|
+
return seq;
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/**
|
|
918
|
+
* Supersession: the new memory is born, the old one keeps its id, its prose, and
|
|
919
|
+
* a forwarding address. `resolve(oldId)` follows it forever — the VERSION ROW is
|
|
920
|
+
* what expires at H, not the ability to resolve (§5 G4, §16 G3).
|
|
921
|
+
*/
|
|
922
|
+
supersede(oldId: string, input: PutInput, reason = "supersede"): string {
|
|
923
|
+
const { doc, newId } = this.mutate("supersede", () => {
|
|
924
|
+
const row = this.requireRow(oldId);
|
|
925
|
+
const created = this.insertOne(input);
|
|
926
|
+
// The version row carries a COPY of the head's words rather than a pointer
|
|
927
|
+
// to the file both used to share. The head keeps its own row and its own
|
|
928
|
+
// body too, so the text is held twice for as long as the version row
|
|
929
|
+
// lives — the honest cost of rows over files, bounded by the 90-day
|
|
930
|
+
// version prune (owner ruling 1). See `store/NOTES.md`.
|
|
931
|
+
this.ops.run(
|
|
932
|
+
`INSERT INTO versions
|
|
933
|
+
(memory_id, seq, reason, version_day, archived_at, content_hash, successor_id,
|
|
934
|
+
title, body, meta, learned_on, happened_on)
|
|
935
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
936
|
+
oldId,
|
|
937
|
+
row.revision + 1,
|
|
938
|
+
reason,
|
|
939
|
+
this.livedDay(),
|
|
940
|
+
this.nowFn(),
|
|
941
|
+
row.content_hash,
|
|
942
|
+
created.id,
|
|
943
|
+
row.title,
|
|
944
|
+
row.body,
|
|
945
|
+
row.meta,
|
|
946
|
+
row.learned_on,
|
|
947
|
+
row.happened_on,
|
|
948
|
+
);
|
|
949
|
+
this.ops.run(
|
|
950
|
+
`UPDATE memories SET superseded_by = ?, archived = 1, archived_reason = ?, revision = ?
|
|
951
|
+
WHERE id = ?`,
|
|
952
|
+
created.id,
|
|
953
|
+
reason,
|
|
954
|
+
row.revision + 1,
|
|
955
|
+
oldId,
|
|
956
|
+
);
|
|
957
|
+
return { doc: created, newId: created.id };
|
|
958
|
+
});
|
|
959
|
+
this.indexOne(doc);
|
|
960
|
+
// The head leaves box 3 as the successor enters it. Box 2 keeps the row,
|
|
961
|
+
// the prose and the forwarding address — this is the INDEX, and the index
|
|
962
|
+
// is the index of the live store (`cache.ts#deindexDoc`).
|
|
963
|
+
deindexDoc(this.cache, oldId);
|
|
964
|
+
this.emit("store.supersede", oldId, { successor: newId, reason });
|
|
965
|
+
return newId;
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/** Archive is a state, not a deletion: the id stays resolvable (§4.2 G3). */
|
|
969
|
+
archive(id: string, reason: string): void {
|
|
970
|
+
this.mutate("archive", () => {
|
|
971
|
+
this.requireRow(id);
|
|
972
|
+
this.ops.run("UPDATE memories SET archived = 1, archived_reason = ? WHERE id = ?", reason, id);
|
|
973
|
+
});
|
|
974
|
+
// Out of the index, not out of the store: `read`, `resolve` and the version
|
|
975
|
+
// chain are untouched. An archived row was never deliverable — `activate`
|
|
976
|
+
// discards the hit — and while it stayed indexed it went on voting on
|
|
977
|
+
// rarity against a live denominator (`cache.ts#deindexDoc`, I13).
|
|
978
|
+
deindexDoc(this.cache, id);
|
|
979
|
+
this.emit("store.archive", id, { reason });
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
/**
|
|
983
|
+
* Physics-only bookkeeping. It never rewrites prose, which is why v1's
|
|
984
|
+
* "strength-only exemption to archive-on-overwrite" is not ported: with physics in
|
|
985
|
+
* box 2 the exemption is structural rather than a line-level diff (see NOTES.md).
|
|
986
|
+
*/
|
|
987
|
+
updatePhysics(id: string, patch: Partial<MemoryPhysics>): void {
|
|
988
|
+
this.mutate("updatePhysics", () => {
|
|
989
|
+
this.requireRow(id);
|
|
990
|
+
const sets: string[] = [];
|
|
991
|
+
const args: (string | number | null)[] = [];
|
|
992
|
+
const put = (col: string, val: string | number | null) => {
|
|
993
|
+
sets.push(`${col} = ?`);
|
|
994
|
+
args.push(val);
|
|
995
|
+
};
|
|
996
|
+
if (patch.kind !== undefined) put("kind", patch.kind);
|
|
997
|
+
if (patch.salience !== undefined) {
|
|
998
|
+
put("novelty", patch.salience.novelty);
|
|
999
|
+
put("relevance", patch.salience.relevance);
|
|
1000
|
+
put("emotional", patch.salience.emotional);
|
|
1001
|
+
put("predictive", patch.salience.predictive);
|
|
1002
|
+
put("claimed", patch.salience.claimed ?? null);
|
|
1003
|
+
}
|
|
1004
|
+
if (patch.birthDay !== undefined) put("birth_day", patch.birthDay);
|
|
1005
|
+
if (patch.uses !== undefined) put("uses", patch.uses);
|
|
1006
|
+
if (patch.lastUsedDay !== undefined) put("last_used_day", patch.lastUsedDay);
|
|
1007
|
+
if (patch.reinforcedDays !== undefined) put("reinforced_days", patch.reinforcedDays);
|
|
1008
|
+
if (patch.consolidated !== undefined) put("consolidated", patch.consolidated ? 1 : 0);
|
|
1009
|
+
if (patch.promotedIdentity !== undefined)
|
|
1010
|
+
put("promoted_identity", patch.promotedIdentity ? 1 : 0);
|
|
1011
|
+
if (patch.protected !== undefined) put("protected", patch.protected ? 1 : 0);
|
|
1012
|
+
if (patch.pressure !== undefined) put("pressure", patch.pressure);
|
|
1013
|
+
if (patch.lastChallengedDay !== undefined)
|
|
1014
|
+
put("last_challenged_day", patch.lastChallengedDay);
|
|
1015
|
+
if (sets.length === 0) return;
|
|
1016
|
+
this.ops.run(`UPDATE memories SET ${sets.join(", ")} WHERE id = ?`, ...args, id);
|
|
1017
|
+
});
|
|
1018
|
+
this.emit("store.physics", id, { fields: Object.keys(patch).join(",") });
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
/**
|
|
1022
|
+
* Persist one credited use. The crediting RULE is owned entirely by
|
|
1023
|
+
* physics.creditUse (§5.5 tier weights, birth-day / stale-day / same-day
|
|
1024
|
+
* refusals, distinct-day counting for §5.3 promotion) — the store applies the
|
|
1025
|
+
* verdict absolutely and adds no opinion of its own. One rule, one owner:
|
|
1026
|
+
* a second implementation of this arithmetic is exactly the divergence that
|
|
1027
|
+
* produced v1's "two clocks" fiction.
|
|
1028
|
+
*/
|
|
1029
|
+
reinforce(id: string, day: number, tier: UseTier = "referenced"): CreditOutcome {
|
|
1030
|
+
const outcome = this.mutate("reinforce", () => {
|
|
1031
|
+
const row = this.requireRow(id);
|
|
1032
|
+
const verdict = creditUse(rowToPhysics(row), day, tier);
|
|
1033
|
+
if (verdict.credited) {
|
|
1034
|
+
this.ops.run(
|
|
1035
|
+
`UPDATE memories
|
|
1036
|
+
SET uses = ?, last_used_day = ?, reinforced_days = ?
|
|
1037
|
+
WHERE id = ?`,
|
|
1038
|
+
verdict.next.uses,
|
|
1039
|
+
verdict.next.lastUsedDay,
|
|
1040
|
+
verdict.next.reinforcedDays,
|
|
1041
|
+
id,
|
|
1042
|
+
);
|
|
1043
|
+
}
|
|
1044
|
+
return verdict;
|
|
1045
|
+
});
|
|
1046
|
+
this.emit("store.reinforce", id, {
|
|
1047
|
+
credited: outcome.credited,
|
|
1048
|
+
reason: outcome.reason,
|
|
1049
|
+
day,
|
|
1050
|
+
tier,
|
|
1051
|
+
});
|
|
1052
|
+
return outcome;
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
setBand(id: string, band: Band, day: number): void {
|
|
1056
|
+
this.mutate("setBand", () => {
|
|
1057
|
+
this.requireRow(id);
|
|
1058
|
+
this.ops.run("UPDATE memories SET band = ?, band_day = ? WHERE id = ?", band, day, id);
|
|
1059
|
+
});
|
|
1060
|
+
this.emit("store.band", id, { band, day });
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
link(edge: EdgeInput): void {
|
|
1064
|
+
this.mutate("link", () => {
|
|
1065
|
+
this.ops.run(
|
|
1066
|
+
"INSERT OR REPLACE INTO edges (src, dst, weight, last_day) VALUES (?, ?, ?, ?)",
|
|
1067
|
+
edge.src,
|
|
1068
|
+
edge.dst,
|
|
1069
|
+
edge.weight,
|
|
1070
|
+
edge.day,
|
|
1071
|
+
);
|
|
1072
|
+
});
|
|
1073
|
+
this.emit("store.link", edge.src, { dst: edge.dst, weight: edge.weight });
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
/** Multi-row and foreign-keyed: one bad endpoint rolls the whole batch back. */
|
|
1077
|
+
linkMany(edges: readonly EdgeInput[]): void {
|
|
1078
|
+
this.mutate("linkMany", () => {
|
|
1079
|
+
const st = this.ops.prepare(
|
|
1080
|
+
"INSERT OR REPLACE INTO edges (src, dst, weight, last_day) VALUES (?, ?, ?, ?)",
|
|
1081
|
+
);
|
|
1082
|
+
for (const e of edges) st.run(e.src, e.dst, e.weight, e.day);
|
|
1083
|
+
});
|
|
1084
|
+
this.emit("store.link", undefined, { count: edges.length });
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
setProspective(entry: ProspectiveInput): void {
|
|
1088
|
+
this.mutate("setProspective", () => {
|
|
1089
|
+
this.requireRow(entry.memoryId);
|
|
1090
|
+
this.ops.run(
|
|
1091
|
+
`INSERT OR REPLACE INTO prospective
|
|
1092
|
+
(memory_id, window_key, event_date, precision, state, fires, last_fired_day)
|
|
1093
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
1094
|
+
entry.memoryId,
|
|
1095
|
+
entry.windowKey,
|
|
1096
|
+
entry.eventDate,
|
|
1097
|
+
entry.precision,
|
|
1098
|
+
entry.state,
|
|
1099
|
+
entry.fires ?? 0,
|
|
1100
|
+
entry.lastFiredDay ?? null,
|
|
1101
|
+
);
|
|
1102
|
+
});
|
|
1103
|
+
this.emit("store.prospective", entry.memoryId, {
|
|
1104
|
+
window: entry.windowKey,
|
|
1105
|
+
state: entry.state,
|
|
1106
|
+
});
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
/** The active-day clock (scar E8): days actually lived, not calendar days. */
|
|
1110
|
+
advanceClock(date: string): number {
|
|
1111
|
+
const day = this.mutate("advanceClock", () => {
|
|
1112
|
+
const last = this.getMeta("lastActiveDate") ?? "";
|
|
1113
|
+
if (last !== "" && date < last) {
|
|
1114
|
+
throw new StoreError("CLOCK_BACKWARDS", { date, last });
|
|
1115
|
+
}
|
|
1116
|
+
if (date === last) return this.livedDay();
|
|
1117
|
+
const next = this.livedDay() + 1;
|
|
1118
|
+
this.ops.run("UPDATE meta SET value = ? WHERE key = 'livedDay'", String(next));
|
|
1119
|
+
this.ops.run("UPDATE meta SET value = ? WHERE key = 'lastActiveDate'", date);
|
|
1120
|
+
return next;
|
|
1121
|
+
});
|
|
1122
|
+
this.emit("store.clock", undefined, { livedDay: day, date });
|
|
1123
|
+
return day;
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
setMeta(key: string, value: string): void {
|
|
1127
|
+
this.mutate("setMeta", () => {
|
|
1128
|
+
this.ops.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)", key, value);
|
|
1129
|
+
});
|
|
1130
|
+
this.emit("store.meta", undefined, { key });
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
/**
|
|
1134
|
+
* Many meta rows, ONE transaction and one ring line.
|
|
1135
|
+
*
|
|
1136
|
+
* `setMeta` in a loop is one write transaction — one lock acquisition — per
|
|
1137
|
+
* key, and the caller this exists for moves a whole window's worth of the
|
|
1138
|
+
* backfill's give-up counters at a boundary where the adapter has measured six
|
|
1139
|
+
* overlapping workers against a 5 s busy timeout (adapter `NOTES.md`, I33).
|
|
1140
|
+
* One `mutate` is one acquisition and rolls back as a unit: the same bargain
|
|
1141
|
+
* `linkMany` and `setRanking` already make, and the reason the ring gets a
|
|
1142
|
+
* count here rather than N identical `key` lines.
|
|
1143
|
+
*
|
|
1144
|
+
* Keys repeated within one call resolve last-wins, as `INSERT OR REPLACE` does
|
|
1145
|
+
* anywhere else. An empty list still crosses the stance check, because a
|
|
1146
|
+
* stand-down that depends on how much work there was is not a stand-down.
|
|
1147
|
+
*/
|
|
1148
|
+
setMetaMany(entries: readonly (readonly [string, string])[]): void {
|
|
1149
|
+
this.mutate("setMetaMany", () => {
|
|
1150
|
+
for (const [key, value] of entries) {
|
|
1151
|
+
this.ops.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)", key, value);
|
|
1152
|
+
}
|
|
1153
|
+
});
|
|
1154
|
+
this.emit("store.meta", undefined, { count: entries.length });
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
// ── box 2: per-session gate state (SEAMS item B) ───────────────────────────
|
|
1158
|
+
|
|
1159
|
+
/**
|
|
1160
|
+
* Upsert gate records. One transaction, one row per record — a writer replaces
|
|
1161
|
+
* only the records it names, so two processes in one session cannot drop each
|
|
1162
|
+
* other's (recall/INTERFACE-GAPS.md §1, scar §2.1).
|
|
1163
|
+
*/
|
|
1164
|
+
setGateRecords(rows: readonly GateRecordInput[]): void {
|
|
1165
|
+
// Stance FIRST, then the empty check: an observer must refuse even a no-op
|
|
1166
|
+
// write, or the stand-down becomes conditional on the payload (G6).
|
|
1167
|
+
this.assertWritable("setGateRecords");
|
|
1168
|
+
if (rows.length === 0) return;
|
|
1169
|
+
this.ops.transaction(() => {
|
|
1170
|
+
const st = this.ops.prepare(
|
|
1171
|
+
`INSERT OR REPLACE INTO gate_session
|
|
1172
|
+
(session_id, kind, ref, turn, tier, trains, value, last_day)
|
|
1173
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
1174
|
+
);
|
|
1175
|
+
for (const r of rows) {
|
|
1176
|
+
st.run(
|
|
1177
|
+
r.sessionId,
|
|
1178
|
+
r.kind,
|
|
1179
|
+
r.ref,
|
|
1180
|
+
r.turn,
|
|
1181
|
+
r.tier ?? null,
|
|
1182
|
+
r.trains === undefined || r.trains === null ? null : r.trains ? 1 : 0,
|
|
1183
|
+
r.value ?? null,
|
|
1184
|
+
r.lastDay,
|
|
1185
|
+
);
|
|
1186
|
+
}
|
|
1187
|
+
});
|
|
1188
|
+
this.emit("store.gate.records", undefined, { count: rows.length });
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
gateRecords(sessionId: string, kind?: string): GateSessionRow[] {
|
|
1192
|
+
return kind === undefined
|
|
1193
|
+
? this.ops.all<GateSessionRow>(
|
|
1194
|
+
"SELECT * FROM gate_session WHERE session_id = ? ORDER BY kind, ref",
|
|
1195
|
+
sessionId,
|
|
1196
|
+
)
|
|
1197
|
+
: this.ops.all<GateSessionRow>(
|
|
1198
|
+
"SELECT * FROM gate_session WHERE session_id = ? AND kind = ? ORDER BY ref",
|
|
1199
|
+
sessionId,
|
|
1200
|
+
kind,
|
|
1201
|
+
);
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
/**
|
|
1205
|
+
* The retention sweep the meta keyspace could never have (recall's gap §1: "a
|
|
1206
|
+
* long-lived store accumulates one dead row per session forever"). Operational
|
|
1207
|
+
* state with a lifetime, swept on the active-day clock beside the version prune.
|
|
1208
|
+
*/
|
|
1209
|
+
pruneGateSessions(): PruneReport {
|
|
1210
|
+
const report = this.mutate("pruneGateSessions", () => {
|
|
1211
|
+
const cutoffDay = this.livedDay() - this.retentionDays;
|
|
1212
|
+
const doomed = this.ops.get<{ n: number }>(
|
|
1213
|
+
"SELECT COUNT(*) AS n FROM gate_session WHERE last_day < ?",
|
|
1214
|
+
cutoffDay,
|
|
1215
|
+
);
|
|
1216
|
+
this.ops.run("DELETE FROM gate_session WHERE last_day < ?", cutoffDay);
|
|
1217
|
+
return { pruned: doomed?.n ?? 0, cutoffDay, retentionDays: this.retentionDays };
|
|
1218
|
+
});
|
|
1219
|
+
this.emit("store.gate.pruned", undefined, {
|
|
1220
|
+
count: report.pruned,
|
|
1221
|
+
cutoffDay: report.cutoffDay,
|
|
1222
|
+
});
|
|
1223
|
+
return report;
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
// ── box 2: the durable event log (SEAMS item K) ────────────────────────────
|
|
1227
|
+
|
|
1228
|
+
/**
|
|
1229
|
+
* Append one event. Returns its seq, or 0 when a `dedupKey` latch refused a
|
|
1230
|
+
* repeat — the caller can tell "recorded" from "already recorded", which is
|
|
1231
|
+
* what replay idempotence needs to stay a fact rather than a hope.
|
|
1232
|
+
*/
|
|
1233
|
+
appendEvent(input: EventInput): number {
|
|
1234
|
+
const seq = this.mutate("appendEvent", () => {
|
|
1235
|
+
this.ops.run(
|
|
1236
|
+
`INSERT OR IGNORE INTO events (at, day, name, ref, dedup_key, payload)
|
|
1237
|
+
VALUES (?, ?, ?, ?, ?, ?)`,
|
|
1238
|
+
this.nowFn(),
|
|
1239
|
+
input.day,
|
|
1240
|
+
input.name,
|
|
1241
|
+
input.ref ?? null,
|
|
1242
|
+
input.dedupKey ?? null,
|
|
1243
|
+
input.payload === undefined || input.payload === null
|
|
1244
|
+
? null
|
|
1245
|
+
: JSON.stringify(input.payload),
|
|
1246
|
+
);
|
|
1247
|
+
const row = this.ops.get<{ n: number }>("SELECT changes() AS n");
|
|
1248
|
+
if ((row?.n ?? 0) === 0) return 0;
|
|
1249
|
+
return this.ops.get<{ seq: number }>("SELECT last_insert_rowid() AS seq")?.seq ?? 0;
|
|
1250
|
+
});
|
|
1251
|
+
this.emit("store.event.appended", input.ref ?? undefined, {
|
|
1252
|
+
name: input.name,
|
|
1253
|
+
seq,
|
|
1254
|
+
deduped: seq === 0,
|
|
1255
|
+
});
|
|
1256
|
+
return seq;
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
/** Oldest first, so a story reads in the order it happened. */
|
|
1260
|
+
eventLog(filter: { name?: string; ref?: string; sinceDay?: number; limit?: number } = {}): EventRow[] {
|
|
1261
|
+
const where: string[] = [];
|
|
1262
|
+
const args: (string | number)[] = [];
|
|
1263
|
+
if (filter.name !== undefined) {
|
|
1264
|
+
where.push("name = ?");
|
|
1265
|
+
args.push(filter.name);
|
|
1266
|
+
}
|
|
1267
|
+
if (filter.ref !== undefined) {
|
|
1268
|
+
where.push("ref = ?");
|
|
1269
|
+
args.push(filter.ref);
|
|
1270
|
+
}
|
|
1271
|
+
if (filter.sinceDay !== undefined) {
|
|
1272
|
+
where.push("day >= ?");
|
|
1273
|
+
args.push(filter.sinceDay);
|
|
1274
|
+
}
|
|
1275
|
+
const sql =
|
|
1276
|
+
"SELECT * FROM events" +
|
|
1277
|
+
(where.length === 0 ? "" : ` WHERE ${where.join(" AND ")}`) +
|
|
1278
|
+
" ORDER BY seq ASC LIMIT ?";
|
|
1279
|
+
return this.ops.all<EventRow>(sql, ...args, filter.limit ?? 500);
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
/**
|
|
1283
|
+
* Bounded retention — logs are telemetry, not canonical memory: "the one
|
|
1284
|
+
* system-path exception to no-deletion — bounded-retention logs"
|
|
1285
|
+
* (`docs/harvest/behavioral-spec.md` #17, v1's `pruneLogs` in `log-audit.md`
|
|
1286
|
+
* §3). Events carrying a `dedupKey` are KEPT regardless of age: they are the
|
|
1287
|
+
* replay latch, and sweeping one would let a replayed day re-append a record
|
|
1288
|
+
* the store already accounted for.
|
|
1289
|
+
*
|
|
1290
|
+
* `limit` caps the rows one call deletes, OLDEST FIRST by `seq`, so a pass on a
|
|
1291
|
+
* store that has never been swept cannot run long or hold the write lock across
|
|
1292
|
+
* a backlog: it takes the cap's worth and reports how much is left. Its caller
|
|
1293
|
+
* is `sleep/log.ts`, on the cycle's own budget; before 2026-09-05 nothing
|
|
1294
|
+
* called this at all (`sleep/NOTES.md` §13), and the window it documents was
|
|
1295
|
+
* a number the log was eligible for and never subject to.
|
|
1296
|
+
*/
|
|
1297
|
+
pruneEvents(opts: { limit?: number } = {}): EventPruneReport {
|
|
1298
|
+
const limit = opts.limit === undefined ? null : Math.max(0, Math.floor(opts.limit));
|
|
1299
|
+
const report = this.mutate("pruneEvents", () => {
|
|
1300
|
+
const cutoffDay = this.livedDay() - this.retentionDays;
|
|
1301
|
+
const eligible =
|
|
1302
|
+
this.ops.get<{ n: number }>(
|
|
1303
|
+
"SELECT COUNT(*) AS n FROM events WHERE day < ? AND dedup_key IS NULL",
|
|
1304
|
+
cutoffDay,
|
|
1305
|
+
)?.n ?? 0;
|
|
1306
|
+
if (limit === null) {
|
|
1307
|
+
this.ops.run("DELETE FROM events WHERE day < ? AND dedup_key IS NULL", cutoffDay);
|
|
1308
|
+
} else {
|
|
1309
|
+
this.ops.run(
|
|
1310
|
+
`DELETE FROM events WHERE seq IN (
|
|
1311
|
+
SELECT seq FROM events WHERE day < ? AND dedup_key IS NULL
|
|
1312
|
+
ORDER BY seq ASC LIMIT ?)`,
|
|
1313
|
+
cutoffDay,
|
|
1314
|
+
limit,
|
|
1315
|
+
);
|
|
1316
|
+
}
|
|
1317
|
+
const pruned = this.ops.get<{ n: number }>("SELECT changes() AS n")?.n ?? 0;
|
|
1318
|
+
return {
|
|
1319
|
+
pruned,
|
|
1320
|
+
eligible,
|
|
1321
|
+
remaining: eligible - pruned,
|
|
1322
|
+
limit,
|
|
1323
|
+
cutoffDay,
|
|
1324
|
+
retentionDays: this.retentionDays,
|
|
1325
|
+
};
|
|
1326
|
+
});
|
|
1327
|
+
this.emit("store.events.pruned", undefined, {
|
|
1328
|
+
count: report.pruned,
|
|
1329
|
+
eligible: report.eligible,
|
|
1330
|
+
remaining: report.remaining,
|
|
1331
|
+
limit: report.limit,
|
|
1332
|
+
cutoffDay: report.cutoffDay,
|
|
1333
|
+
retentionDays: report.retentionDays,
|
|
1334
|
+
});
|
|
1335
|
+
return report;
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
/**
|
|
1339
|
+
* The log counted, not touched. READ-ONLY by construction — it never calls
|
|
1340
|
+
* `mutate`, so an observer may ask it (the cycle's read-only report does) and
|
|
1341
|
+
* `counterparts verify` prints it without opening a writable store.
|
|
1342
|
+
*/
|
|
1343
|
+
eventLogCensus(): EventLogCensus {
|
|
1344
|
+
const cutoffDay = this.livedDay() - this.retentionDays;
|
|
1345
|
+
const totals = this.ops.get<{
|
|
1346
|
+
total: number;
|
|
1347
|
+
latched: number;
|
|
1348
|
+
oldest_day: number | null;
|
|
1349
|
+
oldest_at: number | null;
|
|
1350
|
+
newest_day: number | null;
|
|
1351
|
+
}>(
|
|
1352
|
+
`SELECT COUNT(*) AS total,
|
|
1353
|
+
COUNT(dedup_key) AS latched,
|
|
1354
|
+
MIN(day) AS oldest_day,
|
|
1355
|
+
MIN(at) AS oldest_at,
|
|
1356
|
+
MAX(day) AS newest_day
|
|
1357
|
+
FROM events`,
|
|
1358
|
+
);
|
|
1359
|
+
const past = this.ops.get<{ eligible: number; latched: number }>(
|
|
1360
|
+
`SELECT COUNT(*) - COUNT(dedup_key) AS eligible,
|
|
1361
|
+
COUNT(dedup_key) AS latched
|
|
1362
|
+
FROM events WHERE day < ?`,
|
|
1363
|
+
cutoffDay,
|
|
1364
|
+
);
|
|
1365
|
+
return {
|
|
1366
|
+
rows: totals?.total ?? 0,
|
|
1367
|
+
latched: totals?.latched ?? 0,
|
|
1368
|
+
oldestDay: totals?.oldest_day ?? null,
|
|
1369
|
+
oldestAt: totals?.oldest_at ?? null,
|
|
1370
|
+
newestDay: totals?.newest_day ?? null,
|
|
1371
|
+
cutoffDay,
|
|
1372
|
+
retentionDays: this.retentionDays,
|
|
1373
|
+
eligible: past?.eligible ?? 0,
|
|
1374
|
+
latchedPastCutoff: past?.latched ?? 0,
|
|
1375
|
+
};
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
// ── box 3: the ranking cache (SEAMS item J) ────────────────────────────────
|
|
1379
|
+
|
|
1380
|
+
/**
|
|
1381
|
+
* Materialize `strength(m, d)` / `band(m, d)` into box 3. Box 3 only: nothing
|
|
1382
|
+
* here is truth, and `rebuildCache()` drops it with the rest of the cache. A
|
|
1383
|
+
* replayed day is a no-op by construction — same state, same day, same number.
|
|
1384
|
+
*/
|
|
1385
|
+
setRanking(rows: readonly RankingRow[]): void {
|
|
1386
|
+
this.assertWritable("setRanking");
|
|
1387
|
+
if (rows.length === 0) return;
|
|
1388
|
+
this.cache.transaction(() => {
|
|
1389
|
+
const st = this.cache.prepare(
|
|
1390
|
+
"INSERT OR REPLACE INTO ranking (memory_id, strength, band, day) VALUES (?, ?, ?, ?)",
|
|
1391
|
+
);
|
|
1392
|
+
for (const r of rows) st.run(r.id, r.strength, r.band, r.day);
|
|
1393
|
+
});
|
|
1394
|
+
this.emit("store.ranking", undefined, { count: rows.length });
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
ranking(id: string): RankingRow | undefined {
|
|
1398
|
+
const row = this.cache.get<{ memory_id: string; strength: number; band: string; day: number }>(
|
|
1399
|
+
"SELECT * FROM ranking WHERE memory_id = ?",
|
|
1400
|
+
id,
|
|
1401
|
+
);
|
|
1402
|
+
return row === undefined
|
|
1403
|
+
? undefined
|
|
1404
|
+
: { id: row.memory_id, strength: row.strength, band: row.band as Band, day: row.day };
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
rankingAll(): Map<string, RankingRow> {
|
|
1408
|
+
const out = new Map<string, RankingRow>();
|
|
1409
|
+
for (const row of this.cache.all<{
|
|
1410
|
+
memory_id: string;
|
|
1411
|
+
strength: number;
|
|
1412
|
+
band: string;
|
|
1413
|
+
day: number;
|
|
1414
|
+
}>("SELECT * FROM ranking")) {
|
|
1415
|
+
out.set(row.memory_id, {
|
|
1416
|
+
id: row.memory_id,
|
|
1417
|
+
strength: row.strength,
|
|
1418
|
+
band: row.band as Band,
|
|
1419
|
+
day: row.day,
|
|
1420
|
+
});
|
|
1421
|
+
}
|
|
1422
|
+
return out;
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
/**
|
|
1426
|
+
* Bounded versioning (contract §4): superseded-version rows older than H lived
|
|
1427
|
+
* days go. Every discard reports what and how much (scar §2.4).
|
|
1428
|
+
*
|
|
1429
|
+
* **THIS DELETES THE OWNER'S EARLIER WORDS, and since the floor that is the
|
|
1430
|
+
* plain truth of it.** The line that used to stand here said "the archived
|
|
1431
|
+
* prose file is left where it is — this module destroys nothing", and it was
|
|
1432
|
+
* true: a version row was a NOTE about a file nothing ever unlinked, so the
|
|
1433
|
+
* prune cost the history its index and not one word. The words are IN the row
|
|
1434
|
+
* now, so at H the wording itself is gone.
|
|
1435
|
+
*
|
|
1436
|
+
* Kept anyway, at 90 lived days (owner ruling 1, 2026-09-18), and his reason
|
|
1437
|
+
* is the general steer: simple, elegant working-memory mechanics over keeping
|
|
1438
|
+
* everything, and losing some history after a month or two is an acceptable
|
|
1439
|
+
* price. Our own store sets `retentionDays` high for debugging.
|
|
1440
|
+
* `test/self-page.test.ts` makes the cost visible on the self page, which is
|
|
1441
|
+
* where an owner would feel it first.
|
|
1442
|
+
*/
|
|
1443
|
+
pruneSupersededVersions(): PruneReport {
|
|
1444
|
+
const report = this.mutate("pruneSupersededVersions", () => {
|
|
1445
|
+
const cutoffDay = this.livedDay() - this.retentionDays;
|
|
1446
|
+
const doomed = this.ops.all<VersionRow>(
|
|
1447
|
+
"SELECT * FROM versions WHERE version_day < ?",
|
|
1448
|
+
cutoffDay,
|
|
1449
|
+
);
|
|
1450
|
+
this.ops.run("DELETE FROM versions WHERE version_day < ?", cutoffDay);
|
|
1451
|
+
return { pruned: doomed.length, cutoffDay, retentionDays: this.retentionDays };
|
|
1452
|
+
});
|
|
1453
|
+
this.emit("store.versions.pruned", undefined, {
|
|
1454
|
+
count: report.pruned,
|
|
1455
|
+
cutoffDay: report.cutoffDay,
|
|
1456
|
+
retentionDays: report.retentionDays,
|
|
1457
|
+
});
|
|
1458
|
+
return report;
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
/**
|
|
1462
|
+
* The store's half of the owner-removal seam: the canonical, append-only record.
|
|
1463
|
+
* A later stage appends; it never rewrites the earlier line (§16 G8). If this
|
|
1464
|
+
* cannot be written, the caller must move nothing (§16 G10).
|
|
1465
|
+
*/
|
|
1466
|
+
appendRemovalRecord(note: RemovalNote): number {
|
|
1467
|
+
const seq = this.mutate("appendRemovalRecord", () => {
|
|
1468
|
+
this.ops.run(
|
|
1469
|
+
"INSERT INTO removal_record (memory_id, stage, at, actor, reason) VALUES (?, ?, ?, ?, ?)",
|
|
1470
|
+
note.memoryId,
|
|
1471
|
+
note.stage,
|
|
1472
|
+
this.nowFn(),
|
|
1473
|
+
note.actor,
|
|
1474
|
+
note.reason ?? null,
|
|
1475
|
+
);
|
|
1476
|
+
const row = this.ops.get<{ seq: number }>("SELECT last_insert_rowid() AS seq");
|
|
1477
|
+
return row?.seq ?? 0;
|
|
1478
|
+
});
|
|
1479
|
+
this.emit("store.removal.recorded", note.memoryId, { stage: note.stage, seq });
|
|
1480
|
+
return seq;
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
/**
|
|
1484
|
+
* Box 3 only. Deleting the cache file and calling this must lose nothing
|
|
1485
|
+
* canonical; what cannot be recomputed is declared and counted (§5 G8).
|
|
1486
|
+
*/
|
|
1487
|
+
rebuildCache(opts: RebuildOptions = {}): RebuildReport {
|
|
1488
|
+
this.assertWritable("rebuildCache");
|
|
1489
|
+
const keepVectors = opts.keepVectors === true;
|
|
1490
|
+
// Read the surviving vector ids BEFORE the reset, so "kept" is a count and
|
|
1491
|
+
// not an assumption, and so the sweep below knows what it is sweeping.
|
|
1492
|
+
const heldVectors = keepVectors
|
|
1493
|
+
? new Set(
|
|
1494
|
+
this.cache
|
|
1495
|
+
.all<{ memory_id: string }>("SELECT memory_id FROM embeddings")
|
|
1496
|
+
.map((r) => r.memory_id),
|
|
1497
|
+
)
|
|
1498
|
+
: new Set<string>();
|
|
1499
|
+
resetCache(this.cache, { keepEmbeddings: keepVectors });
|
|
1500
|
+
const denied = new Set(this.deniedIds());
|
|
1501
|
+
const rows = this.ops.all<MemoryRow>("SELECT * FROM memories ORDER BY id");
|
|
1502
|
+
let indexed = 0;
|
|
1503
|
+
let skippedDenied = 0;
|
|
1504
|
+
let skippedArchived = 0;
|
|
1505
|
+
let unrecomputed = 0;
|
|
1506
|
+
for (const row of rows) {
|
|
1507
|
+
if (denied.has(row.id)) {
|
|
1508
|
+
// A stray copy of a removed memory is skipped and LOGGED, never deleted (§16 G12).
|
|
1509
|
+
skippedDenied += 1;
|
|
1510
|
+
this.emit("cache.rebuild.denied", row.id, {});
|
|
1511
|
+
continue;
|
|
1512
|
+
}
|
|
1513
|
+
// Not live, not indexed. `archive` and `supersede` take a row out of box 3
|
|
1514
|
+
// as it goes dark; a rebuild that put it back would restore the I13 bug on
|
|
1515
|
+
// the owner's next `verify --rebuild` — the index's denominator would
|
|
1516
|
+
// count rows `recall`'s `storeSize` does not.
|
|
1517
|
+
if (row.archived === 1 || row.superseded_by !== null) {
|
|
1518
|
+
skippedArchived += 1;
|
|
1519
|
+
continue;
|
|
1520
|
+
}
|
|
1521
|
+
const text = indexTextOf(row.title, row.body);
|
|
1522
|
+
// KEEP MEANS KEEP. A row that already has a vector is not offered to the
|
|
1523
|
+
// embedder at all under `keepVectors` — the first version called it and
|
|
1524
|
+
// let `indexDoc` overwrite what it had just promised to preserve, so a
|
|
1525
|
+
// process with an embedder wired paid a network call per row and reported
|
|
1526
|
+
// the result as `keptVectors`. Two words for one behaviour is how an API
|
|
1527
|
+
// starts lying; the name picks the behaviour, and the caller that wants
|
|
1528
|
+
// fresh vectors wants a plain `rebuildCache()`.
|
|
1529
|
+
const held = keepVectors && heldVectors.has(row.id);
|
|
1530
|
+
const vec = held ? null : this.embed ? this.embed(text) : null;
|
|
1531
|
+
if (vec !== null) indexDoc(this.cache, row.id, text, vec);
|
|
1532
|
+
else {
|
|
1533
|
+
indexDoc(this.cache, row.id, text);
|
|
1534
|
+
// A miss is only a LOSS when there was nothing there to keep. Under
|
|
1535
|
+
// `keepVectors` the row's existing vector is still in the table, so
|
|
1536
|
+
// counting it un-recomputed would report a gap box 3 does not have.
|
|
1537
|
+
if (!held) unrecomputed += 1;
|
|
1538
|
+
}
|
|
1539
|
+
indexed += 1;
|
|
1540
|
+
}
|
|
1541
|
+
// Vectors whose memory is no longer canonical do NOT survive a rebuild —
|
|
1542
|
+
// `keepVectors` preserves the cache, it does not resurrect a removed
|
|
1543
|
+
// memory's trace (§16 G12) or keep an orphan the set diff would then report
|
|
1544
|
+
// forever. Deleted here rather than skipped, because the plain rebuild
|
|
1545
|
+
// drops them by dropping the table and the two paths must agree.
|
|
1546
|
+
let droppedVectors = 0;
|
|
1547
|
+
let keptVectors = 0;
|
|
1548
|
+
if (keepVectors && heldVectors.size > 0) {
|
|
1549
|
+
const canonical = new Set(rows.map((r) => r.id));
|
|
1550
|
+
const del = this.cache.prepare("DELETE FROM embeddings WHERE memory_id = ?");
|
|
1551
|
+
this.cache.transaction(() => {
|
|
1552
|
+
for (const id of heldVectors) {
|
|
1553
|
+
if (!canonical.has(id) || denied.has(id)) {
|
|
1554
|
+
del.run(id);
|
|
1555
|
+
droppedVectors += 1;
|
|
1556
|
+
} else keptVectors += 1;
|
|
1557
|
+
}
|
|
1558
|
+
});
|
|
1559
|
+
}
|
|
1560
|
+
// Declared when there is no embedder at all, AND when a configured one
|
|
1561
|
+
// could not answer for some rows — both are "box 3 does not hold what a
|
|
1562
|
+
// vector channel would need", and a silent partial is the worse of the two.
|
|
1563
|
+
//
|
|
1564
|
+
// `keepVectors` is the third way to have nothing to declare, and it is the
|
|
1565
|
+
// reason this is not simply "is there an embedder": a rebuild that kept
|
|
1566
|
+
// every vector it started with is not missing them, whatever this process
|
|
1567
|
+
// could or could not have recomputed. Without the extra arm a
|
|
1568
|
+
// `verify --rebuild --keep-vectors` that lost nothing would still print a
|
|
1569
|
+
// repair instruction for a gap box 3 does not have.
|
|
1570
|
+
const declared =
|
|
1571
|
+
unrecomputed === 0 && (this.embed !== undefined || keepVectors)
|
|
1572
|
+
? []
|
|
1573
|
+
: [
|
|
1574
|
+
{
|
|
1575
|
+
what: "embeddings",
|
|
1576
|
+
owner: "encode/ (the embedder)",
|
|
1577
|
+
repair: "Store.open({ embed }) then rebuildCache()",
|
|
1578
|
+
},
|
|
1579
|
+
];
|
|
1580
|
+
const report: RebuildReport = {
|
|
1581
|
+
indexed,
|
|
1582
|
+
skippedDenied,
|
|
1583
|
+
skippedArchived,
|
|
1584
|
+
unrecomputed,
|
|
1585
|
+
declared,
|
|
1586
|
+
keptVectors,
|
|
1587
|
+
droppedVectors,
|
|
1588
|
+
};
|
|
1589
|
+
this.emit("cache.rebuild", undefined, {
|
|
1590
|
+
indexed,
|
|
1591
|
+
skippedDenied,
|
|
1592
|
+
skippedArchived,
|
|
1593
|
+
unrecomputed,
|
|
1594
|
+
keptVectors,
|
|
1595
|
+
droppedVectors,
|
|
1596
|
+
declaredKinds: declared.map((d) => d.what).join(",") || "none",
|
|
1597
|
+
});
|
|
1598
|
+
return report;
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1601
|
+
/**
|
|
1602
|
+
* Take every NOT-LIVE document out of the text index, and touch nothing else.
|
|
1603
|
+
*
|
|
1604
|
+
* This is I13's migration, and it exists for the same reason `backfillLengths`
|
|
1605
|
+
* does: the repair is a pure function of state box 3 and box 2 already hold,
|
|
1606
|
+
* so it must not be paid for with `rebuildCache`, which begins with
|
|
1607
|
+
* `resetCache` and drops every embedding — roughly 13.9K of them on the store
|
|
1608
|
+
* this was written against, one paid network call each. `counterparts verify
|
|
1609
|
+
* --rebuild` refuses outright for that reason unless the owner passes
|
|
1610
|
+
* `--drop-vectors`, so a rebuild is not a repair anyone can actually run here.
|
|
1611
|
+
*
|
|
1612
|
+
* `archive` and `supersede` keep the invariant going forward
|
|
1613
|
+
* (`cache.ts#deindexDoc`); this is how a store that predates them catches up.
|
|
1614
|
+
* It is NOT run at open: an instrument writes nothing at open, and a write at
|
|
1615
|
+
* open takes the write lock (see the constructor). The owner runs it by name.
|
|
1616
|
+
*
|
|
1617
|
+
* Returns the number of documents removed from the index.
|
|
1618
|
+
*/
|
|
1619
|
+
pruneDeadIndex(): number {
|
|
1620
|
+
this.assertWritable("pruneDeadIndex");
|
|
1621
|
+
const live = new Set(this.list({ archived: false }));
|
|
1622
|
+
const indexed = this.cache
|
|
1623
|
+
.all<{ memory_id: string }>("SELECT DISTINCT memory_id FROM doc_tokens")
|
|
1624
|
+
.map((r) => r.memory_id);
|
|
1625
|
+
let removed = 0;
|
|
1626
|
+
for (const id of indexed) {
|
|
1627
|
+
if (live.has(id)) continue;
|
|
1628
|
+
deindexDoc(this.cache, id);
|
|
1629
|
+
removed += 1;
|
|
1630
|
+
}
|
|
1631
|
+
if (removed > 0) this.emit("cache.prune.dead", undefined, { removed });
|
|
1632
|
+
return removed;
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
/**
|
|
1636
|
+
* Give ONE existing memory its vector — **the vector row only**, never the
|
|
1637
|
+
* token rows.
|
|
1638
|
+
*
|
|
1639
|
+
* `rebuildCache()` was the only public way to put a vector in box 3, and it
|
|
1640
|
+
* resets the whole cache: a store whose embedder arrived after its memories
|
|
1641
|
+
* did (this one — 40 authored notes, 224 episodes and 288 migrated memories
|
|
1642
|
+
* with no vector, measured 2026-09-04) had no way to fill the gap
|
|
1643
|
+
* incrementally, so the semantic channel stayed blind to exactly the
|
|
1644
|
+
* first-person material it most wanted.
|
|
1645
|
+
*
|
|
1646
|
+
* **Why not `indexDoc`, which would have been the obvious reuse:** it deletes
|
|
1647
|
+
* and re-inserts every `doc_tokens` row for the document. The text has not
|
|
1648
|
+
* changed — only the vector is missing — so that is pure churn on the 263 MB
|
|
1649
|
+
* token index whose page-cache warming is what pushed `recall/`'s BUDGET_MS
|
|
1650
|
+
* from 250 to 1200. A backfill of 64 memories per Stop would have made the
|
|
1651
|
+
* cold recall it exists to serve slower.
|
|
1652
|
+
*
|
|
1653
|
+
* It reads the SYNC embedder, like every other indexing site, so the caller's
|
|
1654
|
+
* job is to have warmed the live half first with `indexTextOf(title, body)` —
|
|
1655
|
+
* the same string `indexOne` looks a vector up by. A miss is not an error and
|
|
1656
|
+
* not a lie: nothing is written and `vector` comes back false, so a backfill
|
|
1657
|
+
* that warmed the wrong text reports zero rather than success.
|
|
1658
|
+
*/
|
|
1659
|
+
embedOne(id: string): { found: boolean; vector: boolean } {
|
|
1660
|
+
this.assertWritable("embedOne");
|
|
1661
|
+
if (this.isDenied(id)) return { found: false, vector: false };
|
|
1662
|
+
const row = this.row(id);
|
|
1663
|
+
if (row === undefined) return { found: false, vector: false };
|
|
1664
|
+
let doc: ProseDoc;
|
|
1665
|
+
try {
|
|
1666
|
+
doc = this.readProse(id);
|
|
1667
|
+
} catch {
|
|
1668
|
+
return { found: false, vector: false };
|
|
1669
|
+
}
|
|
1670
|
+
// THE THIRD DOOR, guarded like the other two. `unembeddedIds` will never
|
|
1671
|
+
// offer one of these, but this method takes an id from a caller and a
|
|
1672
|
+
// backfill that named one directly would embed it — the whole point of
|
|
1673
|
+
// `noVector` is that a caller cannot reach the wire for these rows by any
|
|
1674
|
+
// route. `found: true, vector: false` is the honest answer: the row is
|
|
1675
|
+
// there, and it has no vector on purpose.
|
|
1676
|
+
const vec = this.embed && !noVector(doc.type, doc.meta["role"]) ? this.embed(indexText(doc)) : null;
|
|
1677
|
+
if (vec === null) return { found: true, vector: false };
|
|
1678
|
+
setEmbedding(this.cache, id, vec);
|
|
1679
|
+
return { found: true, vector: true };
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
/**
|
|
1683
|
+
* Live memories box 3 holds no vector for, in the order a backfill should take
|
|
1684
|
+
* them: **the first-person material first** — what the experiencer authored
|
|
1685
|
+
* (`source = 'authored'`) and its own episodes — then everything else, oldest
|
|
1686
|
+
* first inside each group.
|
|
1687
|
+
*
|
|
1688
|
+
* The order is the whole point and it is a memory claim, not a convenience:
|
|
1689
|
+
* an authored note and an episode are the memories this brain wrote about
|
|
1690
|
+
* itself, so if a bounded backfill only ever reaches N per run, those are the
|
|
1691
|
+
* N that should arrive first.
|
|
1692
|
+
*
|
|
1693
|
+
* Two boxes, two queries, diffed here: box 2 knows what is live, box 3 knows
|
|
1694
|
+
* what is embedded, and they are separate files by design.
|
|
1695
|
+
*/
|
|
1696
|
+
missingVectors(limit = 64): string[] {
|
|
1697
|
+
return this.unembeddedIds(limit, false);
|
|
1698
|
+
}
|
|
1699
|
+
|
|
1700
|
+
/**
|
|
1701
|
+
* The ids a backfill has given up on — `EMBED_SKIP_AFTER` failed runs each.
|
|
1702
|
+
*
|
|
1703
|
+
* THE HEAD-OF-LINE SCAR (I33, 2026-09-11). Two migrated memories carried a
|
|
1704
|
+
* lone UTF-16 surrogate in their title; the provider answered 400 for the
|
|
1705
|
+
* whole 64-text chunk; `missingVectors` returns a STABLE order, so the same
|
|
1706
|
+
* head-64 was retried at every boundary for a week and 165 blind memories
|
|
1707
|
+
* behind them never got a turn. A skip list is the general fix: whatever the
|
|
1708
|
+
* poison is, an id that has failed three runs stops holding the queue.
|
|
1709
|
+
*
|
|
1710
|
+
* Distinct from `deniedIds()` by design. A denial is a REMOVAL — the row is
|
|
1711
|
+
* dark and must never come back. A skip is an operational give-up on ONE
|
|
1712
|
+
* channel: the memory is live, recallable, and lexically indexed; only its
|
|
1713
|
+
* vector is missing, and a repair (or a rebuild) clears the counter.
|
|
1714
|
+
*
|
|
1715
|
+
* Kept in box 2's meta rather than a column, because it is a fact about a
|
|
1716
|
+
* retry loop and not about the memory — same shape as `sleep.pruned.<id>`,
|
|
1717
|
+
* and no schema bump.
|
|
1718
|
+
*/
|
|
1719
|
+
skippedVectorIds(): string[] {
|
|
1720
|
+
return this.unembeddedIds(Number.MAX_SAFE_INTEGER, true);
|
|
1721
|
+
}
|
|
1722
|
+
|
|
1723
|
+
/**
|
|
1724
|
+
* Live memories with no vector, in backfill order. `skipped` selects WHICH
|
|
1725
|
+
* half: the ones a backfill should try (false) or the ones it has given up on
|
|
1726
|
+
* (true). One query, one order, two readings — a second copy of this walk is
|
|
1727
|
+
* how the two lists would drift.
|
|
1728
|
+
*/
|
|
1729
|
+
private unembeddedIds(limit: number, skipped: boolean): string[] {
|
|
1730
|
+
const embedded = new Set(
|
|
1731
|
+
this.cache.all<{ memory_id: string }>("SELECT memory_id FROM embeddings").map(
|
|
1732
|
+
(r) => r.memory_id,
|
|
1733
|
+
),
|
|
1734
|
+
);
|
|
1735
|
+
const denied = new Set(this.deniedIds());
|
|
1736
|
+
// ONE read of the failure counters per call, not one per candidate row.
|
|
1737
|
+
const failures = this.metaWithPrefix(EMBED_FAILED_PREFIX);
|
|
1738
|
+
const givenUp = (id: string): boolean =>
|
|
1739
|
+
Number(failures.get(`${EMBED_FAILED_PREFIX}${id}`) ?? "0") >= EMBED_SKIP_AFTER;
|
|
1740
|
+
const rows = this.ops.all<{ id: string; type: string; meta: string }>(
|
|
1741
|
+
`SELECT id, type, meta FROM memories
|
|
1742
|
+
WHERE archived = 0 AND superseded_by IS NULL
|
|
1743
|
+
ORDER BY CASE WHEN source IN ('authored', 'episode') OR type = 'episode' THEN 0 ELSE 1 END,
|
|
1744
|
+
birth_day ASC, id ASC`,
|
|
1745
|
+
);
|
|
1746
|
+
const out: string[] = [];
|
|
1747
|
+
for (const r of rows) {
|
|
1748
|
+
if (embedded.has(r.id) || denied.has(r.id)) continue;
|
|
1749
|
+
if (notForEmbedding(r)) continue;
|
|
1750
|
+
if (givenUp(r.id) !== skipped) continue;
|
|
1751
|
+
out.push(r.id);
|
|
1752
|
+
if (out.length >= limit) break;
|
|
1753
|
+
}
|
|
1754
|
+
return out;
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
/**
|
|
1758
|
+
* How many live memories a backfill could still act on — the denominator a
|
|
1759
|
+
* coverage watch needs, and the number that must fall run over run.
|
|
1760
|
+
*
|
|
1761
|
+
* Since I33 it EXCLUDES the give-up list, because the number's job is to say
|
|
1762
|
+
* what is actionable: a count that never falls because three ids in it can
|
|
1763
|
+
* never be embedded is a watch that has stopped meaning anything. The excluded
|
|
1764
|
+
* ids are not hidden — `skippedVectorIds()` names them, the backfill row
|
|
1765
|
+
* carries `skipped`, and `verify` prints both, so the two numbers add up on
|
|
1766
|
+
* the page where an owner reads them.
|
|
1767
|
+
*/
|
|
1768
|
+
unembeddedCount(): number {
|
|
1769
|
+
return this.missingVectors(Number.MAX_SAFE_INTEGER).length;
|
|
1770
|
+
}
|
|
1771
|
+
|
|
1772
|
+
/**
|
|
1773
|
+
* Every meta row under one key prefix. A read; nothing is created.
|
|
1774
|
+
*
|
|
1775
|
+
* The meta table is this store's general-purpose key space, and two of its
|
|
1776
|
+
* inhabitants are per-id counters (`sleep.pruned.<id>`, `embed.failed.<id>`)
|
|
1777
|
+
* whose readers want the whole family at once. One `LIKE` beats N `getMeta`
|
|
1778
|
+
* calls in a loop over every live memory, which is what the alternative was.
|
|
1779
|
+
* `_` and `%` in the prefix are escaped: the caller passes a key prefix, not
|
|
1780
|
+
* a pattern.
|
|
1781
|
+
*/
|
|
1782
|
+
metaWithPrefix(prefix: string): Map<string, string> {
|
|
1783
|
+
const pattern = `${prefix.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
|
|
1784
|
+
const rows = this.ops.all<{ key: string; value: string }>(
|
|
1785
|
+
`SELECT key, value FROM meta WHERE key LIKE ? ESCAPE '\\'`,
|
|
1786
|
+
pattern,
|
|
1787
|
+
);
|
|
1788
|
+
return new Map(rows.map((r) => [r.key, r.value]));
|
|
1789
|
+
}
|
|
1790
|
+
|
|
1791
|
+
/**
|
|
1792
|
+
* How many vectors box 3 HOLDS — the numerator, and a different number from
|
|
1793
|
+
* `unembeddedCount()`.
|
|
1794
|
+
*
|
|
1795
|
+
* Filed as a core follow-up by PR #43's review (`adapters/cli/NOTES.md`,
|
|
1796
|
+
* 2026-09-04): the console needed "how many embeddings would `--rebuild`
|
|
1797
|
+
* destroy" before it could refuse, `unembeddedCount()` is the coverage
|
|
1798
|
+
* denominator instead, and with no read API for the count the CLI reached
|
|
1799
|
+
* past the Store into `cache.sqlite` with its own `openDb`. It still does for
|
|
1800
|
+
* the census — that read is deliberately gated on the FILE existing, so it
|
|
1801
|
+
* cannot mint the box it inspects, which a Store constructor cannot promise —
|
|
1802
|
+
* but a caller that already holds an open Store now has the number here.
|
|
1803
|
+
*
|
|
1804
|
+
* Counts every vector, including one held for an archived or superseded row:
|
|
1805
|
+
* this is what box 3 contains, not what a live coverage ratio would want.
|
|
1806
|
+
*/
|
|
1807
|
+
embeddingCount(): number {
|
|
1808
|
+
return embeddingCount(this.cache);
|
|
1809
|
+
}
|
|
1810
|
+
|
|
1811
|
+
// ── reads ──────────────────────────────────────────────────────────────────
|
|
1812
|
+
|
|
1813
|
+
has(id: string): boolean {
|
|
1814
|
+
return this.row(id) !== undefined;
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
row(id: string): MemoryRow | undefined {
|
|
1818
|
+
return this.ops.get<MemoryRow>("SELECT * FROM memories WHERE id = ?", id);
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1821
|
+
read(id: string): StoredMemory {
|
|
1822
|
+
const row = this.requireRow(id);
|
|
1823
|
+
const doc = this.docOf(row);
|
|
1824
|
+
if (row.archived === 1) {
|
|
1825
|
+
// §5 G13: a read-back of archived content is an event, so "did the archival
|
|
1826
|
+
// mechanisms ever pay for themselves" is an answerable question in v2.
|
|
1827
|
+
this.emit("store.archived.read", id, { reason: row.archived_reason });
|
|
1828
|
+
}
|
|
1829
|
+
return {
|
|
1830
|
+
doc,
|
|
1831
|
+
physics: rowToPhysics(row),
|
|
1832
|
+
band: row.band,
|
|
1833
|
+
bandDay: row.band_day,
|
|
1834
|
+
archived: row.archived === 1,
|
|
1835
|
+
archivedReason: row.archived_reason,
|
|
1836
|
+
supersededBy: row.superseded_by,
|
|
1837
|
+
revision: row.revision,
|
|
1838
|
+
contentHash: row.content_hash,
|
|
1839
|
+
confidential: row.confidential === 1,
|
|
1840
|
+
};
|
|
1841
|
+
}
|
|
1842
|
+
|
|
1843
|
+
readProse(id: string): ProseDoc {
|
|
1844
|
+
return this.read(id).doc;
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
physicsOf(id: string): MemoryPhysics {
|
|
1848
|
+
return rowToPhysics(this.requireRow(id));
|
|
1849
|
+
}
|
|
1850
|
+
|
|
1851
|
+
/**
|
|
1852
|
+
* Follows the forwarding addresses to the live head. Cycles are a hard error.
|
|
1853
|
+
*
|
|
1854
|
+
* A REMOVED id is terminal: the walk stops there and returns it, rather than
|
|
1855
|
+
* walking past it or reporting the address as dangling. That is what makes a
|
|
1856
|
+
* survivor's lineage pointer resolve to a named removal — `read` refuses the
|
|
1857
|
+
* returned id by name, so a renderer prints "[removed by the owner]" instead
|
|
1858
|
+
* of "[a forwarding address with nothing at the end]". The deny-list is
|
|
1859
|
+
* checked BEFORE the row, so the answer is the same before and after the
|
|
1860
|
+
* chase has stripped the row to a skeleton.
|
|
1861
|
+
*/
|
|
1862
|
+
resolve(id: string): string {
|
|
1863
|
+
let current = id;
|
|
1864
|
+
const seen = new Set<string>();
|
|
1865
|
+
for (let depth = 0; depth <= MAX_CHAIN; depth++) {
|
|
1866
|
+
if (seen.has(current)) throw new StoreError("ID_CYCLE", { id, at: current });
|
|
1867
|
+
seen.add(current);
|
|
1868
|
+
if (this.isDenied(current)) return current;
|
|
1869
|
+
const row = this.row(current);
|
|
1870
|
+
if (row === undefined) {
|
|
1871
|
+
throw new StoreError(current === id ? "ID_UNKNOWN" : "ID_DANGLING", { id, at: current });
|
|
1872
|
+
}
|
|
1873
|
+
if (row.superseded_by === null) return current;
|
|
1874
|
+
current = row.superseded_by;
|
|
1875
|
+
}
|
|
1876
|
+
throw new StoreError("ID_CHAIN_TOO_DEEP", { id, max: MAX_CHAIN });
|
|
1877
|
+
}
|
|
1878
|
+
|
|
1879
|
+
list(filter: MemoryFilter = {}): string[] {
|
|
1880
|
+
const { clause, args } = memoryWhere(filter);
|
|
1881
|
+
const sql = `SELECT id FROM memories ${clause} ORDER BY id`;
|
|
1882
|
+
return this.ops.all<{ id: string }>(sql, ...args).map((r) => r.id);
|
|
1883
|
+
}
|
|
1884
|
+
|
|
1885
|
+
/**
|
|
1886
|
+
* How many rows `list()` would return, counted in SQL rather than materialized.
|
|
1887
|
+
* The same filter, the same WHERE, one number — for the callers that want the
|
|
1888
|
+
* SIZE of the store (the wake's delivery preface states it) and would otherwise
|
|
1889
|
+
* build an array of every id to take its length.
|
|
1890
|
+
*/
|
|
1891
|
+
countMemories(filter: MemoryFilter = {}): number {
|
|
1892
|
+
const { clause, args } = memoryWhere(filter);
|
|
1893
|
+
const sql = `SELECT COUNT(*) AS n FROM memories ${clause}`;
|
|
1894
|
+
return this.ops.get<{ n: number }>(sql, ...args)?.n ?? 0;
|
|
1895
|
+
}
|
|
1896
|
+
|
|
1897
|
+
versions(id: string): VersionRow[] {
|
|
1898
|
+
return this.ops.all<VersionRow>(
|
|
1899
|
+
"SELECT * FROM versions WHERE memory_id = ? ORDER BY seq",
|
|
1900
|
+
id,
|
|
1901
|
+
);
|
|
1902
|
+
}
|
|
1903
|
+
|
|
1904
|
+
/** Reading a superseded/archived version is an event (§5 G13). */
|
|
1905
|
+
readVersion(id: string, seq: number): ProseDoc {
|
|
1906
|
+
// The version row survives a removal as a lineage pointer with its content
|
|
1907
|
+
// pointers blanked; reading it is refused by name, never by ENOENT.
|
|
1908
|
+
this.refuseIfDenied(id);
|
|
1909
|
+
const row = this.ops.get<VersionRow>(
|
|
1910
|
+
"SELECT * FROM versions WHERE memory_id = ? AND seq = ?",
|
|
1911
|
+
id,
|
|
1912
|
+
seq,
|
|
1913
|
+
);
|
|
1914
|
+
if (row === undefined) throw new StoreError("VERSION_UNKNOWN", { id, seq });
|
|
1915
|
+
this.emit("store.version.read", id, { seq, reason: row.reason });
|
|
1916
|
+
return this.versionDoc(id, row);
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1919
|
+
/**
|
|
1920
|
+
* Rows whose WORDS WENT MISSING — `body = ''` with a content hash that still
|
|
1921
|
+
* names them. Ids only; never a body (§5 G10).
|
|
1922
|
+
*
|
|
1923
|
+
* The fault `MEMORY_BODY_MISSING` is raised for, counted. It is not a
|
|
1924
|
+
* tombstone (both halves blank, the owner's removal) and no write path in
|
|
1925
|
+
* this build produces it: `put` and `revise` both refuse an empty body, and
|
|
1926
|
+
* the chase blanks the pair together. So a non-empty answer means something
|
|
1927
|
+
* happened to the store underneath itself.
|
|
1928
|
+
*
|
|
1929
|
+
* It exists because the fault stands EVERY session down while `status` and
|
|
1930
|
+
* `verify` both read green, and doctor's red line named the class and not the
|
|
1931
|
+
* row — so the owner could not find which of thousands of rows to act on
|
|
1932
|
+
* (review B, MAJOR-3). A read; nothing here crosses the write seam.
|
|
1933
|
+
*/
|
|
1934
|
+
faultedIds(): string[] {
|
|
1935
|
+
return this.ops
|
|
1936
|
+
.all<{ id: string }>(
|
|
1937
|
+
"SELECT id FROM memories WHERE body = '' AND content_hash <> '' ORDER BY id",
|
|
1938
|
+
)
|
|
1939
|
+
.map((r) => r.id);
|
|
1940
|
+
}
|
|
1941
|
+
|
|
1942
|
+
edgesFrom(src: string): EdgeRow[] {
|
|
1943
|
+
return this.ops.all<EdgeRow>("SELECT * FROM edges WHERE src = ? ORDER BY dst", src);
|
|
1944
|
+
}
|
|
1945
|
+
|
|
1946
|
+
prospectiveFor(id: string): ProspectiveRow[] {
|
|
1947
|
+
return this.ops.all<ProspectiveRow>(
|
|
1948
|
+
"SELECT * FROM prospective WHERE memory_id = ? ORDER BY window_key",
|
|
1949
|
+
id,
|
|
1950
|
+
);
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1953
|
+
removalRecord(id?: string): RemovalRow[] {
|
|
1954
|
+
const rows =
|
|
1955
|
+
id === undefined
|
|
1956
|
+
? this.ops.all<RemovalRow>("SELECT * FROM removal_record ORDER BY seq")
|
|
1957
|
+
: this.ops.all<RemovalRow>(
|
|
1958
|
+
"SELECT * FROM removal_record WHERE memory_id = ? ORDER BY seq",
|
|
1959
|
+
id,
|
|
1960
|
+
);
|
|
1961
|
+
this.emit("store.removalRecord.read", id, { rows: rows.length });
|
|
1962
|
+
return rows;
|
|
1963
|
+
}
|
|
1964
|
+
|
|
1965
|
+
/**
|
|
1966
|
+
* What removal left behind, joined into one row per removed memory: the
|
|
1967
|
+
* tombstone's flags and counts, the latest stage of its record, and whether a
|
|
1968
|
+
* skeleton row survives in `memories`.
|
|
1969
|
+
*
|
|
1970
|
+
* This is the read that keeps scar §2.19 true from the other side — "everything
|
|
1971
|
+
* permanent is enumerable and inspectable" has to survive the one operation
|
|
1972
|
+
* that ends permanence, or a removed protected element simply vanishes from
|
|
1973
|
+
* the list and nobody can tell it apart from one that was never there.
|
|
1974
|
+
*
|
|
1975
|
+
* PURE and emit-free, unlike `removalRecord()`: `self.enumerate` calls it on
|
|
1976
|
+
* every enumeration, and an enumeration that logged would stop being a read
|
|
1977
|
+
* (§14.1 G8).
|
|
1978
|
+
*/
|
|
1979
|
+
tombstones(): Tombstone[] {
|
|
1980
|
+
const rows = this.ops.all<
|
|
1981
|
+
TombstoneRow & { last_stage: string | null; row_survives: number }
|
|
1982
|
+
>(
|
|
1983
|
+
`SELECT t.*,
|
|
1984
|
+
(SELECT r.stage FROM removal_record r
|
|
1985
|
+
WHERE r.memory_id = t.memory_id ORDER BY r.seq DESC LIMIT 1) AS last_stage,
|
|
1986
|
+
(SELECT COUNT(*) FROM memories m WHERE m.id = t.memory_id) AS row_survives
|
|
1987
|
+
FROM removal_tombstone t
|
|
1988
|
+
ORDER BY t.memory_id`,
|
|
1989
|
+
);
|
|
1990
|
+
return rows.map((r) => ({
|
|
1991
|
+
id: r.memory_id,
|
|
1992
|
+
type: r.type,
|
|
1993
|
+
kind: r.kind,
|
|
1994
|
+
band: r.band,
|
|
1995
|
+
wasProtected: r.protected === 1,
|
|
1996
|
+
wasPromotedIdentity: r.promoted_identity === 1,
|
|
1997
|
+
supersededBy: r.superseded_by,
|
|
1998
|
+
stage: (r.last_stage ?? "dark") as RemovalNote["stage"],
|
|
1999
|
+
at: r.at,
|
|
2000
|
+
rowSurvives: r.row_survives > 0,
|
|
2001
|
+
chased: {
|
|
2002
|
+
versions: r.versions,
|
|
2003
|
+
edges: r.edges,
|
|
2004
|
+
prospective: r.prospective,
|
|
2005
|
+
gateRows: r.gate_rows,
|
|
2006
|
+
},
|
|
2007
|
+
}));
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
/** Ids a removal has taken dark: consulted at load and at rebuild (§16 G12). */
|
|
2011
|
+
deniedIds(): string[] {
|
|
2012
|
+
return this.ops
|
|
2013
|
+
.all<{ memory_id: string }>(
|
|
2014
|
+
"SELECT DISTINCT memory_id FROM removal_record WHERE stage IN ('dark', 'chased', 'complete')",
|
|
2015
|
+
)
|
|
2016
|
+
.map((r) => r.memory_id);
|
|
2017
|
+
}
|
|
2018
|
+
|
|
2019
|
+
/**
|
|
2020
|
+
* The token channel's read. `norm` is the document-length normalization
|
|
2021
|
+
* (`cache.ts#LengthNorm`); recall passes its own CAL values, and the two
|
|
2022
|
+
* callers that are not recall take the default.
|
|
2023
|
+
*/
|
|
2024
|
+
search(cue: string, limit = 10, norm: LengthNorm = DEFAULT_LENGTH_NORM): Hit[] {
|
|
2025
|
+
return searchIndex(this.cache, cue, limit, norm);
|
|
2026
|
+
}
|
|
2027
|
+
|
|
2028
|
+
/**
|
|
2029
|
+
* How many indexed documents hold each token — the rarity denominator.
|
|
2030
|
+
*
|
|
2031
|
+
* Separate from `search` on purpose: `search` returns a bounded TOP-K, and a
|
|
2032
|
+
* top-K's length is `min(trueDf, k)`, not a document frequency. Reading it as
|
|
2033
|
+
* one is the measurement error `cache.ts#docFrequency` documents.
|
|
2034
|
+
*/
|
|
2035
|
+
docFrequency(tokens: readonly string[]): Map<string, number> {
|
|
2036
|
+
return docFrequency(this.cache, tokens);
|
|
2037
|
+
}
|
|
2038
|
+
|
|
2039
|
+
nearestTo(vec: readonly number[], limit = 10): Hit[] {
|
|
2040
|
+
return nearest(this.cache, vec, limit);
|
|
2041
|
+
}
|
|
2042
|
+
|
|
2043
|
+
/**
|
|
2044
|
+
* The vectors of the `limit` memories nearest `vec` — E(m), the context a
|
|
2045
|
+
* novelty measurement is prediction error AGAINST (physics §5.1). Read-only,
|
|
2046
|
+
* box 3 only, and it strengthens nothing: this is an instrument's read.
|
|
2047
|
+
*
|
|
2048
|
+
* Returns fewer than `limit` (or none) whenever box 3 holds fewer vectors,
|
|
2049
|
+
* which is the ordinary state of a store whose embedder is switched off — and
|
|
2050
|
+
* `computeNovelty` turns that emptiness into `blind-no-context` rather than a
|
|
2051
|
+
* number, which is the whole point of asking it this way.
|
|
2052
|
+
*/
|
|
2053
|
+
neighbourVectors(vec: readonly number[], limit = 10): number[][] {
|
|
2054
|
+
return nearestVectors(this.cache, vec, limit);
|
|
2055
|
+
}
|
|
2056
|
+
|
|
2057
|
+
livedDay(): number {
|
|
2058
|
+
return Number(this.getMeta("livedDay") ?? "0");
|
|
2059
|
+
}
|
|
2060
|
+
|
|
2061
|
+
getMeta(key: string): string | undefined {
|
|
2062
|
+
return this.ops.get<{ value: string }>("SELECT value FROM meta WHERE key = ?", key)?.value;
|
|
2063
|
+
}
|
|
2064
|
+
|
|
2065
|
+
// ── internals ──────────────────────────────────────────────────────────────
|
|
2066
|
+
|
|
2067
|
+
private requireRow(id: string): MemoryRow {
|
|
2068
|
+
// The deny-list answers FIRST, and answers even after the chase has taken
|
|
2069
|
+
// the row away: a removed id must never come back as "no such memory", and
|
|
2070
|
+
// never as an ENOENT on the prose file that used to hold it.
|
|
2071
|
+
this.refuseIfDenied(id);
|
|
2072
|
+
const row = this.row(id);
|
|
2073
|
+
if (row === undefined) throw new StoreError("ID_UNKNOWN", { id });
|
|
2074
|
+
return row;
|
|
2075
|
+
}
|
|
2076
|
+
|
|
2077
|
+
/** Emit-free (§14.1 G8: reads are pure) — this is called on every read path. */
|
|
2078
|
+
private isDenied(id: string): boolean {
|
|
2079
|
+
const denied = this.ops.get<{ n: number }>(
|
|
2080
|
+
"SELECT COUNT(*) AS n FROM removal_record WHERE memory_id = ? AND stage IN ('dark','chased','complete')",
|
|
2081
|
+
id,
|
|
2082
|
+
);
|
|
2083
|
+
return (denied?.n ?? 0) > 0;
|
|
2084
|
+
}
|
|
2085
|
+
|
|
2086
|
+
private refuseIfDenied(id: string): void {
|
|
2087
|
+
if (this.isDenied(id)) throw new StoreError("REMOVED", { id, by: "owner" });
|
|
2088
|
+
}
|
|
2089
|
+
|
|
2090
|
+
/** Runs INSIDE the caller's transaction. One INSERT; there is nothing to publish. */
|
|
2091
|
+
private insertOne(input: PutInput): ProseDoc {
|
|
2092
|
+
const id = input.id ?? newId(input.type);
|
|
2093
|
+
// Both id checks BEFORE the row: the shape rule used to live in
|
|
2094
|
+
// `serializeProse`, which ran while the file was staged and so refused
|
|
2095
|
+
// before anything had been written. It has to keep refusing first.
|
|
2096
|
+
assertIdWellFormed(id);
|
|
2097
|
+
if (!id.startsWith(`${ID_PREFIX[input.type]}_`)) {
|
|
2098
|
+
throw new StoreError("ID_MALFORMED", { id, type: input.type });
|
|
2099
|
+
}
|
|
2100
|
+
// A removed id is taken FOREVER. Ids are never reused (§4.2 G2), and the one
|
|
2101
|
+
// reuse that would matter is the one that quietly resurrects what the owner
|
|
2102
|
+
// removed — so the deny-list is consulted at birth as well as at read.
|
|
2103
|
+
if (this.has(id) || this.isDenied(id)) throw new StoreError("ID_TAKEN", { id });
|
|
2104
|
+
// NORMALISED AND CHECKED BEFORE THE ROW. `bodyForStorage` is the one rule
|
|
2105
|
+
// both write doors share: whitespace-only is empty, and a lone surrogate is
|
|
2106
|
+
// folded to what SQLite will actually store so the hash below addresses the
|
|
2107
|
+
// bytes that land (review B, MINOR-4/-5).
|
|
2108
|
+
const body = bodyForStorage(input.body, id);
|
|
2109
|
+
const day = this.livedDay();
|
|
2110
|
+
// Source and origin mirror into the prose meta: the document is canonical
|
|
2111
|
+
// and self-describing; the columns are the query surface for the same fact.
|
|
2112
|
+
const meta: Record<string, unknown> = { ...(input.meta ?? {}) };
|
|
2113
|
+
if (input.source !== undefined) meta["source"] = input.source;
|
|
2114
|
+
if (input.origin !== undefined) {
|
|
2115
|
+
const origin: Record<string, string> = {};
|
|
2116
|
+
if (input.origin.session !== undefined) origin["session"] = input.origin.session;
|
|
2117
|
+
if (input.origin.scope !== undefined) origin["scope"] = input.origin.scope;
|
|
2118
|
+
if (input.origin.ref !== undefined) origin["ref"] = input.origin.ref;
|
|
2119
|
+
if (input.origin.spanHash !== undefined) origin["spanHash"] = input.origin.spanHash;
|
|
2120
|
+
if (Object.keys(origin).length > 0) meta["origin"] = origin;
|
|
2121
|
+
}
|
|
2122
|
+
const doc: ProseDoc = {
|
|
2123
|
+
id,
|
|
2124
|
+
type: input.type,
|
|
2125
|
+
learnedOn: input.learnedOn ?? this.today(),
|
|
2126
|
+
bornDay: input.physics?.birthDay ?? day,
|
|
2127
|
+
meta,
|
|
2128
|
+
body,
|
|
2129
|
+
};
|
|
2130
|
+
if (input.title !== undefined) doc.title = input.title;
|
|
2131
|
+
if (input.happenedOn !== undefined) doc.happenedOn = input.happenedOn;
|
|
2132
|
+
// Serialized (and so G6-checked) BEFORE the INSERT, for the same reason:
|
|
2133
|
+
// a function or a NaN in `meta` is silent data loss, and the refusal must
|
|
2134
|
+
// land while nothing has been written.
|
|
2135
|
+
const metaJson = serializeMeta(meta, id);
|
|
2136
|
+
const contentHash = hashText(doc.body);
|
|
2137
|
+
const s: Salience = {
|
|
2138
|
+
novelty: input.salience?.novelty ?? null,
|
|
2139
|
+
relevance: input.salience?.relevance ?? 0,
|
|
2140
|
+
emotional: input.salience?.emotional ?? 0,
|
|
2141
|
+
predictive: input.salience?.predictive ?? 0,
|
|
2142
|
+
claimed: input.salience?.claimed ?? null,
|
|
2143
|
+
};
|
|
2144
|
+
this.ops.run(
|
|
2145
|
+
`INSERT INTO memories (
|
|
2146
|
+
id, type, kind, band, band_day, novelty, relevance, emotional, predictive,
|
|
2147
|
+
claimed, birth_day, uses, last_used_day, reinforced_days, consolidated,
|
|
2148
|
+
promoted_identity, protected, pressure, last_challenged_day, archived,
|
|
2149
|
+
archived_reason, superseded_by, revision, content_hash,
|
|
2150
|
+
learned_on, happened_on, source, origin_session, origin_scope, origin_ref,
|
|
2151
|
+
title, body, meta, confidential)
|
|
2152
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, NULL, NULL, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
2153
|
+
id,
|
|
2154
|
+
input.type,
|
|
2155
|
+
input.kind,
|
|
2156
|
+
input.band ?? "episodic",
|
|
2157
|
+
day,
|
|
2158
|
+
s.novelty,
|
|
2159
|
+
s.relevance,
|
|
2160
|
+
s.emotional,
|
|
2161
|
+
s.predictive,
|
|
2162
|
+
s.claimed ?? null,
|
|
2163
|
+
doc.bornDay,
|
|
2164
|
+
input.physics?.uses ?? 0,
|
|
2165
|
+
input.physics?.lastUsedDay ?? day,
|
|
2166
|
+
input.physics?.reinforcedDays ?? 0,
|
|
2167
|
+
input.physics?.consolidated ? 1 : 0,
|
|
2168
|
+
input.physics?.promotedIdentity ? 1 : 0,
|
|
2169
|
+
input.physics?.protected ? 1 : 0,
|
|
2170
|
+
input.physics?.pressure ?? 0,
|
|
2171
|
+
input.physics?.lastChallengedDay ?? null,
|
|
2172
|
+
contentHash,
|
|
2173
|
+
doc.learnedOn,
|
|
2174
|
+
doc.happenedOn ?? null,
|
|
2175
|
+
input.source ?? null,
|
|
2176
|
+
input.origin?.session ?? null,
|
|
2177
|
+
input.origin?.scope ?? null,
|
|
2178
|
+
input.origin?.ref ?? null,
|
|
2179
|
+
doc.title ?? null,
|
|
2180
|
+
doc.body,
|
|
2181
|
+
metaJson,
|
|
2182
|
+
confidentialByMeta(meta) ? 1 : 0,
|
|
2183
|
+
);
|
|
2184
|
+
return doc;
|
|
2185
|
+
}
|
|
2186
|
+
|
|
2187
|
+
/**
|
|
2188
|
+
* A row read as the document it is.
|
|
2189
|
+
*
|
|
2190
|
+
* THE READ SEAM, and the reason nothing above `store/` noticed the floor
|
|
2191
|
+
* move: `ProseDoc` is the shape it always was, assembled from columns now
|
|
2192
|
+
* instead of parsed out of a file's frontmatter.
|
|
2193
|
+
*
|
|
2194
|
+
* The body check is the fault `PROSE_FILE_MISSING` used to be. A blank body
|
|
2195
|
+
* beside a blank hash is a TOMBSTONE — the owner removed this — and never
|
|
2196
|
+
* reaches here through a read, because the deny-list refuses the id by name
|
|
2197
|
+
* first (`requireRow`); a blank body beside a real hash is a row whose words
|
|
2198
|
+
* went missing underneath the store, which no write path in this module
|
|
2199
|
+
* produces and which is worth a loud, named refusal rather than an empty
|
|
2200
|
+
* memory that reads as if it said nothing.
|
|
2201
|
+
*/
|
|
2202
|
+
private docOf(row: MemoryRow): ProseDoc {
|
|
2203
|
+
if (row.body.length === 0) {
|
|
2204
|
+
throw new StoreError("MEMORY_BODY_MISSING", {
|
|
2205
|
+
id: row.id,
|
|
2206
|
+
tombstoned: rowTombstoned(row),
|
|
2207
|
+
});
|
|
2208
|
+
}
|
|
2209
|
+
const doc: ProseDoc = {
|
|
2210
|
+
id: row.id,
|
|
2211
|
+
type: row.type,
|
|
2212
|
+
learnedOn: row.learned_on,
|
|
2213
|
+
bornDay: row.birth_day,
|
|
2214
|
+
meta: parseMeta(row.meta, row.id),
|
|
2215
|
+
body: row.body,
|
|
2216
|
+
};
|
|
2217
|
+
if (row.title !== null) doc.title = row.title;
|
|
2218
|
+
if (row.happened_on !== null) doc.happenedOn = row.happened_on;
|
|
2219
|
+
return doc;
|
|
2220
|
+
}
|
|
2221
|
+
|
|
2222
|
+
/**
|
|
2223
|
+
* An archived version read as the document it was.
|
|
2224
|
+
*
|
|
2225
|
+
* `title`, `body`, `meta` and the two PROVENANCE dates come from the version
|
|
2226
|
+
* row, because all five can be revised and the version is what they were;
|
|
2227
|
+
* `type` and `bornDay` come from the live row, because neither can (an id's
|
|
2228
|
+
* prefix pins its family, and a birth day is physics, not content).
|
|
2229
|
+
*/
|
|
2230
|
+
private versionDoc(id: string, version: VersionRow): ProseDoc {
|
|
2231
|
+
if (version.body.length === 0) {
|
|
2232
|
+
throw new StoreError("MEMORY_BODY_MISSING", { id, seq: version.seq });
|
|
2233
|
+
}
|
|
2234
|
+
const head = this.row(id);
|
|
2235
|
+
const doc: ProseDoc = {
|
|
2236
|
+
id,
|
|
2237
|
+
type: head?.type ?? "memory",
|
|
2238
|
+
learnedOn: version.learned_on,
|
|
2239
|
+
bornDay: head?.birth_day ?? 0,
|
|
2240
|
+
meta: parseMeta(version.meta, id),
|
|
2241
|
+
body: version.body,
|
|
2242
|
+
};
|
|
2243
|
+
if (version.title !== null) doc.title = version.title;
|
|
2244
|
+
if (version.happened_on !== null) doc.happenedOn = version.happened_on;
|
|
2245
|
+
return doc;
|
|
2246
|
+
}
|
|
2247
|
+
|
|
2248
|
+
/**
|
|
2249
|
+
* Box 3 is best-effort by design: it is rebuildable, so it never fails a
|
|
2250
|
+
* write.
|
|
2251
|
+
*
|
|
2252
|
+
* **This is where `noVector` has to be asked, and the backfill is the second
|
|
2253
|
+
* place and not the first.** The live adapter wires a SYNC embedder
|
|
2254
|
+
* (`claude-code/index.ts`), so every `put` and `revise` embeds here, at write
|
|
2255
|
+
* time, long before `unembeddedIds` is consulted — a filter only on the
|
|
2256
|
+
* backfill leaves the write path handing the whole body to an embedder. That
|
|
2257
|
+
* was measured, with a stub, before it was fixed.
|
|
2258
|
+
*
|
|
2259
|
+
* The TOKENS are still written either way. A row nobody should embed is still
|
|
2260
|
+
* a row the OWNER should be able to find: the dashboard's search, the console
|
|
2261
|
+
* `remove` flow and `expandHandle`'s exact-title match all read the lexical
|
|
2262
|
+
* index, and none of them is a recall candidate path.
|
|
2263
|
+
*/
|
|
2264
|
+
private indexOne(doc: ProseDoc): void {
|
|
2265
|
+
const text = indexText(doc);
|
|
2266
|
+
const vec = this.embed && !noVector(doc.type, doc.meta["role"]) ? this.embed(text) : null;
|
|
2267
|
+
if (vec !== null) indexDoc(this.cache, doc.id, text, vec);
|
|
2268
|
+
else indexDoc(this.cache, doc.id, text);
|
|
2269
|
+
}
|
|
2270
|
+
}
|
|
2271
|
+
|
|
2272
|
+
/**
|
|
2273
|
+
* The string box 3 indexes for a document — and therefore the string a CALLER
|
|
2274
|
+
* must embed if it wants its vector to be the one this store looks up at `put`
|
|
2275
|
+
* time. Exported for exactly that: `counterpart.ts` composes it from a
|
|
2276
|
+
* proposal's title and its GATED content before the memory exists, so one live
|
|
2277
|
+
* call serves both the novelty seam and box 3.
|
|
2278
|
+
*
|
|
2279
|
+
* The word gated is the whole contract. This function is a pure join, so it
|
|
2280
|
+
* cannot enforce which content it is handed — a caller that composes it from the
|
|
2281
|
+
* author's raw draft will cache under a key `indexOne` never asks for, and every
|
|
2282
|
+
* redaction or hedge silently costs the deposit its vector. The ordering that
|
|
2283
|
+
* makes it true lives in `bridge.batteryGate`, and a test asserts it.
|
|
2284
|
+
*/
|
|
2285
|
+
export function indexTextOf(title: string | null | undefined, body: string): string {
|
|
2286
|
+
return [title ?? "", body].join("\n");
|
|
2287
|
+
}
|
|
2288
|
+
|
|
2289
|
+
function indexText(doc: ProseDoc): string {
|
|
2290
|
+
return indexTextOf(doc.title, doc.body);
|
|
2291
|
+
}
|
|
2292
|
+
|
|
2293
|
+
/**
|
|
2294
|
+
* What to TELL somebody whose directory holds pre-rows names — and, when it is
|
|
2295
|
+
* ambiguous, what not to tell them.
|
|
2296
|
+
*
|
|
2297
|
+
* Three cases, and the middle one is the finding this exists for (review A,
|
|
2298
|
+
* MAJOR-1). The PRE-FLOOR build's `Store` constructor — the one tagged
|
|
2299
|
+
* `floor/v5-last`, and what a stale worktree or an un-deployed checkout still
|
|
2300
|
+
* runs — mkdirs `prose/`, `versions/`, `tmp/`
|
|
2301
|
+
* and mints `operational.sqlite` BEFORE it reaches `assertLayout()`, so **one**
|
|
2302
|
+
* old-build SessionStart hook on a v6 store leaves every marker behind. That is
|
|
2303
|
+
* the rollback the cut-over plan actually calls for, and after it the new build
|
|
2304
|
+
* refuses its own store for ever while telling the owner it is "readable by
|
|
2305
|
+
* floor/v5-last" — the build that just stood down on the same directory. Both
|
|
2306
|
+
* builds dead, and nothing saying which four names to remove.
|
|
2307
|
+
*
|
|
2308
|
+
* **The discrimination is by LISTING, never by opening** — see
|
|
2309
|
+
* `preRowsLeftoversAreEmpty`. An old build's leftovers are EMPTY `prose/` and
|
|
2310
|
+
* `versions/`; a real v5 store's are not, and a directory that has both names
|
|
2311
|
+
* because somebody hand-copied a `counterparts.sqlite` into a v5 store is
|
|
2312
|
+
* holding every memory he has under `prose/`. "Remove those four" is the right
|
|
2313
|
+
* instruction for the first and a catastrophe for the second, so the sentence
|
|
2314
|
+
* asks before it says it. **Nothing here deletes anything**; the owner does.
|
|
2315
|
+
*/
|
|
2316
|
+
function preRowsRemedy(
|
|
2317
|
+
dir: string,
|
|
2318
|
+
found: readonly string[],
|
|
2319
|
+
): { readableBy: string } | { alsoFound: string; remedy: string } {
|
|
2320
|
+
if (!existsSync(paths.operational(dir))) return { readableBy: PRE_ROWS_READABLE_BY };
|
|
2321
|
+
const leftovers = found.filter((n) => n !== DATABASE_FILE).join(", ");
|
|
2322
|
+
// MOVE ASIDE, NEVER REMOVE — and that is what makes the guess below safe to
|
|
2323
|
+
// get wrong (third review, NEW-MINOR-2). By LISTING alone an old build's
|
|
2324
|
+
// empty leftovers and a REAL v5 store whose `prose/` somebody moved out look
|
|
2325
|
+
// identical: both have an empty `prose/` and an `operational.sqlite`, and the
|
|
2326
|
+
// second one's database holds every memory's physics, bands, dates and the
|
|
2327
|
+
// permanent removal record. Telling him to delete it would destroy the store.
|
|
2328
|
+
// Telling him to move it into a folder of its own costs one `mv` and is
|
|
2329
|
+
// reversible whichever of the two it turns out to be.
|
|
2330
|
+
if (preRowsLeftoversAreEmpty(dir)) {
|
|
2331
|
+
return {
|
|
2332
|
+
alsoFound: DATABASE_FILE,
|
|
2333
|
+
remedy:
|
|
2334
|
+
`${DATABASE_FILE} is THIS build's store. Beside it are ${leftovers} (and possibly tmp/), ` +
|
|
2335
|
+
`which an older build leaves behind when it is pointed at a store like this one — its ` +
|
|
2336
|
+
`prose/ and versions/ are empty here. MOVE THOSE OUT of this directory into a folder of ` +
|
|
2337
|
+
`their own; do not delete them, and do not delete ${DATABASE_FILE}. This store then opens ` +
|
|
2338
|
+
`again with every memory in it. If you moved prose/ aside yourself, that operational.sqlite ` +
|
|
2339
|
+
`is your PRE-ROWS store and the words that go with it are wherever you put them — keep both, ` +
|
|
2340
|
+
`and open it with the build tagged ${PRE_ROWS_READABLE_BY}.`,
|
|
2341
|
+
};
|
|
2342
|
+
}
|
|
2343
|
+
return {
|
|
2344
|
+
alsoFound: DATABASE_FILE,
|
|
2345
|
+
remedy:
|
|
2346
|
+
`this directory holds TWO stores' names — a pre-rows store (${leftovers}, WITH FILES IN IT) ` +
|
|
2347
|
+
`and a ${DATABASE_FILE}. DELETE NEITHER. Move one of them out into a directory of its own and ` +
|
|
2348
|
+
`point at the one you mean; the pre-rows half is read by the build tagged ${PRE_ROWS_READABLE_BY}.`,
|
|
2349
|
+
};
|
|
2350
|
+
}
|
|
2351
|
+
|
|
2352
|
+
/**
|
|
2353
|
+
* THE TWO ROWS THAT NEVER GET A VECTOR, and why the rule is one function.
|
|
2354
|
+
*
|
|
2355
|
+
* Both are `type: "schema"` rows that are DELIVERED AT THE WAKE and are skipped
|
|
2356
|
+
* by `recall/activate.ts`, so neither can reach a turn through the semantic
|
|
2357
|
+
* channel however good its vector is. Embedding either buys retrieval nothing
|
|
2358
|
+
* and costs three things that were measured rather than argued:
|
|
2359
|
+
*
|
|
2360
|
+
* 1. **The most sensitive prose in the store goes out to an embedding API for
|
|
2361
|
+
* no use.** The self page is up to 16 KB of first-person identity; the
|
|
2362
|
+
* handoff is the prose E1's own CONTRACT calls the likeliest to carry a
|
|
2363
|
+
* token. Data leaves the machine only by the owner's choice (constitution
|
|
2364
|
+
* 6), and "because the indexer indexes everything" is not a choice.
|
|
2365
|
+
* 2. **They put a permanent floor under `unembeddedCount()`** — the number
|
|
2366
|
+
* `doctor` and the parallel run watch, whose whole job is to say what is
|
|
2367
|
+
* ACTIONABLE. On a keyless store that floor never falls.
|
|
2368
|
+
* 3. **A vector for a superseded body can displace a live neighbour** on the
|
|
2369
|
+
* semantic slate (`cache.ts#deindexDoc`'s note: `nearestTo` scans
|
|
2370
|
+
* `embeddings` with no liveness filter). Fewer rows in that table that
|
|
2371
|
+
* nothing can deliver is strictly better.
|
|
2372
|
+
*
|
|
2373
|
+
* - **`role: "page"`** — the self page (S1). Raised by E1's adversarial review
|
|
2374
|
+
* as "worth checking whether the page is in the same position"; it was, and
|
|
2375
|
+
* the coordinating session asked for the exclusion on 2026-09-20. **A
|
|
2376
|
+
* WORKING DEFAULT, not a ruling — the owner has not been asked, and this is
|
|
2377
|
+
* revisable without ceremony** (CLAUDE.md). The three reasons above are the
|
|
2378
|
+
* whole of the argument for it; if any of them stops being true, so does
|
|
2379
|
+
* this line.
|
|
2380
|
+
* - **`role: "handoff"`** — the per-directory handoff (E1).
|
|
2381
|
+
*
|
|
2382
|
+
* Read STRUCTURALLY, for the reason `recall/` reads these roles structurally:
|
|
2383
|
+
* `store/` depends on no module above it, and a parse that fails reads as
|
|
2384
|
+
* "embed it", which is the direction that only ever costs a vector nobody asks
|
|
2385
|
+
* for. The strings' owners are `core/self/page.ts#SELF_PAGE_ROLE` and
|
|
2386
|
+
* `core/handoff/index.ts#HANDOFF_ROLE`.
|
|
2387
|
+
*
|
|
2388
|
+
* **What is NOT excluded, checked by the same test and left alone:**
|
|
2389
|
+
* the JOURNAL (`type: "episode"`) is a real recall candidate — `activate` does
|
|
2390
|
+
* not skip it, `expandHandle` returns it with `journal: true`, and the backfill
|
|
2391
|
+
* puts episodes in the FIRST group on purpose — so a vector buys it something
|
|
2392
|
+
* and it keeps one. Beliefs and entities (`role: "belief"`, `"entity"`) are
|
|
2393
|
+
* candidates too. S2's nightly writer mints no row of its own: it revises the
|
|
2394
|
+
* PAGE row and writes events, so excluding the page covers it whole.
|
|
2395
|
+
*/
|
|
2396
|
+
export function noVector(type: string, role: unknown): boolean {
|
|
2397
|
+
return type === "schema" && (role === "handoff" || role === "page");
|
|
2398
|
+
}
|
|
2399
|
+
|
|
2400
|
+
/** The same rule for a caller holding box 2's columns rather than a document. */
|
|
2401
|
+
function notForEmbedding(row: { type: string; meta: string }): boolean {
|
|
2402
|
+
if (row.type !== "schema") return false;
|
|
2403
|
+
try {
|
|
2404
|
+
return noVector(row.type, (JSON.parse(row.meta) as Record<string, unknown>)["role"]);
|
|
2405
|
+
} catch {
|
|
2406
|
+
return false;
|
|
2407
|
+
}
|
|
2408
|
+
}
|
|
2409
|
+
|
|
2410
|
+
export function newId(type: ProseType): string {
|
|
2411
|
+
return `${ID_PREFIX[type]}_${randomBytes(6).toString("hex")}`;
|
|
2412
|
+
}
|
|
2413
|
+
|
|
2414
|
+
/**
|
|
2415
|
+
* The calendar date an INSTANT falls on — the provenance clock's only arithmetic.
|
|
2416
|
+
*
|
|
2417
|
+
* UTC by deliberate choice, not by accident: every other date in this codebase is
|
|
2418
|
+
* written with the same `toISOString().slice(0, 10)` (the hook that supplies
|
|
2419
|
+
* `advanceClock`'s date, `sleep/cycle.ts#todayDate`, the embedder's seat rotation),
|
|
2420
|
+
* so a local-dating provenance clock would put provenance and physics on two
|
|
2421
|
+
* different calendars. Moving all of them to local dating is a real, separate
|
|
2422
|
+
* question, filed in `NOTES.md` 2026-09-05 with its evidence.
|
|
2423
|
+
*
|
|
2424
|
+
* NOT `physics/clock.ts#dayKey`. That function shifts by the BOUNDARY HOUR, which
|
|
2425
|
+
* is a physics idea — "which lived day does this activity belong to" — and a
|
|
2426
|
+
* memory taken at 01:30 was taken on the 14th no matter which lived day it counts
|
|
2427
|
+
* toward. Provenance does not get the boundary shift.
|
|
2428
|
+
*/
|
|
2429
|
+
export function dateOf(at: number): string {
|
|
2430
|
+
return new Date(at).toISOString().slice(0, 10);
|
|
2431
|
+
}
|
|
2432
|
+
|
|
2433
|
+
/** The ambient date. Adapters and defaults only — a store reads `store.today()`. */
|
|
2434
|
+
export function today(): string {
|
|
2435
|
+
return dateOf(Date.now());
|
|
2436
|
+
}
|
|
2437
|
+
|
|
2438
|
+
/**
|
|
2439
|
+
* True when a data dir has already been initialized (used by adapters, not writes).
|
|
2440
|
+
*
|
|
2441
|
+
* A PRE-ROWS store counts, and has to: ~20 console commands gate on this before
|
|
2442
|
+
* they open anything, and a v5 store answering "false" would send every one of
|
|
2443
|
+
* them down the "there is no store here, run init" path — which is both wrong
|
|
2444
|
+
* and the one sentence that invites somebody to create a store on top of his
|
|
2445
|
+
* old one. Answering true sends them all to the named `STORE_PRE_ROWS` refusal
|
|
2446
|
+
* instead, which says what happened and which build still reads it.
|
|
2447
|
+
*/
|
|
2448
|
+
export function storeExists(dir: string = dataDir()): boolean {
|
|
2449
|
+
return existsSync(paths.operational(dir)) || preRowsMarkersIn(dir).length > 0;
|
|
2450
|
+
}
|