@learningnodes/elen 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/client_test_output.txt +17 -0
- package/dist/client.d.ts +16 -0
- package/dist/client.js +80 -0
- package/dist/id.d.ts +3 -0
- package/dist/id.js +20 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +51 -0
- package/dist/storage/index.d.ts +3 -0
- package/dist/storage/index.js +19 -0
- package/dist/storage/interface.d.ts +11 -0
- package/dist/storage/interface.js +2 -0
- package/dist/storage/memory.d.ts +14 -0
- package/dist/storage/memory.js +69 -0
- package/dist/storage/sqlite.d.ts +34 -0
- package/dist/storage/sqlite.js +334 -0
- package/dist/types.d.ts +30 -0
- package/dist/types.js +2 -0
- package/package.json +22 -0
- package/src/client.ts +93 -0
- package/src/id.ts +18 -0
- package/src/index.ts +45 -0
- package/src/shims.d.ts +27 -0
- package/src/storage/index.ts +3 -0
- package/src/storage/interface.ts +12 -0
- package/src/storage/memory.ts +85 -0
- package/src/storage/sqlite.ts +397 -0
- package/src/types.ts +35 -0
- package/test_output.txt +78 -0
- package/tests/client.test.ts +147 -0
- package/tests/integration.test.ts +49 -0
- package/tests/storage.test.ts +100 -0
- package/tsconfig.json +16 -0
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.SQLiteStorage = void 0;
|
|
7
|
+
const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
|
|
8
|
+
class SQLiteStorage {
|
|
9
|
+
constructor(path, projectId = 'default') {
|
|
10
|
+
this.db = new better_sqlite3_1.default(path);
|
|
11
|
+
this.projectId = projectId;
|
|
12
|
+
this.init();
|
|
13
|
+
}
|
|
14
|
+
init() {
|
|
15
|
+
const pragmaQuery = this.db.prepare('PRAGMA user_version').get();
|
|
16
|
+
const versionRow = pragmaQuery ? pragmaQuery.user_version : 0;
|
|
17
|
+
if (versionRow === 0) {
|
|
18
|
+
this.db.exec(`
|
|
19
|
+
CREATE TABLE IF NOT EXISTS constraint_sets (
|
|
20
|
+
constraint_set_id TEXT PRIMARY KEY,
|
|
21
|
+
atoms TEXT NOT NULL,
|
|
22
|
+
summary TEXT NOT NULL,
|
|
23
|
+
created_at TEXT NOT NULL
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
CREATE TABLE IF NOT EXISTS records (
|
|
27
|
+
record_id TEXT PRIMARY KEY,
|
|
28
|
+
decision_id TEXT NOT NULL,
|
|
29
|
+
q_id TEXT NOT NULL,
|
|
30
|
+
agent_id TEXT NOT NULL,
|
|
31
|
+
domain TEXT NOT NULL,
|
|
32
|
+
project_id TEXT NOT NULL DEFAULT 'default',
|
|
33
|
+
decision_text TEXT NOT NULL,
|
|
34
|
+
constraint_set_id TEXT NOT NULL,
|
|
35
|
+
refs TEXT NOT NULL,
|
|
36
|
+
status TEXT NOT NULL,
|
|
37
|
+
supersedes_id TEXT,
|
|
38
|
+
timestamp TEXT NOT NULL,
|
|
39
|
+
record_json TEXT NOT NULL,
|
|
40
|
+
FOREIGN KEY(constraint_set_id) REFERENCES constraint_sets(constraint_set_id)
|
|
41
|
+
);
|
|
42
|
+
|
|
43
|
+
CREATE TABLE IF NOT EXISTS projects (
|
|
44
|
+
project_id TEXT PRIMARY KEY,
|
|
45
|
+
display_name TEXT NOT NULL,
|
|
46
|
+
source_hint TEXT,
|
|
47
|
+
created_at TEXT NOT NULL
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
CREATE TABLE IF NOT EXISTS project_sharing (
|
|
51
|
+
source_project_id TEXT NOT NULL,
|
|
52
|
+
target_project_id TEXT NOT NULL,
|
|
53
|
+
direction TEXT NOT NULL DEFAULT 'one-way',
|
|
54
|
+
enabled INTEGER NOT NULL DEFAULT 1,
|
|
55
|
+
PRIMARY KEY (source_project_id, target_project_id)
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
CREATE TABLE IF NOT EXISTS search_log (
|
|
59
|
+
search_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
60
|
+
query TEXT NOT NULL,
|
|
61
|
+
domain TEXT,
|
|
62
|
+
project_id TEXT NOT NULL,
|
|
63
|
+
hits INTEGER NOT NULL DEFAULT 0,
|
|
64
|
+
cross_project_hits INTEGER NOT NULL DEFAULT 0,
|
|
65
|
+
searched_at TEXT NOT NULL
|
|
66
|
+
);
|
|
67
|
+
`);
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
// Legacy migration: Database exists but lacks the v1 schema columns.
|
|
71
|
+
this.db.exec("BEGIN TRANSACTION;");
|
|
72
|
+
try {
|
|
73
|
+
this.db.exec(`
|
|
74
|
+
CREATE TABLE IF NOT EXISTS constraint_sets (
|
|
75
|
+
constraint_set_id TEXT PRIMARY KEY,
|
|
76
|
+
atoms TEXT NOT NULL,
|
|
77
|
+
summary TEXT NOT NULL,
|
|
78
|
+
created_at TEXT NOT NULL
|
|
79
|
+
);
|
|
80
|
+
`);
|
|
81
|
+
// Alter legacy records table to inject the new columns gracefully
|
|
82
|
+
const queries = [
|
|
83
|
+
"ALTER TABLE records ADD COLUMN q_id TEXT NOT NULL DEFAULT 'legacy_q'",
|
|
84
|
+
"ALTER TABLE records ADD COLUMN constraint_set_id TEXT NOT NULL DEFAULT 'legacy_c'",
|
|
85
|
+
"ALTER TABLE records ADD COLUMN refs TEXT NOT NULL DEFAULT '[]'",
|
|
86
|
+
"ALTER TABLE records ADD COLUMN status TEXT NOT NULL DEFAULT 'active'",
|
|
87
|
+
"ALTER TABLE records ADD COLUMN supersedes_id TEXT",
|
|
88
|
+
"ALTER TABLE records ADD COLUMN timestamp TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP",
|
|
89
|
+
"ALTER TABLE records ADD COLUMN decision_text TEXT NOT NULL DEFAULT ''"
|
|
90
|
+
];
|
|
91
|
+
for (const query of queries) {
|
|
92
|
+
try {
|
|
93
|
+
this.db.exec(query);
|
|
94
|
+
}
|
|
95
|
+
catch (e) {
|
|
96
|
+
// Ignore "duplicate column name" if partially migrated
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
// Migrate existing 'answer' data over to 'decision_text' if applicable
|
|
100
|
+
try {
|
|
101
|
+
this.db.exec("UPDATE records SET decision_text = answer WHERE decision_text = '' AND answer IS NOT NULL");
|
|
102
|
+
}
|
|
103
|
+
catch (e) {
|
|
104
|
+
// 'answer' column might have been dropped or didn't exist
|
|
105
|
+
}
|
|
106
|
+
this.db.exec("COMMIT;");
|
|
107
|
+
}
|
|
108
|
+
catch (e) {
|
|
109
|
+
this.db.exec("ROLLBACK;");
|
|
110
|
+
throw e;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
this.db.exec('PRAGMA user_version = 1');
|
|
114
|
+
// Ensure current project exists in projects table
|
|
115
|
+
this.ensureProject(this.projectId);
|
|
116
|
+
}
|
|
117
|
+
ensureProject(projectId, displayName) {
|
|
118
|
+
const existing = this.db
|
|
119
|
+
.prepare('SELECT project_id FROM projects WHERE project_id = ?')
|
|
120
|
+
.get(projectId);
|
|
121
|
+
if (!existing) {
|
|
122
|
+
this.db.prepare(`
|
|
123
|
+
INSERT INTO projects (project_id, display_name, source_hint, created_at)
|
|
124
|
+
VALUES (@project_id, @display_name, @source_hint, @created_at)
|
|
125
|
+
`).run({
|
|
126
|
+
project_id: projectId,
|
|
127
|
+
display_name: displayName || projectId.replace(/[-_]/g, ' ').replace(/\\b\\w/g, c => c.toUpperCase()),
|
|
128
|
+
source_hint: null,
|
|
129
|
+
created_at: new Date().toISOString()
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
// --- Project & Sharing Management ---
|
|
134
|
+
getProjects() {
|
|
135
|
+
return this.db.prepare('SELECT * FROM projects ORDER BY created_at ASC').all();
|
|
136
|
+
}
|
|
137
|
+
getSharing() {
|
|
138
|
+
return this.db.prepare('SELECT * FROM project_sharing ORDER BY source_project_id').all();
|
|
139
|
+
}
|
|
140
|
+
upsertSharing(source, target, direction, enabled) {
|
|
141
|
+
this.db.prepare(`
|
|
142
|
+
INSERT INTO project_sharing (source_project_id, target_project_id, direction, enabled)
|
|
143
|
+
VALUES (@source, @target, @direction, @enabled)
|
|
144
|
+
ON CONFLICT(source_project_id, target_project_id)
|
|
145
|
+
DO UPDATE SET direction = @direction, enabled = @enabled
|
|
146
|
+
`).run({ source, target, direction: direction, enabled: enabled ? 1 : 0 });
|
|
147
|
+
}
|
|
148
|
+
deleteSharing(source, target) {
|
|
149
|
+
this.db.prepare('DELETE FROM project_sharing WHERE source_project_id = ? AND target_project_id = ?')
|
|
150
|
+
.run([source, target]);
|
|
151
|
+
}
|
|
152
|
+
getAccessibleProjects() {
|
|
153
|
+
const hasRules = this.db.prepare(`
|
|
154
|
+
SELECT 1 FROM project_sharing
|
|
155
|
+
WHERE source_project_id = ? OR target_project_id = ?
|
|
156
|
+
LIMIT 1
|
|
157
|
+
`).get(this.projectId, this.projectId);
|
|
158
|
+
if (!hasRules) {
|
|
159
|
+
const all = this.db.prepare('SELECT project_id FROM projects').all();
|
|
160
|
+
const ids = new Set(all.map(r => r.project_id));
|
|
161
|
+
ids.add(this.projectId);
|
|
162
|
+
return [...ids];
|
|
163
|
+
}
|
|
164
|
+
const accessible = new Set([this.projectId]);
|
|
165
|
+
const inbound = this.db.prepare(`
|
|
166
|
+
SELECT source_project_id FROM project_sharing
|
|
167
|
+
WHERE target_project_id = ? AND enabled = 1
|
|
168
|
+
`).all(this.projectId);
|
|
169
|
+
for (const row of inbound) {
|
|
170
|
+
accessible.add(row.source_project_id);
|
|
171
|
+
}
|
|
172
|
+
const bidir = this.db.prepare(`
|
|
173
|
+
SELECT source_project_id, target_project_id FROM project_sharing
|
|
174
|
+
WHERE direction = 'bi-directional' AND enabled = 1
|
|
175
|
+
AND (source_project_id = ? OR target_project_id = ?)
|
|
176
|
+
`).all([this.projectId, this.projectId]);
|
|
177
|
+
for (const row of bidir) {
|
|
178
|
+
accessible.add(row.source_project_id);
|
|
179
|
+
accessible.add(row.target_project_id);
|
|
180
|
+
}
|
|
181
|
+
return [...accessible];
|
|
182
|
+
}
|
|
183
|
+
// --- Core Storage Methods ---
|
|
184
|
+
async saveConstraintSet(constraintSet) {
|
|
185
|
+
const statement = this.db.prepare(`
|
|
186
|
+
INSERT OR IGNORE INTO constraint_sets (constraint_set_id, atoms, summary, created_at)
|
|
187
|
+
VALUES (@constraint_set_id, @atoms, @summary, @created_at)
|
|
188
|
+
`);
|
|
189
|
+
statement.run({
|
|
190
|
+
constraint_set_id: constraintSet.constraint_set_id,
|
|
191
|
+
atoms: JSON.stringify(constraintSet.atoms),
|
|
192
|
+
summary: constraintSet.summary,
|
|
193
|
+
created_at: new Date().toISOString()
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
async getConstraintSet(id) {
|
|
197
|
+
const row = this.db
|
|
198
|
+
.prepare('SELECT constraint_set_id, atoms, summary FROM constraint_sets WHERE constraint_set_id = ?')
|
|
199
|
+
.get(id);
|
|
200
|
+
if (!row) {
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
return {
|
|
204
|
+
constraint_set_id: row.constraint_set_id,
|
|
205
|
+
atoms: JSON.parse(row.atoms),
|
|
206
|
+
summary: row.summary
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
async saveRecord(record) {
|
|
210
|
+
const statement = this.db.prepare(`
|
|
211
|
+
INSERT OR REPLACE INTO records (
|
|
212
|
+
record_id, decision_id, q_id, agent_id, domain, project_id, decision_text,
|
|
213
|
+
constraint_set_id, refs, status, supersedes_id, timestamp, record_json
|
|
214
|
+
)
|
|
215
|
+
VALUES (
|
|
216
|
+
@record_id, @decision_id, @q_id, @agent_id, @domain, @project_id, @decision_text,
|
|
217
|
+
@constraint_set_id, @refs, @status, @supersedes_id, @timestamp, @record_json
|
|
218
|
+
)
|
|
219
|
+
`);
|
|
220
|
+
const enrichedRecord = { ...record, project_id: this.projectId };
|
|
221
|
+
statement.run({
|
|
222
|
+
record_id: record.decision_id,
|
|
223
|
+
decision_id: record.decision_id,
|
|
224
|
+
q_id: record.q_id,
|
|
225
|
+
agent_id: record.agent_id,
|
|
226
|
+
domain: record.domain,
|
|
227
|
+
project_id: this.projectId,
|
|
228
|
+
decision_text: record.decision_text,
|
|
229
|
+
constraint_set_id: record.constraint_set_id,
|
|
230
|
+
refs: JSON.stringify(record.refs),
|
|
231
|
+
status: record.status,
|
|
232
|
+
supersedes_id: record.supersedes_id ?? null,
|
|
233
|
+
timestamp: record.timestamp,
|
|
234
|
+
record_json: JSON.stringify(enrichedRecord)
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
async getRecord(recordId) {
|
|
238
|
+
const row = this.db
|
|
239
|
+
.prepare('SELECT record_json FROM records WHERE decision_id = ?')
|
|
240
|
+
.get(recordId);
|
|
241
|
+
if (!row) {
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
return JSON.parse(row.record_json);
|
|
245
|
+
}
|
|
246
|
+
async searchRecords(opts) {
|
|
247
|
+
const conditions = [];
|
|
248
|
+
const params = {};
|
|
249
|
+
if (opts.includeShared !== false) {
|
|
250
|
+
const accessible = this.getAccessibleProjects();
|
|
251
|
+
const placeholders = accessible.map((_, i) => `@proj${i}`);
|
|
252
|
+
conditions.push(`records.project_id IN (${placeholders.join(', ')})`);
|
|
253
|
+
accessible.forEach((id, i) => { params[`proj${i}`] = id; });
|
|
254
|
+
}
|
|
255
|
+
else {
|
|
256
|
+
const projId = opts.projectId || this.projectId;
|
|
257
|
+
conditions.push('records.project_id = @projectId');
|
|
258
|
+
params.projectId = projId;
|
|
259
|
+
}
|
|
260
|
+
if (opts.domain) {
|
|
261
|
+
conditions.push('records.domain = @domain');
|
|
262
|
+
params.domain = opts.domain;
|
|
263
|
+
}
|
|
264
|
+
if (opts.query) {
|
|
265
|
+
conditions.push(`(
|
|
266
|
+
LOWER(records.decision_text) LIKE @query OR
|
|
267
|
+
LOWER(records.domain) LIKE @query OR
|
|
268
|
+
LOWER(records.q_id) LIKE @query
|
|
269
|
+
)`);
|
|
270
|
+
params.query = `%${opts.query.toLowerCase()}%`;
|
|
271
|
+
}
|
|
272
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
|
273
|
+
const limitClause = opts.limit ? `LIMIT ${Math.max(1, opts.limit)}` : '';
|
|
274
|
+
const rows = this.db
|
|
275
|
+
.prepare(`SELECT records.record_json FROM records
|
|
276
|
+
${whereClause}
|
|
277
|
+
ORDER BY records.timestamp DESC
|
|
278
|
+
${limitClause}`)
|
|
279
|
+
.all(params);
|
|
280
|
+
const results = rows.map((row) => JSON.parse(row.record_json));
|
|
281
|
+
try {
|
|
282
|
+
const crossProjectHits = results.filter((r) => {
|
|
283
|
+
return r.project_id && r.project_id !== this.projectId;
|
|
284
|
+
}).length;
|
|
285
|
+
this.db.prepare(`
|
|
286
|
+
INSERT INTO search_log(query, domain, project_id, hits, cross_project_hits, searched_at)
|
|
287
|
+
VALUES(@query, @domain, @project_id, @hits, @cross_project_hits, @searched_at)
|
|
288
|
+
`).run({
|
|
289
|
+
query: opts.query || '',
|
|
290
|
+
domain: opts.domain || null,
|
|
291
|
+
project_id: this.projectId,
|
|
292
|
+
hits: results.length,
|
|
293
|
+
cross_project_hits: crossProjectHits,
|
|
294
|
+
searched_at: new Date().toISOString()
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
catch {
|
|
298
|
+
// Non-critical: don't fail search if logging fails
|
|
299
|
+
}
|
|
300
|
+
return results;
|
|
301
|
+
}
|
|
302
|
+
async getAgentDecisions(agentId, domain) {
|
|
303
|
+
const statement = domain
|
|
304
|
+
? this.db.prepare('SELECT record_json FROM records WHERE agent_id = @agentId AND domain = @domain ORDER BY timestamp DESC')
|
|
305
|
+
: this.db.prepare('SELECT record_json FROM records WHERE agent_id = @agentId ORDER BY timestamp DESC');
|
|
306
|
+
const rows = statement.all({ agentId, domain });
|
|
307
|
+
return rows.map((row) => JSON.parse(row.record_json));
|
|
308
|
+
}
|
|
309
|
+
async getCompetencyProfile(agentId) {
|
|
310
|
+
const records = await this.getAgentDecisions(agentId);
|
|
311
|
+
const domainCounts = new Map();
|
|
312
|
+
for (const record of records) {
|
|
313
|
+
const count = domainCounts.get(record.domain) ?? 0;
|
|
314
|
+
domainCounts.set(record.domain, count + 1);
|
|
315
|
+
}
|
|
316
|
+
const domains = Array.from(domainCounts.keys());
|
|
317
|
+
const strengths = [];
|
|
318
|
+
const weaknesses = [];
|
|
319
|
+
// Simply map domain frequency to strengths
|
|
320
|
+
for (const [domain, count] of domainCounts.entries()) {
|
|
321
|
+
if (count >= 5) {
|
|
322
|
+
strengths.push(domain);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return {
|
|
326
|
+
agent_id: agentId,
|
|
327
|
+
domains,
|
|
328
|
+
strengths,
|
|
329
|
+
weaknesses,
|
|
330
|
+
updated_at: new Date().toISOString()
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
exports.SQLiteStorage = SQLiteStorage;
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { CompetencyProfile, DecisionRecord, DecisionStatus } from '@learningnodes/elen-core';
|
|
2
|
+
export interface ElenConfig {
|
|
3
|
+
agentId: string;
|
|
4
|
+
projectId?: string;
|
|
5
|
+
storage?: 'memory' | 'sqlite';
|
|
6
|
+
sqlitePath?: string;
|
|
7
|
+
apiUrl?: string;
|
|
8
|
+
apiKey?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface CommitDecisionInput {
|
|
11
|
+
question: string;
|
|
12
|
+
domain: string;
|
|
13
|
+
decisionText: string;
|
|
14
|
+
constraints: string[];
|
|
15
|
+
refs?: string[];
|
|
16
|
+
status?: DecisionStatus;
|
|
17
|
+
supersedesId?: string;
|
|
18
|
+
}
|
|
19
|
+
export interface SearchOptions {
|
|
20
|
+
domain?: string;
|
|
21
|
+
projectId?: string;
|
|
22
|
+
includeShared?: boolean;
|
|
23
|
+
query?: string;
|
|
24
|
+
limit?: number;
|
|
25
|
+
}
|
|
26
|
+
export interface SearchPrecedentsOptions {
|
|
27
|
+
limit?: number;
|
|
28
|
+
}
|
|
29
|
+
export type DecisionRecordResult = DecisionRecord;
|
|
30
|
+
export type CompetencyProfileResult = CompetencyProfile;
|
package/dist/types.js
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@learningnodes/elen",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"license": "AGPL-3.0",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"build": "tsc -p tsconfig.json",
|
|
9
|
+
"test": "vitest run",
|
|
10
|
+
"lint": "tsc -p tsconfig.json --noEmit"
|
|
11
|
+
},
|
|
12
|
+
"dependencies": {
|
|
13
|
+
"@learningnodes/elen-core": "file:../core",
|
|
14
|
+
"better-sqlite3": "^11.7.0",
|
|
15
|
+
"nanoid": "^5.1.4"
|
|
16
|
+
},
|
|
17
|
+
"devDependencies": {
|
|
18
|
+
"@types/better-sqlite3": "^7.6.12",
|
|
19
|
+
"typescript": "^5.6.3",
|
|
20
|
+
"vitest": "^2.1.8"
|
|
21
|
+
}
|
|
22
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import {
|
|
2
|
+
decisionRecordSchema,
|
|
3
|
+
constraintSetSchema,
|
|
4
|
+
type DecisionRecord,
|
|
5
|
+
type ConstraintSet
|
|
6
|
+
} from '@learningnodes/elen-core';
|
|
7
|
+
import { createId, createDecisionId, createConstraintSetId } from './id';
|
|
8
|
+
import type { StorageAdapter } from './storage';
|
|
9
|
+
import type { CompetencyProfileResult, CommitDecisionInput, SearchOptions } from './types';
|
|
10
|
+
|
|
11
|
+
export class ElenClient {
|
|
12
|
+
constructor(private readonly agentId: string, private readonly storage: StorageAdapter) { }
|
|
13
|
+
|
|
14
|
+
async commitDecision(input: CommitDecisionInput): Promise<DecisionRecord> {
|
|
15
|
+
const now = new Date().toISOString();
|
|
16
|
+
|
|
17
|
+
// 1. Resolve Constraints (Deterministic Hashing server-side)
|
|
18
|
+
const constraintSetId = createConstraintSetId(input.constraints);
|
|
19
|
+
const existingConstraints = await this.storage.getConstraintSet(constraintSetId);
|
|
20
|
+
|
|
21
|
+
if (!existingConstraints) {
|
|
22
|
+
const newSet: ConstraintSet = {
|
|
23
|
+
constraint_set_id: constraintSetId,
|
|
24
|
+
atoms: input.constraints,
|
|
25
|
+
summary: `Auto-generated summary for ${input.constraints.length} constraints`
|
|
26
|
+
};
|
|
27
|
+
constraintSetSchema.parse(newSet);
|
|
28
|
+
await this.storage.saveConstraintSet(newSet);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// 2. Build the Minimal Decision Atom
|
|
32
|
+
const record: DecisionRecord = {
|
|
33
|
+
decision_id: createDecisionId(input.domain),
|
|
34
|
+
q_id: createId('q'),
|
|
35
|
+
decision_text: input.decisionText,
|
|
36
|
+
constraint_set_id: constraintSetId,
|
|
37
|
+
refs: input.refs ?? [],
|
|
38
|
+
status: input.status ?? 'active',
|
|
39
|
+
supersedes_id: input.supersedesId,
|
|
40
|
+
timestamp: now,
|
|
41
|
+
agent_id: this.agentId,
|
|
42
|
+
domain: input.domain
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
decisionRecordSchema.parse(record);
|
|
46
|
+
await this.storage.saveRecord(record);
|
|
47
|
+
|
|
48
|
+
return record;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async supersedeDecision(oldDecisionId: string, input: CommitDecisionInput): Promise<DecisionRecord> {
|
|
52
|
+
// 1. Mark old as superseded
|
|
53
|
+
const oldRecord = await this.storage.getRecord(oldDecisionId);
|
|
54
|
+
if (oldRecord) {
|
|
55
|
+
oldRecord.status = 'superseded';
|
|
56
|
+
await this.storage.saveRecord(oldRecord);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// 2. Commit new
|
|
60
|
+
return this.commitDecision({
|
|
61
|
+
...input,
|
|
62
|
+
supersedesId: oldDecisionId
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async suggest(opts: SearchOptions): Promise<Partial<DecisionRecord>[]> {
|
|
67
|
+
const fullRecords = await this.storage.searchRecords(opts);
|
|
68
|
+
|
|
69
|
+
// Pointer-first retrieval (minimal payload)
|
|
70
|
+
return fullRecords.map(r => ({
|
|
71
|
+
decision_id: r.decision_id,
|
|
72
|
+
status: r.status,
|
|
73
|
+
decision_text: r.decision_text,
|
|
74
|
+
constraint_set_id: r.constraint_set_id,
|
|
75
|
+
refs: r.refs,
|
|
76
|
+
supersedes_id: r.supersedes_id
|
|
77
|
+
}));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async expand(decisionId: string): Promise<{ record: DecisionRecord, constraints: ConstraintSet } | null> {
|
|
81
|
+
const record = await this.storage.getRecord(decisionId);
|
|
82
|
+
if (!record) return null;
|
|
83
|
+
|
|
84
|
+
const constraints = await this.storage.getConstraintSet(record.constraint_set_id);
|
|
85
|
+
if (!constraints) return null;
|
|
86
|
+
|
|
87
|
+
return { record, constraints };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async getCompetencyProfile(): Promise<CompetencyProfileResult> {
|
|
91
|
+
return this.storage.getCompetencyProfile(this.agentId);
|
|
92
|
+
}
|
|
93
|
+
}
|
package/src/id.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { randomBytes, createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
export function createId(prefix: string): string {
|
|
4
|
+
return `${prefix}-${randomBytes(8).toString('base64url').slice(0, 10)}`;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function createDecisionId(domain: string): string {
|
|
8
|
+
// Analytical Prefix: 3 chars domain + 'A' (Agent) + 'T3' (Routine Tier)
|
|
9
|
+
const d = domain.toUpperCase().replace(/[^A-Z]/g, '').padEnd(3, 'X').substring(0, 3);
|
|
10
|
+
const prefix = `${d}AT3`;
|
|
11
|
+
return `dec:${prefix}-${randomBytes(4).toString('base64url').slice(0, 6)}`;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function createConstraintSetId(atoms: string[]): string {
|
|
15
|
+
const sorted = [...atoms].sort().join('|');
|
|
16
|
+
const hash = createHash('sha256').update(sorted).digest('hex').substring(0, 8);
|
|
17
|
+
return `cs:${hash}`;
|
|
18
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { ElenClient } from './client';
|
|
2
|
+
import { InMemoryStorage, SQLiteStorage, type StorageAdapter } from './storage';
|
|
3
|
+
import type { ElenConfig, CommitDecisionInput, SearchOptions } from './types';
|
|
4
|
+
|
|
5
|
+
export class Elen {
|
|
6
|
+
private readonly client: ElenClient;
|
|
7
|
+
|
|
8
|
+
constructor(config: ElenConfig) {
|
|
9
|
+
const storage = this.createStorage(config);
|
|
10
|
+
this.client = new ElenClient(config.agentId, storage);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
private createStorage(config: ElenConfig): StorageAdapter {
|
|
14
|
+
if (config.storage === 'sqlite') {
|
|
15
|
+
return new SQLiteStorage(config.sqlitePath ?? 'elen.db', config.projectId);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
return new InMemoryStorage();
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async commitDecision(input: CommitDecisionInput) {
|
|
22
|
+
return this.client.commitDecision(input);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async supersedeDecision(oldDecisionId: string, input: CommitDecisionInput) {
|
|
26
|
+
return this.client.supersedeDecision(oldDecisionId, input);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async suggest(opts: SearchOptions) {
|
|
30
|
+
return this.client.suggest(opts);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async expand(decisionId: string) {
|
|
34
|
+
return this.client.expand(decisionId);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async getCompetencyProfile() {
|
|
38
|
+
return this.client.getCompetencyProfile();
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export * from './client';
|
|
43
|
+
export * from './id';
|
|
44
|
+
export * from './storage';
|
|
45
|
+
export * from './types';
|
package/src/shims.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
declare module 'nanoid' {
|
|
2
|
+
export function nanoid(size?: number): string;
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
declare module 'better-sqlite3' {
|
|
6
|
+
interface Statement {
|
|
7
|
+
run(params?: unknown): unknown;
|
|
8
|
+
get(...params: unknown[]): unknown;
|
|
9
|
+
all(params?: unknown): unknown[];
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
interface DatabaseInstance {
|
|
13
|
+
exec(sql: string): void;
|
|
14
|
+
prepare(sql: string): Statement;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
interface DatabaseConstructor {
|
|
18
|
+
new (path: string): DatabaseInstance;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const Database: DatabaseConstructor;
|
|
22
|
+
namespace Database {
|
|
23
|
+
export type Database = DatabaseInstance;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export default Database;
|
|
27
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { CompetencyProfile, DecisionRecord, ConstraintSet } from '@learningnodes/elen-core';
|
|
2
|
+
import type { SearchOptions } from '../types';
|
|
3
|
+
|
|
4
|
+
export interface StorageAdapter {
|
|
5
|
+
saveConstraintSet(constraintSet: ConstraintSet): Promise<void>;
|
|
6
|
+
getConstraintSet(id: string): Promise<ConstraintSet | null>;
|
|
7
|
+
saveRecord(record: DecisionRecord): Promise<void>;
|
|
8
|
+
getRecord(recordId: string): Promise<DecisionRecord | null>;
|
|
9
|
+
searchRecords(opts: SearchOptions): Promise<DecisionRecord[]>;
|
|
10
|
+
getAgentDecisions(agentId: string, domain?: string): Promise<DecisionRecord[]>;
|
|
11
|
+
getCompetencyProfile(agentId: string): Promise<CompetencyProfile>;
|
|
12
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { CompetencyProfile, ConstraintSet, DecisionRecord } from '@learningnodes/elen-core';
|
|
2
|
+
import type { SearchOptions } from '../types';
|
|
3
|
+
import type { StorageAdapter } from './interface';
|
|
4
|
+
|
|
5
|
+
export class InMemoryStorage implements StorageAdapter {
|
|
6
|
+
private readonly constraintSets = new Map<string, ConstraintSet>();
|
|
7
|
+
private readonly records = new Map<string, DecisionRecord>();
|
|
8
|
+
|
|
9
|
+
async saveConstraintSet(constraintSet: ConstraintSet): Promise<void> {
|
|
10
|
+
if (!this.constraintSets.has(constraintSet.constraint_set_id)) {
|
|
11
|
+
this.constraintSets.set(constraintSet.constraint_set_id, constraintSet);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async getConstraintSet(id: string): Promise<ConstraintSet | null> {
|
|
16
|
+
return this.constraintSets.get(id) ?? null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async saveRecord(record: DecisionRecord): Promise<void> {
|
|
20
|
+
this.records.set(record.decision_id, record);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async getRecord(recordId: string): Promise<DecisionRecord | null> {
|
|
24
|
+
return this.records.get(recordId) ?? null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async searchRecords(opts: SearchOptions): Promise<DecisionRecord[]> {
|
|
28
|
+
let results = Array.from(this.records.values());
|
|
29
|
+
|
|
30
|
+
if (opts.domain) {
|
|
31
|
+
results = results.filter((record) => record.domain === opts.domain);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (opts.query) {
|
|
35
|
+
const needle = opts.query.toLowerCase();
|
|
36
|
+
results = results.filter((record) => {
|
|
37
|
+
const haystack = [
|
|
38
|
+
record.decision_text,
|
|
39
|
+
record.domain,
|
|
40
|
+
record.q_id
|
|
41
|
+
].join(' ').toLowerCase();
|
|
42
|
+
|
|
43
|
+
return haystack.includes(needle);
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const limit = opts.limit ?? results.length;
|
|
48
|
+
|
|
49
|
+
return results.sort((a, b) => b.timestamp.localeCompare(a.timestamp)).slice(0, limit);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async getAgentDecisions(agentId: string, domain?: string): Promise<DecisionRecord[]> {
|
|
53
|
+
return Array.from(this.records.values()).filter(
|
|
54
|
+
(record) => record.agent_id === agentId && (domain ? record.domain === domain : true)
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async getCompetencyProfile(agentId: string): Promise<CompetencyProfile> {
|
|
59
|
+
const records = await this.getAgentDecisions(agentId);
|
|
60
|
+
const domainCounts = new Map<string, number>();
|
|
61
|
+
|
|
62
|
+
for (const record of records) {
|
|
63
|
+
const count = domainCounts.get(record.domain) ?? 0;
|
|
64
|
+
domainCounts.set(record.domain, count + 1);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const domains = Array.from(domainCounts.keys());
|
|
68
|
+
const strengths: string[] = [];
|
|
69
|
+
const weaknesses: string[] = [];
|
|
70
|
+
|
|
71
|
+
for (const [domain, count] of domainCounts.entries()) {
|
|
72
|
+
if (count >= 5) {
|
|
73
|
+
strengths.push(domain);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
agent_id: agentId,
|
|
79
|
+
domains,
|
|
80
|
+
strengths,
|
|
81
|
+
weaknesses,
|
|
82
|
+
updated_at: new Date().toISOString()
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
}
|