piroboros 0.0.0-stage → 0.2.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/CHANGELOG.md +43 -0
- package/LICENSE +21 -0
- package/NOTICE +39 -0
- package/README.md +140 -2
- package/agents/astrelia.md +31 -0
- package/agents/avaritia.md +31 -0
- package/agents/elaria.md +31 -0
- package/agents/nytheria.md +32 -0
- package/agents/raskreia.md +32 -0
- package/agents/samaela.md +40 -0
- package/agents/vaelia.md +35 -0
- package/agents/vesperia.md +45 -0
- package/bin/piroboros.mjs +17 -0
- package/dist/auth.js +105 -0
- package/dist/base.js +19 -0
- package/dist/chat/budget.js +87 -0
- package/dist/chat/compactloop.js +63 -0
- package/dist/chat/compactor.js +530 -0
- package/dist/chat/extension.js +36 -0
- package/dist/chat/hook.js +40 -0
- package/dist/chat/log.js +317 -0
- package/dist/chat/outbound.js +114 -0
- package/dist/chat/plan.js +64 -0
- package/dist/chat/prompt.js +115 -0
- package/dist/chat/status.js +37 -0
- package/dist/chat/stuck.js +83 -0
- package/dist/chat/tools.js +163 -0
- package/dist/chat/tree.js +73 -0
- package/dist/chat/turn.js +305 -0
- package/dist/chat/view.js +163 -0
- package/dist/conclave/agents.js +113 -0
- package/dist/conclave/pipeline.js +715 -0
- package/dist/conclave/report.js +43 -0
- package/dist/config.js +614 -0
- package/dist/durable.js +177 -0
- package/dist/guard.js +346 -0
- package/dist/lock.js +56 -0
- package/dist/main.js +348 -0
- package/dist/memory/akashic/api.js +121 -0
- package/dist/memory/akashic/confusables.js +41 -0
- package/dist/memory/akashic/scanner.js +67 -0
- package/dist/memory/akashic/snapshot.js +31 -0
- package/dist/memory/akashic/store.js +1254 -0
- package/dist/memory/akashic/tools.js +168 -0
- package/dist/memory/akashic/vault.js +984 -0
- package/dist/memory/host.js +124 -0
- package/dist/memory/mnemosia/adapters/akashic-memories.js +180 -0
- package/dist/memory/mnemosia/adapters/contract.js +219 -0
- package/dist/memory/mnemosia/agents.js +387 -0
- package/dist/memory/mnemosia/brief.js +890 -0
- package/dist/memory/mnemosia/claims.js +609 -0
- package/dist/memory/mnemosia/conflicts.js +769 -0
- package/dist/memory/mnemosia/escalation.js +257 -0
- package/dist/memory/mnemosia/feedback.js +108 -0
- package/dist/memory/mnemosia/filters.js +248 -0
- package/dist/memory/mnemosia/intent.js +221 -0
- package/dist/memory/mnemosia/open.js +34 -0
- package/dist/memory/mnemosia/orchestrator.js +926 -0
- package/dist/memory/mnemosia/plan.js +266 -0
- package/dist/memory/mnemosia/policy.js +426 -0
- package/dist/memory/mnemosia/progressive.js +550 -0
- package/dist/memory/mnemosia/provenance.js +458 -0
- package/dist/memory/mnemosia/qualifiers.js +428 -0
- package/dist/memory/mnemosia/rank.js +525 -0
- package/dist/memory/mnemosia/relations.js +156 -0
- package/dist/memory/mnemosia/requirements.js +138 -0
- package/dist/memory/mnemosia/rerank.js +253 -0
- package/dist/memory/mnemosia/retention.js +174 -0
- package/dist/memory/mnemosia/rollback.js +337 -0
- package/dist/memory/mnemosia/select.js +607 -0
- package/dist/memory/mnemosia/similarity.js +164 -0
- package/dist/memory/mnemosia/situation.js +251 -0
- package/dist/memory/mnemosia/task.js +418 -0
- package/dist/memory/mnemosia/temporal.js +136 -0
- package/dist/memory/mnemosia/tokens.js +66 -0
- package/dist/memory/mnemosia/tools.js +160 -0
- package/dist/memory/mnemosia/trace.js +306 -0
- package/dist/memory/mnemosia/types.js +298 -0
- package/dist/models.js +360 -0
- package/dist/paths.js +103 -0
- package/dist/redact.js +79 -0
- package/dist/runtime.js +378 -0
- package/dist/search-format.js +102 -0
- package/dist/search.js +351 -0
- package/dist/setup.js +366 -0
- package/dist/shell.js +110 -0
- package/dist/skills.js +311 -0
- package/dist/telemetry.js +84 -0
- package/dist/tui/app.js +1011 -0
- package/dist/tui/commands.js +121 -0
- package/dist/tui/keys.js +83 -0
- package/dist/tui/pane.js +387 -0
- package/dist/tui/panel.js +60 -0
- package/dist/tui/picker.js +25 -0
- package/dist/tui/sanitize.js +59 -0
- package/dist/tui/settings.js +198 -0
- package/dist/tui/setup.js +256 -0
- package/dist/tui/theme.js +26 -0
- package/dist/tui/thinking/parse.js +1094 -0
- package/dist/tui/thinking/select.js +86 -0
- package/dist/tui/thinking/state.js +137 -0
- package/dist/tui/thinking/types.js +3 -0
- package/dist/tui/thinking/view.js +74 -0
- package/dist/tui/viewport.js +208 -0
- package/dist/undo.js +258 -0
- package/dist/web.js +933 -0
- package/docs/conclave.md +21 -0
- package/docs/configuration.md +48 -0
- package/docs/development.md +25 -0
- package/docs/interface.md +33 -0
- package/docs/memory.md +11 -0
- package/docs/privacy.md +13 -0
- package/docs/tools.md +20 -0
- package/docs/web.md +38 -0
- package/models.json.example +34 -0
- package/package.json +76 -4
- package/settings.json.example +29 -0
- package/skills/conclave/SKILL.md +76 -0
|
@@ -0,0 +1,1254 @@
|
|
|
1
|
+
// Ported from akashic-forge/store.ts @ f0a8ad4 (MIT; see NOTICE)
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import { DatabaseSync } from "node:sqlite";
|
|
6
|
+
import { REDACTION_MARKER, redactJsonValue, redactSensitive } from "../../redact.js";
|
|
7
|
+
import { isCharacterRule, scanMemoryText } from "./scanner.js";
|
|
8
|
+
// The scrub is pure and lives in src/redact.ts; re-exported so store consumers keep one import site.
|
|
9
|
+
export { REDACTION_MARKER, redactJsonValue, redactSensitive };
|
|
10
|
+
export const MAX_MEMORY_CHARS = 4_000;
|
|
11
|
+
/** Raw content budget per chunk of a size-aware write; the rest of the per-record cap is marker headroom. */
|
|
12
|
+
export const CHUNK_CONTENT_CHARS = 3_600;
|
|
13
|
+
/** A write within this many characters of the per-memory cap is flagged nearLimit. */
|
|
14
|
+
export const NEAR_MEMORY_LIMIT_CHARS = 400;
|
|
15
|
+
// Corpus size is decoupled from injection size: index.ts bounds the session-start snapshot with its
|
|
16
|
+
// own MAX_INJECTED_CHARS, so these ceilings only govern how much curated memory may exist at rest.
|
|
17
|
+
export const GLOBAL_MEMORY_CHAR_LIMIT = 16_000;
|
|
18
|
+
export const PROJECT_MEMORY_CHAR_LIMIT = 32_000;
|
|
19
|
+
/** §18.1 unit-of-measure ruling: CHARS everywhere — L0 head ≤ 256 chars, L1 head ≤ 2,048 + tail ≤ 512. */
|
|
20
|
+
export const DISCLOSURE_HEAD_CHARS = 256;
|
|
21
|
+
export const DISCLOSURE_L1_HEAD_CHARS = 2_048;
|
|
22
|
+
export const DISCLOSURE_L1_TAIL_CHARS = 512;
|
|
23
|
+
/**
|
|
24
|
+
* Schema axis 2 of 2: the store schema version, a meta row in `store_meta` (NOT `PRAGMA
|
|
25
|
+
* user_version`, which stays 0 and is not an axis — the same distinction the frozen P6 contract
|
|
26
|
+
* documents for the compaction ledger). Validated on open: a database stamped with a NEWER version
|
|
27
|
+
* refuses to open (downgrade would misread newer rows); a stamp older than this build's is the
|
|
28
|
+
* migration window, which has always been the additive CREATE/ALTER discipline in the constructor.
|
|
29
|
+
* Bump semantics: additive table/column additions are MINOR (forward-openable by older builds only
|
|
30
|
+
* if they tolerate unknown columns — they do not, so a MINOR bump still refuses older builds);
|
|
31
|
+
* incompatible changes are MAJOR. Both axes are separate compatibility axes.
|
|
32
|
+
*/
|
|
33
|
+
// store-schema@2 (G5/SEM1): MINOR bump per §7. The extra tables that motivated it are not part of this
|
|
34
|
+
// port; the stamp is kept so a stamped database opens identically.
|
|
35
|
+
export const STORE_SCHEMA_VERSION = "akashic-forge/store-schema@2";
|
|
36
|
+
/**
|
|
37
|
+
* Forward-migration ladder for the store-schema axis. An entry `<from> → <to>`
|
|
38
|
+
* declares that a store stamped `<from>` can be brought up to `<to>` by this
|
|
39
|
+
* build's constructor ALONE — every step must be an additive MINOR bump whose
|
|
40
|
+
* DDL the idempotent ensureSchema block (CREATE IF NOT EXISTS / ALTER-if-
|
|
41
|
+
* missing, run BEFORE the version check) has already applied by the time the
|
|
42
|
+
* ladder runs, so the migration proper is stamping the meta row forward.
|
|
43
|
+
* Anything not reachable through the ladder — a genuinely unknown version, a
|
|
44
|
+
* downgrade, an incompatible MAJOR — still refuses loudly. A cycle in this
|
|
45
|
+
* literal map is a programming error and refuses rather than loops.
|
|
46
|
+
*/
|
|
47
|
+
const SCHEMA_MIGRATIONS = new Map([
|
|
48
|
+
// G5/SEM1 (store-schema@1 → @2): stamp only; the tables it added are not part of this port.
|
|
49
|
+
["akashic-forge/store-schema@1", "akashic-forge/store-schema@2"],
|
|
50
|
+
]);
|
|
51
|
+
export const DEFAULT_MEMORY_LIMITS = { global: GLOBAL_MEMORY_CHAR_LIMIT, project: PROJECT_MEMORY_CHAR_LIMIT };
|
|
52
|
+
/** A limit below the per-memory cap could never admit a single memory, so it is treated as nonsense. */
|
|
53
|
+
function limitOverride(value, fallback) {
|
|
54
|
+
return typeof value === "number" && Number.isInteger(value) && value >= MAX_MEMORY_CHARS ? value : fallback;
|
|
55
|
+
}
|
|
56
|
+
/** limits.json lives beside the database it governs, so a copied database carries its own limits. */
|
|
57
|
+
export function defaultLimitsPathFor(databasePath) {
|
|
58
|
+
return databasePath === ":memory:" ? undefined : join(dirname(databasePath), "limits.json");
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Optional `limits.json` beside the database, shaped `{ "global": 16000, "project": 32000 }`.
|
|
62
|
+
* This resolves in the AkashicStore constructor at session start, so it fails open in every direction:
|
|
63
|
+
* a missing, unreadable, malformed, or nonsensical file degrades to the built-in defaults rather
|
|
64
|
+
* than throwing, because a throw here would leave the user with no memory at all.
|
|
65
|
+
*/
|
|
66
|
+
export function resolveMemoryLimits(limitsPath) {
|
|
67
|
+
try {
|
|
68
|
+
if (!limitsPath || !existsSync(limitsPath))
|
|
69
|
+
return { ...DEFAULT_MEMORY_LIMITS };
|
|
70
|
+
// Strip a UTF-8 BOM: Windows editors add one, and JSON.parse rejects it, which would
|
|
71
|
+
// silently discard a valid override instead of applying it.
|
|
72
|
+
const parsed = JSON.parse(readFileSync(limitsPath, "utf8").replace(/^\u{FEFF}/u, ""));
|
|
73
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
74
|
+
return { ...DEFAULT_MEMORY_LIMITS };
|
|
75
|
+
const value = parsed;
|
|
76
|
+
return { global: limitOverride(value.global, GLOBAL_MEMORY_CHAR_LIMIT), project: limitOverride(value.project, PROJECT_MEMORY_CHAR_LIMIT) };
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return { ...DEFAULT_MEMORY_LIMITS };
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
export const MemoryKind = {
|
|
83
|
+
Decisions: "decisions",
|
|
84
|
+
People: "people",
|
|
85
|
+
ProjectState: "project-state",
|
|
86
|
+
OpenLoops: "open-loops",
|
|
87
|
+
Preferences: "preferences",
|
|
88
|
+
Procedures: "procedures",
|
|
89
|
+
};
|
|
90
|
+
export const MEMORY_KINDS = Object.values(MemoryKind);
|
|
91
|
+
export function validateKind(kind) {
|
|
92
|
+
if (typeof kind === "string" && MEMORY_KINDS.includes(kind))
|
|
93
|
+
return kind;
|
|
94
|
+
throw new Error(`kind must be one of: ${MEMORY_KINDS.join(", ")}`);
|
|
95
|
+
}
|
|
96
|
+
export const MEMORY_STATES = ["PROPOSED", "ACTIVE", "DISPUTED", "SUPERSEDED", "EXPIRED", "REVOKED", "QUARANTINED", "DELETED"];
|
|
97
|
+
/**
|
|
98
|
+
* ACTIVE is the hub: a memory enters through it and every other state is reached from it.
|
|
99
|
+
* DISPUTED, SUPERSEDED, and EXPIRED are reversible because a conflict can be resolved in the
|
|
100
|
+
* memory's favour, a superseding memory can itself be revoked, and an expiry can be renewed.
|
|
101
|
+
* QUARANTINED returns only to ACTIVE, after review. REVOKED and DELETED are terminal so an
|
|
102
|
+
* audited end state is never quietly reopened. Self-transitions are absent: re-asserting the
|
|
103
|
+
* current state is not a transition.
|
|
104
|
+
*/
|
|
105
|
+
export const MEMORY_STATE_TRANSITIONS = {
|
|
106
|
+
PROPOSED: ["ACTIVE", "REVOKED", "QUARANTINED", "DELETED"],
|
|
107
|
+
ACTIVE: ["DISPUTED", "SUPERSEDED", "EXPIRED", "REVOKED", "QUARANTINED", "DELETED"],
|
|
108
|
+
DISPUTED: ["ACTIVE", "SUPERSEDED", "EXPIRED", "REVOKED", "QUARANTINED", "DELETED"],
|
|
109
|
+
SUPERSEDED: ["ACTIVE", "REVOKED", "QUARANTINED", "DELETED"],
|
|
110
|
+
EXPIRED: ["ACTIVE", "SUPERSEDED", "REVOKED", "QUARANTINED", "DELETED"],
|
|
111
|
+
QUARANTINED: ["ACTIVE", "REVOKED", "DELETED"],
|
|
112
|
+
REVOKED: [],
|
|
113
|
+
DELETED: [],
|
|
114
|
+
};
|
|
115
|
+
/** States a caller sees by default; unresolved conflicts stay visible, the rest is history. */
|
|
116
|
+
export const RETRIEVABLE_MEMORY_STATES = ["ACTIVE", "DISPUTED"];
|
|
117
|
+
export function validateState(state) {
|
|
118
|
+
if (typeof state === "string" && MEMORY_STATES.includes(state))
|
|
119
|
+
return state;
|
|
120
|
+
throw new Error(`state must be one of: ${MEMORY_STATES.join(", ")}`);
|
|
121
|
+
}
|
|
122
|
+
export function assertMemoryTransition(from, to) {
|
|
123
|
+
const source = validateState(from);
|
|
124
|
+
const target = validateState(to);
|
|
125
|
+
const allowed = MEMORY_STATE_TRANSITIONS[source];
|
|
126
|
+
if (allowed.length === 0)
|
|
127
|
+
throw new Error(`invalid memory transition ${source} -> ${target}: ${source} is terminal`);
|
|
128
|
+
if (!allowed.includes(target))
|
|
129
|
+
throw new Error(`invalid memory transition ${source} -> ${target}; allowed from ${source}: ${allowed.join(", ")}`);
|
|
130
|
+
return target;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Merge governance the vault stated over governance the database holds. Absent keys keep the stored
|
|
134
|
+
* value; a row the store has never seen takes the column defaults. This is what lets a governed
|
|
135
|
+
* mutation survive the reconcile that runs at every session start.
|
|
136
|
+
*/
|
|
137
|
+
export function resolveGovernance(stated, current) {
|
|
138
|
+
return {
|
|
139
|
+
state: stated.state ?? current?.state ?? "ACTIVE",
|
|
140
|
+
// version and provenance invert the precedence used by the rest of this merge. They are machine
|
|
141
|
+
// bookkeeping - an optimistic-concurrency counter and store-observed evidence - so a stored row
|
|
142
|
+
// outranks anything a vault file says: honouring a hand-written version would peg the row, every
|
|
143
|
+
// mutation would bump the store, and the next reconcile would drop it back, permanently breaking
|
|
144
|
+
// expectedVersion. With no stored row the vault is the only source and its values are taken,
|
|
145
|
+
// which is what lets a vault restored onto a fresh machine keep its versions instead of
|
|
146
|
+
// resetting to 1. Canonicalization passes no current row, so it still echoes the file verbatim.
|
|
147
|
+
version: current?.version ?? stated.version ?? 1,
|
|
148
|
+
provenance: current?.provenance ?? stated.provenance ?? [],
|
|
149
|
+
expiresAt: stated.expiresAt === undefined ? (current?.expiresAt ?? null) : stated.expiresAt,
|
|
150
|
+
supersedes: stated.supersedes === undefined ? (current?.supersedes ?? null) : stated.supersedes,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
function text(value, field) {
|
|
154
|
+
if (typeof value !== "string" || !value.trim())
|
|
155
|
+
throw new Error(`${field} must be a non-empty string`);
|
|
156
|
+
return value;
|
|
157
|
+
}
|
|
158
|
+
/** The one safety check (F1). Write, update, import, render and the mnemosia filters all reach the scanner through here. */
|
|
159
|
+
export function validateMemorySafety(value) {
|
|
160
|
+
const raw = text(value, "content");
|
|
161
|
+
const rule = scanMemoryText(raw);
|
|
162
|
+
if (rule !== undefined)
|
|
163
|
+
throw new Error(isCharacterRule(rule) ? "memory content rejected: invisible Unicode is not allowed" : "memory content rejected by the prompt-injection/exfiltration safety scanner");
|
|
164
|
+
return redactSensitive(raw);
|
|
165
|
+
}
|
|
166
|
+
export function validateMemoryContent(value) {
|
|
167
|
+
const content = validateMemorySafety(value);
|
|
168
|
+
if (content.length > MAX_MEMORY_CHARS) {
|
|
169
|
+
throw new Error(`memory content exceeds ${MAX_MEMORY_CHARS} characters; consolidate or shorten it before retrying`);
|
|
170
|
+
}
|
|
171
|
+
return content;
|
|
172
|
+
}
|
|
173
|
+
function normalizeProject(project) {
|
|
174
|
+
const normalized = resolve(project.trim());
|
|
175
|
+
return process.platform === "win32" ? normalized.toLowerCase() : normalized;
|
|
176
|
+
}
|
|
177
|
+
function projectKey(project) {
|
|
178
|
+
return project ? normalizeProject(project) : "";
|
|
179
|
+
}
|
|
180
|
+
function validateProject(project, scope) {
|
|
181
|
+
if (scope === "project")
|
|
182
|
+
return normalizeProject(text(project, "project"));
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
function validateScope(scope) {
|
|
186
|
+
if (scope !== "global" && scope !== "project")
|
|
187
|
+
throw new Error("scope must be global or project");
|
|
188
|
+
return scope;
|
|
189
|
+
}
|
|
190
|
+
function memoryLimit(limits, scope) {
|
|
191
|
+
return scope === "global" ? limits.global : limits.project;
|
|
192
|
+
}
|
|
193
|
+
function validateFilter(scope) {
|
|
194
|
+
if (scope === undefined || scope === "all" || scope === "global" || scope === "project")
|
|
195
|
+
return scope ?? "all";
|
|
196
|
+
throw new Error("scope must be all, global, or project");
|
|
197
|
+
}
|
|
198
|
+
function limitValue(value, fallback = 20) {
|
|
199
|
+
if (value === undefined)
|
|
200
|
+
return fallback;
|
|
201
|
+
if (!Number.isInteger(value) || value < 1)
|
|
202
|
+
throw new Error("limit must be a positive integer");
|
|
203
|
+
return Math.min(value, 100);
|
|
204
|
+
}
|
|
205
|
+
function importanceValue(value) {
|
|
206
|
+
if (value === undefined)
|
|
207
|
+
return 5;
|
|
208
|
+
if (!Number.isInteger(value) || value < 0 || value > 10)
|
|
209
|
+
throw new Error("importance must be an integer from 0 to 10");
|
|
210
|
+
return value;
|
|
211
|
+
}
|
|
212
|
+
function tagsValue(value) {
|
|
213
|
+
if (value === undefined)
|
|
214
|
+
return [];
|
|
215
|
+
if (!Array.isArray(value) || value.some((tag) => typeof tag !== "string"))
|
|
216
|
+
throw new Error("tags must be strings");
|
|
217
|
+
return [...new Set(value.map((tag) => redactSensitive(tag.trim())).filter(Boolean))].slice(0, 20);
|
|
218
|
+
}
|
|
219
|
+
function versionValue(value, field = "version") {
|
|
220
|
+
if (value === undefined)
|
|
221
|
+
return 1;
|
|
222
|
+
if (!Number.isInteger(value) || value < 1)
|
|
223
|
+
throw new Error(`${field} must be a positive integer`);
|
|
224
|
+
return value;
|
|
225
|
+
}
|
|
226
|
+
function provenanceValue(value) {
|
|
227
|
+
if (value === undefined)
|
|
228
|
+
return [];
|
|
229
|
+
if (!Array.isArray(value))
|
|
230
|
+
throw new Error("provenance must be an array");
|
|
231
|
+
const redacted = redactJsonValue(value);
|
|
232
|
+
try {
|
|
233
|
+
JSON.stringify(redacted);
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
throw new Error("provenance must be JSON-serializable");
|
|
237
|
+
}
|
|
238
|
+
return redacted;
|
|
239
|
+
}
|
|
240
|
+
function expiresAtValue(value) {
|
|
241
|
+
if (value === undefined || value === null)
|
|
242
|
+
return null;
|
|
243
|
+
if (!Number.isFinite(value))
|
|
244
|
+
throw new Error("expires_at must be a finite timestamp");
|
|
245
|
+
return value;
|
|
246
|
+
}
|
|
247
|
+
function supersedesValue(value) {
|
|
248
|
+
if (value === undefined || value === null)
|
|
249
|
+
return null;
|
|
250
|
+
return redactSensitive(text(value, "supersedes"));
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* The deterministic, boundary-aware chunker behind the size-aware write policy.
|
|
254
|
+
*
|
|
255
|
+
* AkashicForge may automatically restructure memory to satisfy storage constraints, but it must not
|
|
256
|
+
* silently destroy or semantically rewrite memory at the storage boundary: every chunk is a raw,
|
|
257
|
+
* lossless slice of the original content, and concatenating all chunks reproduces it byte-for-byte.
|
|
258
|
+
* Redaction and the safety scanner run on the whole content before this chunker ever sees it, so the
|
|
259
|
+
* same scanner verdict covers every chunk it emits.
|
|
260
|
+
*
|
|
261
|
+
* Boundaries, coarsest first: paragraph (blank-line run), then sentence, then any whitespace, then a
|
|
262
|
+
* hard character cut. A boundary is preferred to a mid-word cut whenever one exists within the
|
|
263
|
+
* budget; the hard cut exists so pathological input — one enormous word, no whitespace at all —
|
|
264
|
+
* still chunks instead of throwing.
|
|
265
|
+
*/
|
|
266
|
+
export function chunkContent(content, maxChars = CHUNK_CONTENT_CHARS) {
|
|
267
|
+
if (!Number.isInteger(maxChars) || maxChars < 1)
|
|
268
|
+
throw new Error("maxChars must be a positive integer");
|
|
269
|
+
if (content.length <= maxChars)
|
|
270
|
+
return [{ content, part: 1, parts: 1 }];
|
|
271
|
+
const chunks = [];
|
|
272
|
+
let start = 0;
|
|
273
|
+
// A greedy accumulation: pack each chunk as full as its best boundary allows, because fewer
|
|
274
|
+
// records per group is better for retrieval and for the per-scope capacity budget.
|
|
275
|
+
while (start < content.length) {
|
|
276
|
+
if (content.length - start <= maxChars) {
|
|
277
|
+
chunks.push(content.slice(start));
|
|
278
|
+
break;
|
|
279
|
+
}
|
|
280
|
+
const window = content.slice(start, start + maxChars);
|
|
281
|
+
// Coarse-to-fine: the last blank-line run, sentence end, or whitespace inside the window wins;
|
|
282
|
+
// every boundary index is relative to `start`.
|
|
283
|
+
const boundary = (() => {
|
|
284
|
+
// A blank-line run ends at its last character, and the whole run stays with the chunk it ends,
|
|
285
|
+
// so the next chunk opens on content rather than on a separator. `boundary` is the index of the
|
|
286
|
+
// last character to include, which every other case below follows as well.
|
|
287
|
+
const lf = window.lastIndexOf("\n\n");
|
|
288
|
+
const crlf = window.lastIndexOf("\r\n\r\n");
|
|
289
|
+
const paragraph = Math.max(lf >= 0 ? lf + 1 : -1, crlf >= 0 ? crlf + 3 : -1);
|
|
290
|
+
if (paragraph >= 0)
|
|
291
|
+
return paragraph;
|
|
292
|
+
const sentence = /[.!?…][ \t\r\n]/gu;
|
|
293
|
+
let sentenceEnd = -1;
|
|
294
|
+
let match;
|
|
295
|
+
while ((match = sentence.exec(window)) !== null)
|
|
296
|
+
sentenceEnd = match.index + match[0].length - 1;
|
|
297
|
+
if (sentenceEnd >= 0)
|
|
298
|
+
return sentenceEnd;
|
|
299
|
+
const space = Math.max(window.lastIndexOf(" "), window.lastIndexOf("\t"), window.lastIndexOf("\n"), window.lastIndexOf("\r"));
|
|
300
|
+
if (space >= 0)
|
|
301
|
+
return space;
|
|
302
|
+
return -1;
|
|
303
|
+
})();
|
|
304
|
+
// No boundary at all (one enormous word): a hard cut. A boundary that lands exactly at the
|
|
305
|
+
// budget is taken; one past it falls back to the hard cut rather than exceeding the cap.
|
|
306
|
+
let cut = boundary >= 0 ? start + boundary + 1 : start + maxChars;
|
|
307
|
+
// A hard cut must not land between the two halves of a surrogate pair.
|
|
308
|
+
if (boundary < 0 && cut < content.length) {
|
|
309
|
+
const last = content.charCodeAt(cut - 1);
|
|
310
|
+
if (last >= 0xd800 && last <= 0xdbff && cut - 1 > start)
|
|
311
|
+
cut -= 1;
|
|
312
|
+
}
|
|
313
|
+
chunks.push(content.slice(start, cut));
|
|
314
|
+
start = cut;
|
|
315
|
+
}
|
|
316
|
+
if (chunks.length === 1)
|
|
317
|
+
return [{ content, part: 1, parts: 1 }];
|
|
318
|
+
return chunks.map((chunk, index) => ({ content: chunk, part: index + 1, parts: chunks.length }));
|
|
319
|
+
}
|
|
320
|
+
/** The deterministic group id for a chunked write: same full original content, kind, and tags in, same id out. */
|
|
321
|
+
export function memoryGroupId(content, kind, tags) {
|
|
322
|
+
const canonical = [content, kind, [...tags].sort().join("\u001f")].join("\u001f");
|
|
323
|
+
return `grp-${createHash("sha256").update(canonical, "utf8").digest("hex")}`;
|
|
324
|
+
}
|
|
325
|
+
/** The group id format every layer agrees on: `grp-` plus a SHA-256 hex digest. */
|
|
326
|
+
export const MEMORY_GROUP_ID_RE = /^grp-[0-9a-f]{64}$/;
|
|
327
|
+
/**
|
|
328
|
+
* Prepend a chunk's structural markers: a `[part N/M] [group: id]` line on every part, plus a
|
|
329
|
+
* `split across` note on part 1 so a reader who only ever sees one file knows the memory is split.
|
|
330
|
+
* The markers cost the headroom CHUNK_CONTENT_CHARS leaves below MAX_MEMORY_CHARS.
|
|
331
|
+
*/
|
|
332
|
+
function decorateChunk(chunk, groupId) {
|
|
333
|
+
const header = `[part ${chunk.part}/${chunk.parts}] [group: ${groupId}]`;
|
|
334
|
+
return chunk.part === 1 ? `${header}\n[split across ${chunk.parts} parts; retrieve group ${groupId}]\n${chunk.content}` : `${header}\n${chunk.content}`;
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Undo decorateChunk by exact prefix match, so a raw slice that itself begins with a marker-looking
|
|
338
|
+
* line is never eaten: only the exact lines this store generated are stripped. A human-edited body
|
|
339
|
+
* degrades visibly (its marker line survives) rather than silently losing a content line.
|
|
340
|
+
*/
|
|
341
|
+
function rawChunkContent(memory) {
|
|
342
|
+
let content = memory.content;
|
|
343
|
+
if (memory.part === null || memory.parts === null || memory.memoryGroupId === null)
|
|
344
|
+
return content;
|
|
345
|
+
const marker = `[part ${memory.part}/${memory.parts}] [group: ${memory.memoryGroupId}]`;
|
|
346
|
+
if (content.startsWith(`${marker}\n`))
|
|
347
|
+
content = content.slice(marker.length + 1);
|
|
348
|
+
if (memory.part === 1) {
|
|
349
|
+
const note = `[split across ${memory.parts} parts; retrieve group ${memory.memoryGroupId}]`;
|
|
350
|
+
if (content.startsWith(`${note}\n`))
|
|
351
|
+
content = content.slice(note.length + 1);
|
|
352
|
+
}
|
|
353
|
+
return content;
|
|
354
|
+
}
|
|
355
|
+
/** Reassemble a group's parts into the exact original content: raw slices, in part order, joined. */
|
|
356
|
+
export function reassembleGroup(records) {
|
|
357
|
+
return [...records]
|
|
358
|
+
.filter((memory) => memory.part !== null)
|
|
359
|
+
.sort((a, b) => (a.part ?? 0) - (b.part ?? 0))
|
|
360
|
+
.map(rawChunkContent)
|
|
361
|
+
.join("");
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* §18.1/§18.3 window slice over a boundary map: assembles exactly the parts whose raw ranges
|
|
365
|
+
* intersect [start, start + length) — the part-intersection rule for L0 heads, L1 head/tail
|
|
366
|
+
* windows, and L2 slices alike. The map's contents are already in memory, so this is a pure
|
|
367
|
+
* re-slice with no second read.
|
|
368
|
+
*/
|
|
369
|
+
function rawWindow(map, start, length) {
|
|
370
|
+
if (length <= 0 || map.length === 0)
|
|
371
|
+
return "";
|
|
372
|
+
const end = start + length;
|
|
373
|
+
let out = "";
|
|
374
|
+
for (const entry of map) {
|
|
375
|
+
if (entry.end <= start)
|
|
376
|
+
continue;
|
|
377
|
+
if (entry.start >= end)
|
|
378
|
+
break;
|
|
379
|
+
const from = Math.max(0, start - entry.start);
|
|
380
|
+
const to = Math.min(entry.rawLength, end - entry.start);
|
|
381
|
+
if (to > from)
|
|
382
|
+
out += entry.raw.slice(from, to);
|
|
383
|
+
}
|
|
384
|
+
return out;
|
|
385
|
+
}
|
|
386
|
+
/** Convert free text into literal FTS5 terms; operators and punctuation never reach MATCH. */
|
|
387
|
+
export function tokenizeSearch(value) {
|
|
388
|
+
text(value, "query");
|
|
389
|
+
const tokens = value.normalize("NFKC").match(/[\p{L}\p{N}_-]+/gu) ?? [];
|
|
390
|
+
return [...new Set(tokens.filter((token) => /[\p{L}\p{N}_]/u.test(token)).map((token) => token.slice(0, 128)))].slice(0, 32);
|
|
391
|
+
}
|
|
392
|
+
export function toSafeMatchQuery(value) {
|
|
393
|
+
const tokens = tokenizeSearch(value);
|
|
394
|
+
if (tokens.length === 0)
|
|
395
|
+
throw new Error("query must contain searchable text");
|
|
396
|
+
return tokens.map((token) => `"${token.replaceAll('"', '""')}"`).join(" ");
|
|
397
|
+
}
|
|
398
|
+
function parseMetadata(value) {
|
|
399
|
+
if (typeof value !== "string" || !value)
|
|
400
|
+
return {};
|
|
401
|
+
try {
|
|
402
|
+
const parsed = JSON.parse(value);
|
|
403
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
404
|
+
}
|
|
405
|
+
catch {
|
|
406
|
+
return {};
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
function rowString(row, key) {
|
|
410
|
+
return String(row[key] ?? "");
|
|
411
|
+
}
|
|
412
|
+
function rowNumber(row, key) {
|
|
413
|
+
return Number(row[key] ?? 0);
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* The `bm25()` column, when the query that produced this row asked for one.
|
|
417
|
+
*
|
|
418
|
+
* Additive by construction: every non-FTS read selects no such column, so the key is absent and the
|
|
419
|
+
* record is byte-for-byte what it was before. `Number.isFinite` rather than a bare cast because a
|
|
420
|
+
* row from any other origin must not be able to smuggle a NaN into a relevance field.
|
|
421
|
+
*/
|
|
422
|
+
function rankFromRow(row) {
|
|
423
|
+
const value = row[BM25_COLUMN_ALIAS];
|
|
424
|
+
return typeof value === "number" && Number.isFinite(value) ? { rank: value } : {};
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Group fields off a row, additive exactly as `rank` is: a row that predates the size-aware write
|
|
428
|
+
* policy (or a vault record without group frontmatter) carries NULL columns, and NULL means "not a
|
|
429
|
+
* chunk part", which is stated by the key's absence — never by a `null` value — so the record
|
|
430
|
+
* shape of an ordinary memory stays byte-for-byte what it was before the columns existed.
|
|
431
|
+
*/
|
|
432
|
+
function groupFromRow(row) {
|
|
433
|
+
const groupId = row.memory_group_id;
|
|
434
|
+
if (groupId === null || groupId === undefined || !groupId)
|
|
435
|
+
return {};
|
|
436
|
+
return { memoryGroupId: String(groupId), part: rowNumber(row, "part"), parts: rowNumber(row, "parts") };
|
|
437
|
+
}
|
|
438
|
+
function parseProvenance(value) {
|
|
439
|
+
if (typeof value !== "string" || !value)
|
|
440
|
+
return [];
|
|
441
|
+
try {
|
|
442
|
+
const parsed = JSON.parse(value);
|
|
443
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
444
|
+
}
|
|
445
|
+
catch {
|
|
446
|
+
return [];
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Where `bm25()` lands in an FTS row. Aliased rather than named `rank` because `rank` is a reserved
|
|
451
|
+
* FTS5 column name, and a column list that shadowed it would be a trap for the next reader.
|
|
452
|
+
*/
|
|
453
|
+
const BM25_COLUMN_ALIAS = "bm25_rank";
|
|
454
|
+
const MEMORY_COLUMN_NAMES = ["id", "kind", "content", "content_hash", "scope", "project", "tags", "importance", "state", "version", "expires_at", "supersedes", "provenance", "memory_group_id", "part", "parts", "created_at", "updated_at"];
|
|
455
|
+
const MUTATION_COLUMNS = "id, memory_id, idempotency_key, actor, reason, transition, prev_version, new_version, policy_version, created_at, details_json";
|
|
456
|
+
/** One column list for every memory read, so a new governance column can never be missed. */
|
|
457
|
+
function memoryColumns(alias) {
|
|
458
|
+
return MEMORY_COLUMN_NAMES.map((column) => (alias ? `${alias}.${column}` : column)).join(", ");
|
|
459
|
+
}
|
|
460
|
+
/** The lossy projection the tool renders; full records stay available through the typed read paths. */
|
|
461
|
+
function memoryResult(memory) {
|
|
462
|
+
return { source: "memory", id: memory.id, kind: memory.kind, content: memory.content, scope: memory.scope, project: memory.project, tags: memory.tags, importance: memory.importance, createdAt: memory.createdAt, updatedAt: memory.updatedAt };
|
|
463
|
+
}
|
|
464
|
+
/** Unresolved conflicts stay visible by default; every other state is history a caller opts into. */
|
|
465
|
+
function stateWhere(alias, includeAllStates) {
|
|
466
|
+
if (includeAllStates === true)
|
|
467
|
+
return "1 = 1";
|
|
468
|
+
return `${alias}.state IN (${RETRIEVABLE_MEMORY_STATES.map((state) => `'${state}'`).join(", ")})`;
|
|
469
|
+
}
|
|
470
|
+
export class AkashicStore {
|
|
471
|
+
path;
|
|
472
|
+
/** Resolved once per open, so the write path can never validate against different ceilings. */
|
|
473
|
+
limits;
|
|
474
|
+
db;
|
|
475
|
+
depth = 0;
|
|
476
|
+
/** §18.6 reassembly counter: incremented by getMemoryGroup only (listMemoriesByGroup returns parts and the
|
|
477
|
+
* consolidation path re-chunks). Per store instance; readable via stats().reassembly. */
|
|
478
|
+
reassemblyCount = 0;
|
|
479
|
+
constructor(databasePath, limitsPath = defaultLimitsPathFor(databasePath)) {
|
|
480
|
+
this.path = databasePath;
|
|
481
|
+
this.limits = resolveMemoryLimits(limitsPath);
|
|
482
|
+
if (databasePath !== ":memory:")
|
|
483
|
+
mkdirSync(dirname(databasePath), { recursive: true });
|
|
484
|
+
this.db = new DatabaseSync(databasePath);
|
|
485
|
+
this.db.exec("PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL;");
|
|
486
|
+
this.db.exec(`
|
|
487
|
+
CREATE TABLE IF NOT EXISTS memories (
|
|
488
|
+
rowid INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
489
|
+
id TEXT NOT NULL UNIQUE,
|
|
490
|
+
kind TEXT NOT NULL DEFAULT 'project-state',
|
|
491
|
+
scope TEXT NOT NULL CHECK (scope IN ('global', 'project')),
|
|
492
|
+
project TEXT,
|
|
493
|
+
project_key TEXT NOT NULL,
|
|
494
|
+
content TEXT NOT NULL,
|
|
495
|
+
content_hash TEXT NOT NULL,
|
|
496
|
+
tags TEXT NOT NULL DEFAULT '[]',
|
|
497
|
+
importance INTEGER NOT NULL DEFAULT 5 CHECK (importance BETWEEN 0 AND 10),
|
|
498
|
+
version INTEGER NOT NULL DEFAULT 1,
|
|
499
|
+
state TEXT NOT NULL DEFAULT 'ACTIVE',
|
|
500
|
+
expires_at INTEGER,
|
|
501
|
+
supersedes TEXT,
|
|
502
|
+
provenance TEXT NOT NULL DEFAULT '[]',
|
|
503
|
+
memory_group_id TEXT,
|
|
504
|
+
part INTEGER,
|
|
505
|
+
parts INTEGER,
|
|
506
|
+
created_at INTEGER NOT NULL,
|
|
507
|
+
updated_at INTEGER NOT NULL
|
|
508
|
+
);
|
|
509
|
+
CREATE UNIQUE INDEX IF NOT EXISTS memories_scope_content ON memories(scope, project_key, content_hash);
|
|
510
|
+
CREATE INDEX IF NOT EXISTS memories_scope_updated ON memories(scope, project_key, updated_at DESC);
|
|
511
|
+
CREATE TABLE IF NOT EXISTS memory_mutations (
|
|
512
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
513
|
+
memory_id TEXT NOT NULL,
|
|
514
|
+
idempotency_key TEXT NOT NULL UNIQUE,
|
|
515
|
+
actor TEXT NOT NULL,
|
|
516
|
+
reason TEXT,
|
|
517
|
+
transition TEXT NOT NULL,
|
|
518
|
+
prev_version INTEGER,
|
|
519
|
+
new_version INTEGER,
|
|
520
|
+
policy_version TEXT,
|
|
521
|
+
created_at INTEGER NOT NULL,
|
|
522
|
+
details_json TEXT NOT NULL DEFAULT '{}'
|
|
523
|
+
);
|
|
524
|
+
CREATE INDEX IF NOT EXISTS memory_mutations_memory ON memory_mutations(memory_id, id DESC);
|
|
525
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(content, tokenize = 'unicode61 remove_diacritics 2');
|
|
526
|
+
CREATE TABLE IF NOT EXISTS store_meta (
|
|
527
|
+
key TEXT PRIMARY KEY,
|
|
528
|
+
value TEXT NOT NULL
|
|
529
|
+
);
|
|
530
|
+
`);
|
|
531
|
+
// Governance columns are bolted on exactly the way `kind` was: an additive ALTER TABLE with a
|
|
532
|
+
// constant default, so an existing database backfills in place and re-running is a no-op.
|
|
533
|
+
const columns = new Set(this.db.prepare("PRAGMA table_info(memories)").all().map((column) => rowString(column, "name")));
|
|
534
|
+
if (!columns.has("kind"))
|
|
535
|
+
this.db.exec("ALTER TABLE memories ADD COLUMN kind TEXT NOT NULL DEFAULT 'project-state'");
|
|
536
|
+
if (!columns.has("version"))
|
|
537
|
+
this.db.exec("ALTER TABLE memories ADD COLUMN version INTEGER NOT NULL DEFAULT 1");
|
|
538
|
+
if (!columns.has("state"))
|
|
539
|
+
this.db.exec("ALTER TABLE memories ADD COLUMN state TEXT NOT NULL DEFAULT 'ACTIVE'");
|
|
540
|
+
if (!columns.has("expires_at"))
|
|
541
|
+
this.db.exec("ALTER TABLE memories ADD COLUMN expires_at INTEGER");
|
|
542
|
+
if (!columns.has("supersedes"))
|
|
543
|
+
this.db.exec("ALTER TABLE memories ADD COLUMN supersedes TEXT");
|
|
544
|
+
if (!columns.has("provenance"))
|
|
545
|
+
this.db.exec("ALTER TABLE memories ADD COLUMN provenance TEXT NOT NULL DEFAULT '[]'");
|
|
546
|
+
// Size-aware write policy: group columns are additive with NULL/absent defaults, so an old
|
|
547
|
+
// row (or a whole old database) backfills as an ordinary unchunked memory and keeps loading.
|
|
548
|
+
if (!columns.has("memory_group_id"))
|
|
549
|
+
this.db.exec("ALTER TABLE memories ADD COLUMN memory_group_id TEXT");
|
|
550
|
+
if (!columns.has("part"))
|
|
551
|
+
this.db.exec("ALTER TABLE memories ADD COLUMN part INTEGER");
|
|
552
|
+
if (!columns.has("parts"))
|
|
553
|
+
this.db.exec("ALTER TABLE memories ADD COLUMN parts INTEGER");
|
|
554
|
+
this.db.exec("CREATE INDEX IF NOT EXISTS memories_group ON memories(memory_group_id, part ASC)");
|
|
555
|
+
try {
|
|
556
|
+
this.validateStoreSchemaVersion();
|
|
557
|
+
}
|
|
558
|
+
catch (error) {
|
|
559
|
+
// A refused open must not leak the connection it opened while discovering the mismatch.
|
|
560
|
+
this.db.close();
|
|
561
|
+
throw error;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
/**
|
|
565
|
+
* The DB-level schema axis (STORE_SCHEMA_VERSION, a store_meta row). A fresh or pre-axis database
|
|
566
|
+
* gets stamped; a database stamped by a different build refuses to open rather than misreading
|
|
567
|
+
* rows written under a schema it does not know. The additive CREATE/ALTER migration above always
|
|
568
|
+
* runs BEFORE this check, so a future version bump stamps only after its migrations have succeeded.
|
|
569
|
+
*/
|
|
570
|
+
validateStoreSchemaVersion() {
|
|
571
|
+
const row = this.db.prepare("SELECT value FROM store_meta WHERE key = 'store_schema_version'").get();
|
|
572
|
+
if (row === undefined) {
|
|
573
|
+
this.db.prepare("INSERT INTO store_meta (key, value) VALUES ('store_schema_version', ?)").run(STORE_SCHEMA_VERSION);
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
let version = rowString(row, "value");
|
|
577
|
+
if (version !== STORE_SCHEMA_VERSION) {
|
|
578
|
+
// Walk the forward-migration ladder: each hop must be a declared additive
|
|
579
|
+
// MINOR whose DDL ensureSchema has already applied (idempotently, above).
|
|
580
|
+
// The migration proper is stamping the meta row to this build's version.
|
|
581
|
+
const walked = new Set([version]);
|
|
582
|
+
while (version !== STORE_SCHEMA_VERSION) {
|
|
583
|
+
const next = SCHEMA_MIGRATIONS.get(version);
|
|
584
|
+
if (next === undefined || walked.has(next)) {
|
|
585
|
+
throw new Error(`store schema version mismatch: database is '${version}', this build expects '${STORE_SCHEMA_VERSION}', and no forward migration path exists; refusing to open`);
|
|
586
|
+
}
|
|
587
|
+
walked.add(next);
|
|
588
|
+
version = next;
|
|
589
|
+
}
|
|
590
|
+
this.db.prepare("UPDATE store_meta SET value = ? WHERE key = 'store_schema_version'").run(STORE_SCHEMA_VERSION);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* Public and reentrant so a caller can make several store writes atomic — a governed mutation has
|
|
595
|
+
* to check a version, apply it, and append its ledger row or do none of them. SQLite has no nested
|
|
596
|
+
* BEGIN, so an inner call joins the outer transaction instead of starting one.
|
|
597
|
+
*/
|
|
598
|
+
transaction(fn) {
|
|
599
|
+
if (this.depth > 0) {
|
|
600
|
+
this.depth += 1;
|
|
601
|
+
try {
|
|
602
|
+
return fn();
|
|
603
|
+
}
|
|
604
|
+
finally {
|
|
605
|
+
this.depth -= 1;
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
609
|
+
this.depth = 1;
|
|
610
|
+
try {
|
|
611
|
+
const result = fn();
|
|
612
|
+
this.db.exec("COMMIT");
|
|
613
|
+
return result;
|
|
614
|
+
}
|
|
615
|
+
catch (error) {
|
|
616
|
+
try {
|
|
617
|
+
this.db.exec("ROLLBACK");
|
|
618
|
+
}
|
|
619
|
+
catch {
|
|
620
|
+
// Preserve the original failure.
|
|
621
|
+
}
|
|
622
|
+
throw error;
|
|
623
|
+
}
|
|
624
|
+
finally {
|
|
625
|
+
this.depth = 0;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
scopeWhere(alias, scope, project) {
|
|
629
|
+
const filter = validateFilter(scope);
|
|
630
|
+
if (filter === "global")
|
|
631
|
+
return { sql: `${alias}.scope = 'global'`, args: [] };
|
|
632
|
+
if (filter === "project")
|
|
633
|
+
return { sql: `${alias}.scope = 'project' AND ${alias}.project = ?`, args: [normalizeProject(text(project, "project"))] };
|
|
634
|
+
if (project !== undefined)
|
|
635
|
+
return { sql: `(${alias}.scope = 'global' OR (${alias}.scope = 'project' AND ${alias}.project = ?))`, args: [normalizeProject(text(project, "project"))] };
|
|
636
|
+
return { sql: "1 = 1", args: [] };
|
|
637
|
+
}
|
|
638
|
+
memoryFromRow(row) {
|
|
639
|
+
let tags = [];
|
|
640
|
+
try {
|
|
641
|
+
const parsed = JSON.parse(rowString(row, "tags"));
|
|
642
|
+
if (Array.isArray(parsed))
|
|
643
|
+
tags = parsed.filter((tag) => typeof tag === "string");
|
|
644
|
+
}
|
|
645
|
+
catch {
|
|
646
|
+
// Keep malformed legacy metadata harmless.
|
|
647
|
+
}
|
|
648
|
+
const kind = rowString(row, "kind");
|
|
649
|
+
const state = rowString(row, "state");
|
|
650
|
+
return {
|
|
651
|
+
id: rowString(row, "id"),
|
|
652
|
+
kind: MEMORY_KINDS.includes(kind) ? kind : MemoryKind.ProjectState,
|
|
653
|
+
content: rowString(row, "content"),
|
|
654
|
+
contentHash: rowString(row, "content_hash"),
|
|
655
|
+
scope: rowString(row, "scope"),
|
|
656
|
+
project: row.project === null || row.project === undefined ? null : rowString(row, "project") || null,
|
|
657
|
+
tags,
|
|
658
|
+
importance: rowNumber(row, "importance"),
|
|
659
|
+
state: MEMORY_STATES.includes(state) ? state : "ACTIVE",
|
|
660
|
+
version: rowNumber(row, "version") || 1,
|
|
661
|
+
provenance: parseProvenance(row.provenance),
|
|
662
|
+
expiresAt: row.expires_at === null || row.expires_at === undefined ? null : rowNumber(row, "expires_at"),
|
|
663
|
+
supersedes: row.supersedes === null || row.supersedes === undefined ? null : rowString(row, "supersedes") || null,
|
|
664
|
+
...groupFromRow(row),
|
|
665
|
+
createdAt: rowNumber(row, "created_at"),
|
|
666
|
+
updatedAt: rowNumber(row, "updated_at"),
|
|
667
|
+
...rankFromRow(row),
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
memoryRow(id) {
|
|
671
|
+
return this.db.prepare(`SELECT rowid, ${memoryColumns()} FROM memories WHERE id = ?`).get(text(id, "id"));
|
|
672
|
+
}
|
|
673
|
+
mutationFromRow(row) {
|
|
674
|
+
return {
|
|
675
|
+
id: rowNumber(row, "id"),
|
|
676
|
+
memoryId: rowString(row, "memory_id"),
|
|
677
|
+
idempotencyKey: rowString(row, "idempotency_key"),
|
|
678
|
+
actor: rowString(row, "actor"),
|
|
679
|
+
reason: row.reason === null || row.reason === undefined ? null : rowString(row, "reason"),
|
|
680
|
+
transition: rowString(row, "transition"),
|
|
681
|
+
prevVersion: row.prev_version === null || row.prev_version === undefined ? null : rowNumber(row, "prev_version"),
|
|
682
|
+
newVersion: row.new_version === null || row.new_version === undefined ? null : rowNumber(row, "new_version"),
|
|
683
|
+
policyVersion: row.policy_version === null || row.policy_version === undefined ? null : rowString(row, "policy_version"),
|
|
684
|
+
createdAt: rowNumber(row, "created_at"),
|
|
685
|
+
details: parseMetadata(row.details_json),
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
memoryUsage(scope, project) {
|
|
689
|
+
const validScope = validateScope(scope);
|
|
690
|
+
const normalizedProject = validateProject(project, validScope);
|
|
691
|
+
const rows = this.db.prepare("SELECT content FROM memories WHERE scope = ? AND project_key = ?").all(validScope, projectKey(normalizedProject));
|
|
692
|
+
const usedChars = rows.reduce((total, row) => total + rowString(row, "content").length, 0);
|
|
693
|
+
const limitChars = memoryLimit(this.limits, validScope);
|
|
694
|
+
return {
|
|
695
|
+
scope: validScope,
|
|
696
|
+
project: normalizedProject,
|
|
697
|
+
usedChars,
|
|
698
|
+
limitChars,
|
|
699
|
+
remainingChars: Math.max(0, limitChars - usedChars),
|
|
700
|
+
percentage: Math.round((usedChars / limitChars) * 100),
|
|
701
|
+
entries: rows.length,
|
|
702
|
+
needsConsolidation: usedChars / limitChars >= 0.8,
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
ensureCapacity(scope, project, chars, excludeId) {
|
|
706
|
+
const usage = this.memoryUsage(scope, project ?? undefined);
|
|
707
|
+
const rows = this.db.prepare("SELECT id, content FROM memories WHERE scope = ? AND project_key = ?").all(scope, projectKey(project)).filter((row) => rowString(row, "id") !== excludeId);
|
|
708
|
+
const usedChars = rows.reduce((total, row) => total + rowString(row, "content").length, 0);
|
|
709
|
+
if (usedChars + chars <= usage.limitChars)
|
|
710
|
+
return;
|
|
711
|
+
const currentEntries = rows.map((row) => `${rowString(row, "id")}: ${rowString(row, "content").slice(0, 240)}`).join(" | ");
|
|
712
|
+
throw new Error(`memory at ${usedChars}/${usage.limitChars} chars. Adding this entry (${chars} chars) would exceed the limit. Consolidate or remove entries before retrying. Current entries: ${currentEntries || "none"}`);
|
|
713
|
+
}
|
|
714
|
+
insertMemory(input, now, group = null) {
|
|
715
|
+
const kind = validateKind(input.kind ?? MemoryKind.ProjectState);
|
|
716
|
+
const scope = validateScope(input.scope ?? "project");
|
|
717
|
+
const project = validateProject(input.project, scope);
|
|
718
|
+
if (group !== null) {
|
|
719
|
+
// The size-aware write path has already validated, chunked, and capacity-checked; the decorated
|
|
720
|
+
// chunk still cannot exceed the per-record invariant, and this check enforces it here too.
|
|
721
|
+
if (group.content.length > MAX_MEMORY_CHARS)
|
|
722
|
+
throw new Error(`memory content exceeds ${MAX_MEMORY_CHARS} characters; consolidate or shorten it before retrying`);
|
|
723
|
+
const id = randomUUID();
|
|
724
|
+
const tags = tagsValue(input.tags);
|
|
725
|
+
const importance = importanceValue(input.importance);
|
|
726
|
+
const provenance = provenanceValue(input.provenance);
|
|
727
|
+
const hash = createHash("sha256").update(group.content, "utf8").digest("hex");
|
|
728
|
+
const result = this.db
|
|
729
|
+
.prepare("INSERT INTO memories (id, kind, scope, project, project_key, content, content_hash, tags, importance, provenance, memory_group_id, part, parts, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
|
|
730
|
+
.run(id, kind, scope, project, projectKey(project), group.content, hash, JSON.stringify(tags), importance, JSON.stringify(provenance), group.groupId, group.part, group.parts, now, now);
|
|
731
|
+
const rowid = Number(result.lastInsertRowid);
|
|
732
|
+
this.db.prepare("INSERT INTO memory_fts (rowid, content) VALUES (?, ?)").run(rowid, group.content);
|
|
733
|
+
return {
|
|
734
|
+
memory: {
|
|
735
|
+
id,
|
|
736
|
+
kind,
|
|
737
|
+
content: group.content,
|
|
738
|
+
contentHash: hash,
|
|
739
|
+
scope,
|
|
740
|
+
project,
|
|
741
|
+
tags,
|
|
742
|
+
importance,
|
|
743
|
+
state: "ACTIVE",
|
|
744
|
+
version: 1,
|
|
745
|
+
provenance,
|
|
746
|
+
expiresAt: null,
|
|
747
|
+
supersedes: null,
|
|
748
|
+
memoryGroupId: group.groupId,
|
|
749
|
+
part: group.part,
|
|
750
|
+
parts: group.parts,
|
|
751
|
+
chunked: true,
|
|
752
|
+
createdAt: now,
|
|
753
|
+
updatedAt: now,
|
|
754
|
+
},
|
|
755
|
+
duplicate: false,
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
const raw = text(input.content, "content");
|
|
759
|
+
const cleanContent = validateMemoryContent(raw);
|
|
760
|
+
const hash = createHash("sha256").update(cleanContent, "utf8").digest("hex");
|
|
761
|
+
const duplicateRow = this.db
|
|
762
|
+
.prepare(`SELECT rowid, ${memoryColumns()} FROM memories WHERE scope = ? AND project_key = ? AND content_hash = ?`)
|
|
763
|
+
.get(scope, projectKey(project), hash);
|
|
764
|
+
if (duplicateRow) {
|
|
765
|
+
const memory = this.memoryFromRow(duplicateRow);
|
|
766
|
+
memory.duplicate = true;
|
|
767
|
+
return { memory, duplicate: true };
|
|
768
|
+
}
|
|
769
|
+
this.ensureCapacity(scope, project, cleanContent.length);
|
|
770
|
+
const id = randomUUID();
|
|
771
|
+
const tags = tagsValue(input.tags);
|
|
772
|
+
const importance = importanceValue(input.importance);
|
|
773
|
+
const provenance = provenanceValue(input.provenance);
|
|
774
|
+
const result = this.db
|
|
775
|
+
.prepare("INSERT INTO memories (id, kind, scope, project, project_key, content, content_hash, tags, importance, provenance, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
|
|
776
|
+
.run(id, kind, scope, project, projectKey(project), cleanContent, hash, JSON.stringify(tags), importance, JSON.stringify(provenance), now, now);
|
|
777
|
+
const rowid = Number(result.lastInsertRowid);
|
|
778
|
+
this.db.prepare("INSERT INTO memory_fts (rowid, content) VALUES (?, ?)").run(rowid, cleanContent);
|
|
779
|
+
// Governance columns take their schema defaults: a new memory is always born ACTIVE at version 1.
|
|
780
|
+
return {
|
|
781
|
+
memory: {
|
|
782
|
+
id,
|
|
783
|
+
kind,
|
|
784
|
+
content: cleanContent,
|
|
785
|
+
contentHash: hash,
|
|
786
|
+
scope,
|
|
787
|
+
project,
|
|
788
|
+
tags,
|
|
789
|
+
importance,
|
|
790
|
+
state: "ACTIVE",
|
|
791
|
+
version: 1,
|
|
792
|
+
provenance,
|
|
793
|
+
expiresAt: null,
|
|
794
|
+
supersedes: null,
|
|
795
|
+
createdAt: now,
|
|
796
|
+
updatedAt: now,
|
|
797
|
+
},
|
|
798
|
+
duplicate: false,
|
|
799
|
+
};
|
|
800
|
+
}
|
|
801
|
+
/** The id of a chunked write whose parts this scope already holds in full, or undefined. */
|
|
802
|
+
existingGroupDuplicate(groupId, parts, scope, project) {
|
|
803
|
+
const rows = this.db
|
|
804
|
+
.prepare("SELECT id, part FROM memories WHERE memory_group_id = ? AND scope = ? AND project_key = ?")
|
|
805
|
+
.all(groupId, scope, projectKey(project));
|
|
806
|
+
if (rows.length !== parts)
|
|
807
|
+
return undefined;
|
|
808
|
+
const seen = new Set(rows.map((row) => rowNumber(row, "part")));
|
|
809
|
+
if (seen.size !== parts)
|
|
810
|
+
return undefined;
|
|
811
|
+
return rowString(rows[0], "id");
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* The size-aware write. Oversized content (> MAX_MEMORY_CHARS) is never truncated, never
|
|
815
|
+
* LLM-summarized, and never rejected: it is split by the deterministic boundary-aware chunker
|
|
816
|
+
* into parts that each satisfy the per-record invariant, tagged with the group id derived from
|
|
817
|
+
* the full original content, and written in one transaction so a group is all-or-nothing.
|
|
818
|
+
*/
|
|
819
|
+
rememberWithStatus(input) {
|
|
820
|
+
const kind = validateKind(input.kind ?? MemoryKind.ProjectState);
|
|
821
|
+
const scope = validateScope(input.scope ?? "project");
|
|
822
|
+
const project = validateProject(input.project, scope);
|
|
823
|
+
// Safety and redaction run on the FULL content before chunking, so a threat pattern or a
|
|
824
|
+
// credential split across a boundary is still caught, and every chunk is equally clean.
|
|
825
|
+
const cleanContent = validateMemorySafety(text(input.content, "content"));
|
|
826
|
+
const tags = tagsValue(input.tags);
|
|
827
|
+
const status = {
|
|
828
|
+
contentLength: cleanContent.length,
|
|
829
|
+
contentLimit: MAX_MEMORY_CHARS,
|
|
830
|
+
contentRemaining: Math.max(0, MAX_MEMORY_CHARS - cleanContent.length),
|
|
831
|
+
nearLimit: cleanContent.length >= MAX_MEMORY_CHARS - NEAR_MEMORY_LIMIT_CHARS,
|
|
832
|
+
chunked: false,
|
|
833
|
+
};
|
|
834
|
+
if (cleanContent.length <= MAX_MEMORY_CHARS) {
|
|
835
|
+
return this.transaction(() => {
|
|
836
|
+
const inserted = this.insertMemory({ ...input, content: cleanContent, kind, scope, project: project ?? undefined, tags }, Date.now());
|
|
837
|
+
return { memories: [inserted.memory], status };
|
|
838
|
+
});
|
|
839
|
+
}
|
|
840
|
+
const groupId = memoryGroupId(cleanContent, kind, tags);
|
|
841
|
+
const chunks = chunkContent(cleanContent);
|
|
842
|
+
const parts = chunks.length;
|
|
843
|
+
if (parts < 2)
|
|
844
|
+
throw new Error("chunked write produced fewer than two parts");
|
|
845
|
+
status.chunked = true;
|
|
846
|
+
status.memoryGroupId = groupId;
|
|
847
|
+
status.parts = parts;
|
|
848
|
+
return this.transaction(() => {
|
|
849
|
+
// Idempotency for a chunked write: the same full content in the same scope lands as the
|
|
850
|
+
// same group, and a second submission finds every part already present.
|
|
851
|
+
const existing = this.existingGroupDuplicate(groupId, parts, scope, project);
|
|
852
|
+
if (existing !== undefined) {
|
|
853
|
+
// Scope-keyed duplicate population (G8 Nytheria impl-gate B1): memoryGroupId is
|
|
854
|
+
// scope-blind, so listMemoriesByGroup(groupId) returns the UNION of every scope's
|
|
855
|
+
// rows sharing the id. The duplicate return must carry only THIS write's
|
|
856
|
+
// scope/project rows — and memory[0] must be the requested scope's part 1, never
|
|
857
|
+
// a foreign-scope row a caller would stamp into promoted_to.
|
|
858
|
+
const memories = this.listMemoriesByGroup(groupId, scope, project);
|
|
859
|
+
for (const memory of memories)
|
|
860
|
+
memory.duplicate = true;
|
|
861
|
+
return { memories, status };
|
|
862
|
+
}
|
|
863
|
+
// One capacity check for the whole group: the parts are written in this same transaction,
|
|
864
|
+
// so checking the first against a corpus that still lacks the rest would be a fiction.
|
|
865
|
+
// A group that lost a part (one forgotten) is restored: only the missing parts are written, the held ones stay.
|
|
866
|
+
const held = new Set(this.db.prepare("SELECT part FROM memories WHERE memory_group_id = ? AND scope = ? AND project_key = ?").all(groupId, scope, projectKey(project)).map((row) => rowNumber(row, "part")));
|
|
867
|
+
const missing = chunks.filter((chunk) => !held.has(chunk.part));
|
|
868
|
+
this.ensureCapacity(scope, project, missing.reduce((sum, chunk) => sum + decorateChunk(chunk, groupId).length, 0));
|
|
869
|
+
const inserted = missing.map((chunk, index) => this.insertMemory({ ...input, content: chunk.content, kind, scope, project: project ?? undefined, tags }, Date.now() + index, { groupId, part: chunk.part, parts, content: decorateChunk(chunk, groupId) }));
|
|
870
|
+
if (held.size === 0)
|
|
871
|
+
return { memories: inserted.map((each) => each.memory), status };
|
|
872
|
+
const memories = this.listMemoriesByGroup(groupId, scope, project);
|
|
873
|
+
// The parts that were already held are duplicates. Only the restored ones are new.
|
|
874
|
+
for (const memory of memories)
|
|
875
|
+
if (held.has(memory.part ?? 0))
|
|
876
|
+
memory.duplicate = true;
|
|
877
|
+
return { memories, status };
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
/**
|
|
881
|
+
* The parts of a chunk group in part order, every state included. The group id ignores scope, so pass
|
|
882
|
+
* the scope (and project) to read one scope's copy. Without a scope it is the union of every copy.
|
|
883
|
+
*/
|
|
884
|
+
listMemoriesByGroup(groupId, scope, project) {
|
|
885
|
+
if (!MEMORY_GROUP_ID_RE.test(text(groupId, "groupId")))
|
|
886
|
+
throw new Error("groupId must be a memory group id (grp-<sha256>)");
|
|
887
|
+
const rows = scope === undefined
|
|
888
|
+
? this.db.prepare(`SELECT ${memoryColumns()} FROM memories WHERE memory_group_id = ? ORDER BY part ASC`).all(groupId)
|
|
889
|
+
: this.db.prepare(`SELECT ${memoryColumns()} FROM memories WHERE memory_group_id = ? AND scope = ? AND project_key = ? ORDER BY part ASC`).all(groupId, scope, projectKey(project));
|
|
890
|
+
return rows.map((row) => this.memoryFromRow(row));
|
|
891
|
+
}
|
|
892
|
+
/** The reassembled original content of a group, plus its parts in order; a group with a missing part still reads. */
|
|
893
|
+
getMemoryGroup(groupId, scope, project) {
|
|
894
|
+
const parts = this.listMemoriesByGroup(groupId, scope, project);
|
|
895
|
+
if (parts.length === 0)
|
|
896
|
+
return undefined;
|
|
897
|
+
this.reassemblyCount += 1;
|
|
898
|
+
return { content: reassembleGroup(parts), parts };
|
|
899
|
+
}
|
|
900
|
+
// -------------------------------------------------------------------------------------------
|
|
901
|
+
// G7/PROG1 (§18.1 memory-plane scope): group-aware L0/L1 projections sharing one
|
|
902
|
+
// boundary-map mechanism; a single-row memory is a degenerate group. Accept any part id of the group;
|
|
903
|
+
// getMemoryGroup remains memory L2, untouched.
|
|
904
|
+
// -------------------------------------------------------------------------------------------
|
|
905
|
+
/** Memory L0: group metadata + the first ≤ 256 chars of the group's RAW space. */
|
|
906
|
+
memoryL0(id) {
|
|
907
|
+
const row = this.memoryRow(text(id, "id"));
|
|
908
|
+
if (!row)
|
|
909
|
+
return undefined;
|
|
910
|
+
return this.memoryDisclosureRow(this.memoryFromRow(row), "L0");
|
|
911
|
+
}
|
|
912
|
+
/** Memory L1: + head ≤ 2,048 / tail ≤ 512 chars of the group's RAW space. */
|
|
913
|
+
memoryL1(id) {
|
|
914
|
+
const row = this.memoryRow(text(id, "id"));
|
|
915
|
+
if (!row)
|
|
916
|
+
return undefined;
|
|
917
|
+
return this.memoryDisclosureRow(this.memoryFromRow(row), "L1");
|
|
918
|
+
}
|
|
919
|
+
remember(input) {
|
|
920
|
+
return this.rememberWithStatus(input).memories[0];
|
|
921
|
+
}
|
|
922
|
+
record(input) {
|
|
923
|
+
return this.remember(input);
|
|
924
|
+
}
|
|
925
|
+
getMemory(id) {
|
|
926
|
+
const row = this.memoryRow(id);
|
|
927
|
+
return row ? this.memoryFromRow(row) : undefined;
|
|
928
|
+
}
|
|
929
|
+
listMemories(options = {}) {
|
|
930
|
+
const where = this.scopeWhere("m", options.scope, options.project);
|
|
931
|
+
const limit = limitValue(options.limit);
|
|
932
|
+
// m.id ASC final tie-break: equal (importance, updated_at) rows — e.g. bursts written in the
|
|
933
|
+
// same millisecond — otherwise order by rowid (insertion scan), which is not guaranteed stable
|
|
934
|
+
// across VACUUM or query-plan changes, and the injected memory snapshot must render byte-stable.
|
|
935
|
+
const order = options.order === "importance" ? "m.importance DESC, m.updated_at DESC, m.id ASC" : "m.updated_at DESC, m.id ASC";
|
|
936
|
+
return this.db
|
|
937
|
+
.prepare(`SELECT ${memoryColumns("m")} FROM memories m WHERE ${where.sql} AND ${stateWhere("m", options.includeAllStates)} ORDER BY ${order} LIMIT ?`)
|
|
938
|
+
.all(...where.args, limit)
|
|
939
|
+
.map((row) => this.memoryFromRow(row));
|
|
940
|
+
}
|
|
941
|
+
/** The vault export view: every state, because the Markdown files are the record of record. */
|
|
942
|
+
allMemories() {
|
|
943
|
+
return this.db.prepare(`SELECT ${memoryColumns()} FROM memories ORDER BY updated_at DESC`).all().map((row) => this.memoryFromRow(row));
|
|
944
|
+
}
|
|
945
|
+
updateMemory(id, patch) {
|
|
946
|
+
const memoryId = text(id, "id");
|
|
947
|
+
const changes = typeof patch === "string" ? { content: patch } : patch;
|
|
948
|
+
if (!changes || typeof changes !== "object")
|
|
949
|
+
throw new Error("update must be an object or content string");
|
|
950
|
+
return this.transaction(() => {
|
|
951
|
+
const oldRow = this.memoryRow(memoryId);
|
|
952
|
+
if (!oldRow)
|
|
953
|
+
throw new Error(`memory not found: ${memoryId}`);
|
|
954
|
+
const old = this.memoryFromRow(oldRow);
|
|
955
|
+
const kind = validateKind(changes.kind ?? old.kind);
|
|
956
|
+
const scope = validateScope(changes.scope ?? old.scope);
|
|
957
|
+
const project = validateProject(changes.project === undefined ? old.project ?? undefined : changes.project, scope);
|
|
958
|
+
const content = changes.content === undefined ? old.content : text(changes.content, "content");
|
|
959
|
+
const cleanContent = validateMemoryContent(content);
|
|
960
|
+
const hash = createHash("sha256").update(cleanContent, "utf8").digest("hex");
|
|
961
|
+
const duplicate = this.db
|
|
962
|
+
.prepare("SELECT id FROM memories WHERE scope = ? AND project_key = ? AND content_hash = ? AND id <> ?")
|
|
963
|
+
.get(scope, projectKey(project), hash, memoryId);
|
|
964
|
+
if (duplicate)
|
|
965
|
+
throw new Error("duplicate memory content in this scope");
|
|
966
|
+
this.ensureCapacity(scope, project, cleanContent.length, memoryId);
|
|
967
|
+
const tags = changes.tags === undefined ? old.tags : tagsValue(changes.tags);
|
|
968
|
+
const importance = changes.importance === undefined ? old.importance : importanceValue(changes.importance);
|
|
969
|
+
// A content edit leaves governance alone; only a caller that passes a governance key changes
|
|
970
|
+
// it, and the lifecycle transition behind that key is validated before we are called.
|
|
971
|
+
const state = changes.state === undefined ? old.state : validateState(changes.state);
|
|
972
|
+
const version = changes.version === undefined ? old.version : versionValue(changes.version);
|
|
973
|
+
const expiresAt = changes.expiresAt === undefined ? old.expiresAt : expiresAtValue(changes.expiresAt);
|
|
974
|
+
const supersedes = changes.supersedes === undefined ? old.supersedes : supersedesValue(changes.supersedes);
|
|
975
|
+
const provenance = changes.provenance === undefined ? old.provenance : provenanceValue(changes.provenance);
|
|
976
|
+
const now = Date.now();
|
|
977
|
+
const rowid = rowNumber(oldRow, "rowid");
|
|
978
|
+
this.db.prepare("UPDATE memories SET kind = ?, scope = ?, project = ?, project_key = ?, content = ?, content_hash = ?, tags = ?, importance = ?, state = ?, version = ?, expires_at = ?, supersedes = ?, provenance = ?, updated_at = ? WHERE id = ?").run(kind, scope, project, projectKey(project), cleanContent, hash, JSON.stringify(tags), importance, state, version, expiresAt, supersedes, JSON.stringify(provenance), now, memoryId);
|
|
979
|
+
this.db.prepare("DELETE FROM memory_fts WHERE rowid = ?").run(rowid);
|
|
980
|
+
this.db.prepare("INSERT INTO memory_fts (rowid, content) VALUES (?, ?)").run(rowid, cleanContent);
|
|
981
|
+
return { id: memoryId, kind, content: cleanContent, contentHash: hash, scope, project, tags, importance, state, version, provenance, expiresAt, supersedes, createdAt: old.createdAt, updatedAt: now };
|
|
982
|
+
});
|
|
983
|
+
}
|
|
984
|
+
forgetMemory(id) {
|
|
985
|
+
const memoryId = text(id, "id");
|
|
986
|
+
return this.transaction(() => {
|
|
987
|
+
const row = this.memoryRow(memoryId);
|
|
988
|
+
if (!row)
|
|
989
|
+
return false;
|
|
990
|
+
this.db.prepare("DELETE FROM memory_fts WHERE rowid = ?").run(rowNumber(row, "rowid"));
|
|
991
|
+
this.db.prepare("DELETE FROM memories WHERE id = ?").run(memoryId);
|
|
992
|
+
return true;
|
|
993
|
+
});
|
|
994
|
+
}
|
|
995
|
+
forget(id) {
|
|
996
|
+
return this.forgetMemory(id);
|
|
997
|
+
}
|
|
998
|
+
consolidate(input, content, options = {}) {
|
|
999
|
+
const request = Array.isArray(input) ? { ...options, ids: input, content } : input;
|
|
1000
|
+
if (!request || !Array.isArray(request.ids) || request.ids.length < 2 || request.ids.some((id) => typeof id !== "string" || !id.trim()))
|
|
1001
|
+
throw new Error("consolidate requires at least two memory ids");
|
|
1002
|
+
return this.transaction(() => {
|
|
1003
|
+
const ids = [...new Set(request.ids.map((id) => id.trim()))];
|
|
1004
|
+
const memories = ids.map((id) => {
|
|
1005
|
+
const row = this.memoryRow(id);
|
|
1006
|
+
if (!row)
|
|
1007
|
+
throw new Error(`memory not found: ${id}`);
|
|
1008
|
+
return this.memoryFromRow(row);
|
|
1009
|
+
});
|
|
1010
|
+
const first = memories[0];
|
|
1011
|
+
const kind = validateKind(request.kind ?? first.kind);
|
|
1012
|
+
const scope = validateScope(request.scope ?? first.scope);
|
|
1013
|
+
const project = validateProject(request.project === undefined ? first.project ?? undefined : request.project, scope);
|
|
1014
|
+
if (memories.some((memory) => memory.scope !== scope || projectKey(memory.project) !== projectKey(project)))
|
|
1015
|
+
throw new Error("memories must share scope and project");
|
|
1016
|
+
const mergedContent = request.content === undefined ? memories.map((memory) => memory.content).join("\n") : text(request.content, "content");
|
|
1017
|
+
for (const memory of memories) {
|
|
1018
|
+
const row = this.memoryRow(memory.id);
|
|
1019
|
+
if (row) {
|
|
1020
|
+
this.db.prepare("DELETE FROM memory_fts WHERE rowid = ?").run(rowNumber(row, "rowid"));
|
|
1021
|
+
this.db.prepare("DELETE FROM memories WHERE id = ?").run(memory.id);
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
const inserted = this.insertMemory({ content: mergedContent, kind, scope, project: project ?? undefined, tags: request.tags ?? [...new Set(memories.flatMap((memory) => memory.tags))], importance: request.importance ?? Math.max(...memories.map((memory) => memory.importance)) }, Date.now());
|
|
1025
|
+
return { memory: inserted.memory, removedIds: ids };
|
|
1026
|
+
});
|
|
1027
|
+
}
|
|
1028
|
+
/** Append-only lifecycle log. Rows are only ever inserted; there is no update or delete path. */
|
|
1029
|
+
recordMutation(input) {
|
|
1030
|
+
const memoryId = text(input.memoryId, "memoryId");
|
|
1031
|
+
const idempotencyKey = text(input.idempotencyKey, "idempotencyKey");
|
|
1032
|
+
const actor = redactSensitive(text(input.actor, "actor"));
|
|
1033
|
+
const fromState = validateState(input.fromState);
|
|
1034
|
+
// A patch that edits content or evidence without moving the record still needs an audit row, so a
|
|
1035
|
+
// state-preserving mutation records `X->X` rather than being asserted as a transition. Terminal
|
|
1036
|
+
// states stay closed to every mutation, which is what made the self-edge invalid in the first place.
|
|
1037
|
+
const toState = validateState(input.toState);
|
|
1038
|
+
if (toState !== fromState)
|
|
1039
|
+
assertMemoryTransition(fromState, toState);
|
|
1040
|
+
else if (MEMORY_STATE_TRANSITIONS[fromState].length === 0)
|
|
1041
|
+
throw new Error(`invalid memory mutation on ${fromState}: ${fromState} is terminal`);
|
|
1042
|
+
const transition = `${fromState}->${toState}`;
|
|
1043
|
+
const reason = input.reason === undefined || input.reason === null ? null : redactSensitive(text(input.reason, "reason"));
|
|
1044
|
+
const prevVersion = input.prevVersion === undefined || input.prevVersion === null ? null : versionValue(input.prevVersion, "prevVersion");
|
|
1045
|
+
const newVersion = input.newVersion === undefined || input.newVersion === null ? null : versionValue(input.newVersion, "newVersion");
|
|
1046
|
+
const policyVersion = input.policyVersion === undefined || input.policyVersion === null ? null : redactSensitive(text(input.policyVersion, "policyVersion"));
|
|
1047
|
+
let details = "{}";
|
|
1048
|
+
if (input.details !== undefined) {
|
|
1049
|
+
try {
|
|
1050
|
+
details = JSON.stringify(redactJsonValue(input.details));
|
|
1051
|
+
}
|
|
1052
|
+
catch {
|
|
1053
|
+
throw new Error("details must be JSON-serializable");
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
const createdAt = input.timestamp === undefined ? Date.now() : input.timestamp;
|
|
1057
|
+
if (!Number.isFinite(createdAt))
|
|
1058
|
+
throw new Error("timestamp must be finite");
|
|
1059
|
+
return this.transaction(() => {
|
|
1060
|
+
const existing = this.db.prepare(`SELECT ${MUTATION_COLUMNS} FROM memory_mutations WHERE idempotency_key = ?`).get(idempotencyKey);
|
|
1061
|
+
if (existing) {
|
|
1062
|
+
const record = this.mutationFromRow(existing);
|
|
1063
|
+
record.duplicate = true;
|
|
1064
|
+
return record;
|
|
1065
|
+
}
|
|
1066
|
+
const result = this.db
|
|
1067
|
+
.prepare("INSERT INTO memory_mutations (memory_id, idempotency_key, actor, reason, transition, prev_version, new_version, policy_version, created_at, details_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
|
|
1068
|
+
.run(memoryId, idempotencyKey, actor, reason, transition, prevVersion, newVersion, policyVersion, createdAt, details);
|
|
1069
|
+
return { id: Number(result.lastInsertRowid), memoryId, idempotencyKey, actor, reason, transition, prevVersion, newVersion, policyVersion, createdAt, details: input.details ?? {} };
|
|
1070
|
+
});
|
|
1071
|
+
}
|
|
1072
|
+
/** The idempotency lookup a replaying caller needs before it decides whether to write at all. */
|
|
1073
|
+
getMutation(idempotencyKey) {
|
|
1074
|
+
const row = this.db.prepare(`SELECT ${MUTATION_COLUMNS} FROM memory_mutations WHERE idempotency_key = ?`).get(text(idempotencyKey, "idempotencyKey"));
|
|
1075
|
+
return row ? this.mutationFromRow(row) : undefined;
|
|
1076
|
+
}
|
|
1077
|
+
listMutations(memoryId, limit) {
|
|
1078
|
+
const bounded = limitValue(limit, 50);
|
|
1079
|
+
const rows = memoryId === undefined
|
|
1080
|
+
? this.db.prepare(`SELECT ${MUTATION_COLUMNS} FROM memory_mutations ORDER BY id DESC LIMIT ?`).all(bounded)
|
|
1081
|
+
: this.db.prepare(`SELECT ${MUTATION_COLUMNS} FROM memory_mutations WHERE memory_id = ? ORDER BY id DESC LIMIT ?`).all(text(memoryId, "memoryId"), bounded);
|
|
1082
|
+
return rows.map((row) => this.mutationFromRow(row));
|
|
1083
|
+
}
|
|
1084
|
+
// -------------------------------------------------------------------------------------------
|
|
1085
|
+
// G7/PROG1 (§18) store-private projection machinery: the RAW-space boundary map, projection
|
|
1086
|
+
// builders, the shared group-dedupe helper, and the single-record disclosure APIs.
|
|
1087
|
+
// -------------------------------------------------------------------------------------------
|
|
1088
|
+
/**
|
|
1089
|
+
* §18.3 boundary map (frozen mechanism): ONE ordered scan —
|
|
1090
|
+
* `WHERE (memory_group_id = ?) OR (memory_group_id IS NULL AND id = ?)` with `ORDER BY part ASC`
|
|
1091
|
+
* — over the table the id belongs to. A NULL-group row is its own logical group (the
|
|
1092
|
+
* groupless-row rule), so the map for a groupless id holds exactly that row. Each part's RAW
|
|
1093
|
+
* content is stripped via rawChunkContent (the exact inverse of decorateChunk) and its raw
|
|
1094
|
+
* length computed IN JS from `.length` (the code-point ruling: never SQL LENGTH). Entries
|
|
1095
|
+
* carry the raw slices themselves, so every window read below re-slices them with no second read.
|
|
1096
|
+
*/
|
|
1097
|
+
groupBoundaryMap(table, id) {
|
|
1098
|
+
// Two-step resolution, not a NULL-bind: `memory_group_id = NULL` is never true under SQL
|
|
1099
|
+
// NULL semantics, so the group id is resolved from the row first, and a groupless row falls
|
|
1100
|
+
// back to its own id (the §18.3 groupless-row rule — the row IS its own logical group).
|
|
1101
|
+
// The group id ignores scope, so the group is also pinned to this row's scope and project.
|
|
1102
|
+
const row = this.db.prepare(`SELECT memory_group_id, scope, project_key FROM ${table} WHERE id = ?`).get(id);
|
|
1103
|
+
if (row === undefined)
|
|
1104
|
+
return [];
|
|
1105
|
+
const groupId = row.memory_group_id === null || row.memory_group_id === undefined || !row.memory_group_id ? null : String(row.memory_group_id);
|
|
1106
|
+
const rows = (groupId === null
|
|
1107
|
+
? this.db.prepare(`SELECT id, part, parts, memory_group_id, content FROM ${table} WHERE memory_group_id IS NULL AND id = ? ORDER BY part ASC`).all(id)
|
|
1108
|
+
: this.db.prepare(`SELECT id, part, parts, memory_group_id, content FROM ${table} WHERE memory_group_id = ? AND scope = ? AND project_key = ? ORDER BY part ASC`).all(groupId, String(row.scope), String(row.project_key)));
|
|
1109
|
+
let cursor = 0;
|
|
1110
|
+
return rows.map((row) => {
|
|
1111
|
+
const raw = rawChunkContent({
|
|
1112
|
+
content: rowString(row, "content"),
|
|
1113
|
+
part: row.part === null || row.part === undefined ? null : rowNumber(row, "part"),
|
|
1114
|
+
parts: row.parts === null || row.parts === undefined ? null : rowNumber(row, "parts"),
|
|
1115
|
+
memoryGroupId: row.memory_group_id === null || row.memory_group_id === undefined || !row.memory_group_id ? null : rowString(row, "memory_group_id"),
|
|
1116
|
+
});
|
|
1117
|
+
const entry = { id: rowString(row, "id"), raw, rawLength: raw.length, start: cursor, end: cursor + raw.length };
|
|
1118
|
+
cursor = entry.end;
|
|
1119
|
+
return entry;
|
|
1120
|
+
});
|
|
1121
|
+
}
|
|
1122
|
+
/** Apply the L0/L1 projection to one memory row over its group's RAW space (§18.1 scope decision). */
|
|
1123
|
+
memoryDisclosureRow(row, level) {
|
|
1124
|
+
const map = this.groupBoundaryMap("memories", row.id);
|
|
1125
|
+
const fullLength = map.reduce((total, entry) => total + entry.rawLength, 0);
|
|
1126
|
+
const headLimit = level === "L0" ? DISCLOSURE_HEAD_CHARS : DISCLOSURE_L1_HEAD_CHARS;
|
|
1127
|
+
const tailLimit = level === "L0" ? 0 : DISCLOSURE_L1_TAIL_CHARS;
|
|
1128
|
+
let content;
|
|
1129
|
+
if (fullLength <= headLimit + tailLimit) {
|
|
1130
|
+
content = rawWindow(map, 0, fullLength);
|
|
1131
|
+
}
|
|
1132
|
+
else if (level === "L0") {
|
|
1133
|
+
content = rawWindow(map, 0, headLimit);
|
|
1134
|
+
}
|
|
1135
|
+
else {
|
|
1136
|
+
content = `${rawWindow(map, 0, headLimit)}\n…\n${rawWindow(map, fullLength - tailLimit, tailLimit)}`;
|
|
1137
|
+
}
|
|
1138
|
+
return { ...row, content, disclosureLevel: level, contentOffset: 0, contentLimit: headLimit, fullLength, reassembled: false, partCount: map.length, firstPartId: map.length > 0 ? map[0].id : row.id };
|
|
1139
|
+
}
|
|
1140
|
+
// -------------------------------------------------------------------------------------------
|
|
1141
|
+
// G7/PROG1 (§18.3): the single-record disclosure APIs. All accept ANY part id of the logical
|
|
1142
|
+
// record (the boundary map resolves the group); a vanished id returns undefined, exactly like
|
|
1143
|
+
// getMemoryGroup (§18.2 missing-id consistency — no throw anywhere).
|
|
1144
|
+
// -------------------------------------------------------------------------------------------
|
|
1145
|
+
/**
|
|
1146
|
+
* Full-text memory retrieval that keeps whole records, so a caller can see governance and provenance.
|
|
1147
|
+
*
|
|
1148
|
+
* The row also carries FTS5's own `bm25()` as `MemoryRecord.rank`. That is **additive**: the
|
|
1149
|
+
* ordering is unchanged (`importance DESC, updated_at DESC, id ASC` — bm25 does not order anything here),
|
|
1150
|
+
* every existing field is unchanged, and a caller that ignores `rank` sees exactly what it saw
|
|
1151
|
+
* before. The database already computes the number to satisfy the MATCH; discarding it was the
|
|
1152
|
+
* only thing this method used to do with it.
|
|
1153
|
+
*/
|
|
1154
|
+
searchMemories(options) {
|
|
1155
|
+
const match = toSafeMatchQuery(options.query);
|
|
1156
|
+
const limit = limitValue(options.limit);
|
|
1157
|
+
const where = this.scopeWhere("m", options.scope, options.project);
|
|
1158
|
+
return this.db
|
|
1159
|
+
.prepare(`SELECT ${memoryColumns("m")}, bm25(memory_fts) AS ${BM25_COLUMN_ALIAS} FROM memory_fts f JOIN memories m ON m.rowid = f.rowid WHERE memory_fts MATCH ? AND ${where.sql} AND ${stateWhere("m", options.includeAllStates)} ORDER BY m.importance DESC, m.updated_at DESC, m.id ASC LIMIT ?`)
|
|
1160
|
+
.all(match, ...where.args, limit)
|
|
1161
|
+
.map((row) => this.memoryFromRow(row));
|
|
1162
|
+
}
|
|
1163
|
+
search(queryOrOptions, options = {}) {
|
|
1164
|
+
const request = typeof queryOrOptions === "string" ? { ...options, query: queryOrOptions } : queryOrOptions;
|
|
1165
|
+
return this.searchMemories(request).map(memoryResult);
|
|
1166
|
+
}
|
|
1167
|
+
recent(options = {}) {
|
|
1168
|
+
return this.listMemories({ ...options, limit: limitValue(options.limit) }).map(memoryResult);
|
|
1169
|
+
}
|
|
1170
|
+
stats(project) {
|
|
1171
|
+
const count = (sql, ...args) => rowNumber(this.db.prepare(sql).get(...args) ?? {}, "count");
|
|
1172
|
+
const memoriesByKind = {};
|
|
1173
|
+
for (const row of this.db.prepare("SELECT kind, COUNT(*) AS count FROM memories GROUP BY kind ORDER BY count DESC, kind").all())
|
|
1174
|
+
memoriesByKind[rowString(row, "kind")] = rowNumber(row, "count");
|
|
1175
|
+
const projects = this.db.prepare("SELECT DISTINCT project FROM memories WHERE scope = 'project' AND project IS NOT NULL AND project <> '' ORDER BY project").all().map((row) => rowString(row, "project"));
|
|
1176
|
+
return {
|
|
1177
|
+
databasePath: this.path,
|
|
1178
|
+
memories: count("SELECT COUNT(*) AS count FROM memories"),
|
|
1179
|
+
globalMemories: count("SELECT COUNT(*) AS count FROM memories WHERE scope = 'global'"),
|
|
1180
|
+
projectMemories: count("SELECT COUNT(*) AS count FROM memories WHERE scope = 'project'"),
|
|
1181
|
+
memoriesByKind,
|
|
1182
|
+
memoryFtsRows: count("SELECT COUNT(*) AS count FROM memory_fts"),
|
|
1183
|
+
reassembly: this.reassemblyCount,
|
|
1184
|
+
memoryUsage: {
|
|
1185
|
+
global: this.memoryUsage("global"),
|
|
1186
|
+
...(project !== undefined ? { project: this.memoryUsage("project", project) } : {}),
|
|
1187
|
+
projects: projects.map((name) => this.memoryUsage("project", name)),
|
|
1188
|
+
},
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
get isOpen() {
|
|
1192
|
+
return this.db.isOpen;
|
|
1193
|
+
}
|
|
1194
|
+
getMeta(key) {
|
|
1195
|
+
const row = this.db.prepare("SELECT value FROM store_meta WHERE key = ?").get(key);
|
|
1196
|
+
return row === undefined ? undefined : rowString(row, "value");
|
|
1197
|
+
}
|
|
1198
|
+
/** An undefined value removes the key. */
|
|
1199
|
+
setMeta(key, value) {
|
|
1200
|
+
if (value === undefined)
|
|
1201
|
+
this.db.prepare("DELETE FROM store_meta WHERE key = ?").run(key);
|
|
1202
|
+
else
|
|
1203
|
+
this.db.prepare("INSERT INTO store_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(key, value);
|
|
1204
|
+
}
|
|
1205
|
+
/** Memories in `state`, newest first. The default listings skip every state except ACTIVE and DISPUTED. */
|
|
1206
|
+
listByState(state, limit = 100) {
|
|
1207
|
+
return this.db.prepare(`SELECT ${memoryColumns()} FROM memories WHERE state = ? ORDER BY updated_at DESC, id ASC LIMIT ?`).all(validateState(state), limit).map((row) => this.memoryFromRow(row));
|
|
1208
|
+
}
|
|
1209
|
+
countMemories() {
|
|
1210
|
+
return rowNumber(this.db.prepare("SELECT COUNT(*) AS count FROM memories").get() ?? {}, "count");
|
|
1211
|
+
}
|
|
1212
|
+
countState(state) {
|
|
1213
|
+
return rowNumber(this.db.prepare("SELECT COUNT(*) AS count FROM memories WHERE state = ?").get(validateState(state)) ?? {}, "count");
|
|
1214
|
+
}
|
|
1215
|
+
/**
|
|
1216
|
+
* Insert a record that came from a vault file (F2). Insert only: an id or a content already present is reported
|
|
1217
|
+
* and left alone. The row is PROPOSED at version 1 with importance at most 5, tagged source=vault-import, and the
|
|
1218
|
+
* file's governance keys are ignored. The content passes the same scanner as every other write.
|
|
1219
|
+
*/
|
|
1220
|
+
importMemory(record, now = Date.now()) {
|
|
1221
|
+
const content = validateMemoryContent(record.content);
|
|
1222
|
+
return this.transaction(() => {
|
|
1223
|
+
if (this.memoryRow(record.id))
|
|
1224
|
+
return { status: "exists", id: record.id };
|
|
1225
|
+
const kind = validateKind(record.kind);
|
|
1226
|
+
const scope = validateScope(record.scope);
|
|
1227
|
+
const project = validateProject(record.project, scope);
|
|
1228
|
+
const hash = createHash("sha256").update(content, "utf8").digest("hex");
|
|
1229
|
+
const same = this.db.prepare("SELECT id FROM memories WHERE scope = ? AND project_key = ? AND content_hash = ?").get(scope, projectKey(project), hash);
|
|
1230
|
+
if (same)
|
|
1231
|
+
return { status: "duplicate", id: rowString(same, "id") };
|
|
1232
|
+
this.ensureCapacity(scope, project, content.length);
|
|
1233
|
+
const tags = tagsValue([...record.tags.filter((tag) => tag !== IMPORT_TAG), IMPORT_TAG].slice(-20));
|
|
1234
|
+
const importance = Math.min(importanceValue(record.importance), 5);
|
|
1235
|
+
const provenance = provenanceValue([{ actor: "vault-import", at: now }]);
|
|
1236
|
+
const group = record.memoryGroupId ?? null;
|
|
1237
|
+
const result = this.db
|
|
1238
|
+
.prepare("INSERT INTO memories (id, kind, scope, project, project_key, content, content_hash, tags, importance, state, provenance, memory_group_id, part, parts, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'PROPOSED', ?, ?, ?, ?, ?, ?)")
|
|
1239
|
+
.run(record.id, kind, scope, project, projectKey(project), content, hash, JSON.stringify(tags), importance, JSON.stringify(provenance), group, group === null ? null : record.part ?? null, group === null ? null : record.parts ?? null, now, now);
|
|
1240
|
+
this.db.prepare("INSERT INTO memory_fts (rowid, content) VALUES (?, ?)").run(Number(result.lastInsertRowid), content);
|
|
1241
|
+
return { status: "inserted", memory: this.memoryFromRow(this.memoryRow(record.id)) };
|
|
1242
|
+
});
|
|
1243
|
+
}
|
|
1244
|
+
close() {
|
|
1245
|
+
if (this.db.isOpen)
|
|
1246
|
+
this.db.close();
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
/** The tag every vault-imported record carries until it is accepted and after. */
|
|
1250
|
+
export const IMPORT_TAG = "source=vault-import";
|
|
1251
|
+
/** Stable short hash of a project path, used in vault files so the absolute path is never published. */
|
|
1252
|
+
export function projectHash(project) {
|
|
1253
|
+
return createHash("sha256").update(normalizeProject(project), "utf8").digest("hex").slice(0, 16);
|
|
1254
|
+
}
|