ctxtop 4.0.0 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.antigravity-plugin/plugin.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/CHECKSUMS.sha256 +59 -42
- package/README.md +351 -330
- package/bin/ah-statusline.mjs +30 -0
- package/bin/ctxtop.mjs +330 -5
- package/config/default_flightcheck.json +19 -0
- package/config/modelCatalog.json +165 -0
- package/hooks/handlers/compact-lifecycle.mjs +323 -8
- package/hooks/handlers/config-change.mjs +402 -0
- package/hooks/handlers/hookIo.mjs +56 -0
- package/hooks/handlers/post-model-switch.mjs +111 -0
- package/hooks/handlers/post-tool-use.mjs +117 -16
- package/hooks/handlers/pre-model-switch.mjs +823 -24
- package/hooks/handlers/pre-tool-use.mjs +271 -4
- package/hooks/handlers/stop-gate.mjs +297 -11
- package/hooks/handlers/user-prompt-submit.mjs +224 -0
- package/hooks/hooks.json +50 -0
- package/hooks/post_tool_use.mjs +8 -0
- package/hooks/register.js +48 -9
- package/hooks/session_start.mjs +11 -1
- package/hooks/stop.mjs +11 -1
- package/package.json +11 -4
- package/packages/antigravity/package.json +1 -1
- package/packages/claude-code/package.json +1 -1
- package/packages/core/package.json +1 -1
- package/packages/engine-node/package.json +1 -1
- package/packages/mcp/package.json +1 -1
- package/packages/mcp/src/server.mjs +1 -1
- package/packages/pro/package.json +1 -1
- package/plugin.json +1 -1
- package/sidecars/horizon-daemon/server.mjs +38 -2
- package/skills/handoff/SKILL.md +8 -0
- package/src/adapters/antigravity/index.mjs +31 -1
- package/src/adapters/claude-code/index.mjs +40 -1
- package/src/cli/horizon_hud.mjs +254 -52
- package/src/config/modelCatalog.json +84 -0
- package/src/core/bucket_b_runtime.mjs +1200 -0
- package/src/core/constants.mjs +191 -4
- package/src/core/detectors_det01_to_16.mjs +54 -5
- package/src/core/doc_indexer.mjs +338 -0
- package/src/core/layer5_hygiene.mjs +118 -0
- package/src/core/parser.mjs +2 -1
- package/src/core/paths.mjs +3 -2
- package/src/core/rsl_clash_auditor.mjs +423 -0
- package/src/core/rsl_distiller.mjs +372 -0
- package/src/core/rsl_ledger.mjs +969 -0
- package/src/core/rsl_triage.mjs +909 -0
- package/src/core/session_auditor.mjs +658 -0
- package/src/core/shield_manager.mjs +1417 -0
- package/src/core/task_quota_router.mjs +1 -1
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +874 -47
- package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +13 -6
- package/src/core-isomorphic/config/anthropicModelCatalog.json +404 -1
- package/src/core-isomorphic/config/catalogLoader.mjs +546 -46
- package/src/core-isomorphic/config/horizonConfig.mjs +47 -1
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +266 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +18 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +98 -12
- package/src/core-isomorphic/economics/driftLatency.mjs +114 -0
- package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
- package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
- package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +191 -191
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +154 -5
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +103 -11
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +311 -1
- package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +16 -0
- package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/src/core-isomorphic/index.js +1 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +36 -12
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +293 -237
- package/src/core-isomorphic/ui/modViews.mjs +35 -9
- package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
- package/src/diagnostics/doctorEngine.mjs +95 -3
- package/src/engine-node/db/probe.mjs +234 -2
- package/src/engine-node/index.mjs +3 -0
- package/src/engine-node/sensors/blindspots.mjs +13 -6
- package/src/hooks/antigravity_rsl_hook.mjs +250 -0
- package/src/hooks/claude_rsl_hook.mjs +288 -0
- package/src/hooks/post_invocation.mjs +196 -4
- package/src/hooks/pre_invocation.mjs +732 -22
- package/src/hooks/session_start.mjs +39 -1
- package/src/utils/modelSwitchTelemetry.mjs +308 -0
- package/src/utils/sessionCalibration.mjs +657 -0
- package/src/webview/horizon_panel.html +1325 -317
|
@@ -0,0 +1,860 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core-isomorphic/guards/bucketBAlphaBeta.mjs
|
|
3
|
+
* Pure Isomorphic Evaluators for Bucket B Sub-Waves B-Alpha & B-Beta:
|
|
4
|
+
* - `#2` `GREP_GLOB_FIREWALL` (Context-aware >15-match search ranker)
|
|
5
|
+
* - `#4` `BLAST_RADIUS_BREAKER` (Unverified multi-file / logic-line edit cap)
|
|
6
|
+
* - `#9` `WEB_BOILERPLATE_BUDGETER` (Lossless `<code>`/`<pre>`/`<table>` HTML distiller)
|
|
7
|
+
* - `#8` `DUPLICATE_CLONE_DETECTOR` (5-line FNV-1a 64-bit normalized shingle clone detector)
|
|
8
|
+
* - `#3b` `TEST_INTEGRITY_LOCK` (EvilGenie hardcoded input-output return oracle)
|
|
9
|
+
* - `#19` `OVERENGINEERING_DIFF_GATE` (Test-exempt non-test diff bloat & dead abstraction scorer)
|
|
10
|
+
*
|
|
11
|
+
* Mod Law 4 Compliant: Zero `node:*` imports, zero `process.cwd`/`exit`, zero global mutable state.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const FORBIDDEN_SKU_PATH_RE =
|
|
15
|
+
/(?:^|\/)(?:packages\/airlock(?:\/|$)|\.github\/workflows\/airlock-schema-canary\.yml$|docs\/HIGHBEAM_AIRLOCK_[^/]*\.md$)/i;
|
|
16
|
+
|
|
17
|
+
const TEST_PATH_RE =
|
|
18
|
+
/(?:^|\/)(?:test|tests|__tests__|spec|specs)\/|\.(?:test|spec)\.[cm]?[jt]sx?$/i;
|
|
19
|
+
|
|
20
|
+
const ARCHIVE_OR_LOW_PRIORITY_PATH_RE =
|
|
21
|
+
/(?:^|\/)(?:archive|archived|deprecated|legacy|evaluation_bundles|vendor|dist|build|coverage|snapshots|__snapshots__|fixtures|examples|docs)\//i;
|
|
22
|
+
|
|
23
|
+
const ACTIVE_SOURCE_ROOT_RE = /^(?:src|hooks|bin|packages|sidecars|lib|app)\//i;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Checks whether a normalized relative path belongs to an isolated sister SKU.
|
|
27
|
+
*
|
|
28
|
+
* @param {string} relPath
|
|
29
|
+
* @returns {boolean}
|
|
30
|
+
*/
|
|
31
|
+
export function isBucketBForbiddenSkuPath(relPath = '') {
|
|
32
|
+
const norm = String(relPath || '').replace(/\\/g, '/').replace(/^\.\//, '');
|
|
33
|
+
return FORBIDDEN_SKU_PATH_RE.test(norm);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// ============================================================================
|
|
37
|
+
// #2 GREP_GLOB_FIREWALL
|
|
38
|
+
// ============================================================================
|
|
39
|
+
|
|
40
|
+
const REPO_WIDE_AUDIT_PROMPT_RE =
|
|
41
|
+
/\b(?:rename|refactor\s+across|replace\s+all|replace_all|all\s+occurrences|every\s+file|everywhere|repo-wide|codebase-wide|across\s+the\s+(?:repo|codebase|workspace)|audit\s+all|find\s+all\s+usages|global\s+search)\b/i;
|
|
42
|
+
|
|
43
|
+
function dirnamePosix(p = '') {
|
|
44
|
+
const idx = p.lastIndexOf('/');
|
|
45
|
+
return idx > 0 ? p.slice(0, idx) : '';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function stemName(p = '') {
|
|
49
|
+
const base = p.slice(p.lastIndexOf('/') + 1);
|
|
50
|
+
return base.replace(/\.(?:test|spec)\./i, '.').replace(/\.[^.]+$/, '');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Ranks and caps unbounded `Grep` / `Glob` result lists (`> 15` files) using active-session context.
|
|
55
|
+
*
|
|
56
|
+
* @param {object} input
|
|
57
|
+
* @param {string[]} [input.matchPaths=[]]
|
|
58
|
+
* @param {string} [input.query='']
|
|
59
|
+
* @param {string} [input.lastUserPrompt='']
|
|
60
|
+
* @param {Iterable<string>} [input.activeFiles=[]] - Files read or edited in this session
|
|
61
|
+
* @param {Iterable<string>} [input.dirtyFiles=[]] - Modified files in git working tree
|
|
62
|
+
* @param {string} [input.lastEditedFile='']
|
|
63
|
+
* @param {Record<string, number>} [input.mtimeByPath={}] - Epoch ms per path
|
|
64
|
+
* @param {number} [input.maxMatchesThreshold=15]
|
|
65
|
+
* @param {number} [input.topK=8]
|
|
66
|
+
*/
|
|
67
|
+
export function evaluateGrepGlobFirewall(input = {}) {
|
|
68
|
+
const maxMatchesThreshold = Number(input.maxMatchesThreshold) || 15;
|
|
69
|
+
const topK = Number(input.topK) || 8;
|
|
70
|
+
const rawPaths = Array.isArray(input.matchPaths) ? input.matchPaths : [];
|
|
71
|
+
const cleanPaths = [];
|
|
72
|
+
const seen = new Set();
|
|
73
|
+
|
|
74
|
+
for (const p of rawPaths) {
|
|
75
|
+
const norm = String(p || '').replace(/\\/g, '/').replace(/^\.\//, '');
|
|
76
|
+
if (!norm || seen.has(norm) || isBucketBForbiddenSkuPath(norm)) continue;
|
|
77
|
+
seen.add(norm);
|
|
78
|
+
cleanPaths.push(norm);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (cleanPaths.length <= maxMatchesThreshold) {
|
|
82
|
+
return {
|
|
83
|
+
triggered: false,
|
|
84
|
+
decision: 'allow',
|
|
85
|
+
rankedPaths: cleanPaths,
|
|
86
|
+
topPaths: cleanPaths,
|
|
87
|
+
omittedCount: 0,
|
|
88
|
+
tokensSavedEst: 0
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const prompt = String(input.lastUserPrompt || '');
|
|
93
|
+
if (REPO_WIDE_AUDIT_PROMPT_RE.test(prompt)) {
|
|
94
|
+
return {
|
|
95
|
+
triggered: false,
|
|
96
|
+
decision: 'allow',
|
|
97
|
+
exemptReason: 'repo_wide_audit_intent',
|
|
98
|
+
rankedPaths: cleanPaths,
|
|
99
|
+
topPaths: cleanPaths,
|
|
100
|
+
omittedCount: 0,
|
|
101
|
+
tokensSavedEst: 0
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Exempt short exact symbol boundary searches (`\bid\b`, `db`, `fs`, `ui`) up to 25 matches
|
|
106
|
+
const q = String(input.query || '').trim();
|
|
107
|
+
const strippedBoundary = q.replace(/^\\b|\\b$/g, '');
|
|
108
|
+
const isShortExactSymbol =
|
|
109
|
+
/^[A-Za-z_$][A-Za-z0-9_$]{1,3}$/.test(strippedBoundary) &&
|
|
110
|
+
(q.startsWith('\\b') || Boolean(input.exactSymbol));
|
|
111
|
+
if (isShortExactSymbol && cleanPaths.length <= 25) {
|
|
112
|
+
return {
|
|
113
|
+
triggered: false,
|
|
114
|
+
decision: 'allow',
|
|
115
|
+
exemptReason: 'short_exact_symbol_query',
|
|
116
|
+
rankedPaths: cleanPaths,
|
|
117
|
+
topPaths: cleanPaths,
|
|
118
|
+
omittedCount: 0,
|
|
119
|
+
tokensSavedEst: 0
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const activeSet = new Set(
|
|
124
|
+
Array.from(input.activeFiles || [], (f) => String(f).replace(/\\/g, '/').replace(/^\.\//, ''))
|
|
125
|
+
);
|
|
126
|
+
const dirtySet = new Set(
|
|
127
|
+
Array.from(input.dirtyFiles || [], (f) => String(f).replace(/\\/g, '/').replace(/^\.\//, ''))
|
|
128
|
+
);
|
|
129
|
+
const lastEdited = String(input.lastEditedFile || '').replace(/\\/g, '/').replace(/^\.\//, '');
|
|
130
|
+
const lastDir = dirnamePosix(lastEdited);
|
|
131
|
+
const lastParentDir = dirnamePosix(lastDir);
|
|
132
|
+
const lastStem = lastEdited ? stemName(lastEdited) : '';
|
|
133
|
+
const mtimeMap = input.mtimeByPath || {};
|
|
134
|
+
const mtimes = Object.values(mtimeMap).filter((v) => typeof v === 'number' && v > 0);
|
|
135
|
+
const maxMtime = mtimes.length > 0 ? Math.max(...mtimes) : 0;
|
|
136
|
+
|
|
137
|
+
const scored = cleanPaths.map((p, origIdx) => {
|
|
138
|
+
let score = 0;
|
|
139
|
+
if (activeSet.has(p)) score += 1000;
|
|
140
|
+
if (dirtySet.has(p)) score += 520;
|
|
141
|
+
|
|
142
|
+
const dir = dirnamePosix(p);
|
|
143
|
+
if (lastDir && dir === lastDir) score += 320;
|
|
144
|
+
else if (lastParentDir && dir.startsWith(lastParentDir)) score += 180;
|
|
145
|
+
|
|
146
|
+
if (lastStem && stemName(p) === lastStem) score += 260;
|
|
147
|
+
|
|
148
|
+
const mtime = Number(mtimeMap[p] || 0);
|
|
149
|
+
if (maxMtime > 0 && mtime > 0) {
|
|
150
|
+
const ageMs = Math.max(0, maxMtime - mtime);
|
|
151
|
+
if (ageMs <= 10 * 60 * 1000) score += 160;
|
|
152
|
+
else if (ageMs <= 60 * 60 * 1000) score += 90;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (ARCHIVE_OR_LOW_PRIORITY_PATH_RE.test(p)) score -= 240;
|
|
156
|
+
else if (ACTIVE_SOURCE_ROOT_RE.test(p)) score += 110;
|
|
157
|
+
|
|
158
|
+
if (q && stemName(p).toLowerCase().includes(strippedBoundary.toLowerCase())) {
|
|
159
|
+
score += 140;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return { path: p, score, origIdx };
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
scored.sort((a, b) => (b.score !== a.score ? b.score - a.score : a.origIdx - b.origIdx));
|
|
166
|
+
const rankedPaths = scored.map((s) => s.path);
|
|
167
|
+
const topPaths = rankedPaths.slice(0, topK);
|
|
168
|
+
const omittedCount = Math.max(0, rankedPaths.length - topPaths.length);
|
|
169
|
+
|
|
170
|
+
return {
|
|
171
|
+
triggered: true,
|
|
172
|
+
decision: 'warn',
|
|
173
|
+
code: 'GREP_GLOB_FIREWALL',
|
|
174
|
+
rankedPaths,
|
|
175
|
+
topPaths,
|
|
176
|
+
omittedCount,
|
|
177
|
+
tokensSavedEst: omittedCount * 140,
|
|
178
|
+
reason: `[Quota Shield] Ranked ${rankedPaths.length} search matches -> Top ${topPaths.length} active-context matches (+${omittedCount} lower-priority paths omitted; refine glob/path to inspect others).`
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ============================================================================
|
|
183
|
+
// #9 WEB_BOILERPLATE_BUDGETER
|
|
184
|
+
// ============================================================================
|
|
185
|
+
|
|
186
|
+
const STRIP_BLOCK_TAG_RE =
|
|
187
|
+
/<(script|style|svg|nav|footer|header|aside|noscript|iframe|form)\b[^>]*>[\s\S]*?<\/\1>/gi;
|
|
188
|
+
|
|
189
|
+
const BOILERPLATE_CONTAINER_RE =
|
|
190
|
+
/<(div|section)\b[^>]*(?:id|class)\s*=\s*["'][^"']*(?:cookie-banner|cookie-consent|gdpr|newsletter-signup|site-nav|navbar|sidebar-nav|breadcrumbs|share-buttons|promo-banner|ad-slot|toc-sidebar)[^"']*["'][^>]*>[\s\S]*?<\/\1>/gi;
|
|
191
|
+
|
|
192
|
+
function decodeHtmlEntities(str = '') {
|
|
193
|
+
return String(str)
|
|
194
|
+
.replace(/ /gi, ' ')
|
|
195
|
+
.replace(/&/gi, '&')
|
|
196
|
+
.replace(/</gi, '<')
|
|
197
|
+
.replace(/>/gi, '>')
|
|
198
|
+
.replace(/"/gi, '"')
|
|
199
|
+
.replace(/'|'/gi, "'");
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function convertHtmlTableToMarkdown(tableHtml = '', restoreTokenFn) {
|
|
203
|
+
const rows = [];
|
|
204
|
+
const trMatches = tableHtml.match(/<tr\b[^>]*>[\s\S]*?<\/tr>/gi) || [];
|
|
205
|
+
for (const tr of trMatches) {
|
|
206
|
+
const cells = [];
|
|
207
|
+
const cellMatches = tr.match(/<t[hd]\b[^>]*>[\s\S]*?<\/t[hd]>/gi) || [];
|
|
208
|
+
for (const cell of cellMatches) {
|
|
209
|
+
const inner = cell
|
|
210
|
+
.replace(/^<t[hd]\b[^>]*>|<\/t[hd]>$/gi, '')
|
|
211
|
+
.replace(/<[^>]+>/g, ' ');
|
|
212
|
+
const restored = restoreTokenFn(inner);
|
|
213
|
+
const cleaned = decodeHtmlEntities(restored).replace(/\s+/g, ' ').trim().replace(/\|/g, '\\|');
|
|
214
|
+
cells.push(cleaned);
|
|
215
|
+
}
|
|
216
|
+
if (cells.length > 0) rows.push(cells);
|
|
217
|
+
}
|
|
218
|
+
if (rows.length === 0) return '';
|
|
219
|
+
const colCount = Math.max(...rows.map((r) => r.length));
|
|
220
|
+
const padRow = (r) => {
|
|
221
|
+
const copy = [...r];
|
|
222
|
+
while (copy.length < colCount) copy.push('');
|
|
223
|
+
return `| ${copy.join(' | ')} |`;
|
|
224
|
+
};
|
|
225
|
+
const headerLine = padRow(rows[0]);
|
|
226
|
+
const sepLine = `| ${new Array(colCount).fill('---').join(' | ')} |`;
|
|
227
|
+
const bodyLines = rows.slice(1).map(padRow);
|
|
228
|
+
return `\n${[headerLine, sepLine, ...bodyLines].join('\n')}\n`;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Distills bloated raw HTML pages into compact Markdown while preserving 100% of
|
|
233
|
+
* `<pre>`, `<code>`, and `<table>` cell contents verbatim.
|
|
234
|
+
*
|
|
235
|
+
* @param {object} input
|
|
236
|
+
* @param {string} [input.html='']
|
|
237
|
+
* @param {number} [input.webFetchesInTurn=1]
|
|
238
|
+
* @param {number} [input.minBytesToDistill=1200]
|
|
239
|
+
*/
|
|
240
|
+
export function distillHtmlWebPayload(input = {}) {
|
|
241
|
+
const html = String(input.html || '');
|
|
242
|
+
const webFetchesInTurn = Number(input.webFetchesInTurn) || 1;
|
|
243
|
+
const minBytes = Number(input.minBytesToDistill) || 1200;
|
|
244
|
+
|
|
245
|
+
if (html.length < minBytes && webFetchesInTurn <= 5) {
|
|
246
|
+
return {
|
|
247
|
+
triggered: false,
|
|
248
|
+
decision: 'allow',
|
|
249
|
+
distilled: html,
|
|
250
|
+
tokenReductionPct: 0,
|
|
251
|
+
tokensSavedEst: 0,
|
|
252
|
+
excessiveFetchVelocity: false
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const protectedSlots = [];
|
|
257
|
+
const stash = (text) => {
|
|
258
|
+
const token = `\u0000CTX_SLOT_${protectedSlots.length}\u0000`;
|
|
259
|
+
protectedSlots.push(text);
|
|
260
|
+
return token;
|
|
261
|
+
};
|
|
262
|
+
const restoreAll = (text) =>
|
|
263
|
+
String(text).replace(/\u0000CTX_SLOT_(\d+)\u0000/g, (_m, idx) => protectedSlots[Number(idx)] ?? '');
|
|
264
|
+
|
|
265
|
+
// 1. Strip comments and non-content chrome blocks BEFORE touching code/tables
|
|
266
|
+
let working = html
|
|
267
|
+
.replace(/<!--[\s\S]*?-->/g, '')
|
|
268
|
+
.replace(STRIP_BLOCK_TAG_RE, '\n')
|
|
269
|
+
.replace(BOILERPLATE_CONTAINER_RE, '\n');
|
|
270
|
+
|
|
271
|
+
// 2. Protect `<pre>...</pre>` blocks verbatim
|
|
272
|
+
working = working.replace(/<pre\b[^>]*>([\s\S]*?)<\/pre>/gi, (_m, inner) => {
|
|
273
|
+
const cleanCode = decodeHtmlEntities(
|
|
274
|
+
inner.replace(/^<code\b[^>]*>|<\/code>$/gi, '')
|
|
275
|
+
).trim();
|
|
276
|
+
return stash(`\n\`\`\`\n${cleanCode}\n\`\`\`\n`);
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
// 3. Protect inline `<code>...</code>` spans verbatim
|
|
280
|
+
working = working.replace(/<code\b[^>]*>([\s\S]*?)<\/code>/gi, (_m, inner) => {
|
|
281
|
+
const cleanInline = decodeHtmlEntities(inner.replace(/<[^>]+>/g, '')).trim();
|
|
282
|
+
return stash(`\`${cleanInline}\``);
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
// 4. Convert `<table>...</table>` into lossless Markdown pipe tables
|
|
286
|
+
working = working.replace(/<table\b[^>]*>[\s\S]*?<\/table>/gi, (tableBlock) =>
|
|
287
|
+
stash(convertHtmlTableToMarkdown(tableBlock, restoreAll))
|
|
288
|
+
);
|
|
289
|
+
|
|
290
|
+
// 5. Convert structural headings & list items, then strip all remaining HTML tags/attributes
|
|
291
|
+
working = working
|
|
292
|
+
.replace(/<h([1-6])\b[^>]*>([\s\S]*?)<\/h\1>/gi, (_m, lvl, inner) =>
|
|
293
|
+
`\n${'#'.repeat(Number(lvl))} ${inner.replace(/<[^>]+>/g, '').trim()}\n`
|
|
294
|
+
)
|
|
295
|
+
.replace(/<li\b[^>]*>([\s\S]*?)<\/li>/gi, (_m, inner) => `\n- ${inner.replace(/<[^>]+>/g, '').trim()}`)
|
|
296
|
+
.replace(/<(?:p|div|section|article|br|hr)\b[^>]*>/gi, '\n')
|
|
297
|
+
.replace(/<[^>]+>/g, ' ');
|
|
298
|
+
|
|
299
|
+
let distilled = decodeHtmlEntities(working);
|
|
300
|
+
distilled = restoreAll(distilled)
|
|
301
|
+
.replace(/[ \t]+\n/g, '\n')
|
|
302
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
303
|
+
.trim();
|
|
304
|
+
|
|
305
|
+
const origTok = Math.max(1, Math.ceil(html.length / 4));
|
|
306
|
+
const newTok = Math.ceil(distilled.length / 4);
|
|
307
|
+
const savedTok = Math.max(0, origTok - newTok);
|
|
308
|
+
const reductionPct = Number(((savedTok / origTok) * 100).toFixed(2));
|
|
309
|
+
const excessiveFetchVelocity = webFetchesInTurn > 5;
|
|
310
|
+
|
|
311
|
+
return {
|
|
312
|
+
triggered: savedTok >= 150 || excessiveFetchVelocity,
|
|
313
|
+
decision: 'warn',
|
|
314
|
+
code: 'WEB_BOILERPLATE_BUDGETER',
|
|
315
|
+
distilled,
|
|
316
|
+
tokenReductionPct: reductionPct,
|
|
317
|
+
tokensSavedEst: savedTok,
|
|
318
|
+
excessiveFetchVelocity,
|
|
319
|
+
reason: `[Quota Shield] Distilled web HTML (${reductionPct}% boilerplate stripped, ~${savedTok} tok saved${
|
|
320
|
+
excessiveFetchVelocity ? `; high web fetch velocity: ${webFetchesInTurn} fetches in turn` : ''
|
|
321
|
+
}).`
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// ============================================================================
|
|
326
|
+
// #4 BLAST_RADIUS_BREAKER
|
|
327
|
+
// ============================================================================
|
|
328
|
+
|
|
329
|
+
const GREENFIELD_SCAFFOLD_PROMPT_RE =
|
|
330
|
+
/\b(?:scaffold|greenfield|bootstrap|create\s+(?:a\s+)?new\s+(?:package|app|project|module)|generate\s+boilerplate|initial\s+skeleton)\b/i;
|
|
331
|
+
|
|
332
|
+
function isPureImportExportDiff(changedLines = []) {
|
|
333
|
+
const nonBlank = changedLines.map((l) => l.trim()).filter(Boolean);
|
|
334
|
+
if (nonBlank.length === 0) return true;
|
|
335
|
+
let importCount = 0;
|
|
336
|
+
for (const line of nonBlank) {
|
|
337
|
+
if (
|
|
338
|
+
/^(?:import\b|export\b.*\bfrom\b|from\s+['"]|\x7d\s*from\s+['"]|const\s+\S+\s*=\s*require\x28)/.test(
|
|
339
|
+
line
|
|
340
|
+
)
|
|
341
|
+
) {
|
|
342
|
+
importCount += 1;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return importCount / nonBlank.length >= 0.9;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Evaluates unverified source edit blast radius since the last exit-`0` test/`tsc` verification.
|
|
350
|
+
*
|
|
351
|
+
* @param {object} input
|
|
352
|
+
* @param {Array<{ filePath: string, netLines?: number, changedLines?: string[] }>} [input.editsSinceVerify=[]]
|
|
353
|
+
* @param {string} [input.lastUserPrompt='']
|
|
354
|
+
* @param {number} [input.maxUnverifiedFiles=6]
|
|
355
|
+
* @param {number} [input.maxNetLogicLines=250]
|
|
356
|
+
*/
|
|
357
|
+
export function evaluateBlastRadiusBreaker(input = {}) {
|
|
358
|
+
const maxUnverifiedFiles = Number(input.maxUnverifiedFiles) || 6;
|
|
359
|
+
const maxNetLogicLines = Number(input.maxNetLogicLines) || 250;
|
|
360
|
+
const prompt = String(input.lastUserPrompt || '');
|
|
361
|
+
|
|
362
|
+
if (GREENFIELD_SCAFFOLD_PROMPT_RE.test(prompt)) {
|
|
363
|
+
return {
|
|
364
|
+
triggered: false,
|
|
365
|
+
decision: 'allow',
|
|
366
|
+
exemptReason: 'greenfield_scaffold_intent',
|
|
367
|
+
distinctSourceFiles: 0,
|
|
368
|
+
netLogicLines: 0,
|
|
369
|
+
tokensSavedEst: 0
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const edits = Array.isArray(input.editsSinceVerify) ? input.editsSinceVerify : [];
|
|
374
|
+
const sourceFileSet = new Set();
|
|
375
|
+
let netLogicLines = 0;
|
|
376
|
+
|
|
377
|
+
for (const edit of edits) {
|
|
378
|
+
const norm = String(edit.filePath || '').replace(/\\/g, '/').replace(/^\.\//, '');
|
|
379
|
+
if (!norm || isBucketBForbiddenSkuPath(norm)) continue;
|
|
380
|
+
// Exempt test files and Markdown docs from unverified source blast radius
|
|
381
|
+
if (TEST_PATH_RE.test(norm) || /\.md$/i.test(norm)) continue;
|
|
382
|
+
if (Array.isArray(edit.changedLines) && isPureImportExportDiff(edit.changedLines)) continue;
|
|
383
|
+
|
|
384
|
+
sourceFileSet.add(norm);
|
|
385
|
+
netLogicLines += Math.max(0, Number(edit.netLines) || 0);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
const distinctSourceFiles = sourceFileSet.size;
|
|
389
|
+
const exceededFiles = distinctSourceFiles > maxUnverifiedFiles;
|
|
390
|
+
const exceededLines = distinctSourceFiles >= 4 && netLogicLines > maxNetLogicLines;
|
|
391
|
+
|
|
392
|
+
if (!exceededFiles && !exceededLines) {
|
|
393
|
+
return {
|
|
394
|
+
triggered: false,
|
|
395
|
+
decision: 'allow',
|
|
396
|
+
distinctSourceFiles,
|
|
397
|
+
netLogicLines,
|
|
398
|
+
tokensSavedEst: 0
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
return {
|
|
403
|
+
triggered: true,
|
|
404
|
+
decision: 'warn',
|
|
405
|
+
code: 'BLAST_RADIUS_BREAKER',
|
|
406
|
+
distinctSourceFiles,
|
|
407
|
+
netLogicLines,
|
|
408
|
+
tokensSavedEst: 2400,
|
|
409
|
+
reason: `[Build Integrity Shield] ${distinctSourceFiles} source files (${netLogicLines} net logic lines) modified without an intervening passing test or typecheck. Run targeted verification before expanding edit scope.`
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// ============================================================================
|
|
414
|
+
// #8 DUPLICATE_CLONE_DETECTOR (5-Line Normalized FNV-1a 64-bit Shingling)
|
|
415
|
+
// ============================================================================
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Computes a fast zero-BigInt-allocation 64-bit dual-lane FNV-1a hex digest (`Math.imul` SMI).
|
|
419
|
+
*
|
|
420
|
+
* @param {string} str
|
|
421
|
+
* @returns {string}
|
|
422
|
+
*/
|
|
423
|
+
export function fnv1a64Hex(str = '') {
|
|
424
|
+
let h1 = 0x811c9dc5 | 0;
|
|
425
|
+
let h2 = 0x9e3779b9 | 0;
|
|
426
|
+
for (let i = 0; i < str.length; i++) {
|
|
427
|
+
const code = str.charCodeAt(i);
|
|
428
|
+
h1 = Math.imul(h1 ^ code, 0x01000193);
|
|
429
|
+
h2 = Math.imul(h2 ^ ((code << 5) | (code >>> 3)), 0x85ebca6b);
|
|
430
|
+
}
|
|
431
|
+
return (h1 >>> 0).toString(16).padStart(8, '0') + (h2 >>> 0).toString(16).padStart(8, '0');
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
const BOILERPLATE_LINE_SKIP_RE =
|
|
435
|
+
/^(?:[\x7b\x7d\x28\x29[\];,]+|try\s*\x7b|\x7d\s*catch\b[^\x7b]*\x7b|\x7d\s*finally\s*\x7b|else\s*\x7b|\x7d\s*else\s*\x7b|(?:describe|it|test|beforeEach|afterEach|before|after)\s*\x28|return\s+(?:null|undefined|true|false|\x7b\x7d|\[\])\s*;?|(?:import\s+|export\s+(?:\*|\x7b[^\x7d]*\x7d)\s+from\s+|const\s+\S+\s*=\s*require\x28))/;
|
|
436
|
+
|
|
437
|
+
function hashLineDual32(str) {
|
|
438
|
+
let h1 = 0x811c9dc5 | 0;
|
|
439
|
+
let h2 = 0x9e3779b9 | 0;
|
|
440
|
+
for (let i = 0; i < str.length; i++) {
|
|
441
|
+
const c = str.charCodeAt(i);
|
|
442
|
+
h1 = Math.imul(h1 ^ c, 0x01000193);
|
|
443
|
+
h2 = Math.imul(h2 ^ ((c << 5) | (c >>> 3)), 0x85ebca6b);
|
|
444
|
+
}
|
|
445
|
+
return [h1, h2];
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* Strips imports, comments, single-brace lines, and test `describe`/`it` boilerplate wrappers,
|
|
450
|
+
* returning normalized non-trivial logic lines suitable for 5-line clone shingling.
|
|
451
|
+
*
|
|
452
|
+
* @param {string} source
|
|
453
|
+
* @returns {Array<{ norm: string, lineNo: number, h1: number, h2: number, len: number }>}
|
|
454
|
+
*/
|
|
455
|
+
export function normalizeLinesForShingling(source = '') {
|
|
456
|
+
const src = String(source || '');
|
|
457
|
+
const rawLines = src.split('\n');
|
|
458
|
+
const result = [];
|
|
459
|
+
let inBlockComment = false;
|
|
460
|
+
let skippingMultilineImport = false;
|
|
461
|
+
|
|
462
|
+
for (let idx = 0; idx < rawLines.length; idx++) {
|
|
463
|
+
let line = rawLines[idx];
|
|
464
|
+
if (line.endsWith('\r')) line = line.slice(0, -1);
|
|
465
|
+
|
|
466
|
+
if (inBlockComment) {
|
|
467
|
+
const endIdx = line.indexOf('*/');
|
|
468
|
+
if (endIdx < 0) continue;
|
|
469
|
+
inBlockComment = false;
|
|
470
|
+
line = line.slice(endIdx + 2);
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
const trimmedStart = line.trimStart();
|
|
474
|
+
if (trimmedStart.startsWith('/*')) {
|
|
475
|
+
const blockEnd = trimmedStart.indexOf('*/', 2);
|
|
476
|
+
if (blockEnd >= 0) {
|
|
477
|
+
line = trimmedStart.slice(blockEnd + 2);
|
|
478
|
+
} else {
|
|
479
|
+
inBlockComment = true;
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
if (trimmedStart.startsWith('//')) continue;
|
|
485
|
+
|
|
486
|
+
line = line.trim();
|
|
487
|
+
if (line.length < 8 || line.startsWith('*')) continue;
|
|
488
|
+
|
|
489
|
+
if (skippingMultilineImport) {
|
|
490
|
+
if (line.includes('fro' + 'm ') || line.endsWith('\x7d;') || line.endsWith('\x7d')) {
|
|
491
|
+
skippingMultilineImport = false;
|
|
492
|
+
}
|
|
493
|
+
continue;
|
|
494
|
+
}
|
|
495
|
+
const c0 = line.charCodeAt(0);
|
|
496
|
+
if ((c0 === 105 || c0 === 101) && /^(?:import|export)\s*\{[^}]*$/.test(line)) {
|
|
497
|
+
skippingMultilineImport = true;
|
|
498
|
+
continue;
|
|
499
|
+
}
|
|
500
|
+
if (
|
|
501
|
+
(c0 === 123 || c0 === 125 || c0 === 40 || c0 === 41 || c0 === 91 || c0 === 93 || c0 === 59 || c0 === 116 || c0 === 101 || c0 === 100 || c0 === 105 || c0 === 98 || c0 === 97 || c0 === 114 || c0 === 99) &&
|
|
502
|
+
BOILERPLATE_LINE_SKIP_RE.test(line)
|
|
503
|
+
) {
|
|
504
|
+
continue;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
const norm = line.includes(' ') || line.includes('\t') ? line.replace(/\s+/g, ' ') : line;
|
|
508
|
+
if (norm.length < 8) continue;
|
|
509
|
+
const [h1, h2] = hashLineDual32(norm);
|
|
510
|
+
result.push({ norm, lineNo: idx + 1, h1, h2, len: norm.length });
|
|
511
|
+
}
|
|
512
|
+
return result;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Computes 5-line rolling FNV-1a 64-bit shingles in O(N) integer ops (`0` per-window string allocations).
|
|
517
|
+
*
|
|
518
|
+
* @param {string} source
|
|
519
|
+
* @param {number} [windowSize=5]
|
|
520
|
+
* @returns {Array<{ hash: string, startLine: number, endLine: number }>}
|
|
521
|
+
*/
|
|
522
|
+
export function computeFileShingles(source = '', windowSize = 5) {
|
|
523
|
+
const normLines = normalizeLinesForShingling(source);
|
|
524
|
+
if (normLines.length < windowSize) return [];
|
|
525
|
+
const shingles = [];
|
|
526
|
+
for (let i = 0; i <= normLines.length - windowSize; i++) {
|
|
527
|
+
let charSum = 0;
|
|
528
|
+
let w1 = 0x811c9dc5 | 0;
|
|
529
|
+
let w2 = 0x9e3779b9 | 0;
|
|
530
|
+
for (let k = 0; k < windowSize; k++) {
|
|
531
|
+
const entry = normLines[i + k];
|
|
532
|
+
charSum += entry.len;
|
|
533
|
+
w1 = Math.imul(w1 ^ entry.h1, 0x01000193);
|
|
534
|
+
w2 = Math.imul(w2 ^ entry.h2, 0x85ebca6b);
|
|
535
|
+
}
|
|
536
|
+
if (charSum < 81) continue;
|
|
537
|
+
shingles.push({
|
|
538
|
+
hash: ((w1 >>> 0) * 2097152 + (w2 >>> 11)).toString(16),
|
|
539
|
+
startLine: normLines[i].lineNo,
|
|
540
|
+
endLine: normLines[i + windowSize - 1].lineNo
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
return shingles;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* Evaluates a newly added or edited code snippet against a pre-indexed workspace shingle map.
|
|
548
|
+
* Requires `>= 2` overlapping 5-line shingles (`>= 6` normalized logic lines) matching a distinct file.
|
|
549
|
+
*
|
|
550
|
+
* @param {object} input
|
|
551
|
+
* @param {string} input.targetPath
|
|
552
|
+
* @param {string} input.addedCode
|
|
553
|
+
* @param {Record<string, Array<{ file: string, startLine: number }>>} [input.shingleIndex={}]
|
|
554
|
+
* @param {number} [input.minMatchingShingles=2]
|
|
555
|
+
*/
|
|
556
|
+
export function detectDuplicateClones(input = {}) {
|
|
557
|
+
const targetNorm = String(input.targetPath || '').replace(/\\/g, '/').replace(/^\.\//, '');
|
|
558
|
+
if (!targetNorm || isBucketBForbiddenSkuPath(targetNorm) || TEST_PATH_RE.test(targetNorm)) {
|
|
559
|
+
return { triggered: false, decision: 'allow', clones: [], tokensSavedEst: 0 };
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
const minMatchingShingles = Number(input.minMatchingShingles) || 2;
|
|
563
|
+
const candidateShingles = computeFileShingles(input.addedCode || '', 5);
|
|
564
|
+
if (candidateShingles.length < minMatchingShingles) {
|
|
565
|
+
return { triggered: false, decision: 'allow', clones: [], tokensSavedEst: 0 };
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
const index = input.shingleIndex || {};
|
|
569
|
+
const hitsByOtherFile = new Map();
|
|
570
|
+
|
|
571
|
+
for (const sh of candidateShingles) {
|
|
572
|
+
const postings = index[sh.hash];
|
|
573
|
+
if (!Array.isArray(postings)) continue;
|
|
574
|
+
for (const post of postings) {
|
|
575
|
+
if (!post || post.file === targetNorm || isBucketBForbiddenSkuPath(post.file)) continue;
|
|
576
|
+
const entry = hitsByOtherFile.get(post.file) || {
|
|
577
|
+
file: post.file,
|
|
578
|
+
matchedShingles: 0,
|
|
579
|
+
firstSourceLine: post.startLine,
|
|
580
|
+
firstCandidateLine: sh.startLine
|
|
581
|
+
};
|
|
582
|
+
entry.matchedShingles += 1;
|
|
583
|
+
hitsByOtherFile.set(post.file, entry);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
const clones = Array.from(hitsByOtherFile.values())
|
|
588
|
+
.filter((c) => c.matchedShingles >= minMatchingShingles)
|
|
589
|
+
.sort((a, b) => b.matchedShingles - a.matchedShingles);
|
|
590
|
+
|
|
591
|
+
if (clones.length === 0) {
|
|
592
|
+
return { triggered: false, decision: 'allow', clones: [], tokensSavedEst: 0 };
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
const top = clones[0];
|
|
596
|
+
return {
|
|
597
|
+
triggered: true,
|
|
598
|
+
decision: 'warn',
|
|
599
|
+
code: 'DUPLICATE_CLONE_DETECTOR',
|
|
600
|
+
clones,
|
|
601
|
+
tokensSavedEst: 650,
|
|
602
|
+
reason: `[Code Health Hint] Added logic block duplicates ${top.matchedShingles + 4}+ lines in \`${top.file}:${top.firstSourceLine}\` — consider reusing or extracting a shared helper.`
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// ============================================================================
|
|
607
|
+
// #3b TEST_INTEGRITY_LOCK (EvilGenie Hardcoded Input-Output Return Oracle)
|
|
608
|
+
// ============================================================================
|
|
609
|
+
|
|
610
|
+
const TRIVIAL_NUMERIC_LITERALS = new Set([
|
|
611
|
+
-1, 0, 1, 2, 3, 4, 8, 10, 16, 24, 32, 60, 64, 100, 128, 256, 512, 1000, 1024
|
|
612
|
+
]);
|
|
613
|
+
|
|
614
|
+
const HTTP_STATUS_CODES = new Set([
|
|
615
|
+
200, 201, 202, 204, 206, 301, 302, 304, 307, 308,
|
|
616
|
+
400, 401, 403, 404, 405, 408, 409, 410, 413, 422, 429,
|
|
617
|
+
500, 501, 502, 503, 504
|
|
618
|
+
]);
|
|
619
|
+
|
|
620
|
+
function isHttpStatusLiteral(num) {
|
|
621
|
+
return HTTP_STATUS_CODES.has(num);
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
function isDomainEnumOrTokenString(lit = '') {
|
|
625
|
+
const inner = lit.slice(1, -1);
|
|
626
|
+
if (inner.length <= 2) return true;
|
|
627
|
+
// Uppercase enum constants, CLI flags, MIME/path/glob tokens, JS keywords/types
|
|
628
|
+
if (/^[A-Z][A-Z0-9_:-]+$/.test(inner)) return true;
|
|
629
|
+
if (/^--?[a-z0-9-]+$/i.test(inner)) return true;
|
|
630
|
+
if (/^(?:string|number|boolean|object|function|symbol|undefined|bigint)$/.test(inner)) return true;
|
|
631
|
+
if (/^(?:allow|deny|warn|ask|defer|shadow|coach|enforce|true|false|null|ok|error|json|utf8|utf-8|win32|darwin|linux)$/i.test(inner)) {
|
|
632
|
+
return true;
|
|
633
|
+
}
|
|
634
|
+
if (/^[./\\]|\/|\.[a-z0-9]{1,6}$/i.test(inner)) return true;
|
|
635
|
+
if (/^[a-z]+(?:[-_:][a-z0-9]+)+$/i.test(inner) && !/\s/.test(inner) && !/[,[\]{}]/.test(inner)) {
|
|
636
|
+
return true;
|
|
637
|
+
}
|
|
638
|
+
return false;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
function isSpecificTestOracleCondition(cond = '') {
|
|
642
|
+
const c = cond.trim();
|
|
643
|
+
// Serialized container/tuple equality (`JSON.stringify(x) === '[...]'`)
|
|
644
|
+
if (/JSON\.stringify\s*\([^\x29]+\)\s*===?\s*['"`][\x5b\x7b]/.test(c)) return true;
|
|
645
|
+
|
|
646
|
+
// Require conjunctive `&&` multi-parameter check (`a === 17 && b === 42`), never disjunctive `||` enum aliases!
|
|
647
|
+
if (!c.includes('&&')) return false;
|
|
648
|
+
|
|
649
|
+
const isStatusContext = /\b(?:status|statusCode|httpStatus|code)\b/i.test(c);
|
|
650
|
+
const eqMatches = [
|
|
651
|
+
...c.matchAll(
|
|
652
|
+
/\b([A-Za-z_$][A-Za-z0-9_$.[\]]*)\s*===?\s*(-?\d+(?:\.\d+)?|'[^'\n]{1,80}'|"[^"\n]{1,80}")/g
|
|
653
|
+
)
|
|
654
|
+
];
|
|
655
|
+
if (eqMatches.length < 2) return false;
|
|
656
|
+
|
|
657
|
+
const lhsVars = new Set();
|
|
658
|
+
let magicLiterals = 0;
|
|
659
|
+
for (const m of eqMatches) {
|
|
660
|
+
lhsVars.add(m[1]);
|
|
661
|
+
const rhs = m[2];
|
|
662
|
+
if (/^-?\d/.test(rhs)) {
|
|
663
|
+
const n = Number(rhs);
|
|
664
|
+
if (!TRIVIAL_NUMERIC_LITERALS.has(n) && !(isStatusContext && isHttpStatusLiteral(n))) {
|
|
665
|
+
magicLiterals += 1;
|
|
666
|
+
}
|
|
667
|
+
} else if (!isDomainEnumOrTokenString(rhs)) {
|
|
668
|
+
magicLiterals += 1;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
return lhsVars.size >= 2 && magicLiterals >= 2;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
function isConcreteLiteralReturn(retExpr = '', cond = '') {
|
|
676
|
+
const r = retExpr.trim().replace(/;$/, '').trim();
|
|
677
|
+
if (!r || /^(?:true|false|null|undefined|0|1|-1|''|""|\[\]|\{\})$/.test(r)) return false;
|
|
678
|
+
if (/^-?\d+(?:\.\d+)?$/.test(r)) {
|
|
679
|
+
const n = Number(r);
|
|
680
|
+
const isStatusContext = /\b(?:status|statusCode|httpStatus|code)\b/i.test(cond);
|
|
681
|
+
return !(isStatusContext && isHttpStatusLiteral(n));
|
|
682
|
+
}
|
|
683
|
+
if (/^\[[\d\s,.'"truefalsn-]+\]$/.test(r)) return true;
|
|
684
|
+
if (/^(['"])(?:(?!\1).)+\1$/.test(r)) return !isDomainEnumOrTokenString(r);
|
|
685
|
+
return false;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/**
|
|
689
|
+
* Detects EvilGenie-style benchmark test-case hardcoding (`if (input === magic) return expectedLiteral`
|
|
690
|
+
* chains) in newly added non-test production source code.
|
|
691
|
+
*
|
|
692
|
+
* @param {object} input
|
|
693
|
+
* @param {string} [input.filePath='']
|
|
694
|
+
* @param {string} [input.addedCode='']
|
|
695
|
+
* @param {number} [input.minOracleBranches=3]
|
|
696
|
+
*/
|
|
697
|
+
export function evaluateHardcodedOracle(input = {}) {
|
|
698
|
+
const norm = String(input.filePath || '').replace(/\\/g, '/').replace(/^\.\//, '');
|
|
699
|
+
if (TEST_PATH_RE.test(norm) || isBucketBForbiddenSkuPath(norm)) {
|
|
700
|
+
return { triggered: false, decision: 'allow', oracleBranches: 0, samples: [] };
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
const minOracleBranches = Number(input.minOracleBranches) || 3;
|
|
704
|
+
const code = String(input.addedCode || '');
|
|
705
|
+
const lines = code.split(/\r?\n/);
|
|
706
|
+
const matchedEntries = [];
|
|
707
|
+
|
|
708
|
+
for (let i = 0; i < lines.length; i++) {
|
|
709
|
+
const line = lines[i].trim();
|
|
710
|
+
if (!line || line.startsWith('//') || line.startsWith('*')) continue;
|
|
711
|
+
|
|
712
|
+
const singleMatch = line.match(/^(?:else\s+)?if\s*\((.+)\)\s*\{?\s*return\s+([^;{}]+);?\s*\}?$/);
|
|
713
|
+
if (singleMatch) {
|
|
714
|
+
const [, cond, ret] = singleMatch;
|
|
715
|
+
if (isSpecificTestOracleCondition(cond) && isConcreteLiteralReturn(ret, cond)) {
|
|
716
|
+
matchedEntries.push({ lineNo: i, text: line.slice(0, 120) });
|
|
717
|
+
}
|
|
718
|
+
continue;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
const headMatch = line.match(/^(?:else\s+)?if\s*\((.+)\)\s*\x7b?$/);
|
|
722
|
+
if (headMatch && i + 1 < lines.length) {
|
|
723
|
+
const nextLine = lines[i + 1].trim();
|
|
724
|
+
const retMatch = nextLine.match(/^return\s+([^;{}]+);?$/);
|
|
725
|
+
if (
|
|
726
|
+
retMatch &&
|
|
727
|
+
isSpecificTestOracleCondition(headMatch[1]) &&
|
|
728
|
+
isConcreteLiteralReturn(retMatch[1], headMatch[1])
|
|
729
|
+
) {
|
|
730
|
+
matchedEntries.push({ lineNo: i, text: `${line} ${nextLine}`.slice(0, 120) });
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// Require >= minOracleBranches clustered within a 25-line function window
|
|
736
|
+
let clustered = [];
|
|
737
|
+
for (let i = 0; i < matchedEntries.length; i++) {
|
|
738
|
+
const windowItems = [matchedEntries[i]];
|
|
739
|
+
for (let j = i + 1; j < matchedEntries.length; j++) {
|
|
740
|
+
if (matchedEntries[j].lineNo - matchedEntries[i].lineNo <= 25) {
|
|
741
|
+
windowItems.push(matchedEntries[j]);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
if (windowItems.length > clustered.length) clustered = windowItems;
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
const samples = clustered.map((e) => e.text);
|
|
748
|
+
if (samples.length < minOracleBranches) {
|
|
749
|
+
return {
|
|
750
|
+
triggered: false,
|
|
751
|
+
decision: 'allow',
|
|
752
|
+
oracleBranches: samples.length,
|
|
753
|
+
samples
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
return {
|
|
758
|
+
triggered: true,
|
|
759
|
+
decision: 'warn',
|
|
760
|
+
code: 'EVILGENIE_HARDCODED_ORACLE',
|
|
761
|
+
oracleBranches: samples.length,
|
|
762
|
+
samples: samples.slice(0, 5),
|
|
763
|
+
tokensSavedEst: 1500,
|
|
764
|
+
reason: `[Test Integrity Shield] Detected ${samples.length} hardcoded input->literal return branches resembling benchmark test-case memorization. Implement general domain logic instead of special-casing test inputs.`
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
// ============================================================================
|
|
769
|
+
// #19 OVERENGINEERING_DIFF_GATE
|
|
770
|
+
// ============================================================================
|
|
771
|
+
|
|
772
|
+
const NARROW_BUGFIX_PROMPT_RE =
|
|
773
|
+
/\b(?:fix\s+(?:the\s+)?(?:typo|off-by-one|null|bug|crash|edge\s+case|regex|import)|one-line|small\s+tweak|minor\s+fix|hotfix)\b/i;
|
|
774
|
+
|
|
775
|
+
/**
|
|
776
|
+
* Scores diff proportionality (`nonTestAddedLines` vs. deleted lines + unused exported abstractions),
|
|
777
|
+
* strictly excluding `test/<suite>` and `*.test.*` lines from the bloat numerator so thorough test suites are never penalized.
|
|
778
|
+
*
|
|
779
|
+
* @param {object} input
|
|
780
|
+
* @param {Array<{ filePath: string, addedLines?: string[], deletedLineCount?: number }>} [input.fileDiffs=[]]
|
|
781
|
+
* @param {string} [input.lastUserPrompt='']
|
|
782
|
+
* @param {number} [input.maxBugfixAddedLines=180]
|
|
783
|
+
*/
|
|
784
|
+
export function evaluateOverengineeringDiffGate(input = {}) {
|
|
785
|
+
const diffs = Array.isArray(input.fileDiffs) ? input.fileDiffs : [];
|
|
786
|
+
const prompt = String(input.lastUserPrompt || '');
|
|
787
|
+
const maxBugfixAddedLines = Number(input.maxBugfixAddedLines) || 180;
|
|
788
|
+
|
|
789
|
+
let nonTestAddedLines = 0;
|
|
790
|
+
let testAddedLines = 0;
|
|
791
|
+
let nonTestDeletedLines = 0;
|
|
792
|
+
const exportedAbstractions = [];
|
|
793
|
+
const allAddedText = [];
|
|
794
|
+
|
|
795
|
+
for (const d of diffs) {
|
|
796
|
+
const norm = String(d.filePath || '').replace(/\\/g, '/').replace(/^\.\//, '');
|
|
797
|
+
if (!norm || isBucketBForbiddenSkuPath(norm)) continue;
|
|
798
|
+
const added = Array.isArray(d.addedLines) ? d.addedLines : [];
|
|
799
|
+
if (TEST_PATH_RE.test(norm)) {
|
|
800
|
+
testAddedLines += added.length;
|
|
801
|
+
continue;
|
|
802
|
+
}
|
|
803
|
+
if (/\.md$|\.json$/i.test(norm)) continue;
|
|
804
|
+
|
|
805
|
+
nonTestAddedLines += added.length;
|
|
806
|
+
nonTestDeletedLines += Math.max(0, Number(d.deletedLineCount) || 0);
|
|
807
|
+
|
|
808
|
+
for (const line of added) {
|
|
809
|
+
allAddedText.push(line);
|
|
810
|
+
const clsMatch = line.match(
|
|
811
|
+
/^\s*export\s+(?:abstract\s+)?(?:class|interface)\s+([A-Za-z0-9_]+(?:Factory|Builder|Manager|Strategy|Provider|Registry|Orchestrator|Adapter))\b/
|
|
812
|
+
);
|
|
813
|
+
if (clsMatch) {
|
|
814
|
+
exportedAbstractions.push(clsMatch[1]);
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
const joinedCorpus = allAddedText.join('\n');
|
|
820
|
+
let unusedExportedAbstractions = 0;
|
|
821
|
+
for (const sym of exportedAbstractions) {
|
|
822
|
+
const matches = joinedCorpus.match(new RegExp(`\\b${sym}\\b`, 'g')) || [];
|
|
823
|
+
// Only the declaration occurrence itself (`matches.length <= 1`)
|
|
824
|
+
if (matches.length <= 1) unusedExportedAbstractions += 1;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
const isNarrowBugfix =
|
|
828
|
+
NARROW_BUGFIX_PROMPT_RE.test(prompt) ||
|
|
829
|
+
(nonTestDeletedLines > 0 && nonTestDeletedLines <= 12 && !GREENFIELD_SCAFFOLD_PROMPT_RE.test(prompt));
|
|
830
|
+
|
|
831
|
+
const addDeleteRatio = nonTestAddedLines / Math.max(1, nonTestDeletedLines);
|
|
832
|
+
const bloatedBugfix =
|
|
833
|
+
isNarrowBugfix &&
|
|
834
|
+
nonTestAddedLines > maxBugfixAddedLines &&
|
|
835
|
+
(unusedExportedAbstractions >= 1 || addDeleteRatio > 18);
|
|
836
|
+
const deadAbstractionBloat =
|
|
837
|
+
nonTestAddedLines > 140 && unusedExportedAbstractions >= 2;
|
|
838
|
+
|
|
839
|
+
if (!bloatedBugfix && !deadAbstractionBloat) {
|
|
840
|
+
return {
|
|
841
|
+
triggered: false,
|
|
842
|
+
decision: 'allow',
|
|
843
|
+
nonTestAddedLines,
|
|
844
|
+
testAddedLines,
|
|
845
|
+
unusedExportedAbstractions,
|
|
846
|
+
tokensSavedEst: 0
|
|
847
|
+
};
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
return {
|
|
851
|
+
triggered: true,
|
|
852
|
+
decision: 'warn',
|
|
853
|
+
code: 'OVERENGINEERING_DIFF_GATE',
|
|
854
|
+
nonTestAddedLines,
|
|
855
|
+
testAddedLines,
|
|
856
|
+
unusedExportedAbstractions,
|
|
857
|
+
tokensSavedEst: 950,
|
|
858
|
+
reason: `[Code Health Hint] Diff adds ${nonTestAddedLines} non-test production lines (test lines excluded: ${testAddedLines}) with ${unusedExportedAbstractions} unreferenced exported abstraction(s). Prefer minimal direct fixes over speculative wrapper classes.`
|
|
859
|
+
};
|
|
860
|
+
}
|