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
@@ -7,6 +7,7 @@ import { scorePromptSufficiency, toWorkspaceRelativePath } from '../core/prompt_
7
7
  import { loadFlightcheckConfig } from '../core/config.mjs';
8
8
  import {
9
9
  resolveModelCeiling,
10
+ resolveModelRates,
10
11
  normalizeModelKey,
11
12
  isModelDeprecated,
12
13
  getDeprecatedModelMigrationNotice,
@@ -37,9 +38,55 @@ import { recordHookDiagnostic } from '../core/hook_diagnostics.mjs';
37
38
  import {
38
39
  evaluateScopeBrake,
39
40
  evaluateRelayBreaker,
40
- evaluateTwoStageSightseeingIntercept
41
+ evaluateTwoStageSightseeingIntercept,
42
+ evaluateShardedSpecDrift,
43
+ evaluateTurn1ContractGate
41
44
  } from '../core/shared/prompt_hygiene_governor.mjs';
42
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
+ ]);
43
90
 
44
91
  export {
45
92
  classifyTaskComplexity,
@@ -191,13 +238,23 @@ export async function handlePreToolUse(inputData = {}) {
191
238
  });
192
239
 
193
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);
194
251
  if (/^(run_command|execute_bash|bash|powershell|exec)$/i.test(toolName)) {
195
252
  if (resolveDetectorOverride(horizonConfig, 'DET-19') !== 'off') {
196
253
  const det19 = evaluateDet19GitHookBypass(syntheticStep);
197
254
  if (det19) return makeBlockPayload(det19);
198
255
  }
199
256
  if (resolveDetectorOverride(horizonConfig, 'DET-08') !== 'off') {
200
- const det08 = evaluateDet08DestructiveShell(syntheticStep);
257
+ const det08 = evaluateDet08DestructiveShell(syntheticStep, { userExplicitTestIntent });
201
258
  if (det08) return makeBlockPayload(det08);
202
259
  }
203
260
  }
@@ -243,8 +300,234 @@ export async function handlePreToolUse(inputData = {}) {
243
300
  }
244
301
  if (!isSilentMode) gateSystemMessage = twoStage.reason;
245
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
+ }
246
465
  }
247
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
+
248
531
  const det09Mode = resolveDetectorOverride(horizonConfig, 'DET-09');
249
532
  if (det09Mode !== 'off') {
250
533
  const det09 = evaluateDet09MidSessionRuleMutate(syntheticStep, {
@@ -284,6 +567,114 @@ export async function handlePreToolUse(inputData = {}) {
284
567
  }
285
568
  }
286
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
+
287
678
  const nowMs = inputData.nowMs ?? inputData.eventTimestampUtc ?? Date.now();
288
679
  const eventTimestampUtc = inputData.eventTimestampUtc ?? nowMs;
289
680
  const serviceTier = inputData.serviceTier || 'standard';
@@ -415,16 +806,52 @@ export async function handlePreToolUse(inputData = {}) {
415
806
  systemMessage = coldCacheWakeup.message;
416
807
  }
417
808
  }
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
- });
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
+ }
428
855
  } else if (toolName === 'manage_subagents') {
429
856
  const action = String(toolInput?.Action || toolInput?.action || '').toLowerCase();
430
857
  if (action === 'kill' && Array.isArray(toolInput?.ConversationIds)) {
@@ -510,6 +937,50 @@ export async function handlePreInvocation(inputData = {}) {
510
937
  return { terminationBehavior: 'terminate', decision: 'block', detectorId: 'DET-18', userMessage: det18.message };
511
938
  }
512
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
+ }
513
984
  return {};
514
985
  }
515
986
 
@@ -614,7 +1085,93 @@ export async function handlePreInvocation(inputData = {}) {
614
1085
  }
615
1086
 
616
1087
  // 3. HALT_HYGIENE_OR_SAFETY
1088
+ sessionMeta.lastUserPrompt = rawPrompt;
617
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
+ }
618
1175
  if (telemetry.amputationRisk && isTelemetryReliable) {
619
1176
  const handoff = sidecar.handoff || {};
620
1177
  const handoffAction = handoff.result === 'NEEDS_FIXES'
@@ -774,19 +1331,51 @@ export async function handlePreInvocation(inputData = {}) {
774
1331
  }) || '';
775
1332
  const hasActiveSetMatch = Boolean(matchedScope);
776
1333
 
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
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.
779
1337
  const timestampMs = Number(inputData.timestampMs ?? inputData.nowMs ?? inputData.timestamp ?? Date.now());
780
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;
781
1343
  sessionMeta.recentPrompts = Array.isArray(sessionMeta.recentPrompts) ? sessionMeta.recentPrompts : [];
782
1344
  sessionMeta.recentPrompts = sessionMeta.recentPrompts.filter(e => (timestampMs - e.ts) <= 90000);
783
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
+
784
1371
  sidecar.sessionMeta = sessionMeta;
785
- try {
786
- writeSidecarAtomicSync(conversationId, sidecar);
787
- } catch (err) {
788
- recordHookDiagnostic('pre_invocation', 'recentPrompts.writeSidecar', err);
789
- }
1372
+ const flushSidecarOnce = () => {
1373
+ try {
1374
+ writeSidecarAtomicSync(conversationId, sidecar);
1375
+ } catch (err) {
1376
+ recordHookDiagnostic('pre_invocation', 'recentPrompts.writeSidecar', err);
1377
+ }
1378
+ };
790
1379
 
791
1380
  const rapidSameScopeCount = sessionMeta.recentPrompts.filter(
792
1381
  e => e.targetScope && e.targetScope === matchedScope && e.wordCount <= 18
@@ -800,12 +1389,30 @@ export async function handlePreInvocation(inputData = {}) {
800
1389
  extraWarn: { continue: true },
801
1390
  extraBlock: { continue: false }
802
1391
  });
803
- if (dripRes) return dripRes;
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
+ };
804
1407
  }
805
1408
 
806
1409
  if (!hasCheckTag) {
807
- if (hasActiveSetMatch) return {};
1410
+ if (hasActiveSetMatch) {
1411
+ flushSidecarOnce();
1412
+ return {};
1413
+ }
808
1414
  if (config.hook_level === 'guard' && turnCount > (config.trust_decay_turn_threshold || 10)) {
1415
+ flushSidecarOnce();
809
1416
  return {};
810
1417
  }
811
1418
  }
@@ -937,9 +1544,112 @@ export async function handlePreInvocation(inputData = {}) {
937
1544
  rewriteSuggestion
938
1545
  );
939
1546
  const vagueRes = applyHabitOverride('vague-prompt-rubric', 'REWRITE_SCORECARD', card);
940
- if (vagueRes) return vagueRes;
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
+ }
941
1650
  }
942
1651
 
1652
+ flushSidecarOnce();
943
1653
  return {};
944
1654
  }
945
1655