@nithin-naubad/memory-engine 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nithin Naubad
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,9 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # Memory Engine
2
+
3
+ Standalone local SQLite memory, evidence verification and skill proposals. Requires Node.js 22.13 or later. No cloud service or external runtime dependencies.
4
+
5
+ ## Local installation
6
+
7
+ Clone this repository and run `npm install -g .` from its root. Run `memory-engine` from the project directory with a version 1 JSON request on stdin, for example `{"version":1,"operation":"stats"}`. The engine stores project-local data under `.memory-engine/memory/`.
8
+
9
+ The package is currently private in npm metadata to prevent accidental publication. Integration and release verification are pending.
package/bridge-cli.js ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import { dispatchMemoryRequest } from "./bridge.js";
3
+ const chunks = [];
4
+ let size = 0;
5
+ try {
6
+ for await (const chunk of process.stdin) {
7
+ size += chunk.length;
8
+ if (size > 65536) throw new Error("Request too large.");
9
+ chunks.push(chunk);
10
+ }
11
+ const result = await dispatchMemoryRequest(JSON.parse(Buffer.concat(chunks).toString("utf8")));
12
+ process.stdout.write(JSON.stringify({ version: 1, ok: true, result }) + "\n");
13
+ } catch (error) {
14
+ process.stdout.write(JSON.stringify({ version: 1, ok: false, error: error.message }) + "\n");
15
+ process.exitCode = 1;
16
+ }
package/bridge.js ADDED
@@ -0,0 +1,20 @@
1
+ import { extractExecutionCandidates, openLocalMemoryStore } from "./local-store.js";
2
+
3
+ // One request per invocation; stdout is reserved for the versioned response.
4
+ const operations = new Map([
5
+ ["record", ["value"]], ["recordExecution", ["runId", "value"]], ["get", ["id"]], ["list", ["limit"]],
6
+ ["search", ["query", "limit"]], ["retrieve", ["query", "context", "adapter"]],
7
+ ["verify", ["id", "evidence"]], ["archive", ["id"]], ["stats", []],
8
+ ["consolidate", ["context"]], ["propose", ["context", "memoryId"]],
9
+ ["approvedSkills", ["context"]], ["proposal", ["id"]], ["proposals", []], ["decideProposal", ["id", "decision", "evidence"]]
10
+ ]);
11
+ export async function dispatchMemoryRequest(request, root = process.cwd()) {
12
+ if (request?.version !== 1) throw new Error("Unsupported memory protocol or operation.");
13
+ const params = request.params ?? {};
14
+ if (typeof params !== "object" || Array.isArray(params)) throw new Error("Invalid parameters.");
15
+ if (request.operation === "extractExecutionCandidates") return extractExecutionCandidates(params.observations);
16
+ if (!operations.has(request.operation)) throw new Error("Unsupported memory protocol or operation.");
17
+ const store = await openLocalMemoryStore(root);
18
+ try { return store[request.operation](...operations.get(request.operation).map(key => params[key])); }
19
+ finally { store.close(); }
20
+ }
package/contract.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "version": 4,
3
+ "applicationId": 1279873601,
4
+ "types": [
5
+ "episodic",
6
+ "semantic",
7
+ "procedural",
8
+ "corrective"
9
+ ],
10
+ "statuses": [
11
+ "candidate",
12
+ "verified",
13
+ "archived"
14
+ ],
15
+ "limits": {
16
+ "records": 5000,
17
+ "results": 100,
18
+ "title": 160,
19
+ "learning": 4000,
20
+ "evidence": 16,
21
+ "id": 128
22
+ },
23
+ "adapters": {
24
+ "coding": {
25
+ "types": [
26
+ "corrective"
27
+ ],
28
+ "prefix": "test:",
29
+ "check": "test",
30
+ "error": "Verification requires a linked passing coding test, a compatibility context, and explicit review."
31
+ },
32
+ "practice": {
33
+ "types": [
34
+ "corrective",
35
+ "procedural"
36
+ ],
37
+ "prefix": "exercise:",
38
+ "check": "exercise",
39
+ "error": "Verification requires a linked passing practice exercise, a compatibility context, and explicit review."
40
+ }
41
+ },
42
+ "migration3": "CREATE TABLE skill_proposals (id TEXT PRIMARY KEY, context TEXT NOT NULL, title TEXT NOT NULL, markdown TEXT NOT NULL, sources TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','approved','rejected','withdrawn')), created_at TEXT NOT NULL, decided_at TEXT, receipt TEXT);",
43
+ "migration2": "ALTER TABLE memories ADD COLUMN verification TEXT; CREATE INDEX memories_verified ON memories(status, updated_at);",
44
+ "migration": "CREATE TABLE memories (\n id TEXT PRIMARY KEY,\n type TEXT NOT NULL,\n title TEXT NOT NULL,\n learning TEXT NOT NULL,\n evidence TEXT NOT NULL,\n scope TEXT NOT NULL DEFAULT 'project' CHECK (scope = 'project'),\n status TEXT NOT NULL DEFAULT 'candidate',\n revision INTEGER NOT NULL DEFAULT 1,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n);\nCREATE TABLE memory_tombstones (id TEXT PRIMARY KEY, revision INTEGER NOT NULL, deleted_at TEXT NOT NULL);\nCREATE TABLE memory_index_state (id INTEGER PRIMARY KEY CHECK (id = 1), revision INTEGER NOT NULL, indexed_revision INTEGER NOT NULL);\nINSERT INTO memory_index_state VALUES (1, 0, -1);\nCREATE INDEX memories_status_updated ON memories (status, updated_at DESC);"
45
+ }
package/local-store.js ADDED
@@ -0,0 +1,246 @@
1
+ import { proposalActions } from "./proposals.js";
2
+ import { reviewEvidence, eligibleText, hasMemoryAdapter, safeContext } from "./validation.js";
3
+ import { randomUUID } from "node:crypto";
4
+ import { chmod, lstat, mkdir, readFile, writeFile } from "node:fs/promises";
5
+ import { join, resolve } from "node:path";
6
+
7
+ const spec = JSON.parse(await readFile(new URL("./contract.json", import.meta.url), "utf8"));
8
+ const { limits } = spec;
9
+ const safeRef = /^[A-Za-z0-9][A-Za-z0-9_.:-]*$/;
10
+ const time = () => new Date().toISOString();
11
+ const queryTokens = value => value.toLowerCase().match(/[\p{L}\p{N}_]+/gu)?.slice(0, 12) ?? [];
12
+
13
+ function text(value, max, name) {
14
+ if (typeof value !== "string" || !value.trim() || [...value.trim()].length > max || value.includes("\0")) {
15
+ throw new Error(name + " must contain 1–" + max + " characters.");
16
+ }
17
+ return value.trim();
18
+ }
19
+
20
+ function record(value) {
21
+ if (!spec.types.includes(value?.type)) throw new Error("Choose episodic, semantic, procedural, or corrective memory.");
22
+ const evidence = value.evidence ?? [];
23
+ if (!Array.isArray(evidence) || evidence.length > limits.evidence ||
24
+ evidence.some(item => typeof item !== "string" || item.length > limits.id || !safeRef.test(item))) {
25
+ throw new Error("Use up to 16 evidence IDs, such as run:abc123.");
26
+ }
27
+ return {
28
+ type: value.type, title: text(value.title, limits.title, "Title"),
29
+ learning: text(value.learning, limits.learning, "Learning"), evidence: [...new Set(evidence)],
30
+ };
31
+ }
32
+
33
+ export function extractExecutionCandidates(values) {
34
+ if (!Array.isArray(values) || values.length > 8) throw new Error("Supply up to eight execution observations.");
35
+ const candidates = new Map();
36
+ for (const value of values) {
37
+ try {
38
+ const { type, title, learning } = record({ type: value?.type, title: value?.title, learning: value?.learning });
39
+ if (eligibleText(title + " " + learning)) {
40
+ candidates.set(JSON.stringify([type, title, learning]), { type, title, learning });
41
+ }
42
+ } catch {
43
+ // A malformed observation cannot prevent review of the others.
44
+ }
45
+ }
46
+ return [...candidates.values()];
47
+ }
48
+
49
+ function present(row) {
50
+ return row ? { id: row.id, type: row.type, title: row.title, learning: row.learning,
51
+ evidence: JSON.parse(row.evidence), scope: row.scope, status: row.status, revision: row.revision,
52
+ createdAt: row.created_at, updatedAt: row.updated_at, ...(row.verification ? { verification: JSON.parse(row.verification) } : {}) } : null;
53
+ }
54
+
55
+ function bounded(limit) {
56
+ if (!Number.isInteger(limit) || limit < 1 || limit > limits.results) throw new Error("Limit must be between 1 and 100.");
57
+ return limit;
58
+ }
59
+
60
+ async function directory(root, namespace) {
61
+ let path = resolve(root);
62
+ for (const part of [namespace, "memory"]) {
63
+ path = join(path, part);
64
+ await mkdir(path, { mode: 0o700 }).catch(error => { if (error.code !== "EEXIST") throw error; });
65
+ if (!(await lstat(path)).isDirectory()) throw new Error("Memory folders must be regular directories.");
66
+ }
67
+ await chmod(path, 0o700);
68
+ await writeFile(join(path, ".gitignore"), "*\n", { flag: "wx", mode: 0o600 })
69
+ .catch(error => { if (error.code !== "EEXIST") throw error; });
70
+ return path;
71
+ }
72
+
73
+ export async function openLocalMemoryStore(root = process.cwd(), { forceKeyword = false, namespace = ".memory-engine", extension } = {}) {
74
+ if (!/^\.[A-Za-z0-9][A-Za-z0-9_-]*$/.test(namespace)) throw new Error("Invalid memory namespace.");
75
+ const dir = await directory(root, namespace);
76
+ const file = join(dir, "memory.db");
77
+ await writeFile(file, "", { flag: "wx", mode: 0o600 })
78
+ .catch(error => { if (error.code !== "EEXIST") throw error; });
79
+ if (!(await lstat(file)).isFile()) throw new Error("The memory database must be a regular file.");
80
+ await chmod(file, 0o600);
81
+ const { DatabaseSync } = await import("node:sqlite");
82
+ const db = new DatabaseSync(file);
83
+ function transaction(fn) {
84
+ db.exec("BEGIN IMMEDIATE");
85
+ try {
86
+ const result = fn();
87
+ db.exec("COMMIT");
88
+ return result;
89
+ } catch (error) {
90
+ db.exec("ROLLBACK");
91
+ throw error;
92
+ }
93
+ }
94
+ let fts = false;
95
+ try {
96
+ db.exec("PRAGMA busy_timeout = 3000");
97
+ transaction(() => {
98
+ const { user_version: version } = db.prepare("PRAGMA user_version").get();
99
+ const { application_id: app } = db.prepare("PRAGMA application_id").get();
100
+ if (version > spec.version) throw new Error("Update the memory engine before opening this newer memory database.");
101
+ if ((app !== 0 && app !== spec.applicationId) || (version !== 0 && app !== spec.applicationId) ||
102
+ (version === 0 && db.prepare("SELECT 1 FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' LIMIT 1").get())) {
103
+ throw new Error("The file is not a compatible memory database.");
104
+ }
105
+ if (version === 0) db.exec(spec.migration + "PRAGMA application_id = " + spec.applicationId);
106
+ if (version < 2) db.exec(spec.migration2);
107
+ if (version < 3) db.exec(spec.migration3);
108
+ if (version < 4) db.exec("PRAGMA user_version = 4");
109
+ });
110
+ db.exec("PRAGMA journal_mode = WAL; PRAGMA secure_delete = ON");
111
+ if (!forceKeyword) {
112
+ try {
113
+ db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(id UNINDEXED, title, learning)");
114
+ fts = true;
115
+ } catch (error) {
116
+ if (!/no such module: fts5/i.test(error.message)) throw error;
117
+ }
118
+ }
119
+ } catch (error) { db.close(); throw error; }
120
+
121
+ const get = id => present(db.prepare("SELECT * FROM memories WHERE id = ?").get(id));
122
+ const dirty = () => db.exec("UPDATE memory_index_state SET revision = revision + 1 WHERE id = 1");
123
+ const erase = (id, revision) => {
124
+ db.prepare("INSERT INTO memory_tombstones VALUES (?,?,?) ON CONFLICT(id) DO NOTHING").run(id, revision, time());
125
+ if (fts) db.prepare("DELETE FROM memory_fts WHERE id=?").run(id);
126
+ db.prepare("DELETE FROM skill_proposals WHERE EXISTS (SELECT 1 FROM json_each(sources) WHERE json_extract(value, '$.id')=?)").run(id);
127
+ db.prepare("DELETE FROM memories WHERE id=?").run(id);
128
+ dirty();
129
+ };
130
+ let extensions;
131
+ try {
132
+ extensions = extension?.({ db, transaction, get, erase, dirty, record, eligibleText, limits, time }) ?? {};
133
+ } catch (error) { db.close(); throw error; }
134
+ function insertMemory(item) {
135
+ if (db.prepare("SELECT count(*) AS count FROM memories").get().count >= limits.records) {
136
+ throw new Error("Memory is full. Forget a record before adding one.");
137
+ }
138
+ const id = randomUUID();
139
+ const now = time();
140
+ db.prepare("INSERT INTO memories (id,type,title,learning,evidence,created_at,updated_at) VALUES (?,?,?,?,?,?,?)")
141
+ .run(id, item.type, item.title, item.learning, JSON.stringify(item.evidence), now, now);
142
+ dirty();
143
+ return get(id);
144
+ }
145
+
146
+ return {
147
+ ...extensions,
148
+ ...proposalActions(db, transaction),
149
+ file,
150
+ close: () => db.close(),
151
+ get,
152
+ list(limit = 20) {
153
+ return db.prepare("SELECT * FROM memories ORDER BY updated_at DESC, id LIMIT ?").all(bounded(limit)).map(present);
154
+ },
155
+ record(value) {
156
+ const item = record(value);
157
+ return transaction(() => insertMemory(item));
158
+ },
159
+ recordExecution(runId, value) {
160
+ if (typeof runId !== "string" || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(runId)) {
161
+ throw new Error("Supply a local execution identifier.");
162
+ }
163
+ const extra = value?.evidence ?? [];
164
+ if (!Array.isArray(extra)) throw new Error("Evidence must be an array.");
165
+ const reference = "run:" + runId.toLowerCase();
166
+ const item = record({ ...value, evidence: [...new Set([reference, ...extra])] });
167
+ if (!eligibleText(item.title + " " + item.learning)) {
168
+ throw new Error("Remove credentials or instruction overrides from the learning.");
169
+ }
170
+ return transaction(() => {
171
+ const existing = db.prepare(
172
+ "SELECT id FROM memories WHERE type = ? AND title = ? AND learning = ? AND status != 'archived' " +
173
+ "AND EXISTS (SELECT 1 FROM json_each(memories.evidence) WHERE value = ?) ORDER BY created_at, id LIMIT 1",
174
+ ).get(item.type, item.title, item.learning, reference);
175
+ return existing ? { ...get(existing.id), reused: true } : insertMemory(item);
176
+ });
177
+ },
178
+ search(query, limit = 20) {
179
+ bounded(limit);
180
+ const tokens = queryTokens(text(query, 240, "Query"));
181
+ if (!tokens.length) return [];
182
+ if (!fts) {
183
+ const terms = tokens.map(() => "instr(lower(title || ' ' || learning), ?) > 0").join(" AND ");
184
+ return db.prepare("SELECT * FROM memories WHERE status != 'archived' AND " + terms + " ORDER BY updated_at DESC, id LIMIT ?")
185
+ .all(...tokens, limit).map(present);
186
+ }
187
+ return transaction(() => {
188
+ const state = db.prepare("SELECT revision, indexed_revision FROM memory_index_state WHERE id=1").get();
189
+ if (state.revision !== state.indexed_revision) {
190
+ db.exec("DELETE FROM memory_fts; INSERT INTO memory_fts SELECT id,title,learning FROM memories;" +
191
+ "UPDATE memory_index_state SET indexed_revision=revision WHERE id=1");
192
+ }
193
+ const expression = tokens.map(token => '"' + token + '"').join(" AND ");
194
+ return db.prepare("SELECT memories.* FROM memory_fts JOIN memories ON memories.id = memory_fts.id " +
195
+ "WHERE memory_fts MATCH ? AND memories.status != 'archived' ORDER BY bm25(memory_fts), memories.id LIMIT ?").all(expression, limit).map(present);
196
+ });
197
+ },
198
+ verify(id, evidence) {
199
+ return transaction(() => {
200
+ const receipt = reviewEvidence(get(id), evidence);
201
+ db.prepare("UPDATE memories SET status='verified', verification=?, revision=revision+1, updated_at=? WHERE id=?")
202
+ .run(JSON.stringify(receipt), time(), id);
203
+ return get(id);
204
+ });
205
+ },
206
+ retrieve(query, context, adapter = "coding") {
207
+ if (!safeContext(context) || !hasMemoryAdapter(adapter)) return [];
208
+ const tokens = new Set(queryTokens(query).filter(token => token.length >= 4));
209
+ if (!tokens.size) return [];
210
+ const result = [];
211
+ let remaining = 2400;
212
+ const rows = db.prepare("SELECT * FROM memories WHERE status='verified' AND json_extract(verification, '$.context') = ? AND json_extract(verification, '$.adapter') = ? ORDER BY updated_at DESC, id LIMIT 100").all(context, adapter);
213
+ for (const row of rows) {
214
+ const item = present(row);
215
+ const body = item.title + " " + item.learning;
216
+ if (!eligibleText(body) || !queryTokens(body).some(token => tokens.has(token)) || body.length > remaining) continue;
217
+ result.push(item);
218
+ remaining -= body.length;
219
+ if (result.length === 4) break;
220
+ }
221
+ return result;
222
+ },
223
+ archive(id) {
224
+ return transaction(() => {
225
+ const item = get(id);
226
+ if (!item || item.status === "archived") return item;
227
+ db.prepare("UPDATE memories SET status = 'archived', revision = revision + 1, updated_at = ? WHERE id = ?")
228
+ .run(time(), id);
229
+ return get(id);
230
+ });
231
+ },
232
+ stats() {
233
+ const counts = Object.fromEntries(spec.statuses.map(status => [status, 0]));
234
+ for (const row of db.prepare("SELECT status, count(*) AS count FROM memories GROUP BY status").all()) counts[row.status] = row.count;
235
+ return { schemaVersion: spec.version, search: fts ? "fts5" : "keyword", ...counts };
236
+ },
237
+ forget(id) {
238
+ return transaction(() => {
239
+ const item = get(id);
240
+ if (!item) return false;
241
+ erase(id, item.revision + 1);
242
+ return true;
243
+ });
244
+ },
245
+ };
246
+ }
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
- {
2
- "name": "@nithin-naubad/memory-engine",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@nithin-naubad/memory-engine",
3
+ "version": "0.1.1",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "type": "module",
8
+ "description": "Local SQLite memory, evidence verification and skill proposals",
9
+ "engines": {
10
+ "node": ">=22.13.0"
11
+ },
12
+ "license": "MIT",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./standalone.d.ts",
16
+ "default": "./standalone.js"
17
+ },
18
+ "./bridge": "./bridge.js"
19
+ },
20
+ "bin": {
21
+ "memory-engine": "./bridge-cli.js"
22
+ },
23
+ "files": [
24
+ "standalone.js",
25
+ "standalone.d.ts",
26
+ "local-store.js",
27
+ "contract.json",
28
+ "validation.js",
29
+ "proposals.js",
30
+ "bridge.js",
31
+ "bridge-cli.js",
32
+ "LICENSE",
33
+ "README.md"
34
+ ],
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/naubadnithinkumar/memory-engine.git"
38
+ },
39
+ "scripts": {
40
+ "test": "node --test"
41
+ }
42
+ }
package/proposals.js ADDED
@@ -0,0 +1,90 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { eligibleText, safeContext } from "./validation.js";
3
+
4
+ function readSources(db, context) {
5
+ const rows = db.prepare("SELECT id,title,learning,revision,verification FROM memories WHERE status='verified' " +
6
+ "AND json_extract(verification,'$.context')=? AND json_extract(verification,'$.adapter')='coding' ORDER BY created_at,id LIMIT 500").all(context);
7
+ return rows.filter(row => eligibleText(row.title + " " + row.learning)).map(row => ({
8
+ id: row.id, title: row.title, learning: row.learning, revision: row.revision,
9
+ evidenceId: JSON.parse(row.verification).evidenceId,
10
+ }));
11
+ }
12
+
13
+ export function consolidate(db, context) {
14
+ if (!safeContext(context)) throw new Error("Supply a valid compatibility context.");
15
+ const groups = new Map();
16
+ for (const row of readSources(db, context)) {
17
+ const key = row.learning.normalize("NFKC").toLowerCase().replace(/\s+/g, " ").trim();
18
+ if (!groups.has(key)) groups.set(key, []);
19
+ groups.get(key).push(row);
20
+ }
21
+ return [...groups.values()]
22
+ .filter(group => new Set(group.map(row => row.evidenceId)).size >= 2)
23
+ .map(group => ({ title: group[0].title, learning: group[0].learning,
24
+ sources: group.map(({ id, revision, evidenceId }) => ({ id, revision, evidenceId })) }));
25
+ }
26
+
27
+ function present(row) {
28
+ return row ? { id: row.id, context: row.context, title: row.title, markdown: row.markdown,
29
+ sources: JSON.parse(row.sources), status: row.status, createdAt: row.created_at,
30
+ decidedAt: row.decided_at, receipt: row.receipt ? JSON.parse(row.receipt) : null } : null;
31
+ }
32
+
33
+ export function proposalActions(db, transaction) {
34
+ const get = id => present(db.prepare("SELECT * FROM skill_proposals WHERE id=?").get(id));
35
+ const now = () => new Date().toISOString();
36
+ return {
37
+ consolidate: context => consolidate(db, context),
38
+ propose(context, memoryId) {
39
+ return transaction(() => {
40
+ const group = consolidate(db, context).find(item => item.sources.some(source => source.id === memoryId));
41
+ if (!group) throw new Error("Choose a verified correction corroborated by a different test reference.");
42
+ const sources = JSON.stringify(group.sources);
43
+ const prior = db.prepare("SELECT * FROM skill_proposals WHERE context=? AND sources=? AND status IN ('pending','approved')").get(context, sources);
44
+ if (prior) return present(prior);
45
+ if (db.prepare("SELECT count(*) AS count FROM skill_proposals").get().count >= 500) {
46
+ throw new Error("Skill proposal store reached its limit.");
47
+ }
48
+ const id = randomUUID();
49
+ const markdown = "# " + group.title.replace(/[\r\n]+/g, " ") + "\n\n## When to use\n\nCompatibility context: `" +
50
+ context + "`. Confirm it still applies.\n\n## Suggested practice\n\n" + group.learning + "\n";
51
+ db.prepare("INSERT INTO skill_proposals (id,context,title,markdown,sources,created_at) VALUES (?,?,?,?,?,?)")
52
+ .run(id, context, group.title, markdown, sources, now());
53
+ return get(id);
54
+ });
55
+ },
56
+ approvedSkills(context) {
57
+ if (!safeContext(context)) return [];
58
+ const sources = readSources(db, context);
59
+ return db.prepare("SELECT * FROM skill_proposals WHERE context=? AND status='approved' ORDER BY decided_at DESC,id LIMIT 100").all(context)
60
+ .map(present).filter(p => p.receipt && p.sources.every(s => sources.some(r => r.id === s.id && r.revision === s.revision && r.evidenceId === s.evidenceId)));
61
+ },
62
+ proposal: get,
63
+ proposals: () => db.prepare("SELECT * FROM skill_proposals ORDER BY created_at DESC,id LIMIT 100").all().map(present),
64
+ decideProposal(id, decision, evidence) {
65
+ if (!["approved", "rejected", "withdrawn"].includes(decision)) throw new Error("Invalid skill proposal decision.");
66
+ return transaction(() => {
67
+ const proposal = get(id);
68
+ if (!proposal) throw new Error("Skill proposal was not found.");
69
+ const expected = decision === "withdrawn" ? "approved" : "pending";
70
+ if (proposal.status !== expected) throw new Error("This skill proposal is " + proposal.status + ".");
71
+ let receipt = proposal.receipt;
72
+ if (decision === "approved") {
73
+ const sources = readSources(db, proposal.context);
74
+ if (proposal.sources.some(source => !sources.some(row => row.id === source.id && row.revision === source.revision))) {
75
+ throw new Error("A source memory changed. Generate a fresh proposal.");
76
+ }
77
+ if (evidence?.result !== "passed" || evidence.reviewed !== true || evidence.context !== proposal.context ||
78
+ typeof evidence.evidenceId !== "string" || !/^test:[A-Za-z0-9][A-Za-z0-9_.:-]{0,110}$/.test(evidence.evidenceId) ||
79
+ proposal.sources.some(source => source.evidenceId === evidence.evidenceId)) {
80
+ throw new Error("Approval requires a separate passing regression test and explicit review for this context.");
81
+ }
82
+ receipt = { evidenceId: evidence.evidenceId, context: evidence.context, result: "passed", reviewed: true };
83
+ }
84
+ db.prepare("UPDATE skill_proposals SET status=?, decided_at=?, receipt=? WHERE id=?")
85
+ .run(decision, now(), receipt ? JSON.stringify(receipt) : null, id);
86
+ return get(id);
87
+ });
88
+ },
89
+ };
90
+ }
@@ -0,0 +1,52 @@
1
+ export type MemoryType = "episodic" | "semantic" | "procedural" | "corrective";
2
+ export type MemoryStatus = "candidate" | "verified" | "archived";
3
+ export interface MemoryInput { type: MemoryType; title: string; learning: string; evidence?: string[] }
4
+ export type MemoryAdapter = "coding" | "practice";
5
+ export type VerificationReceipt = { evidenceId: string; context: string } & (
6
+ { adapter: "coding"; test: string } | { adapter: "practice"; exercise: string }
7
+ );
8
+ export interface MemoryRecord extends MemoryInput {
9
+ id: string;
10
+ evidence: string[];
11
+ scope: "project";
12
+ status: MemoryStatus;
13
+ revision: number;
14
+ createdAt: string;
15
+ updatedAt: string;
16
+ verification?: VerificationReceipt;
17
+ }
18
+ export interface SkillProposalSource { id: string; revision: number; evidenceId: string }
19
+ export interface SkillProposalReceipt { evidenceId: string; context: string; result: "passed"; reviewed: true }
20
+ export interface SkillProposal {
21
+ id: string;
22
+ context: string;
23
+ title: string;
24
+ markdown: string;
25
+ sources: SkillProposalSource[];
26
+ status: "pending" | "approved" | "rejected" | "withdrawn";
27
+ createdAt: string;
28
+ decidedAt: string | null;
29
+ receipt: SkillProposalReceipt | null;
30
+ }
31
+ export interface MemoryStore {
32
+ readonly file: string;
33
+ consolidate(context: string): Array<{ title: string; learning: string; sources: SkillProposalSource[] }>;
34
+ propose(context: string, memoryId: string): SkillProposal;
35
+ proposal(id: string): SkillProposal | null;
36
+ proposals(): SkillProposal[];
37
+ approvedSkills(context: string): SkillProposal[];
38
+ decideProposal(id: string, decision: "approved" | "rejected" | "withdrawn", evidence?: SkillProposalReceipt): SkillProposal;
39
+ close(): void;
40
+ get(id: string): MemoryRecord | null;
41
+ list(limit?: number): MemoryRecord[];
42
+ record(value: MemoryInput): MemoryRecord;
43
+ recordExecution(runId: string, value: MemoryInput): MemoryRecord & { reused?: true };
44
+ search(query: string, limit?: number): MemoryRecord[];
45
+ stats(): { schemaVersion: number; search: "fts5" | "keyword" } & Record<MemoryStatus, number>;
46
+ verify(id: string, evidence: VerificationReceipt & { result: "passed"; reviewed: true }): MemoryRecord;
47
+ retrieve(query: string, context: string, adapter?: MemoryAdapter): MemoryRecord[];
48
+ archive(id: string): MemoryRecord | null;
49
+ forget(id: string): boolean;
50
+ }
51
+ export function openLocalMemoryStore(root?: string, options?: { forceKeyword?: boolean; namespace?: string }): Promise<MemoryStore>;
52
+ export function extractExecutionCandidates(observations: unknown[]): Array<Pick<MemoryInput, "type" | "title" | "learning">>;
package/standalone.js ADDED
@@ -0,0 +1 @@
1
+ export { extractExecutionCandidates, openLocalMemoryStore } from "./local-store.js";
package/validation.js ADDED
@@ -0,0 +1,25 @@
1
+ import { readFileSync } from "node:fs";
2
+ const { adapters } = JSON.parse(readFileSync(new URL("./contract.json", import.meta.url), "utf8"));
3
+
4
+ const secret = /\b(?:lyra_sdk_[a-f0-9]{64}|sk-[\w-]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|AKIA[A-Z0-9]{16})\b|-----BEGIN [^-]+PRIVATE KEY-----/i;
5
+ const unsafe = /(?:ignore|override|disregard)\s+(?:all\s+)?(?:prior|previous|system)\s+instructions|\breveal\s+(?:your\s+)?(?:system prompt|credentials|secrets)\b/i;
6
+ const label = /^[A-Za-z0-9][A-Za-z0-9_.:/@-]{0,95}$/;
7
+ const evidenceSuffix = /^[A-Za-z0-9][A-Za-z0-9_.:-]*$/;
8
+ export const safeContext = value => typeof value === "string" && label.test(value);
9
+ export const eligibleText = text => !secret.test(text) && !unsafe.test(text);
10
+ export const hasMemoryAdapter = value => typeof value === "string" && Object.hasOwn(adapters, value);
11
+
12
+ export function reviewEvidence(item, evidence) {
13
+ if (!item || item.status === "archived") throw new Error("Choose an active memory record.");
14
+ if (!eligibleText(item.title + " " + item.learning)) throw new Error("Remove credentials or instruction overrides from the memory.");
15
+ const adapter = evidence?.adapter;
16
+ if (!hasMemoryAdapter(adapter)) throw new Error("Choose a supported memory adapter.");
17
+ const rule = adapters[adapter];
18
+ const id = evidence.evidenceId;
19
+ if (!rule.types.includes(item.type) || evidence.result !== "passed" || evidence.reviewed !== true ||
20
+ typeof id !== "string" || !id.startsWith(rule.prefix) || !evidenceSuffix.test(id.slice(rule.prefix.length)) ||
21
+ !item.evidence.includes(id) || !safeContext(evidence.context) || !safeContext(evidence[rule.check])) {
22
+ throw new Error(rule.error);
23
+ }
24
+ return { adapter, evidenceId: id, [rule.check]: evidence[rule.check], context: evidence.context };
25
+ }