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
@@ -41,7 +41,8 @@ import {
41
41
 
42
42
  export { isPrefixInstructionFile, evaluateDet09PrefixMutationFence };
43
43
  import { TtlWatchdog } from '../coach/ttlWatchdog.mjs';
44
- import { evaluateScopeAndQuotaBrake } from '../telemetry/scopeLockRegistry.mjs';
44
+ import { evaluateScopeAndQuotaBrake, readActiveScopeLocks } from '../telemetry/scopeLockRegistry.mjs';
45
+ import { evaluateActiveDet30StepDown } from '../economics/driftLatency.mjs';
45
46
  import { loadMicroSkillsRegistry, evaluateMicroSkillIntercept } from '../coach/microSkills.mjs';
46
47
  import {
47
48
  RELAY_STATES,
@@ -79,7 +80,13 @@ import {
79
80
  evaluateSilentPrefixMutations,
80
81
  evaluateDet18UntrustedSettingsGuard,
81
82
  evaluateDet19SubagentIpiSanitizer,
82
- evaluateDet20ScopeLockAndQuotaBrake
83
+ evaluateDet20ScopeLockAndQuotaBrake,
84
+ sanitizeBreakerSessionId,
85
+ getBreakerStateFilePath,
86
+ readBreakerStateSnapshot,
87
+ writeBreakerStateSnapshot,
88
+ serializeCircuitBreakerState,
89
+ hydrateCircuitBreakerState
83
90
  } from './det13_20_mcp_scope.mjs';
84
91
 
85
92
  export {
@@ -104,58 +111,13 @@ export {
104
111
  evaluateSilentPrefixMutations,
105
112
  evaluateDet18UntrustedSettingsGuard,
106
113
  evaluateDet19SubagentIpiSanitizer,
107
- evaluateDet20ScopeLockAndQuotaBrake
114
+ evaluateDet20ScopeLockAndQuotaBrake,
115
+ sanitizeBreakerSessionId,
116
+ getBreakerStateFilePath,
117
+ readBreakerStateSnapshot,
118
+ writeBreakerStateSnapshot
108
119
  };
109
120
 
110
- /**
111
- * Sanitizes a session ID for `.claude/cache/ah_breaker_state_<sessionId>.json`.
112
- * @param {string} [sessionId='default']
113
- * @returns {string}
114
- */
115
- export function sanitizeBreakerSessionId(sessionId = 'default') {
116
- return String(sessionId || 'default').replace(/[^a-zA-Z0-9._-]/g, '_');
117
- }
118
-
119
- /**
120
- * Resolves the atomic CLI circuit-breaker state file path (`.claude/cache/ah_breaker_state_<sessionId>.json`).
121
- * @param {string} [sessionId='default']
122
- * @param {object} [options={}]
123
- * @returns {string}
124
- */
125
- export function getBreakerStateFilePath(sessionId = 'default', options = {}) {
126
- if (options?.breakerStatePath) {
127
- return options.breakerStatePath;
128
- }
129
- const cwd = getCwd(options);
130
- return path.join(
131
- cwd,
132
- '.claude',
133
- 'cache',
134
- `ah_breaker_state_${sanitizeBreakerSessionId(sessionId)}.json`
135
- );
136
- }
137
-
138
- /**
139
- * Safely reads a persisted `CircuitBreakerEngine` snapshot from disk (`ISS-038`).
140
- * @param {string} [sessionId='default']
141
- * @param {object} [options={}]
142
- * @returns {object | null}
143
- */
144
- export function readBreakerStateSnapshot(sessionId = 'default', options = {}) {
145
- return readJsonSafe(getBreakerStateFilePath(sessionId, options), null, options);
146
- }
147
-
148
- /**
149
- * Atomically writes a `CircuitBreakerEngine` snapshot to disk (`ISS-038`).
150
- * @param {string} [sessionId='default']
151
- * @param {object} [snapshot={}]
152
- * @param {object} [options={}]
153
- * @returns {boolean}
154
- */
155
- export function writeBreakerStateSnapshot(sessionId = 'default', snapshot = {}, options = {}) {
156
- return writeJsonAtomic(getBreakerStateFilePath(sessionId, options), snapshot, options);
157
- }
158
-
159
121
  /**
160
122
  * Unified Stateful Circuit Breaker Engine (`DET-01`..`DET-20`).
161
123
  */
@@ -174,11 +136,61 @@ export class CircuitBreakerEngine {
174
136
  this.sequentialSearchCount = Number(options.sequentialSearchCount || 0);
175
137
  this.fileHashHistory = new Map();
176
138
  this.modifiedFilesInTurn = new Set();
139
+ this.unverifiedEdits = Array.isArray(options.unverifiedEdits)
140
+ ? options.unverifiedEdits.filter((e) => e && typeof e.filePath === 'string').map((e) => ({ ...e }))
141
+ : [];
142
+ this.turnFileDiffs = Array.isArray(options.turnFileDiffs)
143
+ ? options.turnFileDiffs.filter((e) => e && typeof e.filePath === 'string').map((e) => ({ ...e }))
144
+ : [];
177
145
  this.pendingBatchEdits = new Set();
178
146
  this.pendingFormatFiles = new Set();
179
147
  this.codeEditedSinceLastTest = Boolean(options.codeEditedSinceLastTest || false);
180
148
  this.lastTurnGitCommitted = Boolean(options.lastTurnGitCommitted || false);
181
149
  this.committedTopDirs = Array.isArray(options.committedTopDirs) ? [...options.committedTopDirs] : [];
150
+ this.pendingVerificationCommand = Boolean(options.pendingVerificationCommand || false);
151
+ this.lastFailingLocation = options.lastFailingLocation ? String(options.lastFailingLocation) : null;
152
+ this.pending_downshift =
153
+ options.pending_downshift && typeof options.pending_downshift === 'object'
154
+ ? { ...options.pending_downshift }
155
+ : null;
156
+ this.pendingDownshiftModel = options.pendingDownshiftModel
157
+ ? String(options.pendingDownshiftModel)
158
+ : this.pending_downshift?.toModel
159
+ ? String(this.pending_downshift.toModel)
160
+ : null;
161
+ this.justCompacted = Boolean(options.justCompacted || false);
162
+ this.turnsSinceLastCompact =
163
+ options.turnsSinceLastCompact !== undefined &&
164
+ options.turnsSinceLastCompact !== null &&
165
+ Number.isFinite(Number(options.turnsSinceLastCompact))
166
+ ? Math.max(0, Number(options.turnsSinceLastCompact))
167
+ : null;
168
+ this.taskBoundaryState =
169
+ options.taskBoundaryState && typeof options.taskBoundaryState === 'object'
170
+ ? {
171
+ openFailure: Boolean(options.taskBoundaryState.openFailure),
172
+ editsSinceBoundary: Math.max(0, Number(options.taskBoundaryState.editsSinceBoundary || 0)),
173
+ lastBoundarySuggestedTurn: options.taskBoundaryState.lastBoundarySuggestedTurn ?? null
174
+ }
175
+ : { openFailure: false, editsSinceBoundary: 0, lastBoundarySuggestedTurn: null };
176
+ this.lastToolsetHash =
177
+ options.lastToolsetHash && typeof options.lastToolsetHash === 'object'
178
+ ? { ...options.lastToolsetHash }
179
+ : null;
180
+ this.lastContextTokens =
181
+ options.lastContextTokens !== undefined &&
182
+ options.lastContextTokens !== null &&
183
+ Number.isFinite(Number(options.lastContextTokens))
184
+ ? Math.max(0, Number(options.lastContextTokens))
185
+ : null;
186
+ this.lastModelId = options.lastModelId ? String(options.lastModelId) : null;
187
+ this.activeBackgroundTasks = Array.isArray(options.activeBackgroundTasks)
188
+ ? [...options.activeBackgroundTasks]
189
+ : [];
190
+ this.activeWriteWorkers = Array.isArray(options.activeWriteWorkers)
191
+ ? [...options.activeWriteWorkers]
192
+ : [];
193
+ this.lastUserPrompt = options.lastUserPrompt ? String(options.lastUserPrompt) : '';
182
194
  this.consecutiveTrivialMaxEffortTurns = Number(options.consecutiveTrivialMaxEffortTurns || 0);
183
195
  this.recentEditTimestampsByFile = options.recentEditTimestampsByFile && typeof options.recentEditTimestampsByFile === 'object' ? { ...options.recentEditTimestampsByFile } : {};
184
196
  this.totalDiscoveryCalls = Number(options.totalDiscoveryCalls || 0);
@@ -241,42 +253,7 @@ export class CircuitBreakerEngine {
241
253
  * @returns {object}
242
254
  */
243
255
  exportStateSnapshot() {
244
- const hashObj = {};
245
- for (const [k, v] of this.fileHashHistory.entries()) {
246
- hashObj[k] = Array.isArray(v) ? [...v] : [];
247
- }
248
- return {
249
- schemaVersion: '1.0.0',
250
- updatedAt: Date.now(),
251
- mode: this.mode,
252
- consecutiveFailures: this.consecutiveFailures,
253
- lastFailedToolKey: this.lastFailedToolKey,
254
- sequentialSearchCount: this.sequentialSearchCount,
255
- fileHashHistory: hashObj,
256
- modifiedFilesInTurn: Array.from(this.modifiedFilesInTurn),
257
- editedFiles: Array.from(this.modifiedFilesInTurn),
258
- pendingBatchEdits: Array.from(this.pendingBatchEdits),
259
- pendingFormatFiles: Array.from(this.pendingFormatFiles),
260
- codeEditedSinceLastTest: Boolean(this.codeEditedSinceLastTest),
261
- lastTurnGitCommitted: Boolean(this.lastTurnGitCommitted),
262
- committedTopDirs: Array.isArray(this.committedTopDirs) ? [...this.committedTopDirs] : [],
263
- consecutiveTrivialMaxEffortTurns: this.consecutiveTrivialMaxEffortTurns,
264
- recentEditTimestampsByFile: { ...this.recentEditTimestampsByFile },
265
- totalDiscoveryCalls: this.totalDiscoveryCalls,
266
- consecutiveVisionTurns: this.consecutiveVisionTurns,
267
- unanchoredTurnFlag: Boolean(this.unanchoredTurnFlag),
268
- candidateFiles: Array.isArray(this.candidateFiles) ? [...this.candidateFiles] : [],
269
- relayState: this.relayState ? { ...this.relayState } : { state: RELAY_STATES.IDLE, critiquePastes: 0, boundSpecPath: 'SPEC.md' },
270
- steeredPrompts: Number(this.steeredPrompts || 0),
271
- blockedPrompts: Number(this.blockedPrompts || 0),
272
- sightseeingToolsPrevented: Number(this.sightseeingToolsPrevented || 0),
273
- subagentTurns: { ...this.subagentTurns },
274
- subagentTokens: { ...this.subagentTokens },
275
- det11AdvisedTurn: this.det11AdvisedTurn,
276
- det13AdvisedTurn: this.det13AdvisedTurn,
277
- queuedMutations: this.router.mutationQueue.toJSON(),
278
- hysteresisState: this.router.hysteresisLock.getStatus()
279
- };
256
+ return serializeCircuitBreakerState(this);
280
257
  }
281
258
 
282
259
  /**
@@ -285,104 +262,7 @@ export class CircuitBreakerEngine {
285
262
  * @returns {this}
286
263
  */
287
264
  hydrateStateSnapshot(snap) {
288
- if (!snap || typeof snap !== 'object') return this;
289
-
290
- if (typeof snap.consecutiveFailures === 'number' && Number.isFinite(snap.consecutiveFailures)) {
291
- this.consecutiveFailures = Math.max(0, snap.consecutiveFailures);
292
- }
293
- if (snap.lastFailedToolKey !== undefined) {
294
- this.lastFailedToolKey = snap.lastFailedToolKey ? String(snap.lastFailedToolKey) : null;
295
- }
296
- if (
297
- typeof snap.sequentialSearchCount === 'number' &&
298
- Number.isFinite(snap.sequentialSearchCount)
299
- ) {
300
- this.sequentialSearchCount = Math.max(0, snap.sequentialSearchCount);
301
- }
302
- if (snap.fileHashHistory && typeof snap.fileHashHistory === 'object') {
303
- this.fileHashHistory = new Map();
304
- for (const [k, v] of Object.entries(snap.fileHashHistory)) {
305
- if (Array.isArray(v)) {
306
- this.fileHashHistory.set(k, v.slice(-6).map(String));
307
- }
308
- }
309
- }
310
- const editedList = Array.isArray(snap.modifiedFilesInTurn)
311
- ? snap.modifiedFilesInTurn
312
- : Array.isArray(snap.editedFiles)
313
- ? snap.editedFiles
314
- : null;
315
- if (editedList) {
316
- this.modifiedFilesInTurn = new Set(editedList.filter(Boolean).map(String));
317
- }
318
- if (Array.isArray(snap.pendingBatchEdits)) {
319
- this.pendingBatchEdits = new Set(snap.pendingBatchEdits.filter(Boolean).map(String));
320
- }
321
- if (Array.isArray(snap.pendingFormatFiles)) {
322
- this.pendingFormatFiles = new Set(snap.pendingFormatFiles.filter(Boolean).map(String));
323
- }
324
- if (typeof snap.codeEditedSinceLastTest === 'boolean') {
325
- this.codeEditedSinceLastTest = snap.codeEditedSinceLastTest;
326
- }
327
- if (typeof snap.lastTurnGitCommitted === 'boolean') {
328
- this.lastTurnGitCommitted = snap.lastTurnGitCommitted;
329
- }
330
- if (Array.isArray(snap.committedTopDirs)) {
331
- this.committedTopDirs = [...snap.committedTopDirs];
332
- }
333
- if (typeof snap.consecutiveTrivialMaxEffortTurns === 'number') {
334
- this.consecutiveTrivialMaxEffortTurns = snap.consecutiveTrivialMaxEffortTurns;
335
- }
336
- if (snap.recentEditTimestampsByFile && typeof snap.recentEditTimestampsByFile === 'object') {
337
- this.recentEditTimestampsByFile = { ...snap.recentEditTimestampsByFile };
338
- }
339
- if (typeof snap.totalDiscoveryCalls === 'number') {
340
- this.totalDiscoveryCalls = snap.totalDiscoveryCalls;
341
- }
342
- if (typeof snap.consecutiveVisionTurns === 'number') {
343
- this.consecutiveVisionTurns = snap.consecutiveVisionTurns;
344
- }
345
- if (typeof snap.unanchoredTurnFlag === 'boolean') {
346
- this.unanchoredTurnFlag = snap.unanchoredTurnFlag;
347
- }
348
- if (Array.isArray(snap.candidateFiles)) {
349
- this.candidateFiles = [...snap.candidateFiles];
350
- }
351
- if (snap.relayState && typeof snap.relayState === 'object') {
352
- this.relayState = { ...snap.relayState };
353
- }
354
- if (typeof snap.steeredPrompts === 'number') {
355
- this.steeredPrompts = snap.steeredPrompts;
356
- }
357
- if (typeof snap.blockedPrompts === 'number') {
358
- this.blockedPrompts = snap.blockedPrompts;
359
- }
360
- if (typeof snap.sightseeingToolsPrevented === 'number') {
361
- this.sightseeingToolsPrevented = snap.sightseeingToolsPrevented;
362
- }
363
- if (snap.subagentTurns && typeof snap.subagentTurns === 'object') {
364
- this.subagentTurns = { ...snap.subagentTurns };
365
- }
366
- if (snap.subagentTokens && typeof snap.subagentTokens === 'object') {
367
- this.subagentTokens = { ...snap.subagentTokens };
368
- }
369
- if (snap.det11AdvisedTurn !== undefined) {
370
- this.det11AdvisedTurn = snap.det11AdvisedTurn;
371
- }
372
- if (snap.det13AdvisedTurn !== undefined) {
373
- this.det13AdvisedTurn = snap.det13AdvisedTurn;
374
- }
375
- if (Array.isArray(snap.queuedMutations)) {
376
- this.router.mutationQueue.items = [...snap.queuedMutations];
377
- }
378
- if (snap.hysteresisState && typeof snap.hysteresisState === 'object') {
379
- this.router.hysteresisLock.locked = Boolean(snap.hysteresisState.locked);
380
- this.router.hysteresisLock.pinnedModel = snap.hysteresisState.pinnedModel || null;
381
- this.router.hysteresisLock.pinnedEffort = snap.hysteresisState.pinnedEffort || null;
382
- this.router.hysteresisLock.reason = snap.hysteresisState.reason || null;
383
- this.router.hysteresisLock.lockedAtTurn = snap.hysteresisState.lockedAtTurn ?? null;
384
- }
385
- return this;
265
+ return hydrateCircuitBreakerState(this, snap);
386
266
  }
387
267
 
388
268
  /**
@@ -710,10 +590,59 @@ export class CircuitBreakerEngine {
710
590
  );
711
591
  if (det04.triggered) return det04;
712
592
 
713
- // 4. DET-01: Destructive Shell & Git Hook-Bypass Blocker (Ring-0 Security)
714
- const det01 = resolveVerdict(evaluateDet01GitAndShellSafety({ toolName, command }));
593
+ // 4. DET-01: Destructive Shell & Git Hook-Bypass Blocker (Ring-0 Security + #3 Test Integrity + #18 Worktree Discard)
594
+ const effectiveUserPrompt = String(
595
+ toolEvent.lastUserInput ?? toolEvent.prompt ?? toolEvent.user_input ?? this.lastUserPrompt ?? ''
596
+ );
597
+ const det01 = resolveVerdict(
598
+ evaluateDet01GitAndShellSafety({
599
+ toolName,
600
+ command,
601
+ lastUserInput: effectiveUserPrompt,
602
+ userExplicitTestIntent: Boolean(toolEvent.userExplicitTestIntent)
603
+ })
604
+ );
715
605
  if (det01.triggered) return det01;
716
606
 
607
+ // 4b. Item A9 (#18): Concurrent Multi-Agent Worktree Isolation Guard on write-capable Task/Agent spawns
608
+ if (/^(?:Task|Agent)$/i.test(toolName) && !isCoachAdvisorySuppressed('DET-20')) {
609
+ const subagentType = String(
610
+ toolInput.subagent_type || toolInput.subagentType || toolInput.agent_type || toolInput.type || ''
611
+ ).trim();
612
+ const isReadOnlySubagent =
613
+ /^(?:Explore|Plan|research|claude-code-guide|ah-flash-scout)$/i.test(subagentType) ||
614
+ toolInput.readonly === true;
615
+ if (!isReadOnlySubagent) {
616
+ const isolation = String(toolInput.isolation || '').trim().toLowerCase();
617
+ const activeLocksCount = readActiveScopeLocks(this.options).locks.length;
618
+ const activeWorkersCount = Math.max(
619
+ activeLocksCount,
620
+ Array.isArray(this.activeWriteWorkers) ? this.activeWriteWorkers.length : 0,
621
+ Number(toolEvent.activeWriteWorkers ?? telemetryState.activeWriteWorkers ?? 0)
622
+ );
623
+ if (isolation !== 'worktree' && activeWorkersCount >= 1) {
624
+ const det20Worktree = resolveVerdict({
625
+ detectorId: 'DET-20',
626
+ triggered: true,
627
+ subType: 'WORKTREE_ISOLATION_REQUIRED',
628
+ decision: activeMode === FLIGHT_MODES.AUTO_PILOT ? 'deny' : 'ask',
629
+ advisory: false,
630
+ reason:
631
+ `[DET-20 Worktree Isolation Guard (#18)] Spawning write-capable ${toolName} without isolation: "worktree" while ${activeWorkersCount} write worker(s)/lock(s) are already active risks shared-tree clobbering. Set isolation: "worktree".`
632
+ });
633
+ if (det20Worktree.triggered) return det20Worktree;
634
+ }
635
+ if (toolInput.run_in_background === true || toolInput.background === true) {
636
+ const workerId = String(
637
+ toolInput.name || toolInput.description || `${toolName}_${Date.now()}`
638
+ ).slice(0, 60);
639
+ if (!this.activeWriteWorkers.includes(workerId)) {
640
+ this.activeWriteWorkers.push(workerId);
641
+ }
642
+ }
643
+ }
644
+ }
645
+
717
646
  // 5. DET-02: Secret & Credential Boundary (Ring-0 Security)
718
647
  const det02 = resolveVerdict(evaluateDet02SecretBoundary({ toolName, filePath, command }));
719
648
  if (det02.triggered) return det02;
@@ -743,7 +672,7 @@ export class CircuitBreakerEngine {
743
672
  }
744
673
  }
745
674
 
746
- // 9. DET-05: AST/Diff Edit Thrashing & Code Stripping Breaker
675
+ // 9. DET-05: AST/Diff Edit Thrashing, Test Integrity (#3) & Error Masking (#12) Breaker
747
676
  if (EDIT_WRITE_TOOL_REGEX.test(toolName)) {
748
677
  if (oldText || newText) {
749
678
  const history = this.fileHashHistory.get(filePath) || [];
@@ -751,6 +680,10 @@ export class CircuitBreakerEngine {
751
680
  filePath,
752
681
  oldText,
753
682
  newText,
683
+ toolName,
684
+ flightMode: activeMode,
685
+ lastUserInput: effectiveUserPrompt,
686
+ userExplicitTestIntent: Boolean(toolEvent.userExplicitTestIntent),
754
687
  fullFileOldLines: toolEvent.fullFileOldLines,
755
688
  fullFileNewLines: toolEvent.fullFileNewLines,
756
689
  hashHistory: history
@@ -843,11 +776,11 @@ export class CircuitBreakerEngine {
843
776
  .filter(Boolean);
844
777
  }
845
778
  if (
846
- /\b(?:node\s+--test|npm\s+test|pnpm\s+test|yarn\s+test|bun\s+test|vitest|jest|pytest|cargo\s+test|go\s+test)\b/i.test(
779
+ /\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(
847
780
  command
848
781
  )
849
782
  ) {
850
- this.codeEditedSinceLastTest = false;
783
+ this.pendingVerificationCommand = true;
851
784
  }
852
785
  this.sequentialSearchCount = 0;
853
786
  }
@@ -1059,6 +992,54 @@ export class CircuitBreakerEngine {
1059
992
  return this.consecutiveFailures;
1060
993
  }
1061
994
 
995
+ /**
996
+ * Updates `codeEditedSinceLastTest` and `lastFailingLocation` strictly on `PostToolUse`
997
+ * after a test/typecheck command actually completes with `exit_code === 0`.
998
+ *
999
+ * @param {{ succeeded: boolean, command?: string, outputText?: string }} outcome
1000
+ */
1001
+ recordVerificationOutcome(outcome = {}) {
1002
+ const succeeded = Boolean(outcome.succeeded);
1003
+ const command = String(outcome.command || '');
1004
+ const outputText = String(outcome.outputText || '');
1005
+ const isVerificationCmd =
1006
+ this.pendingVerificationCommand ||
1007
+ /\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(
1008
+ command
1009
+ );
1010
+
1011
+ if (!isVerificationCmd) {
1012
+ return {
1013
+ wasVerificationCommand: false,
1014
+ codeEditedSinceLastTest: this.codeEditedSinceLastTest,
1015
+ lastFailingLocation: this.lastFailingLocation
1016
+ };
1017
+ }
1018
+
1019
+ this.pendingVerificationCommand = false;
1020
+ if (succeeded) {
1021
+ this.codeEditedSinceLastTest = false;
1022
+ this.unverifiedEdits = [];
1023
+ this.lastFailingLocation = null;
1024
+ } else {
1025
+ if (this.modifiedFilesInTurn.size > 0 || this.codeEditedSinceLastTest) {
1026
+ this.codeEditedSinceLastTest = true;
1027
+ }
1028
+ const locMatch = outputText.match(
1029
+ /([A-Za-z0-9_./\\-]+\.(?:[cm]?[jt]sx?|py|rs|go|rb|java|kt|swift|c|cpp|h|hpp)):(\d+)(?::\d+)?/
1030
+ );
1031
+ if (locMatch) {
1032
+ this.lastFailingLocation = `${locMatch[1].replace(/\\/g, '/')}:${locMatch[2]}`;
1033
+ }
1034
+ }
1035
+
1036
+ return {
1037
+ wasVerificationCommand: true,
1038
+ codeEditedSinceLastTest: this.codeEditedSinceLastTest,
1039
+ lastFailingLocation: this.lastFailingLocation
1040
+ };
1041
+ }
1042
+
1062
1043
  /**
1063
1044
  * Evaluates `UserPromptSubmit` for Prompt Hygiene Governor (v4.1 Phase 1):
1064
1045
  * Relay Breaker (`'relay-breaker'`) & Scope Brake (`'vague-prompt-rubric'`).
@@ -1070,6 +1051,7 @@ export class CircuitBreakerEngine {
1070
1051
  const prompt = String(
1071
1052
  promptEvent.prompt ?? promptEvent.user_input ?? promptEvent.message ?? ''
1072
1053
  );
1054
+ this.lastUserPrompt = prompt;
1073
1055
  const activeMode = normalizeFlightMode(
1074
1056
  promptEvent.mode || telemetryState.flightMode || this.mode || FLIGHT_MODES.COACH
1075
1057
  );
@@ -1077,6 +1059,24 @@ export class CircuitBreakerEngine {
1077
1059
  return { triggered: false, decision: 'allow', reason: null };
1078
1060
  }
1079
1061
 
1062
+ // Item A6 (#11): Active DET-30 Thinking Runaway Step-Down Gate (>4,000 thinking tokens & >12x ratio across >=2 turns)
1063
+ const det30Override = resolveDetectorOverride('DET-30', this.horizonConfig);
1064
+ if (det30Override !== 'off' && activeMode !== FLIGHT_MODES.SILENT) {
1065
+ const det30Eval = evaluateActiveDet30StepDown({
1066
+ recentTurns: promptEvent.recentTurns || telemetryState.recentTurns,
1067
+ thinkingDrift: promptEvent.thinkingDrift || telemetryState.thinkingDrift,
1068
+ mode: det30Override === 'block' ? FLIGHT_MODES.AUTO_PILOT : (det30Override === 'warn' ? FLIGHT_MODES.COACH : activeMode)
1069
+ });
1070
+ if (det30Eval.triggered) {
1071
+ if (det30Eval.decision === 'block') {
1072
+ this.blockedPrompts = Number(this.blockedPrompts || 0) + 1;
1073
+ } else {
1074
+ this.steeredPrompts = Number(this.steeredPrompts || 0) + 1;
1075
+ }
1076
+ return det30Eval;
1077
+ }
1078
+ }
1079
+
1080
1080
  const modifiedNonMd = Array.from(this.modifiedFilesInTurn).filter(
1081
1081
  (f) => !/\.md$/i.test(String(f || ''))
1082
1082
  );