@klhapp/skillmux 1.9.3 → 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/src/db.ts CHANGED
@@ -1,521 +1,3 @@
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
- import type { VaultSkill } from "./vault";
7
-
8
- export interface SkillRow {
9
- skill_id: string;
10
- title: string;
11
- description: string;
12
- aliases: string;
13
- content_sha256: string;
14
- }
15
-
16
- export function openAudit(stateDir: string): Database {
17
- mkdirSync(stateDir, { recursive: true });
18
- const db = new Database(join(stateDir, "audit.sqlite3"), { create: true });
19
- // auto_vacuum only takes on an empty database, so it must precede both the
20
- // journal-mode switch and any CREATE TABLE. It is what lets a retention
21
- // prune reclaim space without a full VACUUM.
22
- db.run("PRAGMA auto_vacuum = INCREMENTAL");
23
- db.run("PRAGMA journal_mode = WAL");
24
- db.run("PRAGMA busy_timeout = 2000");
25
- db.run(`CREATE TABLE IF NOT EXISTS audit (
26
- id INTEGER PRIMARY KEY AUTOINCREMENT,
27
- ts TEXT NOT NULL,
28
- request_id TEXT,
29
- query TEXT NOT NULL,
30
- retrieval TEXT NOT NULL DEFAULT 'lexical',
31
- degraded_from TEXT,
32
- degradation_reason TEXT,
33
- candidates TEXT NOT NULL,
34
- latency_ms INTEGER NOT NULL
35
- )`);
36
- // CREATE TABLE IF NOT EXISTS no-ops on a table opened from before request_id
37
- // existed (AC4), so add it explicitly when missing.
38
- const auditColumns = new Set(
39
- (db.query("PRAGMA table_info(audit)").all() as { name: string }[]).map((c) => c.name),
40
- );
41
- if (!auditColumns.has("request_id")) {
42
- db.run("ALTER TABLE audit ADD COLUMN request_id TEXT");
43
- }
44
- db.run(`CREATE TABLE IF NOT EXISTS fetch (
45
- id INTEGER PRIMARY KEY AUTOINCREMENT,
46
- ts TEXT NOT NULL,
47
- skill_id TEXT NOT NULL,
48
- request_id TEXT,
49
- resolve_audit_id INTEGER,
50
- rank_at_resolve INTEGER
51
- )`);
52
- db.run(`CREATE TABLE IF NOT EXISTS admin_audit (
53
- id INTEGER PRIMARY KEY AUTOINCREMENT,
54
- ts TEXT NOT NULL,
55
- changes TEXT NOT NULL,
56
- resulting_revision TEXT NOT NULL,
57
- row_hash TEXT NOT NULL,
58
- prev_row_hash TEXT
59
- )`);
60
- adoptAuditFromIndex(db, stateDir);
61
- return db;
62
- }
63
-
64
- // Audit rows used to live in index.sqlite3. Move any that remain there into the
65
- // audit store, then drop the old table so the index carries no user queries.
66
- function adoptAuditFromIndex(db: Database, stateDir: string): void {
67
- const indexPath = join(stateDir, "index.sqlite3");
68
- if (!existsSync(indexPath)) return;
69
-
70
- db.run("ATTACH DATABASE ? AS legacy", [indexPath]);
71
- try {
72
- const legacyAudit = db
73
- .query("SELECT name FROM legacy.sqlite_master WHERE type = 'table' AND name = 'audit'")
74
- .get();
75
- if (!legacyAudit) return;
76
-
77
- // Older audit tables predate the retrieval columns and carry outcome /
78
- // degraded / selected_skill_id instead. Select what is actually there and
79
- // let the canonical defaults stand in for the rest.
80
- const legacyColumns = new Set(
81
- (db.query("PRAGMA legacy.table_info(audit)").all() as { name: string }[]).map((c) => c.name),
82
- );
83
- const retrieval = legacyColumns.has("retrieval") ? "COALESCE(retrieval, 'lexical')" : "'lexical'";
84
- const degradedFrom = legacyColumns.has("degraded_from") ? "degraded_from" : "NULL";
85
- const degradationReason = legacyColumns.has("degradation_reason") ? "degradation_reason" : "NULL";
86
-
87
- // SQLite commits atomically across attached databases, so the copy and the
88
- // drop either both land or neither does.
89
- db.transaction(() => {
90
- db.run(`INSERT INTO audit (ts, query, retrieval, degraded_from, degradation_reason, candidates, latency_ms)
91
- SELECT ts, query, ${retrieval}, ${degradedFrom}, ${degradationReason}, candidates, latency_ms FROM legacy.audit`);
92
- db.run("DROP TABLE legacy.audit");
93
- })();
94
- } finally {
95
- db.run("DETACH DATABASE legacy");
96
- }
97
- }
98
-
99
- export function openIndex(stateDir: string): Database {
100
- mkdirSync(stateDir, { recursive: true });
101
- const db = new Database(join(stateDir, "index.sqlite3"), { create: true });
102
- db.run("PRAGMA journal_mode = WAL");
103
- db.run("PRAGMA busy_timeout = 2000");
104
- db.run(`CREATE TABLE IF NOT EXISTS skills (
105
- skill_id TEXT PRIMARY KEY,
106
- title TEXT NOT NULL,
107
- description TEXT NOT NULL,
108
- aliases TEXT NOT NULL,
109
- content_sha256 TEXT NOT NULL
110
- )`);
111
- db.run(`CREATE VIRTUAL TABLE IF NOT EXISTS skills_fts USING fts5(
112
- skill_id UNINDEXED, title, description, aliases,
113
- tokenize = 'unicode61 remove_diacritics 2'
114
- )`);
115
- db.run(`CREATE TABLE IF NOT EXISTS vectors (
116
- skill_id TEXT PRIMARY KEY,
117
- content_sha256 TEXT NOT NULL,
118
- embedding_fingerprint TEXT NOT NULL DEFAULT '',
119
- dim INTEGER NOT NULL,
120
- vec BLOB NOT NULL
121
- )`);
122
- const vectorColumns = db.query("PRAGMA table_info(vectors)").all() as { name: string }[];
123
- if (!vectorColumns.some((column) => column.name === "embedding_fingerprint")) {
124
- db.run("ALTER TABLE vectors ADD COLUMN embedding_fingerprint TEXT NOT NULL DEFAULT ''");
125
- }
126
- // Audit rows live in audit.sqlite3; openAudit adopts any left here.
127
- db.run(`CREATE TABLE IF NOT EXISTS index_meta (
128
- key TEXT PRIMARY KEY,
129
- value TEXT NOT NULL
130
- )`);
131
- return db;
132
- }
133
-
134
- export function upsertSkill(db: Database, skill: VaultSkill): void {
135
- const aliases = skill.aliases.join(" ");
136
- db.transaction(() => {
137
- db.run("DELETE FROM skills WHERE skill_id = ?", [skill.skill_id]);
138
- db.run("DELETE FROM skills_fts WHERE skill_id = ?", [skill.skill_id]);
139
- db.run(
140
- "INSERT INTO skills (skill_id, title, description, aliases, content_sha256) VALUES (?, ?, ?, ?, ?)",
141
- [skill.skill_id, skill.title, skill.description, aliases, skill.content_sha256],
142
- );
143
- db.run(
144
- "INSERT INTO skills_fts (skill_id, title, description, aliases) VALUES (?, ?, ?, ?)",
145
- [skill.skill_id, skill.title, skill.description, aliases],
146
- );
147
- })();
148
- }
149
-
150
- export function toSkillRow(skill: VaultSkill): SkillRow {
151
- return {
152
- skill_id: skill.skill_id,
153
- title: skill.title,
154
- description: skill.description,
155
- aliases: skill.aliases.join(" "),
156
- content_sha256: skill.content_sha256,
157
- };
158
- }
159
-
160
- /** Replace the whole lexical index with `rows`; drops vectors of removed skills. */
161
- export function replaceSkills(db: Database, rows: SkillRow[]): void {
162
- db.transaction(() => {
163
- db.run("DELETE FROM skills");
164
- db.run("DELETE FROM skills_fts");
165
- for (const row of rows) {
166
- db.run(
167
- "INSERT INTO skills (skill_id, title, description, aliases, content_sha256) VALUES (?, ?, ?, ?, ?)",
168
- [row.skill_id, row.title, row.description, row.aliases, row.content_sha256],
169
- );
170
- db.run(
171
- "INSERT INTO skills_fts (skill_id, title, description, aliases) VALUES (?, ?, ?, ?)",
172
- [row.skill_id, row.title, row.description, row.aliases],
173
- );
174
- }
175
- db.run("DELETE FROM vectors WHERE skill_id NOT IN (SELECT skill_id FROM skills)");
176
- })();
177
- }
178
-
179
- export function ingestVault(db: Database, skills: VaultSkill[]): void {
180
- replaceSkills(db, skills.map(toSkillRow));
181
- }
182
-
183
- export function deleteSkill(db: Database, skillId: string): void {
184
- db.transaction(() => {
185
- db.run("DELETE FROM skills WHERE skill_id = ?", [skillId]);
186
- db.run("DELETE FROM skills_fts WHERE skill_id = ?", [skillId]);
187
- db.run("DELETE FROM vectors WHERE skill_id = ?", [skillId]);
188
- })();
189
- }
190
-
191
- export function skillCount(db: Database): number {
192
- return (db.query("SELECT count(*) AS n FROM skills").get() as { n: number }).n;
193
- }
194
-
195
- export function getSkillRow(db: Database, skillId: string): SkillRow | null {
196
- return db.query("SELECT * FROM skills WHERE skill_id = ?").get(skillId) as SkillRow | null;
197
- }
198
-
199
- /**
200
- * Sanitize free text into an FTS5 OR-query; returns null when no usable terms
201
- * remain. Terms keep any Unicode letters/digits (CJK included) so non-ASCII
202
- * queries still get lexical recall — unicode61 tokenizes contiguous CJK runs
203
- * as single tokens, so matching works at that granularity.
204
- */
205
- export function toFtsQuery(text: string): string | null {
206
- const terms = [
207
- ...new Set(
208
- text
209
- .toLowerCase()
210
- .split(/[^\p{L}\p{N}]+/u)
211
- .filter((t) => t.length >= 2),
212
- ),
213
- ];
214
- if (terms.length === 0) return null;
215
- return terms.map((t) => `"${t}"`).join(" OR ");
216
- }
217
-
218
- export function ftsSearch(db: Database, text: string, k: number): SkillRow[] {
219
- const query = toFtsQuery(text);
220
- if (query === null) return [];
221
- return db
222
- .query(
223
- `SELECT s.* FROM skills_fts f
224
- JOIN skills s ON s.skill_id = f.skill_id
225
- WHERE skills_fts MATCH ?
226
- ORDER BY bm25(skills_fts) LIMIT ?`,
227
- )
228
- .all(query, k) as SkillRow[];
229
- }
230
-
231
- export function findExactMatch(db: Database, query: string): SkillRow | null {
232
- const cleanQuery = query.trim().toLowerCase();
233
- return db
234
- .query(
235
- `SELECT * FROM skills
236
- WHERE lower(skill_id) = ?
237
- OR lower(title) = ?
238
- OR ' ' || lower(aliases) || ' ' LIKE ?`,
239
- )
240
- .get(cleanQuery, cleanQuery, `% ${cleanQuery} %`) as SkillRow | null;
241
- }
242
-
243
- export function getIndexMeta(db: Database, key: string): string | null {
244
- const row = db
245
- .query("SELECT value FROM index_meta WHERE key = ?")
246
- .get(key) as { value: string } | null;
247
- return row ? row.value : null;
248
- }
249
-
250
- export function setIndexMeta(db: Database, key: string, value: string): void {
251
- db.run(
252
- `INSERT INTO index_meta (key, value) VALUES (?, ?)
253
- ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
254
- [key, value],
255
- );
256
- }
257
-
258
- export function upsertVector(
259
- db: Database,
260
- skillId: string,
261
- contentSha256: string,
262
- embeddingFingerprint: string,
263
- vec: Float32Array,
264
- ): void {
265
- db.run(
266
- `INSERT INTO vectors (skill_id, content_sha256, embedding_fingerprint, dim, vec) VALUES (?, ?, ?, ?, ?)
267
- ON CONFLICT(skill_id) DO UPDATE SET
268
- content_sha256 = excluded.content_sha256,
269
- embedding_fingerprint = excluded.embedding_fingerprint,
270
- dim = excluded.dim,
271
- vec = excluded.vec`,
272
- [skillId, contentSha256, embeddingFingerprint, vec.length, new Uint8Array(vec.buffer, vec.byteOffset, vec.byteLength)],
273
- );
274
- }
275
-
276
- /**
277
- * Skills with no usable stored vector: none at all, content changed since
278
- * embedding, or embedded at a different dimension than currently configured.
279
- */
280
- export function skillsNeedingVectors(db: Database, dimension: number, embeddingFingerprint: string): SkillRow[] {
281
- return db
282
- .query(
283
- `SELECT s.* FROM skills s
284
- LEFT JOIN vectors v ON v.skill_id = s.skill_id
285
- AND v.content_sha256 = s.content_sha256
286
- AND v.dim = ?
287
- AND v.embedding_fingerprint = ?
288
- WHERE v.skill_id IS NULL`,
289
- )
290
- .all(dimension, embeddingFingerprint) as SkillRow[];
291
- }
292
-
293
- function cosine(a: Float32Array, b: Float32Array): number {
294
- if (a.length !== b.length) return 0;
295
- let dot = 0;
296
- let normA = 0;
297
- let normB = 0;
298
- for (let i = 0; i < a.length; i++) {
299
- dot += a[i]! * b[i]!;
300
- normA += a[i]! * a[i]!;
301
- normB += b[i]! * b[i]!;
302
- }
303
- if (normA === 0 || normB === 0) return 0;
304
- return dot / (Math.sqrt(normA) * Math.sqrt(normB));
305
- }
306
-
307
- /** Brute-force cosine over every stored vector (vault is ~100 skills; no ANN). */
308
- export function vectorTopK(db: Database, query: Float32Array, k: number): SkillRow[] {
309
- const rows = db
310
- .query(
311
- `SELECT s.skill_id, s.title, s.description, s.aliases, s.content_sha256, v.vec
312
- FROM vectors v JOIN skills s ON s.skill_id = v.skill_id`,
313
- )
314
- .all() as (SkillRow & { vec: Uint8Array })[];
315
- return rows
316
- .map(({ vec, ...row }) => ({
317
- row,
318
- score: cosine(query, new Float32Array(vec.buffer, vec.byteOffset, vec.byteLength / 4)),
319
- }))
320
- .sort((a, b) => b.score - a.score)
321
- .slice(0, k)
322
- .map((r) => r.row);
323
- }
324
-
325
- export interface AuditInsert {
326
- ts: string;
327
- request_id?: string | null;
328
- query: string;
329
- retrieval: AuditRow["retrieval"];
330
- degraded_from?: string | null;
331
- degradation_reason?: string | null;
332
- candidates: AuditCandidate[];
333
- latency_ms: number;
334
- }
335
-
336
- export function insertAudit(db: Database, row: AuditInsert): void {
337
- db.run(
338
- `INSERT INTO audit (ts, request_id, query, retrieval, degraded_from, degradation_reason, candidates, latency_ms)
339
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
340
- [
341
- row.ts,
342
- row.request_id ?? null,
343
- row.query,
344
- row.retrieval,
345
- row.degraded_from ?? null,
346
- row.degradation_reason ?? null,
347
- JSON.stringify(row.candidates),
348
- row.latency_ms,
349
- ],
350
- );
351
- }
352
-
353
- /**
354
- * Correlation lookup for AC5/AC7: looks up the resolve that produced
355
- * `requestId`, or null when it names no known resolve (including malformed
356
- * input, which is never validated at the boundary per AC7).
357
- */
358
- export function getAuditRowByRequestId(
359
- db: Database,
360
- requestId: string,
361
- ): { id: number; candidates: AuditCandidate[] } | null {
362
- const row = db
363
- .query("SELECT id, candidates FROM audit WHERE request_id = ?")
364
- .get(requestId) as { id: number; candidates: string } | null;
365
- if (!row) return null;
366
- return { id: row.id, candidates: JSON.parse(row.candidates) as AuditCandidate[] };
367
- }
368
-
369
- export interface FetchInsert {
370
- ts: string;
371
- skill_id: string;
372
- request_id?: string | null;
373
- resolve_audit_id?: number | null;
374
- rank_at_resolve?: number | null;
375
- }
376
-
377
- export function insertFetch(db: Database, row: FetchInsert): void {
378
- db.run(
379
- `INSERT INTO fetch (ts, skill_id, request_id, resolve_audit_id, rank_at_resolve)
380
- VALUES (?, ?, ?, ?, ?)`,
381
- [
382
- row.ts,
383
- row.skill_id,
384
- row.request_id ?? null,
385
- row.resolve_audit_id ?? null,
386
- row.rank_at_resolve ?? null,
387
- ],
388
- );
389
- }
390
-
391
- export interface PruneResult {
392
- audit_deleted: number;
393
- fetch_deleted: number;
394
- admin_audit_deleted: number;
395
- }
396
-
397
- /**
398
- * Deletes resolve, fetch, and admin_audit rows with ts before `cutoffIso`,
399
- * each by its own timestamp; no FK ties them, so a fetch outliving its
400
- * resolve row simply reads back uncorrelated (AC7's existing null path).
401
- * admin_audit shares this cutoff rather than a separate retention config
402
- * (AC10) — its hash chain is unaffected since pruning only ever removes the
403
- * oldest rows, never rows in the middle of the chain. Reclaims the freed
404
- * pages with an incremental vacuum, which only touches audit.sqlite3 (AC16).
405
- */
406
- export function pruneAuditBefore(db: Database, cutoffIso: string): PruneResult {
407
- const auditResult = db.run("DELETE FROM audit WHERE ts < ?", [cutoffIso]);
408
- const fetchResult = db.run("DELETE FROM fetch WHERE ts < ?", [cutoffIso]);
409
- const adminAuditResult = db.run("DELETE FROM admin_audit WHERE ts < ?", [cutoffIso]);
410
- db.run("PRAGMA incremental_vacuum");
411
-
412
- return {
413
- audit_deleted: auditResult.changes,
414
- fetch_deleted: fetchResult.changes,
415
- admin_audit_deleted: adminAuditResult.changes,
416
- };
417
- }
418
-
419
- /** AC12: retentionDays <= 0 disables pruning entirely. */
420
- export function pruneAudit(db: Database, retentionDays: number, now: Date = new Date()): PruneResult {
421
- if (retentionDays <= 0) return { audit_deleted: 0, fetch_deleted: 0, admin_audit_deleted: 0 };
422
- const cutoff = new Date(now.getTime() - retentionDays * 86_400_000).toISOString();
423
- return pruneAuditBefore(db, cutoff);
424
- }
425
-
426
- export interface AdminAuditChange {
427
- key: string;
428
- old_value: unknown;
429
- new_value: unknown;
430
- }
431
-
432
- export interface AdminAuditInsert {
433
- ts: string;
434
- changes: AdminAuditChange[];
435
- resulting_revision: string;
436
- }
437
-
438
- export interface AdminAuditRow {
439
- id: number;
440
- ts: string;
441
- changes: AdminAuditChange[];
442
- resulting_revision: string;
443
- row_hash: string;
444
- prev_row_hash: string | null;
445
- }
446
-
447
- function computeAdminAuditRowHash(
448
- prevRowHash: string | null,
449
- fields: { ts: string; changes: AdminAuditChange[]; resulting_revision: string },
450
- ): string {
451
- const payload = JSON.stringify({ prev_row_hash: prevRowHash, ...fields });
452
- return createHash("sha256").update(payload).digest("hex");
453
- }
454
-
455
- /**
456
- * Appends one tamper-evident admin_audit row, chaining its hash to the
457
- * previous row's hash (or null for the first row) so any out-of-band
458
- * edit/delete breaks the chain — see verifyAdminAuditChain.
459
- */
460
- export function insertAdminAuditRow(db: Database, row: AdminAuditInsert): AdminAuditRow {
461
- const prevRow = db
462
- .query("SELECT row_hash FROM admin_audit ORDER BY id DESC LIMIT 1")
463
- .get() as { row_hash: string } | null;
464
- const prevRowHash = prevRow?.row_hash ?? null;
465
- const rowHash = computeAdminAuditRowHash(prevRowHash, row);
466
-
467
- db.run(
468
- `INSERT INTO admin_audit (ts, changes, resulting_revision, row_hash, prev_row_hash)
469
- VALUES (?, ?, ?, ?, ?)`,
470
- [row.ts, JSON.stringify(row.changes), row.resulting_revision, rowHash, prevRowHash],
471
- );
472
-
473
- const inserted = db.query("SELECT last_insert_rowid() AS id").get() as { id: number };
474
- return {
475
- id: inserted.id,
476
- ts: row.ts,
477
- changes: row.changes,
478
- resulting_revision: row.resulting_revision,
479
- row_hash: rowHash,
480
- prev_row_hash: prevRowHash,
481
- };
482
- }
483
-
484
- export interface AdminAuditChainResult {
485
- valid: boolean;
486
- broken_at_id: number | null;
487
- }
488
-
489
- /** Walks admin_audit in insertion order and reports whether the hash chain is unbroken. */
490
- export function verifyAdminAuditChain(db: Database): AdminAuditChainResult {
491
- const rows = db
492
- .query("SELECT id, ts, changes, resulting_revision, row_hash, prev_row_hash FROM admin_audit ORDER BY id ASC")
493
- .all() as { id: number; ts: string; changes: string; resulting_revision: string; row_hash: string; prev_row_hash: string | null }[];
494
-
495
- let expectedPrevHash: string | null = null;
496
- for (const row of rows) {
497
- if (row.prev_row_hash !== expectedPrevHash) {
498
- return { valid: false, broken_at_id: row.id };
499
- }
500
- const recomputed = computeAdminAuditRowHash(expectedPrevHash, {
501
- ts: row.ts,
502
- changes: JSON.parse(row.changes),
503
- resulting_revision: row.resulting_revision,
504
- });
505
- if (recomputed !== row.row_hash) {
506
- return { valid: false, broken_at_id: row.id };
507
- }
508
- expectedPrevHash = row.row_hash;
509
- }
510
- return { valid: true, broken_at_id: null };
511
- }
512
-
513
- /** Dry-run counterpart of pruneAuditBefore: counts without deleting (AC15). */
514
- export function countPrunable(db: Database, cutoffIso: string): PruneResult {
515
- const auditRow = db.query("SELECT count(*) AS n FROM audit WHERE ts < ?").get(cutoffIso) as { n: number };
516
- const fetchRow = db.query("SELECT count(*) AS n FROM fetch WHERE ts < ?").get(cutoffIso) as { n: number };
517
- const adminAuditRow = db
518
- .query("SELECT count(*) AS n FROM admin_audit WHERE ts < ?")
519
- .get(cutoffIso) as { n: number };
520
- return { audit_deleted: auditRow.n, fetch_deleted: fetchRow.n, admin_audit_deleted: adminAuditRow.n };
521
- }
1
+ // Barrel re-export — keeps all existing `import { X } from "./db"` working.
2
+ export * from "./db-index";
3
+ export * from "./db-audit";
@@ -0,0 +1,46 @@
1
+ export type GlobalFlag =
2
+ | "--json"
3
+ | "--allow-insecure"
4
+ | "--verbose"
5
+ | "--dry-run";
6
+
7
+ export type GlobalFlagWithValue = "--context" | "--server";
8
+
9
+ /**
10
+ * Checks if an argument is a global flag that takes a value (e.g. `--context`, `--server`).
11
+ * If an `allowed` list is provided, only flags in that subset are matched.
12
+ */
13
+ export function isGlobalFlagWithValue(
14
+ option: string | undefined,
15
+ allowed?: readonly GlobalFlagWithValue[] | GlobalFlagWithValue,
16
+ ...rest: GlobalFlagWithValue[]
17
+ ): boolean {
18
+ if (!option) return false;
19
+ if (allowed !== undefined) {
20
+ const list = Array.isArray(allowed) ? allowed : [allowed, ...rest];
21
+ return list.includes(option as GlobalFlagWithValue);
22
+ }
23
+ return option === "--context" || option === "--server";
24
+ }
25
+
26
+ /**
27
+ * Checks if an argument is a global flag that takes no value (e.g. `--json`, `--allow-insecure`, `--verbose`, `--dry-run`).
28
+ * If an `allowed` list is provided, only flags in that subset are matched.
29
+ */
30
+ export function isGlobalFlag(
31
+ option: string | undefined,
32
+ allowed?: readonly GlobalFlag[] | GlobalFlag,
33
+ ...rest: GlobalFlag[]
34
+ ): boolean {
35
+ if (!option) return false;
36
+ if (allowed !== undefined) {
37
+ const list = Array.isArray(allowed) ? allowed : [allowed, ...rest];
38
+ return list.includes(option as GlobalFlag);
39
+ }
40
+ return (
41
+ option === "--json" ||
42
+ option === "--allow-insecure" ||
43
+ option === "--verbose" ||
44
+ option === "--dry-run"
45
+ );
46
+ }
package/src/logger.ts ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Centralized logging helpers, all writing to stderr via console.error.
3
+ * `log` emits structured JSON ({ level, stage, ...payload }) for machine-
4
+ * readable signals like router-core's retrieval-degradation warnings.
5
+ * `redactedErrorLog` builds a plain-text [prefix, message] pair for
6
+ * operator-facing runtime errors that need secret redaction.
7
+ */
8
+
9
+ export const log = {
10
+ warn(stage: string, payload: Record<string, unknown>): void {
11
+ console.error(JSON.stringify({ level: "warn", stage, ...payload }));
12
+ },
13
+ error(stage: string, payload: Record<string, unknown>): void {
14
+ console.error(JSON.stringify({ level: "error", stage, ...payload }));
15
+ },
16
+ };
17
+
18
+ /** Pairs a fixed log prefix with a redacted error message, for console.error. */
19
+ export function redactedErrorLog(
20
+ prefix: string,
21
+ err: unknown,
22
+ redact: (text: string) => string,
23
+ ): [string, string] {
24
+ const msg = err instanceof Error ? err.message : String(err);
25
+ return [prefix, redact(msg)];
26
+ }
package/src/output.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ResolvedTarget } from "./context";
1
+ import type { ResolvedContext } from "./context";
2
2
 
3
3
  export interface JsonEnvelope<T = any> {
4
4
  schema_version: 1;
@@ -10,7 +10,7 @@ export interface JsonEnvelope<T = any> {
10
10
 
11
11
  export function formatJsonEnvelope<T>(opts: {
12
12
  ok: boolean;
13
- target: ResolvedTarget | string | { name: string; server: string };
13
+ target: ResolvedContext | string | { name: string; server: string };
14
14
  data?: T;
15
15
  error?: { code: string; message: string; details?: any } | null;
16
16
  }): JsonEnvelope<T> {
@@ -51,7 +51,7 @@ export class CliError extends Error {
51
51
  }
52
52
 
53
53
  export function emitSuccess<T>(
54
- ctx: { isJson: boolean; target?: ResolvedTarget | string | { name: string; server: string } },
54
+ ctx: { isJson: boolean; target?: ResolvedContext | string | { name: string; server: string } },
55
55
  data: T,
56
56
  renderText: () => void,
57
57
  ): void {
@@ -119,7 +119,32 @@ export function isInteractive(
119
119
  return stdoutIsTTY === true && env.TERM !== "dumb";
120
120
  }
121
121
 
122
- export function renderTargetBanner(target: ResolvedTarget): void {
122
+ /** Color is opt-out only: https://no-color.org, plus the same TTY check as isInteractive(). */
123
+ export function isColorEnabled(
124
+ env: NodeJS.ProcessEnv = process.env,
125
+ stdoutIsTTY = process.stdout.isTTY,
126
+ ): boolean {
127
+ if (env.NO_COLOR !== undefined) return false;
128
+ return isInteractive(env, stdoutIsTTY);
129
+ }
130
+
131
+ const ANSI = { reset: "\x1b[0m", bold: "\x1b[1m", red: "\x1b[31m", yellow: "\x1b[33m", green: "\x1b[32m" } as const;
132
+
133
+ function paint(code: string, text: string): string {
134
+ return isColorEnabled() ? `${code}${text}${ANSI.reset}` : text;
135
+ }
136
+
137
+ export const red = (text: string): string => paint(ANSI.red, text);
138
+ export const yellow = (text: string): string => paint(ANSI.yellow, text);
139
+ export const green = (text: string): string => paint(ANSI.green, text);
140
+ export const bold = (text: string): string => paint(ANSI.bold, text);
141
+
142
+ /** Prints a "warning: <line>" message to stderr, colored yellow when color is enabled. */
143
+ export function warn(line: string): void {
144
+ console.error(yellow(`warning: ${line}`));
145
+ }
146
+
147
+ export function renderTargetBanner(target: ResolvedContext): void {
123
148
  if (!isInteractive()) return;
124
149
  if (target.type === "local") {
125
150
  console.log(`Target: local`);
@@ -143,7 +168,7 @@ export function renderTable(columns: { key: string; header: string }[], rows: Re
143
168
  const headerLine = columns.map((col) => col.header.padEnd(widths.get(col.key) ?? 0)).join(" ");
144
169
  const sepLine = columns.map((col) => "-".repeat(widths.get(col.key) ?? 0)).join(" ");
145
170
 
146
- console.log(headerLine);
171
+ console.log(bold(headerLine));
147
172
  console.log(sepLine);
148
173
  for (const row of rows) {
149
174
  const line = columns.map((col) => String(row[col.key] ?? "").padEnd(widths.get(col.key) ?? 0)).join(" ");