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,909 @@
1
+ /**
2
+ * @file src/core/rsl_triage.mjs
3
+ * Dual-Platform Stage 1 Zero-Token Contrastive Triage & Anti-Reward-Hacking Gate.
4
+ *
5
+ * Supports both Google Antigravity (`SessionStart`, `PostToolUse`, `Stop`, `transcriptPath`,
6
+ * `artifactDirectoryPath`) and Claude Code (`session_id`, `cwd`, `transcript_path`, `PostToolUse`,
7
+ * `Stop`, `SessionEnd`) with <30ms synchronous latency and 0 LLM tokens.
8
+ */
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import crypto from 'node:crypto';
13
+ import { atomicWriteFileSync } from './atomic_io.mjs';
14
+ import { RSL_CONSTANTS } from './constants.mjs';
15
+
16
+ const TEST_FILE_EXT_RE = /\.(?:[cm]?[jt]sx?|py|go|rs)$/i;
17
+ const EXCLUDED_DIR_SEGMENTS = new Set([
18
+ 'node_modules',
19
+ '.git',
20
+ '.agents',
21
+ '.claude',
22
+ 'evaluation_bundles',
23
+ 'dist',
24
+ 'build',
25
+ 'out',
26
+ '.next',
27
+ 'coverage'
28
+ ]);
29
+
30
+ const GIT_MINING_RE = /\bgit\s+(?:fsck|cat-file|reflog|verify-pack)\b/i;
31
+ const TEST_CMD_RE = /(?:npm\s+(?:run\s+)?test|node\s+--test|pytest|vitest|jest|cargo\s+test|go\s+test|unittest|mocha|playwright)/i;
32
+ const USER_AUTHORIZED_TEST_REMOVAL_RE = /\b(?:delete|remove|drop|prune|disable|skip)\s+(?:the\s+|these\s+|old\s+|obsolete\s+)?tests?\b/i;
33
+ const USER_CORRECTION_RE = /\b(?:don'?t|do\s+not|never|instead\s+use|wrong|stop\s+using|should\s+be|always\s+use|avoid|rejected)\b/i;
34
+
35
+ /**
36
+ * Sanitizes a conversation/session identifier for telemetry filenames.
37
+ * @param {string} [sessionId='default']
38
+ * @returns {string}
39
+ */
40
+ export function sanitizeRslSessionId(sessionId = 'default') {
41
+ const safe = String(sessionId || 'default')
42
+ .replace(/[^a-zA-Z0-9._-]/g, '_')
43
+ .slice(0, 80);
44
+ return safe || 'default';
45
+ }
46
+
47
+ /**
48
+ * Resolves the workspace root from Antigravity, Claude Code, or CLI options.
49
+ * @param {object} [payload={}]
50
+ * @param {object} [options={}]
51
+ * @returns {string}
52
+ */
53
+ export function resolveWorkspaceRoot(payload = {}, options = {}) {
54
+ const candidate =
55
+ options.workspaceRoot ||
56
+ options.cwd ||
57
+ (Array.isArray(payload?.workspacePaths) && payload.workspacePaths[0]) ||
58
+ payload?.workspaceRoot ||
59
+ payload?.cwd ||
60
+ process.cwd();
61
+ return path.resolve(String(candidate || process.cwd()));
62
+ }
63
+
64
+ /**
65
+ * Strictly excludes `packages/airlock/` and non-source directories from all workspace scans.
66
+ * @param {string} relPath
67
+ * @returns {boolean}
68
+ */
69
+ export function isExcludedFromRslScan(relPath = '') {
70
+ const posix = String(relPath || '')
71
+ .replace(/\\/g, '/')
72
+ .replace(/^\.\/+/, '')
73
+ .replace(/^\/+/, '');
74
+ if (!posix) return false;
75
+ if (
76
+ posix === 'packages/airlock' ||
77
+ posix.startsWith('packages/airlock/') ||
78
+ posix === '.github/workflows/airlock-schema-canary.yml' ||
79
+ posix.startsWith('docs/HIGHBEAM_AIRLOCK_')
80
+ ) {
81
+ return true;
82
+ }
83
+ const parts = posix.split('/');
84
+ return parts.some((part) => EXCLUDED_DIR_SEGMENTS.has(part));
85
+ }
86
+
87
+ function isWorkspaceTestFile(relPosix) {
88
+ if (!TEST_FILE_EXT_RE.test(relPosix)) return false;
89
+ return (
90
+ /\.(?:test|spec)\.(?:[cm]?[jt]sx?|py|go|rs)$/i.test(relPosix) ||
91
+ /(?:^|\/)(?:test|tests|__tests__)\/.+\.(?:[cm]?[jt]sx?|py|go|rs)$/i.test(relPosix) ||
92
+ /_test\.(?:py|go)$/i.test(relPosix)
93
+ );
94
+ }
95
+
96
+ /**
97
+ * Computes SHA-256 + assertion/skip metrics for a single test file (opened strictly read-only `'r'`).
98
+ * @param {string} filePath
99
+ * @returns {{ sha256: string, lfSha256: string, assertionCount: number, skipCount: number, bytes: number } | null}
100
+ */
101
+ export function computeTestFileMetrics(filePath) {
102
+ let fd;
103
+ try {
104
+ const stat = fs.statSync(filePath);
105
+ if (!stat.isFile() || stat.size > 512 * 1024) return null;
106
+ fd = fs.openSync(filePath, 'r');
107
+ const buf = Buffer.allocUnsafe(stat.size);
108
+ let offset = 0;
109
+ while (offset < stat.size) {
110
+ const n = fs.readSync(fd, buf, offset, stat.size - offset, offset);
111
+ if (n === 0) break;
112
+ offset += n;
113
+ }
114
+ const rawBuf = offset === stat.size ? buf : buf.subarray(0, offset);
115
+ const raw = rawBuf.toString('utf8');
116
+ const normalized = raw.replace(/\r\n/g, '\n');
117
+ const sha256 = crypto.createHash('sha256').update(rawBuf).digest('hex');
118
+ const lfSha256 = crypto.createHash('sha256').update(normalized, 'utf8').digest('hex');
119
+ const assertionCount =
120
+ (normalized.match(/\b(?:assert(?:\.[a-zA-Z0-9_]+)?\s*\(|expect\s*\(|should\.|assert_eq!\s*\()/g) || []).length +
121
+ (normalized.match(/^\s*assert\s+\S+/gm) || []).length;
122
+ const skipCount =
123
+ (normalized.match(/(?:\.(?:skip|todo)\s*\(|\b(?:xit|xdescribe|xtest)\s*\(|(?:@?pytest\.mark\.skip(?:if)?|unittest\.skip)\b|#\[\s*ignore\b)/g) || []).length;
124
+ return { sha256, lfSha256, assertionCount, skipCount, bytes: rawBuf.byteLength };
125
+ } catch {
126
+ return null;
127
+ } finally {
128
+ if (fd !== undefined) {
129
+ try {
130
+ fs.closeSync(fd);
131
+ } catch {
132
+ // Ignore close error
133
+ }
134
+ }
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Snapshots SHA-256 hashes, assertion counts, and skip counts of workspace test files
140
+ * into `.agents/telemetry/<sessionId>.test_hashes.json` (excluding `packages/airlock/`).
141
+ *
142
+ * @param {string} workspaceRoot
143
+ * @param {string} [sessionId='default']
144
+ * @param {object} [options={}]
145
+ */
146
+ export function snapshotTestSuiteBaseline(workspaceRoot, sessionId = 'default', options = {}) {
147
+ const baseRoot = path.resolve(workspaceRoot || process.cwd());
148
+ const safeSessionId = sanitizeRslSessionId(sessionId);
149
+ const maxFiles = Math.max(1, Number(options.maxFiles || 400));
150
+ const deadlineMs = Date.now() + Number(options.budgetMs || 22);
151
+ const files = {};
152
+ let scannedCount = 0;
153
+
154
+ const walk = (dir, depth) => {
155
+ if (depth > 6 || scannedCount >= maxFiles || Date.now() > deadlineMs) return;
156
+ let entries;
157
+ try {
158
+ entries = fs.readdirSync(dir, { withFileTypes: true });
159
+ } catch {
160
+ return;
161
+ }
162
+ for (const entry of entries) {
163
+ if (scannedCount >= maxFiles || Date.now() > deadlineMs) break;
164
+ const fullPath = path.join(dir, entry.name);
165
+ const relPosix = path.relative(baseRoot, fullPath).replace(/\\/g, '/');
166
+ if (isExcludedFromRslScan(relPosix)) continue;
167
+ if (entry.isDirectory()) {
168
+ walk(fullPath, depth + 1);
169
+ } else if (entry.isFile() && isWorkspaceTestFile(relPosix)) {
170
+ const metrics = computeTestFileMetrics(fullPath);
171
+ if (metrics) {
172
+ files[relPosix] = metrics;
173
+ scannedCount += 1;
174
+ }
175
+ }
176
+ }
177
+ };
178
+
179
+ walk(baseRoot, 0);
180
+ const snapshotPath = path.join(baseRoot, '.agents', 'telemetry', `${safeSessionId}.test_hashes.json`);
181
+ const payload = {
182
+ schemaVersion: '2026.11.1',
183
+ sessionId: safeSessionId,
184
+ recordedAt: new Date().toISOString(),
185
+ fileCount: scannedCount,
186
+ files
187
+ };
188
+
189
+ try {
190
+ fs.mkdirSync(path.dirname(snapshotPath), { recursive: true });
191
+ atomicWriteFileSync(snapshotPath, `${JSON.stringify(payload, null, 2)}\n`);
192
+ } catch {
193
+ // Non-fatal on read-only workspaces
194
+ }
195
+
196
+ return { snapshotPath, fileCount: scannedCount, files };
197
+ }
198
+
199
+ function extractTargetFileFromArgs(args, workspaceRoot) {
200
+ if (!args || typeof args !== 'object') return '';
201
+ const raw =
202
+ args.file_path ||
203
+ args.filePath ||
204
+ args.TargetFile ||
205
+ args.AbsolutePath ||
206
+ args.Path ||
207
+ args.path ||
208
+ args.notebook_path ||
209
+ args.targetFile ||
210
+ '';
211
+ if (!raw || typeof raw !== 'string') return '';
212
+ const trimmed = raw.trim();
213
+ if (!trimmed) return '';
214
+ if (path.isAbsolute(trimmed) && workspaceRoot) {
215
+ const rel = path.relative(workspaceRoot, trimmed).replace(/\\/g, '/');
216
+ if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) {
217
+ return rel;
218
+ }
219
+ }
220
+ return trimmed.replace(/\\/g, '/');
221
+ }
222
+
223
+ function extractCommandFromArgs(args) {
224
+ if (!args || typeof args !== 'object') return '';
225
+ const raw = args.CommandLine || args.command || args.cmd || args.script || '';
226
+ return typeof raw === 'string' ? raw.trim() : '';
227
+ }
228
+
229
+ function inspectClaudeToolResponseFailure(resp) {
230
+ if (!resp) return { failed: false, errorText: '' };
231
+ if (typeof resp === 'string') {
232
+ const trimmed = resp.trim();
233
+ const isErr = /\b(?:Error|ERR!|FAIL|Exception|Command failed|exit status [1-9]|exit code [1-9])\b/i.test(trimmed);
234
+ return { failed: isErr, errorText: isErr ? trimmed.slice(0, 500) : '' };
235
+ }
236
+ if (typeof resp !== 'object') return { failed: false, errorText: '' };
237
+
238
+ const exitVal = resp.exitCode ?? resp.exit_code ?? resp.returncode;
239
+ const hasNonZeroExit = exitVal !== undefined && exitVal !== null && Number.isFinite(Number(exitVal)) && Number(exitVal) !== 0;
240
+ const stderr = typeof resp.stderr === 'string' ? resp.stderr.trim() : '';
241
+ const errStr = typeof resp.error === 'string' ? resp.error.trim() : (resp.error?.message ? String(resp.error.message) : '');
242
+ const stdoutStr = typeof resp.stdout === 'string' ? resp.stdout.trim() : '';
243
+ const hasStderrErr = Boolean(stderr) && (hasNonZeroExit || /\b(?:Error|ERR!|FAIL|Exception|SyntaxError|TypeError|ENOENT|exit code [1-9])\b/i.test(stderr));
244
+ const failed = Boolean(
245
+ resp.is_error === true ||
246
+ resp.isError === true ||
247
+ resp.succeeded === false ||
248
+ resp.status === 'error' ||
249
+ resp.status === 'failed' ||
250
+ Boolean(errStr) ||
251
+ hasNonZeroExit ||
252
+ hasStderrErr
253
+ );
254
+
255
+ if (!failed) return { failed: false, errorText: '' };
256
+ const detail = [errStr, stderr, hasNonZeroExit ? `exit ${exitVal}` : '', !errStr && !stderr ? stdoutStr : '']
257
+ .filter(Boolean)
258
+ .join(' | ')
259
+ .slice(0, 500);
260
+ return { failed: true, errorText: detail || 'Tool execution failed' };
261
+ }
262
+
263
+ /**
264
+ * Normalizes a `PostToolUse` payload from either Google Antigravity or Claude Code.
265
+ *
266
+ * @param {object} [rawPayload={}]
267
+ * @param {object} [options={}]
268
+ * @returns {object}
269
+ */
270
+ export function normalizeRslToolEvent(rawPayload = {}, options = {}) {
271
+ const workspaceRoot = resolveWorkspaceRoot(rawPayload, options);
272
+ const isClaudeShape = Boolean(
273
+ options.platform === 'claude' ||
274
+ rawPayload.tool_name ||
275
+ rawPayload.session_id ||
276
+ rawPayload.transcript_path
277
+ );
278
+ const platform = options.platform || (isClaudeShape ? 'claude' : 'antigravity');
279
+ const sessionId = sanitizeRslSessionId(
280
+ rawPayload.conversationId || rawPayload.session_id || rawPayload.sessionId || options.sessionId || 'default'
281
+ );
282
+ const toolName = String(
283
+ rawPayload.toolCall?.name || rawPayload.tool_name || rawPayload.toolName || ''
284
+ ).trim();
285
+ const args = rawPayload.toolCall?.args || rawPayload.tool_input || rawPayload.toolInput || {};
286
+ const targetFile = extractTargetFileFromArgs(args, workspaceRoot);
287
+ const command = extractCommandFromArgs(args);
288
+ const stepIdx = Number.isFinite(Number(rawPayload.stepIdx ?? rawPayload.step_index))
289
+ ? Number(rawPayload.stepIdx ?? rawPayload.step_index)
290
+ : null;
291
+
292
+ let failed = false;
293
+ let errorText = '';
294
+
295
+ if (typeof rawPayload.error === 'string' && rawPayload.error.trim().length > 0) {
296
+ failed = true;
297
+ errorText = rawPayload.error.trim().slice(0, 500);
298
+ } else if (rawPayload.is_error === true || rawPayload.isError === true || rawPayload.succeeded === false) {
299
+ failed = true;
300
+ errorText = String(rawPayload.tool_error || rawPayload.error || 'Tool execution failed').slice(0, 500);
301
+ } else if (
302
+ (rawPayload.exit_code !== undefined && Number(rawPayload.exit_code) !== 0) ||
303
+ (rawPayload.exitCode !== undefined && Number(rawPayload.exitCode) !== 0)
304
+ ) {
305
+ failed = true;
306
+ errorText = `exit ${rawPayload.exit_code ?? rawPayload.exitCode}`;
307
+ } else {
308
+ const respCheck = inspectClaudeToolResponseFailure(rawPayload.tool_response ?? rawPayload.toolResponse);
309
+ failed = respCheck.failed;
310
+ errorText = respCheck.errorText;
311
+ }
312
+
313
+ const isTestRun = TEST_CMD_RE.test(command);
314
+ const isTestPass = isTestRun && !failed;
315
+ const isGitMining = GIT_MINING_RE.test(command);
316
+
317
+ return {
318
+ ts: Date.now(),
319
+ platform,
320
+ sessionId,
321
+ workspaceRoot,
322
+ stepIdx,
323
+ toolName,
324
+ targetFile,
325
+ command: command.slice(0, 300),
326
+ failed,
327
+ errorText,
328
+ isTestRun,
329
+ isTestPass,
330
+ isGitMining
331
+ };
332
+ }
333
+
334
+ /**
335
+ * Records a normalized `PostToolUse` step outcome to `.agents/telemetry/<sessionId>.rsl_steps.jsonl`.
336
+ * Executes in <5ms synchronously.
337
+ *
338
+ * @param {object} [rawPayload={}]
339
+ * @param {object} [options={}]
340
+ */
341
+ export function recordStepOutcome(rawPayload = {}, options = {}) {
342
+ const normalized = normalizeRslToolEvent(rawPayload, options);
343
+ const stepsPath = path.join(
344
+ normalized.workspaceRoot,
345
+ '.agents',
346
+ 'telemetry',
347
+ `${normalized.sessionId}.rsl_steps.jsonl`
348
+ );
349
+ try {
350
+ fs.mkdirSync(path.dirname(stepsPath), { recursive: true });
351
+ fs.appendFileSync(stepsPath, `${JSON.stringify(normalized)}\n`, 'utf8');
352
+ } catch {
353
+ // Never throw from post-tool hook telemetry
354
+ }
355
+ return { ...normalized, stepsPath };
356
+ }
357
+
358
+ function readFileBoundedReadOnly(filePath, maxBytes = 512 * 1024) {
359
+ let fd;
360
+ try {
361
+ const stat = fs.statSync(filePath);
362
+ if (!stat.isFile()) return '';
363
+ const bytesToRead = Math.min(stat.size, maxBytes);
364
+ const startOffset = Math.max(0, stat.size - bytesToRead);
365
+ fd = fs.openSync(filePath, 'r');
366
+ const buf = Buffer.allocUnsafe(bytesToRead);
367
+ let offset = 0;
368
+ while (offset < bytesToRead) {
369
+ const n = fs.readSync(fd, buf, offset, bytesToRead - offset, startOffset + offset);
370
+ if (n === 0) break;
371
+ offset += n;
372
+ }
373
+ let text = buf.subarray(0, offset).toString('utf8');
374
+ if (startOffset > 0) {
375
+ const nl = text.indexOf('\n');
376
+ if (nl !== -1) text = text.slice(nl + 1);
377
+ }
378
+ return text;
379
+ } catch {
380
+ return '';
381
+ } finally {
382
+ if (fd !== undefined) {
383
+ try {
384
+ fs.closeSync(fd);
385
+ } catch {
386
+ // Ignore
387
+ }
388
+ }
389
+ }
390
+ }
391
+
392
+ function readRecordedSteps(workspaceRoot, sessionId) {
393
+ const safeId = sanitizeRslSessionId(sessionId);
394
+ const stepsPath = path.join(workspaceRoot, '.agents', 'telemetry', `${safeId}.rsl_steps.jsonl`);
395
+ if (!fs.existsSync(stepsPath)) return [];
396
+ const raw = readFileBoundedReadOnly(stepsPath, 512 * 1024);
397
+ const steps = [];
398
+ for (const line of raw.split(/\r?\n/)) {
399
+ if (!line.trim()) continue;
400
+ try {
401
+ const parsed = JSON.parse(line);
402
+ if (parsed && typeof parsed === 'object') steps.push(parsed);
403
+ } catch {
404
+ // Skip malformed line
405
+ }
406
+ }
407
+ return steps;
408
+ }
409
+
410
+ function extractTextFromClaudeContent(content) {
411
+ if (typeof content === 'string') return content;
412
+ if (!Array.isArray(content)) return '';
413
+ return content
414
+ .map((block) => {
415
+ if (typeof block === 'string') return block;
416
+ if (block?.type === 'text') return String(block.text || '');
417
+ return '';
418
+ })
419
+ .filter(Boolean)
420
+ .join('\n');
421
+ }
422
+
423
+ function parseTranscriptForRsl(transcriptPath, workspaceRoot, sessionId, platform) {
424
+ if (!transcriptPath || !fs.existsSync(transcriptPath)) {
425
+ return { steps: [], userCorrections: [], prompts: [] };
426
+ }
427
+ const raw = readFileBoundedReadOnly(transcriptPath, 512 * 1024);
428
+ if (!raw) return { steps: [], userCorrections: [], prompts: [] };
429
+
430
+ const steps = [];
431
+ const userCorrections = [];
432
+ const prompts = [];
433
+ const toolUseById = new Map();
434
+ let syntheticIdx = 0;
435
+
436
+ for (const line of raw.split(/\r?\n/)) {
437
+ if (!line.trim()) continue;
438
+ let obj;
439
+ try {
440
+ obj = JSON.parse(line);
441
+ } catch {
442
+ continue;
443
+ }
444
+ if (!obj || typeof obj !== 'object') continue;
445
+
446
+ // 1. Antigravity transcript entries
447
+ if (obj.type === 'USER_INPUT' && typeof obj.content === 'string') {
448
+ const txt = obj.content.trim();
449
+ if (txt) {
450
+ prompts.push(txt);
451
+ if (USER_CORRECTION_RE.test(txt)) {
452
+ userCorrections.push({
453
+ stepIdx: obj.step_index ?? syntheticIdx,
454
+ text: txt.slice(0, 400)
455
+ });
456
+ }
457
+ }
458
+ }
459
+
460
+ if (Array.isArray(obj.tool_calls)) {
461
+ for (const tc of obj.tool_calls) {
462
+ const idx = obj.step_index ?? syntheticIdx++;
463
+ const ev = normalizeRslToolEvent(
464
+ {
465
+ conversationId: sessionId,
466
+ workspacePaths: [workspaceRoot],
467
+ toolCall: { name: tc.name, args: tc.args || tc.arguments || {} },
468
+ stepIdx: idx,
469
+ error: tc.error || obj.error || ''
470
+ },
471
+ { platform }
472
+ );
473
+ steps.push(ev);
474
+ }
475
+ }
476
+
477
+ // 2. Claude Code JSONL transcript entries
478
+ if (obj.type === 'user' || obj.role === 'user') {
479
+ const msgContent = obj.message?.content ?? obj.content;
480
+ const text = extractTextFromClaudeContent(msgContent).trim();
481
+ if (text) {
482
+ prompts.push(text);
483
+ if (USER_CORRECTION_RE.test(text)) {
484
+ userCorrections.push({
485
+ stepIdx: syntheticIdx,
486
+ text: text.slice(0, 400)
487
+ });
488
+ }
489
+ }
490
+ if (Array.isArray(msgContent)) {
491
+ for (const block of msgContent) {
492
+ if (block?.type === 'tool_result') {
493
+ const linked = toolUseById.get(block.tool_use_id) || {};
494
+ const resultText = extractTextFromClaudeContent(block.content) || String(block.content || '');
495
+ const inferredErr =
496
+ Boolean(block.is_error) ||
497
+ (block.is_error === undefined && /^(?:Error:|Exit code [1-9]|Command failed)/im.test(resultText));
498
+ const ev = normalizeRslToolEvent(
499
+ {
500
+ session_id: sessionId,
501
+ cwd: workspaceRoot,
502
+ tool_name: linked.name || block.tool_name || 'Bash',
503
+ tool_input: linked.input || {},
504
+ stepIdx: syntheticIdx++,
505
+ tool_response: {
506
+ is_error: inferredErr,
507
+ error: inferredErr ? resultText : '',
508
+ stderr: inferredErr ? resultText : '',
509
+ stdout: inferredErr ? '' : resultText
510
+ }
511
+ },
512
+ { platform: 'claude' }
513
+ );
514
+ steps.push(ev);
515
+ }
516
+ }
517
+ }
518
+ }
519
+
520
+ if (obj.type === 'assistant' || obj.role === 'assistant') {
521
+ const msgContent = obj.message?.content ?? obj.content;
522
+ if (Array.isArray(msgContent)) {
523
+ for (const block of msgContent) {
524
+ if (block?.type === 'tool_use') {
525
+ toolUseById.set(block.id || `u_${syntheticIdx}`, {
526
+ name: block.name,
527
+ input: block.input || {}
528
+ });
529
+ }
530
+ }
531
+ }
532
+ }
533
+
534
+ // 3. Direct tool step records inside custom transcripts
535
+ if ((obj.tool_name || obj.toolCall) && obj.type !== 'assistant' && obj.type !== 'user') {
536
+ const ev = normalizeRslToolEvent(
537
+ {
538
+ ...obj,
539
+ cwd: obj.cwd || workspaceRoot,
540
+ session_id: obj.session_id || sessionId
541
+ },
542
+ { platform }
543
+ );
544
+ if (ev.stepIdx === null) ev.stepIdx = syntheticIdx++;
545
+ steps.push(ev);
546
+ }
547
+ }
548
+
549
+ return { steps, userCorrections, prompts };
550
+ }
551
+
552
+ function scanArtifactDirectoryForSupervision(artifactDirectoryPath) {
553
+ if (!artifactDirectoryPath || !fs.existsSync(artifactDirectoryPath)) {
554
+ return [];
555
+ }
556
+ const comments = [];
557
+ let entries = [];
558
+ try {
559
+ entries = fs.readdirSync(artifactDirectoryPath, { withFileTypes: true });
560
+ } catch {
561
+ return [];
562
+ }
563
+
564
+ for (const entry of entries.slice(0, 30)) {
565
+ if (!entry.isFile() || !/\.(?:md|json|txt)$/i.test(entry.name)) continue;
566
+ const full = path.join(artifactDirectoryPath, entry.name);
567
+ const content = readFileBoundedReadOnly(full, 128 * 1024);
568
+ if (!content) continue;
569
+
570
+ const lines = content.split(/\r?\n/);
571
+ for (let i = 0; i < lines.length; i++) {
572
+ const line = lines[i];
573
+ if (/✗\s*rejected|\[\s*rejected\s*\]|"status"\s*:\s*"rejected"/i.test(line)) {
574
+ const ctx = lines.slice(Math.max(0, i - 1), Math.min(lines.length, i + 3)).join(' ').trim();
575
+ comments.push({
576
+ file: entry.name,
577
+ kind: 'rejected',
578
+ lineNumber: i + 1,
579
+ text: ctx.slice(0, 400)
580
+ });
581
+ } else if (line.includes('💬')) {
582
+ comments.push({
583
+ file: entry.name,
584
+ kind: 'inline_comment',
585
+ lineNumber: i + 1,
586
+ text: line.replace(/\s+/g, ' ').trim().slice(0, 400)
587
+ });
588
+ }
589
+ }
590
+ }
591
+ return comments.slice(0, 10);
592
+ }
593
+
594
+ /**
595
+ * Runs EvilGenie & Coding-or-Cheating verification against the SessionStart test baseline.
596
+ *
597
+ * @param {string} workspaceRoot
598
+ * @param {string} sessionId
599
+ * @param {Array<object>} steps
600
+ * @param {string} [promptText='']
601
+ */
602
+ export function evaluateTestIntegrityGate(workspaceRoot, sessionId, steps = [], promptText = '') {
603
+ const safeId = sanitizeRslSessionId(sessionId);
604
+ const baselinePath = path.join(workspaceRoot, '.agents', 'telemetry', `${safeId}.test_hashes.json`);
605
+ const taintDetails = [];
606
+ const userAuthorizedRemoval = USER_AUTHORIZED_TEST_REMOVAL_RE.test(String(promptText || ''));
607
+
608
+ for (const st of steps) {
609
+ if (st?.isGitMining || GIT_MINING_RE.test(String(st?.command || ''))) {
610
+ taintDetails.push(`git_object_mining: ${String(st?.command || '').slice(0, 120)}`);
611
+ }
612
+ }
613
+
614
+ if (fs.existsSync(baselinePath)) {
615
+ try {
616
+ const baseline = JSON.parse(fs.readFileSync(baselinePath, 'utf8'));
617
+ const files = baseline?.files || {};
618
+ for (const [relPosix, prev] of Object.entries(files)) {
619
+ if (isExcludedFromRslScan(relPosix)) continue;
620
+ const abs = path.join(workspaceRoot, relPosix);
621
+ if (!fs.existsSync(abs)) {
622
+ if (!userAuthorizedRemoval) {
623
+ taintDetails.push(`test_file_deleted: ${relPosix}`);
624
+ }
625
+ continue;
626
+ }
627
+ const curr = computeTestFileMetrics(abs);
628
+ if (!curr) continue;
629
+ if (curr.skipCount > Number(prev.skipCount || 0)) {
630
+ taintDetails.push(`test_skip_added: ${relPosix} (${prev.skipCount} -> ${curr.skipCount})`);
631
+ }
632
+ if (curr.assertionCount < Number(prev.assertionCount || 0) && !userAuthorizedRemoval) {
633
+ taintDetails.push(
634
+ `test_assertions_removed: ${relPosix} (${prev.assertionCount} -> ${curr.assertionCount})`
635
+ );
636
+ }
637
+ }
638
+ } catch {
639
+ // Corrupt baseline should fail open for integrity gate
640
+ }
641
+ }
642
+
643
+ return {
644
+ tainted: taintDetails.length > 0,
645
+ status: taintDetails.length > 0 ? 'TAINTED_REWARD_HACK' : 'CLEAN',
646
+ taintDetails
647
+ };
648
+ }
649
+
650
+ function normalizeTerminationReason(rawStopPayload = {}) {
651
+ const raw = String(
652
+ rawStopPayload.terminationReason ?? rawStopPayload.termination_reason ?? ''
653
+ ).trim();
654
+ const upper = raw.toUpperCase();
655
+ if (!raw || upper === 'NO_TOOL_CALL' || upper === 'MODEL_STOP' || upper === 'END_TURN') {
656
+ return { raw: raw || 'NO_TOOL_CALL', cleanStop: true, canceled: false };
657
+ }
658
+ if (upper === 'USER_CANCELED' || upper === 'CANCELLED' || upper === 'CANCELED') {
659
+ return { raw, cleanStop: false, canceled: true };
660
+ }
661
+ if (
662
+ upper === 'TERMINAL_STEP_TYPE' ||
663
+ upper === 'INJECTED_RESPONSE' ||
664
+ upper === 'MAX_INVOCATIONS' ||
665
+ upper === 'MAX_STEPS_EXCEEDED'
666
+ ) {
667
+ return { raw, cleanStop: upper === 'TERMINAL_STEP_TYPE' || upper === 'INJECTED_RESPONSE', canceled: false };
668
+ }
669
+ return { raw, cleanStop: upper !== 'ERROR', canceled: false };
670
+ }
671
+
672
+ function stepsMatchTarget(a, b) {
673
+ if (!a || !b) return false;
674
+ if (a.targetFile && b.targetFile && a.targetFile === b.targetFile) return true;
675
+ if (a.toolName && b.toolName && a.toolName === b.toolName) return true;
676
+ return false;
677
+ }
678
+
679
+ function extractContrastivePairsAndThrash(steps = [], cleanStop = true) {
680
+ const pairs = [];
681
+ const thrashLoops = [];
682
+ const windowSize = RSL_CONSTANTS.CONTRASTIVE_WINDOW_STEPS;
683
+
684
+ let consecutiveFails = 0;
685
+ let thrashStartIdx = null;
686
+ let thrashTarget = '';
687
+
688
+ for (let i = 0; i < steps.length; i++) {
689
+ const st = steps[i];
690
+ if (st.failed) {
691
+ if (consecutiveFails === 0 || (thrashTarget && (st.targetFile || st.toolName) === thrashTarget)) {
692
+ if (consecutiveFails === 0) {
693
+ thrashStartIdx = st.stepIdx ?? i;
694
+ thrashTarget = st.targetFile || st.toolName;
695
+ }
696
+ consecutiveFails += 1;
697
+ } else {
698
+ consecutiveFails = 1;
699
+ thrashStartIdx = st.stepIdx ?? i;
700
+ thrashTarget = st.targetFile || st.toolName;
701
+ }
702
+
703
+ // Search 1..windowSize steps ahead for recovery on same tool/file
704
+ const recoverySteps = [];
705
+ let recoveredIdx = -1;
706
+ let validatedByTest = false;
707
+
708
+ for (let j = i + 1; j < steps.length && j <= i + windowSize; j++) {
709
+ const cand = steps[j];
710
+ if (cand.failed) break;
711
+ if (cand.isTestPass) validatedByTest = true;
712
+ if (stepsMatchTarget(st, cand) || cand.isTestPass || recoveredIdx === -1) {
713
+ recoverySteps.push({
714
+ stepIdx: cand.stepIdx ?? j,
715
+ toolName: cand.toolName,
716
+ targetFile: cand.targetFile,
717
+ command: cand.command,
718
+ isTestPass: Boolean(cand.isTestPass)
719
+ });
720
+ if (stepsMatchTarget(st, cand) && recoveredIdx === -1) {
721
+ recoveredIdx = j;
722
+ }
723
+ if (cand.isTestPass && recoveredIdx !== -1) {
724
+ break;
725
+ }
726
+ if (recoveredIdx !== -1) {
727
+ const next = steps[j + 1];
728
+ if (!next || next.failed || (!stepsMatchTarget(st, next) && !next.isTestPass)) {
729
+ break;
730
+ }
731
+ }
732
+ }
733
+ }
734
+
735
+ if (recoveredIdx !== -1 && (validatedByTest || cleanStop)) {
736
+ pairs.push({
737
+ failureStepIdx: st.stepIdx ?? i,
738
+ recoveryStepIdx: steps[recoveredIdx].stepIdx ?? recoveredIdx,
739
+ toolName: st.toolName,
740
+ targetFile: st.targetFile || steps[recoveredIdx].targetFile || '',
741
+ command: st.command,
742
+ errorText: st.errorText,
743
+ recoveryAction: steps[recoveredIdx].command || steps[recoveredIdx].targetFile || steps[recoveredIdx].toolName,
744
+ recoverySteps,
745
+ validatedByTest
746
+ });
747
+ }
748
+ } else {
749
+ if (consecutiveFails >= 3) {
750
+ thrashLoops.push({
751
+ startStepIdx: thrashStartIdx,
752
+ resolvedStepIdx: st.stepIdx ?? i,
753
+ failureCount: consecutiveFails,
754
+ target: thrashTarget,
755
+ resolvedTool: st.toolName
756
+ });
757
+ }
758
+ consecutiveFails = 0;
759
+ thrashStartIdx = null;
760
+ thrashTarget = '';
761
+ }
762
+ }
763
+
764
+ return { pairs, thrashLoops };
765
+ }
766
+
767
+ /**
768
+ * Builds a bounded contrastive post-mortem digest (~2k tokens) from step telemetry,
769
+ * read-only transcripts, and Antigravity artifacts. Fast-exits in <10ms if 0 triggers occurred.
770
+ *
771
+ * @param {object} [rawStopPayload={}]
772
+ * @param {object} [options={}]
773
+ */
774
+ export function buildContrastiveDigest(rawStopPayload = {}, options = {}) {
775
+ const workspaceRoot = resolveWorkspaceRoot(rawStopPayload, options);
776
+ const platform =
777
+ options.platform ||
778
+ (rawStopPayload.session_id || rawStopPayload.transcript_path ? 'claude' : 'antigravity');
779
+ const sessionId = sanitizeRslSessionId(
780
+ rawStopPayload.conversationId || rawStopPayload.session_id || rawStopPayload.sessionId || options.sessionId || 'default'
781
+ );
782
+ const term = normalizeTerminationReason(rawStopPayload);
783
+ const transcriptPath = rawStopPayload.transcriptPath || rawStopPayload.transcript_path || options.transcriptPath || '';
784
+ const artifactDirectoryPath = rawStopPayload.artifactDirectoryPath || options.artifactDirectoryPath || '';
785
+
786
+ const recordedSteps = readRecordedSteps(workspaceRoot, sessionId);
787
+ const transcriptData = parseTranscriptForRsl(transcriptPath, workspaceRoot, sessionId, platform);
788
+ const steps = recordedSteps.length > 0 ? recordedSteps : transcriptData.steps;
789
+
790
+ const combinedPromptText = [
791
+ String(rawStopPayload.lastUserInput || ''),
792
+ ...transcriptData.prompts
793
+ ]
794
+ .filter(Boolean)
795
+ .join('\n');
796
+
797
+ const integrity = evaluateTestIntegrityGate(workspaceRoot, sessionId, steps, combinedPromptText);
798
+
799
+ const touchedFiles = Array.from(
800
+ new Set(steps.map((s) => s.targetFile).filter(Boolean))
801
+ );
802
+ const executedTools = Array.from(
803
+ new Set(steps.map((s) => s.toolName).filter(Boolean))
804
+ );
805
+ const unresolvedErrors = steps
806
+ .filter((s) => s.failed)
807
+ .map((s) => ({
808
+ stepIdx: s.stepIdx,
809
+ toolName: s.toolName,
810
+ targetFile: s.targetFile,
811
+ errorText: s.errorText
812
+ }));
813
+
814
+ if (integrity.tainted) {
815
+ return {
816
+ schemaVersion: '2026.11.1',
817
+ sessionId,
818
+ platform,
819
+ workspaceRoot,
820
+ terminationReason: term.raw,
821
+ triggered: false,
822
+ tainted: true,
823
+ status: 'TAINTED_REWARD_HACK',
824
+ taintDetails: integrity.taintDetails,
825
+ contrastivePairs: [],
826
+ artifactComments: [],
827
+ userCorrections: [],
828
+ thrashLoops: [],
829
+ touchedFiles,
830
+ executedTools,
831
+ unresolvedErrors
832
+ };
833
+ }
834
+
835
+ const { pairs, thrashLoops } = extractContrastivePairsAndThrash(steps, term.cleanStop);
836
+ const artifactComments = scanArtifactDirectoryForSupervision(artifactDirectoryPath);
837
+ const userCorrections = transcriptData.userCorrections.slice(0, 8);
838
+
839
+ const hasTriggers =
840
+ !term.canceled &&
841
+ (pairs.length > 0 || artifactComments.length > 0 || userCorrections.length > 0 || thrashLoops.length > 0);
842
+
843
+ if (!hasTriggers) {
844
+ return {
845
+ schemaVersion: '2026.11.1',
846
+ sessionId,
847
+ platform,
848
+ workspaceRoot,
849
+ terminationReason: term.raw,
850
+ triggered: false,
851
+ tainted: false,
852
+ status: 'CLEAN_NO_TRIGGERS',
853
+ taintDetails: [],
854
+ contrastivePairs: [],
855
+ artifactComments: [],
856
+ userCorrections: [],
857
+ thrashLoops: [],
858
+ touchedFiles,
859
+ executedTools,
860
+ unresolvedErrors
861
+ };
862
+ }
863
+
864
+ let digest = {
865
+ schemaVersion: '2026.11.1',
866
+ sessionId,
867
+ platform,
868
+ workspaceRoot,
869
+ recordedAt: new Date().toISOString(),
870
+ terminationReason: term.raw,
871
+ triggered: true,
872
+ tainted: false,
873
+ status: 'READY',
874
+ taintDetails: [],
875
+ contrastivePairs: pairs.slice(0, 6),
876
+ artifactComments: artifactComments.slice(0, 6),
877
+ userCorrections: userCorrections.slice(0, 6),
878
+ thrashLoops: thrashLoops.slice(0, 4),
879
+ touchedFiles: touchedFiles.slice(0, 20),
880
+ executedTools: executedTools.slice(0, 15),
881
+ unresolvedErrors: unresolvedErrors.slice(0, 10)
882
+ };
883
+
884
+ // Enforce ~2k token budget ceiling on persisted contrastive digest
885
+ let serialized = JSON.stringify(digest, null, 2);
886
+ if (serialized.length > RSL_CONSTANTS.MAX_DIGEST_CHARS) {
887
+ digest = {
888
+ ...digest,
889
+ contrastivePairs: digest.contrastivePairs.slice(0, 3),
890
+ artifactComments: digest.artifactComments.slice(0, 3),
891
+ userCorrections: digest.userCorrections.slice(0, 3)
892
+ };
893
+ serialized = JSON.stringify(digest, null, 2);
894
+ }
895
+
896
+ const queueDir = path.join(workspaceRoot, '.agents', 'telemetry', 'rsl_queue');
897
+ const digestPath = path.join(queueDir, `${sessionId}.digest.json`);
898
+ try {
899
+ fs.mkdirSync(queueDir, { recursive: true });
900
+ atomicWriteFileSync(digestPath, `${serialized}\n`);
901
+ } catch {
902
+ // Non-fatal
903
+ }
904
+
905
+ return {
906
+ ...digest,
907
+ digestPath
908
+ };
909
+ }