@klhapp/skillmux 1.9.2 → 1.10.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 +30 -0
- package/README.md +1 -1
- package/docs/README.md +1 -1
- package/docs/cli.md +74 -3
- package/docs/concepts.md +1 -1
- package/docs/configuration.md +52 -1
- package/docs/deployment.md +10 -6
- package/docs/getting-started.md +1 -1
- package/docs/skill-management.md +49 -0
- package/package.json +1 -1
- package/src/adapters.ts +148 -2
- package/src/cli.ts +302 -1291
- package/src/clients.ts +17 -0
- package/src/commands/audit.ts +54 -51
- package/src/commands/config.ts +11 -12
- package/src/commands/context.ts +103 -0
- package/src/commands/core.ts +5 -1
- package/src/commands/doctor.ts +76 -0
- package/src/commands/eval.ts +10 -13
- package/src/commands/init.ts +621 -0
- package/src/commands/install.ts +132 -0
- package/src/commands/local-vault.ts +60 -0
- package/src/commands/models.ts +10 -0
- package/src/commands/outdated.ts +8 -5
- package/src/commands/project.ts +37 -11
- package/src/commands/report.ts +66 -0
- package/src/commands/scan.ts +61 -0
- package/src/commands/skill.ts +32 -0
- package/src/commands/sync.ts +232 -0
- package/src/commands/target.ts +18 -6
- package/src/commands/update.ts +11 -5
- package/src/concurrency-limiter.ts +61 -0
- package/src/config-service.ts +1 -51
- package/src/config.ts +5 -0
- package/src/context.ts +8 -3
- package/src/db-audit.ts +286 -0
- package/src/db-index.ts +238 -0
- package/src/db.ts +3 -413
- package/src/global-flags.ts +46 -0
- package/src/install.ts +15 -0
- package/src/logger.ts +26 -0
- package/src/output.ts +30 -5
- package/src/redact.ts +52 -0
- package/src/router-core.ts +8 -27
- package/src/server.ts +594 -267
- package/src/toml-writer.ts +51 -0
- package/src/types.ts +7 -0
package/src/db-audit.ts
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import { Database } from "bun:sqlite";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { existsSync, mkdirSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import type { AuditCandidate, AuditRow } from "./types";
|
|
6
|
+
|
|
7
|
+
export function openAudit(stateDir: string): Database {
|
|
8
|
+
mkdirSync(stateDir, { recursive: true });
|
|
9
|
+
const db = new Database(join(stateDir, "audit.sqlite3"), { create: true });
|
|
10
|
+
// auto_vacuum only takes on an empty database, so it must precede both the
|
|
11
|
+
// journal-mode switch and any CREATE TABLE. It is what lets a retention
|
|
12
|
+
// prune reclaim space without a full VACUUM.
|
|
13
|
+
db.run("PRAGMA auto_vacuum = INCREMENTAL");
|
|
14
|
+
db.run("PRAGMA journal_mode = WAL");
|
|
15
|
+
db.run("PRAGMA busy_timeout = 2000");
|
|
16
|
+
db.run(`CREATE TABLE IF NOT EXISTS audit (
|
|
17
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
18
|
+
ts TEXT NOT NULL,
|
|
19
|
+
request_id TEXT,
|
|
20
|
+
query TEXT NOT NULL,
|
|
21
|
+
retrieval TEXT NOT NULL DEFAULT 'lexical',
|
|
22
|
+
degraded_from TEXT,
|
|
23
|
+
degradation_reason TEXT,
|
|
24
|
+
candidates TEXT NOT NULL,
|
|
25
|
+
latency_ms INTEGER NOT NULL
|
|
26
|
+
)`);
|
|
27
|
+
// CREATE TABLE IF NOT EXISTS no-ops on a table opened from before request_id
|
|
28
|
+
// existed (AC4), so add it explicitly when missing.
|
|
29
|
+
const auditColumns = new Set(
|
|
30
|
+
(db.query("PRAGMA table_info(audit)").all() as { name: string }[]).map((c) => c.name),
|
|
31
|
+
);
|
|
32
|
+
if (!auditColumns.has("request_id")) {
|
|
33
|
+
db.run("ALTER TABLE audit ADD COLUMN request_id TEXT");
|
|
34
|
+
}
|
|
35
|
+
db.run(`CREATE TABLE IF NOT EXISTS fetch (
|
|
36
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
37
|
+
ts TEXT NOT NULL,
|
|
38
|
+
skill_id TEXT NOT NULL,
|
|
39
|
+
request_id TEXT,
|
|
40
|
+
resolve_audit_id INTEGER,
|
|
41
|
+
rank_at_resolve INTEGER
|
|
42
|
+
)`);
|
|
43
|
+
db.run(`CREATE TABLE IF NOT EXISTS admin_audit (
|
|
44
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
45
|
+
ts TEXT NOT NULL,
|
|
46
|
+
changes TEXT NOT NULL,
|
|
47
|
+
resulting_revision TEXT NOT NULL,
|
|
48
|
+
row_hash TEXT NOT NULL,
|
|
49
|
+
prev_row_hash TEXT
|
|
50
|
+
)`);
|
|
51
|
+
adoptAuditFromIndex(db, stateDir);
|
|
52
|
+
return db;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Audit rows used to live in index.sqlite3. Move any that remain there into the
|
|
56
|
+
// audit store, then drop the old table so the index carries no user queries.
|
|
57
|
+
function adoptAuditFromIndex(db: Database, stateDir: string): void {
|
|
58
|
+
const indexPath = join(stateDir, "index.sqlite3");
|
|
59
|
+
if (!existsSync(indexPath)) return;
|
|
60
|
+
|
|
61
|
+
db.run("ATTACH DATABASE ? AS legacy", [indexPath]);
|
|
62
|
+
try {
|
|
63
|
+
const legacyAudit = db
|
|
64
|
+
.query("SELECT name FROM legacy.sqlite_master WHERE type = 'table' AND name = 'audit'")
|
|
65
|
+
.get();
|
|
66
|
+
if (!legacyAudit) return;
|
|
67
|
+
|
|
68
|
+
// Older audit tables predate the retrieval columns and carry outcome /
|
|
69
|
+
// degraded / selected_skill_id instead. Select what is actually there and
|
|
70
|
+
// let the canonical defaults stand in for the rest.
|
|
71
|
+
const legacyColumns = new Set(
|
|
72
|
+
(db.query("PRAGMA legacy.table_info(audit)").all() as { name: string }[]).map((c) => c.name),
|
|
73
|
+
);
|
|
74
|
+
const retrieval = legacyColumns.has("retrieval") ? "COALESCE(retrieval, 'lexical')" : "'lexical'";
|
|
75
|
+
const degradedFrom = legacyColumns.has("degraded_from") ? "degraded_from" : "NULL";
|
|
76
|
+
const degradationReason = legacyColumns.has("degradation_reason") ? "degradation_reason" : "NULL";
|
|
77
|
+
|
|
78
|
+
// SQLite commits atomically across attached databases, so the copy and the
|
|
79
|
+
// drop either both land or neither does.
|
|
80
|
+
db.transaction(() => {
|
|
81
|
+
db.run(`INSERT INTO audit (ts, query, retrieval, degraded_from, degradation_reason, candidates, latency_ms)
|
|
82
|
+
SELECT ts, query, ${retrieval}, ${degradedFrom}, ${degradationReason}, candidates, latency_ms FROM legacy.audit`);
|
|
83
|
+
db.run("DROP TABLE legacy.audit");
|
|
84
|
+
})();
|
|
85
|
+
} finally {
|
|
86
|
+
db.run("DETACH DATABASE legacy");
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface AuditInsert {
|
|
91
|
+
ts: string;
|
|
92
|
+
request_id?: string | null;
|
|
93
|
+
query: string;
|
|
94
|
+
retrieval: AuditRow["retrieval"];
|
|
95
|
+
degraded_from?: string | null;
|
|
96
|
+
degradation_reason?: string | null;
|
|
97
|
+
candidates: AuditCandidate[];
|
|
98
|
+
latency_ms: number;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function insertAudit(db: Database, row: AuditInsert): void {
|
|
102
|
+
db.run(
|
|
103
|
+
`INSERT INTO audit (ts, request_id, query, retrieval, degraded_from, degradation_reason, candidates, latency_ms)
|
|
104
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
105
|
+
[
|
|
106
|
+
row.ts,
|
|
107
|
+
row.request_id ?? null,
|
|
108
|
+
row.query,
|
|
109
|
+
row.retrieval,
|
|
110
|
+
row.degraded_from ?? null,
|
|
111
|
+
row.degradation_reason ?? null,
|
|
112
|
+
JSON.stringify(row.candidates),
|
|
113
|
+
row.latency_ms,
|
|
114
|
+
],
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Correlation lookup for AC5/AC7: looks up the resolve that produced
|
|
120
|
+
* `requestId`, or null when it names no known resolve (including malformed
|
|
121
|
+
* input, which is never validated at the boundary per AC7).
|
|
122
|
+
*/
|
|
123
|
+
export function getAuditRowByRequestId(
|
|
124
|
+
db: Database,
|
|
125
|
+
requestId: string,
|
|
126
|
+
): { id: number; candidates: AuditCandidate[] } | null {
|
|
127
|
+
const row = db
|
|
128
|
+
.query("SELECT id, candidates FROM audit WHERE request_id = ?")
|
|
129
|
+
.get(requestId) as { id: number; candidates: string } | null;
|
|
130
|
+
if (!row) return null;
|
|
131
|
+
return { id: row.id, candidates: JSON.parse(row.candidates) as AuditCandidate[] };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export interface FetchInsert {
|
|
135
|
+
ts: string;
|
|
136
|
+
skill_id: string;
|
|
137
|
+
request_id?: string | null;
|
|
138
|
+
resolve_audit_id?: number | null;
|
|
139
|
+
rank_at_resolve?: number | null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function insertFetch(db: Database, row: FetchInsert): void {
|
|
143
|
+
db.run(
|
|
144
|
+
`INSERT INTO fetch (ts, skill_id, request_id, resolve_audit_id, rank_at_resolve)
|
|
145
|
+
VALUES (?, ?, ?, ?, ?)`,
|
|
146
|
+
[
|
|
147
|
+
row.ts,
|
|
148
|
+
row.skill_id,
|
|
149
|
+
row.request_id ?? null,
|
|
150
|
+
row.resolve_audit_id ?? null,
|
|
151
|
+
row.rank_at_resolve ?? null,
|
|
152
|
+
],
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export interface PruneResult {
|
|
157
|
+
audit_deleted: number;
|
|
158
|
+
fetch_deleted: number;
|
|
159
|
+
admin_audit_deleted: number;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Deletes resolve, fetch, and admin_audit rows with ts before `cutoffIso`,
|
|
164
|
+
* each by its own timestamp; no FK ties them, so a fetch outliving its
|
|
165
|
+
* resolve row simply reads back uncorrelated (AC7's existing null path).
|
|
166
|
+
* admin_audit shares this cutoff rather than a separate retention config
|
|
167
|
+
* (AC10) — its hash chain is unaffected since pruning only ever removes the
|
|
168
|
+
* oldest rows, never rows in the middle of the chain. Reclaims the freed
|
|
169
|
+
* pages with an incremental vacuum, which only touches audit.sqlite3 (AC16).
|
|
170
|
+
*/
|
|
171
|
+
export function pruneAuditBefore(db: Database, cutoffIso: string): PruneResult {
|
|
172
|
+
const auditResult = db.run("DELETE FROM audit WHERE ts < ?", [cutoffIso]);
|
|
173
|
+
const fetchResult = db.run("DELETE FROM fetch WHERE ts < ?", [cutoffIso]);
|
|
174
|
+
const adminAuditResult = db.run("DELETE FROM admin_audit WHERE ts < ?", [cutoffIso]);
|
|
175
|
+
db.run("PRAGMA incremental_vacuum");
|
|
176
|
+
|
|
177
|
+
return {
|
|
178
|
+
audit_deleted: auditResult.changes,
|
|
179
|
+
fetch_deleted: fetchResult.changes,
|
|
180
|
+
admin_audit_deleted: adminAuditResult.changes,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** AC12: retentionDays <= 0 disables pruning entirely. */
|
|
185
|
+
export function pruneAudit(db: Database, retentionDays: number, now: Date = new Date()): PruneResult {
|
|
186
|
+
if (retentionDays <= 0) return { audit_deleted: 0, fetch_deleted: 0, admin_audit_deleted: 0 };
|
|
187
|
+
const cutoff = new Date(now.getTime() - retentionDays * 86_400_000).toISOString();
|
|
188
|
+
return pruneAuditBefore(db, cutoff);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export interface AdminAuditChange {
|
|
192
|
+
key: string;
|
|
193
|
+
old_value: unknown;
|
|
194
|
+
new_value: unknown;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export interface AdminAuditInsert {
|
|
198
|
+
ts: string;
|
|
199
|
+
changes: AdminAuditChange[];
|
|
200
|
+
resulting_revision: string;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export interface AdminAuditRow {
|
|
204
|
+
id: number;
|
|
205
|
+
ts: string;
|
|
206
|
+
changes: AdminAuditChange[];
|
|
207
|
+
resulting_revision: string;
|
|
208
|
+
row_hash: string;
|
|
209
|
+
prev_row_hash: string | null;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function computeAdminAuditRowHash(
|
|
213
|
+
prevRowHash: string | null,
|
|
214
|
+
fields: { ts: string; changes: AdminAuditChange[]; resulting_revision: string },
|
|
215
|
+
): string {
|
|
216
|
+
const payload = JSON.stringify({ prev_row_hash: prevRowHash, ...fields });
|
|
217
|
+
return createHash("sha256").update(payload).digest("hex");
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Appends one tamper-evident admin_audit row, chaining its hash to the
|
|
222
|
+
* previous row's hash (or null for the first row) so any out-of-band
|
|
223
|
+
* edit/delete breaks the chain — see verifyAdminAuditChain.
|
|
224
|
+
*/
|
|
225
|
+
export function insertAdminAuditRow(db: Database, row: AdminAuditInsert): AdminAuditRow {
|
|
226
|
+
const prevRow = db
|
|
227
|
+
.query("SELECT row_hash FROM admin_audit ORDER BY id DESC LIMIT 1")
|
|
228
|
+
.get() as { row_hash: string } | null;
|
|
229
|
+
const prevRowHash = prevRow?.row_hash ?? null;
|
|
230
|
+
const rowHash = computeAdminAuditRowHash(prevRowHash, row);
|
|
231
|
+
|
|
232
|
+
db.run(
|
|
233
|
+
`INSERT INTO admin_audit (ts, changes, resulting_revision, row_hash, prev_row_hash)
|
|
234
|
+
VALUES (?, ?, ?, ?, ?)`,
|
|
235
|
+
[row.ts, JSON.stringify(row.changes), row.resulting_revision, rowHash, prevRowHash],
|
|
236
|
+
);
|
|
237
|
+
|
|
238
|
+
const inserted = db.query("SELECT last_insert_rowid() AS id").get() as { id: number };
|
|
239
|
+
return {
|
|
240
|
+
id: inserted.id,
|
|
241
|
+
ts: row.ts,
|
|
242
|
+
changes: row.changes,
|
|
243
|
+
resulting_revision: row.resulting_revision,
|
|
244
|
+
row_hash: rowHash,
|
|
245
|
+
prev_row_hash: prevRowHash,
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export interface AdminAuditChainResult {
|
|
250
|
+
valid: boolean;
|
|
251
|
+
broken_at_id: number | null;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Walks admin_audit in insertion order and reports whether the hash chain is unbroken. */
|
|
255
|
+
export function verifyAdminAuditChain(db: Database): AdminAuditChainResult {
|
|
256
|
+
const rows = db
|
|
257
|
+
.query("SELECT id, ts, changes, resulting_revision, row_hash, prev_row_hash FROM admin_audit ORDER BY id ASC")
|
|
258
|
+
.all() as { id: number; ts: string; changes: string; resulting_revision: string; row_hash: string; prev_row_hash: string | null }[];
|
|
259
|
+
|
|
260
|
+
let expectedPrevHash: string | null = null;
|
|
261
|
+
for (const row of rows) {
|
|
262
|
+
if (row.prev_row_hash !== expectedPrevHash) {
|
|
263
|
+
return { valid: false, broken_at_id: row.id };
|
|
264
|
+
}
|
|
265
|
+
const recomputed = computeAdminAuditRowHash(expectedPrevHash, {
|
|
266
|
+
ts: row.ts,
|
|
267
|
+
changes: JSON.parse(row.changes),
|
|
268
|
+
resulting_revision: row.resulting_revision,
|
|
269
|
+
});
|
|
270
|
+
if (recomputed !== row.row_hash) {
|
|
271
|
+
return { valid: false, broken_at_id: row.id };
|
|
272
|
+
}
|
|
273
|
+
expectedPrevHash = row.row_hash;
|
|
274
|
+
}
|
|
275
|
+
return { valid: true, broken_at_id: null };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Dry-run counterpart of pruneAuditBefore: counts without deleting (AC15). */
|
|
279
|
+
export function countPrunable(db: Database, cutoffIso: string): PruneResult {
|
|
280
|
+
const auditRow = db.query("SELECT count(*) AS n FROM audit WHERE ts < ?").get(cutoffIso) as { n: number };
|
|
281
|
+
const fetchRow = db.query("SELECT count(*) AS n FROM fetch WHERE ts < ?").get(cutoffIso) as { n: number };
|
|
282
|
+
const adminAuditRow = db
|
|
283
|
+
.query("SELECT count(*) AS n FROM admin_audit WHERE ts < ?")
|
|
284
|
+
.get(cutoffIso) as { n: number };
|
|
285
|
+
return { audit_deleted: auditRow.n, fetch_deleted: fetchRow.n, admin_audit_deleted: adminAuditRow.n };
|
|
286
|
+
}
|
package/src/db-index.ts
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { Database } from "bun:sqlite";
|
|
2
|
+
import { mkdirSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { VaultSkill } from "./vault";
|
|
5
|
+
|
|
6
|
+
export interface SkillRow {
|
|
7
|
+
skill_id: string;
|
|
8
|
+
title: string;
|
|
9
|
+
description: string;
|
|
10
|
+
aliases: string;
|
|
11
|
+
content_sha256: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function openIndex(stateDir: string): Database {
|
|
15
|
+
mkdirSync(stateDir, { recursive: true });
|
|
16
|
+
const db = new Database(join(stateDir, "index.sqlite3"), { create: true });
|
|
17
|
+
db.run("PRAGMA journal_mode = WAL");
|
|
18
|
+
db.run("PRAGMA busy_timeout = 2000");
|
|
19
|
+
db.run(`CREATE TABLE IF NOT EXISTS skills (
|
|
20
|
+
skill_id TEXT PRIMARY KEY,
|
|
21
|
+
title TEXT NOT NULL,
|
|
22
|
+
description TEXT NOT NULL,
|
|
23
|
+
aliases TEXT NOT NULL,
|
|
24
|
+
content_sha256 TEXT NOT NULL
|
|
25
|
+
)`);
|
|
26
|
+
db.run(`CREATE VIRTUAL TABLE IF NOT EXISTS skills_fts USING fts5(
|
|
27
|
+
skill_id UNINDEXED, title, description, aliases,
|
|
28
|
+
tokenize = 'unicode61 remove_diacritics 2'
|
|
29
|
+
)`);
|
|
30
|
+
db.run(`CREATE TABLE IF NOT EXISTS vectors (
|
|
31
|
+
skill_id TEXT PRIMARY KEY,
|
|
32
|
+
content_sha256 TEXT NOT NULL,
|
|
33
|
+
embedding_fingerprint TEXT NOT NULL DEFAULT '',
|
|
34
|
+
dim INTEGER NOT NULL,
|
|
35
|
+
vec BLOB NOT NULL
|
|
36
|
+
)`);
|
|
37
|
+
const vectorColumns = db.query("PRAGMA table_info(vectors)").all() as { name: string }[];
|
|
38
|
+
if (!vectorColumns.some((column) => column.name === "embedding_fingerprint")) {
|
|
39
|
+
db.run("ALTER TABLE vectors ADD COLUMN embedding_fingerprint TEXT NOT NULL DEFAULT ''");
|
|
40
|
+
}
|
|
41
|
+
// Audit rows live in audit.sqlite3; openAudit adopts any left here.
|
|
42
|
+
db.run(`CREATE TABLE IF NOT EXISTS index_meta (
|
|
43
|
+
key TEXT PRIMARY KEY,
|
|
44
|
+
value TEXT NOT NULL
|
|
45
|
+
)`);
|
|
46
|
+
return db;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function upsertSkill(db: Database, skill: VaultSkill): void {
|
|
50
|
+
const aliases = skill.aliases.join(" ");
|
|
51
|
+
db.transaction(() => {
|
|
52
|
+
db.run("DELETE FROM skills WHERE skill_id = ?", [skill.skill_id]);
|
|
53
|
+
db.run("DELETE FROM skills_fts WHERE skill_id = ?", [skill.skill_id]);
|
|
54
|
+
db.run(
|
|
55
|
+
"INSERT INTO skills (skill_id, title, description, aliases, content_sha256) VALUES (?, ?, ?, ?, ?)",
|
|
56
|
+
[skill.skill_id, skill.title, skill.description, aliases, skill.content_sha256],
|
|
57
|
+
);
|
|
58
|
+
db.run(
|
|
59
|
+
"INSERT INTO skills_fts (skill_id, title, description, aliases) VALUES (?, ?, ?, ?)",
|
|
60
|
+
[skill.skill_id, skill.title, skill.description, aliases],
|
|
61
|
+
);
|
|
62
|
+
})();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function toSkillRow(skill: VaultSkill): SkillRow {
|
|
66
|
+
return {
|
|
67
|
+
skill_id: skill.skill_id,
|
|
68
|
+
title: skill.title,
|
|
69
|
+
description: skill.description,
|
|
70
|
+
aliases: skill.aliases.join(" "),
|
|
71
|
+
content_sha256: skill.content_sha256,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Replace the whole lexical index with `rows`; drops vectors of removed skills. */
|
|
76
|
+
export function replaceSkills(db: Database, rows: SkillRow[]): void {
|
|
77
|
+
db.transaction(() => {
|
|
78
|
+
db.run("DELETE FROM skills");
|
|
79
|
+
db.run("DELETE FROM skills_fts");
|
|
80
|
+
for (const row of rows) {
|
|
81
|
+
db.run(
|
|
82
|
+
"INSERT INTO skills (skill_id, title, description, aliases, content_sha256) VALUES (?, ?, ?, ?, ?)",
|
|
83
|
+
[row.skill_id, row.title, row.description, row.aliases, row.content_sha256],
|
|
84
|
+
);
|
|
85
|
+
db.run(
|
|
86
|
+
"INSERT INTO skills_fts (skill_id, title, description, aliases) VALUES (?, ?, ?, ?)",
|
|
87
|
+
[row.skill_id, row.title, row.description, row.aliases],
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
db.run("DELETE FROM vectors WHERE skill_id NOT IN (SELECT skill_id FROM skills)");
|
|
91
|
+
})();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function ingestVault(db: Database, skills: VaultSkill[]): void {
|
|
95
|
+
replaceSkills(db, skills.map(toSkillRow));
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function deleteSkill(db: Database, skillId: string): void {
|
|
99
|
+
db.transaction(() => {
|
|
100
|
+
db.run("DELETE FROM skills WHERE skill_id = ?", [skillId]);
|
|
101
|
+
db.run("DELETE FROM skills_fts WHERE skill_id = ?", [skillId]);
|
|
102
|
+
db.run("DELETE FROM vectors WHERE skill_id = ?", [skillId]);
|
|
103
|
+
})();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function skillCount(db: Database): number {
|
|
107
|
+
return (db.query("SELECT count(*) AS n FROM skills").get() as { n: number }).n;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function getSkillRow(db: Database, skillId: string): SkillRow | null {
|
|
111
|
+
return db.query("SELECT * FROM skills WHERE skill_id = ?").get(skillId) as SkillRow | null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Sanitize free text into an FTS5 OR-query; returns null when no usable terms
|
|
116
|
+
* remain. Terms keep any Unicode letters/digits (CJK included) so non-ASCII
|
|
117
|
+
* queries still get lexical recall — unicode61 tokenizes contiguous CJK runs
|
|
118
|
+
* as single tokens, so matching works at that granularity.
|
|
119
|
+
*/
|
|
120
|
+
export function toFtsQuery(text: string): string | null {
|
|
121
|
+
const terms = [
|
|
122
|
+
...new Set(
|
|
123
|
+
text
|
|
124
|
+
.toLowerCase()
|
|
125
|
+
.split(/[^\p{L}\p{N}]+/u)
|
|
126
|
+
.filter((t) => t.length >= 2),
|
|
127
|
+
),
|
|
128
|
+
];
|
|
129
|
+
if (terms.length === 0) return null;
|
|
130
|
+
return terms.map((t) => `"${t}"`).join(" OR ");
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function ftsSearch(db: Database, text: string, k: number): SkillRow[] {
|
|
134
|
+
const query = toFtsQuery(text);
|
|
135
|
+
if (query === null) return [];
|
|
136
|
+
return db
|
|
137
|
+
.query(
|
|
138
|
+
`SELECT s.* FROM skills_fts f
|
|
139
|
+
JOIN skills s ON s.skill_id = f.skill_id
|
|
140
|
+
WHERE skills_fts MATCH ?
|
|
141
|
+
ORDER BY bm25(skills_fts) LIMIT ?`,
|
|
142
|
+
)
|
|
143
|
+
.all(query, k) as SkillRow[];
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function findExactMatch(db: Database, query: string): SkillRow | null {
|
|
147
|
+
const cleanQuery = query.trim().toLowerCase();
|
|
148
|
+
return db
|
|
149
|
+
.query(
|
|
150
|
+
`SELECT * FROM skills
|
|
151
|
+
WHERE lower(skill_id) = ?
|
|
152
|
+
OR lower(title) = ?
|
|
153
|
+
OR ' ' || lower(aliases) || ' ' LIKE ?`,
|
|
154
|
+
)
|
|
155
|
+
.get(cleanQuery, cleanQuery, `% ${cleanQuery} %`) as SkillRow | null;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function getIndexMeta(db: Database, key: string): string | null {
|
|
159
|
+
const row = db
|
|
160
|
+
.query("SELECT value FROM index_meta WHERE key = ?")
|
|
161
|
+
.get(key) as { value: string } | null;
|
|
162
|
+
return row ? row.value : null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function setIndexMeta(db: Database, key: string, value: string): void {
|
|
166
|
+
db.run(
|
|
167
|
+
`INSERT INTO index_meta (key, value) VALUES (?, ?)
|
|
168
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
|
|
169
|
+
[key, value],
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function upsertVector(
|
|
174
|
+
db: Database,
|
|
175
|
+
skillId: string,
|
|
176
|
+
contentSha256: string,
|
|
177
|
+
embeddingFingerprint: string,
|
|
178
|
+
vec: Float32Array,
|
|
179
|
+
): void {
|
|
180
|
+
db.run(
|
|
181
|
+
`INSERT INTO vectors (skill_id, content_sha256, embedding_fingerprint, dim, vec) VALUES (?, ?, ?, ?, ?)
|
|
182
|
+
ON CONFLICT(skill_id) DO UPDATE SET
|
|
183
|
+
content_sha256 = excluded.content_sha256,
|
|
184
|
+
embedding_fingerprint = excluded.embedding_fingerprint,
|
|
185
|
+
dim = excluded.dim,
|
|
186
|
+
vec = excluded.vec`,
|
|
187
|
+
[skillId, contentSha256, embeddingFingerprint, vec.length, new Uint8Array(vec.buffer, vec.byteOffset, vec.byteLength)],
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Skills with no usable stored vector: none at all, content changed since
|
|
193
|
+
* embedding, or embedded at a different dimension than currently configured.
|
|
194
|
+
*/
|
|
195
|
+
export function skillsNeedingVectors(db: Database, dimension: number, embeddingFingerprint: string): SkillRow[] {
|
|
196
|
+
return db
|
|
197
|
+
.query(
|
|
198
|
+
`SELECT s.* FROM skills s
|
|
199
|
+
LEFT JOIN vectors v ON v.skill_id = s.skill_id
|
|
200
|
+
AND v.content_sha256 = s.content_sha256
|
|
201
|
+
AND v.dim = ?
|
|
202
|
+
AND v.embedding_fingerprint = ?
|
|
203
|
+
WHERE v.skill_id IS NULL`,
|
|
204
|
+
)
|
|
205
|
+
.all(dimension, embeddingFingerprint) as SkillRow[];
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function cosine(a: Float32Array, b: Float32Array): number {
|
|
209
|
+
if (a.length !== b.length) return 0;
|
|
210
|
+
let dot = 0;
|
|
211
|
+
let normA = 0;
|
|
212
|
+
let normB = 0;
|
|
213
|
+
for (let i = 0; i < a.length; i++) {
|
|
214
|
+
dot += a[i]! * b[i]!;
|
|
215
|
+
normA += a[i]! * a[i]!;
|
|
216
|
+
normB += b[i]! * b[i]!;
|
|
217
|
+
}
|
|
218
|
+
if (normA === 0 || normB === 0) return 0;
|
|
219
|
+
return dot / (Math.sqrt(normA) * Math.sqrt(normB));
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Brute-force cosine over every stored vector (vault is ~100 skills; no ANN). */
|
|
223
|
+
export function vectorTopK(db: Database, query: Float32Array, k: number): SkillRow[] {
|
|
224
|
+
const rows = db
|
|
225
|
+
.query(
|
|
226
|
+
`SELECT s.skill_id, s.title, s.description, s.aliases, s.content_sha256, v.vec
|
|
227
|
+
FROM vectors v JOIN skills s ON s.skill_id = v.skill_id`,
|
|
228
|
+
)
|
|
229
|
+
.all() as (SkillRow & { vec: Uint8Array })[];
|
|
230
|
+
return rows
|
|
231
|
+
.map(({ vec, ...row }) => ({
|
|
232
|
+
row,
|
|
233
|
+
score: cosine(query, new Float32Array(vec.buffer, vec.byteOffset, vec.byteLength / 4)),
|
|
234
|
+
}))
|
|
235
|
+
.sort((a, b) => b.score - a.score)
|
|
236
|
+
.slice(0, k)
|
|
237
|
+
.map((r) => r.row);
|
|
238
|
+
}
|