ctxtop 4.0.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/.antigravity-plugin/plugin.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHECKSUMS.sha256 +59 -42
  4. package/README.md +351 -330
  5. package/bin/ah-statusline.mjs +30 -0
  6. package/bin/ctxtop.mjs +330 -5
  7. package/config/default_flightcheck.json +19 -0
  8. package/config/modelCatalog.json +165 -0
  9. package/hooks/handlers/compact-lifecycle.mjs +323 -8
  10. package/hooks/handlers/config-change.mjs +402 -0
  11. package/hooks/handlers/hookIo.mjs +56 -0
  12. package/hooks/handlers/post-model-switch.mjs +111 -0
  13. package/hooks/handlers/post-tool-use.mjs +117 -16
  14. package/hooks/handlers/pre-model-switch.mjs +823 -24
  15. package/hooks/handlers/pre-tool-use.mjs +271 -4
  16. package/hooks/handlers/stop-gate.mjs +297 -11
  17. package/hooks/handlers/user-prompt-submit.mjs +224 -0
  18. package/hooks/hooks.json +50 -0
  19. package/hooks/post_tool_use.mjs +8 -0
  20. package/hooks/register.js +48 -9
  21. package/hooks/session_start.mjs +11 -1
  22. package/hooks/stop.mjs +11 -1
  23. package/package.json +11 -4
  24. package/packages/antigravity/package.json +1 -1
  25. package/packages/claude-code/package.json +1 -1
  26. package/packages/core/package.json +1 -1
  27. package/packages/engine-node/package.json +1 -1
  28. package/packages/mcp/package.json +1 -1
  29. package/packages/mcp/src/server.mjs +1 -1
  30. package/packages/pro/package.json +1 -1
  31. package/plugin.json +1 -1
  32. package/sidecars/horizon-daemon/server.mjs +38 -2
  33. package/skills/handoff/SKILL.md +8 -0
  34. package/src/adapters/antigravity/index.mjs +31 -1
  35. package/src/adapters/claude-code/index.mjs +40 -1
  36. package/src/cli/horizon_hud.mjs +254 -52
  37. package/src/config/modelCatalog.json +84 -0
  38. package/src/core/bucket_b_runtime.mjs +1200 -0
  39. package/src/core/constants.mjs +191 -4
  40. package/src/core/detectors_det01_to_16.mjs +54 -5
  41. package/src/core/doc_indexer.mjs +338 -0
  42. package/src/core/layer5_hygiene.mjs +118 -0
  43. package/src/core/parser.mjs +2 -1
  44. package/src/core/paths.mjs +3 -2
  45. package/src/core/rsl_clash_auditor.mjs +423 -0
  46. package/src/core/rsl_distiller.mjs +372 -0
  47. package/src/core/rsl_ledger.mjs +969 -0
  48. package/src/core/rsl_triage.mjs +909 -0
  49. package/src/core/session_auditor.mjs +658 -0
  50. package/src/core/shield_manager.mjs +1417 -0
  51. package/src/core/task_quota_router.mjs +1 -1
  52. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +874 -47
  53. package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  54. package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
  55. package/src/core-isomorphic/coach/ttlWatchdog.mjs +13 -6
  56. package/src/core-isomorphic/config/anthropicModelCatalog.json +404 -1
  57. package/src/core-isomorphic/config/catalogLoader.mjs +546 -46
  58. package/src/core-isomorphic/config/horizonConfig.mjs +47 -1
  59. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +266 -0
  60. package/src/core-isomorphic/economics/cacheGravity.mjs +18 -0
  61. package/src/core-isomorphic/economics/cliffBreaker.mjs +98 -12
  62. package/src/core-isomorphic/economics/driftLatency.mjs +114 -0
  63. package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  64. package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  65. package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  66. package/src/core-isomorphic/guards/circuitBreakers.mjs +191 -191
  67. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +154 -5
  68. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +103 -11
  69. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +311 -1
  70. package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
  71. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +16 -0
  72. package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  73. package/src/core-isomorphic/index.js +1 -0
  74. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +36 -12
  75. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +293 -237
  76. package/src/core-isomorphic/ui/modViews.mjs +35 -9
  77. package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
  78. package/src/diagnostics/doctorEngine.mjs +95 -3
  79. package/src/engine-node/db/probe.mjs +234 -2
  80. package/src/engine-node/index.mjs +3 -0
  81. package/src/engine-node/sensors/blindspots.mjs +13 -6
  82. package/src/hooks/antigravity_rsl_hook.mjs +250 -0
  83. package/src/hooks/claude_rsl_hook.mjs +288 -0
  84. package/src/hooks/post_invocation.mjs +196 -4
  85. package/src/hooks/pre_invocation.mjs +732 -22
  86. package/src/hooks/session_start.mjs +39 -1
  87. package/src/utils/modelSwitchTelemetry.mjs +308 -0
  88. package/src/utils/sessionCalibration.mjs +657 -0
  89. package/src/webview/horizon_panel.html +1325 -317
@@ -0,0 +1,288 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file src/hooks/claude_rsl_hook.mjs
4
+ * Claude Code Lifecycle Hook Adapter for Highbeam RSL (`SessionStart`, `PreToolUse`,
5
+ * `PostToolUse`, `Stop`, `SessionEnd`).
6
+ *
7
+ * Works both standalone (via `.claude/settings.json` top-level `"hooks"`) and in-process
8
+ * inside canonical `hooks/handlers/*.mjs` handlers (<30ms, 0 LLM tokens).
9
+ */
10
+
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { atomicWriteFileSync } from '../core/atomic_io.mjs';
15
+ import {
16
+ resolveWorkspaceRoot,
17
+ sanitizeRslSessionId,
18
+ snapshotTestSuiteBaseline,
19
+ recordStepOutcome,
20
+ buildContrastiveDigest
21
+ } from '../core/rsl_triage.mjs';
22
+ import { distillContrastiveDigest } from '../core/rsl_distiller.mjs';
23
+ import {
24
+ getRslLedgerPath,
25
+ ingestDistilledHeuristics,
26
+ evaluatePromotedPreToolGuards,
27
+ RSL_PKG_ROOT
28
+ } from '../core/rsl_ledger.mjs';
29
+
30
+ const __filename = fileURLToPath(import.meta.url);
31
+ const CLAUDE_RSL_CMD_RE = /src[\\/]hooks[\\/]claude_rsl_hook\.mjs/i;
32
+
33
+ function parseCliFlags(argv = []) {
34
+ const out = {};
35
+ for (const arg of argv) {
36
+ if (arg.startsWith('--event=')) out.event = arg.slice('--event='.length).trim();
37
+ else if (arg.startsWith('--mode=')) out.mode = arg.slice('--mode='.length).trim();
38
+ }
39
+ return out;
40
+ }
41
+
42
+ function readStdinJsonQuick(maxTimeoutMs = 150) {
43
+ return new Promise((resolve) => {
44
+ if (process.stdin.isTTY) {
45
+ resolve({});
46
+ return;
47
+ }
48
+ let raw = '';
49
+ let settled = false;
50
+ let settleTimer = null;
51
+
52
+ const done = (val) => {
53
+ if (settled) return;
54
+ settled = true;
55
+ clearTimeout(maxTimer);
56
+ if (settleTimer) clearTimeout(settleTimer);
57
+ try {
58
+ process.stdin.pause();
59
+ } catch {
60
+ // Ignore
61
+ }
62
+ resolve(val);
63
+ };
64
+
65
+ const tryParse = () => {
66
+ try {
67
+ const trimmed = raw.trim();
68
+ return trimmed ? JSON.parse(trimmed) : {};
69
+ } catch {
70
+ return {};
71
+ }
72
+ };
73
+
74
+ const maxTimer = setTimeout(() => done(tryParse()), maxTimeoutMs);
75
+ process.stdin.setEncoding('utf8');
76
+ process.stdin.on('data', (chunk) => {
77
+ raw += chunk;
78
+ if (settleTimer) clearTimeout(settleTimer);
79
+ if (raw.trim().endsWith('}')) {
80
+ settleTimer = setTimeout(() => {
81
+ try {
82
+ done(JSON.parse(raw));
83
+ } catch {
84
+ // Wait for end or timeout
85
+ }
86
+ }, 2);
87
+ }
88
+ });
89
+ process.stdin.on('end', () => done(tryParse()));
90
+ process.stdin.on('error', () => done({}));
91
+ });
92
+ }
93
+
94
+ function resolveClaudeEvent(payload = {}, options = {}) {
95
+ const explicit = options.event || payload.hook_event_name || payload.hookEventName;
96
+ if (explicit) return String(explicit).trim();
97
+ if ('stop_hook_active' in payload || 'stopHookActive' in payload) return 'Stop';
98
+ if (payload.tool_name || payload.toolName) {
99
+ return 'tool_response' in payload || 'toolResponse' in payload ? 'PostToolUse' : 'PreToolUse';
100
+ }
101
+ return 'SessionStart';
102
+ }
103
+
104
+ /**
105
+ * Programmatic handler for Claude Code RSL hook events.
106
+ * @param {object} [payload={}]
107
+ * @param {object} [options={}]
108
+ */
109
+ export function handleClaudeRslHook(payload = {}, options = {}) {
110
+ const event = resolveClaudeEvent(payload, options);
111
+ const stopHookActive = Boolean(payload.stop_hook_active ?? payload.stopHookActive);
112
+
113
+ if ((event === 'Stop' || event === 'SessionEnd') && stopHookActive) {
114
+ return {
115
+ exitCode: 0,
116
+ stdoutJson: {},
117
+ event,
118
+ skippedReason: 'stop_hook_active'
119
+ };
120
+ }
121
+
122
+ const workspaceRoot = resolveWorkspaceRoot(payload, options);
123
+ const sessionId = sanitizeRslSessionId(
124
+ payload.session_id || payload.sessionId || payload.conversationId || options.sessionId || 'default'
125
+ );
126
+
127
+ if (event === 'SessionStart') {
128
+ const snapshot = snapshotTestSuiteBaseline(workspaceRoot, sessionId, options);
129
+ return {
130
+ exitCode: 0,
131
+ stdoutJson: {},
132
+ event,
133
+ snapshot
134
+ };
135
+ }
136
+
137
+ if (event === 'PreToolUse') {
138
+ const verdict = evaluatePromotedPreToolGuards(workspaceRoot, 'claude', payload);
139
+ if (verdict.decision === 'deny') {
140
+ return {
141
+ exitCode: 0,
142
+ stdoutJson: {
143
+ permissionDecision: 'deny',
144
+ hookSpecificOutput: {
145
+ hookEventName: 'PreToolUse',
146
+ permissionDecision: 'deny',
147
+ permissionDecisionReason: verdict.reason
148
+ }
149
+ },
150
+ event,
151
+ verdict
152
+ };
153
+ }
154
+ return {
155
+ exitCode: 0,
156
+ stdoutJson: {},
157
+ event,
158
+ verdict
159
+ };
160
+ }
161
+
162
+ if (event === 'PostToolUse') {
163
+ const recorded = recordStepOutcome(payload, { ...options, platform: 'claude' });
164
+ return {
165
+ exitCode: 0,
166
+ stdoutJson: {},
167
+ event,
168
+ recorded
169
+ };
170
+ }
171
+
172
+ if (event === 'Stop' || event === 'SessionEnd') {
173
+ const digest = buildContrastiveDigest(payload, { ...options, platform: 'claude' });
174
+ const hasLedger = fs.existsSync(getRslLedgerPath(workspaceRoot));
175
+ let distillation = null;
176
+ let ledgerResult = null;
177
+
178
+ if (digest.tainted) {
179
+ ledgerResult = ingestDistilledHeuristics(workspaceRoot, {}, digest, options);
180
+ } else if (digest.triggered || hasLedger) {
181
+ distillation = digest.triggered
182
+ ? distillContrastiveDigest(digest, { mode: options.mode || 'local' })
183
+ : { is_valid_learning: false, mode: 'local', heuristics: [] };
184
+ ledgerResult = ingestDistilledHeuristics(workspaceRoot, distillation, digest, options);
185
+ }
186
+
187
+ return {
188
+ exitCode: 0,
189
+ stdoutJson: {},
190
+ event,
191
+ digest,
192
+ distillation,
193
+ ledgerResult
194
+ };
195
+ }
196
+
197
+ return {
198
+ exitCode: 0,
199
+ stdoutJson: {},
200
+ event
201
+ };
202
+ }
203
+
204
+ /**
205
+ * Registers or removes standalone RSL lifecycle hooks in `<workspaceRoot>/.claude/settings.json`
206
+ * under top-level `"hooks"`, never setting `"disableAllHooks": true`.
207
+ *
208
+ * @param {string} workspaceRoot
209
+ * @param {object} [options={}]
210
+ */
211
+ export function syncClaudeWorkspaceRslHooks(workspaceRoot, options = {}) {
212
+ const baseRoot = path.resolve(workspaceRoot || process.cwd());
213
+ const settingsPath = path.join(baseRoot, '.claude', 'settings.json');
214
+ const pkgRoot = String(options.pkgRoot || RSL_PKG_ROOT).replace(/\\/g, '/').replace(/\/+$/, '');
215
+ const hookScript = `${pkgRoot}/src/hooks/claude_rsl_hook.mjs`;
216
+
217
+ let doc = {};
218
+ if (fs.existsSync(settingsPath)) {
219
+ try {
220
+ const parsed = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
221
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) doc = { ...parsed };
222
+ } catch {
223
+ doc = {};
224
+ }
225
+ }
226
+
227
+ const prevHooks = doc.hooks && typeof doc.hooks === 'object' && !Array.isArray(doc.hooks)
228
+ ? { ...doc.hooks }
229
+ : {};
230
+
231
+ const stripExisting = (entries) => {
232
+ if (!Array.isArray(entries)) return [];
233
+ return entries.filter((entry) => {
234
+ const cmds = [
235
+ entry?.command,
236
+ ...(Array.isArray(entry?.hooks) ? entry.hooks.map((h) => h?.command) : [])
237
+ ].map((c) => String(c || ''));
238
+ return !cmds.some((c) => CLAUDE_RSL_CMD_RE.test(c) && !c.includes('--event=PreToolUse'));
239
+ });
240
+ };
241
+
242
+ if (options.remove) {
243
+ for (const ev of ['SessionStart', 'PostToolUse', 'Stop', 'SessionEnd']) {
244
+ if (Array.isArray(prevHooks[ev])) {
245
+ const remaining = stripExisting(prevHooks[ev]);
246
+ if (remaining.length > 0) prevHooks[ev] = remaining;
247
+ else delete prevHooks[ev];
248
+ }
249
+ }
250
+ } else {
251
+ const mergeEvent = (evName, matcher, flagEvent) => {
252
+ const cleaned = stripExisting(prevHooks[evName]);
253
+ cleaned.push({
254
+ ...(matcher ? { matcher } : {}),
255
+ hooks: [{ type: 'command', command: `node "${hookScript}" --event=${flagEvent}` }]
256
+ });
257
+ prevHooks[evName] = cleaned;
258
+ };
259
+ mergeEvent('SessionStart', 'startup|resume|clear|compact|fork', 'SessionStart');
260
+ mergeEvent('PostToolUse', 'Bash|PowerShell|Edit|MultiEdit|Write|Read|Grep|Glob', 'PostToolUse');
261
+ mergeEvent('Stop', null, 'Stop');
262
+ mergeEvent('SessionEnd', null, 'SessionEnd');
263
+ }
264
+
265
+ doc.hooks = prevHooks;
266
+ if (doc.disableAllHooks === true) {
267
+ delete doc.disableAllHooks;
268
+ }
269
+
270
+ fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
271
+ atomicWriteFileSync(settingsPath, `${JSON.stringify(doc, null, 2)}\n`);
272
+ return { settingsPath };
273
+ }
274
+
275
+ const isMain = process.argv[1] && path.resolve(process.argv[1]) === __filename;
276
+ if (isMain) {
277
+ const flags = parseCliFlags(process.argv.slice(2));
278
+ readStdinJsonQuick()
279
+ .then((payload) => {
280
+ const res = handleClaudeRslHook(payload, flags);
281
+ process.stdout.write(`${JSON.stringify(res.stdoutJson ?? {})}\n`);
282
+ process.exit(0);
283
+ })
284
+ .catch(() => {
285
+ process.stdout.write('{}\n');
286
+ process.exit(0);
287
+ });
288
+ }
@@ -15,6 +15,7 @@ import { SwarmIdleTtlTracker, computeSwarmRosterTtlBadges } from '../core/subage
15
15
  import { loadHorizonConfig } from '../core/horizon_config.mjs';
16
16
  import { recordHookDiagnostic } from '../core/hook_diagnostics.mjs';
17
17
  import { evaluateBetweenTurnEffortAdvisor } from '../core/coach/effort_advisor.mjs';
18
+ import { runBucketBPostToolPass, runBucketBStopPass } from '../core/bucket_b_runtime.mjs';
18
19
 
19
20
  export async function readStdinSafe({ maxTimeoutMs = 1000, settleMs = 50 } = {}) {
20
21
  if (process.stdin.isTTY || process.stdin.readableEnded) return {};
@@ -221,16 +222,95 @@ export async function handlePostToolUse(inputData = {}) {
221
222
  });
222
223
  const flightMode = String(inputData.flightMode || horizonConfig.flightMode || 'COACH').toUpperCase();
223
224
 
225
+ const toolName = String(inputData.tool_name || inputData.toolName || '');
226
+ const toolInput = inputData.tool_input || inputData.toolInput || inputData.args || {};
227
+ const cmdStr = String(toolInput.CommandLine || toolInput.command || toolInput.cmd || inputData.command || '');
228
+ const rawOutput =
229
+ typeof (inputData.tool_output ?? inputData.toolOutput ?? inputData.output ?? inputData.tool_response) === 'string'
230
+ ? (inputData.tool_output ?? inputData.toolOutput ?? inputData.output ?? inputData.tool_response)
231
+ : String(
232
+ inputData.tool_output ??
233
+ inputData.toolOutput ??
234
+ inputData.output ??
235
+ inputData.tool_response?.output ??
236
+ inputData.tool_response?.content ??
237
+ ''
238
+ );
239
+ const didFail =
240
+ inputData.is_error === true ||
241
+ inputData.isError === true ||
242
+ inputData.succeeded === false ||
243
+ inputData.status === 'ERROR' ||
244
+ (typeof inputData.exitCode === 'number' && inputData.exitCode !== 0) ||
245
+ (typeof inputData.exit_code === 'number' && inputData.exit_code !== 0);
246
+
247
+ if (/^(?:run_command|execute_bash|Bash|PowerShell)$/i.test(toolName)) {
248
+ const isVerificationCmd =
249
+ /\b(?:node\s+--test|npm\s+(?:run\s+)?test|pnpm\s+(?:run\s+)?test|yarn\s+test|bun\s+test|vitest|jest|pytest|cargo\s+test|go\s+test|tsc(?:\s|$)|npx\s+tsc)\b/i.test(
250
+ cmdStr
251
+ );
252
+ if (!didFail && isVerificationCmd) {
253
+ if (sidecar.fileState) {
254
+ sidecar.fileState.unverifiedEdits = [];
255
+ }
256
+ if (sidecar.sessionMeta) {
257
+ sidecar.sessionMeta.lastFailingLocation = null;
258
+ }
259
+ } else if (didFail && rawOutput) {
260
+ const locMatch = rawOutput.match(
261
+ /([A-Za-z0-9_./\\-]+\.(?:[cm]?[jt]sx?|py|rs|go|rb|java|kt|swift|c|cpp|h|hpp)):(\d+)(?::\d+)?/
262
+ );
263
+ if (locMatch) {
264
+ sidecar.sessionMeta.lastFailingLocation = `${locMatch[1].replace(/\\/g, '/')}:${locMatch[2]}`;
265
+ }
266
+ }
267
+ }
268
+
269
+ let postPass = null;
270
+ if (flightMode !== 'OFF' && inputData.bucketBShadow !== false && toolName && rawOutput) {
271
+ try {
272
+ postPass = runBucketBPostToolPass({
273
+ platform: 'antigravity',
274
+ sessionId: conversationId,
275
+ cwd: workspacePath,
276
+ hasExplicitCwd: Boolean(inputData.cwd || inputData.workspacePath),
277
+ toolName,
278
+ toolInput: toolInput && typeof toolInput === 'object' ? toolInput : {},
279
+ rawOutput,
280
+ lastUserPrompt: String(inputData.lastUserPrompt || ''),
281
+ activeFiles: sidecar.fileState?.activeSetPaths || [],
282
+ webFetchesInTurn: Number(inputData.webFetchesInTurn || 1),
283
+ options: {
284
+ bucketBStage: inputData.bucketBStage,
285
+ bucketBAlphaStage: inputData.bucketBAlphaStage,
286
+ mode: flightMode,
287
+ horizonConfig
288
+ }
289
+ });
290
+ } catch (_postErr) {
291
+ postPass = null;
292
+ }
293
+ }
294
+
224
295
  writeSidecarAtomicSync(conversationId, sidecar);
225
296
  if (flightMode === 'OFF') {
226
297
  return { flightMode };
227
298
  }
228
- return {
299
+ const postToolOut = {
229
300
  flightMode,
230
301
  active_model_id: sidecar.sessionMeta.active_model_id || sidecar.sessionMeta.activeModel || null,
231
302
  pending_model_id: sidecar.sessionMeta.pending_model_id || null,
232
303
  swarmTtlBadges: sidecar.swarmTtlBadges
233
304
  };
305
+ if (postPass?.triggered) {
306
+ postToolOut.updatedOutput = postPass.updatedOutput;
307
+ postToolOut.savedTokens = postPass.savedTokens;
308
+ postToolOut.guardrailId = postPass.guardrailId;
309
+ if (flightMode !== 'SILENT') {
310
+ postToolOut.systemMessage = postPass.reason;
311
+ }
312
+ }
313
+ return postToolOut;
234
314
  }
235
315
 
236
316
  export async function handlePostInvocation(inputData = {}) {
@@ -310,14 +390,23 @@ export async function handlePostInvocation(inputData = {}) {
310
390
  sidecar.sessionMeta.consecutiveErrorStreak = 0;
311
391
  }
312
392
 
313
- // Track test runs
314
- const isTestRun = toolsInvoked.includes('run_command') && /(test|pytest|jest|vitest|cargo test)/i.test(inputData.command || '');
393
+ // Track test runs (including TypeScript typecheck `tsc`)
394
+ const isTestRun = toolsInvoked.includes('run_command') && /\b(?:test|pytest|jest|vitest|cargo\s+test|go\s+test|tsc)\b/i.test(inputData.command || '');
315
395
  if (isTestRun && inputData.exitCode === 0) {
316
396
  sidecar.sessionMeta.turnsSinceLastPassingTest = 0;
397
+ if (sidecar.fileState) {
398
+ sidecar.fileState.unverifiedEdits = [];
399
+ }
317
400
  } else {
318
401
  sidecar.sessionMeta.turnsSinceLastPassingTest = (sidecar.sessionMeta.turnsSinceLastPassingTest || 0) + 1;
319
402
  }
320
403
 
404
+ if (Array.isArray(inputData.activeBackgroundTasks)) {
405
+ sidecar.sessionMeta.activeBackgroundTasks = inputData.activeBackgroundTasks
406
+ .filter(Boolean)
407
+ .map((t) => (typeof t === 'string' ? t : String(t?.id || t?.command || 'bg_task')));
408
+ }
409
+
321
410
  // Incremental transcript sync so sidecar.telemetry.totalInputTokens updates in standalone CLI/hook mode
322
411
  try {
323
412
  const resolvedSessionDir = resolveExactSessionDir(conversationId, inputData);
@@ -393,14 +482,117 @@ export async function handlePostInvocation(inputData = {}) {
393
482
  recordHookDiagnostic('post_invocation', 'effortAdvisor', err, { persist: false });
394
483
  }
395
484
 
485
+ const bgTasks = Array.isArray(sidecar.sessionMeta?.activeBackgroundTasks)
486
+ ? sidecar.sessionMeta.activeBackgroundTasks
487
+ : [];
488
+ const orphanBackgroundWarning =
489
+ bgTasks.length > 0 && (inputData.sessionEnding === true || inputData.stop === true)
490
+ ? `[Highbeam Quota Shield — Orphan Background Drain (#10)] ${bgTasks.length} background daemon/task(s) still active (${bgTasks.slice(0, 3).join(', ')}). Kill via manage_task before ending session.`
491
+ : null;
492
+
493
+ const postToolName = String(inputData.tool_name || inputData.toolName || '');
494
+ const postRawOutput = inputData.tool_output ?? inputData.toolOutput ?? inputData.output;
495
+ let invPostPass = null;
496
+ let invPostFlightMode = 'COACH';
497
+ if (postToolName && postRawOutput && inputData.bucketBShadow !== false) {
498
+ try {
499
+ const postWorkspace = inputData.cwd || inputData.workspacePath || sidecar.workspacePath || process.cwd();
500
+ const postHorizonConfig = inputData.horizonConfig || loadHorizonConfig({
501
+ cwd: postWorkspace,
502
+ ...(inputData.homeDir ? { homeDir: inputData.homeDir } : {})
503
+ });
504
+ invPostFlightMode = String(inputData.flightMode || postHorizonConfig.flightMode || 'COACH').toUpperCase();
505
+ if (invPostFlightMode !== 'OFF') {
506
+ invPostPass = runBucketBPostToolPass({
507
+ platform: 'antigravity',
508
+ sessionId: conversationId,
509
+ cwd: postWorkspace,
510
+ hasExplicitCwd: Boolean(inputData.cwd || inputData.workspacePath),
511
+ toolName: postToolName,
512
+ toolInput: inputData.tool_input || inputData.toolInput || {},
513
+ rawOutput: String(postRawOutput),
514
+ lastUserPrompt: String(inputData.lastUserPrompt || ''),
515
+ activeFiles: sidecar.fileState?.activeSetPaths || [],
516
+ webFetchesInTurn: Number(inputData.webFetchesInTurn || 1),
517
+ options: {
518
+ bucketBStage: inputData.bucketBStage,
519
+ bucketBAlphaStage: inputData.bucketBAlphaStage,
520
+ mode: invPostFlightMode,
521
+ horizonConfig: postHorizonConfig
522
+ }
523
+ });
524
+ }
525
+ } catch (_invPostErr) {
526
+ invPostPass = null;
527
+ }
528
+ }
529
+
530
+ const turnFileDiffs = Array.isArray(inputData.fileDiffs)
531
+ ? inputData.fileDiffs
532
+ : Array.isArray(sidecar.fileState?.turnFileDiffs)
533
+ ? sidecar.fileState.turnFileDiffs
534
+ : [];
535
+ let turnStopPass = null;
536
+ let turnFlightMode = invPostFlightMode;
537
+ if (turnFileDiffs.length > 0 && inputData.bucketBShadow !== false) {
538
+ try {
539
+ const turnWorkspace = inputData.cwd || inputData.workspacePath || sidecar.workspacePath || process.cwd();
540
+ const turnHorizonConfig = inputData.horizonConfig || loadHorizonConfig({
541
+ cwd: turnWorkspace,
542
+ ...(inputData.homeDir ? { homeDir: inputData.homeDir } : {})
543
+ });
544
+ turnFlightMode = String(inputData.flightMode || turnHorizonConfig.flightMode || 'COACH').toUpperCase();
545
+ if (turnFlightMode !== 'OFF') {
546
+ turnStopPass = runBucketBStopPass({
547
+ platform: 'antigravity',
548
+ sessionId: conversationId,
549
+ cwd: turnWorkspace,
550
+ hasExplicitCwd: Boolean(inputData.cwd || inputData.workspacePath),
551
+ fileDiffs: turnFileDiffs,
552
+ lastUserPrompt: String(inputData.lastUserPrompt ?? inputData.prompt ?? sidecar.sessionMeta?.lastUserPrompt ?? ''),
553
+ options: {
554
+ bucketBStage: inputData.bucketBStage,
555
+ bucketBBetaStage: inputData.bucketBBetaStage,
556
+ mode: turnFlightMode,
557
+ horizonConfig: turnHorizonConfig
558
+ }
559
+ });
560
+ }
561
+ } catch (_turnStopErr) {
562
+ turnStopPass = null;
563
+ }
564
+ }
565
+ if (sidecar.fileState) {
566
+ sidecar.fileState.turnFileDiffs = [];
567
+ }
568
+
396
569
  writeSidecarAtomicSync(conversationId, sidecar);
397
- return {
570
+ const out = {
398
571
  active_model_id: sidecar.sessionMeta.active_model_id || sidecar.sessionMeta.activeModel || null,
399
572
  pending_model_id: sidecar.sessionMeta.pending_model_id || null,
400
573
  swarmRoster: sidecar.swarmRoster,
401
574
  swarmTtlBadges: sidecar.swarmTtlBadges,
402
575
  effortAdvisor: sidecar.effortAdvisor || null
403
576
  };
577
+ if (invPostPass?.triggered) {
578
+ out.updatedOutput = invPostPass.updatedOutput;
579
+ out.savedTokens = invPostPass.savedTokens;
580
+ out.guardrailId = invPostPass.guardrailId;
581
+ }
582
+ if (turnStopPass?.triggered) {
583
+ out.overengineeringHint = turnStopPass.reason;
584
+ out.savedTokens = (out.savedTokens || 0) + (turnStopPass.savedTokens || 0);
585
+ out.guardrailId = out.guardrailId || turnStopPass.guardrailId;
586
+ }
587
+ if (orphanBackgroundWarning) {
588
+ out.orphanBackgroundWarning = orphanBackgroundWarning;
589
+ out.systemMessage = orphanBackgroundWarning;
590
+ } else if (invPostPass?.triggered && invPostFlightMode !== 'SILENT' && !out.systemMessage) {
591
+ out.systemMessage = invPostPass.reason;
592
+ } else if (turnStopPass?.triggered && turnFlightMode !== 'SILENT' && !out.systemMessage) {
593
+ out.systemMessage = turnStopPass.reason;
594
+ }
595
+ return out;
404
596
  }
405
597
 
406
598
  // Auto-run if executed directly