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
|
@@ -238,7 +238,13 @@ export const DEFAULT_HORIZON_CONFIG = Object.freeze({
|
|
|
238
238
|
blindSearchLimit: 6,
|
|
239
239
|
consecutiveFailureLimit: 3,
|
|
240
240
|
enableLocalKeepAlive: false,
|
|
241
|
-
microSkillConfirmSessions: 2
|
|
241
|
+
microSkillConfirmSessions: 2,
|
|
242
|
+
minSwitchPenaltyUSD: 0.02,
|
|
243
|
+
notableAllowPenaltyUSD: 0.02,
|
|
244
|
+
outputShrinkageMinTurns: 5,
|
|
245
|
+
outputShrinkagePriorTokens: 500,
|
|
246
|
+
smartCompactBoundarySuggest: false,
|
|
247
|
+
resumeToolsetWarnMinTokens: 10000
|
|
242
248
|
}
|
|
243
249
|
});
|
|
244
250
|
|
|
@@ -547,6 +553,9 @@ export function loadHorizonConfig(options = {}) {
|
|
|
547
553
|
const warnings = [];
|
|
548
554
|
let flightMode = DEFAULT_HORIZON_CONFIG.flightMode;
|
|
549
555
|
let resolvedNamespace = DEFAULT_HORIZON_CONFIG.detectorNamespace;
|
|
556
|
+
let autoPilotDecision = null;
|
|
557
|
+
let expectedRemainingTurns = null;
|
|
558
|
+
let useEmpiricalHorizonPrior = false;
|
|
550
559
|
|
|
551
560
|
const mergeHabitSlugsFromMap = (mapObj) => {
|
|
552
561
|
if (!mapObj || typeof mapObj !== 'object' || Array.isArray(mapObj)) return;
|
|
@@ -657,6 +666,40 @@ export function loadHorizonConfig(options = {}) {
|
|
|
657
666
|
}
|
|
658
667
|
}
|
|
659
668
|
}
|
|
669
|
+
|
|
670
|
+
if (layer.autoPilotDecision === 'ask' || layer.autoPilotDecision === 'deny') {
|
|
671
|
+
autoPilotDecision = layer.autoPilotDecision;
|
|
672
|
+
}
|
|
673
|
+
if (
|
|
674
|
+
layer.expectedRemainingTurns !== undefined &&
|
|
675
|
+
layer.expectedRemainingTurns !== null &&
|
|
676
|
+
Number.isFinite(Number(layer.expectedRemainingTurns))
|
|
677
|
+
) {
|
|
678
|
+
expectedRemainingTurns = Math.max(0, Number(layer.expectedRemainingTurns));
|
|
679
|
+
}
|
|
680
|
+
if (typeof layer.useEmpiricalHorizonPrior === 'boolean') {
|
|
681
|
+
useEmpiricalHorizonPrior = layer.useEmpiricalHorizonPrior;
|
|
682
|
+
}
|
|
683
|
+
if (typeof layer.smartCompactBoundarySuggest === 'boolean') {
|
|
684
|
+
thresholds.smartCompactBoundarySuggest = layer.smartCompactBoundarySuggest;
|
|
685
|
+
}
|
|
686
|
+
if (
|
|
687
|
+
layer.resumeToolsetWarnMinTokens !== undefined &&
|
|
688
|
+
layer.resumeToolsetWarnMinTokens !== null &&
|
|
689
|
+
Number.isFinite(Number(layer.resumeToolsetWarnMinTokens))
|
|
690
|
+
) {
|
|
691
|
+
thresholds.resumeToolsetWarnMinTokens = Math.max(0, Number(layer.resumeToolsetWarnMinTokens));
|
|
692
|
+
}
|
|
693
|
+
for (const tk of [
|
|
694
|
+
'minSwitchPenaltyUSD',
|
|
695
|
+
'notableAllowPenaltyUSD',
|
|
696
|
+
'outputShrinkageMinTurns',
|
|
697
|
+
'outputShrinkagePriorTokens'
|
|
698
|
+
]) {
|
|
699
|
+
if (layer[tk] !== undefined && layer[tk] !== null && Number.isFinite(Number(layer[tk]))) {
|
|
700
|
+
thresholds[tk] = Math.max(0, Number(layer[tk]));
|
|
701
|
+
}
|
|
702
|
+
}
|
|
660
703
|
};
|
|
661
704
|
|
|
662
705
|
mergeLayer(globalRaw, { isDiskLayer: true, sourceLabel: globalConfigPath });
|
|
@@ -680,6 +723,9 @@ export function loadHorizonConfig(options = {}) {
|
|
|
680
723
|
semanticDetectors,
|
|
681
724
|
thresholds,
|
|
682
725
|
warnings,
|
|
726
|
+
...(autoPilotDecision ? { autoPilotDecision } : {}),
|
|
727
|
+
...(expectedRemainingTurns !== null ? { expectedRemainingTurns } : {}),
|
|
728
|
+
...(useEmpiricalHorizonPrior ? { useEmpiricalHorizonPrior: true } : {}),
|
|
683
729
|
sources: {
|
|
684
730
|
globalLoaded: Boolean(globalRaw),
|
|
685
731
|
projectLoaded: Boolean(projectRaw),
|
|
@@ -620,3 +620,269 @@ export function evaluateTwoStageSightseeingIntercept({
|
|
|
620
620
|
consumeFlag: false
|
|
621
621
|
};
|
|
622
622
|
}
|
|
623
|
+
|
|
624
|
+
const SHARDED_SPEC_PIVOT_PATTERNS = Object.freeze([
|
|
625
|
+
/\b(?:actually|instead|wait)\b[^.?!]{0,40}\b(?:make|use|support|change|switch|add|keep|enforce|require|return|handle|format|allow|reject|export|include|preserve)\b/i,
|
|
626
|
+
/\b(?:also|additionally)\s+(?:make\s+sure|add|support|include|handle|enforce|allow|ensure|require|update|expose|reject|export|return)\b/i,
|
|
627
|
+
/\b(?:don't\s+forget\s+to|do\s+not\s+forget\s+to|make\s+sure\s+(?:it|we|you)\s+(?:also\s+)?(?:support|handle|reject|enforce|preserve|include|export|return)|one\s+more\s+(?:thing|requirement|constraint)|new\s+requirement|change\s+the\s+(?:format|schema|output|contract|behavior)\s+to)\b/i
|
|
628
|
+
]);
|
|
629
|
+
|
|
630
|
+
const TRIVIAL_COMMAND_FOLLOWUP_RE =
|
|
631
|
+
/^(?:also|and|now|then|please)?\s*(?:just\s+)?(?:run|re-?run|execute|check)\s+(?:the\s+)?(?:unit\s+|integration\s+|all\s+)?(?:tests?|npm\s+test|pnpm\s+test|pytest|vitest|jest|lint|build|typecheck|tsc|git\s+status|git\s+diff)[.!?\s]*$/i;
|
|
632
|
+
|
|
633
|
+
const TURN1_BUILD_INTENT_RE =
|
|
634
|
+
/\b(?:build|implement|create|design|architect|redesign|migrate|refactor|overhaul|integrate|add\s+support\s+for|set\s+up)\b/i;
|
|
635
|
+
|
|
636
|
+
const TURN1_QUESTION_RE =
|
|
637
|
+
/^(?:how|why|what|where|when|who|can\s+you\s+explain|could\s+you\s+explain|explain|describe|review|summarize)\b/i;
|
|
638
|
+
|
|
639
|
+
const TURN1_SPEC_REF_RE = /\bspecs?[\\/][\w.-]+\.md\b/i;
|
|
640
|
+
|
|
641
|
+
const REAL_CODE_SYMBOL_RE =
|
|
642
|
+
/`[^`]{2,}`|\b[a-z][a-zA-Z0-9]+_[a-zA-Z0-9_]+\b|\b[a-z][a-z0-9]*[A-Z][A-Za-z0-9]+\b|\b[A-Z][a-z0-9]+[A-Z][A-Za-z0-9]*\b|\b[a-zA-Z_]\w+\([^\x29]*\)/;
|
|
643
|
+
|
|
644
|
+
const TURN1_BOUNDARY_RE =
|
|
645
|
+
/\b(?:do\s+not|don't|only|without\s+touching|out\s+of\s+scope|non-goal|avoid|preserve|must\s+not|cannot)\b/i;
|
|
646
|
+
|
|
647
|
+
const TURN1_VERIFY_RE =
|
|
648
|
+
/\b(?:test|tests|verify|verification|acceptance\s+criteria|should\s+pass|assert|exit\s+code|exit\s+0|spec|benchmark)\b/i;
|
|
649
|
+
|
|
650
|
+
export const TURN1_CONTRACT_DIRECTIVE =
|
|
651
|
+
'[CTX_CONTRACT: State (1) target files, (2) negative constraints/invariants, and (3) verification command in <=8 lines before calling file-mutation tools.]';
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* Tracks cross-turn requirement-modifying user prompts (`Spec Sharding / Drip-Feed`)
|
|
655
|
+
* and emits `[CTX_HINT: SHARDED_SPEC]` when 4+ constraint shards accumulate alongside `>=25k` tokens.
|
|
656
|
+
* Zero I/O, Mod Law 4 compliant.
|
|
657
|
+
*
|
|
658
|
+
* @param {object} [params={}]
|
|
659
|
+
*/
|
|
660
|
+
export function evaluateShardedSpecDrift({
|
|
661
|
+
prompt = '',
|
|
662
|
+
provenance = 'user',
|
|
663
|
+
isAutonomousTurn = false,
|
|
664
|
+
isSubagent = false,
|
|
665
|
+
isScheduledTask = false,
|
|
666
|
+
isLoopIteration = false,
|
|
667
|
+
priorShards = [],
|
|
668
|
+
initialGoal = '',
|
|
669
|
+
totalTokens = 0,
|
|
670
|
+
turnNumber = 1,
|
|
671
|
+
lastAlertTurn = 0,
|
|
672
|
+
minShards = 4,
|
|
673
|
+
minTokens = 25000,
|
|
674
|
+
cooldownTurns = 3,
|
|
675
|
+
overrideMode = 'default',
|
|
676
|
+
flightMode = 'COACH',
|
|
677
|
+
detectorId = 'DET-26'
|
|
678
|
+
} = {}) {
|
|
679
|
+
const safeShards = Array.isArray(priorShards)
|
|
680
|
+
? priorShards
|
|
681
|
+
.filter((s) => s && typeof s.excerpt === 'string' && s.excerpt.trim().length > 0)
|
|
682
|
+
.map((s) => ({ turn: Number(s.turn || 0), excerpt: String(s.excerpt).trim() }))
|
|
683
|
+
: [];
|
|
684
|
+
const raw = String(prompt || '').trim();
|
|
685
|
+
const cleaned = raw.replace(/#check\b/gi, '').trim();
|
|
686
|
+
const normOverride = String(overrideMode || 'default').toLowerCase();
|
|
687
|
+
const fmUpper = String(flightMode || 'COACH').toUpperCase();
|
|
688
|
+
const numericTurn = Math.max(1, Number(turnNumber || 1));
|
|
689
|
+
const numericLastAlert = Number(lastAlertTurn || 0);
|
|
690
|
+
const nextInitialGoal =
|
|
691
|
+
String(initialGoal || '').trim() || (numericTurn <= 1 && cleaned ? cleaned.slice(0, 280) : '');
|
|
692
|
+
|
|
693
|
+
const noOp = (reason = null) => ({
|
|
694
|
+
detectorId,
|
|
695
|
+
slug: 'sharded-spec-drift',
|
|
696
|
+
triggered: false,
|
|
697
|
+
subType: null,
|
|
698
|
+
decision: 'allow',
|
|
699
|
+
bypassReason: reason,
|
|
700
|
+
shardCount: safeShards.length,
|
|
701
|
+
specShards: safeShards,
|
|
702
|
+
initialGoal: nextInitialGoal,
|
|
703
|
+
lastAlertTurn: numericLastAlert,
|
|
704
|
+
steerContext: null
|
|
705
|
+
});
|
|
706
|
+
|
|
707
|
+
if (normOverride === 'off' || fmUpper === 'OFF' || fmUpper === 'SILENT') {
|
|
708
|
+
return noOp('DISABLED_BY_CONFIG');
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
if (
|
|
712
|
+
Boolean(isAutonomousTurn) ||
|
|
713
|
+
Boolean(isSubagent) ||
|
|
714
|
+
Boolean(isScheduledTask) ||
|
|
715
|
+
Boolean(isLoopIteration) ||
|
|
716
|
+
AUTONOMOUS_PROVENANCE_RE.test(String(provenance || '')) ||
|
|
717
|
+
!cleaned ||
|
|
718
|
+
cleaned.startsWith('/') ||
|
|
719
|
+
AFFIRMATIVE_OR_CONTINUATION_RE.test(cleaned)
|
|
720
|
+
) {
|
|
721
|
+
return noOp('AUTONOMOUS_OR_CONTINUATION');
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
if (matchRelayHardNegativeFilter(cleaned).matched) {
|
|
725
|
+
return noOp('HARD_NEGATIVE_PAYLOAD');
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
let nextShards = safeShards.slice();
|
|
729
|
+
const isFollowUpTurn = numericTurn >= 2 || Boolean(String(initialGoal || '').trim()) || safeShards.length > 0;
|
|
730
|
+
const isPivotPrompt =
|
|
731
|
+
isFollowUpTurn &&
|
|
732
|
+
!TRIVIAL_COMMAND_FOLLOWUP_RE.test(cleaned) &&
|
|
733
|
+
SHARDED_SPEC_PIVOT_PATTERNS.some((re) => re.test(cleaned));
|
|
734
|
+
|
|
735
|
+
if (isPivotPrompt) {
|
|
736
|
+
const excerpt = cleaned.slice(0, 220);
|
|
737
|
+
const prevExcerpt = nextShards.length > 0 ? nextShards[nextShards.length - 1].excerpt : '';
|
|
738
|
+
if (excerpt && excerpt !== prevExcerpt) {
|
|
739
|
+
nextShards.push({ turn: numericTurn, excerpt });
|
|
740
|
+
if (nextShards.length > 10) {
|
|
741
|
+
nextShards = nextShards.slice(-10);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
const tokensNum = Math.max(0, Number(totalTokens || 0));
|
|
747
|
+
const cooldownOk = numericLastAlert <= 0 || numericTurn - numericLastAlert >= Number(cooldownTurns || 3);
|
|
748
|
+
const triggered =
|
|
749
|
+
isPivotPrompt &&
|
|
750
|
+
nextShards.length >= Number(minShards || 4) &&
|
|
751
|
+
tokensNum >= Number(minTokens || 25000) &&
|
|
752
|
+
cooldownOk;
|
|
753
|
+
|
|
754
|
+
if (!triggered) {
|
|
755
|
+
return {
|
|
756
|
+
detectorId,
|
|
757
|
+
slug: 'sharded-spec-drift',
|
|
758
|
+
triggered: false,
|
|
759
|
+
subType: null,
|
|
760
|
+
decision: 'allow',
|
|
761
|
+
bypassReason: null,
|
|
762
|
+
shardCount: nextShards.length,
|
|
763
|
+
specShards: nextShards,
|
|
764
|
+
initialGoal: nextInitialGoal,
|
|
765
|
+
lastAlertTurn: numericLastAlert,
|
|
766
|
+
steerContext: null
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
const steerContext = `[CTX_HINT: SHARDED_SPEC — ${nextShards.length} incremental constraint turns across ~${Math.round(tokensNum / 1000)}k tokens. Run \`npx ctxtop handoff --consolidate\` (or /handoff) to merge scattered requirements into one clean contract before restarting.]`;
|
|
771
|
+
return {
|
|
772
|
+
detectorId,
|
|
773
|
+
slug: 'sharded-spec-drift',
|
|
774
|
+
triggered: true,
|
|
775
|
+
subType: 'SHARDED_SPEC_DRIFT',
|
|
776
|
+
decision: 'steer',
|
|
777
|
+
bypassReason: null,
|
|
778
|
+
shardCount: nextShards.length,
|
|
779
|
+
specShards: nextShards,
|
|
780
|
+
initialGoal: nextInitialGoal,
|
|
781
|
+
lastAlertTurn: numericTurn,
|
|
782
|
+
steerContext
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/**
|
|
787
|
+
* One-shot Turn-1 Specification Contract Gate (`[CTX_CONTRACT]`) for unanchored multi-file build/refactor prompts.
|
|
788
|
+
* Skips `/plan` mode, questions, slash commands, active-set matches, and Turn 2+.
|
|
789
|
+
* Zero I/O, Mod Law 4 compliant.
|
|
790
|
+
*
|
|
791
|
+
* @param {object} [params={}]
|
|
792
|
+
*/
|
|
793
|
+
export function evaluateTurn1ContractGate({
|
|
794
|
+
prompt = '',
|
|
795
|
+
provenance = 'user',
|
|
796
|
+
isAutonomousTurn = false,
|
|
797
|
+
isSubagent = false,
|
|
798
|
+
isScheduledTask = false,
|
|
799
|
+
isLoopIteration = false,
|
|
800
|
+
inPlanMode = false,
|
|
801
|
+
turnNumber = 1,
|
|
802
|
+
invocationNum = 1,
|
|
803
|
+
alreadyInjected = false,
|
|
804
|
+
hasActiveSetMatch = false,
|
|
805
|
+
sufficiency = null,
|
|
806
|
+
overrideMode = 'default',
|
|
807
|
+
flightMode = 'COACH',
|
|
808
|
+
detectorId = 'DET-26'
|
|
809
|
+
} = {}) {
|
|
810
|
+
const allow = (bypassReason = null) => ({
|
|
811
|
+
detectorId,
|
|
812
|
+
slug: 'turn1-contract-gate',
|
|
813
|
+
triggered: false,
|
|
814
|
+
subType: null,
|
|
815
|
+
decision: 'allow',
|
|
816
|
+
bypassReason,
|
|
817
|
+
contractDirective: null
|
|
818
|
+
});
|
|
819
|
+
|
|
820
|
+
const normOverride = String(overrideMode || 'default').toLowerCase();
|
|
821
|
+
const fmUpper = String(flightMode || 'COACH').toUpperCase();
|
|
822
|
+
if (normOverride === 'off' || fmUpper === 'OFF' || fmUpper === 'SILENT') {
|
|
823
|
+
return allow('DISABLED_BY_CONFIG');
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
if (
|
|
827
|
+
Boolean(alreadyInjected) ||
|
|
828
|
+
Number(turnNumber || 1) > 1 ||
|
|
829
|
+
Number(invocationNum || 1) > 1 ||
|
|
830
|
+
Boolean(inPlanMode) ||
|
|
831
|
+
Boolean(hasActiveSetMatch)
|
|
832
|
+
) {
|
|
833
|
+
return allow('NOT_ELIGIBLE_TURN1');
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
if (
|
|
837
|
+
Boolean(isAutonomousTurn) ||
|
|
838
|
+
Boolean(isSubagent) ||
|
|
839
|
+
Boolean(isScheduledTask) ||
|
|
840
|
+
Boolean(isLoopIteration) ||
|
|
841
|
+
AUTONOMOUS_PROVENANCE_RE.test(String(provenance || ''))
|
|
842
|
+
) {
|
|
843
|
+
return allow('AUTONOMOUS_BYPASS');
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
const cleaned = String(prompt || '').replace(/#check\b/gi, '').trim();
|
|
847
|
+
if (
|
|
848
|
+
!cleaned ||
|
|
849
|
+
cleaned.startsWith('/') ||
|
|
850
|
+
AFFIRMATIVE_OR_CONTINUATION_RE.test(cleaned) ||
|
|
851
|
+
cleaned.endsWith('?') ||
|
|
852
|
+
TURN1_QUESTION_RE.test(cleaned) ||
|
|
853
|
+
TURN1_SPEC_REF_RE.test(cleaned) ||
|
|
854
|
+
matchRelayHardNegativeFilter(cleaned).matched
|
|
855
|
+
) {
|
|
856
|
+
return allow('EXEMPT_PROMPT_KIND');
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
const wordCount = cleaned.split(/\s+/).filter(Boolean).length;
|
|
860
|
+
if (wordCount < 8 || wordCount > 55 || !TURN1_BUILD_INTENT_RE.test(cleaned)) {
|
|
861
|
+
return allow('NOT_UNANCHORED_BUILD');
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
const hasConcreteTarget =
|
|
865
|
+
CONCRETE_FILE_OR_PATH_RE.test(cleaned) || REAL_CODE_SYMBOL_RE.test(cleaned);
|
|
866
|
+
if (hasConcreteTarget) {
|
|
867
|
+
return allow('HAS_CONCRETE_TARGET');
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
const dims = sufficiency?.dims || null;
|
|
871
|
+
const lacksBoundaryOrVerify = dims
|
|
872
|
+
? Number(dims.boundedness || 0) === 0 || Number(dims.testability || 0) === 0
|
|
873
|
+
: !TURN1_BOUNDARY_RE.test(cleaned) || !TURN1_VERIFY_RE.test(cleaned);
|
|
874
|
+
|
|
875
|
+
if (!lacksBoundaryOrVerify) {
|
|
876
|
+
return allow('HAS_CONSTRAINTS_AND_VERIFY');
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
return {
|
|
880
|
+
detectorId,
|
|
881
|
+
slug: 'turn1-contract-gate',
|
|
882
|
+
triggered: true,
|
|
883
|
+
subType: 'TURN1_CONTRACT_GATE',
|
|
884
|
+
decision: 'steer',
|
|
885
|
+
bypassReason: null,
|
|
886
|
+
contractDirective: TURN1_CONTRACT_DIRECTIVE
|
|
887
|
+
};
|
|
888
|
+
}
|
|
@@ -61,17 +61,35 @@ export const MODEL_BREAK_EVEN_RATES = Object.freeze({
|
|
|
61
61
|
export function resolveNaturalDownshiftPeer(modelId = 'claude-opus-5-5') {
|
|
62
62
|
const norm = normalizeModelId(modelId);
|
|
63
63
|
switch (norm) {
|
|
64
|
+
case 'claude-mythos-5-2':
|
|
65
|
+
case 'claude-mythos-5-1':
|
|
66
|
+
case 'claude-mythos-5':
|
|
64
67
|
case 'claude-fable-5-2':
|
|
65
68
|
case 'claude-fable-5-1':
|
|
69
|
+
case 'claude-fable-5':
|
|
66
70
|
return 'claude-opus-5-5';
|
|
67
71
|
case 'claude-opus-5-5':
|
|
68
72
|
return 'claude-sonnet-5-5';
|
|
73
|
+
case 'claude-opus-5':
|
|
74
|
+
return 'claude-sonnet-5';
|
|
75
|
+
case 'claude-opus-4-8':
|
|
76
|
+
case 'claude-opus-4-7':
|
|
69
77
|
case 'claude-opus-4-6':
|
|
78
|
+
case 'claude-opus-4-5':
|
|
79
|
+
case 'claude-opus-4-1':
|
|
80
|
+
case 'claude-opus-4-0':
|
|
70
81
|
return 'claude-sonnet-4-6';
|
|
71
82
|
case 'claude-sonnet-5-5':
|
|
83
|
+
case 'claude-sonnet-5':
|
|
72
84
|
return 'claude-haiku-5-5';
|
|
73
85
|
case 'claude-sonnet-4-6':
|
|
86
|
+
case 'claude-sonnet-4-5':
|
|
87
|
+
case 'claude-sonnet-4-0':
|
|
74
88
|
return 'claude-haiku-4-5';
|
|
89
|
+
case 'claude-3-7-sonnet':
|
|
90
|
+
case 'claude-3-5-sonnet':
|
|
91
|
+
case 'claude-3-5-haiku':
|
|
92
|
+
return 'claude-3-5-haiku';
|
|
75
93
|
case 'claude-haiku-4-5':
|
|
76
94
|
case 'claude-haiku-5-5':
|
|
77
95
|
return 'claude-haiku-5-5';
|
|
@@ -25,6 +25,15 @@ export const HAIKU_CLIFF_THRESHOLDS = Object.freeze({
|
|
|
25
25
|
PRICE_MULTIPLIER: 5.0
|
|
26
26
|
});
|
|
27
27
|
|
|
28
|
+
export const GEMINI_PRO_200K_CLIFF_THRESHOLDS = Object.freeze({
|
|
29
|
+
ADVISORY_TOKENS: 180000,
|
|
30
|
+
BREAKER_TOKENS: 196000,
|
|
31
|
+
CLIFF_TOKENS: 200000,
|
|
32
|
+
INPUT_MULTIPLIER: 2.0,
|
|
33
|
+
OUTPUT_MULTIPLIER: 1.5,
|
|
34
|
+
PRICE_MULTIPLIER: 2.0
|
|
35
|
+
});
|
|
36
|
+
|
|
28
37
|
/**
|
|
29
38
|
* Checks whether a given model string corresponds to an Anthropic Claude Haiku model.
|
|
30
39
|
* @param {string} [modelId='']
|
|
@@ -34,6 +43,62 @@ export function isHaikuModel(modelId = '') {
|
|
|
34
43
|
return String(modelId || '').toLowerCase().includes('haiku');
|
|
35
44
|
}
|
|
36
45
|
|
|
46
|
+
/**
|
|
47
|
+
* Checks whether a given model string corresponds to Gemini 3.1 Pro or Gemini 2.5 Pro
|
|
48
|
+
* (subject to the 200,000-token 2x input / 1.5x output pricing cliff).
|
|
49
|
+
* @param {string} [modelId='']
|
|
50
|
+
* @returns {boolean}
|
|
51
|
+
*/
|
|
52
|
+
export function isGeminiPro200kCliffModel(modelId = '') {
|
|
53
|
+
const lower = String(modelId || '').toLowerCase().trim();
|
|
54
|
+
return /gemini[-_.\s]*(?:3[._-]1|2[._-]5)[-_.\s]*pro\b/.test(lower);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Resolves parameterized pricing cliff metadata for models with stepped prompt pricing
|
|
59
|
+
* (Claude Haiku 5.5 at 100K 5x, Gemini 3.1/2.5 Pro at 200K 2x input / 1.5x output).
|
|
60
|
+
* Returns `null` for models without a prompt pricing cliff (Sonnet, Opus, Fable, Gemini 4, Flash).
|
|
61
|
+
*
|
|
62
|
+
* @param {string} [modelId='']
|
|
63
|
+
* @returns {{
|
|
64
|
+
* family: 'haiku' | 'gemini-pro',
|
|
65
|
+
* advisoryTokens: number,
|
|
66
|
+
* breakerTokens: number,
|
|
67
|
+
* cliffTokens: number,
|
|
68
|
+
* inputMultiplier: number,
|
|
69
|
+
* outputMultiplier: number,
|
|
70
|
+
* priceMultiplier: number,
|
|
71
|
+
* label: string
|
|
72
|
+
* } | null}
|
|
73
|
+
*/
|
|
74
|
+
export function resolveModelCliffSpec(modelId = '') {
|
|
75
|
+
if (isHaikuModel(modelId)) {
|
|
76
|
+
return {
|
|
77
|
+
family: 'haiku',
|
|
78
|
+
advisoryTokens: HAIKU_CLIFF_THRESHOLDS.ADVISORY_TOKENS,
|
|
79
|
+
breakerTokens: HAIKU_CLIFF_THRESHOLDS.BREAKER_TOKENS,
|
|
80
|
+
cliffTokens: HAIKU_CLIFF_THRESHOLDS.CLIFF_TOKENS,
|
|
81
|
+
inputMultiplier: HAIKU_CLIFF_THRESHOLDS.PRICE_MULTIPLIER,
|
|
82
|
+
outputMultiplier: HAIKU_CLIFF_THRESHOLDS.PRICE_MULTIPLIER,
|
|
83
|
+
priceMultiplier: HAIKU_CLIFF_THRESHOLDS.PRICE_MULTIPLIER,
|
|
84
|
+
label: 'Haiku 100k 5x cost cliff'
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
if (isGeminiPro200kCliffModel(modelId)) {
|
|
88
|
+
return {
|
|
89
|
+
family: 'gemini-pro',
|
|
90
|
+
advisoryTokens: GEMINI_PRO_200K_CLIFF_THRESHOLDS.ADVISORY_TOKENS,
|
|
91
|
+
breakerTokens: GEMINI_PRO_200K_CLIFF_THRESHOLDS.BREAKER_TOKENS,
|
|
92
|
+
cliffTokens: GEMINI_PRO_200K_CLIFF_THRESHOLDS.CLIFF_TOKENS,
|
|
93
|
+
inputMultiplier: GEMINI_PRO_200K_CLIFF_THRESHOLDS.INPUT_MULTIPLIER,
|
|
94
|
+
outputMultiplier: GEMINI_PRO_200K_CLIFF_THRESHOLDS.OUTPUT_MULTIPLIER,
|
|
95
|
+
priceMultiplier: GEMINI_PRO_200K_CLIFF_THRESHOLDS.PRICE_MULTIPLIER,
|
|
96
|
+
label: 'Gemini Pro 200k 2x input / 1.5x output cliff'
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
|
|
37
102
|
/**
|
|
38
103
|
* Evaluates prompt token volume against the Haiku 100k 5x price cliff.
|
|
39
104
|
*
|
|
@@ -127,38 +192,59 @@ export function evaluateDet12HaikuPreCliffBreaker(params = {}) {
|
|
|
127
192
|
}
|
|
128
193
|
|
|
129
194
|
const totalTokens = Math.max(0, Number(candidate) || 0);
|
|
195
|
+
const projectedDelta = Math.max(0, Number(safeParams.projectedDeltaTokens) || 0);
|
|
196
|
+
const effectiveTokens = totalTokens + projectedDelta;
|
|
130
197
|
|
|
131
|
-
const
|
|
132
|
-
if (!
|
|
198
|
+
const cliffSpec = resolveModelCliffSpec(modelId);
|
|
199
|
+
if (!cliffSpec || effectiveTokens < cliffSpec.advisoryTokens) {
|
|
133
200
|
return {
|
|
134
201
|
detectorId: HAIKU_CLIFF_DETECTOR_ID,
|
|
135
202
|
triggered: false,
|
|
136
203
|
decision: 'allow',
|
|
137
204
|
advisory: false,
|
|
138
205
|
modelId,
|
|
139
|
-
totalInputTokens:
|
|
140
|
-
cliffThresholdTokens: HAIKU_CLIFF_THRESHOLDS.CLIFF_TOKENS,
|
|
141
|
-
reason:
|
|
142
|
-
?
|
|
143
|
-
: `Non-
|
|
206
|
+
totalInputTokens: effectiveTokens,
|
|
207
|
+
cliffThresholdTokens: cliffSpec ? cliffSpec.cliffTokens : HAIKU_CLIFF_THRESHOLDS.CLIFF_TOKENS,
|
|
208
|
+
reason: cliffSpec
|
|
209
|
+
? `${cliffSpec.family === 'haiku' ? 'Haiku' : 'Gemini Pro'} prompt size (${effectiveTokens.toLocaleString()}) is within safe volume (<${Math.round(cliffSpec.advisoryTokens / 1000)}k).`
|
|
210
|
+
: `Non-cliff model (${modelId || 'unspecified'}); exempt from DET-12 pricing cliff breaker.`
|
|
144
211
|
};
|
|
145
212
|
}
|
|
146
213
|
|
|
147
|
-
const isHardDeny =
|
|
214
|
+
const isHardDeny = effectiveTokens >= cliffSpec.breakerTokens;
|
|
215
|
+
const breakerLabelK = Math.round(cliffSpec.breakerTokens / 1000);
|
|
216
|
+
const advisoryLabelK = Math.round(cliffSpec.advisoryTokens / 1000);
|
|
217
|
+
const cliffLabelK = Math.round(cliffSpec.cliffTokens / 1000);
|
|
218
|
+
const multDesc =
|
|
219
|
+
cliffSpec.family === 'haiku'
|
|
220
|
+
? '5x price jump'
|
|
221
|
+
: '2x input / 1.5x output price jump';
|
|
222
|
+
|
|
223
|
+
const familyTag = cliffSpec.family === 'haiku' ? 'Haiku' : 'Gemini Pro';
|
|
224
|
+
|
|
148
225
|
return {
|
|
149
226
|
detectorId: HAIKU_CLIFF_DETECTOR_ID,
|
|
150
227
|
triggered: true,
|
|
151
228
|
decision: isHardDeny ? 'deny' : 'advise_compact',
|
|
152
229
|
advisory: !isHardDeny,
|
|
153
230
|
modelId,
|
|
154
|
-
totalInputTokens:
|
|
155
|
-
cliffThresholdTokens:
|
|
231
|
+
totalInputTokens: effectiveTokens,
|
|
232
|
+
cliffThresholdTokens: cliffSpec.cliffTokens,
|
|
233
|
+
cliffSpec,
|
|
156
234
|
reason: isHardDeny
|
|
157
|
-
? `[DET-12
|
|
158
|
-
: `[DET-12
|
|
235
|
+
? `[DET-12 ${familyTag} Cliff Breaker] Prompt volume (${effectiveTokens.toLocaleString()} tokens) reached or exceeded ${breakerLabelK}k buffer. Tripping circuit breaker before ${cliffLabelK}k ${multDesc}.`
|
|
236
|
+
: `[DET-12 ${familyTag} ${advisoryLabelK}k Pre-Cliff Breaker] Prompt volume (${effectiveTokens.toLocaleString()} tokens) approaching ${cliffLabelK}k ${multDesc}. Compact now to avoid stepped billing penalty.`
|
|
159
237
|
};
|
|
160
238
|
}
|
|
161
239
|
|
|
240
|
+
/**
|
|
241
|
+
* Parameterized cross-provider pricing cliff breaker (`Haiku 5.5` 100K 5x + `Gemini 3.1/2.5 Pro` 200K 2x/1.5x).
|
|
242
|
+
* @param {object} [params={}]
|
|
243
|
+
*/
|
|
244
|
+
export function evaluateParameterizedCliffBreaker(params = {}) {
|
|
245
|
+
return evaluateDet12HaikuPreCliffBreaker(params);
|
|
246
|
+
}
|
|
247
|
+
|
|
162
248
|
/**
|
|
163
249
|
* Convenience wrapper returning unified breaker decision.
|
|
164
250
|
* @param {string} modelId
|
|
@@ -317,3 +317,117 @@ export function formatDriftLabel(drift) {
|
|
|
317
317
|
const rollingStr = drift.rollingDriftRatio != null ? `${drift.rollingDriftRatio}x` : '—';
|
|
318
318
|
return `Avg TTFT ${ttftStr} · Rolling Drift ${rollingStr}`;
|
|
319
319
|
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Item A6 (#11): Audits Gemini thinking + output token ceiling against client timeout
|
|
323
|
+
* (`maxOutputTokens + thinkingBudget > 32,768` with `timeoutMs < 120,000` risks billed partial thinking on timeout).
|
|
324
|
+
*
|
|
325
|
+
* @param {object} [params={}]
|
|
326
|
+
* @param {string} [params.modelId='']
|
|
327
|
+
* @param {number} [params.maxOutputTokens=0]
|
|
328
|
+
* @param {number} [params.thinkingBudget=0]
|
|
329
|
+
* @param {number} [params.timeoutMs=0]
|
|
330
|
+
*/
|
|
331
|
+
export function evaluateGeminiThinkingTimeoutRisk(params = {}) {
|
|
332
|
+
const modelId = String(params.modelId || '').toLowerCase();
|
|
333
|
+
const isGeminiThinking =
|
|
334
|
+
modelId === '' ||
|
|
335
|
+
/gemini-(?:4|3\.1-pro|3-pro|2\.5-pro|2\.5-flash)/i.test(modelId);
|
|
336
|
+
const maxOutput = Math.max(0, Number(params.maxOutputTokens ?? 0));
|
|
337
|
+
const thinkingBudget = Math.max(0, Number(params.thinkingBudget ?? 0));
|
|
338
|
+
const combinedBudget = maxOutput + thinkingBudget;
|
|
339
|
+
const timeoutMs = Number(params.timeoutMs ?? 0);
|
|
340
|
+
|
|
341
|
+
if (
|
|
342
|
+
isGeminiThinking &&
|
|
343
|
+
combinedBudget > 32768 &&
|
|
344
|
+
timeoutMs > 0 &&
|
|
345
|
+
timeoutMs < 120000
|
|
346
|
+
) {
|
|
347
|
+
return {
|
|
348
|
+
triggered: true,
|
|
349
|
+
detectorId: 'DET-30',
|
|
350
|
+
combinedBudget,
|
|
351
|
+
timeoutMs,
|
|
352
|
+
recommendedTimeoutMs: 180000,
|
|
353
|
+
advisory:
|
|
354
|
+
`[Highbeam Quota Shield — Thinking Timeout Billing Guard (#11)] ` +
|
|
355
|
+
`Combined maxOutputTokens + thinkingBudget (${combinedBudget.toLocaleString()} tok > 32,768) paired with client timeout ${Math.round(timeoutMs / 1000)}s (< 120s). ` +
|
|
356
|
+
`Under Gemini timeout-billing rules, aborted long-thinking requests bill generated thinking tokens — raise timeout >= 180s or cap thinkingBudget <= 16,000.`
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
return {
|
|
361
|
+
triggered: false,
|
|
362
|
+
detectorId: 'DET-30',
|
|
363
|
+
combinedBudget,
|
|
364
|
+
timeoutMs,
|
|
365
|
+
advisory: null
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Item A6 (#11): Active `DET-30` Pre-Turn Step-Down Gate.
|
|
371
|
+
* Triggers when `thinkingTokens > 4,000` AND `thinkingTokens / max(1, visibleOutputTokens) > 12`
|
|
372
|
+
* across `>= 2` consecutive turns (`block` in `AUTO_PILOT`, steering advisory in `COACH`).
|
|
373
|
+
*
|
|
374
|
+
* @param {object} [params={}]
|
|
375
|
+
* @param {Array<object>} [params.recentTurns=[]]
|
|
376
|
+
* @param {object} [params.thinkingDrift=null]
|
|
377
|
+
* @param {string} [params.mode='COACH']
|
|
378
|
+
*/
|
|
379
|
+
export function evaluateActiveDet30StepDown(params = {}) {
|
|
380
|
+
const turns = Array.isArray(params.recentTurns) && params.recentTurns.length > 0
|
|
381
|
+
? params.recentTurns
|
|
382
|
+
: Array.isArray(params.thinkingDrift?.turns)
|
|
383
|
+
? params.thinkingDrift.turns
|
|
384
|
+
: [];
|
|
385
|
+
|
|
386
|
+
let streak = 0;
|
|
387
|
+
let streakThinkingTokens = 0;
|
|
388
|
+
let latestRatio = 0;
|
|
389
|
+
|
|
390
|
+
for (let i = turns.length - 1; i >= 0; i--) {
|
|
391
|
+
const t = turns[i] || {};
|
|
392
|
+
const thinking = Number(t.thinkingTokens ?? t.thinking_tokens ?? 0);
|
|
393
|
+
const visible = Number(
|
|
394
|
+
t.visibleOutputTokens ?? t.outputTokens ?? t.output_tokens ?? 0
|
|
395
|
+
);
|
|
396
|
+
const ratio = thinking / Math.max(1, visible);
|
|
397
|
+
if (thinking > 4000 && ratio > 12) {
|
|
398
|
+
streak += 1;
|
|
399
|
+
streakThinkingTokens += thinking;
|
|
400
|
+
if (latestRatio === 0) latestRatio = Math.round(ratio * 10) / 10;
|
|
401
|
+
} else {
|
|
402
|
+
break;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
if (streak < 2) {
|
|
407
|
+
return {
|
|
408
|
+
triggered: false,
|
|
409
|
+
detectorId: 'DET-30',
|
|
410
|
+
subType: null,
|
|
411
|
+
decision: 'allow',
|
|
412
|
+
consecutiveTurns: streak,
|
|
413
|
+
reason: null
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
const flightMode = String(params.mode || 'COACH').toUpperCase();
|
|
418
|
+
const decision = flightMode === 'AUTO_PILOT' ? 'block' : 'steer';
|
|
419
|
+
return {
|
|
420
|
+
triggered: true,
|
|
421
|
+
detectorId: 'DET-30',
|
|
422
|
+
subType: 'THINKING_RUNAWAY_STEPDOWN',
|
|
423
|
+
decision,
|
|
424
|
+
consecutiveTurns: streak,
|
|
425
|
+
streakThinkingTokens,
|
|
426
|
+
latestRatio,
|
|
427
|
+
recommendedEffort: 'medium',
|
|
428
|
+
recommendedMaxThinkingTokens: 16000,
|
|
429
|
+
reason:
|
|
430
|
+
`[DET-30 Thinking Runaway Governor (#11)] ${streak} consecutive turns burned ${streakThinkingTokens.toLocaleString()} thinking tokens ` +
|
|
431
|
+
`(${latestRatio}x thinking-to-output ratio > 12x). Step down via /effort medium or set MAX_THINKING_TOKENS=16000 before continuing.`
|
|
432
|
+
};
|
|
433
|
+
}
|