ctxtop 0.0.0-stage → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.antigravity-plugin/plugin.json +36 -0
- package/.claude-plugin/plugin.json +18 -0
- package/CHECKSUMS.sha256 +149 -0
- package/LICENSE +27 -0
- package/README.md +330 -3
- package/SECURITY.md +22 -0
- package/agents/ah-flash-scout.md +25 -0
- package/assets/advanced_view_loaded_420px.png +0 -0
- package/assets/hero-demo.svg +188 -0
- package/assets/logo.svg +19 -0
- package/assets/simple_view_lean_420px.png +0 -0
- package/assets/simple_view_loaded_420px.png +0 -0
- package/assets/social-preview.svg +72 -0
- package/assets/zone_c_step3_shield_full.png +0 -0
- package/bin/ah-statusline.mjs +145 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1474 -0
- package/commands/cost-radar.md +11 -0
- package/commands/evolve.md +10 -0
- package/commands/handoff.md +10 -0
- package/commands/horizon.md +10 -0
- package/commands/inspect.md +10 -0
- package/commands/precheck.md +10 -0
- package/config/default_flightcheck.json +114 -0
- package/config/modelCatalog.json +620 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +262 -0
- package/hooks/handlers/hookIo.mjs +255 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-tool-use.mjs +265 -0
- package/hooks/handlers/pre-model-switch.mjs +249 -0
- package/hooks/handlers/pre-tool-use.mjs +365 -0
- package/hooks/handlers/stop-gate.mjs +240 -0
- package/hooks/handlers/user-prompt-submit.mjs +143 -0
- package/hooks/hooks.json +81 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +17 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +687 -0
- package/hooks/session_start.mjs +14 -0
- package/hooks/stop.mjs +13 -0
- package/hooks.json +56 -0
- package/package.json +103 -4
- package/packages/antigravity/package.json +14 -0
- package/packages/antigravity/src/index.mjs +1 -0
- package/packages/claude-code/package.json +14 -0
- package/packages/claude-code/src/index.mjs +2 -0
- package/packages/core/package.json +14 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/engine-node/package.json +14 -0
- package/packages/engine-node/src/index.mjs +1 -0
- package/packages/mcp/package.json +17 -0
- package/packages/mcp/src/server.mjs +396 -0
- package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
- package/packages/pro/README-SIGNING.md +30 -0
- package/packages/pro/package.json +16 -0
- package/packages/pro/src/index.mjs +3 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -0
- package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
- package/plugin.json +36 -0
- package/rules/AGENTS.md +10 -0
- package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
- package/sidecars/horizon-daemon/server.mjs +2002 -0
- package/sidecars/horizon-daemon/sidecar.json +19 -0
- package/skills/cost-radar/SKILL.md +21 -0
- package/skills/evolve/SKILL.md +21 -0
- package/skills/handoff/SKILL.md +42 -0
- package/skills/horizon/SKILL.md +17 -0
- package/skills/inspect/SKILL.md +18 -0
- package/skills/precheck/SKILL.md +44 -0
- package/src/adapters/antigravity/index.mjs +79 -0
- package/src/adapters/claude-code/index.mjs +155 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +686 -0
- package/src/cli/init.mjs +425 -0
- package/src/cli/postmortem.mjs +515 -0
- package/src/coach/cacheGravityRouter.mjs +12 -0
- package/src/config/modelCatalog.json +620 -0
- package/src/config/platformQuirks.json +19 -0
- package/src/core/action_queue.mjs +264 -0
- package/src/core/ag_bridge.mjs +346 -0
- package/src/core/atomic_io.mjs +124 -0
- package/src/core/baseline.mjs +607 -0
- package/src/core/blindspot_sensors.mjs +399 -0
- package/src/core/classifier.mjs +1757 -0
- package/src/core/coach/circuit_breakers.mjs +650 -0
- package/src/core/coach/contradiction_auditor.mjs +239 -0
- package/src/core/coach/effort_advisor.mjs +143 -0
- package/src/core/coach/handoff_hydrator.mjs +483 -0
- package/src/core/coach/progressive_checkpointer.mjs +551 -0
- package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
- package/src/core/coach/reflector_queue.mjs +505 -0
- package/src/core/coach/saved_quota_ledger.mjs +615 -0
- package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
- package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
- package/src/core/coach/task_quota_router.mjs +955 -0
- package/src/core/coach/turn_zero_gate.mjs +574 -0
- package/src/core/compaction_coach.mjs +1126 -0
- package/src/core/config.mjs +214 -0
- package/src/core/constants.mjs +1800 -0
- package/src/core/detectors_det01_to_16.mjs +1474 -0
- package/src/core/episodic_memory.mjs +135 -0
- package/src/core/fts5_output_compressor.mjs +359 -0
- package/src/core/git_ledger.mjs +189 -0
- package/src/core/handoff_audit.mjs +558 -0
- package/src/core/history.mjs +221 -0
- package/src/core/hook_diagnostics.mjs +158 -0
- package/src/core/horizon_classifier.mjs +326 -0
- package/src/core/horizon_config.mjs +802 -0
- package/src/core/host_watchdog.mjs +200 -0
- package/src/core/layer5_hygiene.mjs +966 -0
- package/src/core/log_resolver.mjs +231 -0
- package/src/core/mcp_auditor.mjs +138 -0
- package/src/core/micro_skills_store.mjs +91 -0
- package/src/core/offenders.mjs +161 -0
- package/src/core/parser.mjs +1996 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +310 -0
- package/src/core/prefix_cache_shield.mjs +386 -0
- package/src/core/pro_license.mjs +385 -0
- package/src/core/prompt_rubric.mjs +518 -0
- package/src/core/pruner.mjs +433 -0
- package/src/core/quota.mjs +1860 -0
- package/src/core/rsi_instinct_engine.mjs +1197 -0
- package/src/core/sanitizer.mjs +121 -0
- package/src/core/session_forensics.mjs +303 -0
- package/src/core/session_timeline.mjs +358 -0
- package/src/core/settings.mjs +99 -0
- package/src/core/shared/detectors.mjs +1342 -0
- package/src/core/shared/fnv1a64.mjs +85 -0
- package/src/core/shared/handoff_schema.mjs +123 -0
- package/src/core/shared/index.mjs +5 -0
- package/src/core/shared/ipi_sanitizer.mjs +165 -0
- package/src/core/shared/micro_skills.mjs +1 -0
- package/src/core/shared/plugin_validator.mjs +202 -0
- package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
- package/src/core/sidecar_store.mjs +302 -0
- package/src/core/sprint_metrics.mjs +366 -0
- package/src/core/sqlite_client.mjs +283 -0
- package/src/core/storage_doctor.mjs +358 -0
- package/src/core/subagents.mjs +609 -0
- package/src/core/swarm_topology.mjs +360 -0
- package/src/core/task_quota_router.mjs +1656 -0
- package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
- package/src/core/telemetry/scope_lock_registry.mjs +578 -0
- package/src/core/telemetry/shadow_file_detector.mjs +291 -0
- package/src/core/telemetry/trajectory_watcher.mjs +259 -0
- package/src/core/timeline_svg.mjs +236 -0
- package/src/core/tool_surgeon.mjs +305 -0
- package/src/core/trajectory_stitcher.mjs +645 -0
- package/src/core/u_shaped_optimizer.mjs +789 -0
- package/src/core/wal_hygiene.mjs +233 -0
- package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/src/core-isomorphic/catalog/index.mjs +1 -0
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
- package/src/core-isomorphic/coach/microSkills.mjs +1 -0
- package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
- package/src/core-isomorphic/control/callTree.mjs +338 -0
- package/src/core-isomorphic/control/coachLatches.mjs +126 -0
- package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/src/core-isomorphic/control/index.mjs +49 -0
- package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/src/core-isomorphic/diagnostics/index.mjs +9 -0
- package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
- package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/src/core-isomorphic/economics/index.mjs +47 -0
- package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
- package/src/core-isomorphic/index.js +26 -0
- package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
- package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
- package/src/core-isomorphic/ui/modViews.mjs +1478 -0
- package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/src/core-isomorphic/ustf/index.mjs +7 -0
- package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/src/core-isomorphic/ustf/schema.mjs +186 -0
- package/src/core-isomorphic/utils/runtime.mjs +962 -0
- package/src/demo/synthetic_states.mjs +661 -0
- package/src/diagnostics/bugReportGenerator.mjs +253 -0
- package/src/diagnostics/doctorEngine.mjs +203 -0
- package/src/engine-node/db/index.mjs +58 -0
- package/src/engine-node/db/jsonl_fallback.mjs +184 -0
- package/src/engine-node/db/probe.mjs +110 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +9 -0
- package/src/engine-node/ipc/client.mjs +447 -0
- package/src/engine-node/ipc/index.mjs +22 -0
- package/src/engine-node/ipc/protocol.mjs +177 -0
- package/src/engine-node/ipc/server.mjs +445 -0
- package/src/engine-node/offloader/index.mjs +6 -0
- package/src/engine-node/offloader/tool_offloader.mjs +241 -0
- package/src/engine-node/sensors/blindspots.mjs +369 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +419 -0
- package/src/hooks/pre_invocation.mjs +1015 -0
- package/src/hooks/session_start.mjs +161 -0
- package/src/shims/agy_cli_compressor.mjs +705 -0
- package/src/shims/agy_git_guard.mjs +749 -0
- package/src/shims/ah_log_query.mjs +39 -0
- package/src/ui/costRadarSvg.mjs +6 -0
- package/src/ui/horizonGrid.mjs +1 -0
- package/src/ui/horizonPanelHtml.mjs +1 -0
- package/src/ui/horizon_panel.css +167 -0
- package/src/ui/horizon_panel.js +212 -0
- package/src/ui/modViews.mjs +1 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +11389 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,1015 @@
|
|
|
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
|
+
normalizeModelKey,
|
|
11
|
+
isModelDeprecated,
|
|
12
|
+
getDeprecatedModelMigrationNotice,
|
|
13
|
+
evaluateCarbonVerbosityGuardrail
|
|
14
|
+
} from '../core/constants.mjs';
|
|
15
|
+
import {
|
|
16
|
+
SwarmIdleTtlTracker,
|
|
17
|
+
evaluateSwarmColdCacheWakeup,
|
|
18
|
+
computeSwarmRosterTtlBadges
|
|
19
|
+
} from '../core/subagents.mjs';
|
|
20
|
+
import {
|
|
21
|
+
classifyTaskComplexity,
|
|
22
|
+
CacheGravityScorer,
|
|
23
|
+
TaskMdDirectiveWatcher,
|
|
24
|
+
ModelSelectorActuator,
|
|
25
|
+
evaluateTaskAndQuotaRoute
|
|
26
|
+
} from '../core/task_quota_router.mjs';
|
|
27
|
+
import { loadHorizonConfig, resolveDetectorOverride } from '../core/horizon_config.mjs';
|
|
28
|
+
import {
|
|
29
|
+
evaluateDet08DestructiveShell,
|
|
30
|
+
evaluateDet09MidSessionRuleMutate,
|
|
31
|
+
evaluateDet18UntrustedWorkspaceSettings,
|
|
32
|
+
evaluateDet19GitHookBypass,
|
|
33
|
+
evaluateDet20ScopeCollision
|
|
34
|
+
} from '../core/detectors_det01_to_16.mjs';
|
|
35
|
+
import { loadRegistry } from '../core/telemetry/scope_lock_registry.mjs';
|
|
36
|
+
import { recordHookDiagnostic } from '../core/hook_diagnostics.mjs';
|
|
37
|
+
import {
|
|
38
|
+
evaluateScopeBrake,
|
|
39
|
+
evaluateRelayBreaker,
|
|
40
|
+
evaluateTwoStageSightseeingIntercept
|
|
41
|
+
} from '../core/shared/prompt_hygiene_governor.mjs';
|
|
42
|
+
import { foldCodeToSignatureStub, computeCompactLineDiff } from '../core/pruner.mjs';
|
|
43
|
+
|
|
44
|
+
export {
|
|
45
|
+
classifyTaskComplexity,
|
|
46
|
+
CacheGravityScorer,
|
|
47
|
+
TaskMdDirectiveWatcher,
|
|
48
|
+
ModelSelectorActuator,
|
|
49
|
+
evaluateTaskAndQuotaRoute
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
async function readStdinSafe({ maxTimeoutMs = 1000, settleMs = 50 } = {}) {
|
|
53
|
+
if (process.stdin.isTTY || process.stdin.readableEnded) return {};
|
|
54
|
+
return new Promise((resolve) => {
|
|
55
|
+
let raw = '';
|
|
56
|
+
let settled = false;
|
|
57
|
+
let settleTimer = null;
|
|
58
|
+
|
|
59
|
+
const finish = (val) => {
|
|
60
|
+
if (settled) return;
|
|
61
|
+
settled = true;
|
|
62
|
+
clearTimeout(maxTimer);
|
|
63
|
+
if (settleTimer) clearTimeout(settleTimer);
|
|
64
|
+
try {
|
|
65
|
+
process.stdin.pause();
|
|
66
|
+
} catch (err) {
|
|
67
|
+
recordHookDiagnostic('pre_invocation', 'stdin.pause', err, { persist: false });
|
|
68
|
+
}
|
|
69
|
+
resolve(val);
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const tryParse = () => {
|
|
73
|
+
try {
|
|
74
|
+
return raw ? JSON.parse(raw) : {};
|
|
75
|
+
} catch (err) {
|
|
76
|
+
recordHookDiagnostic('pre_invocation', 'stdin.parse', err);
|
|
77
|
+
return {};
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const maxTimer = setTimeout(() => finish(tryParse()), maxTimeoutMs);
|
|
82
|
+
|
|
83
|
+
process.stdin.setEncoding('utf8');
|
|
84
|
+
process.stdin.on('data', chunk => {
|
|
85
|
+
raw += chunk;
|
|
86
|
+
if (settleTimer) clearTimeout(settleTimer);
|
|
87
|
+
if (raw.trim().endsWith('}')) {
|
|
88
|
+
settleTimer = setTimeout(() => {
|
|
89
|
+
try {
|
|
90
|
+
finish(JSON.parse(raw));
|
|
91
|
+
} catch (err) {
|
|
92
|
+
recordHookDiagnostic('pre_invocation', 'stdin.settleParse', err, { persist: false });
|
|
93
|
+
}
|
|
94
|
+
}, settleMs);
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
process.stdin.on('end', () => finish(tryParse()));
|
|
98
|
+
process.stdin.on('error', (err) => {
|
|
99
|
+
recordHookDiagnostic('pre_invocation', 'stdin.error', err);
|
|
100
|
+
finish({});
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function formatScorecard(p1, p2, p3, p4) {
|
|
106
|
+
const pad = (s, len = 74) => s.length >= len ? s.slice(0, len) : s + ' '.repeat(len - s.length);
|
|
107
|
+
return [
|
|
108
|
+
'╭─ Flight Check v3.1 ──────────────────────────────────────────────────────────╮',
|
|
109
|
+
`│ 1. PROMPT : ${pad(p1, 62)} │`,
|
|
110
|
+
`│ 2. HORIZON: ${pad(p2, 62)} │`,
|
|
111
|
+
`│ 3. ACTION : ${pad(p3, 62)} │`,
|
|
112
|
+
`│ 4. REWRITE: ${pad(p4, 62)} │`,
|
|
113
|
+
'╰──────────────────────────────────────────────────────────────────────────────╯',
|
|
114
|
+
'Bypass once: prefix with `!` • Lock model/effort: include `!lock`'
|
|
115
|
+
].join('\n');
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function recordAntigravitySidecarSavings(sidecar, { category = 'BOUNDED_READ_ENFORCED', savedTokens = 0, detail = '', nowMs = Date.now() } = {}) {
|
|
119
|
+
const tokens = Math.max(0, Number(savedTokens || 0));
|
|
120
|
+
if (!sidecar || typeof sidecar !== 'object' || tokens <= 0) return;
|
|
121
|
+
sidecar.telemetry = sidecar.telemetry && typeof sidecar.telemetry === 'object' ? sidecar.telemetry : {};
|
|
122
|
+
sidecar.telemetry.savedTokens = Number(sidecar.telemetry.savedTokens || 0) + tokens;
|
|
123
|
+
sidecar.telemetry.boundedReadInterventions = Number(sidecar.telemetry.boundedReadInterventions || 0) + 1;
|
|
124
|
+
sidecar.telemetry.savedTokensByCategory =
|
|
125
|
+
sidecar.telemetry.savedTokensByCategory && typeof sidecar.telemetry.savedTokensByCategory === 'object'
|
|
126
|
+
? sidecar.telemetry.savedTokensByCategory
|
|
127
|
+
: {};
|
|
128
|
+
sidecar.telemetry.savedTokensByCategory[category] =
|
|
129
|
+
Number(sidecar.telemetry.savedTokensByCategory[category] || 0) + tokens;
|
|
130
|
+
const recent = Array.isArray(sidecar.telemetry.recentInterventions)
|
|
131
|
+
? sidecar.telemetry.recentInterventions
|
|
132
|
+
: [];
|
|
133
|
+
recent.push({
|
|
134
|
+
ts: new Date(nowMs).toISOString(),
|
|
135
|
+
category,
|
|
136
|
+
savedTokens: tokens,
|
|
137
|
+
detail
|
|
138
|
+
});
|
|
139
|
+
sidecar.telemetry.recentInterventions = recent.slice(-25);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export async function handlePreToolUse(inputData = {}) {
|
|
143
|
+
const conversationId = inputData.conversationId || inputData.session_id || inputData.conversation_id || 'default_session';
|
|
144
|
+
const sidecar = readSidecarSync(conversationId);
|
|
145
|
+
sidecar.sessionMeta = sidecar.sessionMeta || {};
|
|
146
|
+
sidecar.swarmRoster = sidecar.swarmRoster || {};
|
|
147
|
+
|
|
148
|
+
// Phase 3.2: Buffer mid-turn model switches without mutating active_model_id
|
|
149
|
+
const requestedMidTurnModel = inputData.requestedModel || inputData.newModel || inputData.pending_model_id || null;
|
|
150
|
+
if (requestedMidTurnModel) {
|
|
151
|
+
const normalizedNext = normalizeModelKey(requestedMidTurnModel);
|
|
152
|
+
if (!sidecar.sessionMeta.active_model_id) {
|
|
153
|
+
sidecar.sessionMeta.active_model_id = normalizeModelKey(
|
|
154
|
+
inputData.active_model_id || inputData.modelName || sidecar.sessionMeta.activeModel || 'gemini-3.8-flash'
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
if (normalizedNext !== sidecar.sessionMeta.active_model_id) {
|
|
158
|
+
sidecar.sessionMeta.pending_model_id = normalizedNext;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const toolName = String(inputData.tool_name || inputData.tool || inputData.toolName || '').trim();
|
|
163
|
+
const toolInput = inputData.tool_input || inputData.toolInput || inputData.args || inputData.parameters || inputData.Arguments || inputData;
|
|
164
|
+
const workspacePath = inputData.cwd || inputData.workspacePath || sidecar.workspacePath || process.cwd();
|
|
165
|
+
const horizonConfig = inputData.horizonConfig || loadHorizonConfig({
|
|
166
|
+
cwd: workspacePath,
|
|
167
|
+
...(inputData.homeDir ? { homeDir: inputData.homeDir } : {})
|
|
168
|
+
});
|
|
169
|
+
const flightMode = String(inputData.flightMode || horizonConfig.flightMode || 'COACH').toUpperCase();
|
|
170
|
+
const isSilentMode = flightMode === 'SILENT';
|
|
171
|
+
const isOffMode = flightMode === 'OFF';
|
|
172
|
+
const isAutoPilotMode = flightMode === 'AUTO_PILOT';
|
|
173
|
+
|
|
174
|
+
const syntheticStep = [{
|
|
175
|
+
toolCalls: [{
|
|
176
|
+
name: toolName,
|
|
177
|
+
args: toolInput && typeof toolInput === 'object' ? toolInput : {}
|
|
178
|
+
}]
|
|
179
|
+
}];
|
|
180
|
+
|
|
181
|
+
const makeBlockPayload = (detResult) => ({
|
|
182
|
+
decision: 'block',
|
|
183
|
+
permissionDecision: 'deny',
|
|
184
|
+
terminationBehavior: 'terminate',
|
|
185
|
+
blocked: true,
|
|
186
|
+
flightMode,
|
|
187
|
+
detectorId: detResult.id,
|
|
188
|
+
reason: detResult.message,
|
|
189
|
+
userMessage: detResult.message,
|
|
190
|
+
systemMessage: detResult.message
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
// Ring-0 Security Gates (active even in SILENT / OFF unless explicitly disabled in Antigravity namespace)
|
|
194
|
+
if (/^(run_command|execute_bash|bash|powershell|exec)$/i.test(toolName)) {
|
|
195
|
+
if (resolveDetectorOverride(horizonConfig, 'DET-19') !== 'off') {
|
|
196
|
+
const det19 = evaluateDet19GitHookBypass(syntheticStep);
|
|
197
|
+
if (det19) return makeBlockPayload(det19);
|
|
198
|
+
}
|
|
199
|
+
if (resolveDetectorOverride(horizonConfig, 'DET-08') !== 'off') {
|
|
200
|
+
const det08 = evaluateDet08DestructiveShell(syntheticStep);
|
|
201
|
+
if (det08) return makeBlockPayload(det08);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
if (/^(edit_file|write_file|write_to_file|replace_file_content|multi_replace_file_content|run_command|execute_bash|bash|powershell)$/i.test(toolName)) {
|
|
205
|
+
if (resolveDetectorOverride(horizonConfig, 'DET-18') !== 'off') {
|
|
206
|
+
const det18 = evaluateDet18UntrustedWorkspaceSettings(syntheticStep, {
|
|
207
|
+
workspacePath,
|
|
208
|
+
scanWorkspace: false
|
|
209
|
+
});
|
|
210
|
+
if (det18) return makeBlockPayload(det18);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Non-Ring-0 Guardrails (DET-09 warm-cache rule fence, DET-20 concurrent scope lock collision, Two-Stage Prompt Hygiene)
|
|
215
|
+
let gateSystemMessage = null;
|
|
216
|
+
if (!isOffMode) {
|
|
217
|
+
const scopeOverride = resolveDetectorOverride(horizonConfig, 'vague-prompt-rubric');
|
|
218
|
+
const relayOverride = resolveDetectorOverride(horizonConfig, 'relay-breaker');
|
|
219
|
+
const twoStage = evaluateTwoStageSightseeingIntercept({
|
|
220
|
+
toolName,
|
|
221
|
+
toolArgs: toolInput && typeof toolInput === 'object' ? toolInput : {},
|
|
222
|
+
unanchoredTurnFlag: Boolean(inputData.unanchoredTurnFlag ?? sidecar.sessionMeta?.unanchoredTurnFlag),
|
|
223
|
+
candidateFiles: Array.isArray(inputData.candidateFiles)
|
|
224
|
+
? inputData.candidateFiles
|
|
225
|
+
: (sidecar.fileState?.modifiedFiles || sidecar.fileState?.activeSetPaths || []),
|
|
226
|
+
relayState: inputData.relayState ?? sidecar.sessionMeta?.relayState,
|
|
227
|
+
overrideMode: scopeOverride !== 'default' ? scopeOverride : relayOverride,
|
|
228
|
+
flightMode,
|
|
229
|
+
detectorId: 'DET-26'
|
|
230
|
+
});
|
|
231
|
+
if (twoStage.intercepted) {
|
|
232
|
+
if (twoStage.consumeFlag && sidecar.sessionMeta) {
|
|
233
|
+
sidecar.sessionMeta.unanchoredTurnFlag = false;
|
|
234
|
+
sidecar.sessionMeta.sightseeingToolsPrevented = Number(sidecar.sessionMeta.sightseeingToolsPrevented || 0) + 1;
|
|
235
|
+
try {
|
|
236
|
+
writeSidecarAtomicSync(conversationId, sidecar);
|
|
237
|
+
} catch (err) {
|
|
238
|
+
recordHookDiagnostic('pre_invocation', 'twoStage.writeSidecar', err);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (twoStage.decision === 'deny') {
|
|
242
|
+
return makeBlockPayload({ id: twoStage.detectorId, message: twoStage.reason });
|
|
243
|
+
}
|
|
244
|
+
if (!isSilentMode) gateSystemMessage = twoStage.reason;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
if (!isOffMode && /^(edit_file|write_file|write_to_file|replace_file_content|multi_replace_file_content)$/i.test(toolName)) {
|
|
248
|
+
const det09Mode = resolveDetectorOverride(horizonConfig, 'DET-09');
|
|
249
|
+
if (det09Mode !== 'off') {
|
|
250
|
+
const det09 = evaluateDet09MidSessionRuleMutate(syntheticStep, {
|
|
251
|
+
cachedTokens: inputData.cachedTokens ?? sidecar.telemetry?.cachedTokens ?? sidecar.telemetry?.totalInputTokens ?? 0,
|
|
252
|
+
cacheTtlSeconds: inputData.cacheTtlSeconds ?? sidecar.telemetry?.cacheTtlSeconds ?? 300,
|
|
253
|
+
cacheState: inputData.cacheState
|
|
254
|
+
});
|
|
255
|
+
if (det09) {
|
|
256
|
+
if (isAutoPilotMode || det09Mode === 'block') return makeBlockPayload(det09);
|
|
257
|
+
if (!isSilentMode) gateSystemMessage = det09.message;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const det20Mode = resolveDetectorOverride(horizonConfig, 'DET-20');
|
|
262
|
+
if (det20Mode !== 'off') {
|
|
263
|
+
const rawTarget = String(
|
|
264
|
+
toolInput?.Path || toolInput?.path || toolInput?.TargetFile || toolInput?.AbsolutePath || ''
|
|
265
|
+
).trim();
|
|
266
|
+
if (rawTarget) {
|
|
267
|
+
const relTarget = path.isAbsolute(rawTarget)
|
|
268
|
+
? path.relative(workspacePath, rawTarget).replace(/\\/g, '/')
|
|
269
|
+
: rawTarget.replace(/\\/g, '/');
|
|
270
|
+
const activeLeases = Array.isArray(inputData.activeLeases)
|
|
271
|
+
? inputData.activeLeases
|
|
272
|
+
: loadRegistry(workspacePath).leases;
|
|
273
|
+
const det20 = evaluateDet20ScopeCollision([], {
|
|
274
|
+
currentTrajectoryId: conversationId,
|
|
275
|
+
claimedPaths: [relTarget],
|
|
276
|
+
activeLeases,
|
|
277
|
+
workspaceDir: workspacePath
|
|
278
|
+
});
|
|
279
|
+
if (det20) {
|
|
280
|
+
if (isAutoPilotMode || det20Mode === 'block') return makeBlockPayload(det20);
|
|
281
|
+
if (!isSilentMode && !gateSystemMessage) gateSystemMessage = det20.message;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const nowMs = inputData.nowMs ?? inputData.eventTimestampUtc ?? Date.now();
|
|
288
|
+
const eventTimestampUtc = inputData.eventTimestampUtc ?? nowMs;
|
|
289
|
+
const serviceTier = inputData.serviceTier || 'standard';
|
|
290
|
+
const tracker = new SwarmIdleTtlTracker({
|
|
291
|
+
initialRoster: inputData.swarmRoster || sidecar.swarmRoster,
|
|
292
|
+
cacheTtlMs: inputData.cacheTtlMs ?? 300000,
|
|
293
|
+
coldWakeThresholdTokens: inputData.coldWakeThresholdTokens ?? 100000
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
let coldCacheWakeup = null;
|
|
297
|
+
let systemMessage = gateSystemMessage;
|
|
298
|
+
let astSignatureStub = null;
|
|
299
|
+
let deltaDiffStub = null;
|
|
300
|
+
let astStubSavedTokens = 0;
|
|
301
|
+
|
|
302
|
+
if (!isOffMode && (toolName === 'read_file' || toolName === 'Read' || toolName === 'view_file')) {
|
|
303
|
+
const rawTarget = String(
|
|
304
|
+
toolInput?.Path || toolInput?.path || toolInput?.file_path || toolInput?.TargetFile || toolInput?.AbsolutePath || ''
|
|
305
|
+
).trim();
|
|
306
|
+
const hasLineBounds = Number.isFinite(Number(toolInput?.StartLine ?? toolInput?.start_line ?? toolInput?.offset)) ||
|
|
307
|
+
Number.isFinite(Number(toolInput?.EndLine ?? toolInput?.end_line ?? toolInput?.limit));
|
|
308
|
+
if (rawTarget && !hasLineBounds) {
|
|
309
|
+
const resolvedPath = path.isAbsolute(rawTarget) ? rawTarget : path.resolve(workspacePath, rawTarget);
|
|
310
|
+
const normKey = resolvedPath.replace(/\\/g, '/').toLowerCase();
|
|
311
|
+
if (!sidecar.fileState || typeof sidecar.fileState !== 'object') sidecar.fileState = {};
|
|
312
|
+
if (!sidecar.fileState.unclippedReadCounts || typeof sidecar.fileState.unclippedReadCounts !== 'object') {
|
|
313
|
+
sidecar.fileState.unclippedReadCounts = {};
|
|
314
|
+
}
|
|
315
|
+
if (!sidecar.fileState.readSnapshots || typeof sidecar.fileState.readSnapshots !== 'object') {
|
|
316
|
+
sidecar.fileState.readSnapshots = {};
|
|
317
|
+
}
|
|
318
|
+
const priorReads = Number(inputData.priorUnclippedReads ?? sidecar.fileState.unclippedReadCounts[normKey] ?? 0);
|
|
319
|
+
const nextReads = priorReads + 1;
|
|
320
|
+
sidecar.fileState.unclippedReadCounts[normKey] = nextReads;
|
|
321
|
+
|
|
322
|
+
if (fs.existsSync(resolvedPath)) {
|
|
323
|
+
try {
|
|
324
|
+
const stat = fs.statSync(resolvedPath);
|
|
325
|
+
if (stat.isFile() && stat.size > 256 && stat.size <= 512 * 1024) {
|
|
326
|
+
const rawContent = fs.readFileSync(resolvedPath, 'utf8');
|
|
327
|
+
const prevSnap = typeof inputData.priorContentSnapshot === 'string'
|
|
328
|
+
? inputData.priorContentSnapshot
|
|
329
|
+
: (typeof sidecar.fileState.readSnapshots[normKey] === 'string' ? sidecar.fileState.readSnapshots[normKey] : null);
|
|
330
|
+
|
|
331
|
+
if (prevSnap !== null && prevSnap !== rawContent) {
|
|
332
|
+
const delta = computeCompactLineDiff(prevSnap, rawContent, path.basename(resolvedPath));
|
|
333
|
+
if (delta.wasDiffed) {
|
|
334
|
+
deltaDiffStub = delta.diffText;
|
|
335
|
+
astStubSavedTokens = delta.savedTokens;
|
|
336
|
+
const deltaNotice = `[Highbeam Post-Edit Delta Read — ${path.basename(resolvedPath)} (+${delta.savedTokens} tokens saved)]\n${delta.diffText}`;
|
|
337
|
+
if (!isSilentMode && !systemMessage) {
|
|
338
|
+
systemMessage = deltaNotice;
|
|
339
|
+
}
|
|
340
|
+
try {
|
|
341
|
+
recordAntigravitySidecarSavings(sidecar, {
|
|
342
|
+
category: 'BOUNDED_READ_ENFORCED',
|
|
343
|
+
savedTokens: delta.savedTokens,
|
|
344
|
+
detail: `Post-edit delta read for ${path.basename(resolvedPath)}`,
|
|
345
|
+
nowMs: inputData.nowMs ?? inputData.eventTimestampUtc ?? Date.now()
|
|
346
|
+
});
|
|
347
|
+
} catch (err) {
|
|
348
|
+
recordHookDiagnostic('pre_invocation', 'handlePreToolUse.recordDeltaSavings', err);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
} else if (nextReads >= 3 && stat.size > 512) {
|
|
352
|
+
const fullTokens = Math.max(1, Math.ceil(rawContent.length / 4));
|
|
353
|
+
const folded = foldCodeToSignatureStub(rawContent, resolvedPath);
|
|
354
|
+
const stubText = typeof folded?.condensed === 'string' && folded.condensed.length > 0
|
|
355
|
+
? folded.condensed
|
|
356
|
+
: rawContent.slice(0, 1200);
|
|
357
|
+
const stubTokens = Math.max(1, Math.ceil(stubText.length / 4));
|
|
358
|
+
astStubSavedTokens = Math.max(0, fullTokens - stubTokens);
|
|
359
|
+
astSignatureStub = stubText;
|
|
360
|
+
const stubNotice = `[Highbeam AST Signature Stub — Read #${nextReads} of ${path.basename(resolvedPath)} (${astStubSavedTokens} tokens saved; pass StartLine/EndLine for full bodies)]\n${stubText}`;
|
|
361
|
+
if (!isSilentMode && !systemMessage) {
|
|
362
|
+
systemMessage = stubNotice;
|
|
363
|
+
}
|
|
364
|
+
if (astStubSavedTokens > 0) {
|
|
365
|
+
try {
|
|
366
|
+
recordAntigravitySidecarSavings(sidecar, {
|
|
367
|
+
category: 'BOUNDED_READ_ENFORCED',
|
|
368
|
+
savedTokens: astStubSavedTokens,
|
|
369
|
+
detail: `AST signature stub read #${nextReads} for ${path.basename(resolvedPath)}`,
|
|
370
|
+
nowMs: inputData.nowMs ?? inputData.eventTimestampUtc ?? Date.now()
|
|
371
|
+
});
|
|
372
|
+
} catch (err) {
|
|
373
|
+
recordHookDiagnostic('pre_invocation', 'handlePreToolUse.recordAstStubSavings', err);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
if (rawContent.length <= 128 * 1024) {
|
|
379
|
+
const snapKeys = Object.keys(sidecar.fileState.readSnapshots);
|
|
380
|
+
if (!sidecar.fileState.readSnapshots[normKey] && snapKeys.length >= 12) {
|
|
381
|
+
delete sidecar.fileState.readSnapshots[snapKeys[0]];
|
|
382
|
+
}
|
|
383
|
+
sidecar.fileState.readSnapshots[normKey] = rawContent;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
} catch (err) {
|
|
387
|
+
recordHookDiagnostic('pre_invocation', 'handlePreToolUse.astSignatureStub', err);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
if (toolName === 'send_message' || toolInput?.Recipient || toolInput?.recipient || /@[a-z0-9_-]+/i.test(String(toolInput?.Message || toolInput?.message || toolInput?.brief || ''))) {
|
|
394
|
+
coldCacheWakeup = tracker.handlePreToolSendMessage(toolInput, {
|
|
395
|
+
nowMs,
|
|
396
|
+
eventTimestampUtc,
|
|
397
|
+
serviceTier
|
|
398
|
+
});
|
|
399
|
+
if (coldCacheWakeup.coldWakeDetected) {
|
|
400
|
+
if (isAutoPilotMode && !inputData.allowColdWake && Number(coldCacheWakeup.incrementalColdPenaltyUsd || 0) >= 0.5) {
|
|
401
|
+
return {
|
|
402
|
+
decision: 'block',
|
|
403
|
+
permissionDecision: 'deny',
|
|
404
|
+
terminationBehavior: 'terminate',
|
|
405
|
+
blocked: true,
|
|
406
|
+
flightMode,
|
|
407
|
+
autoPilotGate: 'COLD_CACHE_CLIFF_HOLD',
|
|
408
|
+
coldCacheWakeup,
|
|
409
|
+
reason: coldCacheWakeup.message,
|
|
410
|
+
userMessage: coldCacheWakeup.message,
|
|
411
|
+
systemMessage: coldCacheWakeup.message
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
if (!isSilentMode && !isOffMode) {
|
|
415
|
+
systemMessage = coldCacheWakeup.message;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
} else if (toolName === 'invoke_subagent' || toolName === 'define_subagent') {
|
|
419
|
+
const subagentId = toolInput?.ConversationId || toolInput?.conversationId || toolInput?.Name || toolInput?.TypeName || toolInput?.Role || 'subagent';
|
|
420
|
+
const subagentModel = toolInput?.Model && toolInput.Model !== 'inherit'
|
|
421
|
+
? toolInput.Model
|
|
422
|
+
: (sidecar.sessionMeta.active_model_id || sidecar.sessionMeta.activeModel || 'gemini-4-carbon');
|
|
423
|
+
tracker.touchAgentActive(subagentId, {
|
|
424
|
+
modelId: subagentModel,
|
|
425
|
+
warmPrefixTokens: Number(toolInput?.warm_prefix_tokens ?? 0),
|
|
426
|
+
timestampMs: nowMs
|
|
427
|
+
});
|
|
428
|
+
} else if (toolName === 'manage_subagents') {
|
|
429
|
+
const action = String(toolInput?.Action || toolInput?.action || '').toLowerCase();
|
|
430
|
+
if (action === 'kill' && Array.isArray(toolInput?.ConversationIds)) {
|
|
431
|
+
for (const id of toolInput.ConversationIds) {
|
|
432
|
+
tracker.terminateAgent(id, { timestampMs: nowMs });
|
|
433
|
+
}
|
|
434
|
+
} else if (action === 'kill_all') {
|
|
435
|
+
for (const id of Object.keys(tracker.getRosterSnapshot())) {
|
|
436
|
+
tracker.terminateAgent(id, { timestampMs: nowMs });
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
sidecar.swarmRoster = tracker.getRosterSnapshot();
|
|
442
|
+
sidecar.swarmTtlBadges = computeSwarmRosterTtlBadges(sidecar.swarmRoster, {
|
|
443
|
+
nowMs,
|
|
444
|
+
cacheTtlMs: inputData.cacheTtlMs ?? 300000
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
try {
|
|
448
|
+
writeSidecarAtomicSync(conversationId, sidecar);
|
|
449
|
+
} catch (err) {
|
|
450
|
+
recordHookDiagnostic('pre_invocation', 'handlePreToolUse.writeSidecar', err);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
const response = {
|
|
454
|
+
decision: 'allow',
|
|
455
|
+
flightMode,
|
|
456
|
+
active_model_id: sidecar.sessionMeta.active_model_id || sidecar.sessionMeta.activeModel || null,
|
|
457
|
+
pending_model_id: sidecar.sessionMeta.pending_model_id || null,
|
|
458
|
+
swarmTtlBadges: sidecar.swarmTtlBadges
|
|
459
|
+
};
|
|
460
|
+
if (coldCacheWakeup) response.coldCacheWakeup = coldCacheWakeup;
|
|
461
|
+
if (astSignatureStub) {
|
|
462
|
+
response.astSignatureStub = astSignatureStub;
|
|
463
|
+
response.savedTokens = astStubSavedTokens;
|
|
464
|
+
}
|
|
465
|
+
if (deltaDiffStub) {
|
|
466
|
+
response.deltaDiffStub = deltaDiffStub;
|
|
467
|
+
response.savedTokens = astStubSavedTokens;
|
|
468
|
+
}
|
|
469
|
+
if (systemMessage && !isSilentMode && !isOffMode) response.systemMessage = systemMessage;
|
|
470
|
+
return response;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
export async function handlePreInvocation(inputData = {}) {
|
|
474
|
+
if (
|
|
475
|
+
inputData.hook_event_name === 'PreToolUse' ||
|
|
476
|
+
inputData.event === 'PreToolUse' ||
|
|
477
|
+
inputData.tool_name ||
|
|
478
|
+
inputData.toolName ||
|
|
479
|
+
inputData.tool_input ||
|
|
480
|
+
inputData.args ||
|
|
481
|
+
inputData.parameters ||
|
|
482
|
+
inputData.Arguments ||
|
|
483
|
+
(typeof inputData.tool === 'string' && inputData.tool.length > 0) ||
|
|
484
|
+
(typeof inputData.name === 'string' && !inputData.prompt && !inputData.user_input)
|
|
485
|
+
) {
|
|
486
|
+
return handlePreToolUse(inputData);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
const config = inputData.configOverride || loadFlightcheckConfig();
|
|
490
|
+
const rawPrompt = String(inputData.prompt || inputData.user_input || inputData.message || '').trim();
|
|
491
|
+
const conversationId = inputData.conversationId || inputData.session_id || inputData.conversation_id || 'default_session';
|
|
492
|
+
const sidecar = readSidecarSync(conversationId);
|
|
493
|
+
const workspacePath = inputData.cwd || inputData.workspacePath || sidecar.workspacePath || process.cwd();
|
|
494
|
+
const horizonConfig = inputData.horizonConfig || loadHorizonConfig({
|
|
495
|
+
cwd: workspacePath,
|
|
496
|
+
...(inputData.homeDir ? { homeDir: inputData.homeDir } : {})
|
|
497
|
+
});
|
|
498
|
+
const flightMode = String(inputData.flightMode || horizonConfig.flightMode || 'COACH').toUpperCase();
|
|
499
|
+
|
|
500
|
+
// 1. Control Flags & flightMode Handling (ISS-039)
|
|
501
|
+
if (config.hook_level === 'off' || flightMode === 'OFF') {
|
|
502
|
+
return {};
|
|
503
|
+
}
|
|
504
|
+
if (flightMode === 'SILENT') {
|
|
505
|
+
// SILENT suppresses all non-Ring-0 advisory context/stderr chatter on PreInvocation
|
|
506
|
+
// (Ring-0 security blocks remain active in PreToolUse and workspace settings checks).
|
|
507
|
+
if (resolveDetectorOverride(horizonConfig, 'DET-18') !== 'off' && inputData.scanWorkspaceSettings === true) {
|
|
508
|
+
const det18 = evaluateDet18UntrustedWorkspaceSettings([], { workspacePath, scanWorkspace: true });
|
|
509
|
+
if (det18) {
|
|
510
|
+
return { terminationBehavior: 'terminate', decision: 'block', detectorId: 'DET-18', userMessage: det18.message };
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
return {};
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
const sessionMeta = sidecar.sessionMeta || {};
|
|
517
|
+
const telemetry = sidecar.telemetry || {};
|
|
518
|
+
const sensors = sidecar.sensors || {};
|
|
519
|
+
const fileState = sidecar.fileState || {};
|
|
520
|
+
|
|
521
|
+
if (rawPrompt.includes('!lock')) {
|
|
522
|
+
sessionMeta.effortLocked = true;
|
|
523
|
+
sidecar.sessionMeta = sessionMeta;
|
|
524
|
+
try {
|
|
525
|
+
writeSidecarAtomicSync(conversationId, sidecar);
|
|
526
|
+
} catch (err) {
|
|
527
|
+
recordHookDiagnostic('pre_invocation', 'effortLock.writeSidecar', err);
|
|
528
|
+
}
|
|
529
|
+
return {};
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
if (rawPrompt.startsWith('! ') || rawPrompt === '!' || rawPrompt.startsWith('!force')) {
|
|
533
|
+
return {};
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
const hasCheckTag = /#check\b/i.test(rawPrompt);
|
|
537
|
+
const turnCount = sessionMeta.turnCount || 0;
|
|
538
|
+
const purity = telemetry.signalPurityPct ?? 100.0;
|
|
539
|
+
const tokens = telemetry.totalInputTokens || 0;
|
|
540
|
+
const activeEffort = inputData.effort || sessionMeta.activeEffort || 'high';
|
|
541
|
+
const activeModel = inputData.modelName || sessionMeta.activeModel || (config.recommended_models?.fast || 'gemini-3.8-flash');
|
|
542
|
+
const quotaFrac = telemetry.quota?.remaining_fraction ?? 1.0;
|
|
543
|
+
const ceiling = resolveModelCeiling(activeModel, null, { config }) || 256000;
|
|
544
|
+
const ceilingK = Math.round(ceiling / 1000);
|
|
545
|
+
|
|
546
|
+
// In AUTO_PILOT mode, enforce active guard halts even if legacy hook_level was 'advisory'
|
|
547
|
+
const hookLevel = flightMode === 'AUTO_PILOT' ? 'guard' : (config.hook_level || 'guard');
|
|
548
|
+
const cooldownTurns = config.halt_cooldown_turns ?? 3;
|
|
549
|
+
const lastHalts = { ...(sessionMeta.lastHalts || {}) };
|
|
550
|
+
const isTelemetryReliable = telemetry.confidence !== 'LOW';
|
|
551
|
+
|
|
552
|
+
function haltOrAdvise(stateKey, card, { exemptFromCooldown = false } = {}) {
|
|
553
|
+
const lastFiredTurn = lastHalts[stateKey];
|
|
554
|
+
const isWithinCooldown = typeof lastFiredTurn === 'number' && ((turnCount - lastFiredTurn) <= cooldownTurns);
|
|
555
|
+
|
|
556
|
+
if (hookLevel === 'advisory' || (isWithinCooldown && !exemptFromCooldown)) {
|
|
557
|
+
return { systemMessage: card };
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
lastHalts[stateKey] = turnCount;
|
|
561
|
+
sessionMeta.lastHalts = lastHalts;
|
|
562
|
+
sidecar.sessionMeta = sessionMeta;
|
|
563
|
+
try {
|
|
564
|
+
writeSidecarAtomicSync(conversationId, sidecar);
|
|
565
|
+
} catch (err) {
|
|
566
|
+
recordHookDiagnostic('pre_invocation', 'haltOrAdvise.writeSidecar', err);
|
|
567
|
+
}
|
|
568
|
+
return { terminationBehavior: 'terminate', userMessage: card };
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
function applyHabitOverride(slug, stateKey, card, { detectorId = null, defaultMode = 'haltOrAdvise', extraWarn = {}, extraBlock = {} } = {}) {
|
|
572
|
+
const override = resolveDetectorOverride(horizonConfig, slug);
|
|
573
|
+
if (override === 'off') return null;
|
|
574
|
+
if (override === 'warn') {
|
|
575
|
+
return { systemMessage: card, ...(detectorId ? { detectorId } : {}), ...extraWarn };
|
|
576
|
+
}
|
|
577
|
+
if (override === 'block') {
|
|
578
|
+
lastHalts[stateKey] = turnCount;
|
|
579
|
+
sessionMeta.lastHalts = lastHalts;
|
|
580
|
+
sidecar.sessionMeta = sessionMeta;
|
|
581
|
+
try {
|
|
582
|
+
writeSidecarAtomicSync(conversationId, sidecar);
|
|
583
|
+
} catch (err) {
|
|
584
|
+
recordHookDiagnostic('pre_invocation', 'applyHabitOverride.writeSidecar', err);
|
|
585
|
+
}
|
|
586
|
+
return {
|
|
587
|
+
terminationBehavior: 'terminate',
|
|
588
|
+
decision: 'block',
|
|
589
|
+
...(detectorId ? { detectorId } : {}),
|
|
590
|
+
userMessage: card,
|
|
591
|
+
...extraBlock
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
if (defaultMode === 'flightMode') {
|
|
595
|
+
if (flightMode === 'AUTO_PILOT') {
|
|
596
|
+
return {
|
|
597
|
+
terminationBehavior: 'terminate',
|
|
598
|
+
decision: 'block',
|
|
599
|
+
...(detectorId ? { detectorId } : {}),
|
|
600
|
+
userMessage: card,
|
|
601
|
+
...extraBlock
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
return { systemMessage: card, ...(detectorId ? { detectorId } : {}), ...extraWarn };
|
|
605
|
+
}
|
|
606
|
+
return haltOrAdvise(stateKey, card);
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
// 2. ALLOW_PLAN_OR_SUBAGENT
|
|
610
|
+
if (!hasCheckTag && (sessionMeta.inPlanMode || sessionMeta.lastTurnUsedSubagent)) {
|
|
611
|
+
if (!telemetry.amputationRisk && !sensors.threeStrikeLoop) {
|
|
612
|
+
return {};
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// 3. HALT_HYGIENE_OR_SAFETY
|
|
617
|
+
const isHighOrMaxEffort = activeEffort === 'high' || activeEffort === 'max';
|
|
618
|
+
if (telemetry.amputationRisk && isTelemetryReliable) {
|
|
619
|
+
const handoff = sidecar.handoff || {};
|
|
620
|
+
const handoffAction = handoff.result === 'NEEDS_FIXES'
|
|
621
|
+
? `Handoff NEEDS FIXES: ${(handoff.failingChecks || []).slice(0, 2).join('; ') || 'update task.md'}`
|
|
622
|
+
: `/clear or /compact`;
|
|
623
|
+
const rewriteCmd = handoff.result === 'NEEDS_FIXES'
|
|
624
|
+
? `"Update task.md checkpoint (/handoff), then type /compact or /clear"`
|
|
625
|
+
: `"Save progress to task.md and start a clean session with /clear (or /compact)"`;
|
|
626
|
+
|
|
627
|
+
const card = formatScorecard(
|
|
628
|
+
`[Amputation Crisis] Tokens: ${Math.round(tokens / 1000)}k/${ceilingK}k (Context Truncation Risk)`,
|
|
629
|
+
`[Useful Context: ${purity}% | Oldest Rules at Risk]`,
|
|
630
|
+
handoffAction,
|
|
631
|
+
rewriteCmd
|
|
632
|
+
);
|
|
633
|
+
return haltOrAdvise('AMPUTATION_CRISIS', card, { exemptFromCooldown: true });
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
if (sensors.threeStrikeLoop) {
|
|
637
|
+
const loopInfo = sensors.loopFingerprint
|
|
638
|
+
? `Loop: ${sensors.loopFingerprint.slice(0, 48)}`
|
|
639
|
+
: 'Consecutive command failures detected';
|
|
640
|
+
const card = formatScorecard(
|
|
641
|
+
`[3-Strike Error Loop] ${loopInfo}`,
|
|
642
|
+
`[Useful Context: ${purity}% | Errors: 3 strikes]`,
|
|
643
|
+
`Break loop: isolate with subagent or compact`,
|
|
644
|
+
`"Diagnose previous errors using invoke_subagent or run /compact"`
|
|
645
|
+
);
|
|
646
|
+
return haltOrAdvise('THREE_STRIKE_LOOP', card);
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
if (fileState.foreignBleedKiIds && fileState.foreignBleedKiIds.length > 0 && sessionMeta.inPlanMode) {
|
|
650
|
+
const card = formatScorecard(
|
|
651
|
+
`[Foreign KI Bleed] Injected memory from other workspace`,
|
|
652
|
+
`[Bleed IDs: ${fileState.foreignBleedKiIds.join(', ')}]`,
|
|
653
|
+
`/context`,
|
|
654
|
+
`"Eject foreign knowledge items in /context before planning"`
|
|
655
|
+
);
|
|
656
|
+
return haltOrAdvise('FOREIGN_BLEED', card);
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
if (isTelemetryReliable && purity < (config.compact_halt_purity_pct || 45.0) && isHighOrMaxEffort) {
|
|
660
|
+
const card = formatScorecard(
|
|
661
|
+
`[Low Useful Context] ${purity}% useful context on ${activeEffort} effort`,
|
|
662
|
+
`[Wasted Context: +$${(telemetry.sludgeTaxUsdPerTurn || 0).toFixed(2)}/turn]`,
|
|
663
|
+
`/compact`,
|
|
664
|
+
`"Run /compact to compress stale reads before high-effort execution"`
|
|
665
|
+
);
|
|
666
|
+
return haltOrAdvise('LOW_PURITY', card);
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
if (sensors.uncheckpointedGitDrift) {
|
|
670
|
+
const card = formatScorecard(
|
|
671
|
+
`[Uncheckpointed Drift] ${sensors.dirtyGitFileCount || 4}+ dirty files untested`,
|
|
672
|
+
`[Git Drift: >=3 turns without passing test]`,
|
|
673
|
+
`git commit or run test`,
|
|
674
|
+
`"Run unit tests and commit working changes before editing further"`
|
|
675
|
+
);
|
|
676
|
+
return haltOrAdvise('GIT_DRIFT', card);
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
// 4. HALT_EFFORT_OR_QUOTA
|
|
680
|
+
const fastModel = config.recommended_models?.fast || 'gemini-3.8-flash';
|
|
681
|
+
const deepModel = config.recommended_models?.deep || 'gemini-3.1-pro';
|
|
682
|
+
|
|
683
|
+
if (isTelemetryReliable && sensors.quotaFloorBreached && (activeModel.includes('pro') || activeModel.includes('argon') || activeModel.includes('carbon') || activeEffort === 'max')) {
|
|
684
|
+
const card = formatScorecard(
|
|
685
|
+
`[Quota Floor Breached] 5h Quota: ${Math.round(quotaFrac * 100)}% (<10%)`,
|
|
686
|
+
`[Tokens: ${Math.round(tokens / 1000)}k | Risk: 0% lockout]`,
|
|
687
|
+
`/model ${fastModel} • /effort low`,
|
|
688
|
+
`"Switch to ${fastModel} on low effort to preserve remaining quota"`
|
|
689
|
+
);
|
|
690
|
+
return haltOrAdvise('QUOTA_FLOOR', card);
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
const promptTokenEst = Math.max(1, Math.ceil(rawPrompt.length / 4));
|
|
694
|
+
const isColdCache = tokens < 10000;
|
|
695
|
+
const isTrivial = promptTokenEst < 15;
|
|
696
|
+
if (isTelemetryReliable && !sessionMeta.effortLocked && isTrivial && (sessionMeta.consecutiveTrivialOnMax >= 2 || (isColdCache && (activeModel.includes('pro') || activeModel.includes('argon') || activeModel.includes('carbon')) && activeEffort === 'max'))) {
|
|
697
|
+
const card = formatScorecard(
|
|
698
|
+
`[Effort Overkill] Trivial edit (${promptTokenEst} tokens) on max effort`,
|
|
699
|
+
`[Cold cache / trivial turn]`,
|
|
700
|
+
`/model ${fastModel} • /effort low`,
|
|
701
|
+
`"Run trivial single-file edit on ${fastModel} / low effort"`
|
|
702
|
+
);
|
|
703
|
+
const effortRes = applyHabitOverride('effort-overkill', 'EFFORT_OVERKILL', card);
|
|
704
|
+
if (effortRes) return effortRes;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
// 4b. Local Formatter / Import Sorter Bypass (DET-15 / 'formatter-bypass')
|
|
708
|
+
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);
|
|
709
|
+
const pastedLineCount = (rawPrompt.match(/\r?\n/g) || []).length;
|
|
710
|
+
if (isFormattingIntent && pastedLineCount >= 40 && !/\b(add|implement|refactor|create|fix\s+bug|logic|test|calculate)\b/i.test(rawPrompt)) {
|
|
711
|
+
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).';
|
|
712
|
+
const fmtRes = applyHabitOverride('formatter-bypass', 'LOCAL_FORMATTER_BYPASS', bypassNotice, {
|
|
713
|
+
detectorId: 'DET-15',
|
|
714
|
+
defaultMode: 'flightMode'
|
|
715
|
+
});
|
|
716
|
+
if (fmtRes) return fmtRes;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
// 5. INJECT_CONTEXT_GUARD
|
|
720
|
+
const guards = [];
|
|
721
|
+
const eventTimestampUtc = inputData.eventTimestampUtc ?? null;
|
|
722
|
+
if (isModelDeprecated(activeModel, eventTimestampUtc)) {
|
|
723
|
+
const notice = getDeprecatedModelMigrationNotice(activeModel, eventTimestampUtc);
|
|
724
|
+
if (notice) guards.push(notice);
|
|
725
|
+
}
|
|
726
|
+
const recentTurns = inputData.recentTurns || sidecar.recentTurns || [];
|
|
727
|
+
if (Array.isArray(recentTurns) && recentTurns.length >= 2) {
|
|
728
|
+
const verbosityGuard = evaluateCarbonVerbosityGuardrail(recentTurns, {
|
|
729
|
+
modelId: activeModel,
|
|
730
|
+
activeEffort,
|
|
731
|
+
eventTimestampUtc
|
|
732
|
+
});
|
|
733
|
+
if (verbosityGuard.triggered && verbosityGuard.prescription) {
|
|
734
|
+
guards.push(verbosityGuard.prescription);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
if (!isTelemetryReliable) {
|
|
738
|
+
guards.push('Telemetry confidence DEGRADED (parser schema drift detected) — running fail-open');
|
|
739
|
+
}
|
|
740
|
+
if (fileState.dirtySnapshotPaths && fileState.dirtySnapshotPaths.length > 0) {
|
|
741
|
+
guards.push(`Dirty Snapshots modified externally: ${fileState.dirtySnapshotPaths.slice(0, 2).join(', ')} — re-read with view_file before editing`);
|
|
742
|
+
}
|
|
743
|
+
if (fileState.unseenCallers && fileState.unseenCallers.length > 0) {
|
|
744
|
+
guards.push(`Unseen Callers importing target: ${fileState.unseenCallers.slice(0, 2).join(', ')} — verify signature compatibility`);
|
|
745
|
+
}
|
|
746
|
+
if (fileState.legacyPoisonPaths && fileState.legacyPoisonPaths.length > 0) {
|
|
747
|
+
guards.push(`Legacy Poison paths in context: ${fileState.legacyPoisonPaths.slice(0, 2).join(', ')} — avoid copying deprecated patterns`);
|
|
748
|
+
}
|
|
749
|
+
if (fileState.streamCutoffRiskFiles && fileState.streamCutoffRiskFiles.length > 0) {
|
|
750
|
+
guards.push(`Stream Cutoff Risk (>600 lines): ${fileState.streamCutoffRiskFiles.slice(0, 2).join(', ')} — use surgical edit chunks under 300 lines`);
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
if (guards.length > 0) {
|
|
754
|
+
return {
|
|
755
|
+
systemMessage: `[Flight Check Context Guard] Active hazards: ${guards.join('; ')}`
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
// 6. STEER_SUBAGENT
|
|
760
|
+
const isComplexTopic = /(concurrency|deadlock|race condition|architecture refactor|multi-module)/i.test(rawPrompt);
|
|
761
|
+
if (tokens >= (config.subagent_min_cache_tokens || 25000) &&
|
|
762
|
+
purity >= (config.subagent_min_purity_pct || 70.0) &&
|
|
763
|
+
(activeEffort === 'low' || activeEffort === 'medium') &&
|
|
764
|
+
isComplexTopic) {
|
|
765
|
+
return {
|
|
766
|
+
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.`
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
// 7. ALLOW_ACTIVE_SET & Trust Decay
|
|
771
|
+
const matchedScope = (fileState.activeSetPaths || fileState.modifiedFiles || []).find(p => {
|
|
772
|
+
const base = path.basename(p);
|
|
773
|
+
return rawPrompt.includes(base) || rawPrompt.includes(p);
|
|
774
|
+
}) || '';
|
|
775
|
+
const hasActiveSetMatch = Boolean(matchedScope);
|
|
776
|
+
|
|
777
|
+
// Conversational Drip-Feeding check (DET-02B):
|
|
778
|
+
// Even if prompt mentions activeSetPaths, 4+ rapid micro-prompts (<= 18 words) targeting the same file within 90s trigger advisory
|
|
779
|
+
const timestampMs = Number(inputData.timestampMs ?? inputData.nowMs ?? inputData.timestamp ?? Date.now());
|
|
780
|
+
const wordCount = rawPrompt.split(/\s+/).filter(Boolean).length;
|
|
781
|
+
sessionMeta.recentPrompts = Array.isArray(sessionMeta.recentPrompts) ? sessionMeta.recentPrompts : [];
|
|
782
|
+
sessionMeta.recentPrompts = sessionMeta.recentPrompts.filter(e => (timestampMs - e.ts) <= 90000);
|
|
783
|
+
sessionMeta.recentPrompts.push({ ts: timestampMs, wordCount, targetScope: matchedScope });
|
|
784
|
+
sidecar.sessionMeta = sessionMeta;
|
|
785
|
+
try {
|
|
786
|
+
writeSidecarAtomicSync(conversationId, sidecar);
|
|
787
|
+
} catch (err) {
|
|
788
|
+
recordHookDiagnostic('pre_invocation', 'recentPrompts.writeSidecar', err);
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
const rapidSameScopeCount = sessionMeta.recentPrompts.filter(
|
|
792
|
+
e => e.targetScope && e.targetScope === matchedScope && e.wordCount <= 18
|
|
793
|
+
).length;
|
|
794
|
+
|
|
795
|
+
if (rapidSameScopeCount >= 4) {
|
|
796
|
+
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.`;
|
|
797
|
+
const dripRes = applyHabitOverride('drip-feed', 'CONVERSATIONAL_DRIP_FEED', dripCard, {
|
|
798
|
+
detectorId: 'DET-02B',
|
|
799
|
+
defaultMode: 'flightMode',
|
|
800
|
+
extraWarn: { continue: true },
|
|
801
|
+
extraBlock: { continue: false }
|
|
802
|
+
});
|
|
803
|
+
if (dripRes) return dripRes;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
if (!hasCheckTag) {
|
|
807
|
+
if (hasActiveSetMatch) return {};
|
|
808
|
+
if (config.hook_level === 'guard' && turnCount > (config.trust_decay_turn_threshold || 10)) {
|
|
809
|
+
return {};
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// 8a. Prompt Hygiene Governor (v4.1 Phase 1): Relay Breaker ('relay-breaker') & Scope Brake ('vague-prompt-rubric')
|
|
814
|
+
const relayOverride = resolveDetectorOverride(horizonConfig, 'relay-breaker');
|
|
815
|
+
const relayEval = evaluateRelayBreaker({
|
|
816
|
+
prompt: rawPrompt,
|
|
817
|
+
relayState: inputData.relayState ?? sessionMeta.relayState,
|
|
818
|
+
sourceCodeEditsInSession: Number(inputData.sourceCodeEditsInSession ?? (fileState.modifiedFiles || []).filter(p => !/\.md$/i.test(String(p || ''))).length),
|
|
819
|
+
sourceCodeEditedSinceLastRelay: Boolean(inputData.sourceCodeEditedSinceLastRelay),
|
|
820
|
+
priorTurnWebSearches: Number(inputData.priorTurnWebSearches ?? sessionMeta.priorTurnWebSearches ?? 0),
|
|
821
|
+
zeroEditSessionTokens: Number(inputData.zeroEditSessionTokens ?? (((fileState.modifiedFiles || []).length === 0) ? tokens : 0)),
|
|
822
|
+
boundSpecPath: inputData.boundSpecPath ?? sessionMeta.relayState?.boundSpecPath ?? null,
|
|
823
|
+
overrideMode: relayOverride,
|
|
824
|
+
flightMode,
|
|
825
|
+
detectorId: 'DET-26'
|
|
826
|
+
});
|
|
827
|
+
sessionMeta.relayState = relayEval.relayStateSnapshot;
|
|
828
|
+
if (relayEval.triggered) {
|
|
829
|
+
sidecar.sessionMeta = sessionMeta;
|
|
830
|
+
try {
|
|
831
|
+
writeSidecarAtomicSync(conversationId, sidecar);
|
|
832
|
+
} catch (err) {
|
|
833
|
+
recordHookDiagnostic('pre_invocation', 'relayBreaker.writeSidecar', err);
|
|
834
|
+
}
|
|
835
|
+
if (relayEval.decision === 'block') {
|
|
836
|
+
sessionMeta.blockedPrompts = Number(sessionMeta.blockedPrompts || 0) + 1;
|
|
837
|
+
return {
|
|
838
|
+
terminationBehavior: 'terminate',
|
|
839
|
+
decision: 'block',
|
|
840
|
+
detectorId: 'DET-26',
|
|
841
|
+
subType: relayEval.subType,
|
|
842
|
+
relayState: relayEval.nextState,
|
|
843
|
+
userMessage: relayEval.tailInjection
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
sessionMeta.steeredPrompts = Number(sessionMeta.steeredPrompts || 0) + 1;
|
|
847
|
+
return {
|
|
848
|
+
ephemeralMessage: relayEval.tailInjection,
|
|
849
|
+
systemMessage: relayEval.tailInjection,
|
|
850
|
+
detectorId: 'DET-26',
|
|
851
|
+
subType: relayEval.subType,
|
|
852
|
+
relayState: relayEval.nextState
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
const scopeOverride = resolveDetectorOverride(horizonConfig, 'vague-prompt-rubric');
|
|
857
|
+
const scopeEval = evaluateScopeBrake({
|
|
858
|
+
prompt: rawPrompt,
|
|
859
|
+
provenance: inputData.provenance || inputData.source || 'user',
|
|
860
|
+
isAutonomousTurn: Boolean(inputData.isAutonomousTurn || inputData.autonomous),
|
|
861
|
+
isSubagent: Boolean(inputData.isSubagent || sessionMeta.isSubagent),
|
|
862
|
+
isScheduledTask: Boolean(inputData.isScheduledTask),
|
|
863
|
+
isLoopIteration: Boolean(inputData.isLoopIteration),
|
|
864
|
+
priorTurnEditedFilesCount: Number(
|
|
865
|
+
inputData.priorTurnEditedFilesCount ??
|
|
866
|
+
(Array.isArray(sessionMeta.lastTurnEditedFiles) ? sessionMeta.lastTurnEditedFiles.length : 0)
|
|
867
|
+
),
|
|
868
|
+
priorTurnSingleFileTarget: inputData.priorTurnSingleFileTarget ?? sessionMeta.priorTurnSingleFileTarget ?? null,
|
|
869
|
+
priorTurnHadToolOrTestFailure: Boolean(
|
|
870
|
+
inputData.priorTurnHadToolOrTestFailure ??
|
|
871
|
+
sensors.lastTurnToolFailed ??
|
|
872
|
+
sensors.threeStrikeLoop
|
|
873
|
+
),
|
|
874
|
+
priorTurnAssistantAskedQuestion: Boolean(
|
|
875
|
+
inputData.priorTurnAssistantAskedQuestion ?? sessionMeta.lastTurnAskedQuestion
|
|
876
|
+
),
|
|
877
|
+
activeSetPaths: fileState.activeSetPaths || [],
|
|
878
|
+
modifiedFiles: fileState.modifiedFiles || [],
|
|
879
|
+
recentlyViewedFiles: fileState.recentlyViewedFiles || [],
|
|
880
|
+
overrideMode: scopeOverride,
|
|
881
|
+
flightMode,
|
|
882
|
+
detectorId: 'DET-26'
|
|
883
|
+
});
|
|
884
|
+
if (scopeEval.triggered) {
|
|
885
|
+
sessionMeta.unanchoredTurnFlag = true;
|
|
886
|
+
sidecar.sessionMeta = sessionMeta;
|
|
887
|
+
try {
|
|
888
|
+
writeSidecarAtomicSync(conversationId, sidecar);
|
|
889
|
+
} catch (err) {
|
|
890
|
+
recordHookDiagnostic('pre_invocation', 'scopeBrake.writeSidecar', err);
|
|
891
|
+
}
|
|
892
|
+
if (scopeEval.decision === 'block') {
|
|
893
|
+
sessionMeta.blockedPrompts = Number(sessionMeta.blockedPrompts || 0) + 1;
|
|
894
|
+
return {
|
|
895
|
+
terminationBehavior: 'terminate',
|
|
896
|
+
decision: 'block',
|
|
897
|
+
detectorId: 'DET-26',
|
|
898
|
+
subType: scopeEval.subType,
|
|
899
|
+
userMessage: scopeEval.blockReason
|
|
900
|
+
};
|
|
901
|
+
}
|
|
902
|
+
sessionMeta.steeredPrompts = Number(sessionMeta.steeredPrompts || 0) + 1;
|
|
903
|
+
return {
|
|
904
|
+
ephemeralMessage: scopeEval.steerContext,
|
|
905
|
+
systemMessage: scopeEval.steerContext,
|
|
906
|
+
detectorId: 'DET-26',
|
|
907
|
+
subType: scopeEval.subType,
|
|
908
|
+
candidateFiles: scopeEval.candidateFiles
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
sessionMeta.unanchoredTurnFlag = false;
|
|
912
|
+
|
|
913
|
+
// 8b. HALT_REWRITE_SCORECARD (Explicit #check or Cold Session Vague Multi-File Prompt)
|
|
914
|
+
const isColdSession = turnCount <= (config.cold_session_max_turns || 3);
|
|
915
|
+
const promptSufficiency = scorePromptSufficiency(rawPrompt, { activeSetPaths: fileState.activeSetPaths });
|
|
916
|
+
const isArchitecturalVague = promptSufficiency.score <= 4 &&
|
|
917
|
+
/\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);
|
|
918
|
+
const isVagueMultiFile = (/(refactor everything|fix all|update the whole project|caching)/i.test(rawPrompt) || isArchitecturalVague) && !rawPrompt.includes('@');
|
|
919
|
+
|
|
920
|
+
// Ground rule: "Short prompts are not bad by default" - concise scoped instructions shouldn't trigger vague halt
|
|
921
|
+
if (hasCheckTag || (isColdSession && isVagueMultiFile && (!promptSufficiency.shortPrompt || isArchitecturalVague))) {
|
|
922
|
+
const cleanedPrompt = rawPrompt.replace(/#check\b/gi, '').trim();
|
|
923
|
+
const recommendedModel = tokens > 50000 ? deepModel : fastModel;
|
|
924
|
+
const recommendedEffort = isComplexTopic ? 'high' : 'medium';
|
|
925
|
+
const rawTargetHint = (fileState.activeSetPaths && fileState.activeSetPaths[0]) || '';
|
|
926
|
+
const targetHint = (rawTargetHint ? toWorkspaceRelativePath(rawTargetHint, sidecar.workspacePath || process.cwd()) : '') || '<target-file>';
|
|
927
|
+
const missingSnippet = promptSufficiency.missing.length > 0 ? ` | Missing: ${promptSufficiency.missing[0]}` : '';
|
|
928
|
+
|
|
929
|
+
const rewriteSuggestion = promptSufficiency.missing.includes('testability & expected outcome')
|
|
930
|
+
? `"In @${targetHint}, ${cleanedPrompt || 'implement updates'} and run automated tests to verify"`
|
|
931
|
+
: `"In @${targetHint}, ${cleanedPrompt || 'implement surgical updates with unit test'}"`;
|
|
932
|
+
|
|
933
|
+
const card = formatScorecard(
|
|
934
|
+
`[Sufficiency ${promptSufficiency.score}/12 ${promptSufficiency.band}]${missingSnippet}`,
|
|
935
|
+
`[Purity: ${purity}% | Sludge: +$${(telemetry.sludgeTaxUsdPerTurn || 0).toFixed(2)}/t | Tokens: ${Math.round(tokens / 1000)}k]`,
|
|
936
|
+
`/model ${recommendedModel} • /effort ${recommendedEffort}`,
|
|
937
|
+
rewriteSuggestion
|
|
938
|
+
);
|
|
939
|
+
const vagueRes = applyHabitOverride('vague-prompt-rubric', 'REWRITE_SCORECARD', card);
|
|
940
|
+
if (vagueRes) return vagueRes;
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
return {};
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
/**
|
|
947
|
+
* Sanitizes internal hook return payloads into strict Antigravity protojson-compatible
|
|
948
|
+
* CLI stdout objects (no unknown fields like flightMode, active_model_id, swarmTtlBadges).
|
|
949
|
+
*/
|
|
950
|
+
export function toProtoSafePreHookOutput(output, { isPreToolUse = false } = {}) {
|
|
951
|
+
const out = output && typeof output === 'object' ? output : {};
|
|
952
|
+
if (isPreToolUse) {
|
|
953
|
+
const rawDecision = String(out.decision || '').toLowerCase();
|
|
954
|
+
let decision = 'allow';
|
|
955
|
+
if (rawDecision === 'deny' || rawDecision === 'block' || out.blocked === true || out.terminationBehavior === 'terminate') {
|
|
956
|
+
decision = 'deny';
|
|
957
|
+
} else if (rawDecision === 'ask') {
|
|
958
|
+
decision = 'ask';
|
|
959
|
+
}
|
|
960
|
+
const reasonText = out.reason || out.errorMessage?.userMessage || out.userMessage || out.systemMessage || out.ephemeralMessage;
|
|
961
|
+
if (decision !== 'allow' && reasonText) {
|
|
962
|
+
return { decision, reason: String(reasonText) };
|
|
963
|
+
}
|
|
964
|
+
return { decision };
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
if (out.terminationBehavior === 'terminate') {
|
|
968
|
+
const userMessage = String(
|
|
969
|
+
out.errorMessage?.userMessage ||
|
|
970
|
+
out.userMessage ||
|
|
971
|
+
out.reason ||
|
|
972
|
+
out.systemMessage ||
|
|
973
|
+
'Halted by Highbeam Flightcheck'
|
|
974
|
+
);
|
|
975
|
+
return {
|
|
976
|
+
terminationBehavior: 'terminate',
|
|
977
|
+
errorMessage: { userMessage }
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
const advisory = out.ephemeralMessage || out.systemMessage;
|
|
981
|
+
if (typeof advisory === 'string' && advisory.trim().length > 0) {
|
|
982
|
+
return { ephemeralMessage: advisory };
|
|
983
|
+
}
|
|
984
|
+
return {};
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
// Auto-run when executed directly by Antigravity Hook Harness
|
|
988
|
+
const isMain = process.argv[1] && (process.argv[1].endsWith('pre_invocation.mjs') || process.argv[1].endsWith('pre_invocation.js'));
|
|
989
|
+
const isPreToolUseCli = process.argv.includes('--event=PreToolUse');
|
|
990
|
+
if (isMain) {
|
|
991
|
+
let detectedPreToolUse = isPreToolUseCli;
|
|
992
|
+
readStdinSafe().then(input => {
|
|
993
|
+
const safeInput = input && typeof input === 'object' ? input : {};
|
|
994
|
+
if (isPreToolUseCli && !safeInput.hook_event_name) {
|
|
995
|
+
safeInput.hook_event_name = 'PreToolUse';
|
|
996
|
+
}
|
|
997
|
+
if (
|
|
998
|
+
safeInput.hook_event_name === 'PreToolUse' ||
|
|
999
|
+
safeInput.event === 'PreToolUse' ||
|
|
1000
|
+
safeInput.tool_name ||
|
|
1001
|
+
safeInput.toolName
|
|
1002
|
+
) {
|
|
1003
|
+
detectedPreToolUse = true;
|
|
1004
|
+
}
|
|
1005
|
+
return handlePreInvocation(safeInput);
|
|
1006
|
+
}).then(output => {
|
|
1007
|
+
const safeOut = toProtoSafePreHookOutput(output, { isPreToolUse: detectedPreToolUse });
|
|
1008
|
+
console.log(JSON.stringify(safeOut));
|
|
1009
|
+
process.exit(0);
|
|
1010
|
+
}).catch((err) => {
|
|
1011
|
+
recordHookDiagnostic('pre_invocation', 'main', err);
|
|
1012
|
+
console.log(JSON.stringify(detectedPreToolUse ? { decision: 'allow' } : {}));
|
|
1013
|
+
process.exit(0);
|
|
1014
|
+
});
|
|
1015
|
+
}
|