thumbgate 1.39.1 → 1.40.2
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/plugin.json +1 -1
- package/.well-known/llms.txt +2 -2
- package/.well-known/mcp/server-card.json +1 -1
- package/README.md +5 -4
- package/adapters/claude/.mcp.json +6 -2
- package/adapters/codex/config.toml +5 -0
- package/adapters/forge/forge.yaml +4 -4
- package/adapters/future-agi/.mcp.json +1 -1
- package/adapters/future-agi/config.toml +1 -1
- package/adapters/future-agi/opencode.json +1 -1
- package/adapters/herdr/herdr-plugin.toml +2 -2
- package/adapters/mcp/server-stdio.js +82 -7
- package/adapters/opencode/opencode.json +1 -1
- package/bin/cli.js +128 -15
- package/config/brand-standards.json +131 -0
- package/config/gates/default.json +18 -1
- package/config/github-about.json +1 -1
- package/config/mcp-allowlists.json +16 -3
- package/config/merge-quality-checks.json +1 -0
- package/config/post-deploy-marketing-pages.json +3 -3
- package/config/schemas/task-outcome-receipt.schema.json +9 -0
- package/openapi/openapi.yaml +7 -3
- package/package.json +98 -31
- package/public/about.html +2 -2
- package/public/admin.html +771 -0
- package/public/agent-manager.html +3 -3
- package/public/agents-cost-savings.html +1 -1
- package/public/ai-malpractice-prevention.html +12 -12
- package/public/architecture.html +0 -1
- package/public/assets/diagrams/decision.svg +3 -3
- package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
- package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
- package/public/blog/git-at-agent-scale.html +2 -2
- package/public/blog/inside-your-boundary.html +1 -1
- package/public/blog/process-over-outcome-gates.html +1 -1
- package/public/case-studies.html +1 -2
- package/public/codex-enterprise.html +1 -1
- package/public/codex-plugin.html +1 -1
- package/public/dashboard.html +773 -481
- package/public/diagnostic.html +8 -3
- package/public/enterprise-governance.html +26 -174
- package/public/eval-scorecard.html +3 -4
- package/public/eval-scorecard.json +2 -2
- package/public/evaluations.html +0 -1
- package/public/founders.html +3 -3
- package/public/gaming-playbook.html +4 -4
- package/public/guide.html +3 -5
- package/public/index.html +181 -205
- package/public/install.html +12 -11
- package/public/js/buyer-intent.js +49 -8
- package/public/lessons.html +103 -46
- package/public/numbers.html +32 -33
- package/public/operator-framework.html +44 -72
- package/public/peter.html +3 -3
- package/public/platform-partners.html +1 -1
- package/public/pricing.html +61 -327
- package/public/pro.html +3 -1
- package/public/project-switcher.js +76 -0
- package/public/whitepaper.html +1 -2
- package/scripts/activation-quickstart.js +15 -3
- package/scripts/activation-tracker.js +280 -3
- package/scripts/agent-action-inventory.js +235 -143
- package/scripts/agent-operations-planner.js +1 -1
- package/scripts/agent-readiness.js +36 -6
- package/scripts/agentic-prompt-pipelines.js +901 -0
- package/scripts/analytics-report.js +363 -0
- package/scripts/analytics-window.js +7 -1
- package/scripts/async-job-runner.js +66 -11
- package/scripts/audit-trail.js +37 -24
- package/scripts/auto-context-packs.js +249 -0
- package/scripts/auto-promote-gates.js +37 -27
- package/scripts/backfill-lesson-scopes.js +122 -0
- package/scripts/billing-setup.js +137 -0
- package/scripts/billing.js +889 -132
- package/scripts/bot-detection.js +112 -0
- package/scripts/brand-standards-gate.js +571 -0
- package/scripts/chatgpt-ads-readiness-pack.js +1 -1
- package/scripts/check-update.js +236 -0
- package/scripts/cli-schema.js +1 -1
- package/scripts/commercial-offer.js +2 -2
- package/scripts/contextfs.js +9 -3
- package/scripts/conversion-rate-stats.js +442 -0
- package/scripts/cost-cli.js +147 -0
- package/scripts/creator-campaigns.js +239 -0
- package/scripts/cross-encoder-reranker.js +4 -0
- package/scripts/cuda-gate-batch.js +560 -0
- package/scripts/daemon-manager.js +108 -0
- package/scripts/dashboard-chat.js +11 -0
- package/scripts/dashboard.js +576 -169
- package/scripts/decision-journal.js +7 -4
- package/scripts/delegation-runtime.js +1036 -0
- package/scripts/dispatch-brief.js +159 -0
- package/scripts/distribution-surfaces.js +110 -0
- package/scripts/docker-sandbox-planner.js +3 -3
- package/scripts/egm-goldfish-packet.js +95 -0
- package/scripts/embeddinggemma-adapter.js +407 -0
- package/scripts/export-dpo-pairs.js +12 -7
- package/scripts/feedback-aggregate.js +4 -0
- package/scripts/feedback-attribution.js +6 -4
- package/scripts/feedback-history-distiller.js +18 -6
- package/scripts/feedback-loop.js +255 -89
- package/scripts/feedback-paths.js +8 -1
- package/scripts/feedback-sanitizer.js +5 -0
- package/scripts/feedback-scope.js +106 -0
- package/scripts/feedback-session.js +8 -2
- package/scripts/filesystem-search.js +13 -8
- package/scripts/financial-control-plane.js +707 -45
- package/scripts/funnel-analytics.js +35 -0
- package/scripts/gate-semantic-layer.js +292 -0
- package/scripts/gate-stats.js +8 -2
- package/scripts/gates-engine.js +694 -230
- package/scripts/generate-eval-scorecard.js +0 -1
- package/scripts/harness-tool-names.js +31 -5
- package/scripts/hybrid-feedback-context.js +5 -2
- package/scripts/implementation-notes.js +241 -0
- package/scripts/intent-router.js +518 -0
- package/scripts/intervention-policy.js +2 -1
- package/scripts/latency-budget.js +164 -0
- package/scripts/lesson-canonical.js +2 -2
- package/scripts/lesson-db.js +55 -14
- package/scripts/lesson-graph.js +2 -1
- package/scripts/lesson-retrieval.js +95 -9
- package/scripts/lesson-search.js +86 -22
- package/scripts/lesson-synthesis.js +21 -5
- package/scripts/mailer/index.js +17 -1
- package/scripts/mailer/resend-mailer.js +213 -179
- package/scripts/mcp-writeguard.js +158 -0
- package/scripts/migrate-project-scope.js +209 -0
- package/scripts/model-candidates.js +414 -0
- package/scripts/openrouter-armor-partnership-diode.js +2419 -0
- package/scripts/operational-dashboard.js +172 -0
- package/scripts/operational-integrity.js +436 -3
- package/scripts/operational-summary.js +190 -0
- package/scripts/operator-artifacts.js +622 -0
- package/scripts/optimize-context.js +17 -0
- package/scripts/override-audit.js +2 -0
- package/scripts/owner-admin.js +338 -0
- package/scripts/pr-manager.js +194 -1
- package/scripts/predictive-insights.js +449 -0
- package/scripts/profound-aeo-citation-engine.js +583 -0
- package/scripts/progressive-signoff.js +260 -0
- package/scripts/project-catalog.js +243 -0
- package/scripts/project-dashboard.js +61 -0
- package/scripts/project-evidence.js +172 -0
- package/scripts/project-identity.js +182 -0
- package/scripts/project-scope.js +381 -0
- package/scripts/prompt-guard.js +446 -52
- package/scripts/proof-report.js +232 -0
- package/scripts/provider-action-normalizer.js +14 -6
- package/scripts/pulse.js +80 -0
- package/scripts/rate-limiter.js +41 -0
- package/scripts/rrsi-doctor.js +2698 -0
- package/scripts/secret-redaction.js +171 -25
- package/scripts/secret-scanner.js +101 -42
- package/scripts/self-protection.js +2 -2
- package/scripts/seo-gsd.js +14 -14
- package/scripts/session-context-dedupe.js +66 -0
- package/scripts/session-report.js +120 -0
- package/scripts/settings-hierarchy.js +4 -2
- package/scripts/statusline-meta.js +34 -23
- package/scripts/subagent-profiles.js +79 -0
- package/scripts/task-outcomes.js +29 -2
- package/scripts/telemetry-analytics.js +238 -13
- package/scripts/third-author-cli.js +118 -0
- package/scripts/third-author-governance.js +437 -0
- package/scripts/thumbgate-dream.js +878 -0
- package/scripts/thumbgate-search.js +23 -9
- package/scripts/tool-kpi-tracker.js +5 -2
- package/scripts/tool-registry.js +42 -1
- package/scripts/triage-savings-calculator.js +1 -1
- package/scripts/vector-store.js +4 -1
- package/scripts/verified-lessons.js +270 -0
- package/scripts/verify-marketing-pages-deployed.js +2 -2
- package/scripts/workflow-sentinel.js +29 -10
- package/server.json +2 -2
- package/skills/thumbgate-daily-discoveries/SKILL.md +25 -41
- package/src/api/server.js +2371 -451
- package/src/feedback.js +21 -0
- package/src/hermes-sync-plane.js +2 -1
- package/src/index.js +2 -0
- package/src/lesson-search.js +9 -0
- package/src/mckinsey-top-company-ai-coding.js +493 -0
- package/src/mcp/server.js +3 -0
- package/src/mcp-writeguard.js +772 -11
- package/src/openshell-lovable-engine.js +1475 -0
- package/src/task-outcome.js +3 -0
- package/config/evals/agent-safety-eval.json +0 -447
- package/config/evals/retrieval-ranking-golden.json +0 -522
- package/config/progressive/01-wire-only.json +0 -11
- package/config/progressive/02-dashboard-empty-ok.json +0 -10
- package/config/progressive/03-one-lesson.json +0 -10
- package/config/progressive/04-warn-fires.json +0 -11
- package/config/progressive/05-strict-optional.json +0 -11
- package/config/progressive/README.md +0 -15
- package/public/assets/diagrams/agent-integration.png +0 -0
- package/public/assets/diagrams/thumbgate-architecture.png +0 -0
- package/scripts/install-thumbgate-daily-publish-launchd.sh +0 -83
- package/scripts/thumbgate-daily-discoveries-publish.js +0 -461
- package/scripts/thumbgate-daily-discoveries-publish.sh +0 -18
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
const crypto = require('node:crypto');
|
|
7
|
+
const { projectForRecord, resolveProjectEvidence, isGeneratedGate } = require('./project-identity');
|
|
8
|
+
const { SIGNAL_FILES, signalPaths, accountDirectories, accountAttribution, attributionForFile } = require('./project-catalog');
|
|
9
|
+
|
|
10
|
+
function digest(file) {
|
|
11
|
+
const hash = crypto.createHash('sha256');
|
|
12
|
+
const fd = fs.openSync(file, 'r');
|
|
13
|
+
const buffer = Buffer.alloc(64 * 1024);
|
|
14
|
+
try { let n; while ((n = fs.readSync(fd, buffer, 0, buffer.length, null))) hash.update(buffer.subarray(0, n)); } finally { fs.closeSync(fd); }
|
|
15
|
+
return hash.digest('hex');
|
|
16
|
+
}
|
|
17
|
+
function fingerprint(file) {
|
|
18
|
+
const stat = fs.statSync(file, { bigint: true });
|
|
19
|
+
return { ino: String(stat.ino), size: String(stat.size), mtime: String(stat.mtimeNs), checksum: digest(file) };
|
|
20
|
+
}
|
|
21
|
+
function sameFingerprint(a, b) { return JSON.stringify(a) === JSON.stringify(b); }
|
|
22
|
+
function *lines(file) {
|
|
23
|
+
const fd = fs.openSync(file, 'r');
|
|
24
|
+
const buffer = Buffer.alloc(64 * 1024);
|
|
25
|
+
const decoder = new (require('node:string_decoder').StringDecoder)('utf8');
|
|
26
|
+
let pending = '';
|
|
27
|
+
try {
|
|
28
|
+
let n;
|
|
29
|
+
while ((n = fs.readSync(fd, buffer, 0, buffer.length, null))) {
|
|
30
|
+
pending += decoder.write(buffer.subarray(0, n));
|
|
31
|
+
let end;
|
|
32
|
+
while ((end = pending.indexOf('\n')) !== -1) { yield pending.slice(0, end + 1); pending = pending.slice(end + 1); }
|
|
33
|
+
}
|
|
34
|
+
pending += decoder.end();
|
|
35
|
+
if (pending) yield pending;
|
|
36
|
+
} finally { fs.closeSync(fd); }
|
|
37
|
+
}
|
|
38
|
+
function atomicJson(file, value) {
|
|
39
|
+
const temporary = `${file}.${crypto.randomUUID()}.tmp`;
|
|
40
|
+
const fd = fs.openSync(temporary, 'wx', 0o600);
|
|
41
|
+
try { fs.writeFileSync(fd, JSON.stringify(value, null, 2) + '\n'); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
42
|
+
fs.renameSync(temporary, file);
|
|
43
|
+
const dir = fs.openSync(path.dirname(file), 'r');
|
|
44
|
+
try { fs.fsyncSync(dir); } finally { fs.closeSync(dir); }
|
|
45
|
+
}
|
|
46
|
+
function copyDatabaseForInspection(file) {
|
|
47
|
+
const directory = fs.mkdtempSync(path.join(require('node:os').tmpdir(), 'thumbgate-migration-'));
|
|
48
|
+
fs.chmodSync(directory, 0o700);
|
|
49
|
+
const files = [file, file + '-wal', file + '-shm'].filter((candidate) => fs.existsSync(candidate));
|
|
50
|
+
const before = files.map((candidate) => fingerprint(candidate));
|
|
51
|
+
try {
|
|
52
|
+
for (const source of files) {
|
|
53
|
+
const target = path.join(directory, path.basename(source));
|
|
54
|
+
fs.copyFileSync(source, target);
|
|
55
|
+
fs.chmodSync(target, 0o600);
|
|
56
|
+
}
|
|
57
|
+
const current = [file, file + '-wal', file + '-shm'].filter((candidate) => fs.existsSync(candidate));
|
|
58
|
+
if (JSON.stringify(current) !== JSON.stringify(files) || files.some((candidate, i) => !sameFingerprint(before[i], fingerprint(candidate)))) throw new Error('Database changed during inspection');
|
|
59
|
+
return { file: path.join(directory, path.basename(file)), cleanup: () => fs.rmSync(directory, { recursive: true, force: true }) };
|
|
60
|
+
} catch (error) { fs.rmSync(directory, { recursive: true, force: true }); throw error; }
|
|
61
|
+
}
|
|
62
|
+
function migrateAccount(root, options, counts) {
|
|
63
|
+
const attribution = accountAttribution(root, options);
|
|
64
|
+
const manifestPath = path.join(root, 'project-scope-migration.json');
|
|
65
|
+
let manifest = { version: 1, files: {}, databases: {} };
|
|
66
|
+
if (fs.existsSync(manifestPath)) manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
|
67
|
+
const save = () => atomicJson(manifestPath, manifest);
|
|
68
|
+
const replace = (file, render) => {
|
|
69
|
+
counts.files++;
|
|
70
|
+
const relative = path.relative(root, file);
|
|
71
|
+
const previous = manifest.files[relative];
|
|
72
|
+
const original = fingerprint(file);
|
|
73
|
+
if (previous) {
|
|
74
|
+
if (previous.replacementChecksum === original.checksum) { counts.skipped++; return; }
|
|
75
|
+
if (!sameFingerprint(previous.original, original)) throw new Error('Migration source changed; refusing replacement');
|
|
76
|
+
}
|
|
77
|
+
if (!options.apply) { render(null); return; }
|
|
78
|
+
const temporary = `${file}.${crypto.randomUUID()}.tmp`;
|
|
79
|
+
const backup = previous?.backup || `${file}.project-scope-${crypto.randomUUID()}.bak`;
|
|
80
|
+
const fd = fs.openSync(temporary, 'wx', 0o600);
|
|
81
|
+
try { render(fd); fs.fsyncSync(fd); } catch (error) { fs.closeSync(fd); fs.unlinkSync(temporary); throw error; }
|
|
82
|
+
fs.closeSync(fd);
|
|
83
|
+
try {
|
|
84
|
+
options.beforeReplace?.(file);
|
|
85
|
+
if (!sameFingerprint(original, fingerprint(file))) throw new Error('Concurrent source modification; migration stopped');
|
|
86
|
+
if (!previous) {
|
|
87
|
+
fs.copyFileSync(file, backup, fs.constants.COPYFILE_EXCL);
|
|
88
|
+
const backupFd = fs.openSync(backup, 'r'); try { fs.fsyncSync(backupFd); } finally { fs.closeSync(backupFd); }
|
|
89
|
+
}
|
|
90
|
+
manifest.files[relative] = { original, backup, replacementChecksum: digest(temporary), complete: false };
|
|
91
|
+
save();
|
|
92
|
+
if (!sameFingerprint(original, fingerprint(file))) throw new Error('Concurrent source modification; migration stopped');
|
|
93
|
+
fs.renameSync(temporary, file);
|
|
94
|
+
const directory = fs.openSync(path.dirname(file), 'r'); try { fs.fsyncSync(directory); } finally { fs.closeSync(directory); }
|
|
95
|
+
manifest.files[relative].complete = true;
|
|
96
|
+
save();
|
|
97
|
+
} finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
|
|
98
|
+
};
|
|
99
|
+
for (const filename of SIGNAL_FILES) {
|
|
100
|
+
for (const file of signalPaths(root, filename)) {
|
|
101
|
+
replace(file, (fd) => {
|
|
102
|
+
for (const line of lines(file)) {
|
|
103
|
+
let output = line;
|
|
104
|
+
try {
|
|
105
|
+
const row = JSON.parse(line);
|
|
106
|
+
if (!row || typeof row !== 'object' || Array.isArray(row)) throw new Error('Not a record');
|
|
107
|
+
counts.rows++;
|
|
108
|
+
const result = resolveProjectEvidence(row, attributionForFile(attribution, file));
|
|
109
|
+
const project = result.descriptor;
|
|
110
|
+
counts.evidence[result.evidence] = (counts.evidence[result.evidence] || 0) + 1;
|
|
111
|
+
if (result.reason) counts.reasons[result.reason] = (counts.reasons[result.reason] || 0) + 1;
|
|
112
|
+
if (result.anchorEvidence) counts.anchorEvidence[result.anchorEvidence] = (counts.anchorEvidence[result.anchorEvidence] || 0) + 1;
|
|
113
|
+
if (project.projectKey === 'unassigned') { counts.unassigned++; counts.unassignedReasons[result.reason] = (counts.unassignedReasons[result.reason] || 0) + 1; }
|
|
114
|
+
else { counts.attributed++; if (project.projectKey.startsWith('legacy_')) counts.legacyAttributed++; else if (project.projectKey.startsWith('repo_')) counts.canonicalAttributed++; else counts.localAttributed++; }
|
|
115
|
+
const newline = line.endsWith('\r\n') ? '\r\n' : line.endsWith('\n') ? '\n' : '';
|
|
116
|
+
output = JSON.stringify({ ...row, ...project }) + newline;
|
|
117
|
+
} catch { if (line.trim()) counts.malformed++; }
|
|
118
|
+
if (fd !== null) fs.writeSync(fd, output);
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
for (const dir of accountDirectories(root)) {
|
|
124
|
+
for (const name of ['auto-promoted-gates.json', 'custom-gates.json', 'dashboard-review-state.json']) {
|
|
125
|
+
const file = path.join(dir, name);
|
|
126
|
+
if (!fs.existsSync(file)) continue;
|
|
127
|
+
if (fs.lstatSync(file).isSymbolicLink()) throw new Error('Symlink migration file refused');
|
|
128
|
+
replace(file, (fd) => {
|
|
129
|
+
const original = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
130
|
+
let updated;
|
|
131
|
+
if (name === 'dashboard-review-state.json') updated = original.version === 2 ? original : { version: 2, byProject: { all: original } };
|
|
132
|
+
else {
|
|
133
|
+
const items = (Array.isArray(original) ? original : original.gates || []).map((item) => {
|
|
134
|
+
if (item.scope === 'global' && !isGeneratedGate(item)) return item;
|
|
135
|
+
const generated = name === 'auto-promoted-gates.json' || isGeneratedGate(item);
|
|
136
|
+
if (!generated && !item.projectKey) return { ...item, scope: 'global' };
|
|
137
|
+
const descriptor = projectForRecord(item, attributionForFile(attribution, file));
|
|
138
|
+
if (descriptor.projectKey === 'unassigned') { counts.legacyUnscopedGates++; return { ...item, scope: 'project', projectKey: 'unassigned', legacyUnscoped: true }; }
|
|
139
|
+
return { ...item, ...descriptor, scope: 'project' };
|
|
140
|
+
});
|
|
141
|
+
updated = Array.isArray(original) ? items : { ...original, gates: items };
|
|
142
|
+
}
|
|
143
|
+
if (fd !== null) fs.writeSync(fd, JSON.stringify(updated, null, 2) + '\n');
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
const file = path.join(dir, 'lessons.sqlite');
|
|
147
|
+
if (!fs.existsSync(file)) continue;
|
|
148
|
+
if (fs.lstatSync(file).isSymbolicLink()) throw new Error('Symlink database refused');
|
|
149
|
+
const Database = require('better-sqlite3');
|
|
150
|
+
const inspection = options.apply ? null : copyDatabaseForInspection(file);
|
|
151
|
+
let db;
|
|
152
|
+
try { db = new Database(inspection?.file || file, { readonly: !options.apply, fileMustExist: true }); } catch (error) { inspection?.cleanup(); throw error; }
|
|
153
|
+
try {
|
|
154
|
+
if (!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'lessons'").get()) { counts.uninitializedDatabases++; continue; }
|
|
155
|
+
const rows = db.prepare('SELECT * FROM lessons').all();
|
|
156
|
+
counts.dbRows += rows.length;
|
|
157
|
+
if (options.apply) {
|
|
158
|
+
options.beforeDatabase?.();
|
|
159
|
+
db.transaction(() => {
|
|
160
|
+
require('./lesson-db').upgradeProjectColumns(db);
|
|
161
|
+
options.afterDatabaseSchema?.(db);
|
|
162
|
+
const update = db.prepare('UPDATE lessons SET projectKey = ?, projectName = ? WHERE id = ?');
|
|
163
|
+
for (const row of rows) {
|
|
164
|
+
// A newly added default is not historical evidence.
|
|
165
|
+
const recorded = row.projectKey === 'unassigned' ? { ...row, projectKey: undefined } : row;
|
|
166
|
+
const project = projectForRecord(recorded, attributionForFile(attribution, file));
|
|
167
|
+
update.run(project.projectKey, project.projectName, row.id);
|
|
168
|
+
options.afterDatabaseRow?.(db, row);
|
|
169
|
+
}
|
|
170
|
+
}).immediate();
|
|
171
|
+
manifest.databases[path.relative(root, file)] = { complete: true, rows: rows.length };
|
|
172
|
+
save();
|
|
173
|
+
}
|
|
174
|
+
} finally { db.close(); inspection?.cleanup(); }
|
|
175
|
+
}
|
|
176
|
+
const report = attribution.pathEvidence.report();
|
|
177
|
+
for (const key of ['probes', 'cachedCandidates', 'metadataBytes']) counts.pathProbe[key] += report[key];
|
|
178
|
+
}
|
|
179
|
+
function migrateProjectScope(root, options = {}) {
|
|
180
|
+
const counts = { files: 0, rows: 0, attributed: 0, unassigned: 0, legacyUnscopedGates: 0, malformed: 0, dbRows: 0, skipped: 0, uninitializedDatabases: 0, canonicalAttributed: 0, legacyAttributed: 0, localAttributed: 0, evidence: {}, reasons: {}, unassignedReasons: {}, anchorEvidence: {}, pathProbe: { probes: 0, cachedCandidates: 0, metadataBytes: 0 } };
|
|
181
|
+
if (!root || !fs.existsSync(root)) return counts;
|
|
182
|
+
if (fs.lstatSync(root).isSymbolicLink()) throw new Error('Symlink account root refused');
|
|
183
|
+
if (options.apply && !options.offline) throw new Error('Apply requires offline: true after stopping all writers');
|
|
184
|
+
const lockPath = path.join(root, '.project-scope-migration.lock');
|
|
185
|
+
let lock;
|
|
186
|
+
if (options.apply) { lock = fs.openSync(lockPath, 'wx', 0o600); fs.writeFileSync(lock, String(process.pid)); }
|
|
187
|
+
try {
|
|
188
|
+
migrateAccount(path.resolve(root), options, counts);
|
|
189
|
+
const tenants = path.join(root, 'tenants');
|
|
190
|
+
if (fs.existsSync(tenants)) {
|
|
191
|
+
if (fs.lstatSync(tenants).isSymbolicLink()) throw new Error('Symlink tenant directory refused');
|
|
192
|
+
for (const tenant of fs.readdirSync(tenants, { withFileTypes: true })) {
|
|
193
|
+
if (tenant.isSymbolicLink()) throw new Error('Symlink tenant refused');
|
|
194
|
+
if (tenant.isDirectory()) migrateAccount(path.join(tenants, tenant.name), { ...options, localPathEvidence: undefined }, counts);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return counts;
|
|
198
|
+
} finally { if (lock !== undefined) { fs.closeSync(lock); fs.unlinkSync(lockPath); } }
|
|
199
|
+
}
|
|
200
|
+
module.exports = { migrateProjectScope, fingerprint };
|
|
201
|
+
if (require.main === module) {
|
|
202
|
+
const args = process.argv.slice(2);
|
|
203
|
+
const rootIndex = args.indexOf('--feedback-dir');
|
|
204
|
+
if (rootIndex === -1 || !args[rootIndex + 1]) { console.error('Usage: migrate-project-scope --feedback-dir <account-root> [--apply --offline]'); process.exitCode = 1; }
|
|
205
|
+
else {
|
|
206
|
+
try { console.log(JSON.stringify(migrateProjectScope(args[rootIndex + 1], { apply: args.includes('--apply'), offline: args.includes('--offline') }))); }
|
|
207
|
+
catch { console.error('Project migration failed. Source files and backup manifest are preserved.'); process.exitCode = 1; }
|
|
208
|
+
}
|
|
209
|
+
}
|
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
const { resolveFeedbackDir: resolveSharedFeedbackDir } = require('./feedback-paths');
|
|
7
|
+
|
|
8
|
+
const ROOT = path.join(__dirname, '..');
|
|
9
|
+
const DEFAULT_CATALOG_PATH = path.join(ROOT, 'config', 'model-candidates.json');
|
|
10
|
+
const DEFAULT_WORKLOAD = 'pretool-gating';
|
|
11
|
+
const TOKENIZER_BRITTLENESS_WORKLOAD = 'tokenizer-brittleness';
|
|
12
|
+
|
|
13
|
+
const DEFAULT_TOKENIZER_BRITTLENESS_CASES = Object.freeze([
|
|
14
|
+
{
|
|
15
|
+
id: 'malformed-jsonl-control-char',
|
|
16
|
+
input: '{"event":"gate","path":"/tmp/build\\u0000.log","ok":tru',
|
|
17
|
+
expectedSignals: ['malformed-json', 'control-char', 'file-path'],
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
id: 'unicode-confusable-secret',
|
|
21
|
+
input: 'OPENAI_API_KEY=sk-prоj-confusable-value with Cyrillic о and zero\u200bwidth marker',
|
|
22
|
+
expectedSignals: ['secret-like', 'unicode-confusable', 'zero-width'],
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
id: 'stack-trace-symbols',
|
|
26
|
+
input: 'TypeError: Cannot read properties of undefined\n at run (/repo/src/api/server.js:281:17)\n at async main (/repo/bin/cli.js:42:3)',
|
|
27
|
+
expectedSignals: ['stack-trace', 'file-path', 'code-symbols'],
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
id: 'sql-json-path',
|
|
31
|
+
input: "select json_extract(payload, '$.checkout.session.id') from billing_events where customer_email like '%@example.com';",
|
|
32
|
+
expectedSignals: ['sql', 'json-path', 'code-symbols'],
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
id: 'mixed-language-code',
|
|
36
|
+
input: '修复 gate-check: if (状态 !== "通过") throw new Error("阻止 deploy🚫");',
|
|
37
|
+
expectedSignals: ['non-ascii', 'code-symbols', 'emoji'],
|
|
38
|
+
},
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
const COST_CLASS_SCORES = Object.freeze({
|
|
42
|
+
low: 12,
|
|
43
|
+
medium: 8,
|
|
44
|
+
high: 4,
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
function normalizeSlug(value, fallback = '') {
|
|
48
|
+
if (value === undefined || value === null || value === '') return fallback;
|
|
49
|
+
const source = String(value).trim().toLowerCase();
|
|
50
|
+
let normalized = '';
|
|
51
|
+
let previousWasDash = false;
|
|
52
|
+
|
|
53
|
+
for (const char of source) {
|
|
54
|
+
const isAlphaNumeric = (char >= 'a' && char <= 'z') || (char >= '0' && char <= '9');
|
|
55
|
+
if (isAlphaNumeric) {
|
|
56
|
+
normalized += char;
|
|
57
|
+
previousWasDash = false;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (!previousWasDash && normalized) {
|
|
61
|
+
normalized += '-';
|
|
62
|
+
previousWasDash = true;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (normalized.endsWith('-')) {
|
|
67
|
+
normalized = normalized.slice(0, -1);
|
|
68
|
+
}
|
|
69
|
+
return normalized || fallback;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function parseNumber(value, fallback = 0) {
|
|
73
|
+
const parsed = Number(value);
|
|
74
|
+
return Number.isFinite(parsed) ? parsed : fallback;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function countCodePoints(value) {
|
|
78
|
+
return Array.from(String(value || '')).length;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function detectTokenizerBrittlenessSignals(input) {
|
|
82
|
+
const text = String(input || '');
|
|
83
|
+
const signals = new Set();
|
|
84
|
+
|
|
85
|
+
if (/[\u0000-\u001F\u007F]/u.test(text) || /\\u00[0-1][0-9a-f]/i.test(text)) signals.add('control-char');
|
|
86
|
+
if (/[\u200B-\u200D\uFEFF]/u.test(text)) signals.add('zero-width');
|
|
87
|
+
if (/[^\x00-\x7F]/u.test(text)) signals.add('non-ascii');
|
|
88
|
+
if (/[\u0400-\u04FF]/u.test(text) && /[A-Za-z]/.test(text)) signals.add('unicode-confusable');
|
|
89
|
+
if (/\p{Extended_Pictographic}/u.test(text)) signals.add('emoji');
|
|
90
|
+
if (/(api[_-]?key|secret|token|password)\s*[:=]/i.test(text)) signals.add('secret-like');
|
|
91
|
+
if (/\/[A-Za-z0-9._/-]+(?:\.[A-Za-z0-9]+)?(?::\d+)?/u.test(text)) signals.add('file-path');
|
|
92
|
+
if (/\bat\s+(?:async\s+)?[\w$.<>-]+\s*\([^)]*:\d+:\d+\)/u.test(text) || /\b(?:TypeError|ReferenceError|SyntaxError):/u.test(text)) signals.add('stack-trace');
|
|
93
|
+
if (/\b(select|insert|update|delete|from|where|join)\b/i.test(text)) signals.add('sql');
|
|
94
|
+
if (/\$\.[A-Za-z0-9_[\].-]+/u.test(text)) signals.add('json-path');
|
|
95
|
+
if (/[{}()[\];=<>!|&$]|\bfunction\b|\bconst\b|\blet\b|\bthrow\b/u.test(text)) signals.add('code-symbols');
|
|
96
|
+
|
|
97
|
+
const trimmed = text.trim();
|
|
98
|
+
const looksJsonLike = trimmed.startsWith('{') || trimmed.startsWith('[') || trimmed.includes('}{');
|
|
99
|
+
if (looksJsonLike) {
|
|
100
|
+
try {
|
|
101
|
+
JSON.parse(trimmed);
|
|
102
|
+
} catch {
|
|
103
|
+
signals.add('malformed-json');
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return Array.from(signals).sort((a, b) => a.localeCompare(b));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function evaluateTokenizerBrittlenessCases(cases = DEFAULT_TOKENIZER_BRITTLENESS_CASES) {
|
|
111
|
+
const normalizedCases = Array.isArray(cases) ? cases : DEFAULT_TOKENIZER_BRITTLENESS_CASES;
|
|
112
|
+
const evaluated = normalizedCases.map((entry, index) => {
|
|
113
|
+
const input = String(entry && entry.input ? entry.input : '');
|
|
114
|
+
const expectedSignals = Array.isArray(entry && entry.expectedSignals) ? entry.expectedSignals : [];
|
|
115
|
+
const signals = detectTokenizerBrittlenessSignals(input);
|
|
116
|
+
const missingSignals = expectedSignals.filter((signal) => !signals.includes(signal));
|
|
117
|
+
const byteLength = Buffer.byteLength(input, 'utf8');
|
|
118
|
+
const codePointLength = countCodePoints(input);
|
|
119
|
+
return {
|
|
120
|
+
id: entry && entry.id ? String(entry.id) : `case-${index + 1}`,
|
|
121
|
+
byteLength,
|
|
122
|
+
codePointLength,
|
|
123
|
+
byteToCodePointRatio: codePointLength > 0 ? Number((byteLength / codePointLength).toFixed(2)) : 0,
|
|
124
|
+
expectedSignals,
|
|
125
|
+
signals,
|
|
126
|
+
missingSignals,
|
|
127
|
+
passed: missingSignals.length === 0,
|
|
128
|
+
};
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
const coveredSignals = new Set(evaluated.flatMap((entry) => entry.signals));
|
|
132
|
+
const failed = evaluated.filter((entry) => !entry.passed);
|
|
133
|
+
return {
|
|
134
|
+
caseCount: evaluated.length,
|
|
135
|
+
passed: failed.length === 0,
|
|
136
|
+
passRate: evaluated.length > 0 ? Number(((evaluated.length - failed.length) / evaluated.length).toFixed(4)) : 1,
|
|
137
|
+
coveredSignals: Array.from(coveredSignals).sort((a, b) => a.localeCompare(b)),
|
|
138
|
+
cases: evaluated,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function buildTokenizerBrittlenessPlan(options = {}) {
|
|
143
|
+
const evaluation = evaluateTokenizerBrittlenessCases(options.cases);
|
|
144
|
+
return {
|
|
145
|
+
name: 'tokenizer-brittleness-readiness',
|
|
146
|
+
evaluation,
|
|
147
|
+
routingPolicy: {
|
|
148
|
+
productionDefault: 'existing-token-models-with-gates',
|
|
149
|
+
experimentalTarget: 'byte-level-or-tokenizer-free-models',
|
|
150
|
+
allowProductionRouting: false,
|
|
151
|
+
reason: 'Fast BLT is a research direction; ThumbGate should first preserve symbols, secrets, paths, JSONL structure, and stack traces through evals before adopting a byte-level runtime.',
|
|
152
|
+
},
|
|
153
|
+
recommendations: [
|
|
154
|
+
'Keep tokenizer-brittleness fixtures in the model benchmark path for log, code, SQL, JSONL, and security workloads.',
|
|
155
|
+
'Prefer tokenizer-free or byte-level candidates only after they beat current routing on symbol preservation and secret-detection recall.',
|
|
156
|
+
'Do not add a BLT runtime dependency until maintained weights, serving code, and wall-clock latency evidence exist.',
|
|
157
|
+
],
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function resolveFeedbackDir(explicitDir) {
|
|
162
|
+
return resolveSharedFeedbackDir({ feedbackDir: explicitDir });
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function getModelCandidatesReportPath(feedbackDir) {
|
|
166
|
+
return path.join(resolveFeedbackDir(feedbackDir), 'model-candidates-report.json');
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function loadCatalog(catalogPath = DEFAULT_CATALOG_PATH) {
|
|
170
|
+
const catalog = JSON.parse(fs.readFileSync(catalogPath, 'utf8'));
|
|
171
|
+
if (!catalog || typeof catalog !== 'object') {
|
|
172
|
+
throw new Error('Model candidate catalog must be an object.');
|
|
173
|
+
}
|
|
174
|
+
if (!catalog.workloads || typeof catalog.workloads !== 'object') {
|
|
175
|
+
throw new Error('Model candidate catalog requires workloads.');
|
|
176
|
+
}
|
|
177
|
+
if (!Array.isArray(catalog.candidates) || catalog.candidates.length === 0) {
|
|
178
|
+
throw new Error('Model candidate catalog requires a non-empty candidates array.');
|
|
179
|
+
}
|
|
180
|
+
return catalog;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function listCandidates(options = {}) {
|
|
184
|
+
const catalog = options.catalog || loadCatalog(options.catalogPath);
|
|
185
|
+
const providerFilter = normalizeSlug(options.provider);
|
|
186
|
+
const familyFilter = normalizeSlug(options.family);
|
|
187
|
+
const gatewayFilter = normalizeSlug(options.gateway);
|
|
188
|
+
|
|
189
|
+
return catalog.candidates.filter((candidate) => {
|
|
190
|
+
if (providerFilter && normalizeSlug(candidate.provider) !== providerFilter) return false;
|
|
191
|
+
if (familyFilter && normalizeSlug(candidate.family) !== familyFilter) return false;
|
|
192
|
+
if (gatewayFilter && normalizeSlug(candidate.gateway) !== gatewayFilter) return false;
|
|
193
|
+
return true;
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function scoreCandidate(candidate, workload) {
|
|
198
|
+
const strengths = Array.isArray(candidate.strengths) ? candidate.strengths : [];
|
|
199
|
+
const desiredStrengths = Array.isArray(workload.desiredStrengths) ? workload.desiredStrengths : [];
|
|
200
|
+
const matchedStrengths = desiredStrengths.filter((strength) => strengths.includes(strength));
|
|
201
|
+
const strengthScore = matchedStrengths.length * 18;
|
|
202
|
+
const contextWindow = parseNumber(candidate.contextWindow, 0);
|
|
203
|
+
const targetContextWindow = parseNumber(workload.targetContextWindow, 0);
|
|
204
|
+
const contextScore = contextWindow >= targetContextWindow
|
|
205
|
+
? 18
|
|
206
|
+
: Math.max(0, Math.round((contextWindow / Math.max(1, targetContextWindow)) * 12));
|
|
207
|
+
const longContextBonus = strengths.includes('long-context') && targetContextWindow >= 128000 ? 8 : 0;
|
|
208
|
+
const fastInferenceBonus = strengths.includes('fast-inference') && workload.id !== 'long-trace-review' ? 6 : 0;
|
|
209
|
+
const costScore = COST_CLASS_SCORES[normalizeSlug(candidate.costClass)] || 0;
|
|
210
|
+
const totalScore = strengthScore + contextScore + longContextBonus + fastInferenceBonus + costScore;
|
|
211
|
+
|
|
212
|
+
return {
|
|
213
|
+
totalScore,
|
|
214
|
+
matchedStrengths,
|
|
215
|
+
scoreBreakdown: {
|
|
216
|
+
strengthScore,
|
|
217
|
+
contextScore,
|
|
218
|
+
longContextBonus,
|
|
219
|
+
fastInferenceBonus,
|
|
220
|
+
costScore,
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function buildBenchmarkPlan(candidate, workload) {
|
|
226
|
+
const benchmarkCommands = Array.isArray(workload.benchmarkCommands) ? workload.benchmarkCommands : [];
|
|
227
|
+
const metrics = Array.isArray(workload.metrics) ? workload.metrics : [];
|
|
228
|
+
return {
|
|
229
|
+
workload: workload.id,
|
|
230
|
+
suiteCount: benchmarkCommands.length,
|
|
231
|
+
commands: benchmarkCommands.map((command, index) => ({
|
|
232
|
+
id: `${workload.id}-${index + 1}`,
|
|
233
|
+
command,
|
|
234
|
+
})),
|
|
235
|
+
metrics,
|
|
236
|
+
candidateId: candidate.id,
|
|
237
|
+
provider: candidate.provider,
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function buildReadinessNotes(candidate, workloadId) {
|
|
242
|
+
const notes = [];
|
|
243
|
+
if (candidate.researchOnly) {
|
|
244
|
+
notes.push('research-only: benchmark target, not production routing');
|
|
245
|
+
}
|
|
246
|
+
if (workloadId === TOKENIZER_BRITTLENESS_WORKLOAD && !(candidate.strengths || []).includes('tokenizer-free')) {
|
|
247
|
+
notes.push('requires tokenizer-brittleness eval before code/log/security routing');
|
|
248
|
+
}
|
|
249
|
+
return notes;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function recommendCandidates(options = {}) {
|
|
253
|
+
const catalog = options.catalog || loadCatalog(options.catalogPath);
|
|
254
|
+
let workload;
|
|
255
|
+
let workloadId;
|
|
256
|
+
|
|
257
|
+
if (options.workloadFile && fs.existsSync(options.workloadFile)) {
|
|
258
|
+
try {
|
|
259
|
+
workload = JSON.parse(fs.readFileSync(options.workloadFile, 'utf8'));
|
|
260
|
+
workloadId = workload.id || 'custom-workload';
|
|
261
|
+
} catch (err) {
|
|
262
|
+
throw new Error(`Failed to parse custom workload file: ${err.message}`);
|
|
263
|
+
}
|
|
264
|
+
} else {
|
|
265
|
+
workloadId = normalizeSlug(options.workload, DEFAULT_WORKLOAD);
|
|
266
|
+
workload = catalog.workloads[workloadId];
|
|
267
|
+
if (!workload) {
|
|
268
|
+
throw new Error(`Unknown workload "${workloadId}". Valid workloads: ${Object.keys(catalog.workloads).join(', ')}`);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const scopedCandidates = listCandidates({
|
|
273
|
+
catalog,
|
|
274
|
+
provider: options.provider,
|
|
275
|
+
family: options.family,
|
|
276
|
+
gateway: options.gateway,
|
|
277
|
+
});
|
|
278
|
+
const ranked = scopedCandidates
|
|
279
|
+
.map((candidate) => {
|
|
280
|
+
const scoring = scoreCandidate(candidate, { ...workload, id: workloadId });
|
|
281
|
+
return {
|
|
282
|
+
...candidate,
|
|
283
|
+
matchedStrengths: scoring.matchedStrengths,
|
|
284
|
+
score: scoring.totalScore,
|
|
285
|
+
scoreBreakdown: scoring.scoreBreakdown,
|
|
286
|
+
benchmarkPlan: buildBenchmarkPlan(candidate, { ...workload, id: workloadId }),
|
|
287
|
+
readinessNotes: buildReadinessNotes(candidate, workloadId),
|
|
288
|
+
};
|
|
289
|
+
})
|
|
290
|
+
.sort((left, right) => {
|
|
291
|
+
if (right.score !== left.score) return right.score - left.score;
|
|
292
|
+
return parseNumber(right.contextWindow, 0) - parseNumber(left.contextWindow, 0);
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
const maxCandidates = Math.max(1, Math.floor(parseNumber(options.maxCandidates, 3)));
|
|
296
|
+
|
|
297
|
+
return {
|
|
298
|
+
workloadId,
|
|
299
|
+
workload: { id: workloadId, ...workload },
|
|
300
|
+
recommended: ranked.slice(0, maxCandidates),
|
|
301
|
+
considered: ranked.length,
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function buildModelCandidatesReport(options = {}) {
|
|
306
|
+
const catalog = options.catalog || loadCatalog(options.catalogPath);
|
|
307
|
+
const recommendation = recommendCandidates({
|
|
308
|
+
catalog,
|
|
309
|
+
workload: options.workload,
|
|
310
|
+
workloadFile: options.workloadFile,
|
|
311
|
+
provider: options.provider,
|
|
312
|
+
family: options.family,
|
|
313
|
+
gateway: options.gateway,
|
|
314
|
+
maxCandidates: options.maxCandidates || 3,
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
return {
|
|
318
|
+
generatedAt: new Date().toISOString(),
|
|
319
|
+
workload: recommendation.workload,
|
|
320
|
+
filters: {
|
|
321
|
+
provider: normalizeSlug(options.provider) || null,
|
|
322
|
+
family: normalizeSlug(options.family) || null,
|
|
323
|
+
gateway: normalizeSlug(options.gateway) || null,
|
|
324
|
+
},
|
|
325
|
+
considered: recommendation.considered,
|
|
326
|
+
recommended: recommendation.recommended,
|
|
327
|
+
summary: recommendation.recommended.length > 0
|
|
328
|
+
? `${recommendation.recommended[0].id} is the top candidate for ${recommendation.workload.label}.`
|
|
329
|
+
: 'No candidates matched the selected filters.',
|
|
330
|
+
tokenizerBrittleness: recommendation.workloadId === TOKENIZER_BRITTLENESS_WORKLOAD || options.includeTokenizerBrittleness
|
|
331
|
+
? buildTokenizerBrittlenessPlan(options.tokenizerBrittleness)
|
|
332
|
+
: null,
|
|
333
|
+
catalogVersion: catalog.version || 1,
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function writeModelCandidatesReport(feedbackDir, options = {}) {
|
|
338
|
+
const report = buildModelCandidatesReport(options);
|
|
339
|
+
const reportPath = getModelCandidatesReportPath(feedbackDir);
|
|
340
|
+
fs.mkdirSync(path.dirname(reportPath), { recursive: true });
|
|
341
|
+
fs.writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`);
|
|
342
|
+
return { reportPath, report };
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function renderModelCandidatesReport(report) {
|
|
346
|
+
const lines = [
|
|
347
|
+
`# Managed Model Candidates - ${report.workload.label}`,
|
|
348
|
+
'',
|
|
349
|
+
report.workload.summary,
|
|
350
|
+
'',
|
|
351
|
+
`Catalog version: ${report.catalogVersion}`,
|
|
352
|
+
`Candidates considered: ${report.considered}`,
|
|
353
|
+
];
|
|
354
|
+
if (report.filters.provider) lines.push(`Provider filter: ${report.filters.provider}`);
|
|
355
|
+
if (report.filters.family) lines.push(`Family filter: ${report.filters.family}`);
|
|
356
|
+
lines.push('');
|
|
357
|
+
|
|
358
|
+
if (!Array.isArray(report.recommended) || report.recommended.length === 0) {
|
|
359
|
+
lines.push('No candidates matched the selected filters.');
|
|
360
|
+
return `${lines.join('\n')}\n`;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const recommendationLines = report.recommended.flatMap((candidate, index) => [
|
|
364
|
+
`${index + 1}. ${candidate.id}`,
|
|
365
|
+
` Score: ${candidate.score}`,
|
|
366
|
+
` Context window: ${candidate.contextWindow}`,
|
|
367
|
+
` Cost class: ${candidate.costClass}`,
|
|
368
|
+
` Matched strengths: ${candidate.matchedStrengths.join(', ') || 'none'}`,
|
|
369
|
+
` Notes: ${candidate.notes}`,
|
|
370
|
+
...(Array.isArray(candidate.readinessNotes) && candidate.readinessNotes.length
|
|
371
|
+
? [` Readiness: ${candidate.readinessNotes.join('; ')}`]
|
|
372
|
+
: []),
|
|
373
|
+
' Benchmark commands:',
|
|
374
|
+
...candidate.benchmarkPlan.commands.map((entry) => ` - ${entry.command}`),
|
|
375
|
+
` Benchmark metrics: ${candidate.benchmarkPlan.metrics.join(', ')}`,
|
|
376
|
+
'',
|
|
377
|
+
]);
|
|
378
|
+
lines.push(...recommendationLines);
|
|
379
|
+
|
|
380
|
+
if (report.tokenizerBrittleness) {
|
|
381
|
+
lines.push('Tokenizer brittleness readiness:', '');
|
|
382
|
+
lines.push(`- Cases: ${report.tokenizerBrittleness.evaluation.caseCount}`);
|
|
383
|
+
lines.push(`- Pass rate: ${report.tokenizerBrittleness.evaluation.passRate}`);
|
|
384
|
+
lines.push(`- Production routing: ${report.tokenizerBrittleness.routingPolicy.allowProductionRouting ? 'allowed' : 'blocked until benchmarked'}`);
|
|
385
|
+
lines.push('');
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
return `${lines.join('\n').trimEnd()}\n`;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
module.exports = {
|
|
392
|
+
DEFAULT_CATALOG_PATH,
|
|
393
|
+
DEFAULT_TOKENIZER_BRITTLENESS_CASES,
|
|
394
|
+
DEFAULT_WORKLOAD,
|
|
395
|
+
TOKENIZER_BRITTLENESS_WORKLOAD,
|
|
396
|
+
buildTokenizerBrittlenessPlan,
|
|
397
|
+
buildBenchmarkPlan,
|
|
398
|
+
buildModelCandidatesReport,
|
|
399
|
+
detectTokenizerBrittlenessSignals,
|
|
400
|
+
evaluateTokenizerBrittlenessCases,
|
|
401
|
+
getModelCandidatesReportPath,
|
|
402
|
+
listCandidates,
|
|
403
|
+
loadCatalog,
|
|
404
|
+
recommendCandidates,
|
|
405
|
+
renderModelCandidatesReport,
|
|
406
|
+
resolveFeedbackDir,
|
|
407
|
+
scoreCandidate,
|
|
408
|
+
writeModelCandidatesReport,
|
|
409
|
+
};
|
|
410
|
+
|
|
411
|
+
if (path.resolve(process.argv[1] || '') === path.resolve(__filename)) {
|
|
412
|
+
const report = buildModelCandidatesReport();
|
|
413
|
+
process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
|
414
|
+
}
|