llm-api-purity-check 0.0.0-stage → 1.2.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.
@@ -0,0 +1,383 @@
1
+ /**
2
+ * 1-355 Numerical Distribution Model Fingerprinting Engine
3
+ *
4
+ * Statistical attribution (Hellinger + Ordered-block nuisance projection + Jensen-Shannon similarity)
5
+ * built on MIT-licensed open-source methods from xqy2006/ModelTrace & kiss-kedaya/chanshui,
6
+ * packaged for standalone CLI use by AIAPIPK (https://www.aiapipk.com/detect/).
7
+ */
8
+
9
+ import crypto from 'node:crypto';
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+
14
+ export const FP_VALUE_MIN = 1;
15
+ export const FP_VALUE_MAX = 355;
16
+ export const FP_DIMENSION = FP_VALUE_MAX - FP_VALUE_MIN + 1;
17
+ const FP_ALPHA = 0.5;
18
+
19
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
20
+ const DEFAULT_BANK_PATH = path.resolve(__dirname, '../data/bank.generated.json');
21
+
22
+ let cachedNumericBank = null;
23
+
24
+ export function loadFingerprintBank(bankPath = DEFAULT_BANK_PATH) {
25
+ if (cachedNumericBank && bankPath === DEFAULT_BANK_PATH) return cachedNumericBank;
26
+ const raw = JSON.parse(fs.readFileSync(bankPath, 'utf-8'));
27
+ const numeric = raw.numeric || raw;
28
+ if (!numeric || !Array.isArray(numeric.models) || !numeric.robust) {
29
+ throw new Error(`Invalid fingerprint bank schema in ${bankPath}`);
30
+ }
31
+ if (bankPath === DEFAULT_BANK_PATH) cachedNumericBank = numeric;
32
+ return numeric;
33
+ }
34
+
35
+ function dot(a, b) {
36
+ let s = 0;
37
+ for (let i = 0; i < a.length; i += 1) s += a[i] * b[i];
38
+ return s;
39
+ }
40
+
41
+ function unit(v) {
42
+ const n = Math.max(Math.sqrt(dot(v, v)), 1e-12);
43
+ return v.map((x) => x / n);
44
+ }
45
+
46
+ function standardizeScalar(values) {
47
+ const mean = values.reduce((a, b) => a + b, 0) / values.length;
48
+ const variance = values.reduce((a, b) => a + (b - mean) ** 2, 0) / values.length;
49
+ const scale = Math.max(Math.sqrt(variance), 1e-12);
50
+ return values.map((v) => (v - mean) / scale);
51
+ }
52
+
53
+ function standardizeWithStats(values, mean, scale) {
54
+ return values.map((v, i) => (v - mean[i]) / scale[i]);
55
+ }
56
+
57
+ function projectOut(values, basis) {
58
+ const out = values.slice();
59
+ for (const vec of basis || []) {
60
+ const proj = dot(out, vec);
61
+ for (let i = 0; i < out.length; i += 1) out[i] -= proj * vec[i];
62
+ }
63
+ return out;
64
+ }
65
+
66
+ export function parseModelTraceNumbers(text) {
67
+ const str = String(text || '');
68
+ const runs = [];
69
+ let current = [];
70
+ let prevEnd = 0;
71
+ for (const match of str.matchAll(/\d+/g)) {
72
+ const idx = match.index ?? 0;
73
+ const sep = str.slice(prevEnd, idx);
74
+ const val = Number(match[0]);
75
+ if (current.length > 0 && /\p{L}/u.test(sep)) {
76
+ runs.push(current);
77
+ current = [];
78
+ }
79
+ if (val >= FP_VALUE_MIN && val <= FP_VALUE_MAX) {
80
+ current.push(val);
81
+ }
82
+ prevEnd = idx + match[0].length;
83
+ }
84
+ if (current.length > 0) runs.push(current);
85
+ return runs.reduce((best, run) => (run.length > best.length ? run : best), []);
86
+ }
87
+
88
+ export function countNumbers355(nums) {
89
+ const counts = new Array(FP_DIMENSION).fill(0);
90
+ for (const n of nums) {
91
+ if (n >= FP_VALUE_MIN && n <= FP_VALUE_MAX) counts[n - FP_VALUE_MIN] += 1;
92
+ }
93
+ return counts;
94
+ }
95
+
96
+ function hellingerFeature(counts) {
97
+ const total = counts.reduce((a, b) => a + b, 0) + FP_ALPHA * FP_DIMENSION;
98
+ return counts.map((v) => Math.sqrt((v + FP_ALPHA) / total));
99
+ }
100
+
101
+ function splitIntoFour(values) {
102
+ const base = Math.floor(values.length / 4);
103
+ const rem = values.length % 4;
104
+ const chunks = [];
105
+ let start = 0;
106
+ for (let i = 0; i < 4; i += 1) {
107
+ const size = base + (i < rem ? 1 : 0);
108
+ chunks.push(values.slice(start, start + size));
109
+ start += size;
110
+ }
111
+ return chunks;
112
+ }
113
+
114
+ function orderedBlockFeature(nums) {
115
+ const pieces = [];
116
+ for (const chunk of splitIntoFour(nums)) {
117
+ const bins = new Array(16).fill(0.5);
118
+ for (const val of chunk) {
119
+ const idx = Math.min(15, Math.floor(((val - 1) / FP_VALUE_MAX) * 16));
120
+ bins[idx] += 1;
121
+ }
122
+ const total = bins.reduce((a, b) => a + b, 0);
123
+ pieces.push(...bins.map((v) => Math.sqrt(v / total)));
124
+ }
125
+ const lastDigits = new Array(10).fill(0.5);
126
+ for (const val of nums) lastDigits[val % 10] += 1;
127
+ const lastTotal = lastDigits.reduce((a, b) => a + b, 0);
128
+ pieces.push(...lastDigits.map((v) => Math.sqrt(v / lastTotal)));
129
+ return pieces;
130
+ }
131
+
132
+ export function jsSimilarity355(queryCounts, refCounts) {
133
+ const leftTotal = queryCounts.reduce((a, b) => a + b, 0);
134
+ const rightTotal = refCounts.reduce((a, b) => a + b, 0) + FP_ALPHA * FP_DIMENSION;
135
+ if (leftTotal <= 0 || rightTotal <= 0) return 0;
136
+ let divP = 0;
137
+ let divQ = 0;
138
+ for (let i = 0; i < FP_DIMENSION; i += 1) {
139
+ const p = queryCounts[i] / leftTotal;
140
+ const q = (refCounts[i] + FP_ALPHA) / rightTotal;
141
+ const m = 0.5 * (p + q);
142
+ if (p > 0) divP += p * Math.log(p / m);
143
+ if (q > 0) divQ += q * Math.log(q / m);
144
+ }
145
+ const js = 0.5 * (divP + divQ);
146
+ return Math.max(0, Math.min(1, 1 - Math.sqrt(Math.max(0, js) / Math.log(2))));
147
+ }
148
+
149
+ function softmax(beta, scores) {
150
+ const mx = Math.max(...scores);
151
+ const weights = scores.map((s) => Math.exp(beta * (s - mx)));
152
+ const sum = weights.reduce((a, b) => a + b, 0) || 1;
153
+ return weights.map((w) => w / sum);
154
+ }
155
+
156
+ function normalizeModelSlug(name) {
157
+ return String(name || '')
158
+ .trim()
159
+ .toLowerCase()
160
+ .replace(/^(openai|anthropic|moonshotai|moonshot|deepseek|xai|x-ai|google|qwen|alibaba|zhipu|z-ai|zai)\//, '')
161
+ .replace(/[-_](?:202\d{5}|latest)$/i, '')
162
+ .replace(/[._\s]+/g, '-');
163
+ }
164
+
165
+ function inferExpectedBankFamily(modelName) {
166
+ const s = String(modelName || '').trim().toLowerCase();
167
+ if (!s) return null;
168
+ if (/(?:^|\/)(?:claude|anthropic\/claude)|(?:^|[-_/])(?:opus|sonnet|haiku|fable)[-_.]?\d/i.test(s)) return 'claude';
169
+ if (/(?:^|\/)(?:gpt|o1|o3|o4|chatgpt|codex)/i.test(s)) return 'gpt';
170
+ return null;
171
+ }
172
+
173
+ export function generateFingerprintChallenges(count = 3) {
174
+ const openings = [
175
+ 'Generate a fresh sequence of arbitrary integers',
176
+ 'Output a sequence of independent integers',
177
+ 'Produce a raw sequence of unpatterned integers',
178
+ ];
179
+ const pool = Array.from({ length: 41 }, (_, i) => 292 + i);
180
+ const lengths = [];
181
+ while (lengths.length < count && pool.length > 0) {
182
+ const idx = crypto.randomInt(0, pool.length);
183
+ lengths.push(pool.splice(idx, 1)[0]);
184
+ }
185
+ return lengths.map((length, index) => ({
186
+ id: `fp-${index + 1}-${crypto.randomBytes(3).toString('hex')}`,
187
+ expectedCount: length,
188
+ prompt:
189
+ `${openings[index % openings.length]}: output exactly ${length} integers between 1 and 355 (inclusive). ` +
190
+ 'Choose each number independently; do not count upward/downward, do not use arithmetic progressions, cycles, or repeating blocks. ' +
191
+ 'Do NOT call any tools, code interpreter, Python, calculator, or external RNG—generate directly from the language model. ' +
192
+ 'Output only the numbers separated by commas or spaces, starting immediately with the first integer and no commentary.',
193
+ }));
194
+ }
195
+
196
+ function robustScoreNumbers(nums, bank) {
197
+ const h = bank.robust.hellinger;
198
+ const ob = bank.robust.ordered_blocks;
199
+ const n = bank.models.length;
200
+
201
+ const hp = unit(
202
+ projectOut(
203
+ standardizeWithStats(hellingerFeature(countNumbers355(nums)), h.feature_mean, h.feature_scale),
204
+ h.nuisance_basis
205
+ )
206
+ );
207
+ const hell = standardizeScalar(h.centroids.map((c) => dot(hp, c)));
208
+
209
+ const weight = Number(ob?.weight || 0);
210
+ if (!ob || weight === 0) return hell;
211
+
212
+ const os = standardizeWithStats(orderedBlockFeature(nums), ob.feature_mean, ob.feature_scale);
213
+ const osUnit = unit(os);
214
+ const op = unit(projectOut(os, ob.nuisance_basis));
215
+
216
+ const templateRaw = new Array(n);
217
+ const nuisanceRaw = new Array(n);
218
+ for (let c = 0; c < n; c += 1) {
219
+ let best = -Infinity;
220
+ for (const env of ob.environment_centroids) {
221
+ const val = dot(osUnit, env[c]);
222
+ if (val > best) best = val;
223
+ }
224
+ templateRaw[c] = Number.isFinite(best) ? best : 0;
225
+ nuisanceRaw[c] = dot(op, ob.centroids[c]);
226
+ }
227
+ const template = standardizeScalar(templateRaw);
228
+ const nuisance = standardizeScalar(nuisanceRaw);
229
+ const ordered = standardizeScalar(template.map((t, i) => 0.5 * t + 0.5 * nuisance[i]));
230
+
231
+ return hell.map((hv, i) => (1 - weight) * hv + weight * ordered[i]);
232
+ }
233
+
234
+ function findClaimedModelInBank(claimedModel, bank) {
235
+ const req = normalizeModelSlug(claimedModel);
236
+ if (!req) return null;
237
+ for (const m of bank.models) {
238
+ if (normalizeModelSlug(m.id) === req || normalizeModelSlug(m.display_name) === req) return m;
239
+ for (const al of m.aliases || []) {
240
+ if (normalizeModelSlug(al) === req) return m;
241
+ }
242
+ }
243
+ for (const m of bank.models) {
244
+ const normId = normalizeModelSlug(m.id);
245
+ if (normId.startsWith(req) || req.startsWith(normId)) {
246
+ const tail = req.length >= normId.length ? req.slice(normId.length) : normId.slice(req.length);
247
+ if (/^-\d{1,2}(?:$|-)/.test(tail)) continue;
248
+ return m;
249
+ }
250
+ }
251
+ return null;
252
+ }
253
+
254
+ export function attributeFingerprint(outputs, claimedModel, bankPath = DEFAULT_BANK_PATH) {
255
+ const bank = loadFingerprintBank(bankPath);
256
+ const minValid = bank.minimum_valid_numbers || 80;
257
+ const valid = [];
258
+ const diagnostics = [];
259
+
260
+ outputs.forEach((o, index) => {
261
+ const nums = parseModelTraceNumbers(o.text);
262
+ const minimum = o.expectedCount ? Math.max(minValid, Math.ceil(o.expectedCount * 0.55)) : minValid;
263
+ const accepted = nums.length >= minimum;
264
+ diagnostics.push({ index, parsedNumbers: nums.length, minimumNumbers: minimum, accepted });
265
+ if (accepted) {
266
+ valid.push({
267
+ nums,
268
+ counts: countNumbers355(nums),
269
+ scores: robustScoreNumbers(nums, bank),
270
+ });
271
+ }
272
+ });
273
+
274
+ const claimedDef = findClaimedModelInBank(claimedModel, bank);
275
+ if (valid.length === 0) {
276
+ return {
277
+ bankModelCount: bank.models.length,
278
+ usedOutputs: 0,
279
+ diagnostics,
280
+ prediction: null,
281
+ predictionName: null,
282
+ probability: 0,
283
+ familyPrediction: null,
284
+ familyProbability: 0,
285
+ topCandidates: [],
286
+ claimedInBank: Boolean(claimedDef),
287
+ claimedCanonicalId: claimedDef?.id || null,
288
+ claimedMatchStatus: 'insufficient',
289
+ };
290
+ }
291
+
292
+ const n = bank.models.length;
293
+ const combinedScores = new Array(n).fill(0);
294
+ for (const v of valid) {
295
+ for (let c = 0; c < n; c += 1) combinedScores[c] += v.scores[c];
296
+ }
297
+ for (let c = 0; c < n; c += 1) combinedScores[c] /= valid.length;
298
+
299
+ const calibKey = String(Math.min(valid.length, 3));
300
+ const calib = bank.calibration?.[calibKey] || { beta: 7.0, cv_accuracy: 0.96 };
301
+ const probs = softmax(calib.beta, combinedScores);
302
+
303
+ const pooledCounts = new Array(FP_DIMENSION).fill(0);
304
+ for (const v of valid) {
305
+ for (let i = 0; i < FP_DIMENSION; i += 1) pooledCounts[i] += v.counts[i];
306
+ }
307
+
308
+ const familyMap = new Map();
309
+ const allResults = bank.models.map((m, idx) => {
310
+ const p = probs[idx];
311
+ const fam = familyMap.get(m.family) || { displayName: m.family_name || m.family, probability: 0 };
312
+ fam.probability += p;
313
+ familyMap.set(m.family, fam);
314
+ return {
315
+ modelId: m.id,
316
+ displayName: m.display_name || m.id,
317
+ family: m.family,
318
+ familyName: m.family_name || m.family,
319
+ probability: Math.round(p * 10000) / 10000,
320
+ jsSimilarity: Math.round(jsSimilarity355(pooledCounts, m.counts) * 10000) / 10000,
321
+ score: Math.round(combinedScores[idx] * 1000) / 1000,
322
+ };
323
+ });
324
+
325
+ allResults.sort((a, b) => b.probability - a.probability || b.score - a.score);
326
+ const familyProbabilities = Array.from(familyMap.entries())
327
+ .map(([family, info]) => ({
328
+ family,
329
+ displayName: info.displayName,
330
+ probability: Math.round(info.probability * 10000) / 10000,
331
+ }))
332
+ .sort((a, b) => b.probability - a.probability);
333
+
334
+ const top = allResults[0];
335
+ const winFam = familyProbabilities[0];
336
+ const lowConfidence = top.probability < 0.6;
337
+
338
+ let claimedModelRank = null;
339
+ let claimedModelProb = null;
340
+ if (claimedDef) {
341
+ const idx = allResults.findIndex((r) => r.modelId === claimedDef.id);
342
+ if (idx >= 0) {
343
+ claimedModelRank = idx + 1;
344
+ claimedModelProb = allResults[idx].probability;
345
+ }
346
+ }
347
+
348
+ const claimedExpectedFamily = claimedDef?.family || inferExpectedBankFamily(claimedModel);
349
+ let claimedMatchStatus = 'not_in_bank';
350
+ if (!claimedDef) {
351
+ if (claimedExpectedFamily && winFam && winFam.family !== claimedExpectedFamily && winFam.probability >= 0.75) {
352
+ claimedMatchStatus = 'family_mismatch';
353
+ }
354
+ } else if (lowConfidence) {
355
+ claimedMatchStatus = 'low_confidence';
356
+ } else if (claimedModelRank === 1 || (claimedModelProb !== null && claimedModelProb >= 0.25)) {
357
+ claimedMatchStatus = 'matched';
358
+ } else if (top.probability >= 0.72 && (claimedModelProb ?? 0) < 0.15) {
359
+ claimedMatchStatus = 'mismatch';
360
+ } else {
361
+ claimedMatchStatus = 'low_confidence';
362
+ }
363
+
364
+ return {
365
+ bankModelCount: bank.models.length,
366
+ usedOutputs: valid.length,
367
+ diagnostics,
368
+ prediction: top.modelId,
369
+ predictionName: top.displayName,
370
+ probability: top.probability,
371
+ lowConfidence,
372
+ familyPrediction: winFam?.family || null,
373
+ familyProbability: winFam?.probability || 0,
374
+ familyProbabilities,
375
+ topCandidates: allResults.slice(0, 5),
376
+ claimedInBank: Boolean(claimedDef),
377
+ claimedCanonicalId: claimedDef?.id || null,
378
+ claimedModelRank,
379
+ claimedModelProb,
380
+ claimedMatchStatus,
381
+ cvAccuracy: calib.cv_accuracy ?? null,
382
+ };
383
+ }
package/src/links.mjs ADDED
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Contextual, restrained AIAPIPK links emitted at the end of a CLI audit.
3
+ * Strictly capped at 1-2 high-signal lines (never spam):
4
+ * - Line 1 (always): site archive, pricing & live status lookup for the audited domain
5
+ * - Line 2 (only when actionable):
6
+ * - If an issue was detected -> verified alternative leaderboard for that model family
7
+ * - Else if model is outside the local 18-model bank -> online 31-model live bank
8
+ */
9
+
10
+ const TWO_PART_TLDS = new Set([
11
+ 'com.cn',
12
+ 'net.cn',
13
+ 'org.cn',
14
+ 'gov.cn',
15
+ 'co.uk',
16
+ 'org.uk',
17
+ 'co.jp',
18
+ 'ne.jp',
19
+ 'com.hk',
20
+ 'com.tw',
21
+ 'com.sg',
22
+ 'com.au',
23
+ 'co.kr',
24
+ ]);
25
+
26
+ const PROXY_SUBDOMAIN_PREFIXES = new Set([
27
+ 'api',
28
+ 'www',
29
+ 'v1',
30
+ 'v2',
31
+ 'proxy',
32
+ 'gateway',
33
+ 'gw',
34
+ 'relay',
35
+ 'openai',
36
+ 'claude',
37
+ 'anthropic',
38
+ 'ai',
39
+ 'llm',
40
+ 'chat',
41
+ 'router',
42
+ ]);
43
+
44
+ export function extractRootDomain(baseUrl) {
45
+ const raw = String(baseUrl || '').trim();
46
+ if (!raw) return null;
47
+ let hostname = '';
48
+ try {
49
+ hostname = new URL(/^https?:\/\//i.test(raw) ? raw : `https://${raw}`).hostname.toLowerCase();
50
+ } catch {
51
+ return null;
52
+ }
53
+ if (!hostname || hostname === 'localhost' || /^(\d{1,3}\.){3}\d{1,3}$/.test(hostname) || hostname.includes(':')) {
54
+ return null;
55
+ }
56
+ const parts = hostname.split('.').filter(Boolean);
57
+ if (parts.length <= 2) return hostname;
58
+
59
+ const lastTwo = `${parts[parts.length - 2]}.${parts[parts.length - 1]}`;
60
+ if (TWO_PART_TLDS.has(lastTwo) && parts.length >= 3) {
61
+ return `${parts[parts.length - 3]}.${lastTwo}`;
62
+ }
63
+ if (parts.length === 3 && PROXY_SUBDOMAIN_PREFIXES.has(parts[0])) {
64
+ return lastTwo;
65
+ }
66
+ return lastTwo;
67
+ }
68
+
69
+ export function inferModelTagSlug(modelName) {
70
+ const m = String(modelName || '').toLowerCase();
71
+ if (/claude|sonnet|opus|haiku|fable/.test(m)) return 'claude';
72
+ if (/gpt|codex|^o[134]([-_ ]|$)|chatgpt/.test(m)) return 'openai';
73
+ if (/gemini/.test(m)) return 'gemini';
74
+ if (/deepseek/.test(m)) return 'deepseek';
75
+ return null;
76
+ }
77
+
78
+ export function hasAuditIssue(results = {}) {
79
+ if (!results || typeof results !== 'object') return false;
80
+ if (results.inject && results.inject.status === 'fail') return true;
81
+ if (results.stream && results.stream.status === 'fail') return true;
82
+ if (results.cache && results.cache.status === 'fail') return true;
83
+ if (
84
+ results.cache &&
85
+ results.cache.status !== 'error' &&
86
+ typeof results.cache.cacheHitRate === 'number' &&
87
+ results.cache.cacheHitRate === 0
88
+ ) {
89
+ return true;
90
+ }
91
+ if (results.logic && (results.logic.status === 'fail' || results.logic.hitTrap)) return true;
92
+ if (results.fingerprint && results.fingerprint.status === 'fail') return true;
93
+ return false;
94
+ }
95
+
96
+ export function buildContextualFooter({ baseUrl, model, results }) {
97
+ const rootDomain = extractRootDomain(baseUrl);
98
+ const lines = [];
99
+
100
+ if (rootDomain) {
101
+ lines.push({
102
+ label: 'Site archive & pricing',
103
+ url: `https://www.aiapipk.com/directory/?q=${encodeURIComponent(rootDomain)}&from=cli`,
104
+ });
105
+ } else {
106
+ lines.push({
107
+ label: 'Live 370+ relay radar',
108
+ url: 'https://www.aiapipk.com/directory/?from=cli',
109
+ });
110
+ }
111
+
112
+ if (hasAuditIssue(results)) {
113
+ const slug = inferModelTagSlug(model);
114
+ lines.push({
115
+ label: slug ? `Verified ${slug} relays` : 'Verified online relays',
116
+ url: slug
117
+ ? `https://www.aiapipk.com/tag/${slug}/?from=cli`
118
+ : 'https://www.aiapipk.com/directory/?from=cli',
119
+ });
120
+ } else if (results?.fingerprint?.claimedMatchStatus === 'out_of_bank') {
121
+ lines.push({
122
+ label: '31-model live bank',
123
+ url: 'https://www.aiapipk.com/detect/?tab=fingerprint&from=cli',
124
+ });
125
+ }
126
+
127
+ return lines;
128
+ }
@@ -0,0 +1,60 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { buildContextualFooter, extractRootDomain, hasAuditIssue, inferModelTagSlug } from '../src/links.mjs';
4
+
5
+ test('extractRootDomain strips proxy subdomains and preserves two-part TLDs', () => {
6
+ assert.equal(extractRootDomain('https://api.qfgapi.com/v1'), 'qfgapi.com');
7
+ assert.equal(extractRootDomain('https://www.foxrouter.org'), 'foxrouter.org');
8
+ assert.equal(extractRootDomain('https://gateway.example.com.cn/v1/messages'), 'example.com.cn');
9
+ assert.equal(extractRootDomain('http://localhost:3000'), null);
10
+ assert.equal(extractRootDomain('http://127.0.0.1:8080'), null);
11
+ });
12
+
13
+ test('inferModelTagSlug maps major families cleanly', () => {
14
+ assert.equal(inferModelTagSlug('claude-sonnet-4-5'), 'claude');
15
+ assert.equal(inferModelTagSlug('gpt-5.4'), 'openai');
16
+ assert.equal(inferModelTagSlug('o3-mini'), 'openai');
17
+ assert.equal(inferModelTagSlug('gemini-2.5-pro'), 'gemini');
18
+ assert.equal(inferModelTagSlug('deepseek-chat'), 'deepseek');
19
+ assert.equal(inferModelTagSlug('custom-model'), null);
20
+ });
21
+
22
+ test('buildContextualFooter emits 1 clean line when audit passes cleanly', () => {
23
+ const lines = buildContextualFooter({
24
+ baseUrl: 'https://api.qfgapi.com',
25
+ model: 'claude-sonnet-4-5',
26
+ results: {
27
+ inject: { status: 'pass', tier: 'zero' },
28
+ cache: { status: 'pass', cacheHitRate: 0.92 },
29
+ fingerprint: { status: 'pass', claimedMatchStatus: 'matched' },
30
+ },
31
+ });
32
+ assert.equal(lines.length, 1);
33
+ assert.equal(lines[0].url, 'https://www.aiapipk.com/directory/?q=qfgapi.com&from=cli');
34
+ });
35
+
36
+ test('buildContextualFooter adds family alternative leaderboard when audit detects failure or 0% cache', () => {
37
+ const lines = buildContextualFooter({
38
+ baseUrl: 'https://api.badrelay.xyz',
39
+ model: 'claude-opus-4-6',
40
+ results: {
41
+ cache: { status: 'warn', cacheHitRate: 0 },
42
+ },
43
+ });
44
+ assert.equal(lines.length, 2);
45
+ assert.equal(hasAuditIssue({ cache: { status: 'warn', cacheHitRate: 0 } }), true);
46
+ assert.equal(lines[1].url, 'https://www.aiapipk.com/tag/claude/?from=cli');
47
+ });
48
+
49
+ test('buildContextualFooter adds 31-model live bank link when model is out_of_bank and no failure', () => {
50
+ const lines = buildContextualFooter({
51
+ baseUrl: 'https://api.goodrelay.com',
52
+ model: 'qwen4-max',
53
+ results: {
54
+ inject: { status: 'pass', tier: 'zero' },
55
+ fingerprint: { status: 'warn', claimedMatchStatus: 'out_of_bank' },
56
+ },
57
+ });
58
+ assert.equal(lines.length, 2);
59
+ assert.equal(lines[1].url, 'https://www.aiapipk.com/detect/?tab=fingerprint&from=cli');
60
+ });