@klhapp/skillmux 1.6.0 → 1.7.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/CHANGELOG.md +21 -0
- package/README.md +7 -7
- package/config.example.toml +5 -0
- package/config.remote.example.toml +4 -7
- package/docs/README.md +4 -4
- package/docs/assets/architecture.svg +1 -1
- package/docs/cli.md +4 -57
- package/docs/concepts.md +12 -14
- package/docs/configuration.md +10 -11
- package/docs/deployment.md +11 -8
- package/docs/getting-started.md +1 -1
- package/docs/mcp-routing.md +28 -23
- package/docs/ranked-shortlist-migration.md +160 -0
- package/docs/schema.json +37 -139
- package/docs/skill-management.md +7 -2
- package/docs/troubleshooting.md +12 -14
- package/package.json +1 -1
- package/src/adapters.ts +1 -536
- package/src/audit.ts +1 -3
- package/src/cli.ts +19 -254
- package/src/completions.ts +0 -4
- package/src/config-service.ts +19 -32
- package/src/config-watcher.ts +2 -6
- package/src/config.ts +61 -60
- package/src/db.ts +32 -18
- package/src/doctor.ts +1 -84
- package/src/eval.ts +143 -60
- package/src/init.ts +4 -5
- package/src/metrics.ts +1 -13
- package/src/router-core.ts +42 -149
- package/src/server.ts +13 -27
- package/src/stats.ts +126 -57
- package/src/types.ts +8 -39
- package/docs/calibration.md +0 -198
- package/src/calibrate.ts +0 -1775
- package/src/config-mutation.ts +0 -65
- package/src/dataset-generator.ts +0 -119
- package/src/decision.ts +0 -45
package/src/adapters.ts
CHANGED
|
@@ -1,26 +1,5 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
2
|
-
import { join } from "node:path";
|
|
3
|
-
import {
|
|
4
|
-
applyCalibrationRun,
|
|
5
|
-
assertCalibrationFeasibility,
|
|
6
|
-
computeCorpusFingerprint,
|
|
7
|
-
createInitialCalibrationRun,
|
|
8
|
-
finalizeCalibrationRun,
|
|
9
|
-
getCalibrationObservations,
|
|
10
|
-
getCalibrationRun,
|
|
11
|
-
insertCalibrationRun,
|
|
12
|
-
listCalibrationRuns,
|
|
13
|
-
loadDecisionCasesFromFile,
|
|
14
|
-
openCalibrateDb,
|
|
15
|
-
runCalibration,
|
|
16
|
-
saveCalibrationObservation,
|
|
17
|
-
summarizeDatasetProvenance,
|
|
18
|
-
type CalibrationResult,
|
|
19
|
-
type QueryObservation,
|
|
20
|
-
} from "./calibrate";
|
|
21
1
|
import { createClients } from "./clients";
|
|
22
|
-
import {
|
|
23
|
-
import { openIndex } from "./db";
|
|
2
|
+
import { expandHome, loadConfig, resolveConfigPath } from "./config";
|
|
24
3
|
import { CliError } from "./output";
|
|
25
4
|
import {
|
|
26
5
|
computeHash,
|
|
@@ -36,38 +15,11 @@ import {
|
|
|
36
15
|
type SetConfigResult,
|
|
37
16
|
} from "./config-service";
|
|
38
17
|
import type { ResolvedTarget } from "./context";
|
|
39
|
-
import {
|
|
40
|
-
classifyInferenceError,
|
|
41
|
-
configure,
|
|
42
|
-
retrieveAndRerankSnapshot,
|
|
43
|
-
syncVaultIfNeeded,
|
|
44
|
-
type StageTiming,
|
|
45
|
-
} from "./router-core";
|
|
46
18
|
import type { Clients, Config } from "./types";
|
|
47
19
|
|
|
48
|
-
/**
|
|
49
|
-
* Maximum retry attempts for transient reranker availability errors during calibration.
|
|
50
|
-
*
|
|
51
|
-
* Single-capacity remote reranker endpoints can suffer isolated blips (e.g. transient
|
|
52
|
-
* connection reset or momentary 503) during long multi-case calibration runs.
|
|
53
|
-
* A small bounded budget of 2 retries (3 attempts total) allows calibration to ride out
|
|
54
|
-
* transient blips without stalling on hard failures.
|
|
55
|
-
*/
|
|
56
|
-
export const CALIBRATION_RERANK_MAX_RETRIES = 2;
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* Base backoff delay (ms) between reranker retries during calibration.
|
|
60
|
-
*
|
|
61
|
-
* A conservative nonzero delay gives recovering remote endpoints time to settle.
|
|
62
|
-
* Because reranker admission is strictly FIFO serialized, waiting workers remain
|
|
63
|
-
* queued rather than creating synchronized retry storms.
|
|
64
|
-
*/
|
|
65
|
-
export const CALIBRATION_RERANK_RETRY_BACKOFF_MS = 250;
|
|
66
|
-
|
|
67
20
|
export interface Capabilities {
|
|
68
21
|
config_read: boolean;
|
|
69
22
|
config_write: boolean;
|
|
70
|
-
calibration: boolean;
|
|
71
23
|
persistence: "writable" | "externally_managed";
|
|
72
24
|
reloadable_keys: string[];
|
|
73
25
|
restart_required_keys: string[];
|
|
@@ -79,43 +31,6 @@ export interface TargetAdapterOptions {
|
|
|
79
31
|
clients?: Clients;
|
|
80
32
|
}
|
|
81
33
|
|
|
82
|
-
/**
|
|
83
|
-
* Aggregate timing data collected during a single calibrateRun invocation.
|
|
84
|
-
*
|
|
85
|
-
* All durations are in milliseconds and are non-negative.
|
|
86
|
-
*
|
|
87
|
-
* Cumulative fields (cumulative_embedding_ms, cumulative_lexical_ms,
|
|
88
|
-
* cumulative_vector_ms, cumulative_reranker_ms, cumulative_checkpoint_ms)
|
|
89
|
-
* represent total worker time summed across all concurrent query retrievals
|
|
90
|
-
* or checkpoint writes. Because queries run concurrently, the sum of these
|
|
91
|
-
* cumulative fields may exceed wall_ms — they measure how much worker time
|
|
92
|
-
* each stage consumed, not how much wall-clock time it contributed.
|
|
93
|
-
*/
|
|
94
|
-
export interface CalibrationTimingSummary {
|
|
95
|
-
/** Total number of dataset cases. */
|
|
96
|
-
cases_total: number;
|
|
97
|
-
/** Cases actually retrieved in this invocation (not reused from a prior run). */
|
|
98
|
-
cases_executed: number;
|
|
99
|
-
/** Cases loaded from a prior interrupted run (resume observations). */
|
|
100
|
-
cases_reused: number;
|
|
101
|
-
/** Wall-clock duration of the full calibrateRun operation (ms). */
|
|
102
|
-
wall_ms: number;
|
|
103
|
-
/** Duration of the one-time vault synchronization before retrieval (ms). */
|
|
104
|
-
vault_sync_ms: number;
|
|
105
|
-
/** Cumulative worker time spent in embedding across all queries (ms). */
|
|
106
|
-
cumulative_embedding_ms: number;
|
|
107
|
-
/** Cumulative worker time spent in lexical search across all queries (ms). */
|
|
108
|
-
cumulative_lexical_ms: number;
|
|
109
|
-
/** Cumulative worker time spent in vector search across all queries (ms). */
|
|
110
|
-
cumulative_vector_ms: number;
|
|
111
|
-
/** Cumulative worker time spent in reranking across all queries (ms). */
|
|
112
|
-
cumulative_reranker_ms: number;
|
|
113
|
-
/** Cumulative worker time spent writing observation checkpoints (ms). */
|
|
114
|
-
cumulative_checkpoint_ms: number;
|
|
115
|
-
/** Duration of threshold selection and test-split certification (ms). */
|
|
116
|
-
policy_evaluation_ms: number;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
34
|
export interface TargetAdapter {
|
|
120
35
|
getCapabilities(): Promise<Capabilities>;
|
|
121
36
|
getConfigShow(): Promise<{ effective: Config; sources: Record<string, string>; active_revision: string }>;
|
|
@@ -124,26 +39,6 @@ export interface TargetAdapter {
|
|
|
124
39
|
configDiff(): Promise<{ diff: Record<string, { prior: unknown; resulting: unknown }> }>;
|
|
125
40
|
configSet(key: string, rawValStr: string, opts?: { dryRun?: boolean }): Promise<SetConfigResult>;
|
|
126
41
|
configStatus(): Promise<ConfigStatusResponse>;
|
|
127
|
-
calibrateRun(opts?: {
|
|
128
|
-
datasetPath?: string;
|
|
129
|
-
minAutoMatchPrecision?: number;
|
|
130
|
-
minRetrievalRecallAtK?: number;
|
|
131
|
-
minDeliveredShortlistRecallAtK?: number;
|
|
132
|
-
minAutoMatchCount?: number;
|
|
133
|
-
tuneAutoMatchPrecisionBuffer?: number;
|
|
134
|
-
tuneAutoMatchCountBuffer?: number;
|
|
135
|
-
tuneDeliveredShortlistRecallBuffer?: number;
|
|
136
|
-
concurrency?: number;
|
|
137
|
-
resumeRunId?: string;
|
|
138
|
-
onProgress?: (completed: number, total: number) => void;
|
|
139
|
-
/** Opt-in timing collection. When true, onTimingSummary is called after a non-throwing result. */
|
|
140
|
-
timing?: boolean;
|
|
141
|
-
/** Called after calibration completes or fails-gates (not called on throws). */
|
|
142
|
-
onTimingSummary?: (summary: CalibrationTimingSummary) => void;
|
|
143
|
-
}): Promise<{ run_id?: string; result?: CalibrationResult }>;
|
|
144
|
-
calibrateList(): Promise<any[]>;
|
|
145
|
-
calibrateShow(runId: string): Promise<any>;
|
|
146
|
-
calibrateApply(runId: string): Promise<any>;
|
|
147
42
|
}
|
|
148
43
|
|
|
149
44
|
export function isLoopbackHost(hostname: string): boolean {
|
|
@@ -170,7 +65,6 @@ export class LocalAdapter implements TargetAdapter {
|
|
|
170
65
|
return {
|
|
171
66
|
config_read: true,
|
|
172
67
|
config_write: !isExternallyManaged,
|
|
173
|
-
calibration: true,
|
|
174
68
|
persistence: isExternallyManaged ? "externally_managed" : "writable",
|
|
175
69
|
reloadable_keys: RELOADABLE_KEYS,
|
|
176
70
|
restart_required_keys: RESTART_REQUIRED_KEYS,
|
|
@@ -222,393 +116,6 @@ export class LocalAdapter implements TargetAdapter {
|
|
|
222
116
|
async configStatus(): Promise<ConfigStatusResponse> {
|
|
223
117
|
return getLocalConfigStatus(this.configPath);
|
|
224
118
|
}
|
|
225
|
-
|
|
226
|
-
async calibrateRun(opts?: {
|
|
227
|
-
datasetPath?: string;
|
|
228
|
-
minAutoMatchPrecision?: number;
|
|
229
|
-
minRetrievalRecallAtK?: number;
|
|
230
|
-
minDeliveredShortlistRecallAtK?: number;
|
|
231
|
-
minAutoMatchCount?: number;
|
|
232
|
-
tuneAutoMatchPrecisionBuffer?: number;
|
|
233
|
-
tuneAutoMatchCountBuffer?: number;
|
|
234
|
-
tuneDeliveredShortlistRecallBuffer?: number;
|
|
235
|
-
concurrency?: number;
|
|
236
|
-
resumeRunId?: string;
|
|
237
|
-
onProgress?: (completed: number, total: number) => void;
|
|
238
|
-
timing?: boolean;
|
|
239
|
-
onTimingSummary?: (summary: CalibrationTimingSummary) => void;
|
|
240
|
-
}): Promise<{ run_id?: string; result?: CalibrationResult }> {
|
|
241
|
-
const collectTiming = opts?.timing === true;
|
|
242
|
-
const wallStart = collectTiming ? performance.now() : 0;
|
|
243
|
-
|
|
244
|
-
const config = await loadConfig(this.configPath);
|
|
245
|
-
const baseClients = this.clients ?? createClients(config);
|
|
246
|
-
|
|
247
|
-
// Bounded admission at the calibration reranker boundary: serialize rerank calls
|
|
248
|
-
// so concurrent case retrieval (embedding, lexical, vector) does not overwhelm
|
|
249
|
-
// a single-capacity remote reranker endpoint.
|
|
250
|
-
//
|
|
251
|
-
// If an admitted request encounters a transient reranker_unavailable error,
|
|
252
|
-
// retry with conservative backoff up to CALIBRATION_RERANK_MAX_RETRIES.
|
|
253
|
-
// Non-availability errors (protocol, timeouts) and permanent failures fail closed.
|
|
254
|
-
let rerankQueue = Promise.resolve() as Promise<any>;
|
|
255
|
-
const serializedRerank: typeof baseClients.rerank = baseClients.rerank
|
|
256
|
-
? (query, docs) => {
|
|
257
|
-
const run = async () => {
|
|
258
|
-
let attempt = 0;
|
|
259
|
-
while (true) {
|
|
260
|
-
try {
|
|
261
|
-
return await baseClients.rerank!(query, docs);
|
|
262
|
-
} catch (err) {
|
|
263
|
-
attempt++;
|
|
264
|
-
const degradationReason = classifyInferenceError("reranker", err);
|
|
265
|
-
if (
|
|
266
|
-
degradationReason === "reranker_unavailable" &&
|
|
267
|
-
attempt <= CALIBRATION_RERANK_MAX_RETRIES
|
|
268
|
-
) {
|
|
269
|
-
await Bun.sleep(CALIBRATION_RERANK_RETRY_BACKOFF_MS * attempt);
|
|
270
|
-
continue;
|
|
271
|
-
}
|
|
272
|
-
throw err;
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
};
|
|
276
|
-
const next = rerankQueue.then(run, run);
|
|
277
|
-
rerankQueue = next.catch(() => {});
|
|
278
|
-
return next;
|
|
279
|
-
}
|
|
280
|
-
: undefined;
|
|
281
|
-
|
|
282
|
-
const clients: Clients = {
|
|
283
|
-
...baseClients,
|
|
284
|
-
rerank: serializedRerank,
|
|
285
|
-
};
|
|
286
|
-
configure({ config, clients });
|
|
287
|
-
|
|
288
|
-
// Measure vault synchronization
|
|
289
|
-
let vault_sync_ms = 0;
|
|
290
|
-
if (collectTiming) {
|
|
291
|
-
const t0 = performance.now();
|
|
292
|
-
await syncVaultIfNeeded();
|
|
293
|
-
vault_sync_ms = Math.max(0, performance.now() - t0);
|
|
294
|
-
} else {
|
|
295
|
-
await syncVaultIfNeeded();
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
const candidateLimit =
|
|
299
|
-
config.output?.ambiguous_candidate_limit ?? config.thresholds?.candidate_limit ?? 5;
|
|
300
|
-
const datasetFile = opts?.datasetPath ?? join(expandHome(config.state_dir), "queries.json");
|
|
301
|
-
const indexDb = openIndex(expandHome(config.state_dir));
|
|
302
|
-
let indexedSkills: Array<{ skill_id: string; content_sha256: string }>;
|
|
303
|
-
let corpusFingerprint: string;
|
|
304
|
-
try {
|
|
305
|
-
indexedSkills = indexDb
|
|
306
|
-
.query("SELECT skill_id, content_sha256 FROM skills ORDER BY skill_id")
|
|
307
|
-
.all() as Array<{ skill_id: string; content_sha256: string }>;
|
|
308
|
-
corpusFingerprint = computeCorpusFingerprint(indexDb);
|
|
309
|
-
} finally {
|
|
310
|
-
indexDb.close();
|
|
311
|
-
}
|
|
312
|
-
const cases = loadDecisionCasesFromFile(
|
|
313
|
-
datasetFile,
|
|
314
|
-
indexedSkills.map((skill) => skill.skill_id),
|
|
315
|
-
);
|
|
316
|
-
|
|
317
|
-
const fingerprint = rerankerFingerprint(config);
|
|
318
|
-
if (!fingerprint) {
|
|
319
|
-
throw new Error("A configured remote reranker is required to record calibration.");
|
|
320
|
-
}
|
|
321
|
-
const datasetText = await Bun.file(datasetFile).text();
|
|
322
|
-
const datasetHash = createHash("sha256").update(datasetText).digest("hex");
|
|
323
|
-
const embedFp = embeddingFingerprint(config);
|
|
324
|
-
const recallSettings = {
|
|
325
|
-
k_lexical: config.recall.k_lexical,
|
|
326
|
-
k_vector: config.recall.k_vector,
|
|
327
|
-
k_rerank: config.recall.k_rerank ?? Math.min(10, config.recall.k_lexical + config.recall.k_vector),
|
|
328
|
-
};
|
|
329
|
-
const minAutoMatchPrecision = opts?.minAutoMatchPrecision ?? 0.75;
|
|
330
|
-
const minAutoMatchCount = opts?.minAutoMatchCount ?? 15;
|
|
331
|
-
const minDeliveredShortlistRecallAtK =
|
|
332
|
-
opts?.minDeliveredShortlistRecallAtK ??
|
|
333
|
-
opts?.minRetrievalRecallAtK ??
|
|
334
|
-
0.95;
|
|
335
|
-
const minShortlistRecallAt5 = opts?.minRetrievalRecallAtK ?? 0.95;
|
|
336
|
-
const tuneAutoMatchPrecisionBuffer = opts?.tuneAutoMatchPrecisionBuffer ?? 0.03;
|
|
337
|
-
const tuneAutoMatchCountBuffer = opts?.tuneAutoMatchCountBuffer ?? 3;
|
|
338
|
-
const tuneDeliveredShortlistRecallBuffer = opts?.tuneDeliveredShortlistRecallBuffer ?? 0.02;
|
|
339
|
-
const concurrency = opts?.concurrency ?? 4;
|
|
340
|
-
|
|
341
|
-
assertCalibrationFeasibility(cases, {
|
|
342
|
-
minAutoMatchPrecision,
|
|
343
|
-
minAutoMatchCount,
|
|
344
|
-
minDeliveredShortlistRecallAtK,
|
|
345
|
-
tuneAutoMatchPrecisionBuffer,
|
|
346
|
-
tuneAutoMatchCountBuffer,
|
|
347
|
-
tuneDeliveredShortlistRecallBuffer,
|
|
348
|
-
});
|
|
349
|
-
|
|
350
|
-
const db = openCalibrateDb(expandHome(config.state_dir));
|
|
351
|
-
let runId: string;
|
|
352
|
-
let initialObservations: Map<number, QueryObservation> | undefined = undefined;
|
|
353
|
-
|
|
354
|
-
// Cumulative timing accumulators (only used when collectTiming=true)
|
|
355
|
-
let cumulative_embedding_ms = 0;
|
|
356
|
-
let cumulative_lexical_ms = 0;
|
|
357
|
-
let cumulative_vector_ms = 0;
|
|
358
|
-
let cumulative_reranker_ms = 0;
|
|
359
|
-
let cumulative_checkpoint_ms = 0;
|
|
360
|
-
|
|
361
|
-
try {
|
|
362
|
-
if (opts?.resumeRunId) {
|
|
363
|
-
runId = opts.resumeRunId;
|
|
364
|
-
const existingRun = getCalibrationRun(db, runId);
|
|
365
|
-
if (!existingRun) {
|
|
366
|
-
throw new Error(`Calibration run "${runId}" not found`);
|
|
367
|
-
}
|
|
368
|
-
if (existingRun.status !== "running") {
|
|
369
|
-
throw new Error(`Cannot resume completed calibration run "${runId}"`);
|
|
370
|
-
}
|
|
371
|
-
if (existingRun.dataset_hash !== datasetHash) {
|
|
372
|
-
throw new Error("Dataset hash mismatch: cannot resume run with a different dataset");
|
|
373
|
-
}
|
|
374
|
-
if (existingRun.corpus_fingerprint !== corpusFingerprint) {
|
|
375
|
-
throw new Error("Corpus fingerprint mismatch: cannot resume run with modified vault skills");
|
|
376
|
-
}
|
|
377
|
-
if (existingRun.embedding_fingerprint !== embedFp) {
|
|
378
|
-
throw new Error("Embedding fingerprint mismatch: cannot resume run with different embedding configuration");
|
|
379
|
-
}
|
|
380
|
-
if (existingRun.reranker_fingerprint !== fingerprint) {
|
|
381
|
-
throw new Error("Reranker fingerprint mismatch: cannot resume run with different reranker configuration");
|
|
382
|
-
}
|
|
383
|
-
if (existingRun.candidate_limit !== candidateLimit) {
|
|
384
|
-
throw new Error("Candidate limit mismatch: cannot resume run with different candidate limit");
|
|
385
|
-
}
|
|
386
|
-
if (
|
|
387
|
-
existingRun.recall_settings &&
|
|
388
|
-
JSON.stringify(existingRun.recall_settings) !== JSON.stringify(recallSettings)
|
|
389
|
-
) {
|
|
390
|
-
throw new Error("Recall settings mismatch: cannot resume run with different recall parameters");
|
|
391
|
-
}
|
|
392
|
-
if (existingRun.min_auto_match_precision !== minAutoMatchPrecision) {
|
|
393
|
-
throw new Error("Certification gate mismatch: min_auto_match_precision differs from original run");
|
|
394
|
-
}
|
|
395
|
-
if ((existingRun.min_auto_match_count ?? 1) !== minAutoMatchCount) {
|
|
396
|
-
throw new Error("Certification gate mismatch: min_auto_match_count differs from original run");
|
|
397
|
-
}
|
|
398
|
-
if (
|
|
399
|
-
(existingRun.min_delivered_shortlist_recall_at_k ?? existingRun.min_shortlist_recall_at_5) !==
|
|
400
|
-
minDeliveredShortlistRecallAtK
|
|
401
|
-
) {
|
|
402
|
-
throw new Error(
|
|
403
|
-
"Certification gate mismatch: min_delivered_shortlist_recall_at_k differs from original run",
|
|
404
|
-
);
|
|
405
|
-
}
|
|
406
|
-
if (existingRun.min_shortlist_recall_at_5 !== minShortlistRecallAt5) {
|
|
407
|
-
throw new Error("Certification gate mismatch: min_retrieval_recall_at_k differs from original run");
|
|
408
|
-
}
|
|
409
|
-
if (
|
|
410
|
-
existingRun.tune_auto_match_precision_buffer !== undefined &&
|
|
411
|
-
existingRun.tune_auto_match_precision_buffer !== tuneAutoMatchPrecisionBuffer
|
|
412
|
-
) {
|
|
413
|
-
throw new Error(
|
|
414
|
-
"Certification gate mismatch: tune_auto_match_precision_buffer differs from original run",
|
|
415
|
-
);
|
|
416
|
-
}
|
|
417
|
-
if (
|
|
418
|
-
existingRun.tune_auto_match_count_buffer !== undefined &&
|
|
419
|
-
existingRun.tune_auto_match_count_buffer !== tuneAutoMatchCountBuffer
|
|
420
|
-
) {
|
|
421
|
-
throw new Error(
|
|
422
|
-
"Certification gate mismatch: tune_auto_match_count_buffer differs from original run",
|
|
423
|
-
);
|
|
424
|
-
}
|
|
425
|
-
if (
|
|
426
|
-
existingRun.tune_delivered_shortlist_recall_buffer !== undefined &&
|
|
427
|
-
existingRun.tune_delivered_shortlist_recall_buffer !== tuneDeliveredShortlistRecallBuffer
|
|
428
|
-
) {
|
|
429
|
-
throw new Error(
|
|
430
|
-
"Certification gate mismatch: tune_delivered_shortlist_recall_buffer differs from original run",
|
|
431
|
-
);
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
initialObservations = getCalibrationObservations(db, runId);
|
|
435
|
-
if (initialObservations.size === 0 && existingRun.observations && existingRun.observations.length > 0) {
|
|
436
|
-
existingRun.observations.forEach((obs, idx) => initialObservations!.set(idx, obs));
|
|
437
|
-
}
|
|
438
|
-
} else {
|
|
439
|
-
runId = `run_${crypto.randomUUID()}`;
|
|
440
|
-
createInitialCalibrationRun(db, {
|
|
441
|
-
run_id: runId,
|
|
442
|
-
created_at: new Date().toISOString(),
|
|
443
|
-
status: "running",
|
|
444
|
-
reranker_fingerprint: fingerprint,
|
|
445
|
-
embedding_fingerprint: embedFp,
|
|
446
|
-
corpus_fingerprint: corpusFingerprint,
|
|
447
|
-
dataset_hash: datasetHash,
|
|
448
|
-
dataset_provenance: summarizeDatasetProvenance(cases),
|
|
449
|
-
recall_settings: recallSettings,
|
|
450
|
-
candidate_limit: candidateLimit,
|
|
451
|
-
min_auto_match_precision: minAutoMatchPrecision,
|
|
452
|
-
min_auto_match_count: minAutoMatchCount,
|
|
453
|
-
min_delivered_shortlist_recall_at_k: minDeliveredShortlistRecallAtK,
|
|
454
|
-
min_shortlist_recall_at_5: minShortlistRecallAt5,
|
|
455
|
-
tune_auto_match_precision_buffer: tuneAutoMatchPrecisionBuffer,
|
|
456
|
-
tune_auto_match_count_buffer: tuneAutoMatchCountBuffer,
|
|
457
|
-
tune_delivered_shortlist_recall_buffer: tuneDeliveredShortlistRecallBuffer,
|
|
458
|
-
});
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
const casesReused = initialObservations?.size ?? 0;
|
|
462
|
-
|
|
463
|
-
const onProgress = opts?.onProgress ?? ((completed, total) => {
|
|
464
|
-
process.stderr.write(`Calibration observations: ${completed}/${total}\n`);
|
|
465
|
-
});
|
|
466
|
-
|
|
467
|
-
const retrievalTiming = collectTiming
|
|
468
|
-
? {
|
|
469
|
-
onTiming: (timing: StageTiming) => {
|
|
470
|
-
cumulative_embedding_ms += timing.embedding_ms;
|
|
471
|
-
cumulative_lexical_ms += timing.lexical_ms;
|
|
472
|
-
cumulative_vector_ms += timing.vector_ms;
|
|
473
|
-
cumulative_reranker_ms += timing.reranker_ms;
|
|
474
|
-
},
|
|
475
|
-
}
|
|
476
|
-
: undefined;
|
|
477
|
-
|
|
478
|
-
const getRankedCandidates = async (query: string) => {
|
|
479
|
-
const res = await retrieveAndRerankSnapshot(
|
|
480
|
-
{ query, forceLexical: false },
|
|
481
|
-
retrievalTiming,
|
|
482
|
-
);
|
|
483
|
-
if (res.retrieval !== "reranked") {
|
|
484
|
-
throw new Error(
|
|
485
|
-
"Calibration requires successful hybrid retrieval and reranking for every query.",
|
|
486
|
-
);
|
|
487
|
-
}
|
|
488
|
-
return res.candidates.map((candidate) => ({
|
|
489
|
-
skill_id: candidate.skill_id,
|
|
490
|
-
score: candidate.score ?? 0,
|
|
491
|
-
}));
|
|
492
|
-
};
|
|
493
|
-
|
|
494
|
-
let policyEvaluationStart = 0;
|
|
495
|
-
|
|
496
|
-
const result = await runCalibration({
|
|
497
|
-
cases,
|
|
498
|
-
getRankedCandidates,
|
|
499
|
-
reranker: clients.rerank,
|
|
500
|
-
candidateLimit,
|
|
501
|
-
minAutoMatchPrecision,
|
|
502
|
-
minRetrievalRecallAtK: minShortlistRecallAt5,
|
|
503
|
-
minDeliveredShortlistRecallAtK,
|
|
504
|
-
minAutoMatchCount,
|
|
505
|
-
tuneAutoMatchPrecisionBuffer,
|
|
506
|
-
tuneAutoMatchCountBuffer,
|
|
507
|
-
tuneDeliveredShortlistRecallBuffer,
|
|
508
|
-
concurrency,
|
|
509
|
-
initialObservations,
|
|
510
|
-
onProgress,
|
|
511
|
-
onObservation: collectTiming
|
|
512
|
-
? (obs, caseIdx) => {
|
|
513
|
-
const t0 = performance.now();
|
|
514
|
-
saveCalibrationObservation(db, runId, caseIdx, obs);
|
|
515
|
-
const t1 = performance.now();
|
|
516
|
-
cumulative_checkpoint_ms += Math.max(0, t1 - t0);
|
|
517
|
-
}
|
|
518
|
-
: (obs, caseIdx) => {
|
|
519
|
-
saveCalibrationObservation(db, runId, caseIdx, obs);
|
|
520
|
-
},
|
|
521
|
-
onObservationsReady: collectTiming
|
|
522
|
-
? () => {
|
|
523
|
-
policyEvaluationStart = performance.now();
|
|
524
|
-
}
|
|
525
|
-
: undefined,
|
|
526
|
-
});
|
|
527
|
-
|
|
528
|
-
// policy_evaluation_ms: threshold selection + certification duration
|
|
529
|
-
const policyEvalEnd = collectTiming ? performance.now() : 0;
|
|
530
|
-
|
|
531
|
-
finalizeCalibrationRun(db, {
|
|
532
|
-
run_id: runId,
|
|
533
|
-
status: result.status,
|
|
534
|
-
failed_reason: result.failed_reason,
|
|
535
|
-
selected_thresholds: result.selected_thresholds,
|
|
536
|
-
tune_metrics: result.tune_metrics,
|
|
537
|
-
test_metrics: result.test_metrics,
|
|
538
|
-
tune_gate_slack: result.tune_gate_slack,
|
|
539
|
-
observations: result.observations,
|
|
540
|
-
});
|
|
541
|
-
|
|
542
|
-
// Emit timing summary after a non-throwing result (completed or failed-gates).
|
|
543
|
-
// Never called when calibrateRun throws.
|
|
544
|
-
if (collectTiming && opts?.onTimingSummary) {
|
|
545
|
-
const wall_ms = Math.max(0, performance.now() - wallStart);
|
|
546
|
-
// policy_evaluation_ms covers threshold selection + test-split certification,
|
|
547
|
-
// the internal work runCalibration does after all observations are collected.
|
|
548
|
-
const policy_evaluation_ms = Math.max(0, policyEvalEnd - policyEvaluationStart);
|
|
549
|
-
|
|
550
|
-
const cases_reused = casesReused;
|
|
551
|
-
const cases_total = cases.length;
|
|
552
|
-
const cases_executed = cases_total - cases_reused;
|
|
553
|
-
|
|
554
|
-
opts.onTimingSummary({
|
|
555
|
-
cases_total,
|
|
556
|
-
cases_executed,
|
|
557
|
-
cases_reused,
|
|
558
|
-
wall_ms,
|
|
559
|
-
vault_sync_ms,
|
|
560
|
-
cumulative_embedding_ms,
|
|
561
|
-
cumulative_lexical_ms,
|
|
562
|
-
cumulative_vector_ms,
|
|
563
|
-
cumulative_reranker_ms,
|
|
564
|
-
cumulative_checkpoint_ms,
|
|
565
|
-
policy_evaluation_ms,
|
|
566
|
-
});
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
return { run_id: runId, result };
|
|
570
|
-
} finally {
|
|
571
|
-
db.close();
|
|
572
|
-
}
|
|
573
|
-
}
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
async calibrateList(): Promise<any[]> {
|
|
577
|
-
const config = await loadConfig(this.configPath);
|
|
578
|
-
const db = openCalibrateDb(expandHome(config.state_dir));
|
|
579
|
-
try {
|
|
580
|
-
return listCalibrationRuns(db);
|
|
581
|
-
} finally {
|
|
582
|
-
db.close();
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
async calibrateShow(runId: string): Promise<any> {
|
|
587
|
-
const config = await loadConfig(this.configPath);
|
|
588
|
-
const db = openCalibrateDb(expandHome(config.state_dir));
|
|
589
|
-
try {
|
|
590
|
-
const run = getCalibrationRun(db, runId);
|
|
591
|
-
if (!run) throw new Error(`Calibration run "${runId}" not found`);
|
|
592
|
-
return run;
|
|
593
|
-
} finally {
|
|
594
|
-
db.close();
|
|
595
|
-
}
|
|
596
|
-
}
|
|
597
|
-
|
|
598
|
-
async calibrateApply(runId: string): Promise<any> {
|
|
599
|
-
const config = await loadConfig(this.configPath);
|
|
600
|
-
const db = openCalibrateDb(expandHome(config.state_dir));
|
|
601
|
-
try {
|
|
602
|
-
const run = getCalibrationRun(db, runId);
|
|
603
|
-
if (!run) throw new Error(`Calibration run "${runId}" not found`);
|
|
604
|
-
await applyCalibrationRun(db, runId, expandHome(this.configPath), {
|
|
605
|
-
currentRerankerFingerprint: rerankerFingerprint(config),
|
|
606
|
-
});
|
|
607
|
-
return { ok: true, run_id: runId };
|
|
608
|
-
} finally {
|
|
609
|
-
db.close();
|
|
610
|
-
}
|
|
611
|
-
}
|
|
612
119
|
}
|
|
613
120
|
|
|
614
121
|
export class RemoteAdapter implements TargetAdapter {
|
|
@@ -774,48 +281,6 @@ export class RemoteAdapter implements TargetAdapter {
|
|
|
774
281
|
}
|
|
775
282
|
return data.runtime;
|
|
776
283
|
}
|
|
777
|
-
|
|
778
|
-
async calibrateRun(opts?: {
|
|
779
|
-
datasetPath?: string;
|
|
780
|
-
minAutoMatchPrecision?: number;
|
|
781
|
-
minRetrievalRecallAtK?: number;
|
|
782
|
-
minDeliveredShortlistRecallAtK?: number;
|
|
783
|
-
minAutoMatchCount?: number;
|
|
784
|
-
tuneAutoMatchPrecisionBuffer?: number;
|
|
785
|
-
tuneAutoMatchCountBuffer?: number;
|
|
786
|
-
tuneDeliveredShortlistRecallBuffer?: number;
|
|
787
|
-
concurrency?: number;
|
|
788
|
-
resumeRunId?: string;
|
|
789
|
-
onProgress?: (completed: number, total: number) => void;
|
|
790
|
-
timing?: boolean;
|
|
791
|
-
onTimingSummary?: (summary: CalibrationTimingSummary) => void;
|
|
792
|
-
}): Promise<{ run_id?: string; result?: CalibrationResult }> {
|
|
793
|
-
void opts;
|
|
794
|
-
throw this.remoteCalibrationNotImplemented();
|
|
795
|
-
}
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
async calibrateList(): Promise<any[]> {
|
|
799
|
-
throw this.remoteCalibrationNotImplemented();
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
async calibrateShow(runId: string): Promise<any> {
|
|
803
|
-
void runId;
|
|
804
|
-
throw this.remoteCalibrationNotImplemented();
|
|
805
|
-
}
|
|
806
|
-
|
|
807
|
-
async calibrateApply(runId: string): Promise<any> {
|
|
808
|
-
void runId;
|
|
809
|
-
throw this.remoteCalibrationNotImplemented();
|
|
810
|
-
}
|
|
811
|
-
|
|
812
|
-
private remoteCalibrationNotImplemented(): CliError {
|
|
813
|
-
return new CliError(
|
|
814
|
-
`Remote calibration is not implemented for target ${this.serverUrl}; ` +
|
|
815
|
-
"run `skillmux calibrate` against a local target.",
|
|
816
|
-
2,
|
|
817
|
-
);
|
|
818
|
-
}
|
|
819
284
|
}
|
|
820
285
|
|
|
821
286
|
export function createTargetAdapter(target: ResolvedTarget, opts?: TargetAdapterOptions): TargetAdapter {
|
package/src/audit.ts
CHANGED
|
@@ -1,15 +1,13 @@
|
|
|
1
1
|
import type { AuditRow } from "./types";
|
|
2
2
|
|
|
3
|
-
/** Shape an audit row to exactly the
|
|
3
|
+
/** Shape an audit row to exactly the AuditRow fields — nothing extra survives. */
|
|
4
4
|
export function buildAuditRow(row: AuditRow): AuditRow {
|
|
5
5
|
const built: AuditRow = {
|
|
6
6
|
id: row.id,
|
|
7
7
|
ts: row.ts,
|
|
8
8
|
query: row.query,
|
|
9
|
-
outcome: row.outcome,
|
|
10
9
|
retrieval: row.retrieval,
|
|
11
10
|
candidates: row.candidates.map((c) => ({ skill_id: c.skill_id, score: c.score })),
|
|
12
|
-
selected_skill_id: row.selected_skill_id,
|
|
13
11
|
latency_ms: row.latency_ms,
|
|
14
12
|
};
|
|
15
13
|
if (row.degraded_from !== undefined && row.degraded_from !== null) {
|