ctxtop 0.0.0-stage → 4.0.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 +36 -0
- package/.claude-plugin/plugin.json +18 -0
- package/CHECKSUMS.sha256 +149 -0
- package/LICENSE +27 -0
- package/README.md +330 -3
- package/SECURITY.md +22 -0
- package/agents/ah-flash-scout.md +25 -0
- package/assets/advanced_view_loaded_420px.png +0 -0
- package/assets/hero-demo.svg +188 -0
- package/assets/logo.svg +19 -0
- package/assets/simple_view_lean_420px.png +0 -0
- package/assets/simple_view_loaded_420px.png +0 -0
- package/assets/social-preview.svg +72 -0
- package/assets/zone_c_step3_shield_full.png +0 -0
- package/bin/ah-statusline.mjs +145 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1474 -0
- package/commands/cost-radar.md +11 -0
- package/commands/evolve.md +10 -0
- package/commands/handoff.md +10 -0
- package/commands/horizon.md +10 -0
- package/commands/inspect.md +10 -0
- package/commands/precheck.md +10 -0
- package/config/default_flightcheck.json +114 -0
- package/config/modelCatalog.json +620 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +262 -0
- package/hooks/handlers/hookIo.mjs +255 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-tool-use.mjs +265 -0
- package/hooks/handlers/pre-model-switch.mjs +249 -0
- package/hooks/handlers/pre-tool-use.mjs +365 -0
- package/hooks/handlers/stop-gate.mjs +240 -0
- package/hooks/handlers/user-prompt-submit.mjs +143 -0
- package/hooks/hooks.json +81 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +17 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +687 -0
- package/hooks/session_start.mjs +14 -0
- package/hooks/stop.mjs +13 -0
- package/hooks.json +56 -0
- package/package.json +103 -4
- package/packages/antigravity/package.json +14 -0
- package/packages/antigravity/src/index.mjs +1 -0
- package/packages/claude-code/package.json +14 -0
- package/packages/claude-code/src/index.mjs +2 -0
- package/packages/core/package.json +14 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/engine-node/package.json +14 -0
- package/packages/engine-node/src/index.mjs +1 -0
- package/packages/mcp/package.json +17 -0
- package/packages/mcp/src/server.mjs +396 -0
- package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
- package/packages/pro/README-SIGNING.md +30 -0
- package/packages/pro/package.json +16 -0
- package/packages/pro/src/index.mjs +3 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -0
- package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
- package/plugin.json +36 -0
- package/rules/AGENTS.md +10 -0
- package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
- package/sidecars/horizon-daemon/server.mjs +2002 -0
- package/sidecars/horizon-daemon/sidecar.json +19 -0
- package/skills/cost-radar/SKILL.md +21 -0
- package/skills/evolve/SKILL.md +21 -0
- package/skills/handoff/SKILL.md +42 -0
- package/skills/horizon/SKILL.md +17 -0
- package/skills/inspect/SKILL.md +18 -0
- package/skills/precheck/SKILL.md +44 -0
- package/src/adapters/antigravity/index.mjs +79 -0
- package/src/adapters/claude-code/index.mjs +155 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +686 -0
- package/src/cli/init.mjs +425 -0
- package/src/cli/postmortem.mjs +515 -0
- package/src/coach/cacheGravityRouter.mjs +12 -0
- package/src/config/modelCatalog.json +620 -0
- package/src/config/platformQuirks.json +19 -0
- package/src/core/action_queue.mjs +264 -0
- package/src/core/ag_bridge.mjs +346 -0
- package/src/core/atomic_io.mjs +124 -0
- package/src/core/baseline.mjs +607 -0
- package/src/core/blindspot_sensors.mjs +399 -0
- package/src/core/classifier.mjs +1757 -0
- package/src/core/coach/circuit_breakers.mjs +650 -0
- package/src/core/coach/contradiction_auditor.mjs +239 -0
- package/src/core/coach/effort_advisor.mjs +143 -0
- package/src/core/coach/handoff_hydrator.mjs +483 -0
- package/src/core/coach/progressive_checkpointer.mjs +551 -0
- package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
- package/src/core/coach/reflector_queue.mjs +505 -0
- package/src/core/coach/saved_quota_ledger.mjs +615 -0
- package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
- package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
- package/src/core/coach/task_quota_router.mjs +955 -0
- package/src/core/coach/turn_zero_gate.mjs +574 -0
- package/src/core/compaction_coach.mjs +1126 -0
- package/src/core/config.mjs +214 -0
- package/src/core/constants.mjs +1800 -0
- package/src/core/detectors_det01_to_16.mjs +1474 -0
- package/src/core/episodic_memory.mjs +135 -0
- package/src/core/fts5_output_compressor.mjs +359 -0
- package/src/core/git_ledger.mjs +189 -0
- package/src/core/handoff_audit.mjs +558 -0
- package/src/core/history.mjs +221 -0
- package/src/core/hook_diagnostics.mjs +158 -0
- package/src/core/horizon_classifier.mjs +326 -0
- package/src/core/horizon_config.mjs +802 -0
- package/src/core/host_watchdog.mjs +200 -0
- package/src/core/layer5_hygiene.mjs +966 -0
- package/src/core/log_resolver.mjs +231 -0
- package/src/core/mcp_auditor.mjs +138 -0
- package/src/core/micro_skills_store.mjs +91 -0
- package/src/core/offenders.mjs +161 -0
- package/src/core/parser.mjs +1996 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +310 -0
- package/src/core/prefix_cache_shield.mjs +386 -0
- package/src/core/pro_license.mjs +385 -0
- package/src/core/prompt_rubric.mjs +518 -0
- package/src/core/pruner.mjs +433 -0
- package/src/core/quota.mjs +1860 -0
- package/src/core/rsi_instinct_engine.mjs +1197 -0
- package/src/core/sanitizer.mjs +121 -0
- package/src/core/session_forensics.mjs +303 -0
- package/src/core/session_timeline.mjs +358 -0
- package/src/core/settings.mjs +99 -0
- package/src/core/shared/detectors.mjs +1342 -0
- package/src/core/shared/fnv1a64.mjs +85 -0
- package/src/core/shared/handoff_schema.mjs +123 -0
- package/src/core/shared/index.mjs +5 -0
- package/src/core/shared/ipi_sanitizer.mjs +165 -0
- package/src/core/shared/micro_skills.mjs +1 -0
- package/src/core/shared/plugin_validator.mjs +202 -0
- package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
- package/src/core/sidecar_store.mjs +302 -0
- package/src/core/sprint_metrics.mjs +366 -0
- package/src/core/sqlite_client.mjs +283 -0
- package/src/core/storage_doctor.mjs +358 -0
- package/src/core/subagents.mjs +609 -0
- package/src/core/swarm_topology.mjs +360 -0
- package/src/core/task_quota_router.mjs +1656 -0
- package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
- package/src/core/telemetry/scope_lock_registry.mjs +578 -0
- package/src/core/telemetry/shadow_file_detector.mjs +291 -0
- package/src/core/telemetry/trajectory_watcher.mjs +259 -0
- package/src/core/timeline_svg.mjs +236 -0
- package/src/core/tool_surgeon.mjs +305 -0
- package/src/core/trajectory_stitcher.mjs +645 -0
- package/src/core/u_shaped_optimizer.mjs +789 -0
- package/src/core/wal_hygiene.mjs +233 -0
- package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/src/core-isomorphic/catalog/index.mjs +1 -0
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
- package/src/core-isomorphic/coach/microSkills.mjs +1 -0
- package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
- package/src/core-isomorphic/control/callTree.mjs +338 -0
- package/src/core-isomorphic/control/coachLatches.mjs +126 -0
- package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/src/core-isomorphic/control/index.mjs +49 -0
- package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/src/core-isomorphic/diagnostics/index.mjs +9 -0
- package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
- package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/src/core-isomorphic/economics/index.mjs +47 -0
- package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
- package/src/core-isomorphic/index.js +26 -0
- package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
- package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
- package/src/core-isomorphic/ui/modViews.mjs +1478 -0
- package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/src/core-isomorphic/ustf/index.mjs +7 -0
- package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/src/core-isomorphic/ustf/schema.mjs +186 -0
- package/src/core-isomorphic/utils/runtime.mjs +962 -0
- package/src/demo/synthetic_states.mjs +661 -0
- package/src/diagnostics/bugReportGenerator.mjs +253 -0
- package/src/diagnostics/doctorEngine.mjs +203 -0
- package/src/engine-node/db/index.mjs +58 -0
- package/src/engine-node/db/jsonl_fallback.mjs +184 -0
- package/src/engine-node/db/probe.mjs +110 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +9 -0
- package/src/engine-node/ipc/client.mjs +447 -0
- package/src/engine-node/ipc/index.mjs +22 -0
- package/src/engine-node/ipc/protocol.mjs +177 -0
- package/src/engine-node/ipc/server.mjs +445 -0
- package/src/engine-node/offloader/index.mjs +6 -0
- package/src/engine-node/offloader/tool_offloader.mjs +241 -0
- package/src/engine-node/sensors/blindspots.mjs +369 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +419 -0
- package/src/hooks/pre_invocation.mjs +1015 -0
- package/src/hooks/session_start.mjs +161 -0
- package/src/shims/agy_cli_compressor.mjs +705 -0
- package/src/shims/agy_git_guard.mjs +749 -0
- package/src/shims/ah_log_query.mjs +39 -0
- package/src/ui/costRadarSvg.mjs +6 -0
- package/src/ui/horizonGrid.mjs +1 -0
- package/src/ui/horizonPanelHtml.mjs +1 -0
- package/src/ui/horizon_panel.css +167 -0
- package/src/ui/horizon_panel.js +212 -0
- package/src/ui/modViews.mjs +1 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +11389 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core-isomorphic/guards/det04_12_thrash_rot.mjs
|
|
3
|
+
* Consecutive Failures, Diff Thrashing, Blind Search, Output Bomb, and Rot/Cliff Breakers (`DET-04`..`DET-12`).
|
|
4
|
+
* Pure-V8 isomorphic ESM module (zero `node:*` imports).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { path, sha256Hex } from '../utils/runtime.mjs';
|
|
8
|
+
import { normalizeModelId, computeTotalPromptTokens } from '../config/catalogLoader.mjs';
|
|
9
|
+
import { SHELL_TOOL_REGEX } from './det01_03_shell_secret.mjs';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* DET-04: Consecutive Tool Failure Breaker (`>= 3` failures -> block 4th + strategy reset).
|
|
13
|
+
*
|
|
14
|
+
* @param {object} [params={}]
|
|
15
|
+
* @param {number} [params.consecutiveFailures=0]
|
|
16
|
+
* @param {number} [params.threshold=3]
|
|
17
|
+
*/
|
|
18
|
+
export function evaluateDet04ConsecutiveFailures(params = {}) {
|
|
19
|
+
const count = Math.max(0, Number(params.consecutiveFailures || 0));
|
|
20
|
+
const threshold = Math.max(1, Number(params.threshold ?? 3));
|
|
21
|
+
|
|
22
|
+
if (count >= threshold) {
|
|
23
|
+
return {
|
|
24
|
+
detectorId: 'DET-04',
|
|
25
|
+
triggered: true,
|
|
26
|
+
decision: 'deny',
|
|
27
|
+
consecutiveFailures: count,
|
|
28
|
+
reason: `[DET-04 Consecutive Failure Breaker] ${count} consecutive tool failures detected. Halting 4th attempt to prevent retry churn; re-verify assumptions or escalate reasoning effort.`
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return {
|
|
33
|
+
detectorId: 'DET-04',
|
|
34
|
+
triggered: false,
|
|
35
|
+
decision: 'allow',
|
|
36
|
+
consecutiveFailures: count,
|
|
37
|
+
reason: null
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Computes added and deleted lines between `oldText` and `newText` without scanning unchanged lines.
|
|
43
|
+
* @param {string} oldText
|
|
44
|
+
* @param {string} newText
|
|
45
|
+
* @returns {{ addedLines: Array<string>, deletedLines: Array<string>, oldLineCount: number, newLineCount: number }}
|
|
46
|
+
*/
|
|
47
|
+
export function computeAddedAndDeletedDiffLines(oldText = '', newText = '') {
|
|
48
|
+
const oldLines = oldText ? String(oldText).split(/\r?\n/) : [];
|
|
49
|
+
const newLines = newText ? String(newText).split(/\r?\n/) : [];
|
|
50
|
+
|
|
51
|
+
const oldCounts = new Map();
|
|
52
|
+
for (const line of oldLines) {
|
|
53
|
+
oldCounts.set(line, (oldCounts.get(line) || 0) + 1);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const newCounts = new Map();
|
|
57
|
+
for (const line of newLines) {
|
|
58
|
+
newCounts.set(line, (newCounts.get(line) || 0) + 1);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const addedLines = [];
|
|
62
|
+
for (const [line, count] of newCounts.entries()) {
|
|
63
|
+
const prev = oldCounts.get(line) || 0;
|
|
64
|
+
for (let i = 0; i < count - prev; i++) {
|
|
65
|
+
addedLines.push(line);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const deletedLines = [];
|
|
70
|
+
for (const [line, count] of oldCounts.entries()) {
|
|
71
|
+
const next = newCounts.get(line) || 0;
|
|
72
|
+
for (let i = 0; i < count - next; i++) {
|
|
73
|
+
deletedLines.push(line);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
addedLines,
|
|
79
|
+
deletedLines,
|
|
80
|
+
oldLineCount: oldLines.length,
|
|
81
|
+
newLineCount: newLines.length
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Computes a fast deterministic hash of content for `A -> B -> A` oscillation tracking.
|
|
87
|
+
* @param {string} content
|
|
88
|
+
* @returns {string}
|
|
89
|
+
*/
|
|
90
|
+
export function hashFileContent(content = '') {
|
|
91
|
+
return sha256Hex(String(content ?? '')).slice(0, 16);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* DET-05: AST/Diff Edit Thrashing & Destructive Code Stripping Breaker.
|
|
96
|
+
* Scans ONLY newly added/deleted diff lines (never pre-existing unchanged file lines),
|
|
97
|
+
* checks `A -> B -> A` file hash oscillation, `> 50%` sudden file shrinkage, and stripped assertions.
|
|
98
|
+
* Never invokes destructive `git checkout -- <file>`.
|
|
99
|
+
*
|
|
100
|
+
* @param {object} [params={}]
|
|
101
|
+
* @param {string} [params.filePath='']
|
|
102
|
+
* @param {string} [params.oldText='']
|
|
103
|
+
* @param {string} [params.newText='']
|
|
104
|
+
* @param {number} [params.fullFileOldLines]
|
|
105
|
+
* @param {number} [params.fullFileNewLines]
|
|
106
|
+
* @param {Array<string>} [params.hashHistory=[]] - Previous content hashes for this file
|
|
107
|
+
*/
|
|
108
|
+
export function evaluateDet05DiffThrashing(params = {}) {
|
|
109
|
+
const oldText = String(params.oldText ?? '');
|
|
110
|
+
const newText = String(params.newText ?? '');
|
|
111
|
+
const { addedLines, deletedLines, oldLineCount, newLineCount } =
|
|
112
|
+
computeAddedAndDeletedDiffLines(oldText, newText);
|
|
113
|
+
|
|
114
|
+
const effectiveOldLines = Number(params.fullFileOldLines ?? oldLineCount);
|
|
115
|
+
const effectiveNewLines = Number(params.fullFileNewLines ?? newLineCount);
|
|
116
|
+
const nextHash = hashFileContent(params.fullNewContent ?? newText);
|
|
117
|
+
|
|
118
|
+
// 0. Check lazy elision comment placeholders (// ... existing code ...)
|
|
119
|
+
const LAZY_ELISION_REGEX = /(?:\/\/|#|--|\/\*)\s*(?:\.\.\.|…)?\s*(?:existing|rest of|remaining|unchanged)\s+(?:code|implementation|file|methods|lines)\b/i;
|
|
120
|
+
if (LAZY_ELISION_REGEX.test(newText)) {
|
|
121
|
+
return {
|
|
122
|
+
detectorId: 'DET-05',
|
|
123
|
+
triggered: true,
|
|
124
|
+
decision: 'deny',
|
|
125
|
+
subType: 'LAZY_ELISION_PLACEHOLDER',
|
|
126
|
+
nextHash,
|
|
127
|
+
reason: `[DET-05 Destructive Code-Stripping] Diff inserts lazy placeholder comments ("// ... existing code ...") deleting implemented logic. Write the complete surgical replacement.`
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// 1. Check `A -> B -> A` hash oscillation
|
|
132
|
+
const hashHistory = Array.isArray(params.hashHistory) ? params.hashHistory : [];
|
|
133
|
+
const oscillationDetected =
|
|
134
|
+
hashHistory.length >= 2 &&
|
|
135
|
+
hashHistory[hashHistory.length - 2] === nextHash &&
|
|
136
|
+
hashHistory[hashHistory.length - 1] !== nextHash;
|
|
137
|
+
|
|
138
|
+
if (oscillationDetected) {
|
|
139
|
+
return {
|
|
140
|
+
detectorId: 'DET-05',
|
|
141
|
+
triggered: true,
|
|
142
|
+
decision: 'deny',
|
|
143
|
+
subType: 'HASH_OSCILLATION_ABA',
|
|
144
|
+
nextHash,
|
|
145
|
+
addedLinesCount: addedLines.length,
|
|
146
|
+
deletedLinesCount: deletedLines.length,
|
|
147
|
+
reason: `[DET-05 Edit Thrashing Breaker] A -> B -> A file hash oscillation detected on "${params.filePath || 'file'}". Stop reverting and re-evaluate root cause.`
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// 2. Check > 50% sudden file shrinkage (when original has >= 12 lines)
|
|
152
|
+
if (effectiveOldLines >= 12 && effectiveNewLines < effectiveOldLines * 0.5) {
|
|
153
|
+
return {
|
|
154
|
+
detectorId: 'DET-05',
|
|
155
|
+
triggered: true,
|
|
156
|
+
decision: 'deny',
|
|
157
|
+
subType: 'SUDDEN_FILE_SHRINKAGE',
|
|
158
|
+
nextHash,
|
|
159
|
+
oldLineCount: effectiveOldLines,
|
|
160
|
+
newLineCount: effectiveNewLines,
|
|
161
|
+
reason: `[DET-05 Destructive Shrinkage Breaker] Edit shrinks "${params.filePath || 'file'}" from ${effectiveOldLines} lines to ${effectiveNewLines} lines (>50% reduction).`
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// 2b. Full-File Regurgitation Check (>=300 lines with >=90% unchanged lines on Write)
|
|
166
|
+
const isFullWrite = String(params.toolName || '').toLowerCase() === 'write' || Boolean(params.isFullWrite);
|
|
167
|
+
if (isFullWrite && effectiveOldLines >= 300 && effectiveNewLines >= Math.floor(effectiveOldLines * 0.9)) {
|
|
168
|
+
const oldLinesArr = oldText.split(/\r?\n/);
|
|
169
|
+
const newLinesArr = newText.split(/\r?\n/);
|
|
170
|
+
const beforeMap = new Map();
|
|
171
|
+
for (const line of oldLinesArr) {
|
|
172
|
+
const trimmed = line.trim();
|
|
173
|
+
beforeMap.set(trimmed, (beforeMap.get(trimmed) || 0) + 1);
|
|
174
|
+
}
|
|
175
|
+
let unchangedCount = 0;
|
|
176
|
+
for (const line of newLinesArr) {
|
|
177
|
+
const trimmed = line.trim();
|
|
178
|
+
const count = beforeMap.get(trimmed) || 0;
|
|
179
|
+
if (count > 0) {
|
|
180
|
+
unchangedCount++;
|
|
181
|
+
beforeMap.set(trimmed, count - 1);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
const changedCount = effectiveOldLines - unchangedCount;
|
|
185
|
+
if (unchangedCount / effectiveOldLines >= 0.90 && changedCount <= Math.max(25, Math.floor(effectiveOldLines * 0.10))) {
|
|
186
|
+
const flightMode = String(params.flightMode || 'COACH').toUpperCase();
|
|
187
|
+
return {
|
|
188
|
+
detectorId: 'DET-05',
|
|
189
|
+
triggered: true,
|
|
190
|
+
decision: flightMode === 'AUTO_PILOT' ? 'ask' : 'allow',
|
|
191
|
+
advisory: flightMode !== 'AUTO_PILOT',
|
|
192
|
+
subType: 'FULL_FILE_REGURGITATION',
|
|
193
|
+
nextHash,
|
|
194
|
+
oldLineCount: effectiveOldLines,
|
|
195
|
+
newLineCount: effectiveNewLines,
|
|
196
|
+
reason: `[DET-05 Full-File Regurgitation] Writing entire ${effectiveOldLines}-line file with ${unchangedCount} lines (${Math.round((unchangedCount / effectiveOldLines) * 100)}%) unchanged. Use surgical Edit instead.`
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// 3. Scan ONLY deleted and added diff lines for test-assertion stripping / error masking
|
|
202
|
+
const assertionRegex = /\b(?:assert\.[a-zA-Z]+|expect\s*\(|should\.)/;
|
|
203
|
+
const trivialTautologyRegex =
|
|
204
|
+
/\b(?:assert\.ok\s*\(\s*true\s*\)|assert\.(?:strictEqual|equal)\s*\(\s*true\s*,\s*true\s*\)|expect\s*\(\s*true\s*\)\s*\.toBe\s*\(\s*true\s*\))/;
|
|
205
|
+
const deletedAssertions = deletedLines.filter(
|
|
206
|
+
(l) => assertionRegex.test(l) && !trivialTautologyRegex.test(l)
|
|
207
|
+
);
|
|
208
|
+
const addedAssertions = addedLines.filter(
|
|
209
|
+
(l) => assertionRegex.test(l) && !trivialTautologyRegex.test(l)
|
|
210
|
+
);
|
|
211
|
+
|
|
212
|
+
const errorMaskingRegex =
|
|
213
|
+
/(?:catch\s*(?:\([^)]*\))?\s*\{\s*\}|@ts-ignore|@ts-nocheck|eslint-disable)/;
|
|
214
|
+
const addedErrorMasking = addedLines.filter((l) => errorMaskingRegex.test(l));
|
|
215
|
+
|
|
216
|
+
if (deletedAssertions.length >= 2 && addedAssertions.length === 0) {
|
|
217
|
+
return {
|
|
218
|
+
detectorId: 'DET-05',
|
|
219
|
+
triggered: true,
|
|
220
|
+
decision: 'deny',
|
|
221
|
+
subType: 'TEST_ASSERTION_STRIPPING',
|
|
222
|
+
nextHash,
|
|
223
|
+
deletedAssertionsCount: deletedAssertions.length,
|
|
224
|
+
reason: `[DET-05 Test Stripping Breaker] Diff deletes ${deletedAssertions.length} test assertions without replacement.`
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (addedErrorMasking.length > 0 && deletedLines.length > addedLines.length && deletedAssertions.length > 0) {
|
|
229
|
+
return {
|
|
230
|
+
detectorId: 'DET-05',
|
|
231
|
+
triggered: true,
|
|
232
|
+
decision: 'deny',
|
|
233
|
+
subType: 'ERROR_MASKING_DIFF',
|
|
234
|
+
nextHash,
|
|
235
|
+
reason: `[DET-05 Error Masking Breaker] Newly added diff lines introduce empty catch / lint suppression while deleting verification checks.`
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
return {
|
|
240
|
+
detectorId: 'DET-05',
|
|
241
|
+
triggered: false,
|
|
242
|
+
decision: 'allow',
|
|
243
|
+
subType: null,
|
|
244
|
+
nextHash,
|
|
245
|
+
addedLinesCount: addedLines.length,
|
|
246
|
+
deletedLinesCount: deletedLines.length,
|
|
247
|
+
reason: null
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* DET-06: Main-Thread Blind Search Guard (`> 6` sequential `Read`/`Grep`/`Glob` calls -> nudge `Explore` subagent).
|
|
253
|
+
*
|
|
254
|
+
* @param {object} [params={}]
|
|
255
|
+
* @param {number} [params.sequentialSearchCount=0]
|
|
256
|
+
* @param {number} [params.threshold=6]
|
|
257
|
+
* @param {number} [params.limit]
|
|
258
|
+
*/
|
|
259
|
+
export function evaluateDet06BlindSearchGuard(params = {}) {
|
|
260
|
+
const count = Math.max(0, Number(params.sequentialSearchCount || 0));
|
|
261
|
+
const rawThreshold = params.threshold ?? params.limit ?? 6;
|
|
262
|
+
const threshold = Math.max(1, Number(rawThreshold));
|
|
263
|
+
|
|
264
|
+
if (count > threshold) {
|
|
265
|
+
return {
|
|
266
|
+
detectorId: 'DET-06',
|
|
267
|
+
triggered: true,
|
|
268
|
+
decision: 'advise_subagent',
|
|
269
|
+
advisory: true,
|
|
270
|
+
sequentialSearchCount: count,
|
|
271
|
+
threshold,
|
|
272
|
+
recommendedSubagent: {
|
|
273
|
+
agentType: 'Explore',
|
|
274
|
+
model: 'claude-haiku-5-5'
|
|
275
|
+
},
|
|
276
|
+
reason: `[DET-06 Blind Search Guard] ${count} sequential Read/Grep calls on the main thread (> ${threshold}). Delegate open-ended codebase exploration to an Explore subagent on claude-haiku-5-5 to prevent main-window distractor bloat.`
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
return {
|
|
281
|
+
detectorId: 'DET-06',
|
|
282
|
+
triggered: false,
|
|
283
|
+
decision: 'allow',
|
|
284
|
+
sequentialSearchCount: count,
|
|
285
|
+
threshold,
|
|
286
|
+
reason: null
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* DET-07: Unbounded Command Output Bomb Guard (`git log` without limit, unpaged `cat` on huge logs/lockfiles).
|
|
292
|
+
*
|
|
293
|
+
* @param {object} [params={}]
|
|
294
|
+
* @param {string} [params.toolName='Bash']
|
|
295
|
+
* @param {string} [params.command='']
|
|
296
|
+
*/
|
|
297
|
+
export function evaluateDet07OutputBombGuard(params = {}) {
|
|
298
|
+
const toolName = String(params.toolName || 'Bash');
|
|
299
|
+
const filePath = String(params.filePath || params.path || params.targetPath || '');
|
|
300
|
+
const limit = params.limit != null ? Number(params.limit) : null;
|
|
301
|
+
|
|
302
|
+
// Native Read / read_file check on lockfiles and minified bundles
|
|
303
|
+
if (/^(read|read_file|view_file)$/i.test(toolName) && filePath) {
|
|
304
|
+
const norm = filePath.replace(/\\/g, '/');
|
|
305
|
+
const isLockfileOrBundle =
|
|
306
|
+
/(?:^|\/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|poetry\.lock|composer\.lock)$/i.test(norm) ||
|
|
307
|
+
/\.(?:min\.js|bundle\.min\.js|bundle\.js|min\.css|map)$/i.test(norm) ||
|
|
308
|
+
/(?:^|\/)(dist|build|\.next|out)\/.*\.(?:js|json|css)$/i.test(norm);
|
|
309
|
+
if (isLockfileOrBundle) {
|
|
310
|
+
const isBounded = limit != null && limit > 0 && limit <= 100;
|
|
311
|
+
if (!isBounded) {
|
|
312
|
+
const base = norm.split('/').pop() || 'lockfile';
|
|
313
|
+
return {
|
|
314
|
+
detectorId: 'DET-07',
|
|
315
|
+
triggered: true,
|
|
316
|
+
decision: 'deny',
|
|
317
|
+
subType: 'LOCKFILE_OR_BUNDLE_READ_BLOCKED',
|
|
318
|
+
reason: `[DET-07 Unbounded Output Bomb Guard] Unbounded native Read on "${base}". Dumping full lockfile/bundle wastes context. Inspect package.json or specify line limits <= 100.`
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
if (!SHELL_TOOL_REGEX.test(toolName)) {
|
|
325
|
+
return { detectorId: 'DET-07', triggered: false, decision: 'allow', reason: null };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const command = String(params.command || '').trim();
|
|
329
|
+
if (!command) {
|
|
330
|
+
return { detectorId: 'DET-07', triggered: false, decision: 'allow', reason: null };
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// Unbounded `git log` without `-n`, `--max-count`, `-<number>`, `head`, or `Select-Object`
|
|
334
|
+
if (
|
|
335
|
+
/\bgit\s+log\b/i.test(command) &&
|
|
336
|
+
!/(?:\s-[n]\s*\d+|\s-\d+\b|--max-count|--oneline\s+-\d+|\|\s*(?:head|tail|Select-Object))/i.test(
|
|
337
|
+
command
|
|
338
|
+
)
|
|
339
|
+
) {
|
|
340
|
+
return {
|
|
341
|
+
detectorId: 'DET-07',
|
|
342
|
+
triggered: true,
|
|
343
|
+
decision: 'deny',
|
|
344
|
+
subType: 'UNBOUNDED_GIT_LOG',
|
|
345
|
+
reason: `[DET-07 Unbounded Output Bomb Guard] Unbounded "git log" can flood the context window. Add "-n 20" or "--max-count=20".`
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// Unpaged `cat` or `Get-Content` on massive lockfiles or `.jsonl` transcripts
|
|
350
|
+
if (
|
|
351
|
+
/\b(?:cat|Get-Content|type)\s+\S*(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|\.jsonl)\b/i.test(
|
|
352
|
+
command
|
|
353
|
+
) &&
|
|
354
|
+
!/(?:\|\s*(?:head|tail|Select-Object)|-TotalCount\s+\d+|-Tail\s+\d+)/i.test(command)
|
|
355
|
+
) {
|
|
356
|
+
return {
|
|
357
|
+
detectorId: 'DET-07',
|
|
358
|
+
triggered: true,
|
|
359
|
+
decision: 'deny',
|
|
360
|
+
subType: 'UNPAGED_LARGE_FILE_DUMP',
|
|
361
|
+
reason: `[DET-07 Unbounded Output Bomb Guard] Dumping entire lockfiles or JSONL transcripts without line limits floods the KV cache. Use head/tail or Grep.`
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
return { detectorId: 'DET-07', triggered: false, decision: 'allow', reason: null };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* DET-11: Context Rot Soft Horizon Gate (`> 60k` tokens and middle distractor ratio `[D] > 35%`).
|
|
370
|
+
*
|
|
371
|
+
* @param {object} [params={}]
|
|
372
|
+
* @param {number} [params.totalInputTokens=0]
|
|
373
|
+
* @param {number} [params.distractorTokens=0]
|
|
374
|
+
* @param {number} [params.distractorRatio]
|
|
375
|
+
*/
|
|
376
|
+
export function evaluateDet11ContextRotGate(params = {}) {
|
|
377
|
+
const totalInputTokens = Math.max(
|
|
378
|
+
0,
|
|
379
|
+
Number(params.totalInputTokens ?? params.totalPromptTokens ?? 0)
|
|
380
|
+
);
|
|
381
|
+
let distractorTokens = 0;
|
|
382
|
+
let distractorRatio = 0;
|
|
383
|
+
|
|
384
|
+
if (params.distractorTokens !== undefined && params.distractorTokens !== null) {
|
|
385
|
+
distractorTokens = Math.max(0, Number(params.distractorTokens || 0));
|
|
386
|
+
distractorRatio =
|
|
387
|
+
totalInputTokens > 0 ? Number((distractorTokens / totalInputTokens).toFixed(4)) : 0;
|
|
388
|
+
} else if (params.distractorRatio !== undefined && params.distractorRatio !== null) {
|
|
389
|
+
const rawRatio = Math.max(0, Number(params.distractorRatio || 0));
|
|
390
|
+
distractorRatio = Number((rawRatio > 1 ? rawRatio / 100 : rawRatio).toFixed(4));
|
|
391
|
+
distractorTokens = Math.round(totalInputTokens * distractorRatio);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// Sim 05: Post-commit topic shift check
|
|
395
|
+
const lastTurnGitCommitted = Boolean(params.lastTurnGitCommitted ?? params.last_turn_git_committed);
|
|
396
|
+
const topicShiftDetected = Boolean(params.topicShiftDetected ?? params.topic_shift ?? params.topicShift);
|
|
397
|
+
const turnId = Number(params.turnId ?? params.currentTurn ?? 0);
|
|
398
|
+
const postCommitTopicShift = Boolean(
|
|
399
|
+
params.postCommitTopicShift ??
|
|
400
|
+
(lastTurnGitCommitted && topicShiftDetected && (turnId === 0 || turnId >= 15) && totalInputTokens >= 25_000)
|
|
401
|
+
);
|
|
402
|
+
|
|
403
|
+
if (postCommitTopicShift) {
|
|
404
|
+
return {
|
|
405
|
+
detectorId: 'DET-11',
|
|
406
|
+
triggered: true,
|
|
407
|
+
decision: 'advise_compact',
|
|
408
|
+
advisory: true,
|
|
409
|
+
subType: 'POST_COMMIT_TOPIC_SHIFT',
|
|
410
|
+
totalInputTokens,
|
|
411
|
+
distractorTokens,
|
|
412
|
+
distractorRatio,
|
|
413
|
+
reason: `[DET-11 Context Rot Soft Horizon] Post-commit topic shift detected (${(totalInputTokens / 1000).toFixed(1)}k tokens). Previous task was committed; run /compact or /handoff to clear stale context before new feature.`
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
if (totalInputTokens > 60_000 && distractorRatio > 0.35) {
|
|
418
|
+
return {
|
|
419
|
+
detectorId: 'DET-11',
|
|
420
|
+
triggered: true,
|
|
421
|
+
decision: 'advise_compact',
|
|
422
|
+
advisory: true,
|
|
423
|
+
totalInputTokens,
|
|
424
|
+
distractorTokens,
|
|
425
|
+
distractorRatio,
|
|
426
|
+
reason: `[DET-11 Context Rot Soft Horizon] Context is ${(totalInputTokens / 1000).toFixed(1)}k tokens with ${(distractorRatio * 100).toFixed(1)}% stale middle-window distractor debt (> 35%). Recommend /compact with StateBaton handoff.`
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
return {
|
|
431
|
+
detectorId: 'DET-11',
|
|
432
|
+
triggered: false,
|
|
433
|
+
decision: 'allow',
|
|
434
|
+
totalInputTokens,
|
|
435
|
+
distractorTokens,
|
|
436
|
+
distractorRatio,
|
|
437
|
+
reason: null
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* DET-12: Haiku 5.5 `90,000`-Token Pre-Cliff Compaction Breaker (prevents crossing 100k `5x` cliff).
|
|
443
|
+
* Sums `inputTokens + cacheReadTokens + cacheWriteTokens` when `totalPromptTokens` / `totalInputTokens`
|
|
444
|
+
* is not pre-computed so the full prompt envelope is always evaluated against the 100,000-token cliff.
|
|
445
|
+
*
|
|
446
|
+
* @param {object} [params={}]
|
|
447
|
+
* @param {string} [params.modelId='claude-haiku-5-5']
|
|
448
|
+
* @param {number} [params.totalInputTokens=0]
|
|
449
|
+
* @param {number} [params.totalPromptTokens]
|
|
450
|
+
* @param {number} [params.inputTokens]
|
|
451
|
+
* @param {number} [params.cacheReadTokens]
|
|
452
|
+
* @param {number} [params.cacheWriteTokens]
|
|
453
|
+
*/
|
|
454
|
+
export function evaluateDet12HaikuPreCliffBreaker(params = {}) {
|
|
455
|
+
const modelId = normalizeModelId(params.modelId || params.model || '');
|
|
456
|
+
const totalInputTokens = computeTotalPromptTokens(params);
|
|
457
|
+
|
|
458
|
+
if (modelId === 'claude-haiku-5-5' && totalInputTokens >= 90_000) {
|
|
459
|
+
const isHardDeny = totalInputTokens >= 98_000;
|
|
460
|
+
return {
|
|
461
|
+
detectorId: 'DET-12',
|
|
462
|
+
triggered: true,
|
|
463
|
+
decision: isHardDeny ? 'deny' : 'advise_compact',
|
|
464
|
+
advisory: !isHardDeny,
|
|
465
|
+
modelId,
|
|
466
|
+
totalInputTokens,
|
|
467
|
+
cliffThresholdTokens: 100_000,
|
|
468
|
+
reason: `[DET-12 Haiku 5.5 90k Pre-Cliff Breaker] Total prompt size (${totalInputTokens.toLocaleString()} tokens) is approaching Claude Haiku 5.5's 100,000-token 5x price cliff ($0.10->$0.50 input, $0.50->$2.50 output). Compact now to avoid a 5x jump across all token categories.`
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
return {
|
|
473
|
+
detectorId: 'DET-12',
|
|
474
|
+
triggered: false,
|
|
475
|
+
decision: 'allow',
|
|
476
|
+
modelId,
|
|
477
|
+
totalInputTokens,
|
|
478
|
+
reason: null
|
|
479
|
+
};
|
|
480
|
+
}
|