ctxtop 0.0.0-stage → 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.
- package/.antigravity-plugin/plugin.json +36 -0
- package/.claude-plugin/plugin.json +18 -0
- package/CHECKSUMS.sha256 +166 -0
- package/LICENSE +27 -0
- package/README.md +350 -2
- package/SECURITY.md +22 -0
- package/agents/ah-flash-scout.md +25 -0
- package/assets/advanced_view_loaded_420px.png +0 -0
- package/assets/hero-demo.svg +188 -0
- package/assets/logo.svg +19 -0
- package/assets/simple_view_lean_420px.png +0 -0
- package/assets/simple_view_loaded_420px.png +0 -0
- package/assets/social-preview.svg +72 -0
- package/assets/zone_c_step3_shield_full.png +0 -0
- package/bin/ah-statusline.mjs +175 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1799 -0
- package/commands/cost-radar.md +11 -0
- package/commands/evolve.md +10 -0
- package/commands/handoff.md +10 -0
- package/commands/horizon.md +10 -0
- package/commands/inspect.md +10 -0
- package/commands/precheck.md +10 -0
- package/config/default_flightcheck.json +133 -0
- package/config/modelCatalog.json +785 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +577 -0
- package/hooks/handlers/config-change.mjs +402 -0
- package/hooks/handlers/hookIo.mjs +311 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-model-switch.mjs +111 -0
- package/hooks/handlers/post-tool-use.mjs +366 -0
- package/hooks/handlers/pre-model-switch.mjs +1048 -0
- package/hooks/handlers/pre-tool-use.mjs +632 -0
- package/hooks/handlers/stop-gate.mjs +526 -0
- package/hooks/handlers/user-prompt-submit.mjs +367 -0
- package/hooks/hooks.json +131 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +25 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +726 -0
- package/hooks/session_start.mjs +24 -0
- package/hooks/stop.mjs +23 -0
- package/hooks.json +56 -0
- package/package.json +110 -4
- package/packages/antigravity/package.json +14 -0
- package/packages/antigravity/src/index.mjs +1 -0
- package/packages/claude-code/package.json +14 -0
- package/packages/claude-code/src/index.mjs +2 -0
- package/packages/core/package.json +14 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/engine-node/package.json +14 -0
- package/packages/engine-node/src/index.mjs +1 -0
- package/packages/mcp/package.json +17 -0
- package/packages/mcp/src/server.mjs +396 -0
- package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
- package/packages/pro/README-SIGNING.md +30 -0
- package/packages/pro/package.json +16 -0
- package/packages/pro/src/index.mjs +3 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -0
- package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
- package/plugin.json +36 -0
- package/rules/AGENTS.md +10 -0
- package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
- package/sidecars/horizon-daemon/server.mjs +2038 -0
- package/sidecars/horizon-daemon/sidecar.json +19 -0
- package/skills/cost-radar/SKILL.md +21 -0
- package/skills/evolve/SKILL.md +21 -0
- package/skills/handoff/SKILL.md +50 -0
- package/skills/horizon/SKILL.md +17 -0
- package/skills/inspect/SKILL.md +18 -0
- package/skills/precheck/SKILL.md +44 -0
- package/src/adapters/antigravity/index.mjs +109 -0
- package/src/adapters/claude-code/index.mjs +194 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +888 -0
- package/src/cli/init.mjs +425 -0
- package/src/cli/postmortem.mjs +515 -0
- package/src/coach/cacheGravityRouter.mjs +12 -0
- package/src/config/modelCatalog.json +704 -0
- package/src/config/platformQuirks.json +19 -0
- package/src/core/action_queue.mjs +264 -0
- package/src/core/ag_bridge.mjs +346 -0
- package/src/core/atomic_io.mjs +124 -0
- package/src/core/baseline.mjs +607 -0
- package/src/core/blindspot_sensors.mjs +399 -0
- package/src/core/bucket_b_runtime.mjs +1200 -0
- package/src/core/classifier.mjs +1757 -0
- package/src/core/coach/circuit_breakers.mjs +650 -0
- package/src/core/coach/contradiction_auditor.mjs +239 -0
- package/src/core/coach/effort_advisor.mjs +143 -0
- package/src/core/coach/handoff_hydrator.mjs +483 -0
- package/src/core/coach/progressive_checkpointer.mjs +551 -0
- package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
- package/src/core/coach/reflector_queue.mjs +505 -0
- package/src/core/coach/saved_quota_ledger.mjs +615 -0
- package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
- package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
- package/src/core/coach/task_quota_router.mjs +955 -0
- package/src/core/coach/turn_zero_gate.mjs +574 -0
- package/src/core/compaction_coach.mjs +1126 -0
- package/src/core/config.mjs +214 -0
- package/src/core/constants.mjs +1987 -0
- package/src/core/detectors_det01_to_16.mjs +1523 -0
- package/src/core/doc_indexer.mjs +338 -0
- package/src/core/episodic_memory.mjs +135 -0
- package/src/core/fts5_output_compressor.mjs +359 -0
- package/src/core/git_ledger.mjs +189 -0
- package/src/core/handoff_audit.mjs +558 -0
- package/src/core/history.mjs +221 -0
- package/src/core/hook_diagnostics.mjs +158 -0
- package/src/core/horizon_classifier.mjs +326 -0
- package/src/core/horizon_config.mjs +802 -0
- package/src/core/host_watchdog.mjs +200 -0
- package/src/core/layer5_hygiene.mjs +1084 -0
- package/src/core/log_resolver.mjs +231 -0
- package/src/core/mcp_auditor.mjs +138 -0
- package/src/core/micro_skills_store.mjs +91 -0
- package/src/core/offenders.mjs +161 -0
- package/src/core/parser.mjs +1997 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +311 -0
- package/src/core/prefix_cache_shield.mjs +386 -0
- package/src/core/pro_license.mjs +385 -0
- package/src/core/prompt_rubric.mjs +518 -0
- package/src/core/pruner.mjs +433 -0
- package/src/core/quota.mjs +1860 -0
- package/src/core/rsi_instinct_engine.mjs +1197 -0
- package/src/core/rsl_clash_auditor.mjs +423 -0
- package/src/core/rsl_distiller.mjs +372 -0
- package/src/core/rsl_ledger.mjs +969 -0
- package/src/core/rsl_triage.mjs +909 -0
- package/src/core/sanitizer.mjs +121 -0
- package/src/core/session_auditor.mjs +658 -0
- package/src/core/session_forensics.mjs +303 -0
- package/src/core/session_timeline.mjs +358 -0
- package/src/core/settings.mjs +99 -0
- package/src/core/shared/detectors.mjs +1342 -0
- package/src/core/shared/fnv1a64.mjs +85 -0
- package/src/core/shared/handoff_schema.mjs +123 -0
- package/src/core/shared/index.mjs +5 -0
- package/src/core/shared/ipi_sanitizer.mjs +165 -0
- package/src/core/shared/micro_skills.mjs +1 -0
- package/src/core/shared/plugin_validator.mjs +202 -0
- package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
- package/src/core/shield_manager.mjs +1417 -0
- package/src/core/sidecar_store.mjs +302 -0
- package/src/core/sprint_metrics.mjs +366 -0
- package/src/core/sqlite_client.mjs +283 -0
- package/src/core/storage_doctor.mjs +358 -0
- package/src/core/subagents.mjs +609 -0
- package/src/core/swarm_topology.mjs +360 -0
- package/src/core/task_quota_router.mjs +1656 -0
- package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
- package/src/core/telemetry/scope_lock_registry.mjs +578 -0
- package/src/core/telemetry/shadow_file_detector.mjs +291 -0
- package/src/core/telemetry/trajectory_watcher.mjs +259 -0
- package/src/core/timeline_svg.mjs +236 -0
- package/src/core/tool_surgeon.mjs +305 -0
- package/src/core/trajectory_stitcher.mjs +645 -0
- package/src/core/u_shaped_optimizer.mjs +789 -0
- package/src/core/wal_hygiene.mjs +233 -0
- package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/src/core-isomorphic/catalog/index.mjs +1 -0
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
- package/src/core-isomorphic/coach/microSkills.mjs +1 -0
- package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1055 -0
- package/src/core-isomorphic/control/callTree.mjs +338 -0
- package/src/core-isomorphic/control/coachLatches.mjs +126 -0
- package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/src/core-isomorphic/control/index.mjs +49 -0
- package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/src/core-isomorphic/diagnostics/index.mjs +9 -0
- package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +433 -0
- package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/src/core-isomorphic/economics/index.mjs +47 -0
- package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
- package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
- package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
- package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
- package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/src/core-isomorphic/index.js +27 -0
- package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1156 -0
- package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1237 -0
- package/src/core-isomorphic/ui/modViews.mjs +1504 -0
- package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/src/core-isomorphic/ustf/index.mjs +7 -0
- package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/src/core-isomorphic/ustf/schema.mjs +186 -0
- package/src/core-isomorphic/utils/runtime.mjs +962 -0
- package/src/demo/synthetic_states.mjs +661 -0
- package/src/diagnostics/bugReportGenerator.mjs +253 -0
- package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
- package/src/diagnostics/doctorEngine.mjs +295 -0
- package/src/engine-node/db/index.mjs +58 -0
- package/src/engine-node/db/jsonl_fallback.mjs +184 -0
- package/src/engine-node/db/probe.mjs +342 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +12 -0
- package/src/engine-node/ipc/client.mjs +447 -0
- package/src/engine-node/ipc/index.mjs +22 -0
- package/src/engine-node/ipc/protocol.mjs +177 -0
- package/src/engine-node/ipc/server.mjs +445 -0
- package/src/engine-node/offloader/index.mjs +6 -0
- package/src/engine-node/offloader/tool_offloader.mjs +241 -0
- package/src/engine-node/sensors/blindspots.mjs +376 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/antigravity_rsl_hook.mjs +250 -0
- package/src/hooks/claude_rsl_hook.mjs +288 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +611 -0
- package/src/hooks/pre_invocation.mjs +1725 -0
- package/src/hooks/session_start.mjs +199 -0
- package/src/shims/agy_cli_compressor.mjs +705 -0
- package/src/shims/agy_git_guard.mjs +749 -0
- package/src/shims/ah_log_query.mjs +39 -0
- package/src/ui/costRadarSvg.mjs +6 -0
- package/src/ui/horizonGrid.mjs +1 -0
- package/src/ui/horizonPanelHtml.mjs +1 -0
- package/src/ui/horizon_panel.css +167 -0
- package/src/ui/horizon_panel.js +212 -0
- package/src/ui/modViews.mjs +1 -0
- package/src/utils/modelSwitchTelemetry.mjs +308 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/utils/sessionCalibration.mjs +657 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +12397 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -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
|
+
}
|