ctxtop 0.0.0-stage → 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 +36 -0
- package/.claude-plugin/plugin.json +18 -0
- package/CHECKSUMS.sha256 +166 -0
- package/LICENSE +27 -0
- package/README.md +350 -2
- 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 +175 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1799 -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 +133 -0
- package/config/modelCatalog.json +785 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +577 -0
- package/hooks/handlers/config-change.mjs +402 -0
- package/hooks/handlers/hookIo.mjs +311 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-model-switch.mjs +111 -0
- package/hooks/handlers/post-tool-use.mjs +366 -0
- package/hooks/handlers/pre-model-switch.mjs +1048 -0
- package/hooks/handlers/pre-tool-use.mjs +632 -0
- package/hooks/handlers/stop-gate.mjs +526 -0
- package/hooks/handlers/user-prompt-submit.mjs +367 -0
- package/hooks/hooks.json +131 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +25 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +726 -0
- package/hooks/session_start.mjs +24 -0
- package/hooks/stop.mjs +23 -0
- package/hooks.json +56 -0
- package/package.json +110 -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 +2038 -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 +50 -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 +109 -0
- package/src/adapters/claude-code/index.mjs +194 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +888 -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 +704 -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/bucket_b_runtime.mjs +1200 -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 +1987 -0
- package/src/core/detectors_det01_to_16.mjs +1523 -0
- package/src/core/doc_indexer.mjs +338 -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 +1084 -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 +1997 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +311 -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/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/sanitizer.mjs +121 -0
- package/src/core/session_auditor.mjs +658 -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/shield_manager.mjs +1417 -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 +1547 -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/resumeToolsetAuditor.mjs +321 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1055 -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 +888 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +433 -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/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 +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
- package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
- package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/src/core-isomorphic/index.js +27 -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 +1156 -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 +1237 -0
- package/src/core-isomorphic/ui/modViews.mjs +1504 -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/claudeHookCapabilities.mjs +396 -0
- package/src/diagnostics/doctorEngine.mjs +295 -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 +342 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +12 -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 +376 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/antigravity_rsl_hook.mjs +250 -0
- package/src/hooks/claude_rsl_hook.mjs +288 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +611 -0
- package/src/hooks/pre_invocation.mjs +1725 -0
- package/src/hooks/session_start.mjs +199 -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/modelSwitchTelemetry.mjs +308 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/utils/sessionCalibration.mjs +657 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +12397 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,1725 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { readSidecarSync, writeSidecarAtomicSync, getSidecarPath } from '../core/sidecar_store.mjs';
|
|
5
|
+
import { canonicalizePath } from '../core/path_canonicalizer.mjs';
|
|
6
|
+
import { scorePromptSufficiency, toWorkspaceRelativePath } from '../core/prompt_rubric.mjs';
|
|
7
|
+
import { loadFlightcheckConfig } from '../core/config.mjs';
|
|
8
|
+
import {
|
|
9
|
+
resolveModelCeiling,
|
|
10
|
+
resolveModelRates,
|
|
11
|
+
normalizeModelKey,
|
|
12
|
+
isModelDeprecated,
|
|
13
|
+
getDeprecatedModelMigrationNotice,
|
|
14
|
+
evaluateCarbonVerbosityGuardrail
|
|
15
|
+
} from '../core/constants.mjs';
|
|
16
|
+
import {
|
|
17
|
+
SwarmIdleTtlTracker,
|
|
18
|
+
evaluateSwarmColdCacheWakeup,
|
|
19
|
+
computeSwarmRosterTtlBadges
|
|
20
|
+
} from '../core/subagents.mjs';
|
|
21
|
+
import {
|
|
22
|
+
classifyTaskComplexity,
|
|
23
|
+
CacheGravityScorer,
|
|
24
|
+
TaskMdDirectiveWatcher,
|
|
25
|
+
ModelSelectorActuator,
|
|
26
|
+
evaluateTaskAndQuotaRoute
|
|
27
|
+
} from '../core/task_quota_router.mjs';
|
|
28
|
+
import { loadHorizonConfig, resolveDetectorOverride } from '../core/horizon_config.mjs';
|
|
29
|
+
import {
|
|
30
|
+
evaluateDet08DestructiveShell,
|
|
31
|
+
evaluateDet09MidSessionRuleMutate,
|
|
32
|
+
evaluateDet18UntrustedWorkspaceSettings,
|
|
33
|
+
evaluateDet19GitHookBypass,
|
|
34
|
+
evaluateDet20ScopeCollision
|
|
35
|
+
} from '../core/detectors_det01_to_16.mjs';
|
|
36
|
+
import { loadRegistry } from '../core/telemetry/scope_lock_registry.mjs';
|
|
37
|
+
import { recordHookDiagnostic } from '../core/hook_diagnostics.mjs';
|
|
38
|
+
import {
|
|
39
|
+
evaluateScopeBrake,
|
|
40
|
+
evaluateRelayBreaker,
|
|
41
|
+
evaluateTwoStageSightseeingIntercept,
|
|
42
|
+
evaluateShardedSpecDrift,
|
|
43
|
+
evaluateTurn1ContractGate
|
|
44
|
+
} from '../core/shared/prompt_hygiene_governor.mjs';
|
|
45
|
+
import { foldCodeToSignatureStub, computeCompactLineDiff } from '../core/pruner.mjs';
|
|
46
|
+
import {
|
|
47
|
+
evaluateShieldReadGuard,
|
|
48
|
+
inspectAndSanitizeMultimodalRead
|
|
49
|
+
} from '../core/shield_manager.mjs';
|
|
50
|
+
import {
|
|
51
|
+
runBucketBPreToolShadowPass,
|
|
52
|
+
runBucketBPromptPass
|
|
53
|
+
} from '../core/bucket_b_runtime.mjs';
|
|
54
|
+
import { evaluateParameterizedCliffBreaker } from '../core-isomorphic/economics/cliffBreaker.mjs';
|
|
55
|
+
import { evaluateActiveDet30StepDown } from '../core-isomorphic/economics/driftLatency.mjs';
|
|
56
|
+
import { evaluateDet05DiffThrashing } from '../core-isomorphic/guards/det04_12_thrash_rot.mjs';
|
|
57
|
+
import { hasExplicitTestModifyIntent } from '../core-isomorphic/guards/det01_03_shell_secret.mjs';
|
|
58
|
+
import { evaluateDet04ConsecutiveFailureBreaker } from '../core/shared/detectors.mjs';
|
|
59
|
+
|
|
60
|
+
const KNOWN_ANTIGRAVITY_TOOL_NAMES = new Set([
|
|
61
|
+
'read_file',
|
|
62
|
+
'view_file',
|
|
63
|
+
'view_file_outline',
|
|
64
|
+
'view_code_item',
|
|
65
|
+
'write_file',
|
|
66
|
+
'write_to_file',
|
|
67
|
+
'edit_file',
|
|
68
|
+
'replace_file_content',
|
|
69
|
+
'multi_replace_file_content',
|
|
70
|
+
'run_command',
|
|
71
|
+
'grep_search',
|
|
72
|
+
'find_by_name',
|
|
73
|
+
'list_dir',
|
|
74
|
+
'search_web',
|
|
75
|
+
'invoke_subagent',
|
|
76
|
+
'define_subagent',
|
|
77
|
+
'send_message',
|
|
78
|
+
'manage_subagents',
|
|
79
|
+
'manage_task',
|
|
80
|
+
'schedule',
|
|
81
|
+
'ask_question',
|
|
82
|
+
'call_mcp_tool',
|
|
83
|
+
'list_resources',
|
|
84
|
+
'read_resource',
|
|
85
|
+
'swarm',
|
|
86
|
+
'run_workflow',
|
|
87
|
+
'search_marketplace',
|
|
88
|
+
'list_plugin_accounts'
|
|
89
|
+
]);
|
|
90
|
+
|
|
91
|
+
export {
|
|
92
|
+
classifyTaskComplexity,
|
|
93
|
+
CacheGravityScorer,
|
|
94
|
+
TaskMdDirectiveWatcher,
|
|
95
|
+
ModelSelectorActuator,
|
|
96
|
+
evaluateTaskAndQuotaRoute
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
async function readStdinSafe({ maxTimeoutMs = 1000, settleMs = 50 } = {}) {
|
|
100
|
+
if (process.stdin.isTTY || process.stdin.readableEnded) return {};
|
|
101
|
+
return new Promise((resolve) => {
|
|
102
|
+
let raw = '';
|
|
103
|
+
let settled = false;
|
|
104
|
+
let settleTimer = null;
|
|
105
|
+
|
|
106
|
+
const finish = (val) => {
|
|
107
|
+
if (settled) return;
|
|
108
|
+
settled = true;
|
|
109
|
+
clearTimeout(maxTimer);
|
|
110
|
+
if (settleTimer) clearTimeout(settleTimer);
|
|
111
|
+
try {
|
|
112
|
+
process.stdin.pause();
|
|
113
|
+
} catch (err) {
|
|
114
|
+
recordHookDiagnostic('pre_invocation', 'stdin.pause', err, { persist: false });
|
|
115
|
+
}
|
|
116
|
+
resolve(val);
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
const tryParse = () => {
|
|
120
|
+
try {
|
|
121
|
+
return raw ? JSON.parse(raw) : {};
|
|
122
|
+
} catch (err) {
|
|
123
|
+
recordHookDiagnostic('pre_invocation', 'stdin.parse', err);
|
|
124
|
+
return {};
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const maxTimer = setTimeout(() => finish(tryParse()), maxTimeoutMs);
|
|
129
|
+
|
|
130
|
+
process.stdin.setEncoding('utf8');
|
|
131
|
+
process.stdin.on('data', chunk => {
|
|
132
|
+
raw += chunk;
|
|
133
|
+
if (settleTimer) clearTimeout(settleTimer);
|
|
134
|
+
if (raw.trim().endsWith('}')) {
|
|
135
|
+
settleTimer = setTimeout(() => {
|
|
136
|
+
try {
|
|
137
|
+
finish(JSON.parse(raw));
|
|
138
|
+
} catch (err) {
|
|
139
|
+
recordHookDiagnostic('pre_invocation', 'stdin.settleParse', err, { persist: false });
|
|
140
|
+
}
|
|
141
|
+
}, settleMs);
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
process.stdin.on('end', () => finish(tryParse()));
|
|
145
|
+
process.stdin.on('error', (err) => {
|
|
146
|
+
recordHookDiagnostic('pre_invocation', 'stdin.error', err);
|
|
147
|
+
finish({});
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function formatScorecard(p1, p2, p3, p4) {
|
|
153
|
+
const pad = (s, len = 74) => s.length >= len ? s.slice(0, len) : s + ' '.repeat(len - s.length);
|
|
154
|
+
return [
|
|
155
|
+
'╭─ Flight Check v3.1 ──────────────────────────────────────────────────────────╮',
|
|
156
|
+
`│ 1. PROMPT : ${pad(p1, 62)} │`,
|
|
157
|
+
`│ 2. HORIZON: ${pad(p2, 62)} │`,
|
|
158
|
+
`│ 3. ACTION : ${pad(p3, 62)} │`,
|
|
159
|
+
`│ 4. REWRITE: ${pad(p4, 62)} │`,
|
|
160
|
+
'╰──────────────────────────────────────────────────────────────────────────────╯',
|
|
161
|
+
'Bypass once: prefix with `!` • Lock model/effort: include `!lock`'
|
|
162
|
+
].join('\n');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function recordAntigravitySidecarSavings(sidecar, { category = 'BOUNDED_READ_ENFORCED', savedTokens = 0, detail = '', nowMs = Date.now() } = {}) {
|
|
166
|
+
const tokens = Math.max(0, Number(savedTokens || 0));
|
|
167
|
+
if (!sidecar || typeof sidecar !== 'object' || tokens <= 0) return;
|
|
168
|
+
sidecar.telemetry = sidecar.telemetry && typeof sidecar.telemetry === 'object' ? sidecar.telemetry : {};
|
|
169
|
+
sidecar.telemetry.savedTokens = Number(sidecar.telemetry.savedTokens || 0) + tokens;
|
|
170
|
+
sidecar.telemetry.boundedReadInterventions = Number(sidecar.telemetry.boundedReadInterventions || 0) + 1;
|
|
171
|
+
sidecar.telemetry.savedTokensByCategory =
|
|
172
|
+
sidecar.telemetry.savedTokensByCategory && typeof sidecar.telemetry.savedTokensByCategory === 'object'
|
|
173
|
+
? sidecar.telemetry.savedTokensByCategory
|
|
174
|
+
: {};
|
|
175
|
+
sidecar.telemetry.savedTokensByCategory[category] =
|
|
176
|
+
Number(sidecar.telemetry.savedTokensByCategory[category] || 0) + tokens;
|
|
177
|
+
const recent = Array.isArray(sidecar.telemetry.recentInterventions)
|
|
178
|
+
? sidecar.telemetry.recentInterventions
|
|
179
|
+
: [];
|
|
180
|
+
recent.push({
|
|
181
|
+
ts: new Date(nowMs).toISOString(),
|
|
182
|
+
category,
|
|
183
|
+
savedTokens: tokens,
|
|
184
|
+
detail
|
|
185
|
+
});
|
|
186
|
+
sidecar.telemetry.recentInterventions = recent.slice(-25);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export async function handlePreToolUse(inputData = {}) {
|
|
190
|
+
const conversationId = inputData.conversationId || inputData.session_id || inputData.conversation_id || 'default_session';
|
|
191
|
+
const sidecar = readSidecarSync(conversationId);
|
|
192
|
+
sidecar.sessionMeta = sidecar.sessionMeta || {};
|
|
193
|
+
sidecar.swarmRoster = sidecar.swarmRoster || {};
|
|
194
|
+
|
|
195
|
+
// Phase 3.2: Buffer mid-turn model switches without mutating active_model_id
|
|
196
|
+
const requestedMidTurnModel = inputData.requestedModel || inputData.newModel || inputData.pending_model_id || null;
|
|
197
|
+
if (requestedMidTurnModel) {
|
|
198
|
+
const normalizedNext = normalizeModelKey(requestedMidTurnModel);
|
|
199
|
+
if (!sidecar.sessionMeta.active_model_id) {
|
|
200
|
+
sidecar.sessionMeta.active_model_id = normalizeModelKey(
|
|
201
|
+
inputData.active_model_id || inputData.modelName || sidecar.sessionMeta.activeModel || 'gemini-3.8-flash'
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
if (normalizedNext !== sidecar.sessionMeta.active_model_id) {
|
|
205
|
+
sidecar.sessionMeta.pending_model_id = normalizedNext;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const toolName = String(inputData.tool_name || inputData.tool || inputData.toolName || '').trim();
|
|
210
|
+
const toolInput = inputData.tool_input || inputData.toolInput || inputData.args || inputData.parameters || inputData.Arguments || inputData;
|
|
211
|
+
const workspacePath = inputData.cwd || inputData.workspacePath || sidecar.workspacePath || process.cwd();
|
|
212
|
+
const horizonConfig = inputData.horizonConfig || loadHorizonConfig({
|
|
213
|
+
cwd: workspacePath,
|
|
214
|
+
...(inputData.homeDir ? { homeDir: inputData.homeDir } : {})
|
|
215
|
+
});
|
|
216
|
+
const flightMode = String(inputData.flightMode || horizonConfig.flightMode || 'COACH').toUpperCase();
|
|
217
|
+
const isSilentMode = flightMode === 'SILENT';
|
|
218
|
+
const isOffMode = flightMode === 'OFF';
|
|
219
|
+
const isAutoPilotMode = flightMode === 'AUTO_PILOT';
|
|
220
|
+
|
|
221
|
+
const syntheticStep = [{
|
|
222
|
+
toolCalls: [{
|
|
223
|
+
name: toolName,
|
|
224
|
+
args: toolInput && typeof toolInput === 'object' ? toolInput : {}
|
|
225
|
+
}]
|
|
226
|
+
}];
|
|
227
|
+
|
|
228
|
+
const makeBlockPayload = (detResult) => ({
|
|
229
|
+
decision: 'block',
|
|
230
|
+
permissionDecision: 'deny',
|
|
231
|
+
terminationBehavior: 'terminate',
|
|
232
|
+
blocked: true,
|
|
233
|
+
flightMode,
|
|
234
|
+
detectorId: detResult.id,
|
|
235
|
+
reason: detResult.message,
|
|
236
|
+
userMessage: detResult.message,
|
|
237
|
+
systemMessage: detResult.message
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
// Ring-0 Security Gates (active even in SILENT / OFF unless explicitly disabled in Antigravity namespace)
|
|
241
|
+
const effectivePromptText = String(
|
|
242
|
+
inputData.lastUserInput ??
|
|
243
|
+
inputData.prompt ??
|
|
244
|
+
inputData.user_input ??
|
|
245
|
+
sidecar.sessionMeta?.lastUserPrompt ??
|
|
246
|
+
''
|
|
247
|
+
);
|
|
248
|
+
const userExplicitTestIntent =
|
|
249
|
+
Boolean(inputData.userExplicitTestIntent || inputData.userAuthorizedTestDeletion) ||
|
|
250
|
+
hasExplicitTestModifyIntent(effectivePromptText);
|
|
251
|
+
if (/^(run_command|execute_bash|bash|powershell|exec)$/i.test(toolName)) {
|
|
252
|
+
if (resolveDetectorOverride(horizonConfig, 'DET-19') !== 'off') {
|
|
253
|
+
const det19 = evaluateDet19GitHookBypass(syntheticStep);
|
|
254
|
+
if (det19) return makeBlockPayload(det19);
|
|
255
|
+
}
|
|
256
|
+
if (resolveDetectorOverride(horizonConfig, 'DET-08') !== 'off') {
|
|
257
|
+
const det08 = evaluateDet08DestructiveShell(syntheticStep, { userExplicitTestIntent });
|
|
258
|
+
if (det08) return makeBlockPayload(det08);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
if (/^(edit_file|write_file|write_to_file|replace_file_content|multi_replace_file_content|run_command|execute_bash|bash|powershell)$/i.test(toolName)) {
|
|
262
|
+
if (resolveDetectorOverride(horizonConfig, 'DET-18') !== 'off') {
|
|
263
|
+
const det18 = evaluateDet18UntrustedWorkspaceSettings(syntheticStep, {
|
|
264
|
+
workspacePath,
|
|
265
|
+
scanWorkspace: false
|
|
266
|
+
});
|
|
267
|
+
if (det18) return makeBlockPayload(det18);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Non-Ring-0 Guardrails (DET-09 warm-cache rule fence, DET-20 concurrent scope lock collision, Two-Stage Prompt Hygiene)
|
|
272
|
+
let gateSystemMessage = null;
|
|
273
|
+
if (!isOffMode) {
|
|
274
|
+
const scopeOverride = resolveDetectorOverride(horizonConfig, 'vague-prompt-rubric');
|
|
275
|
+
const relayOverride = resolveDetectorOverride(horizonConfig, 'relay-breaker');
|
|
276
|
+
const twoStage = evaluateTwoStageSightseeingIntercept({
|
|
277
|
+
toolName,
|
|
278
|
+
toolArgs: toolInput && typeof toolInput === 'object' ? toolInput : {},
|
|
279
|
+
unanchoredTurnFlag: Boolean(inputData.unanchoredTurnFlag ?? sidecar.sessionMeta?.unanchoredTurnFlag),
|
|
280
|
+
candidateFiles: Array.isArray(inputData.candidateFiles)
|
|
281
|
+
? inputData.candidateFiles
|
|
282
|
+
: (sidecar.fileState?.modifiedFiles || sidecar.fileState?.activeSetPaths || []),
|
|
283
|
+
relayState: inputData.relayState ?? sidecar.sessionMeta?.relayState,
|
|
284
|
+
overrideMode: scopeOverride !== 'default' ? scopeOverride : relayOverride,
|
|
285
|
+
flightMode,
|
|
286
|
+
detectorId: 'DET-26'
|
|
287
|
+
});
|
|
288
|
+
if (twoStage.intercepted) {
|
|
289
|
+
if (twoStage.consumeFlag && sidecar.sessionMeta) {
|
|
290
|
+
sidecar.sessionMeta.unanchoredTurnFlag = false;
|
|
291
|
+
sidecar.sessionMeta.sightseeingToolsPrevented = Number(sidecar.sessionMeta.sightseeingToolsPrevented || 0) + 1;
|
|
292
|
+
try {
|
|
293
|
+
writeSidecarAtomicSync(conversationId, sidecar);
|
|
294
|
+
} catch (err) {
|
|
295
|
+
recordHookDiagnostic('pre_invocation', 'twoStage.writeSidecar', err);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
if (twoStage.decision === 'deny') {
|
|
299
|
+
return makeBlockPayload({ id: twoStage.detectorId, message: twoStage.reason });
|
|
300
|
+
}
|
|
301
|
+
if (!isSilentMode) gateSystemMessage = twoStage.reason;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Item A0: Unify shared DET-04 3-Strike Consecutive Tool Failure Breaker in handlePreToolUse
|
|
305
|
+
if (resolveDetectorOverride(horizonConfig, 'DET-04') !== 'off' && sidecar.portfolio?.failureStreaks) {
|
|
306
|
+
const currentTurnNum = Math.max(1, Number(inputData.turn ?? sidecar.sessionMeta?.turnCount ?? 1));
|
|
307
|
+
const det04 = evaluateDet04ConsecutiveFailureBreaker({
|
|
308
|
+
toolName,
|
|
309
|
+
toolArgs: toolInput && typeof toolInput === 'object' ? toolInput : {},
|
|
310
|
+
failureStreaks: sidecar.portfolio.failureStreaks,
|
|
311
|
+
currentTurn: currentTurnNum,
|
|
312
|
+
lastAlertTurnByKey: sidecar.portfolio.lastAlertTurnByKey || {},
|
|
313
|
+
cooldownTurns: 3,
|
|
314
|
+
flightMode
|
|
315
|
+
});
|
|
316
|
+
if (det04.triggered) {
|
|
317
|
+
if (det04.decision === 'deny') {
|
|
318
|
+
return makeBlockPayload({ id: 'DET-04', message: det04.reason });
|
|
319
|
+
}
|
|
320
|
+
if (!isSilentMode && !gateSystemMessage && det04.reason) gateSystemMessage = det04.reason;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// Item A0: Validate define_subagent tools: array against known Antigravity tool names
|
|
325
|
+
if (toolName === 'define_subagent') {
|
|
326
|
+
const rawTools = toolInput?.tools ?? toolInput?.Tools;
|
|
327
|
+
if (Array.isArray(rawTools) && rawTools.length > 0) {
|
|
328
|
+
const invalidTools = rawTools
|
|
329
|
+
.map((t) => String(t || '').trim().replace(/^default_api:/, ''))
|
|
330
|
+
.filter((t) => t && !KNOWN_ANTIGRAVITY_TOOL_NAMES.has(t) && !t.startsWith('mcp_'));
|
|
331
|
+
if (invalidTools.length > 0) {
|
|
332
|
+
const invalidMsg = `[DET-16 Subagent Tool Validation] Unknown tool name(s) in define_subagent (${invalidTools.join(', ')}). Invalid names are silently stripped by the host; use canonical Antigravity tool names or EnableWriteTools/EnableMCPTools.`;
|
|
333
|
+
if (isAutoPilotMode) return makeBlockPayload({ id: 'DET-16', message: invalidMsg });
|
|
334
|
+
if (!isSilentMode && !gateSystemMessage) gateSystemMessage = invalidMsg;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Item A0 + #10: Guard Monitor / IsDaemon shell commands lacking bounds & track active background tasks
|
|
340
|
+
if (toolName === 'Monitor') {
|
|
341
|
+
const hasTimeout = Number.isFinite(Number(toolInput?.timeout_ms ?? toolInput?.timeoutMs));
|
|
342
|
+
const hasFilter = Boolean(toolInput?.filter || toolInput?.pattern || toolInput?.regex);
|
|
343
|
+
if (!hasTimeout || !hasFilter) {
|
|
344
|
+
const monMsg = '[Highbeam Quota Shield — Unbounded Monitor (#10)] Monitor called without explicit timeout_ms and filter; stream bursts can flood main-thread context.';
|
|
345
|
+
if (isAutoPilotMode) return makeBlockPayload({ id: 'DET-07', message: monMsg });
|
|
346
|
+
if (!isSilentMode && !gateSystemMessage) gateSystemMessage = monMsg;
|
|
347
|
+
}
|
|
348
|
+
} else if (/^(run_command|execute_bash)$/i.test(toolName) && Boolean(toolInput?.IsDaemon)) {
|
|
349
|
+
sidecar.sessionMeta = sidecar.sessionMeta || {};
|
|
350
|
+
const bgList = Array.isArray(sidecar.sessionMeta.activeBackgroundTasks)
|
|
351
|
+
? sidecar.sessionMeta.activeBackgroundTasks
|
|
352
|
+
: [];
|
|
353
|
+
const label = String(toolInput?.toolSummary || toolInput?.CommandLine || 'daemon_task').slice(0, 60);
|
|
354
|
+
if (!bgList.includes(label)) bgList.push(label);
|
|
355
|
+
sidecar.sessionMeta.activeBackgroundTasks = bgList.slice(-16);
|
|
356
|
+
} else if (toolName === 'manage_task' && String(toolInput?.Action || '').toLowerCase() === 'kill') {
|
|
357
|
+
if (Array.isArray(sidecar.sessionMeta?.activeBackgroundTasks)) {
|
|
358
|
+
const killedId = String(toolInput?.TaskId || '').trim();
|
|
359
|
+
sidecar.sessionMeta.activeBackgroundTasks = killedId
|
|
360
|
+
? sidecar.sessionMeta.activeBackgroundTasks.filter((t) => t !== killedId)
|
|
361
|
+
: [];
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// Item A3 (#7): Parameterized Pricing Cliff Breaker (Haiku 100K 5x + Gemini 3.1/2.5 Pro 200K 2x/1.5x)
|
|
366
|
+
const det12Mode = resolveDetectorOverride(horizonConfig, 'DET-12');
|
|
367
|
+
if (det12Mode !== 'off') {
|
|
368
|
+
const cliffEval = evaluateParameterizedCliffBreaker({
|
|
369
|
+
modelId:
|
|
370
|
+
inputData.modelName ||
|
|
371
|
+
sidecar.sessionMeta?.active_model_id ||
|
|
372
|
+
sidecar.sessionMeta?.activeModel ||
|
|
373
|
+
'',
|
|
374
|
+
totalInputTokens: Number(
|
|
375
|
+
inputData.totalPromptTokens ??
|
|
376
|
+
inputData.totalInputTokens ??
|
|
377
|
+
sidecar.telemetry?.totalInputTokens ??
|
|
378
|
+
0
|
|
379
|
+
)
|
|
380
|
+
});
|
|
381
|
+
if (cliffEval.triggered) {
|
|
382
|
+
if (cliffEval.decision === 'deny' && (isAutoPilotMode || det12Mode === 'block')) {
|
|
383
|
+
return makeBlockPayload({ id: 'DET-12', message: cliffEval.reason });
|
|
384
|
+
}
|
|
385
|
+
if (!isSilentMode && !gateSystemMessage) {
|
|
386
|
+
gateSystemMessage = cliffEval.reason;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
if (!isOffMode && /^(?:default_api:)?(?:read_file|view_file)$/i.test(toolName)) {
|
|
392
|
+
const hasBounds =
|
|
393
|
+
toolInput?.StartLine !== undefined ||
|
|
394
|
+
toolInput?.EndLine !== undefined ||
|
|
395
|
+
toolInput?.offset !== undefined ||
|
|
396
|
+
toolInput?.limit !== undefined;
|
|
397
|
+
const rawReadTarget = String(
|
|
398
|
+
toolInput?.Path || toolInput?.AbsolutePath || toolInput?.file_path || toolInput?.path || ''
|
|
399
|
+
).trim();
|
|
400
|
+
|
|
401
|
+
// Item A8 (#14): Multimodal .ipynb Base64 Stripper & Unbounded >10-page .pdf Read Blocker
|
|
402
|
+
if (rawReadTarget && /\.(?:ipynb|pdf)$/i.test(rawReadTarget)) {
|
|
403
|
+
const mmRes = inspectAndSanitizeMultimodalRead({
|
|
404
|
+
platform: 'antigravity',
|
|
405
|
+
cwd: workspacePath,
|
|
406
|
+
filePath: rawReadTarget,
|
|
407
|
+
pages: toolInput?.pages,
|
|
408
|
+
hasPageBounds: hasBounds || toolInput?.pages !== undefined
|
|
409
|
+
});
|
|
410
|
+
if (mmRes.action === 'deny') {
|
|
411
|
+
return {
|
|
412
|
+
decision: 'deny',
|
|
413
|
+
permissionDecision: 'deny',
|
|
414
|
+
terminationBehavior: 'terminate',
|
|
415
|
+
blocked: true,
|
|
416
|
+
flightMode,
|
|
417
|
+
detectorId: mmRes.detectorId,
|
|
418
|
+
subType: mmRes.subType,
|
|
419
|
+
reason: mmRes.reason,
|
|
420
|
+
userMessage: mmRes.reason,
|
|
421
|
+
systemMessage: mmRes.reason,
|
|
422
|
+
sanitizedPath: mmRes.sanitizedPath || null,
|
|
423
|
+
pageCount: mmRes.pageCount || null,
|
|
424
|
+
savedTokens: mmRes.savedTokens || 0
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
if (!hasBounds && rawReadTarget) {
|
|
430
|
+
const shieldRes = evaluateShieldReadGuard({
|
|
431
|
+
platform: 'antigravity',
|
|
432
|
+
sessionId: conversationId,
|
|
433
|
+
cwd: workspacePath,
|
|
434
|
+
filePath: rawReadTarget,
|
|
435
|
+
hasSliceBounds: false,
|
|
436
|
+
currentPromptTokens: Number(
|
|
437
|
+
inputData.totalPromptTokens ?? sidecar.telemetry?.totalInputTokens ?? 0
|
|
438
|
+
),
|
|
439
|
+
modelId:
|
|
440
|
+
inputData.modelName ||
|
|
441
|
+
sidecar.sessionMeta?.active_model_id ||
|
|
442
|
+
sidecar.sessionMeta?.activeModel ||
|
|
443
|
+
'gemini-4-carbon',
|
|
444
|
+
shieldConfig: inputData.shieldConfig,
|
|
445
|
+
forceActive: Boolean(inputData.shieldForceActive),
|
|
446
|
+
recordLedger: inputData.recordLedger !== false
|
|
447
|
+
});
|
|
448
|
+
if (shieldRes.action === 'deny') {
|
|
449
|
+
return {
|
|
450
|
+
decision: 'deny',
|
|
451
|
+
permissionDecision: 'deny',
|
|
452
|
+
terminationBehavior: 'terminate',
|
|
453
|
+
blocked: true,
|
|
454
|
+
flightMode,
|
|
455
|
+
detectorId: shieldRes.detectorId,
|
|
456
|
+
reason: shieldRes.reason,
|
|
457
|
+
userMessage: shieldRes.reason,
|
|
458
|
+
systemMessage: shieldRes.reason,
|
|
459
|
+
indexPath: shieldRes.indexPath,
|
|
460
|
+
savedTokens: shieldRes.savedTokens,
|
|
461
|
+
savedUSD: shieldRes.savedUSD
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
if (!isOffMode && /^(edit_file|write_file|write_to_file|replace_file_content|multi_replace_file_content)$/i.test(toolName)) {
|
|
467
|
+
// Item A2 (#3) & Item A7 (#12): Test Integrity Lock + Standalone Silent Error-Masking Linter
|
|
468
|
+
const det03Mode = resolveDetectorOverride(horizonConfig, 'DET-03');
|
|
469
|
+
if (det03Mode !== 'off') {
|
|
470
|
+
const editTarget = String(
|
|
471
|
+
toolInput?.Path || toolInput?.path || toolInput?.TargetFile || toolInput?.AbsolutePath || ''
|
|
472
|
+
).trim();
|
|
473
|
+
const chunks = Array.isArray(toolInput?.ReplacementChunks) ? toolInput.ReplacementChunks : null;
|
|
474
|
+
let oldTxt = String(
|
|
475
|
+
toolInput?.Target ??
|
|
476
|
+
toolInput?.TargetContent ??
|
|
477
|
+
toolInput?.old_string ??
|
|
478
|
+
(chunks ? chunks.map((c) => c?.TargetContent ?? c?.Target ?? '').join('\n') : '') ??
|
|
479
|
+
''
|
|
480
|
+
);
|
|
481
|
+
if (!oldTxt && /^(write_file|write_to_file)$/i.test(toolName) && editTarget) {
|
|
482
|
+
try {
|
|
483
|
+
const absEdit = path.isAbsolute(editTarget)
|
|
484
|
+
? editTarget
|
|
485
|
+
: path.resolve(workspacePath, editTarget);
|
|
486
|
+
if (fs.existsSync(absEdit) && fs.statSync(absEdit).isFile()) {
|
|
487
|
+
oldTxt = fs.readFileSync(absEdit, 'utf8');
|
|
488
|
+
}
|
|
489
|
+
} catch {
|
|
490
|
+
oldTxt = '';
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
const newTxt = String(
|
|
494
|
+
toolInput?.Replacement ??
|
|
495
|
+
toolInput?.ReplacementContent ??
|
|
496
|
+
toolInput?.Content ??
|
|
497
|
+
toolInput?.CodeContent ??
|
|
498
|
+
toolInput?.new_string ??
|
|
499
|
+
(chunks ? chunks.map((c) => c?.ReplacementContent ?? c?.Replacement ?? '').join('\n') : '') ??
|
|
500
|
+
''
|
|
501
|
+
);
|
|
502
|
+
if (oldTxt || newTxt) {
|
|
503
|
+
const diffRes = evaluateDet05DiffThrashing({
|
|
504
|
+
filePath: editTarget,
|
|
505
|
+
oldText: oldTxt,
|
|
506
|
+
newText: newTxt,
|
|
507
|
+
toolName,
|
|
508
|
+
flightMode,
|
|
509
|
+
lastUserInput: effectivePromptText,
|
|
510
|
+
userExplicitTestIntent
|
|
511
|
+
});
|
|
512
|
+
if (diffRes.triggered && diffRes.decision === 'deny' && diffRes.subType !== 'SUDDEN_FILE_SHRINKAGE') {
|
|
513
|
+
if (det03Mode !== 'warn') {
|
|
514
|
+
return makeBlockPayload({ id: 'DET-03', message: diffRes.reason });
|
|
515
|
+
}
|
|
516
|
+
if (!isSilentMode && !gateSystemMessage) gateSystemMessage = diffRes.reason;
|
|
517
|
+
} else if (
|
|
518
|
+
diffRes.triggered &&
|
|
519
|
+
diffRes.subType === 'SUDDEN_FILE_SHRINKAGE' &&
|
|
520
|
+
/\.(?:test|spec)\.[a-z0-9]+$/i.test(editTarget) &&
|
|
521
|
+
!userExplicitTestIntent
|
|
522
|
+
) {
|
|
523
|
+
if (det03Mode !== 'warn') {
|
|
524
|
+
return makeBlockPayload({ id: 'DET-03', message: diffRes.reason });
|
|
525
|
+
}
|
|
526
|
+
if (!isSilentMode && !gateSystemMessage) gateSystemMessage = diffRes.reason;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
const det09Mode = resolveDetectorOverride(horizonConfig, 'DET-09');
|
|
532
|
+
if (det09Mode !== 'off') {
|
|
533
|
+
const det09 = evaluateDet09MidSessionRuleMutate(syntheticStep, {
|
|
534
|
+
cachedTokens: inputData.cachedTokens ?? sidecar.telemetry?.cachedTokens ?? sidecar.telemetry?.totalInputTokens ?? 0,
|
|
535
|
+
cacheTtlSeconds: inputData.cacheTtlSeconds ?? sidecar.telemetry?.cacheTtlSeconds ?? 300,
|
|
536
|
+
cacheState: inputData.cacheState
|
|
537
|
+
});
|
|
538
|
+
if (det09) {
|
|
539
|
+
if (isAutoPilotMode || det09Mode === 'block') return makeBlockPayload(det09);
|
|
540
|
+
if (!isSilentMode) gateSystemMessage = det09.message;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
const det20Mode = resolveDetectorOverride(horizonConfig, 'DET-20');
|
|
545
|
+
if (det20Mode !== 'off') {
|
|
546
|
+
const rawTarget = String(
|
|
547
|
+
toolInput?.Path || toolInput?.path || toolInput?.TargetFile || toolInput?.AbsolutePath || ''
|
|
548
|
+
).trim();
|
|
549
|
+
if (rawTarget) {
|
|
550
|
+
const relTarget = path.isAbsolute(rawTarget)
|
|
551
|
+
? path.relative(workspacePath, rawTarget).replace(/\\/g, '/')
|
|
552
|
+
: rawTarget.replace(/\\/g, '/');
|
|
553
|
+
const activeLeases = Array.isArray(inputData.activeLeases)
|
|
554
|
+
? inputData.activeLeases
|
|
555
|
+
: loadRegistry(workspacePath).leases;
|
|
556
|
+
const det20 = evaluateDet20ScopeCollision([], {
|
|
557
|
+
currentTrajectoryId: conversationId,
|
|
558
|
+
claimedPaths: [relTarget],
|
|
559
|
+
activeLeases,
|
|
560
|
+
workspaceDir: workspacePath
|
|
561
|
+
});
|
|
562
|
+
if (det20) {
|
|
563
|
+
if (isAutoPilotMode || det20Mode === 'block') return makeBlockPayload(det20);
|
|
564
|
+
if (!isSilentMode && !gateSystemMessage) gateSystemMessage = det20.message;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
if (!isOffMode && inputData.bucketBShadow !== false) {
|
|
571
|
+
try {
|
|
572
|
+
const hasExplicitCwd = Boolean(inputData.cwd || inputData.workspacePath);
|
|
573
|
+
const priorUnverifiedEdits = Array.isArray(inputData.editsSinceVerify)
|
|
574
|
+
? inputData.editsSinceVerify
|
|
575
|
+
: Array.isArray(sidecar.fileState?.unverifiedEdits)
|
|
576
|
+
? sidecar.fileState.unverifiedEdits
|
|
577
|
+
: [];
|
|
578
|
+
const shadowRes = runBucketBPreToolShadowPass({
|
|
579
|
+
platform: 'antigravity',
|
|
580
|
+
sessionId: conversationId,
|
|
581
|
+
cwd: workspacePath,
|
|
582
|
+
hasExplicitCwd,
|
|
583
|
+
toolName,
|
|
584
|
+
toolInput: toolInput && typeof toolInput === 'object' ? toolInput : {},
|
|
585
|
+
lastUserPrompt: effectivePromptText,
|
|
586
|
+
editsSinceVerify: priorUnverifiedEdits,
|
|
587
|
+
options: {
|
|
588
|
+
bucketBStage: inputData.bucketBStage,
|
|
589
|
+
bucketBAlphaStage: inputData.bucketBAlphaStage,
|
|
590
|
+
bucketBBetaStage: inputData.bucketBBetaStage,
|
|
591
|
+
bucketBGammaStage: inputData.bucketBGammaStage,
|
|
592
|
+
bucketBLspStage: inputData.bucketBLspStage,
|
|
593
|
+
persistState: inputData.persistState,
|
|
594
|
+
mode: flightMode,
|
|
595
|
+
registryMetadata: inputData.registryMetadata,
|
|
596
|
+
cliCapabilities: inputData.cliCapabilities,
|
|
597
|
+
lspCapabilities: inputData.lspCapabilities,
|
|
598
|
+
horizonConfig
|
|
599
|
+
}
|
|
600
|
+
});
|
|
601
|
+
if (shadowRes.triggered && shadowRes.activeRecords.length > 0) {
|
|
602
|
+
const blockingEntry = shadowRes.activeRecords.find(
|
|
603
|
+
(r) => r.stage === 'ENFORCE' || (isAutoPilotMode && r.verdict.decision === 'ask')
|
|
604
|
+
);
|
|
605
|
+
if (blockingEntry) {
|
|
606
|
+
return makeBlockPayload({
|
|
607
|
+
id: blockingEntry.verdict.code || 'BUCKET_B_GUARD',
|
|
608
|
+
message: blockingEntry.verdict.reason
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
if (!isSilentMode && !gateSystemMessage) {
|
|
612
|
+
gateSystemMessage = shadowRes.activeRecords
|
|
613
|
+
.map((r) => r.verdict.reason)
|
|
614
|
+
.filter(Boolean)
|
|
615
|
+
.join('\n');
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
} catch (err) {
|
|
619
|
+
recordHookDiagnostic('pre_invocation', 'handlePreToolUse.bucketBShadow', err, { persist: false });
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
if (
|
|
624
|
+
!isOffMode &&
|
|
625
|
+
/^(edit_file|write_file|write_to_file|replace_file_content|multi_replace_file_content)$/i.test(
|
|
626
|
+
toolName
|
|
627
|
+
)
|
|
628
|
+
) {
|
|
629
|
+
const editTarget = String(
|
|
630
|
+
toolInput?.Path || toolInput?.path || toolInput?.TargetFile || toolInput?.AbsolutePath || ''
|
|
631
|
+
).trim();
|
|
632
|
+
if (editTarget) {
|
|
633
|
+
const chunks = Array.isArray(toolInput?.ReplacementChunks) ? toolInput.ReplacementChunks : null;
|
|
634
|
+
const newTxt = String(
|
|
635
|
+
toolInput?.Replacement ??
|
|
636
|
+
toolInput?.ReplacementContent ??
|
|
637
|
+
toolInput?.Content ??
|
|
638
|
+
toolInput?.CodeContent ??
|
|
639
|
+
toolInput?.new_string ??
|
|
640
|
+
(chunks ? chunks.map((c) => c?.ReplacementContent ?? c?.Replacement ?? '').join('\n') : '') ??
|
|
641
|
+
''
|
|
642
|
+
);
|
|
643
|
+
const oldTxt = String(
|
|
644
|
+
toolInput?.Target ??
|
|
645
|
+
toolInput?.TargetContent ??
|
|
646
|
+
toolInput?.old_string ??
|
|
647
|
+
(chunks ? chunks.map((c) => c?.TargetContent ?? c?.Target ?? '').join('\n') : '') ??
|
|
648
|
+
''
|
|
649
|
+
);
|
|
650
|
+
const changedLines = newTxt.split(/\r?\n/);
|
|
651
|
+
const netLines = changedLines.filter((l) => l.trim().length > 0).length;
|
|
652
|
+
const deletedLineCount = oldTxt ? oldTxt.split(/\r?\n/).length : 0;
|
|
653
|
+
if (!sidecar.fileState || typeof sidecar.fileState !== 'object') sidecar.fileState = {};
|
|
654
|
+
if (!Array.isArray(sidecar.fileState.unverifiedEdits)) sidecar.fileState.unverifiedEdits = [];
|
|
655
|
+
sidecar.fileState.unverifiedEdits.push({
|
|
656
|
+
filePath: editTarget,
|
|
657
|
+
netLines,
|
|
658
|
+
changedLines: changedLines.slice(0, 64)
|
|
659
|
+
});
|
|
660
|
+
if (sidecar.fileState.unverifiedEdits.length > 32) {
|
|
661
|
+
sidecar.fileState.unverifiedEdits = sidecar.fileState.unverifiedEdits.slice(-32);
|
|
662
|
+
}
|
|
663
|
+
if (!Array.isArray(sidecar.fileState.turnFileDiffs)) sidecar.fileState.turnFileDiffs = [];
|
|
664
|
+
sidecar.fileState.turnFileDiffs.push({
|
|
665
|
+
filePath: editTarget,
|
|
666
|
+
addedLines: newTxt ? changedLines.slice(0, 400) : [],
|
|
667
|
+
deletedLineCount
|
|
668
|
+
});
|
|
669
|
+
if (sidecar.fileState.turnFileDiffs.length > 32) {
|
|
670
|
+
sidecar.fileState.turnFileDiffs = sidecar.fileState.turnFileDiffs.slice(-32);
|
|
671
|
+
}
|
|
672
|
+
if (effectivePromptText) {
|
|
673
|
+
sidecar.sessionMeta.lastUserPrompt = effectivePromptText;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
const nowMs = inputData.nowMs ?? inputData.eventTimestampUtc ?? Date.now();
|
|
679
|
+
const eventTimestampUtc = inputData.eventTimestampUtc ?? nowMs;
|
|
680
|
+
const serviceTier = inputData.serviceTier || 'standard';
|
|
681
|
+
const tracker = new SwarmIdleTtlTracker({
|
|
682
|
+
initialRoster: inputData.swarmRoster || sidecar.swarmRoster,
|
|
683
|
+
cacheTtlMs: inputData.cacheTtlMs ?? 300000,
|
|
684
|
+
coldWakeThresholdTokens: inputData.coldWakeThresholdTokens ?? 100000
|
|
685
|
+
});
|
|
686
|
+
|
|
687
|
+
let coldCacheWakeup = null;
|
|
688
|
+
let systemMessage = gateSystemMessage;
|
|
689
|
+
let astSignatureStub = null;
|
|
690
|
+
let deltaDiffStub = null;
|
|
691
|
+
let astStubSavedTokens = 0;
|
|
692
|
+
|
|
693
|
+
if (!isOffMode && (toolName === 'read_file' || toolName === 'Read' || toolName === 'view_file')) {
|
|
694
|
+
const rawTarget = String(
|
|
695
|
+
toolInput?.Path || toolInput?.path || toolInput?.file_path || toolInput?.TargetFile || toolInput?.AbsolutePath || ''
|
|
696
|
+
).trim();
|
|
697
|
+
const hasLineBounds = Number.isFinite(Number(toolInput?.StartLine ?? toolInput?.start_line ?? toolInput?.offset)) ||
|
|
698
|
+
Number.isFinite(Number(toolInput?.EndLine ?? toolInput?.end_line ?? toolInput?.limit));
|
|
699
|
+
if (rawTarget && !hasLineBounds) {
|
|
700
|
+
const resolvedPath = path.isAbsolute(rawTarget) ? rawTarget : path.resolve(workspacePath, rawTarget);
|
|
701
|
+
const normKey = resolvedPath.replace(/\\/g, '/').toLowerCase();
|
|
702
|
+
if (!sidecar.fileState || typeof sidecar.fileState !== 'object') sidecar.fileState = {};
|
|
703
|
+
if (!sidecar.fileState.unclippedReadCounts || typeof sidecar.fileState.unclippedReadCounts !== 'object') {
|
|
704
|
+
sidecar.fileState.unclippedReadCounts = {};
|
|
705
|
+
}
|
|
706
|
+
if (!sidecar.fileState.readSnapshots || typeof sidecar.fileState.readSnapshots !== 'object') {
|
|
707
|
+
sidecar.fileState.readSnapshots = {};
|
|
708
|
+
}
|
|
709
|
+
const priorReads = Number(inputData.priorUnclippedReads ?? sidecar.fileState.unclippedReadCounts[normKey] ?? 0);
|
|
710
|
+
const nextReads = priorReads + 1;
|
|
711
|
+
sidecar.fileState.unclippedReadCounts[normKey] = nextReads;
|
|
712
|
+
|
|
713
|
+
if (fs.existsSync(resolvedPath)) {
|
|
714
|
+
try {
|
|
715
|
+
const stat = fs.statSync(resolvedPath);
|
|
716
|
+
if (stat.isFile() && stat.size > 256 && stat.size <= 512 * 1024) {
|
|
717
|
+
const rawContent = fs.readFileSync(resolvedPath, 'utf8');
|
|
718
|
+
const prevSnap = typeof inputData.priorContentSnapshot === 'string'
|
|
719
|
+
? inputData.priorContentSnapshot
|
|
720
|
+
: (typeof sidecar.fileState.readSnapshots[normKey] === 'string' ? sidecar.fileState.readSnapshots[normKey] : null);
|
|
721
|
+
|
|
722
|
+
if (prevSnap !== null && prevSnap !== rawContent) {
|
|
723
|
+
const delta = computeCompactLineDiff(prevSnap, rawContent, path.basename(resolvedPath));
|
|
724
|
+
if (delta.wasDiffed) {
|
|
725
|
+
deltaDiffStub = delta.diffText;
|
|
726
|
+
astStubSavedTokens = delta.savedTokens;
|
|
727
|
+
const deltaNotice = `[Highbeam Post-Edit Delta Read — ${path.basename(resolvedPath)} (+${delta.savedTokens} tokens saved)]\n${delta.diffText}`;
|
|
728
|
+
if (!isSilentMode && !systemMessage) {
|
|
729
|
+
systemMessage = deltaNotice;
|
|
730
|
+
}
|
|
731
|
+
try {
|
|
732
|
+
recordAntigravitySidecarSavings(sidecar, {
|
|
733
|
+
category: 'BOUNDED_READ_ENFORCED',
|
|
734
|
+
savedTokens: delta.savedTokens,
|
|
735
|
+
detail: `Post-edit delta read for ${path.basename(resolvedPath)}`,
|
|
736
|
+
nowMs: inputData.nowMs ?? inputData.eventTimestampUtc ?? Date.now()
|
|
737
|
+
});
|
|
738
|
+
} catch (err) {
|
|
739
|
+
recordHookDiagnostic('pre_invocation', 'handlePreToolUse.recordDeltaSavings', err);
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
} else if (nextReads >= 3 && stat.size > 512) {
|
|
743
|
+
const fullTokens = Math.max(1, Math.ceil(rawContent.length / 4));
|
|
744
|
+
const folded = foldCodeToSignatureStub(rawContent, resolvedPath);
|
|
745
|
+
const stubText = typeof folded?.condensed === 'string' && folded.condensed.length > 0
|
|
746
|
+
? folded.condensed
|
|
747
|
+
: rawContent.slice(0, 1200);
|
|
748
|
+
const stubTokens = Math.max(1, Math.ceil(stubText.length / 4));
|
|
749
|
+
astStubSavedTokens = Math.max(0, fullTokens - stubTokens);
|
|
750
|
+
astSignatureStub = stubText;
|
|
751
|
+
const stubNotice = `[Highbeam AST Signature Stub — Read #${nextReads} of ${path.basename(resolvedPath)} (${astStubSavedTokens} tokens saved; pass StartLine/EndLine for full bodies)]\n${stubText}`;
|
|
752
|
+
if (!isSilentMode && !systemMessage) {
|
|
753
|
+
systemMessage = stubNotice;
|
|
754
|
+
}
|
|
755
|
+
if (astStubSavedTokens > 0) {
|
|
756
|
+
try {
|
|
757
|
+
recordAntigravitySidecarSavings(sidecar, {
|
|
758
|
+
category: 'BOUNDED_READ_ENFORCED',
|
|
759
|
+
savedTokens: astStubSavedTokens,
|
|
760
|
+
detail: `AST signature stub read #${nextReads} for ${path.basename(resolvedPath)}`,
|
|
761
|
+
nowMs: inputData.nowMs ?? inputData.eventTimestampUtc ?? Date.now()
|
|
762
|
+
});
|
|
763
|
+
} catch (err) {
|
|
764
|
+
recordHookDiagnostic('pre_invocation', 'handlePreToolUse.recordAstStubSavings', err);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
if (rawContent.length <= 128 * 1024) {
|
|
770
|
+
const snapKeys = Object.keys(sidecar.fileState.readSnapshots);
|
|
771
|
+
if (!sidecar.fileState.readSnapshots[normKey] && snapKeys.length >= 12) {
|
|
772
|
+
delete sidecar.fileState.readSnapshots[snapKeys[0]];
|
|
773
|
+
}
|
|
774
|
+
sidecar.fileState.readSnapshots[normKey] = rawContent;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
} catch (err) {
|
|
778
|
+
recordHookDiagnostic('pre_invocation', 'handlePreToolUse.astSignatureStub', err);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
if (toolName === 'send_message' || toolInput?.Recipient || toolInput?.recipient || /@[a-z0-9_-]+/i.test(String(toolInput?.Message || toolInput?.message || toolInput?.brief || ''))) {
|
|
785
|
+
coldCacheWakeup = tracker.handlePreToolSendMessage(toolInput, {
|
|
786
|
+
nowMs,
|
|
787
|
+
eventTimestampUtc,
|
|
788
|
+
serviceTier
|
|
789
|
+
});
|
|
790
|
+
if (coldCacheWakeup.coldWakeDetected) {
|
|
791
|
+
if (isAutoPilotMode && !inputData.allowColdWake && Number(coldCacheWakeup.incrementalColdPenaltyUsd || 0) >= 0.5) {
|
|
792
|
+
return {
|
|
793
|
+
decision: 'block',
|
|
794
|
+
permissionDecision: 'deny',
|
|
795
|
+
terminationBehavior: 'terminate',
|
|
796
|
+
blocked: true,
|
|
797
|
+
flightMode,
|
|
798
|
+
autoPilotGate: 'COLD_CACHE_CLIFF_HOLD',
|
|
799
|
+
coldCacheWakeup,
|
|
800
|
+
reason: coldCacheWakeup.message,
|
|
801
|
+
userMessage: coldCacheWakeup.message,
|
|
802
|
+
systemMessage: coldCacheWakeup.message
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
if (!isSilentMode && !isOffMode) {
|
|
806
|
+
systemMessage = coldCacheWakeup.message;
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
} else if (toolName === 'invoke_subagent' || toolName === 'define_subagent' || toolName === 'swarm') {
|
|
810
|
+
// Item A9 (#18): Concurrent Multi-Agent Worktree Isolation Guard (`Workspace: "branch" | "share"`)
|
|
811
|
+
if (
|
|
812
|
+
!isOffMode &&
|
|
813
|
+
(toolName === 'invoke_subagent' ||
|
|
814
|
+
(toolName === 'swarm' && String(toolInput?.action || '').toLowerCase() === 'add'))
|
|
815
|
+
) {
|
|
816
|
+
const subType = String(toolInput?.TypeName || toolInput?.name || '').trim().toLowerCase();
|
|
817
|
+
const isReadOnlySub =
|
|
818
|
+
subType === 'research' || subType === 'ah-flash-scout' || subType === 'browser';
|
|
819
|
+
const wsMode = String(toolInput?.Workspace || toolInput?.workspace || 'inherit')
|
|
820
|
+
.trim()
|
|
821
|
+
.toLowerCase();
|
|
822
|
+
if (!isReadOnlySub && wsMode !== 'branch' && wsMode !== 'share') {
|
|
823
|
+
const activeLeasesCount = Array.isArray(inputData.activeLeases)
|
|
824
|
+
? inputData.activeLeases.length
|
|
825
|
+
: loadRegistry(workspacePath).leases.length;
|
|
826
|
+
const activeRosterCount = Object.values(tracker.getRosterSnapshot() || {}).filter(
|
|
827
|
+
(a) => a && a.status !== 'terminated' && !/^(research|ah-flash-scout|browser)$/i.test(String(a.id || ''))
|
|
828
|
+
).length;
|
|
829
|
+
const concurrentWriters = Math.max(
|
|
830
|
+
activeLeasesCount,
|
|
831
|
+
activeRosterCount,
|
|
832
|
+
Number(inputData.activeWriteWorkers ?? 0)
|
|
833
|
+
);
|
|
834
|
+
if (concurrentWriters >= 1 && resolveDetectorOverride(horizonConfig, 'DET-20') !== 'off') {
|
|
835
|
+
const wtMsg =
|
|
836
|
+
`[DET-20 Worktree Isolation Guard (#18)] Spawning write-capable ${toolName} with Workspace: "${wsMode}" while ${concurrentWriters} write worker(s)/lease(s) are already active risks shared-tree clobbering. Set Workspace: "branch" or "share".`;
|
|
837
|
+
if (isAutoPilotMode || resolveDetectorOverride(horizonConfig, 'DET-20') === 'block') {
|
|
838
|
+
return makeBlockPayload({ id: 'DET-20', message: wtMsg });
|
|
839
|
+
}
|
|
840
|
+
if (!isSilentMode && !systemMessage) systemMessage = wtMsg;
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
if (toolName === 'invoke_subagent' || toolName === 'define_subagent') {
|
|
845
|
+
const subagentId = toolInput?.ConversationId || toolInput?.conversationId || toolInput?.Name || toolInput?.TypeName || toolInput?.Role || 'subagent';
|
|
846
|
+
const subagentModel = toolInput?.Model && toolInput.Model !== 'inherit'
|
|
847
|
+
? toolInput.Model
|
|
848
|
+
: (sidecar.sessionMeta.active_model_id || sidecar.sessionMeta.activeModel || 'gemini-4-carbon');
|
|
849
|
+
tracker.touchAgentActive(subagentId, {
|
|
850
|
+
modelId: subagentModel,
|
|
851
|
+
warmPrefixTokens: Number(toolInput?.warm_prefix_tokens ?? 0),
|
|
852
|
+
timestampMs: nowMs
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
} else if (toolName === 'manage_subagents') {
|
|
856
|
+
const action = String(toolInput?.Action || toolInput?.action || '').toLowerCase();
|
|
857
|
+
if (action === 'kill' && Array.isArray(toolInput?.ConversationIds)) {
|
|
858
|
+
for (const id of toolInput.ConversationIds) {
|
|
859
|
+
tracker.terminateAgent(id, { timestampMs: nowMs });
|
|
860
|
+
}
|
|
861
|
+
} else if (action === 'kill_all') {
|
|
862
|
+
for (const id of Object.keys(tracker.getRosterSnapshot())) {
|
|
863
|
+
tracker.terminateAgent(id, { timestampMs: nowMs });
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
sidecar.swarmRoster = tracker.getRosterSnapshot();
|
|
869
|
+
sidecar.swarmTtlBadges = computeSwarmRosterTtlBadges(sidecar.swarmRoster, {
|
|
870
|
+
nowMs,
|
|
871
|
+
cacheTtlMs: inputData.cacheTtlMs ?? 300000
|
|
872
|
+
});
|
|
873
|
+
|
|
874
|
+
try {
|
|
875
|
+
writeSidecarAtomicSync(conversationId, sidecar);
|
|
876
|
+
} catch (err) {
|
|
877
|
+
recordHookDiagnostic('pre_invocation', 'handlePreToolUse.writeSidecar', err);
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
const response = {
|
|
881
|
+
decision: 'allow',
|
|
882
|
+
flightMode,
|
|
883
|
+
active_model_id: sidecar.sessionMeta.active_model_id || sidecar.sessionMeta.activeModel || null,
|
|
884
|
+
pending_model_id: sidecar.sessionMeta.pending_model_id || null,
|
|
885
|
+
swarmTtlBadges: sidecar.swarmTtlBadges
|
|
886
|
+
};
|
|
887
|
+
if (coldCacheWakeup) response.coldCacheWakeup = coldCacheWakeup;
|
|
888
|
+
if (astSignatureStub) {
|
|
889
|
+
response.astSignatureStub = astSignatureStub;
|
|
890
|
+
response.savedTokens = astStubSavedTokens;
|
|
891
|
+
}
|
|
892
|
+
if (deltaDiffStub) {
|
|
893
|
+
response.deltaDiffStub = deltaDiffStub;
|
|
894
|
+
response.savedTokens = astStubSavedTokens;
|
|
895
|
+
}
|
|
896
|
+
if (systemMessage && !isSilentMode && !isOffMode) response.systemMessage = systemMessage;
|
|
897
|
+
return response;
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
export async function handlePreInvocation(inputData = {}) {
|
|
901
|
+
if (
|
|
902
|
+
inputData.hook_event_name === 'PreToolUse' ||
|
|
903
|
+
inputData.event === 'PreToolUse' ||
|
|
904
|
+
inputData.tool_name ||
|
|
905
|
+
inputData.toolName ||
|
|
906
|
+
inputData.tool_input ||
|
|
907
|
+
inputData.args ||
|
|
908
|
+
inputData.parameters ||
|
|
909
|
+
inputData.Arguments ||
|
|
910
|
+
(typeof inputData.tool === 'string' && inputData.tool.length > 0) ||
|
|
911
|
+
(typeof inputData.name === 'string' && !inputData.prompt && !inputData.user_input)
|
|
912
|
+
) {
|
|
913
|
+
return handlePreToolUse(inputData);
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
const config = inputData.configOverride || loadFlightcheckConfig();
|
|
917
|
+
const rawPrompt = String(inputData.prompt || inputData.user_input || inputData.message || '').trim();
|
|
918
|
+
const conversationId = inputData.conversationId || inputData.session_id || inputData.conversation_id || 'default_session';
|
|
919
|
+
const sidecar = readSidecarSync(conversationId);
|
|
920
|
+
const workspacePath = inputData.cwd || inputData.workspacePath || sidecar.workspacePath || process.cwd();
|
|
921
|
+
const horizonConfig = inputData.horizonConfig || loadHorizonConfig({
|
|
922
|
+
cwd: workspacePath,
|
|
923
|
+
...(inputData.homeDir ? { homeDir: inputData.homeDir } : {})
|
|
924
|
+
});
|
|
925
|
+
const flightMode = String(inputData.flightMode || horizonConfig.flightMode || 'COACH').toUpperCase();
|
|
926
|
+
|
|
927
|
+
// 1. Control Flags & flightMode Handling (ISS-039)
|
|
928
|
+
if (config.hook_level === 'off' || flightMode === 'OFF') {
|
|
929
|
+
return {};
|
|
930
|
+
}
|
|
931
|
+
if (flightMode === 'SILENT') {
|
|
932
|
+
// SILENT suppresses all non-Ring-0 advisory context/stderr chatter on PreInvocation
|
|
933
|
+
// (Ring-0 security blocks remain active in PreToolUse and workspace settings checks).
|
|
934
|
+
if (resolveDetectorOverride(horizonConfig, 'DET-18') !== 'off' && inputData.scanWorkspaceSettings === true) {
|
|
935
|
+
const det18 = evaluateDet18UntrustedWorkspaceSettings([], { workspacePath, scanWorkspace: true });
|
|
936
|
+
if (det18) {
|
|
937
|
+
return { terminationBehavior: 'terminate', decision: 'block', detectorId: 'DET-18', userMessage: det18.message };
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
if (rawPrompt && (inputData.cwd || inputData.workspacePath) && inputData.bucketBShadow !== false) {
|
|
941
|
+
try {
|
|
942
|
+
const silentFileState = sidecar.fileState || {};
|
|
943
|
+
const silentSessionMeta = sidecar.sessionMeta || {};
|
|
944
|
+
const isAutonomousOrSubagent = Boolean(
|
|
945
|
+
inputData.isAutonomousTurn ||
|
|
946
|
+
inputData.autonomous ||
|
|
947
|
+
inputData.isSubagent ||
|
|
948
|
+
silentSessionMeta.isSubagent ||
|
|
949
|
+
inputData.isScheduledTask ||
|
|
950
|
+
inputData.isLoopIteration ||
|
|
951
|
+
/^(?:scheduled|cron|loop|subagent|agent_callback|callback|auto|autonomous|background|system|hook|task_notification|wake)$/i.test(
|
|
952
|
+
String(inputData.provenance || inputData.source || '')
|
|
953
|
+
)
|
|
954
|
+
);
|
|
955
|
+
const cachedDirtyFiles = Array.isArray(inputData.cachedDirtyFiles)
|
|
956
|
+
? inputData.cachedDirtyFiles
|
|
957
|
+
: [
|
|
958
|
+
...(silentFileState.modifiedFiles || []),
|
|
959
|
+
...(Array.isArray(silentFileState.unverifiedEdits)
|
|
960
|
+
? silentFileState.unverifiedEdits.map((e) => e?.filePath)
|
|
961
|
+
: [])
|
|
962
|
+
];
|
|
963
|
+
runBucketBPromptPass({
|
|
964
|
+
platform: 'antigravity',
|
|
965
|
+
sessionId: conversationId,
|
|
966
|
+
cwd: workspacePath,
|
|
967
|
+
hasExplicitCwd: true,
|
|
968
|
+
prompt: rawPrompt,
|
|
969
|
+
isAutonomousOrSubagent,
|
|
970
|
+
cachedDirtyFiles,
|
|
971
|
+
lastFailingLocation:
|
|
972
|
+
inputData.lastFailingLocation ?? silentSessionMeta.lastFailingLocation ?? '',
|
|
973
|
+
options: {
|
|
974
|
+
bucketBStage: inputData.bucketBStage,
|
|
975
|
+
bucketBGammaStage: inputData.bucketBGammaStage,
|
|
976
|
+
mode: 'SILENT',
|
|
977
|
+
horizonConfig
|
|
978
|
+
}
|
|
979
|
+
});
|
|
980
|
+
} catch (err) {
|
|
981
|
+
recordHookDiagnostic('pre_invocation', 'handlePreInvocation.silentPromptPass', err, { persist: false });
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
return {};
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
const sessionMeta = sidecar.sessionMeta || {};
|
|
988
|
+
const telemetry = sidecar.telemetry || {};
|
|
989
|
+
const sensors = sidecar.sensors || {};
|
|
990
|
+
const fileState = sidecar.fileState || {};
|
|
991
|
+
|
|
992
|
+
if (rawPrompt.includes('!lock')) {
|
|
993
|
+
sessionMeta.effortLocked = true;
|
|
994
|
+
sidecar.sessionMeta = sessionMeta;
|
|
995
|
+
try {
|
|
996
|
+
writeSidecarAtomicSync(conversationId, sidecar);
|
|
997
|
+
} catch (err) {
|
|
998
|
+
recordHookDiagnostic('pre_invocation', 'effortLock.writeSidecar', err);
|
|
999
|
+
}
|
|
1000
|
+
return {};
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
if (rawPrompt.startsWith('! ') || rawPrompt === '!' || rawPrompt.startsWith('!force')) {
|
|
1004
|
+
return {};
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
const hasCheckTag = /#check\b/i.test(rawPrompt);
|
|
1008
|
+
const turnCount = sessionMeta.turnCount || 0;
|
|
1009
|
+
const purity = telemetry.signalPurityPct ?? 100.0;
|
|
1010
|
+
const tokens = telemetry.totalInputTokens || 0;
|
|
1011
|
+
const activeEffort = inputData.effort || sessionMeta.activeEffort || 'high';
|
|
1012
|
+
const activeModel = inputData.modelName || sessionMeta.activeModel || (config.recommended_models?.fast || 'gemini-3.8-flash');
|
|
1013
|
+
const quotaFrac = telemetry.quota?.remaining_fraction ?? 1.0;
|
|
1014
|
+
const ceiling = resolveModelCeiling(activeModel, null, { config }) || 256000;
|
|
1015
|
+
const ceilingK = Math.round(ceiling / 1000);
|
|
1016
|
+
|
|
1017
|
+
// In AUTO_PILOT mode, enforce active guard halts even if legacy hook_level was 'advisory'
|
|
1018
|
+
const hookLevel = flightMode === 'AUTO_PILOT' ? 'guard' : (config.hook_level || 'guard');
|
|
1019
|
+
const cooldownTurns = config.halt_cooldown_turns ?? 3;
|
|
1020
|
+
const lastHalts = { ...(sessionMeta.lastHalts || {}) };
|
|
1021
|
+
const isTelemetryReliable = telemetry.confidence !== 'LOW';
|
|
1022
|
+
|
|
1023
|
+
function haltOrAdvise(stateKey, card, { exemptFromCooldown = false } = {}) {
|
|
1024
|
+
const lastFiredTurn = lastHalts[stateKey];
|
|
1025
|
+
const isWithinCooldown = typeof lastFiredTurn === 'number' && ((turnCount - lastFiredTurn) <= cooldownTurns);
|
|
1026
|
+
|
|
1027
|
+
if (hookLevel === 'advisory' || (isWithinCooldown && !exemptFromCooldown)) {
|
|
1028
|
+
return { systemMessage: card };
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
lastHalts[stateKey] = turnCount;
|
|
1032
|
+
sessionMeta.lastHalts = lastHalts;
|
|
1033
|
+
sidecar.sessionMeta = sessionMeta;
|
|
1034
|
+
try {
|
|
1035
|
+
writeSidecarAtomicSync(conversationId, sidecar);
|
|
1036
|
+
} catch (err) {
|
|
1037
|
+
recordHookDiagnostic('pre_invocation', 'haltOrAdvise.writeSidecar', err);
|
|
1038
|
+
}
|
|
1039
|
+
return { terminationBehavior: 'terminate', userMessage: card };
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
function applyHabitOverride(slug, stateKey, card, { detectorId = null, defaultMode = 'haltOrAdvise', extraWarn = {}, extraBlock = {} } = {}) {
|
|
1043
|
+
const override = resolveDetectorOverride(horizonConfig, slug);
|
|
1044
|
+
if (override === 'off') return null;
|
|
1045
|
+
if (override === 'warn') {
|
|
1046
|
+
return { systemMessage: card, ...(detectorId ? { detectorId } : {}), ...extraWarn };
|
|
1047
|
+
}
|
|
1048
|
+
if (override === 'block') {
|
|
1049
|
+
lastHalts[stateKey] = turnCount;
|
|
1050
|
+
sessionMeta.lastHalts = lastHalts;
|
|
1051
|
+
sidecar.sessionMeta = sessionMeta;
|
|
1052
|
+
try {
|
|
1053
|
+
writeSidecarAtomicSync(conversationId, sidecar);
|
|
1054
|
+
} catch (err) {
|
|
1055
|
+
recordHookDiagnostic('pre_invocation', 'applyHabitOverride.writeSidecar', err);
|
|
1056
|
+
}
|
|
1057
|
+
return {
|
|
1058
|
+
terminationBehavior: 'terminate',
|
|
1059
|
+
decision: 'block',
|
|
1060
|
+
...(detectorId ? { detectorId } : {}),
|
|
1061
|
+
userMessage: card,
|
|
1062
|
+
...extraBlock
|
|
1063
|
+
};
|
|
1064
|
+
}
|
|
1065
|
+
if (defaultMode === 'flightMode') {
|
|
1066
|
+
if (flightMode === 'AUTO_PILOT') {
|
|
1067
|
+
return {
|
|
1068
|
+
terminationBehavior: 'terminate',
|
|
1069
|
+
decision: 'block',
|
|
1070
|
+
...(detectorId ? { detectorId } : {}),
|
|
1071
|
+
userMessage: card,
|
|
1072
|
+
...extraBlock
|
|
1073
|
+
};
|
|
1074
|
+
}
|
|
1075
|
+
return { systemMessage: card, ...(detectorId ? { detectorId } : {}), ...extraWarn };
|
|
1076
|
+
}
|
|
1077
|
+
return haltOrAdvise(stateKey, card);
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
// 2. ALLOW_PLAN_OR_SUBAGENT
|
|
1081
|
+
if (!hasCheckTag && (sessionMeta.inPlanMode || sessionMeta.lastTurnUsedSubagent)) {
|
|
1082
|
+
if (!telemetry.amputationRisk && !sensors.threeStrikeLoop) {
|
|
1083
|
+
return {};
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
// 3. HALT_HYGIENE_OR_SAFETY
|
|
1088
|
+
sessionMeta.lastUserPrompt = rawPrompt;
|
|
1089
|
+
const isHighOrMaxEffort = activeEffort === 'high' || activeEffort === 'max';
|
|
1090
|
+
|
|
1091
|
+
// 3a.0 Item A6 (#11): Active DET-30 Thinking Runaway Step-Down Gate (>4,000 thinking tokens & >12x ratio across >=2 turns)
|
|
1092
|
+
if (resolveDetectorOverride(horizonConfig, 'DET-30') !== 'off') {
|
|
1093
|
+
const det30Check = evaluateActiveDet30StepDown({
|
|
1094
|
+
recentTurns: inputData.recentTurns || telemetry.recentTurns,
|
|
1095
|
+
thinkingDrift: inputData.thinkingDrift || telemetry.thinkingDrift || sensors.thinkingDrift,
|
|
1096
|
+
mode: flightMode
|
|
1097
|
+
});
|
|
1098
|
+
if (det30Check.triggered) {
|
|
1099
|
+
const det30Card = formatScorecard(
|
|
1100
|
+
det30Check.reason,
|
|
1101
|
+
`[Thinking Streak: ${det30Check.consecutiveTurns} turns | Ratio: ${det30Check.latestRatio}x]`,
|
|
1102
|
+
`Step down effort to medium or cap MAX_THINKING_TOKENS=16000`,
|
|
1103
|
+
`"Switch to medium effort before sending next prompt"`
|
|
1104
|
+
);
|
|
1105
|
+
const det30Res = applyHabitOverride('thinking-runaway', 'DET30_THINKING_STEPDOWN', det30Card, {
|
|
1106
|
+
detectorId: 'DET-30',
|
|
1107
|
+
defaultMode: 'flightMode'
|
|
1108
|
+
});
|
|
1109
|
+
if (det30Res) return det30Res;
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
// 3a. Item A3 (#7): Parameterized Pricing Cliff Breaker (Haiku 100K 5x + Gemini 3.1/2.5 Pro 200K 2x/1.5x)
|
|
1114
|
+
if (resolveDetectorOverride(horizonConfig, 'DET-12') !== 'off') {
|
|
1115
|
+
const cliffCheck = evaluateParameterizedCliffBreaker({
|
|
1116
|
+
modelId: activeModel,
|
|
1117
|
+
totalInputTokens: Number(inputData.totalInputTokens ?? inputData.totalPromptTokens ?? tokens)
|
|
1118
|
+
});
|
|
1119
|
+
if (cliffCheck.triggered) {
|
|
1120
|
+
if (cliffCheck.decision === 'deny') {
|
|
1121
|
+
const cliffCard = formatScorecard(
|
|
1122
|
+
cliffCheck.reason,
|
|
1123
|
+
`[Useful Context: ${purity}% | Cliff Threshold: ${Math.round(cliffCheck.cliffThresholdTokens / 1000)}k]`,
|
|
1124
|
+
`/compact or /clear`,
|
|
1125
|
+
`"Compact context before crossing the ${Math.round(cliffCheck.cliffThresholdTokens / 1000)}k stepped pricing cliff"`
|
|
1126
|
+
);
|
|
1127
|
+
return haltOrAdvise('PRICING_CLIFF_BREAKER', cliffCard, { exemptFromCooldown: true });
|
|
1128
|
+
}
|
|
1129
|
+
const advRes = applyHabitOverride('pricing-cliff', 'PRICING_CLIFF_ADVISORY', cliffCheck.reason, {
|
|
1130
|
+
detectorId: 'DET-12',
|
|
1131
|
+
defaultMode: 'warn'
|
|
1132
|
+
});
|
|
1133
|
+
if (advRes) return advRes;
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
// 3b. Item A1 (#1): Warm-Cache Mid-Session Model Switch Guard (Antigravity PreInvocation)
|
|
1138
|
+
const priorActiveModel = sessionMeta.active_model_id || sessionMeta.activeModel || null;
|
|
1139
|
+
if (
|
|
1140
|
+
inputData.modelName &&
|
|
1141
|
+
priorActiveModel &&
|
|
1142
|
+
turnCount >= 1 &&
|
|
1143
|
+
normalizeModelKey(inputData.modelName) !== normalizeModelKey(priorActiveModel)
|
|
1144
|
+
) {
|
|
1145
|
+
const cachedTok = Number(
|
|
1146
|
+
inputData.cachedTokens ?? telemetry.cachedTokens ?? telemetry.cacheReadTokens ?? tokens ?? 0
|
|
1147
|
+
);
|
|
1148
|
+
const cacheTtlSec = Number(inputData.cacheTtlSeconds ?? telemetry.cacheTtlSeconds ?? 300);
|
|
1149
|
+
if (cachedTok >= 25000 && cacheTtlSec > 0) {
|
|
1150
|
+
const prevRates = resolveModelRates(priorActiveModel, inputData.eventTimestampUtc, 'standard', {
|
|
1151
|
+
totalPromptTokens: cachedTok
|
|
1152
|
+
});
|
|
1153
|
+
const nextRates = resolveModelRates(inputData.modelName, inputData.eventTimestampUtc, 'standard', {
|
|
1154
|
+
totalPromptTokens: cachedTok
|
|
1155
|
+
});
|
|
1156
|
+
const coldPenaltyUsd =
|
|
1157
|
+
(cachedTok / 1_000_000) * Math.max(0, nextRates.write5m - prevRates.cachedRead);
|
|
1158
|
+
const outputDeltaSavingUsd =
|
|
1159
|
+
(1500 / 1_000_000) * Math.max(0, prevRates.output - nextRates.output);
|
|
1160
|
+
if (coldPenaltyUsd > outputDeltaSavingUsd && coldPenaltyUsd >= 0.03) {
|
|
1161
|
+
const bustCard = formatScorecard(
|
|
1162
|
+
`[DET-08 Warm-Cache Model Switch] ${normalizeModelKey(priorActiveModel)} -> ${normalizeModelKey(inputData.modelName)} on ${Math.round(cachedTok / 1000)}k warm prefix`,
|
|
1163
|
+
`[Cold Cache Penalty: +$${coldPenaltyUsd.toFixed(3)} vs $${outputDeltaSavingUsd.toFixed(3)} output saving]`,
|
|
1164
|
+
`Stay on ${normalizeModelKey(priorActiveModel)} or delegate via invoke_subagent`,
|
|
1165
|
+
`"Keep main thread on ${normalizeModelKey(priorActiveModel)} until /compact, or use invoke_subagent"`
|
|
1166
|
+
);
|
|
1167
|
+
const bustRes = applyHabitOverride('mid-session-model-switch', 'MID_SESSION_CACHE_BUST', bustCard, {
|
|
1168
|
+
detectorId: 'DET-08',
|
|
1169
|
+
defaultMode: 'flightMode'
|
|
1170
|
+
});
|
|
1171
|
+
if (bustRes) return bustRes;
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
if (telemetry.amputationRisk && isTelemetryReliable) {
|
|
1176
|
+
const handoff = sidecar.handoff || {};
|
|
1177
|
+
const handoffAction = handoff.result === 'NEEDS_FIXES'
|
|
1178
|
+
? `Handoff NEEDS FIXES: ${(handoff.failingChecks || []).slice(0, 2).join('; ') || 'update task.md'}`
|
|
1179
|
+
: `/clear or /compact`;
|
|
1180
|
+
const rewriteCmd = handoff.result === 'NEEDS_FIXES'
|
|
1181
|
+
? `"Update task.md checkpoint (/handoff), then type /compact or /clear"`
|
|
1182
|
+
: `"Save progress to task.md and start a clean session with /clear (or /compact)"`;
|
|
1183
|
+
|
|
1184
|
+
const card = formatScorecard(
|
|
1185
|
+
`[Amputation Crisis] Tokens: ${Math.round(tokens / 1000)}k/${ceilingK}k (Context Truncation Risk)`,
|
|
1186
|
+
`[Useful Context: ${purity}% | Oldest Rules at Risk]`,
|
|
1187
|
+
handoffAction,
|
|
1188
|
+
rewriteCmd
|
|
1189
|
+
);
|
|
1190
|
+
return haltOrAdvise('AMPUTATION_CRISIS', card, { exemptFromCooldown: true });
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
if (sensors.threeStrikeLoop) {
|
|
1194
|
+
const loopInfo = sensors.loopFingerprint
|
|
1195
|
+
? `Loop: ${sensors.loopFingerprint.slice(0, 48)}`
|
|
1196
|
+
: 'Consecutive command failures detected';
|
|
1197
|
+
const card = formatScorecard(
|
|
1198
|
+
`[3-Strike Error Loop] ${loopInfo}`,
|
|
1199
|
+
`[Useful Context: ${purity}% | Errors: 3 strikes]`,
|
|
1200
|
+
`Break loop: isolate with subagent or compact`,
|
|
1201
|
+
`"Diagnose previous errors using invoke_subagent or run /compact"`
|
|
1202
|
+
);
|
|
1203
|
+
return haltOrAdvise('THREE_STRIKE_LOOP', card);
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
if (fileState.foreignBleedKiIds && fileState.foreignBleedKiIds.length > 0 && sessionMeta.inPlanMode) {
|
|
1207
|
+
const card = formatScorecard(
|
|
1208
|
+
`[Foreign KI Bleed] Injected memory from other workspace`,
|
|
1209
|
+
`[Bleed IDs: ${fileState.foreignBleedKiIds.join(', ')}]`,
|
|
1210
|
+
`/context`,
|
|
1211
|
+
`"Eject foreign knowledge items in /context before planning"`
|
|
1212
|
+
);
|
|
1213
|
+
return haltOrAdvise('FOREIGN_BLEED', card);
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
if (isTelemetryReliable && purity < (config.compact_halt_purity_pct || 45.0) && isHighOrMaxEffort) {
|
|
1217
|
+
const card = formatScorecard(
|
|
1218
|
+
`[Low Useful Context] ${purity}% useful context on ${activeEffort} effort`,
|
|
1219
|
+
`[Wasted Context: +$${(telemetry.sludgeTaxUsdPerTurn || 0).toFixed(2)}/turn]`,
|
|
1220
|
+
`/compact`,
|
|
1221
|
+
`"Run /compact to compress stale reads before high-effort execution"`
|
|
1222
|
+
);
|
|
1223
|
+
return haltOrAdvise('LOW_PURITY', card);
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
if (sensors.uncheckpointedGitDrift) {
|
|
1227
|
+
const card = formatScorecard(
|
|
1228
|
+
`[Uncheckpointed Drift] ${sensors.dirtyGitFileCount || 4}+ dirty files untested`,
|
|
1229
|
+
`[Git Drift: >=3 turns without passing test]`,
|
|
1230
|
+
`git commit or run test`,
|
|
1231
|
+
`"Run unit tests and commit working changes before editing further"`
|
|
1232
|
+
);
|
|
1233
|
+
return haltOrAdvise('GIT_DRIFT', card);
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
// 4. HALT_EFFORT_OR_QUOTA
|
|
1237
|
+
const fastModel = config.recommended_models?.fast || 'gemini-3.8-flash';
|
|
1238
|
+
const deepModel = config.recommended_models?.deep || 'gemini-3.1-pro';
|
|
1239
|
+
|
|
1240
|
+
if (isTelemetryReliable && sensors.quotaFloorBreached && (activeModel.includes('pro') || activeModel.includes('argon') || activeModel.includes('carbon') || activeEffort === 'max')) {
|
|
1241
|
+
const card = formatScorecard(
|
|
1242
|
+
`[Quota Floor Breached] 5h Quota: ${Math.round(quotaFrac * 100)}% (<10%)`,
|
|
1243
|
+
`[Tokens: ${Math.round(tokens / 1000)}k | Risk: 0% lockout]`,
|
|
1244
|
+
`/model ${fastModel} • /effort low`,
|
|
1245
|
+
`"Switch to ${fastModel} on low effort to preserve remaining quota"`
|
|
1246
|
+
);
|
|
1247
|
+
return haltOrAdvise('QUOTA_FLOOR', card);
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
const promptTokenEst = Math.max(1, Math.ceil(rawPrompt.length / 4));
|
|
1251
|
+
const isColdCache = tokens < 10000;
|
|
1252
|
+
const isTrivial = promptTokenEst < 15;
|
|
1253
|
+
if (isTelemetryReliable && !sessionMeta.effortLocked && isTrivial && (sessionMeta.consecutiveTrivialOnMax >= 2 || (isColdCache && (activeModel.includes('pro') || activeModel.includes('argon') || activeModel.includes('carbon')) && activeEffort === 'max'))) {
|
|
1254
|
+
const card = formatScorecard(
|
|
1255
|
+
`[Effort Overkill] Trivial edit (${promptTokenEst} tokens) on max effort`,
|
|
1256
|
+
`[Cold cache / trivial turn]`,
|
|
1257
|
+
`/model ${fastModel} • /effort low`,
|
|
1258
|
+
`"Run trivial single-file edit on ${fastModel} / low effort"`
|
|
1259
|
+
);
|
|
1260
|
+
const effortRes = applyHabitOverride('effort-overkill', 'EFFORT_OVERKILL', card);
|
|
1261
|
+
if (effortRes) return effortRes;
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
// 4b. Local Formatter / Import Sorter Bypass (DET-15 / 'formatter-bypass')
|
|
1265
|
+
const isFormattingIntent = /\b(fix\s+(?:the\s+)?indentation|sort\s+(?:the\s+)?imports|format\s+this\s+(?:code|file|block)|convert\s+tabs\s+to\s+spaces|run\s+prettier)\b/i.test(rawPrompt);
|
|
1266
|
+
const pastedLineCount = (rawPrompt.match(/\r?\n/g) || []).length;
|
|
1267
|
+
if (isFormattingIntent && pastedLineCount >= 40 && !/\b(add|implement|refactor|create|fix\s+bug|logic|test|calculate)\b/i.test(rawPrompt)) {
|
|
1268
|
+
const bypassNotice = '[DET-15 Local Formatter Bypass] Prompt requests code formatting / import sorting on a pasted code block. Run `npx prettier --write <file>` or `npx eslint --fix <file>` directly (0 LLM tokens).';
|
|
1269
|
+
const fmtRes = applyHabitOverride('formatter-bypass', 'LOCAL_FORMATTER_BYPASS', bypassNotice, {
|
|
1270
|
+
detectorId: 'DET-15',
|
|
1271
|
+
defaultMode: 'flightMode'
|
|
1272
|
+
});
|
|
1273
|
+
if (fmtRes) return fmtRes;
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
// 5. INJECT_CONTEXT_GUARD
|
|
1277
|
+
const guards = [];
|
|
1278
|
+
const eventTimestampUtc = inputData.eventTimestampUtc ?? null;
|
|
1279
|
+
if (isModelDeprecated(activeModel, eventTimestampUtc)) {
|
|
1280
|
+
const notice = getDeprecatedModelMigrationNotice(activeModel, eventTimestampUtc);
|
|
1281
|
+
if (notice) guards.push(notice);
|
|
1282
|
+
}
|
|
1283
|
+
const recentTurns = inputData.recentTurns || sidecar.recentTurns || [];
|
|
1284
|
+
if (Array.isArray(recentTurns) && recentTurns.length >= 2) {
|
|
1285
|
+
const verbosityGuard = evaluateCarbonVerbosityGuardrail(recentTurns, {
|
|
1286
|
+
modelId: activeModel,
|
|
1287
|
+
activeEffort,
|
|
1288
|
+
eventTimestampUtc
|
|
1289
|
+
});
|
|
1290
|
+
if (verbosityGuard.triggered && verbosityGuard.prescription) {
|
|
1291
|
+
guards.push(verbosityGuard.prescription);
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
if (!isTelemetryReliable) {
|
|
1295
|
+
guards.push('Telemetry confidence DEGRADED (parser schema drift detected) — running fail-open');
|
|
1296
|
+
}
|
|
1297
|
+
if (fileState.dirtySnapshotPaths && fileState.dirtySnapshotPaths.length > 0) {
|
|
1298
|
+
guards.push(`Dirty Snapshots modified externally: ${fileState.dirtySnapshotPaths.slice(0, 2).join(', ')} — re-read with view_file before editing`);
|
|
1299
|
+
}
|
|
1300
|
+
if (fileState.unseenCallers && fileState.unseenCallers.length > 0) {
|
|
1301
|
+
guards.push(`Unseen Callers importing target: ${fileState.unseenCallers.slice(0, 2).join(', ')} — verify signature compatibility`);
|
|
1302
|
+
}
|
|
1303
|
+
if (fileState.legacyPoisonPaths && fileState.legacyPoisonPaths.length > 0) {
|
|
1304
|
+
guards.push(`Legacy Poison paths in context: ${fileState.legacyPoisonPaths.slice(0, 2).join(', ')} — avoid copying deprecated patterns`);
|
|
1305
|
+
}
|
|
1306
|
+
if (fileState.streamCutoffRiskFiles && fileState.streamCutoffRiskFiles.length > 0) {
|
|
1307
|
+
guards.push(`Stream Cutoff Risk (>600 lines): ${fileState.streamCutoffRiskFiles.slice(0, 2).join(', ')} — use surgical edit chunks under 300 lines`);
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
if (guards.length > 0) {
|
|
1311
|
+
return {
|
|
1312
|
+
systemMessage: `[Flight Check Context Guard] Active hazards: ${guards.join('; ')}`
|
|
1313
|
+
};
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
// 6. STEER_SUBAGENT
|
|
1317
|
+
const isComplexTopic = /(concurrency|deadlock|race condition|architecture refactor|multi-module)/i.test(rawPrompt);
|
|
1318
|
+
if (tokens >= (config.subagent_min_cache_tokens || 25000) &&
|
|
1319
|
+
purity >= (config.subagent_min_purity_pct || 70.0) &&
|
|
1320
|
+
(activeEffort === 'low' || activeEffort === 'medium') &&
|
|
1321
|
+
isComplexTopic) {
|
|
1322
|
+
return {
|
|
1323
|
+
systemMessage: `[Flight Check KV-Cache Guard] Warm context detected (${Math.round(tokens / 1000)}k tokens, ${purity}% Purity). Do not switch session model (preserves warm KV cache). Delegate this analysis via invoke_subagent with pro/max depth.`
|
|
1324
|
+
};
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
// 7. ALLOW_ACTIVE_SET & Trust Decay
|
|
1328
|
+
const matchedScope = (fileState.activeSetPaths || fileState.modifiedFiles || []).find(p => {
|
|
1329
|
+
const base = path.basename(p);
|
|
1330
|
+
return rawPrompt.includes(base) || rawPrompt.includes(p);
|
|
1331
|
+
}) || '';
|
|
1332
|
+
const hasActiveSetMatch = Boolean(matchedScope);
|
|
1333
|
+
|
|
1334
|
+
// Conversational Drip-Feeding check (DET-02B) & Cross-Turn Sharded Spec Detector:
|
|
1335
|
+
// Even if prompt mentions activeSetPaths, 4+ rapid micro-prompts (<= 18 words) targeting the same file within 90s trigger DET-02B,
|
|
1336
|
+
// while 4+ requirement-mutating shards across >=25k tokens trigger SHARDED_SPEC_DRIFT.
|
|
1337
|
+
const timestampMs = Number(inputData.timestampMs ?? inputData.nowMs ?? inputData.timestamp ?? Date.now());
|
|
1338
|
+
const wordCount = rawPrompt.split(/\s+/).filter(Boolean).length;
|
|
1339
|
+
const effectiveTurnNumber = Number(
|
|
1340
|
+
inputData.turnNumber ?? Math.max(turnCount + 1, Number(sessionMeta.promptTurnSeq || 0) + 1)
|
|
1341
|
+
);
|
|
1342
|
+
sessionMeta.promptTurnSeq = effectiveTurnNumber;
|
|
1343
|
+
sessionMeta.recentPrompts = Array.isArray(sessionMeta.recentPrompts) ? sessionMeta.recentPrompts : [];
|
|
1344
|
+
sessionMeta.recentPrompts = sessionMeta.recentPrompts.filter(e => (timestampMs - e.ts) <= 90000);
|
|
1345
|
+
sessionMeta.recentPrompts.push({ ts: timestampMs, wordCount, targetScope: matchedScope });
|
|
1346
|
+
|
|
1347
|
+
const shardedOverride = resolveDetectorOverride(horizonConfig, 'sharded-spec-drift');
|
|
1348
|
+
const shardedEval = rawPrompt
|
|
1349
|
+
? evaluateShardedSpecDrift({
|
|
1350
|
+
prompt: rawPrompt,
|
|
1351
|
+
provenance: inputData.provenance || inputData.source || 'user',
|
|
1352
|
+
isAutonomousTurn: Boolean(inputData.isAutonomousTurn || inputData.autonomous),
|
|
1353
|
+
isSubagent: Boolean(inputData.isSubagent || sessionMeta.isSubagent),
|
|
1354
|
+
isScheduledTask: Boolean(inputData.isScheduledTask),
|
|
1355
|
+
isLoopIteration: Boolean(inputData.isLoopIteration),
|
|
1356
|
+
priorShards: Array.isArray(inputData.specShards) ? inputData.specShards : (sessionMeta.specShards || []),
|
|
1357
|
+
initialGoal: inputData.initialGoal ?? sessionMeta.initialGoal ?? '',
|
|
1358
|
+
totalTokens: Number(inputData.totalInputTokens ?? inputData.totalPromptTokens ?? tokens),
|
|
1359
|
+
turnNumber: effectiveTurnNumber,
|
|
1360
|
+
lastAlertTurn: Number(sessionMeta.lastShardedSpecAlertTurn || 0),
|
|
1361
|
+
overrideMode: shardedOverride,
|
|
1362
|
+
flightMode,
|
|
1363
|
+
detectorId: 'DET-26'
|
|
1364
|
+
})
|
|
1365
|
+
: { triggered: false, specShards: sessionMeta.specShards || [], initialGoal: sessionMeta.initialGoal || '', lastAlertTurn: Number(sessionMeta.lastShardedSpecAlertTurn || 0) };
|
|
1366
|
+
|
|
1367
|
+
sessionMeta.specShards = shardedEval.specShards;
|
|
1368
|
+
if (shardedEval.initialGoal) sessionMeta.initialGoal = shardedEval.initialGoal;
|
|
1369
|
+
sessionMeta.lastShardedSpecAlertTurn = shardedEval.lastAlertTurn;
|
|
1370
|
+
|
|
1371
|
+
sidecar.sessionMeta = sessionMeta;
|
|
1372
|
+
const flushSidecarOnce = () => {
|
|
1373
|
+
try {
|
|
1374
|
+
writeSidecarAtomicSync(conversationId, sidecar);
|
|
1375
|
+
} catch (err) {
|
|
1376
|
+
recordHookDiagnostic('pre_invocation', 'recentPrompts.writeSidecar', err);
|
|
1377
|
+
}
|
|
1378
|
+
};
|
|
1379
|
+
|
|
1380
|
+
const rapidSameScopeCount = sessionMeta.recentPrompts.filter(
|
|
1381
|
+
e => e.targetScope && e.targetScope === matchedScope && e.wordCount <= 18
|
|
1382
|
+
).length;
|
|
1383
|
+
|
|
1384
|
+
if (rapidSameScopeCount >= 4) {
|
|
1385
|
+
const dripCard = `[DET-02B Conversational Drip-Feed Advisory] Detected ${rapidSameScopeCount} rapid single-sentence prompts on ${matchedScope || 'target file'} in <90s. Batch requirements into a single checklist turn to save prefix cache and 4x turn overhead.`;
|
|
1386
|
+
const dripRes = applyHabitOverride('drip-feed', 'CONVERSATIONAL_DRIP_FEED', dripCard, {
|
|
1387
|
+
detectorId: 'DET-02B',
|
|
1388
|
+
defaultMode: 'flightMode',
|
|
1389
|
+
extraWarn: { continue: true },
|
|
1390
|
+
extraBlock: { continue: false }
|
|
1391
|
+
});
|
|
1392
|
+
if (dripRes) {
|
|
1393
|
+
if (!dripRes.terminationBehavior && dripRes.decision !== 'block') flushSidecarOnce();
|
|
1394
|
+
return dripRes;
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
if (shardedEval.triggered) {
|
|
1399
|
+
flushSidecarOnce();
|
|
1400
|
+
return {
|
|
1401
|
+
ephemeralMessage: shardedEval.steerContext,
|
|
1402
|
+
systemMessage: shardedEval.steerContext,
|
|
1403
|
+
detectorId: 'DET-26',
|
|
1404
|
+
subType: shardedEval.subType,
|
|
1405
|
+
shardCount: shardedEval.shardCount
|
|
1406
|
+
};
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
if (!hasCheckTag) {
|
|
1410
|
+
if (hasActiveSetMatch) {
|
|
1411
|
+
flushSidecarOnce();
|
|
1412
|
+
return {};
|
|
1413
|
+
}
|
|
1414
|
+
if (config.hook_level === 'guard' && turnCount > (config.trust_decay_turn_threshold || 10)) {
|
|
1415
|
+
flushSidecarOnce();
|
|
1416
|
+
return {};
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
// 8a. Prompt Hygiene Governor (v4.1 Phase 1): Relay Breaker ('relay-breaker') & Scope Brake ('vague-prompt-rubric')
|
|
1421
|
+
const relayOverride = resolveDetectorOverride(horizonConfig, 'relay-breaker');
|
|
1422
|
+
const relayEval = evaluateRelayBreaker({
|
|
1423
|
+
prompt: rawPrompt,
|
|
1424
|
+
relayState: inputData.relayState ?? sessionMeta.relayState,
|
|
1425
|
+
sourceCodeEditsInSession: Number(inputData.sourceCodeEditsInSession ?? (fileState.modifiedFiles || []).filter(p => !/\.md$/i.test(String(p || ''))).length),
|
|
1426
|
+
sourceCodeEditedSinceLastRelay: Boolean(inputData.sourceCodeEditedSinceLastRelay),
|
|
1427
|
+
priorTurnWebSearches: Number(inputData.priorTurnWebSearches ?? sessionMeta.priorTurnWebSearches ?? 0),
|
|
1428
|
+
zeroEditSessionTokens: Number(inputData.zeroEditSessionTokens ?? (((fileState.modifiedFiles || []).length === 0) ? tokens : 0)),
|
|
1429
|
+
boundSpecPath: inputData.boundSpecPath ?? sessionMeta.relayState?.boundSpecPath ?? null,
|
|
1430
|
+
overrideMode: relayOverride,
|
|
1431
|
+
flightMode,
|
|
1432
|
+
detectorId: 'DET-26'
|
|
1433
|
+
});
|
|
1434
|
+
sessionMeta.relayState = relayEval.relayStateSnapshot;
|
|
1435
|
+
if (relayEval.triggered) {
|
|
1436
|
+
sidecar.sessionMeta = sessionMeta;
|
|
1437
|
+
try {
|
|
1438
|
+
writeSidecarAtomicSync(conversationId, sidecar);
|
|
1439
|
+
} catch (err) {
|
|
1440
|
+
recordHookDiagnostic('pre_invocation', 'relayBreaker.writeSidecar', err);
|
|
1441
|
+
}
|
|
1442
|
+
if (relayEval.decision === 'block') {
|
|
1443
|
+
sessionMeta.blockedPrompts = Number(sessionMeta.blockedPrompts || 0) + 1;
|
|
1444
|
+
return {
|
|
1445
|
+
terminationBehavior: 'terminate',
|
|
1446
|
+
decision: 'block',
|
|
1447
|
+
detectorId: 'DET-26',
|
|
1448
|
+
subType: relayEval.subType,
|
|
1449
|
+
relayState: relayEval.nextState,
|
|
1450
|
+
userMessage: relayEval.tailInjection
|
|
1451
|
+
};
|
|
1452
|
+
}
|
|
1453
|
+
sessionMeta.steeredPrompts = Number(sessionMeta.steeredPrompts || 0) + 1;
|
|
1454
|
+
return {
|
|
1455
|
+
ephemeralMessage: relayEval.tailInjection,
|
|
1456
|
+
systemMessage: relayEval.tailInjection,
|
|
1457
|
+
detectorId: 'DET-26',
|
|
1458
|
+
subType: relayEval.subType,
|
|
1459
|
+
relayState: relayEval.nextState
|
|
1460
|
+
};
|
|
1461
|
+
}
|
|
1462
|
+
|
|
1463
|
+
const scopeOverride = resolveDetectorOverride(horizonConfig, 'vague-prompt-rubric');
|
|
1464
|
+
const scopeEval = evaluateScopeBrake({
|
|
1465
|
+
prompt: rawPrompt,
|
|
1466
|
+
provenance: inputData.provenance || inputData.source || 'user',
|
|
1467
|
+
isAutonomousTurn: Boolean(inputData.isAutonomousTurn || inputData.autonomous),
|
|
1468
|
+
isSubagent: Boolean(inputData.isSubagent || sessionMeta.isSubagent),
|
|
1469
|
+
isScheduledTask: Boolean(inputData.isScheduledTask),
|
|
1470
|
+
isLoopIteration: Boolean(inputData.isLoopIteration),
|
|
1471
|
+
priorTurnEditedFilesCount: Number(
|
|
1472
|
+
inputData.priorTurnEditedFilesCount ??
|
|
1473
|
+
(Array.isArray(sessionMeta.lastTurnEditedFiles) ? sessionMeta.lastTurnEditedFiles.length : 0)
|
|
1474
|
+
),
|
|
1475
|
+
priorTurnSingleFileTarget: inputData.priorTurnSingleFileTarget ?? sessionMeta.priorTurnSingleFileTarget ?? null,
|
|
1476
|
+
priorTurnHadToolOrTestFailure: Boolean(
|
|
1477
|
+
inputData.priorTurnHadToolOrTestFailure ??
|
|
1478
|
+
sensors.lastTurnToolFailed ??
|
|
1479
|
+
sensors.threeStrikeLoop
|
|
1480
|
+
),
|
|
1481
|
+
priorTurnAssistantAskedQuestion: Boolean(
|
|
1482
|
+
inputData.priorTurnAssistantAskedQuestion ?? sessionMeta.lastTurnAskedQuestion
|
|
1483
|
+
),
|
|
1484
|
+
activeSetPaths: fileState.activeSetPaths || [],
|
|
1485
|
+
modifiedFiles: fileState.modifiedFiles || [],
|
|
1486
|
+
recentlyViewedFiles: fileState.recentlyViewedFiles || [],
|
|
1487
|
+
overrideMode: scopeOverride,
|
|
1488
|
+
flightMode,
|
|
1489
|
+
detectorId: 'DET-26'
|
|
1490
|
+
});
|
|
1491
|
+
if (scopeEval.triggered) {
|
|
1492
|
+
sessionMeta.unanchoredTurnFlag = true;
|
|
1493
|
+
sidecar.sessionMeta = sessionMeta;
|
|
1494
|
+
try {
|
|
1495
|
+
writeSidecarAtomicSync(conversationId, sidecar);
|
|
1496
|
+
} catch (err) {
|
|
1497
|
+
recordHookDiagnostic('pre_invocation', 'scopeBrake.writeSidecar', err);
|
|
1498
|
+
}
|
|
1499
|
+
if (scopeEval.decision === 'block') {
|
|
1500
|
+
sessionMeta.blockedPrompts = Number(sessionMeta.blockedPrompts || 0) + 1;
|
|
1501
|
+
return {
|
|
1502
|
+
terminationBehavior: 'terminate',
|
|
1503
|
+
decision: 'block',
|
|
1504
|
+
detectorId: 'DET-26',
|
|
1505
|
+
subType: scopeEval.subType,
|
|
1506
|
+
userMessage: scopeEval.blockReason
|
|
1507
|
+
};
|
|
1508
|
+
}
|
|
1509
|
+
sessionMeta.steeredPrompts = Number(sessionMeta.steeredPrompts || 0) + 1;
|
|
1510
|
+
return {
|
|
1511
|
+
ephemeralMessage: scopeEval.steerContext,
|
|
1512
|
+
systemMessage: scopeEval.steerContext,
|
|
1513
|
+
detectorId: 'DET-26',
|
|
1514
|
+
subType: scopeEval.subType,
|
|
1515
|
+
candidateFiles: scopeEval.candidateFiles
|
|
1516
|
+
};
|
|
1517
|
+
}
|
|
1518
|
+
sessionMeta.unanchoredTurnFlag = false;
|
|
1519
|
+
|
|
1520
|
+
// 8b. HALT_REWRITE_SCORECARD (Explicit #check or Cold Session Vague Multi-File Prompt)
|
|
1521
|
+
const isColdSession = turnCount <= (config.cold_session_max_turns || 3);
|
|
1522
|
+
const promptSufficiency = scorePromptSufficiency(rawPrompt, { activeSetPaths: fileState.activeSetPaths });
|
|
1523
|
+
const isArchitecturalVague = promptSufficiency.score <= 4 &&
|
|
1524
|
+
/\b(refactor|rewrite|rearchitect|migrate|overhaul|redesign)\s+(?:the\s+)?[a-z0-9_-]+\s+(?:pipeline|system|architecture|service|subsystem|layer|workflow|engine)\b/i.test(rawPrompt);
|
|
1525
|
+
const isVagueMultiFile = (/(refactor everything|fix all|update the whole project|caching)/i.test(rawPrompt) || isArchitecturalVague) && !rawPrompt.includes('@');
|
|
1526
|
+
|
|
1527
|
+
// Ground rule: "Short prompts are not bad by default" - concise scoped instructions shouldn't trigger vague halt
|
|
1528
|
+
if (hasCheckTag || (isColdSession && isVagueMultiFile && (!promptSufficiency.shortPrompt || isArchitecturalVague))) {
|
|
1529
|
+
const cleanedPrompt = rawPrompt.replace(/#check\b/gi, '').trim();
|
|
1530
|
+
const recommendedModel = tokens > 50000 ? deepModel : fastModel;
|
|
1531
|
+
const recommendedEffort = isComplexTopic ? 'high' : 'medium';
|
|
1532
|
+
const rawTargetHint = (fileState.activeSetPaths && fileState.activeSetPaths[0]) || '';
|
|
1533
|
+
const targetHint = (rawTargetHint ? toWorkspaceRelativePath(rawTargetHint, sidecar.workspacePath || process.cwd()) : '') || '<target-file>';
|
|
1534
|
+
const missingSnippet = promptSufficiency.missing.length > 0 ? ` | Missing: ${promptSufficiency.missing[0]}` : '';
|
|
1535
|
+
|
|
1536
|
+
const rewriteSuggestion = promptSufficiency.missing.includes('testability & expected outcome')
|
|
1537
|
+
? `"In @${targetHint}, ${cleanedPrompt || 'implement updates'} and run automated tests to verify"`
|
|
1538
|
+
: `"In @${targetHint}, ${cleanedPrompt || 'implement surgical updates with unit test'}"`;
|
|
1539
|
+
|
|
1540
|
+
const card = formatScorecard(
|
|
1541
|
+
`[Sufficiency ${promptSufficiency.score}/12 ${promptSufficiency.band}]${missingSnippet}`,
|
|
1542
|
+
`[Purity: ${purity}% | Sludge: +$${(telemetry.sludgeTaxUsdPerTurn || 0).toFixed(2)}/t | Tokens: ${Math.round(tokens / 1000)}k]`,
|
|
1543
|
+
`/model ${recommendedModel} • /effort ${recommendedEffort}`,
|
|
1544
|
+
rewriteSuggestion
|
|
1545
|
+
);
|
|
1546
|
+
const vagueRes = applyHabitOverride('vague-prompt-rubric', 'REWRITE_SCORECARD', card);
|
|
1547
|
+
if (vagueRes) {
|
|
1548
|
+
if (!vagueRes.terminationBehavior && vagueRes.decision !== 'block') flushSidecarOnce();
|
|
1549
|
+
return vagueRes;
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
const hasTurn1Workspace = Boolean(
|
|
1554
|
+
inputData.cwd ||
|
|
1555
|
+
inputData.workspacePath ||
|
|
1556
|
+
(Array.isArray(inputData.workspacePaths) && inputData.workspacePaths.length > 0) ||
|
|
1557
|
+
inputData.enableTurn1Contract
|
|
1558
|
+
);
|
|
1559
|
+
if (hasTurn1Workspace && resolveDetectorOverride(horizonConfig, 'turn1-contract-gate') !== 'off') {
|
|
1560
|
+
const contractEval = evaluateTurn1ContractGate({
|
|
1561
|
+
prompt: rawPrompt,
|
|
1562
|
+
provenance: inputData.provenance || inputData.source || 'user',
|
|
1563
|
+
isAutonomousTurn: Boolean(inputData.isAutonomousTurn || inputData.autonomous),
|
|
1564
|
+
isSubagent: Boolean(inputData.isSubagent || sessionMeta.isSubagent),
|
|
1565
|
+
isScheduledTask: Boolean(inputData.isScheduledTask),
|
|
1566
|
+
isLoopIteration: Boolean(inputData.isLoopIteration),
|
|
1567
|
+
inPlanMode: Boolean(sessionMeta.inPlanMode || inputData.inPlanMode),
|
|
1568
|
+
turnNumber: effectiveTurnNumber,
|
|
1569
|
+
invocationNum: Number(inputData.invocationNum ?? 1),
|
|
1570
|
+
alreadyInjected: Boolean(sessionMeta.turn1ContractInjected),
|
|
1571
|
+
hasActiveSetMatch,
|
|
1572
|
+
sufficiency: promptSufficiency,
|
|
1573
|
+
overrideMode: resolveDetectorOverride(horizonConfig, 'turn1-contract-gate'),
|
|
1574
|
+
flightMode,
|
|
1575
|
+
detectorId: 'DET-26'
|
|
1576
|
+
});
|
|
1577
|
+
if (contractEval.triggered) {
|
|
1578
|
+
sessionMeta.turn1ContractInjected = true;
|
|
1579
|
+
sessionMeta.lastUserPrompt = rawPrompt;
|
|
1580
|
+
sidecar.sessionMeta = sessionMeta;
|
|
1581
|
+
try {
|
|
1582
|
+
writeSidecarAtomicSync(conversationId, sidecar);
|
|
1583
|
+
} catch (err) {
|
|
1584
|
+
recordHookDiagnostic('pre_invocation', 'turn1Contract.writeSidecar', err);
|
|
1585
|
+
}
|
|
1586
|
+
return {
|
|
1587
|
+
ephemeralMessage: contractEval.contractDirective,
|
|
1588
|
+
systemMessage: contractEval.contractDirective,
|
|
1589
|
+
detectorId: 'DET-26',
|
|
1590
|
+
subType: contractEval.subType
|
|
1591
|
+
};
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
if (rawPrompt && (inputData.cwd || inputData.workspacePath)) {
|
|
1596
|
+
sessionMeta.lastUserPrompt = rawPrompt;
|
|
1597
|
+
sidecar.sessionMeta = sessionMeta;
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1600
|
+
if (rawPrompt && inputData.bucketBShadow !== false) {
|
|
1601
|
+
try {
|
|
1602
|
+
const isAutonomousOrSubagent = Boolean(
|
|
1603
|
+
inputData.isAutonomousTurn ||
|
|
1604
|
+
inputData.autonomous ||
|
|
1605
|
+
inputData.isSubagent ||
|
|
1606
|
+
sessionMeta.isSubagent ||
|
|
1607
|
+
inputData.isScheduledTask ||
|
|
1608
|
+
inputData.isLoopIteration ||
|
|
1609
|
+
/^(?:scheduled|cron|loop|subagent|agent_callback|callback|auto|autonomous|background|system|hook|task_notification|wake)$/i.test(
|
|
1610
|
+
String(inputData.provenance || inputData.source || '')
|
|
1611
|
+
)
|
|
1612
|
+
);
|
|
1613
|
+
const cachedDirtyFiles = Array.isArray(inputData.cachedDirtyFiles)
|
|
1614
|
+
? inputData.cachedDirtyFiles
|
|
1615
|
+
: [
|
|
1616
|
+
...(fileState.modifiedFiles || []),
|
|
1617
|
+
...(Array.isArray(fileState.unverifiedEdits)
|
|
1618
|
+
? fileState.unverifiedEdits.map((e) => e?.filePath)
|
|
1619
|
+
: [])
|
|
1620
|
+
];
|
|
1621
|
+
const promptAnchor = runBucketBPromptPass({
|
|
1622
|
+
platform: 'antigravity',
|
|
1623
|
+
sessionId: conversationId,
|
|
1624
|
+
cwd: workspacePath,
|
|
1625
|
+
hasExplicitCwd: Boolean(inputData.cwd || inputData.workspacePath),
|
|
1626
|
+
prompt: rawPrompt,
|
|
1627
|
+
isAutonomousOrSubagent,
|
|
1628
|
+
cachedDirtyFiles,
|
|
1629
|
+
lastFailingLocation:
|
|
1630
|
+
inputData.lastFailingLocation ?? sessionMeta.lastFailingLocation ?? '',
|
|
1631
|
+
options: {
|
|
1632
|
+
bucketBStage: inputData.bucketBStage,
|
|
1633
|
+
bucketBGammaStage: inputData.bucketBGammaStage,
|
|
1634
|
+
mode: flightMode,
|
|
1635
|
+
horizonConfig
|
|
1636
|
+
}
|
|
1637
|
+
});
|
|
1638
|
+
if (promptAnchor.triggered) {
|
|
1639
|
+
flushSidecarOnce();
|
|
1640
|
+
return {
|
|
1641
|
+
ephemeralMessage: promptAnchor.reason,
|
|
1642
|
+
systemMessage: promptAnchor.reason,
|
|
1643
|
+
anchorContext: promptAnchor.anchorContext,
|
|
1644
|
+
detectorId: 'VAGUE_PROMPT_ANCHOR'
|
|
1645
|
+
};
|
|
1646
|
+
}
|
|
1647
|
+
} catch (err) {
|
|
1648
|
+
recordHookDiagnostic('pre_invocation', 'handlePreInvocation.bucketBPromptPass', err, { persist: false });
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
|
|
1652
|
+
flushSidecarOnce();
|
|
1653
|
+
return {};
|
|
1654
|
+
}
|
|
1655
|
+
|
|
1656
|
+
/**
|
|
1657
|
+
* Sanitizes internal hook return payloads into strict Antigravity protojson-compatible
|
|
1658
|
+
* CLI stdout objects (no unknown fields like flightMode, active_model_id, swarmTtlBadges).
|
|
1659
|
+
*/
|
|
1660
|
+
export function toProtoSafePreHookOutput(output, { isPreToolUse = false } = {}) {
|
|
1661
|
+
const out = output && typeof output === 'object' ? output : {};
|
|
1662
|
+
if (isPreToolUse) {
|
|
1663
|
+
const rawDecision = String(out.decision || '').toLowerCase();
|
|
1664
|
+
let decision = 'allow';
|
|
1665
|
+
if (rawDecision === 'deny' || rawDecision === 'block' || out.blocked === true || out.terminationBehavior === 'terminate') {
|
|
1666
|
+
decision = 'deny';
|
|
1667
|
+
} else if (rawDecision === 'ask') {
|
|
1668
|
+
decision = 'ask';
|
|
1669
|
+
}
|
|
1670
|
+
const reasonText = out.reason || out.errorMessage?.userMessage || out.userMessage || out.systemMessage || out.ephemeralMessage;
|
|
1671
|
+
if (decision !== 'allow' && reasonText) {
|
|
1672
|
+
return { decision, reason: String(reasonText) };
|
|
1673
|
+
}
|
|
1674
|
+
return { decision };
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
if (out.terminationBehavior === 'terminate') {
|
|
1678
|
+
const userMessage = String(
|
|
1679
|
+
out.errorMessage?.userMessage ||
|
|
1680
|
+
out.userMessage ||
|
|
1681
|
+
out.reason ||
|
|
1682
|
+
out.systemMessage ||
|
|
1683
|
+
'Halted by Highbeam Flightcheck'
|
|
1684
|
+
);
|
|
1685
|
+
return {
|
|
1686
|
+
terminationBehavior: 'terminate',
|
|
1687
|
+
errorMessage: { userMessage }
|
|
1688
|
+
};
|
|
1689
|
+
}
|
|
1690
|
+
const advisory = out.ephemeralMessage || out.systemMessage;
|
|
1691
|
+
if (typeof advisory === 'string' && advisory.trim().length > 0) {
|
|
1692
|
+
return { ephemeralMessage: advisory };
|
|
1693
|
+
}
|
|
1694
|
+
return {};
|
|
1695
|
+
}
|
|
1696
|
+
|
|
1697
|
+
// Auto-run when executed directly by Antigravity Hook Harness
|
|
1698
|
+
const isMain = process.argv[1] && (process.argv[1].endsWith('pre_invocation.mjs') || process.argv[1].endsWith('pre_invocation.js'));
|
|
1699
|
+
const isPreToolUseCli = process.argv.includes('--event=PreToolUse');
|
|
1700
|
+
if (isMain) {
|
|
1701
|
+
let detectedPreToolUse = isPreToolUseCli;
|
|
1702
|
+
readStdinSafe().then(input => {
|
|
1703
|
+
const safeInput = input && typeof input === 'object' ? input : {};
|
|
1704
|
+
if (isPreToolUseCli && !safeInput.hook_event_name) {
|
|
1705
|
+
safeInput.hook_event_name = 'PreToolUse';
|
|
1706
|
+
}
|
|
1707
|
+
if (
|
|
1708
|
+
safeInput.hook_event_name === 'PreToolUse' ||
|
|
1709
|
+
safeInput.event === 'PreToolUse' ||
|
|
1710
|
+
safeInput.tool_name ||
|
|
1711
|
+
safeInput.toolName
|
|
1712
|
+
) {
|
|
1713
|
+
detectedPreToolUse = true;
|
|
1714
|
+
}
|
|
1715
|
+
return handlePreInvocation(safeInput);
|
|
1716
|
+
}).then(output => {
|
|
1717
|
+
const safeOut = toProtoSafePreHookOutput(output, { isPreToolUse: detectedPreToolUse });
|
|
1718
|
+
console.log(JSON.stringify(safeOut));
|
|
1719
|
+
process.exit(0);
|
|
1720
|
+
}).catch((err) => {
|
|
1721
|
+
recordHookDiagnostic('pre_invocation', 'main', err);
|
|
1722
|
+
console.log(JSON.stringify(detectedPreToolUse ? { decision: 'allow' } : {}));
|
|
1723
|
+
process.exit(0);
|
|
1724
|
+
});
|
|
1725
|
+
}
|