claude-mem-lite 4.0.4 → 5.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +18 -72
- package/README.zh-CN.md +24 -74
- package/adopt-content.mjs +0 -1
- package/cli/common.mjs +0 -17
- package/cli.mjs +19 -3
- package/commands/mem.md +3 -3
- package/commands/update.md +5 -12
- package/format-utils.mjs +0 -21
- package/haiku-client.mjs +36 -5
- package/hash-utils.mjs +21 -0
- package/hook-episode.mjs +7 -1
- package/hook-optimize.mjs +103 -50
- package/hook-shared.mjs +8 -2
- package/hook-update.mjs +56 -14
- package/hook.mjs +21 -29
- package/hooks/hooks.json +0 -10
- package/install.mjs +100 -678
- package/lib/atomic-write.mjs +16 -0
- package/lib/deferred-work.mjs +7 -3
- package/lib/doctor-drift.mjs +0 -1
- package/lib/frontmatter.mjs +1 -2
- package/lib/get-core.mjs +27 -1
- package/lib/hook-prune.mjs +133 -0
- package/lib/hook-stdin.mjs +1 -1
- package/lib/hook-telemetry.mjs +1 -1
- package/lib/install-shape.mjs +45 -4
- package/lib/maintain-core.mjs +9 -0
- package/lib/metrics.mjs +2 -2
- package/lib/proc-lock.mjs +111 -13
- package/lib/proxy-fetch.mjs +26 -2
- package/lib/scrub-record.mjs +8 -0
- package/lib/shard-gc.mjs +11 -7
- package/lib/tmp-fixture-sweep.mjs +9 -0
- package/mem-cli.mjs +46 -434
- package/nlp.mjs +1 -1
- package/npm-shrinkwrap.json +6 -2
- package/package.json +9 -16
- package/project-utils.mjs +43 -15
- package/schema.mjs +112 -50
- package/scripts/hook-launcher.mjs +9 -3
- package/scripts/prompt-search-utils.mjs +0 -30
- package/scripts/setup.sh +5 -0
- package/scripts/user-prompt-search.js +3 -125
- package/secret-scrub.mjs +32 -3
- package/server.mjs +19 -451
- package/source-files.mjs +12 -29
- package/synonyms.mjs +2 -1
- package/tool-schemas.mjs +23 -91
- package/utils.mjs +5 -13
- package/commands/tools.md +0 -67
- package/install-metadata.mjs +0 -2193
- package/lib/registry-core.mjs +0 -264
- package/registry/preinstalled.json +0 -2419
- package/registry-enricher.mjs +0 -124
- package/registry-github.mjs +0 -86
- package/registry-importer.mjs +0 -569
- package/registry-recommend.mjs +0 -503
- package/registry-retriever.mjs +0 -611
- package/registry-scanner.mjs +0 -261
- package/registry.mjs +0 -665
- package/resource-discovery.mjs +0 -199
- package/scripts/pre-skill-bridge.js +0 -146
package/registry.mjs
DELETED
|
@@ -1,665 +0,0 @@
|
|
|
1
|
-
// claude-mem-lite: Resource registry database schema and CRUD operations
|
|
2
|
-
// Independent from schema.mjs (memory DB) — uses separate resource-registry.db
|
|
3
|
-
|
|
4
|
-
import Database from 'better-sqlite3';
|
|
5
|
-
import { existsSync, mkdirSync } from 'fs';
|
|
6
|
-
import { dirname } from 'path';
|
|
7
|
-
import { debugCatch, truncate } from './utils.mjs';
|
|
8
|
-
|
|
9
|
-
// ─── Schema ──────────────────────────────────────────────────────────────────
|
|
10
|
-
|
|
11
|
-
const RESOURCES_SCHEMA = `
|
|
12
|
-
CREATE TABLE IF NOT EXISTS resources (
|
|
13
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
14
|
-
name TEXT NOT NULL,
|
|
15
|
-
type TEXT NOT NULL CHECK(type IN ('skill','agent')),
|
|
16
|
-
status TEXT NOT NULL DEFAULT 'active'
|
|
17
|
-
CHECK(status IN ('active','disabled','error','indexing')),
|
|
18
|
-
source TEXT NOT NULL CHECK(source IN ('preinstalled','user','github')),
|
|
19
|
-
repo_url TEXT,
|
|
20
|
-
repo_stars INTEGER DEFAULT 0,
|
|
21
|
-
local_path TEXT NOT NULL,
|
|
22
|
-
file_hash TEXT,
|
|
23
|
-
parent_plugin TEXT, -- unused, kept for schema compat
|
|
24
|
-
invocation_name TEXT DEFAULT '',
|
|
25
|
-
intent_tags TEXT DEFAULT '',
|
|
26
|
-
domain_tags TEXT DEFAULT '',
|
|
27
|
-
action_type TEXT DEFAULT '',
|
|
28
|
-
trigger_patterns TEXT DEFAULT '',
|
|
29
|
-
capability_summary TEXT DEFAULT '',
|
|
30
|
-
input_type TEXT DEFAULT '',
|
|
31
|
-
output_type TEXT DEFAULT '',
|
|
32
|
-
prerequisites TEXT DEFAULT '{}',
|
|
33
|
-
keywords TEXT DEFAULT '',
|
|
34
|
-
tech_stack TEXT DEFAULT '',
|
|
35
|
-
use_cases TEXT DEFAULT '',
|
|
36
|
-
complexity TEXT DEFAULT 'intermediate',
|
|
37
|
-
category TEXT,
|
|
38
|
-
quality_tier TEXT DEFAULT 'community',
|
|
39
|
-
popularity_score REAL DEFAULT 0,
|
|
40
|
-
personal_score REAL DEFAULT 0,
|
|
41
|
-
recommend_count INTEGER DEFAULT 0,
|
|
42
|
-
adopt_count INTEGER DEFAULT 0,
|
|
43
|
-
weighted_adopt_sum REAL DEFAULT 0,
|
|
44
|
-
success_count INTEGER DEFAULT 0,
|
|
45
|
-
silenced_until TEXT,
|
|
46
|
-
cooldown_hours INTEGER DEFAULT 0,
|
|
47
|
-
recommendation_mode TEXT DEFAULT 'proactive',
|
|
48
|
-
indexed_at TEXT,
|
|
49
|
-
created_at TEXT DEFAULT (datetime('now')),
|
|
50
|
-
updated_at TEXT DEFAULT (datetime('now')),
|
|
51
|
-
enrichment_status TEXT DEFAULT NULL,
|
|
52
|
-
enriched_at INTEGER DEFAULT NULL,
|
|
53
|
-
repo_updated_at TEXT DEFAULT NULL,
|
|
54
|
-
repo_forks INTEGER DEFAULT 0
|
|
55
|
-
);
|
|
56
|
-
|
|
57
|
-
CREATE UNIQUE INDEX IF NOT EXISTS idx_res_type_name
|
|
58
|
-
ON resources(type, name);
|
|
59
|
-
|
|
60
|
-
CREATE INDEX IF NOT EXISTS idx_res_status
|
|
61
|
-
ON resources(status) WHERE status = 'active';
|
|
62
|
-
`;
|
|
63
|
-
|
|
64
|
-
// Canonical FTS5 column order — all consumers must use this order.
|
|
65
|
-
// BM25 weights (positional): trigger_patterns(3), keywords(3), capability_summary(3),
|
|
66
|
-
// intent_tags(2), use_cases(2), domain_tags(1), tech_stack(1), name(1)
|
|
67
|
-
// — must match the bm25(resources_fts, 3,3,3,2,2,1,1,1) call in COMPOSITE_EXPR.
|
|
68
|
-
const FTS5_SCHEMA = `
|
|
69
|
-
CREATE VIRTUAL TABLE IF NOT EXISTS resources_fts USING fts5(
|
|
70
|
-
trigger_patterns,
|
|
71
|
-
keywords,
|
|
72
|
-
capability_summary,
|
|
73
|
-
intent_tags,
|
|
74
|
-
use_cases,
|
|
75
|
-
domain_tags,
|
|
76
|
-
tech_stack,
|
|
77
|
-
name,
|
|
78
|
-
content=resources,
|
|
79
|
-
content_rowid=id,
|
|
80
|
-
tokenize='unicode61 remove_diacritics 2'
|
|
81
|
-
);
|
|
82
|
-
`;
|
|
83
|
-
|
|
84
|
-
const TRIGGERS_SCHEMA = `
|
|
85
|
-
CREATE TRIGGER IF NOT EXISTS res_fts_insert AFTER INSERT ON resources BEGIN
|
|
86
|
-
INSERT INTO resources_fts(rowid, trigger_patterns, keywords, capability_summary,
|
|
87
|
-
intent_tags, use_cases, domain_tags, tech_stack, name)
|
|
88
|
-
VALUES (NEW.id, NEW.trigger_patterns, NEW.keywords, NEW.capability_summary,
|
|
89
|
-
NEW.intent_tags, NEW.use_cases, NEW.domain_tags, NEW.tech_stack, NEW.name);
|
|
90
|
-
END;
|
|
91
|
-
|
|
92
|
-
CREATE TRIGGER IF NOT EXISTS res_fts_update AFTER UPDATE ON resources BEGIN
|
|
93
|
-
INSERT INTO resources_fts(resources_fts, rowid, trigger_patterns, keywords,
|
|
94
|
-
capability_summary, intent_tags, use_cases, domain_tags, tech_stack, name)
|
|
95
|
-
VALUES ('delete', OLD.id, OLD.trigger_patterns, OLD.keywords, OLD.capability_summary,
|
|
96
|
-
OLD.intent_tags, OLD.use_cases, OLD.domain_tags, OLD.tech_stack, OLD.name);
|
|
97
|
-
INSERT INTO resources_fts(rowid, trigger_patterns, keywords, capability_summary,
|
|
98
|
-
intent_tags, use_cases, domain_tags, tech_stack, name)
|
|
99
|
-
VALUES (NEW.id, NEW.trigger_patterns, NEW.keywords, NEW.capability_summary,
|
|
100
|
-
NEW.intent_tags, NEW.use_cases, NEW.domain_tags, NEW.tech_stack, NEW.name);
|
|
101
|
-
END;
|
|
102
|
-
|
|
103
|
-
CREATE TRIGGER IF NOT EXISTS res_fts_delete AFTER DELETE ON resources BEGIN
|
|
104
|
-
INSERT INTO resources_fts(resources_fts, rowid, trigger_patterns, keywords,
|
|
105
|
-
capability_summary, intent_tags, use_cases, domain_tags, tech_stack, name)
|
|
106
|
-
VALUES ('delete', OLD.id, OLD.trigger_patterns, OLD.keywords, OLD.capability_summary,
|
|
107
|
-
OLD.intent_tags, OLD.use_cases, OLD.domain_tags, OLD.tech_stack, OLD.name);
|
|
108
|
-
END;
|
|
109
|
-
`;
|
|
110
|
-
|
|
111
|
-
const INVOCATIONS_SCHEMA = `
|
|
112
|
-
CREATE TABLE IF NOT EXISTS invocations (
|
|
113
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
114
|
-
resource_id INTEGER NOT NULL REFERENCES resources(id) ON DELETE CASCADE,
|
|
115
|
-
session_id TEXT,
|
|
116
|
-
trigger TEXT CHECK(trigger IN ('session_start','pre_tool_use','user_explicit','user_prompt')),
|
|
117
|
-
tier INTEGER CHECK(tier IN (1,2,3)),
|
|
118
|
-
recommended INTEGER DEFAULT 1,
|
|
119
|
-
adopted INTEGER DEFAULT 0,
|
|
120
|
-
outcome TEXT CHECK(outcome IN ('success','partial','failure','skipped','ignored') OR outcome IS NULL),
|
|
121
|
-
score REAL,
|
|
122
|
-
rejection_reason TEXT CHECK(rejection_reason IN ('alternative','manual','context_switch','session_end','unknown','no_events','unclassified') OR rejection_reason IS NULL),
|
|
123
|
-
created_at TEXT DEFAULT (datetime('now'))
|
|
124
|
-
);
|
|
125
|
-
|
|
126
|
-
CREATE INDEX IF NOT EXISTS idx_inv_resource
|
|
127
|
-
ON invocations(resource_id, created_at);
|
|
128
|
-
|
|
129
|
-
CREATE INDEX IF NOT EXISTS idx_inv_session
|
|
130
|
-
ON invocations(session_id);
|
|
131
|
-
|
|
132
|
-
CREATE INDEX IF NOT EXISTS idx_inv_created_at
|
|
133
|
-
ON invocations(created_at);
|
|
134
|
-
`;
|
|
135
|
-
|
|
136
|
-
// Canonical indexed-column list for resources_fts, in FTS5_SCHEMA order (see the BM25
|
|
137
|
-
// weight note above — order is load-bearing). Drift from this list triggers a rebuild.
|
|
138
|
-
const FTS5_COLUMNS = [
|
|
139
|
-
'trigger_patterns',
|
|
140
|
-
'keywords',
|
|
141
|
-
'capability_summary',
|
|
142
|
-
'intent_tags',
|
|
143
|
-
'use_cases',
|
|
144
|
-
'domain_tags',
|
|
145
|
-
'tech_stack',
|
|
146
|
-
'name',
|
|
147
|
-
];
|
|
148
|
-
|
|
149
|
-
const PREINSTALLED_SCHEMA = `
|
|
150
|
-
CREATE TABLE IF NOT EXISTS preinstalled (
|
|
151
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
152
|
-
name TEXT NOT NULL,
|
|
153
|
-
type TEXT NOT NULL CHECK(type IN ('skill','agent')),
|
|
154
|
-
repo_url TEXT NOT NULL,
|
|
155
|
-
repo_path TEXT DEFAULT '',
|
|
156
|
-
stars INTEGER DEFAULT 0,
|
|
157
|
-
tags TEXT DEFAULT '[]',
|
|
158
|
-
enabled INTEGER DEFAULT 1,
|
|
159
|
-
cloned_at TEXT,
|
|
160
|
-
clone_hash TEXT,
|
|
161
|
-
created_at TEXT DEFAULT (datetime('now'))
|
|
162
|
-
);
|
|
163
|
-
|
|
164
|
-
CREATE UNIQUE INDEX IF NOT EXISTS idx_pre_type_name
|
|
165
|
-
ON preinstalled(type, name);
|
|
166
|
-
`;
|
|
167
|
-
|
|
168
|
-
// ─── Schema version ──────────────────────────────────────────────────────────
|
|
169
|
-
|
|
170
|
-
// Registry DB schema version. Tracked independently of schema.mjs's
|
|
171
|
-
// CURRENT_SCHEMA_VERSION — resource-registry.db is a separate file with its own
|
|
172
|
-
// migration history. v1 = the shape at the time version tracking was introduced; every
|
|
173
|
-
// pre-existing (un-versioned) registry in the wild ADOPTS v1 on first open, keeping its
|
|
174
|
-
// data. Bump when a migration below changes a layout an older binary would mis-handle.
|
|
175
|
-
export const REGISTRY_SCHEMA_VERSION = 1;
|
|
176
|
-
|
|
177
|
-
/**
|
|
178
|
-
* Forward-incompatibility guard, mirroring initSchema's in schema.mjs. If a NEWER
|
|
179
|
-
* claude-mem-lite wrote this registry, this (older) build re-applying its own migrations
|
|
180
|
-
* over the newer layout corrupts it silently. Throw instead. MUST run before any DDL so
|
|
181
|
-
* a newer DB is left untouched.
|
|
182
|
-
* @param {Database} db
|
|
183
|
-
*/
|
|
184
|
-
function assertRegistryNotNewer(db) {
|
|
185
|
-
let row;
|
|
186
|
-
try {
|
|
187
|
-
row = db.prepare('SELECT version FROM schema_version LIMIT 1').get();
|
|
188
|
-
} catch {
|
|
189
|
-
return; // table absent = pre-version DB → adopted (stamped) at the end of init
|
|
190
|
-
}
|
|
191
|
-
if (row && typeof row.version === 'number' && row.version > REGISTRY_SCHEMA_VERSION) {
|
|
192
|
-
throw new Error(
|
|
193
|
-
`Registry DB schema is v${row.version} but this claude-mem-lite binary supports up to v${REGISTRY_SCHEMA_VERSION}. ` +
|
|
194
|
-
`A newer version wrote this DB; upgrade claude-mem-lite (npm i -g claude-mem-lite@latest) or point CLAUDE_MEM_DIR to a fresh directory.`,
|
|
195
|
-
);
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
/**
|
|
200
|
-
* Column-drift self-heal for resources_fts. Deliberately NOT routed through the exported
|
|
201
|
-
* ensureFTS in schema.mjs: that helper creates the index without this one's `tokenize=`
|
|
202
|
-
* clause, and installs `<table>_ai/_ad/_au` triggers that would double-write alongside
|
|
203
|
-
* the res_fts_* set here. Its drift check also compares column SETS, while resources_fts
|
|
204
|
-
* is order-sensitive (registry-retriever's bm25(resources_fts, 3,3,3,2,2,1,1,1) weights
|
|
205
|
-
* by position). Mirrors ensureEventsFTS in schema.mjs, which exists for the same reason.
|
|
206
|
-
*
|
|
207
|
-
* Without this, widening FTS5_SCHEMA leaves existing DBs on the NARROW index while
|
|
208
|
-
* TRIGGERS_SCHEMA is re-exec'd from the wider list on every open — so every
|
|
209
|
-
* `INSERT INTO resources` throws "no column named X" and the write is silently lost.
|
|
210
|
-
* @param {Database} db
|
|
211
|
-
* @returns {boolean} true if the index was recreated (caller must repopulate it)
|
|
212
|
-
*/
|
|
213
|
-
function ensureResourcesFts(db) {
|
|
214
|
-
const ftsRow = db.prepare(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='resources_fts'`).get();
|
|
215
|
-
let recreated = false;
|
|
216
|
-
if (ftsRow) {
|
|
217
|
-
let existingCols = [];
|
|
218
|
-
try {
|
|
219
|
-
existingCols = db
|
|
220
|
-
.prepare(`PRAGMA table_info(resources_fts)`)
|
|
221
|
-
.all()
|
|
222
|
-
.map((c) => c.name);
|
|
223
|
-
} catch {
|
|
224
|
-
/* unreadable → treat as drifted, recreate */
|
|
225
|
-
}
|
|
226
|
-
// Element-wise so additions, removals AND reordering all count as drift.
|
|
227
|
-
const drifted =
|
|
228
|
-
existingCols.length !== FTS5_COLUMNS.length || FTS5_COLUMNS.some((c, i) => existingCols[i] !== c);
|
|
229
|
-
if (drifted) {
|
|
230
|
-
db.exec(`DROP TRIGGER IF EXISTS res_fts_insert`);
|
|
231
|
-
db.exec(`DROP TRIGGER IF EXISTS res_fts_update`);
|
|
232
|
-
db.exec(`DROP TRIGGER IF EXISTS res_fts_delete`);
|
|
233
|
-
db.exec(`DROP TABLE IF EXISTS resources_fts`);
|
|
234
|
-
recreated = true;
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
if (!ftsRow || recreated) db.exec(FTS5_SCHEMA);
|
|
238
|
-
return recreated;
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
// ─── Initialization ──────────────────────────────────────────────────────────
|
|
242
|
-
|
|
243
|
-
/**
|
|
244
|
-
* Initialize registry database with all tables and FTS5.
|
|
245
|
-
* Idempotent — safe to call multiple times.
|
|
246
|
-
* @param {string} dbPath Path to resource-registry.db
|
|
247
|
-
* @returns {Database} Opened database instance
|
|
248
|
-
*/
|
|
249
|
-
export function ensureRegistryDb(dbPath) {
|
|
250
|
-
const dir = dirname(dbPath);
|
|
251
|
-
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
252
|
-
|
|
253
|
-
const db = new Database(dbPath);
|
|
254
|
-
db.pragma('journal_mode = WAL');
|
|
255
|
-
// 5000ms to match the main DB: registry writes (install indexing rewriting
|
|
256
|
-
// resources + resources_fts) race shadow-recommend writes + mem_registry reads
|
|
257
|
-
// on the same file; 3000ms was insufficient under that concurrency (schema.mjs).
|
|
258
|
-
db.pragma('busy_timeout = 5000');
|
|
259
|
-
db.pragma('synchronous = NORMAL');
|
|
260
|
-
db.pragma('foreign_keys = ON');
|
|
261
|
-
|
|
262
|
-
// Before ANY DDL: refuse a registry written by a newer client (see assertRegistryNotNewer).
|
|
263
|
-
// Close the handle on the way out so the caller isn't left leaking an open file.
|
|
264
|
-
try {
|
|
265
|
-
assertRegistryNotNewer(db);
|
|
266
|
-
} catch (e) {
|
|
267
|
-
db.close();
|
|
268
|
-
throw e;
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
db.exec(RESOURCES_SCHEMA);
|
|
272
|
-
|
|
273
|
-
// Migrate: add missing columns to resources (single PRAGMA call for all)
|
|
274
|
-
try {
|
|
275
|
-
const resCols = new Set(
|
|
276
|
-
db
|
|
277
|
-
.prepare('PRAGMA table_info(resources)')
|
|
278
|
-
.all()
|
|
279
|
-
.map((c) => c.name),
|
|
280
|
-
);
|
|
281
|
-
if (!resCols.has('invocation_name'))
|
|
282
|
-
db.exec("ALTER TABLE resources ADD COLUMN invocation_name TEXT DEFAULT ''");
|
|
283
|
-
if (!resCols.has('silenced_until')) db.exec('ALTER TABLE resources ADD COLUMN silenced_until TEXT');
|
|
284
|
-
if (!resCols.has('cooldown_hours'))
|
|
285
|
-
db.exec('ALTER TABLE resources ADD COLUMN cooldown_hours INTEGER DEFAULT 0');
|
|
286
|
-
// recommendation_mode: 'proactive' (default, actively recommended), 'on_request' (only when explicitly asked)
|
|
287
|
-
if (!resCols.has('recommendation_mode'))
|
|
288
|
-
db.exec("ALTER TABLE resources ADD COLUMN recommendation_mode TEXT DEFAULT 'proactive'");
|
|
289
|
-
// weighted_adopt_sum: continuous adoption score accumulator (vs binary adopt_count)
|
|
290
|
-
if (!resCols.has('weighted_adopt_sum'))
|
|
291
|
-
db.exec('ALTER TABLE resources ADD COLUMN weighted_adopt_sum REAL DEFAULT 0');
|
|
292
|
-
// Phase 2: Registry optimization columns
|
|
293
|
-
if (!resCols.has('category')) db.exec('ALTER TABLE resources ADD COLUMN category TEXT');
|
|
294
|
-
if (!resCols.has('quality_tier'))
|
|
295
|
-
db.exec("ALTER TABLE resources ADD COLUMN quality_tier TEXT DEFAULT 'community'");
|
|
296
|
-
if (!resCols.has('popularity_score'))
|
|
297
|
-
db.exec('ALTER TABLE resources ADD COLUMN popularity_score REAL DEFAULT 0');
|
|
298
|
-
if (!resCols.has('personal_score'))
|
|
299
|
-
db.exec('ALTER TABLE resources ADD COLUMN personal_score REAL DEFAULT 0');
|
|
300
|
-
if (!resCols.has('enrichment_status'))
|
|
301
|
-
db.exec('ALTER TABLE resources ADD COLUMN enrichment_status TEXT DEFAULT NULL');
|
|
302
|
-
if (!resCols.has('enriched_at'))
|
|
303
|
-
db.exec('ALTER TABLE resources ADD COLUMN enriched_at INTEGER DEFAULT NULL');
|
|
304
|
-
if (!resCols.has('repo_updated_at'))
|
|
305
|
-
db.exec('ALTER TABLE resources ADD COLUMN repo_updated_at TEXT DEFAULT NULL');
|
|
306
|
-
if (!resCols.has('repo_forks')) db.exec('ALTER TABLE resources ADD COLUMN repo_forks INTEGER DEFAULT 0');
|
|
307
|
-
// Auto-set quality_tier for installed preinstalled resources
|
|
308
|
-
db.exec(
|
|
309
|
-
"UPDATE resources SET quality_tier = 'installed' WHERE source = 'preinstalled' AND quality_tier = 'community'",
|
|
310
|
-
);
|
|
311
|
-
} catch (e) {
|
|
312
|
-
debugCatch(e, 'resources-column-migration');
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
// Migrate: add 'github' to source CHECK constraint (required for smart import)
|
|
316
|
-
// Must disable FK checks during table recreation (RENAME triggers FK validation).
|
|
317
|
-
// legacy_alter_table=ON is REQUIRED: under modern SQLite (the better-sqlite3
|
|
318
|
-
// default) `ALTER TABLE resources RENAME TO resources_old` rewrites child-table FK
|
|
319
|
-
// references, so invocations.resource_id would become `REFERENCES resources_old`
|
|
320
|
-
// and the trailing DROP would leave it dangling — silently killing every future
|
|
321
|
-
// `INSERT INTO invocations` (audit P0 #1). Legacy mode keeps child FKs pointing at
|
|
322
|
-
// the original name, which the freshly-created `resources` table then satisfies.
|
|
323
|
-
let resourcesRebuilt = false;
|
|
324
|
-
try {
|
|
325
|
-
const resSchema = db
|
|
326
|
-
.prepare(`SELECT sql FROM sqlite_master WHERE type='table' AND name='resources'`)
|
|
327
|
-
.get();
|
|
328
|
-
if (resSchema?.sql && !resSchema.sql.includes("'github'")) {
|
|
329
|
-
db.pragma('foreign_keys = OFF');
|
|
330
|
-
db.pragma('legacy_alter_table = ON');
|
|
331
|
-
try {
|
|
332
|
-
db.transaction(() => {
|
|
333
|
-
const hasOld = db
|
|
334
|
-
.prepare(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='resources_old'`)
|
|
335
|
-
.get();
|
|
336
|
-
if (hasOld) db.exec(`DROP TABLE resources_old`);
|
|
337
|
-
// Drop FTS triggers first (reference resources table)
|
|
338
|
-
db.exec(`DROP TRIGGER IF EXISTS res_fts_insert`);
|
|
339
|
-
db.exec(`DROP TRIGGER IF EXISTS res_fts_update`);
|
|
340
|
-
db.exec(`DROP TRIGGER IF EXISTS res_fts_delete`);
|
|
341
|
-
db.exec(`ALTER TABLE resources RENAME TO resources_old`);
|
|
342
|
-
db.exec(RESOURCES_SCHEMA);
|
|
343
|
-
// Copy all existing data
|
|
344
|
-
const cols = db
|
|
345
|
-
.prepare('PRAGMA table_info(resources_old)')
|
|
346
|
-
.all()
|
|
347
|
-
.map((c) => c.name);
|
|
348
|
-
const newCols = new Set(
|
|
349
|
-
db
|
|
350
|
-
.prepare('PRAGMA table_info(resources)')
|
|
351
|
-
.all()
|
|
352
|
-
.map((c) => c.name),
|
|
353
|
-
);
|
|
354
|
-
const common = cols.filter((c) => newCols.has(c)).join(', ');
|
|
355
|
-
db.exec(`INSERT INTO resources (${common}) SELECT ${common} FROM resources_old`);
|
|
356
|
-
db.exec(`DROP TABLE resources_old`);
|
|
357
|
-
// Recreate the table's indexes: the CREATE INDEX IF NOT EXISTS inside
|
|
358
|
-
// RESOURCES_SCHEMA above was SKIPPED while resources_old still held the
|
|
359
|
-
// index names, so the rebuilt table had NONE — including the UNIQUE
|
|
360
|
-
// idx_res_type_name that upsertResource's ON CONFLICT(type,name) requires
|
|
361
|
-
// (review HIGH-1; pre-existing, closed here). Names are free post-DROP.
|
|
362
|
-
db.exec(RESOURCES_SCHEMA);
|
|
363
|
-
})();
|
|
364
|
-
} finally {
|
|
365
|
-
db.pragma('legacy_alter_table = OFF');
|
|
366
|
-
db.pragma('foreign_keys = ON');
|
|
367
|
-
}
|
|
368
|
-
resourcesRebuilt = true;
|
|
369
|
-
}
|
|
370
|
-
} catch (e) {
|
|
371
|
-
debugCatch(e, 'resources-source-check-migration');
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
// FTS5: create if absent, or drop+recreate if the indexed columns have drifted from
|
|
375
|
-
// FTS5_COLUMNS (a stale narrow index silently kills every resources write — audit P2-6).
|
|
376
|
-
const ftsRecreated = ensureResourcesFts(db);
|
|
377
|
-
// Triggers: always ensure (IF NOT EXISTS) — fixes DBs where FTS5 was created without
|
|
378
|
-
// triggers, and reinstates the set ensureResourcesFts drops on drift.
|
|
379
|
-
db.exec(TRIGGERS_SCHEMA);
|
|
380
|
-
|
|
381
|
-
// The source-CHECK migration replaced the `resources` content table out from under
|
|
382
|
-
// the external-content FTS index (content=resources), leaving resources_fts stale.
|
|
383
|
-
// Rebuild it so a later DELETE's res_fts_delete trigger doesn't throw "database disk
|
|
384
|
-
// image is malformed" against the mismatched index. Gated on the migration actually
|
|
385
|
-
// having run so we don't rebuild on every open. A drift-recreated index needs the same
|
|
386
|
-
// repopulation for the opposite reason: it starts EMPTY, so rows written before the
|
|
387
|
-
// drift would be unreachable through search forever.
|
|
388
|
-
if (resourcesRebuilt || ftsRecreated) {
|
|
389
|
-
try {
|
|
390
|
-
db.exec("INSERT INTO resources_fts(resources_fts) VALUES('rebuild')");
|
|
391
|
-
} catch (e) {
|
|
392
|
-
debugCatch(e, 'resources-fts-rebuild-after-source-check');
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
db.exec(INVOCATIONS_SCHEMA);
|
|
397
|
-
|
|
398
|
-
// Migrate invocations CHECK constraint: add 'user_prompt' trigger value
|
|
399
|
-
// SQLite cannot ALTER CHECK constraints, so recreate table if needed
|
|
400
|
-
try {
|
|
401
|
-
const schema = db
|
|
402
|
-
.prepare(`SELECT sql FROM sqlite_master WHERE type='table' AND name='invocations'`)
|
|
403
|
-
.get();
|
|
404
|
-
if (schema?.sql && !schema.sql.includes('user_prompt')) {
|
|
405
|
-
db.transaction(() => {
|
|
406
|
-
// Clean up leftover from previous failed migration attempt
|
|
407
|
-
const hasOld = db
|
|
408
|
-
.prepare(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='invocations_old'`)
|
|
409
|
-
.get();
|
|
410
|
-
if (hasOld) db.exec(`DROP TABLE invocations_old`);
|
|
411
|
-
db.exec(`ALTER TABLE invocations RENAME TO invocations_old`);
|
|
412
|
-
db.exec(INVOCATIONS_SCHEMA);
|
|
413
|
-
// Omit rejection_reason — column may not exist yet on old DBs; ADD COLUMN migration below handles it
|
|
414
|
-
db.exec(`INSERT INTO invocations
|
|
415
|
-
(id, resource_id, session_id, trigger, tier, recommended, adopted, outcome, score, created_at)
|
|
416
|
-
SELECT id, resource_id, session_id, trigger, tier, recommended, adopted, outcome, score, created_at
|
|
417
|
-
FROM invocations_old`);
|
|
418
|
-
db.exec(`DROP TABLE invocations_old`);
|
|
419
|
-
})();
|
|
420
|
-
}
|
|
421
|
-
} catch (e) {
|
|
422
|
-
debugCatch(e, 'ensureRegistryDb-migration');
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
// Migrate invocations CHECK constraint: add 'ignored' outcome value
|
|
426
|
-
try {
|
|
427
|
-
const schema = db
|
|
428
|
-
.prepare(`SELECT sql FROM sqlite_master WHERE type='table' AND name='invocations'`)
|
|
429
|
-
.get();
|
|
430
|
-
if (schema?.sql && !schema.sql.includes("'ignored'")) {
|
|
431
|
-
db.transaction(() => {
|
|
432
|
-
const hasOld = db
|
|
433
|
-
.prepare(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='invocations_old'`)
|
|
434
|
-
.get();
|
|
435
|
-
if (hasOld) db.exec(`DROP TABLE invocations_old`);
|
|
436
|
-
db.exec(`ALTER TABLE invocations RENAME TO invocations_old`);
|
|
437
|
-
db.exec(INVOCATIONS_SCHEMA);
|
|
438
|
-
// Omit rejection_reason — column may not exist yet on old DBs; ADD COLUMN migration below handles it
|
|
439
|
-
db.exec(`INSERT INTO invocations
|
|
440
|
-
(id, resource_id, session_id, trigger, tier, recommended, adopted, outcome, score, created_at)
|
|
441
|
-
SELECT id, resource_id, session_id, trigger, tier, recommended, adopted, outcome, score, created_at
|
|
442
|
-
FROM invocations_old`);
|
|
443
|
-
db.exec(`DROP TABLE invocations_old`);
|
|
444
|
-
})();
|
|
445
|
-
}
|
|
446
|
-
} catch (e) {
|
|
447
|
-
debugCatch(e, 'ensureRegistryDb-ignored-migration');
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
// Migrate: add rejection_reason column if missing
|
|
451
|
-
try {
|
|
452
|
-
const cols = db.prepare('PRAGMA table_info(invocations)').all();
|
|
453
|
-
if (!cols.some((c) => c.name === 'rejection_reason')) {
|
|
454
|
-
db.exec('ALTER TABLE invocations ADD COLUMN rejection_reason TEXT');
|
|
455
|
-
}
|
|
456
|
-
} catch (e) {
|
|
457
|
-
debugCatch(e, 'rejection_reason-migration');
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
// Migrate: add ON DELETE CASCADE to invocations.resource_id (audit P0 #4). Old DBs
|
|
461
|
-
// declared the FK with no ON DELETE action, so deleting a resource that had
|
|
462
|
-
// invocation history threw SQLITE_CONSTRAINT_FOREIGNKEY (registry remove /
|
|
463
|
-
// mem_registry delete) or silently no-op'd (dead-repo purge). SQLite can't ALTER an
|
|
464
|
-
// FK, so rebuild the table. Renaming the CHILD table is safe (nothing references
|
|
465
|
-
// invocations), so legacy_alter_table is not a concern here. Runs after the
|
|
466
|
-
// rejection_reason ADD COLUMN so the column exists in both old and new tables.
|
|
467
|
-
try {
|
|
468
|
-
const schema = db
|
|
469
|
-
.prepare(`SELECT sql FROM sqlite_master WHERE type='table' AND name='invocations'`)
|
|
470
|
-
.get();
|
|
471
|
-
if (schema?.sql && !/ON DELETE CASCADE/i.test(schema.sql)) {
|
|
472
|
-
db.transaction(() => {
|
|
473
|
-
const hasOld = db
|
|
474
|
-
.prepare(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='invocations_old'`)
|
|
475
|
-
.get();
|
|
476
|
-
if (hasOld) db.exec(`DROP TABLE invocations_old`);
|
|
477
|
-
db.exec(`ALTER TABLE invocations RENAME TO invocations_old`);
|
|
478
|
-
db.exec(INVOCATIONS_SCHEMA);
|
|
479
|
-
// Omit rejection_reason from the copy (matching the CHECK migrations above):
|
|
480
|
-
// it was historically a bare TEXT with NO CHECK, so an old row could hold a
|
|
481
|
-
// value outside INVOCATIONS_SCHEMA's current rejection_reason CHECK whitelist.
|
|
482
|
-
// Copying it would throw SQLITE_CONSTRAINT_CHECK → rollback → the FK is left
|
|
483
|
-
// un-cascaded forever and every retry re-fails (review HIGH-2). The column is
|
|
484
|
-
// never written at runtime, so copied rows get NULL — no data loss.
|
|
485
|
-
db.exec(`INSERT INTO invocations
|
|
486
|
-
(id, resource_id, session_id, trigger, tier, recommended, adopted, outcome, score, created_at)
|
|
487
|
-
SELECT id, resource_id, session_id, trigger, tier, recommended, adopted, outcome, score, created_at
|
|
488
|
-
FROM invocations_old`);
|
|
489
|
-
db.exec(`DROP TABLE invocations_old`);
|
|
490
|
-
// Recreate the table's indexes — the INVOCATIONS_SCHEMA CREATE INDEX above was
|
|
491
|
-
// skipped while invocations_old held the names (review HIGH-1). Free post-DROP.
|
|
492
|
-
db.exec(INVOCATIONS_SCHEMA);
|
|
493
|
-
})();
|
|
494
|
-
}
|
|
495
|
-
} catch (e) {
|
|
496
|
-
debugCatch(e, 'invocations-ondelete-cascade-migration');
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
// (Removed the separate idx_invocations_resource_created migration — it was a column-
|
|
500
|
-
// identical duplicate of idx_inv_resource (resource_id, created_at) in INVOCATIONS_SCHEMA.
|
|
501
|
-
// It only ever survived because the rebuild migrations dropped idx_inv_resource; now that
|
|
502
|
-
// the rebuilds recreate their indexes (review HIGH-1), the duplicate is pure dead weight.
|
|
503
|
-
// Pre-existing DBs keep their old idx_invocations_resource_created; it's harmless.)
|
|
504
|
-
|
|
505
|
-
db.exec(PREINSTALLED_SCHEMA);
|
|
506
|
-
|
|
507
|
-
// Stamp the version LAST — only after every table + migration above succeeded. This is
|
|
508
|
-
// also the ADOPTION path for pre-version DBs: they are stamped in place, never wiped or
|
|
509
|
-
// refused. Rewritten each open so exactly one row exists and it reflects this build.
|
|
510
|
-
db.exec('CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)');
|
|
511
|
-
db.transaction(() => {
|
|
512
|
-
db.exec('DELETE FROM schema_version');
|
|
513
|
-
db.prepare('INSERT INTO schema_version (version) VALUES (?)').run(REGISTRY_SCHEMA_VERSION);
|
|
514
|
-
})();
|
|
515
|
-
|
|
516
|
-
return db;
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
// ─── Exported Schema (test-helpers.mjs, and scripts/index-managed.mjs since P1-16, which
|
|
520
|
-
// rebuilds resources_fts from scratch and used to carry its own copy of both blocks) ──
|
|
521
|
-
|
|
522
|
-
export { RESOURCES_SCHEMA, FTS5_SCHEMA, TRIGGERS_SCHEMA, INVOCATIONS_SCHEMA, PREINSTALLED_SCHEMA };
|
|
523
|
-
|
|
524
|
-
// ─── Resource CRUD ───────────────────────────────────────────────────────────
|
|
525
|
-
|
|
526
|
-
const UPSERT_SQL = `
|
|
527
|
-
INSERT INTO resources (name, type, status, source, repo_url, repo_stars, local_path, file_hash,
|
|
528
|
-
invocation_name, intent_tags, domain_tags, action_type, trigger_patterns, capability_summary,
|
|
529
|
-
input_type, output_type, prerequisites, keywords, tech_stack, use_cases, complexity,
|
|
530
|
-
indexed_at, updated_at)
|
|
531
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
|
|
532
|
-
ON CONFLICT(type, name) DO UPDATE SET
|
|
533
|
-
status=excluded.status, source=excluded.source,
|
|
534
|
-
-- Preserve-on-empty (mirror the FTS text columns below): a PARTIAL re-upsert defaults
|
|
535
|
-
-- repo_url/local_path to null/'' in the caller (import is the only edit path). Clobbering
|
|
536
|
-
-- them ORPHANS the resource — mem_use/enrich read local_path (NOT NULL, so '' passes the
|
|
537
|
-
-- constraint and silently breaks reads), and the scanner needs local_path to disable it.
|
|
538
|
-
repo_url=CASE WHEN excluded.repo_url != '' THEN excluded.repo_url ELSE repo_url END,
|
|
539
|
-
repo_stars=CASE WHEN excluded.repo_stars > 0 THEN excluded.repo_stars ELSE repo_stars END,
|
|
540
|
-
local_path=CASE WHEN excluded.local_path != '' THEN excluded.local_path ELSE local_path END,
|
|
541
|
-
file_hash=CASE WHEN excluded.file_hash IS NOT NULL AND excluded.file_hash != '' THEN excluded.file_hash ELSE file_hash END,
|
|
542
|
-
invocation_name=CASE WHEN excluded.invocation_name != '' THEN excluded.invocation_name ELSE invocation_name END,
|
|
543
|
-
-- Preserve-on-empty (mirror repo_stars/invocation_name above): a PARTIAL re-upsert --
|
|
544
|
-
-- e.g. "registry import --name X --capability-summary ...", where mem-cli defaults every
|
|
545
|
-
-- other flag to '' -- must NOT blank the FTS text columns and silently drop the resource
|
|
546
|
-
-- out of search (import is the ONLY registry edit path; there is no update subcommand).
|
|
547
|
-
-- Full upserts are unaffected: every field is non-empty, so the CASE picks excluded.
|
|
548
|
-
intent_tags=CASE WHEN excluded.intent_tags != '' THEN excluded.intent_tags ELSE intent_tags END,
|
|
549
|
-
domain_tags=CASE WHEN excluded.domain_tags != '' THEN excluded.domain_tags ELSE domain_tags END,
|
|
550
|
-
action_type=CASE WHEN excluded.action_type != '' THEN excluded.action_type ELSE action_type END,
|
|
551
|
-
trigger_patterns=CASE WHEN excluded.trigger_patterns != '' THEN excluded.trigger_patterns ELSE trigger_patterns END,
|
|
552
|
-
capability_summary=CASE WHEN excluded.capability_summary != '' THEN excluded.capability_summary ELSE capability_summary END,
|
|
553
|
-
input_type=CASE WHEN excluded.input_type != '' THEN excluded.input_type ELSE input_type END,
|
|
554
|
-
output_type=CASE WHEN excluded.output_type != '' THEN excluded.output_type ELSE output_type END,
|
|
555
|
-
-- Preserve-on-empty (same class as the FTS text columns above): a partial re-import
|
|
556
|
-
-- omits prerequisites/complexity, so upsertResource supplies their DEFAULTS ('{}' /
|
|
557
|
-
-- 'intermediate'). No CLI flag sets these (only a full re-index does), so treating the
|
|
558
|
-
-- default as the "absent" sentinel is safe: a real re-index sends non-default values,
|
|
559
|
-
-- which still overwrite; a metadata edit sends the default, which now preserves.
|
|
560
|
-
prerequisites=CASE WHEN excluded.prerequisites NOT IN ('', '{}') THEN excluded.prerequisites ELSE prerequisites END,
|
|
561
|
-
keywords=CASE WHEN excluded.keywords != '' THEN excluded.keywords ELSE keywords END,
|
|
562
|
-
tech_stack=CASE WHEN excluded.tech_stack != '' THEN excluded.tech_stack ELSE tech_stack END,
|
|
563
|
-
use_cases=CASE WHEN excluded.use_cases != '' THEN excluded.use_cases ELSE use_cases END,
|
|
564
|
-
complexity=CASE WHEN excluded.complexity NOT IN ('', 'intermediate') THEN excluded.complexity ELSE complexity END,
|
|
565
|
-
indexed_at=excluded.indexed_at, updated_at=datetime('now')
|
|
566
|
-
`;
|
|
567
|
-
|
|
568
|
-
/**
|
|
569
|
-
* Insert or update a resource. Idempotent via UPSERT on (type, name).
|
|
570
|
-
* @param {Database} db Registry database
|
|
571
|
-
* @param {object} r Resource object
|
|
572
|
-
* @returns {number} Resource ID
|
|
573
|
-
*/
|
|
574
|
-
export function upsertResource(db, r) {
|
|
575
|
-
return db.transaction(() => {
|
|
576
|
-
db.prepare(UPSERT_SQL).run(
|
|
577
|
-
r.name,
|
|
578
|
-
r.type,
|
|
579
|
-
r.status || 'active',
|
|
580
|
-
r.source || 'preinstalled',
|
|
581
|
-
r.repo_url || null,
|
|
582
|
-
r.repo_stars || 0,
|
|
583
|
-
r.local_path,
|
|
584
|
-
r.file_hash || null,
|
|
585
|
-
r.invocation_name || '',
|
|
586
|
-
r.intent_tags || '',
|
|
587
|
-
r.domain_tags || '',
|
|
588
|
-
r.action_type || '',
|
|
589
|
-
r.trigger_patterns || '',
|
|
590
|
-
r.capability_summary || '',
|
|
591
|
-
r.input_type || '',
|
|
592
|
-
r.output_type || '',
|
|
593
|
-
r.prerequisites || '{}',
|
|
594
|
-
r.keywords || '',
|
|
595
|
-
r.tech_stack || '',
|
|
596
|
-
r.use_cases || '',
|
|
597
|
-
r.complexity || 'intermediate',
|
|
598
|
-
r.indexed_at || null,
|
|
599
|
-
);
|
|
600
|
-
const row = db.prepare('SELECT id FROM resources WHERE type = ? AND name = ?').get(r.type, r.name);
|
|
601
|
-
return row?.id || 0;
|
|
602
|
-
})();
|
|
603
|
-
}
|
|
604
|
-
|
|
605
|
-
// ─── P2-12: registry stats/list twin cores (audit 2026-08-14) ────────────────
|
|
606
|
-
// The five stats statements + the list row line were duplicated in mem-cli.mjs
|
|
607
|
-
// and server.mjs and had already drifted (truncate 50 vs 80; `adopt:null` on
|
|
608
|
-
// one face; the COALESCE ordering fix landed on the MCP face only). Data
|
|
609
|
-
// collection + row-line shape live here; faces keep their own headers/limits.
|
|
610
|
-
|
|
611
|
-
/**
|
|
612
|
-
* Collect the five stat groups the `registry stats` twin renders.
|
|
613
|
-
* @param {import('better-sqlite3').Database} rdb registry DB handle
|
|
614
|
-
* @returns {{total:number, byType:Array<{type:string,c:number}>, topAdopted:object[], zeroAdopt:number, userAdded:number}}
|
|
615
|
-
*/
|
|
616
|
-
export function collectRegistryStats(rdb) {
|
|
617
|
-
const total = rdb.prepare('SELECT COUNT(*) as c FROM resources WHERE status = ?').get('active');
|
|
618
|
-
const byType = rdb
|
|
619
|
-
.prepare('SELECT type, COUNT(*) as c FROM resources WHERE status = ? GROUP BY type')
|
|
620
|
-
.all('active');
|
|
621
|
-
const topAdopted = rdb
|
|
622
|
-
.prepare(
|
|
623
|
-
'SELECT name, type, adopt_count, recommend_count FROM resources WHERE status = ? AND adopt_count > 0 ORDER BY adopt_count DESC LIMIT 10',
|
|
624
|
-
)
|
|
625
|
-
.all('active');
|
|
626
|
-
const zeroAdopt = rdb
|
|
627
|
-
.prepare(
|
|
628
|
-
'SELECT COUNT(*) as c FROM resources WHERE status = ? AND recommend_count > 0 AND adopt_count = 0',
|
|
629
|
-
)
|
|
630
|
-
.get('active');
|
|
631
|
-
const userAdded = rdb
|
|
632
|
-
.prepare("SELECT COUNT(*) as c FROM resources WHERE status = ? AND source = 'user'")
|
|
633
|
-
.get('active');
|
|
634
|
-
return { total: total.c, byType, topAdopted, zeroAdopt: zeroAdopt.c, userAdded: userAdded.c };
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
/**
|
|
638
|
-
* Ranked resource listing for the `registry list` twin: adoption first, then
|
|
639
|
-
* recommendation, NULL counts coalesced (the un-coalesced face sorted NULLs
|
|
640
|
-
* apart AND rendered "adopt:null").
|
|
641
|
-
* @param {import('better-sqlite3').Database} rdb
|
|
642
|
-
* @param {{type?: string}} [opts]
|
|
643
|
-
* @returns {object[]}
|
|
644
|
-
*/
|
|
645
|
-
export function listResourcesRanked(rdb, { type } = {}) {
|
|
646
|
-
const where = type ? 'WHERE type = ? AND status = ?' : 'WHERE status = ?';
|
|
647
|
-
const params = type ? [type, 'active'] : ['active'];
|
|
648
|
-
return rdb
|
|
649
|
-
.prepare(
|
|
650
|
-
`
|
|
651
|
-
SELECT name, type, invocation_name, recommend_count, adopt_count, capability_summary
|
|
652
|
-
FROM resources ${where}
|
|
653
|
-
ORDER BY COALESCE(adopt_count, 0) DESC, COALESCE(recommend_count, 0) DESC, type, name
|
|
654
|
-
`,
|
|
655
|
-
)
|
|
656
|
-
.all(...params);
|
|
657
|
-
}
|
|
658
|
-
|
|
659
|
-
/** One list row, shared shape: `S name (invocation) — rec:N adopt:N — summary…` (80-char summary cap).
|
|
660
|
-
* truncate(), not a hand-rolled slice (adversarial review 2026-08-16): the shared
|
|
661
|
-
* helper flattens newlines (this is a one-row-per-resource listing) and never
|
|
662
|
-
* splits a UTF-16 surrogate pair — a bare slice emitted lone surrogates. */
|
|
663
|
-
export function formatRegistryListLine(r) {
|
|
664
|
-
return `${r.type === 'skill' ? 'S' : 'A'} ${r.name}${r.invocation_name ? ` (${r.invocation_name})` : ''} — rec:${r.recommend_count ?? 0} adopt:${r.adopt_count ?? 0} — ${truncate(r.capability_summary || '', 80)}`;
|
|
665
|
-
}
|