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,372 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core/rsl_distiller.mjs
|
|
3
|
+
* Stage 2 Dual-Platform RSL Distiller (`--mode local` default, 0 LLM tokens, <15ms;
|
|
4
|
+
* optional `--mode sdk` wrapper around `scripts/rsl_sdk_distiller.py`).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import crypto from 'node:crypto';
|
|
10
|
+
import { execFileSync } from 'node:child_process';
|
|
11
|
+
import { fileURLToPath } from 'node:url';
|
|
12
|
+
|
|
13
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
14
|
+
const SDK_SCRIPT_PATH = path.resolve(__dirname, '..', '..', 'scripts', 'rsl_sdk_distiller.py');
|
|
15
|
+
|
|
16
|
+
const XML_LEAK_RE = /<\/?(?:system_context_prefix|ADDITIONAL_METADATA|USER_SETTINGS_CHANGE|CONTEXT_SUMMARY|SYSTEM_MESSAGE|RULE|user_rules)\b/i;
|
|
17
|
+
const TRIVIAL_TYPO_RE = /\b(?:SyntaxError:\s*Unexpected\s+token|missing\s+semicolon|typo\s+in\s+identifier)\b/i;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Normalizes any text into a strict lowercase kebab-case slug (<= 48 chars).
|
|
21
|
+
* @param {string} raw
|
|
22
|
+
* @param {string} [fallback='session-lesson']
|
|
23
|
+
* @returns {string}
|
|
24
|
+
*/
|
|
25
|
+
export function toKebabSlug(raw = '', fallback = 'session-lesson') {
|
|
26
|
+
const cleaned = String(raw || '')
|
|
27
|
+
.toLowerCase()
|
|
28
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
29
|
+
.replace(/^-+|-+$/g, '')
|
|
30
|
+
.slice(0, 48)
|
|
31
|
+
.replace(/-+$/g, '');
|
|
32
|
+
return cleaned || fallback;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function shortStableHash(input = '') {
|
|
36
|
+
return crypto.createHash('sha1').update(String(input || '')).digest('hex').slice(0, 6);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function buildGlobPatterns(targetFile = '') {
|
|
40
|
+
const posix = String(targetFile || '').replace(/\\/g, '/').replace(/^\.\//, '');
|
|
41
|
+
if (!posix) return { globs: '', paths: [] };
|
|
42
|
+
const ext = path.posix.extname(posix);
|
|
43
|
+
const dir = path.posix.dirname(posix);
|
|
44
|
+
const patterns = [];
|
|
45
|
+
if (ext) patterns.push(`*${ext}`);
|
|
46
|
+
if (dir && dir !== '.') {
|
|
47
|
+
const topDir = dir.split('/')[0];
|
|
48
|
+
if (topDir) patterns.push(`${topDir}/**`);
|
|
49
|
+
} else {
|
|
50
|
+
patterns.push(posix);
|
|
51
|
+
}
|
|
52
|
+
const unique = Array.from(new Set(patterns));
|
|
53
|
+
return {
|
|
54
|
+
globs: unique.join(', '),
|
|
55
|
+
paths: unique
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function inferToolMatchers(toolName = '', command = '') {
|
|
60
|
+
const lower = String(toolName || '').toLowerCase();
|
|
61
|
+
if (lower === 'run_command' || lower === 'bash' || lower === 'powershell' || command) {
|
|
62
|
+
return {
|
|
63
|
+
toolMatcher: 'run_command',
|
|
64
|
+
claudeToolMatcher: 'Bash|PowerShell'
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
if (/edit|write|replace|patch/i.test(lower)) {
|
|
68
|
+
return {
|
|
69
|
+
toolMatcher: 'edit_file|write_file|replace_file_content|multi_replace_file_content',
|
|
70
|
+
claudeToolMatcher: 'Edit|MultiEdit|Write|NotebookEdit'
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
toolMatcher: toolName || 'run_command|edit_file|write_file',
|
|
75
|
+
claudeToolMatcher: 'Bash|PowerShell|Edit|MultiEdit|Write'
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function extractDenyPattern(command = '', text = '') {
|
|
80
|
+
const cmd = String(command || '').trim();
|
|
81
|
+
if (cmd) {
|
|
82
|
+
// Capture first two tokens of failing risky command if concise
|
|
83
|
+
const tokens = cmd.split(/\s+/).slice(0, 3).join(' ');
|
|
84
|
+
if (tokens.length >= 4 && tokens.length <= 64) {
|
|
85
|
+
return tokens;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const m = String(text || '').match(/`([^`]{4,64})`/);
|
|
89
|
+
return m ? m[1] : '';
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function buildThirdPersonDescription(contextText = '', negativeScope = 'unrelated files or tasks outside this scope') {
|
|
93
|
+
const cleanCtx = String(contextText || 'applying workspace lessons')
|
|
94
|
+
.replace(/^(?:you are|proactively|always)\s+/i, '')
|
|
95
|
+
.replace(/\$ARGUMENTS\b/gi, '')
|
|
96
|
+
.replace(/\s+/g, ' ')
|
|
97
|
+
.trim()
|
|
98
|
+
.replace(/\.+$/, '');
|
|
99
|
+
return `Use when ${cleanCtx}. Do not use for ${negativeScope}.`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function sanitizeGuidanceText(raw = '') {
|
|
103
|
+
return String(raw || '')
|
|
104
|
+
.replace(/\$ARGUMENTS\b/gi, '')
|
|
105
|
+
.replace(XML_LEAK_RE, '')
|
|
106
|
+
.replace(/\s+/g, ' ')
|
|
107
|
+
.trim();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function distillLocally(digest) {
|
|
111
|
+
const heuristics = [];
|
|
112
|
+
const seenSlugs = new Set();
|
|
113
|
+
|
|
114
|
+
const pushHeuristic = (item) => {
|
|
115
|
+
if (!item || !item.slug || !item.then_guidance) return;
|
|
116
|
+
if (XML_LEAK_RE.test(item.then_guidance) || XML_LEAK_RE.test(item.when_condition || '')) return;
|
|
117
|
+
let slug = toKebabSlug(item.slug);
|
|
118
|
+
if (seenSlugs.has(slug)) {
|
|
119
|
+
slug = toKebabSlug(`${slug}-${shortStableHash(item.when_condition || item.then_guidance)}`);
|
|
120
|
+
}
|
|
121
|
+
seenSlugs.add(slug);
|
|
122
|
+
heuristics.push({
|
|
123
|
+
...item,
|
|
124
|
+
slug,
|
|
125
|
+
description: buildThirdPersonDescription(
|
|
126
|
+
item.description || item.when_condition,
|
|
127
|
+
item.negativeScope || 'unrelated modules or one-off tasks'
|
|
128
|
+
)
|
|
129
|
+
});
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
// 1. Contrastive Failure-Recovery Pairs -> Skill Workflows (multi-step) or Glob/Domain Rules
|
|
133
|
+
for (const pair of digest.contrastivePairs || []) {
|
|
134
|
+
const err = sanitizeGuidanceText(pair.errorText || '');
|
|
135
|
+
const cmd = sanitizeGuidanceText(pair.command || '');
|
|
136
|
+
const recovery = sanitizeGuidanceText(pair.recoveryAction || '');
|
|
137
|
+
const targetFile = String(pair.targetFile || '').replace(/\\/g, '/');
|
|
138
|
+
const recoverySteps = Array.isArray(pair.recoverySteps) ? pair.recoverySteps : [];
|
|
139
|
+
|
|
140
|
+
// Filter out isolated one-off syntax typos unless backed by multi-step test-verified recovery
|
|
141
|
+
const nonTestRecoverySteps = recoverySteps.filter(
|
|
142
|
+
(s) => !s.isTestPass && !/(?:npm\s+(?:run\s+)?test|node\s+--test|pytest|vitest|jest)/i.test(String(s.command || ''))
|
|
143
|
+
);
|
|
144
|
+
if (TRIVIAL_TYPO_RE.test(err) && nonTestRecoverySteps.length < 2 && !pair.validatedByTest) {
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const isMultiStep = nonTestRecoverySteps.length >= 2;
|
|
149
|
+
const { globs, paths } = buildGlobPatterns(targetFile);
|
|
150
|
+
const matchers = inferToolMatchers(pair.toolName, cmd);
|
|
151
|
+
const errorSignature = `${pair.toolName || 'tool'}:${err.slice(0, 80)}`.toLowerCase();
|
|
152
|
+
|
|
153
|
+
if (isMultiStep) {
|
|
154
|
+
const stepLines = recoverySteps.map((s, idx) => {
|
|
155
|
+
const actionDesc = sanitizeGuidanceText(s.command || s.targetFile || s.toolName || `step ${idx + 1}`);
|
|
156
|
+
return `${idx + 1}. Run \`${s.toolName || 'tool'}\` on ${actionDesc}`;
|
|
157
|
+
});
|
|
158
|
+
const baseName = targetFile
|
|
159
|
+
? path.posix.basename(targetFile, path.posix.extname(targetFile))
|
|
160
|
+
: (pair.toolName || 'recovery');
|
|
161
|
+
const slug = toKebabSlug(`recover-${baseName}-${shortStableHash(err || recovery)}`);
|
|
162
|
+
pushHeuristic({
|
|
163
|
+
carrier: 'skill_workflow',
|
|
164
|
+
slug,
|
|
165
|
+
when_condition: `Recovering after \`${pair.toolName || 'tool'}\` fails${err ? ` with "${err.slice(0, 120)}"` : ''}`,
|
|
166
|
+
description: `replaying the verified ${recoverySteps.length}-step recovery workflow for ${targetFile || pair.toolName || 'this task'}`,
|
|
167
|
+
negativeScope: 'unrelated features or clean runs without this failure signature',
|
|
168
|
+
globs,
|
|
169
|
+
paths,
|
|
170
|
+
then_guidance: `Follow the verified recovery sequence:\n${stepLines.join('\n')}`,
|
|
171
|
+
steps: stepLines,
|
|
172
|
+
evidence_step_ids: [pair.failureStepIdx, ...recoverySteps.map((s) => s.stepIdx)].filter(
|
|
173
|
+
(n) => Number.isFinite(Number(n))
|
|
174
|
+
),
|
|
175
|
+
errorSignature,
|
|
176
|
+
...matchers,
|
|
177
|
+
denyPattern: extractDenyPattern(cmd, err)
|
|
178
|
+
});
|
|
179
|
+
} else {
|
|
180
|
+
const carrier = globs ? 'rule_glob' : 'rule_model_decision';
|
|
181
|
+
const baseName = targetFile
|
|
182
|
+
? path.posix.basename(targetFile, path.posix.extname(targetFile))
|
|
183
|
+
: (pair.toolName || 'constraint');
|
|
184
|
+
const slug = toKebabSlug(`avoid-${baseName}-${shortStableHash(err || cmd || recovery)}`);
|
|
185
|
+
const refFile = targetFile ? `@[${path.posix.basename(targetFile)}](${targetFile})` : '';
|
|
186
|
+
const whenCond = `Invoking \`${pair.toolName || 'tool'}\`${targetFile ? ` on ${refFile}` : ''}${cmd ? ` (\`${cmd.slice(0, 80)}\`)` : ''}`;
|
|
187
|
+
const thenGuide = recovery
|
|
188
|
+
? `Avoid repeating "${err.slice(0, 140)}"; apply verified recovery \`${recovery}\`${targetFile ? ` against ${refFile}` : ''}.`
|
|
189
|
+
: `Verify prerequisites before running \`${pair.toolName || 'tool'}\` so "${err.slice(0, 140)}" does not recur.`;
|
|
190
|
+
pushHeuristic({
|
|
191
|
+
carrier,
|
|
192
|
+
slug,
|
|
193
|
+
when_condition: whenCond,
|
|
194
|
+
description: `working with ${targetFile || pair.toolName || 'this domain'} to prevent "${err.slice(0, 80)}"`,
|
|
195
|
+
globs,
|
|
196
|
+
paths,
|
|
197
|
+
then_guidance: thenGuide,
|
|
198
|
+
steps: [],
|
|
199
|
+
evidence_step_ids: [pair.failureStepIdx, pair.recoveryStepIdx].filter((n) => Number.isFinite(Number(n))),
|
|
200
|
+
errorSignature,
|
|
201
|
+
...matchers,
|
|
202
|
+
denyPattern: extractDenyPattern(cmd, err)
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// 2. Antigravity Artifact Rejections & Inline User Comments -> Rules
|
|
208
|
+
for (const comment of digest.artifactComments || []) {
|
|
209
|
+
const cleanText = sanitizeGuidanceText(comment.text || '');
|
|
210
|
+
if (!cleanText || cleanText.length < 8) continue;
|
|
211
|
+
const fileMatch = cleanText.match(/([a-zA-Z0-9_./-]+\.(?:mjs|js|ts|tsx|py|json|md|go|rs))/);
|
|
212
|
+
const targetFile = fileMatch ? fileMatch[1].replace(/\\/g, '/') : '';
|
|
213
|
+
const { globs, paths } = buildGlobPatterns(targetFile);
|
|
214
|
+
const carrier = globs ? 'rule_glob' : 'rule_model_decision';
|
|
215
|
+
const slug = toKebabSlug(`review-${comment.kind || 'feedback'}-${shortStableHash(cleanText)}`);
|
|
216
|
+
pushHeuristic({
|
|
217
|
+
carrier,
|
|
218
|
+
slug,
|
|
219
|
+
when_condition: `User review ${comment.kind === 'rejected' ? 'rejection' : 'inline feedback'} in ${comment.file || 'artifact'}`,
|
|
220
|
+
description: `planning or editing ${targetFile || 'workspace architecture'} affected by artifact review feedback`,
|
|
221
|
+
globs,
|
|
222
|
+
paths,
|
|
223
|
+
then_guidance: `Enforce user artifact guidance: ${cleanText.slice(0, 320)}`,
|
|
224
|
+
steps: [],
|
|
225
|
+
evidence_step_ids: [],
|
|
226
|
+
errorSignature: `artifact:${shortStableHash(cleanText)}`,
|
|
227
|
+
...inferToolMatchers('edit_file', ''),
|
|
228
|
+
denyPattern: extractDenyPattern('', cleanText)
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// 3. Claude / Antigravity User Correction Turns -> Rules
|
|
233
|
+
for (const corr of digest.userCorrections || []) {
|
|
234
|
+
const cleanText = sanitizeGuidanceText(corr.text || '');
|
|
235
|
+
if (!cleanText || cleanText.length < 8) continue;
|
|
236
|
+
const fileMatch = cleanText.match(/([a-zA-Z0-9_./-]+\.(?:mjs|js|ts|tsx|py|json|md|go|rs))/);
|
|
237
|
+
const targetFile = fileMatch ? fileMatch[1].replace(/\\/g, '/') : '';
|
|
238
|
+
const { globs, paths } = buildGlobPatterns(targetFile);
|
|
239
|
+
const carrier = globs ? 'rule_glob' : 'rule_model_decision';
|
|
240
|
+
const slug = toKebabSlug(`user-correction-${shortStableHash(cleanText)}`);
|
|
241
|
+
pushHeuristic({
|
|
242
|
+
carrier,
|
|
243
|
+
slug,
|
|
244
|
+
when_condition: `Session user correction turn (${digest.platform || 'agent'})`,
|
|
245
|
+
description: `handling ${targetFile || 'commands and edits'} governed by explicit user correction`,
|
|
246
|
+
globs,
|
|
247
|
+
paths,
|
|
248
|
+
then_guidance: `Follow explicit user directive: ${cleanText.slice(0, 320)}`,
|
|
249
|
+
steps: [],
|
|
250
|
+
evidence_step_ids: Number.isFinite(Number(corr.stepIdx)) ? [Number(corr.stepIdx)] : [],
|
|
251
|
+
errorSignature: `correction:${shortStableHash(cleanText)}`,
|
|
252
|
+
...inferToolMatchers('run_command', cleanText),
|
|
253
|
+
denyPattern: extractDenyPattern('', cleanText)
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// 4. Resolved 3+ Turn Thrash Loops -> Rules (if not already captured above)
|
|
258
|
+
for (const loop of digest.thrashLoops || []) {
|
|
259
|
+
const target = String(loop.target || '').replace(/\\/g, '/');
|
|
260
|
+
const { globs, paths } = buildGlobPatterns(target.includes('.') || target.includes('/') ? target : '');
|
|
261
|
+
const slug = toKebabSlug(`stop-thrash-${target || loop.resolvedTool || 'loop'}-${shortStableHash(String(loop.startStepIdx))}`);
|
|
262
|
+
if (seenSlugs.has(slug)) continue;
|
|
263
|
+
pushHeuristic({
|
|
264
|
+
carrier: globs ? 'rule_glob' : 'rule_model_decision',
|
|
265
|
+
slug,
|
|
266
|
+
when_condition: `After ${loop.failureCount || 3}+ consecutive failures on \`${target || loop.resolvedTool || 'target'}\``,
|
|
267
|
+
description: `breaking repeated edit-test failure loops on ${target || 'the current task'}`,
|
|
268
|
+
globs,
|
|
269
|
+
paths,
|
|
270
|
+
then_guidance: `Stop retrying the same change on \`${target || 'target'}\`; read diagnostics first and switch to the verified approach (\`${loop.resolvedTool || 'verification'}\`).`,
|
|
271
|
+
steps: [],
|
|
272
|
+
evidence_step_ids: [loop.startStepIdx, loop.resolvedStepIdx].filter((n) => Number.isFinite(Number(n))),
|
|
273
|
+
errorSignature: `thrash:${target || loop.resolvedTool}`.toLowerCase(),
|
|
274
|
+
...inferToolMatchers(loop.resolvedTool, ''),
|
|
275
|
+
denyPattern: ''
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
return {
|
|
280
|
+
is_valid_learning: heuristics.length > 0,
|
|
281
|
+
mode: 'local',
|
|
282
|
+
heuristics
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function normalizeSdkReport(parsed) {
|
|
287
|
+
if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.heuristics)) {
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
const allowedCarriers = new Set(['rule_glob', 'rule_model_decision', 'skill_workflow', 'pre_tool_hook']);
|
|
291
|
+
const heuristics = parsed.heuristics
|
|
292
|
+
.filter((h) => h && typeof h === 'object' && allowedCarriers.has(h.carrier))
|
|
293
|
+
.map((h) => ({
|
|
294
|
+
carrier: h.carrier,
|
|
295
|
+
slug: toKebabSlug(h.slug),
|
|
296
|
+
description: buildThirdPersonDescription(h.description || h.when_condition),
|
|
297
|
+
globs: String(h.globs || '').trim(),
|
|
298
|
+
paths: Array.isArray(h.paths)
|
|
299
|
+
? h.paths.map((p) => String(p).trim()).filter(Boolean)
|
|
300
|
+
: String(h.globs || '')
|
|
301
|
+
.split(',')
|
|
302
|
+
.map((p) => p.trim())
|
|
303
|
+
.filter(Boolean),
|
|
304
|
+
when_condition: sanitizeGuidanceText(h.when_condition || ''),
|
|
305
|
+
then_guidance: sanitizeGuidanceText(h.then_guidance || ''),
|
|
306
|
+
steps: Array.isArray(h.steps) ? h.steps.map((s) => sanitizeGuidanceText(s)).filter(Boolean) : [],
|
|
307
|
+
evidence_step_ids: Array.isArray(h.evidence_step_ids) ? h.evidence_step_ids : [],
|
|
308
|
+
errorSignature: String(h.errorSignature || `sdk:${toKebabSlug(h.slug)}`),
|
|
309
|
+
toolMatcher: String(h.toolMatcher || 'run_command|edit_file|write_file'),
|
|
310
|
+
claudeToolMatcher: String(h.claudeToolMatcher || 'Bash|PowerShell|Edit|MultiEdit|Write'),
|
|
311
|
+
denyPattern: String(h.denyPattern || '')
|
|
312
|
+
}))
|
|
313
|
+
.filter((h) => h.slug && h.then_guidance && !XML_LEAK_RE.test(h.then_guidance));
|
|
314
|
+
|
|
315
|
+
return {
|
|
316
|
+
is_valid_learning: Boolean(parsed.is_valid_learning) && heuristics.length > 0,
|
|
317
|
+
mode: 'sdk',
|
|
318
|
+
heuristics
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Distills a contrastive post-mortem digest into structured heuristics.
|
|
324
|
+
* Default `--mode local` runs deterministically in <15ms with 0 LLM tokens.
|
|
325
|
+
* Optional `--mode sdk` executes `scripts/rsl_sdk_distiller.py` (blocked during test mode unless mocked)
|
|
326
|
+
* and automatically falls back to `local` on failure.
|
|
327
|
+
*
|
|
328
|
+
* @param {object} digest
|
|
329
|
+
* @param {object} [options={}]
|
|
330
|
+
*/
|
|
331
|
+
export function distillContrastiveDigest(digest, options = {}) {
|
|
332
|
+
if (!digest || typeof digest !== 'object') {
|
|
333
|
+
return { is_valid_learning: false, mode: 'local', heuristics: [], reason: 'EMPTY_DIGEST' };
|
|
334
|
+
}
|
|
335
|
+
if (digest.tainted || digest.status === 'TAINTED_REWARD_HACK') {
|
|
336
|
+
return { is_valid_learning: false, mode: 'local', heuristics: [], reason: 'TAINTED_REWARD_HACK' };
|
|
337
|
+
}
|
|
338
|
+
if (!digest.triggered) {
|
|
339
|
+
return { is_valid_learning: false, mode: 'local', heuristics: [], reason: 'NO_TRIGGERS' };
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const requestedMode = String(options.mode || 'local').toLowerCase();
|
|
343
|
+
if (requestedMode === 'sdk') {
|
|
344
|
+
if (typeof options.sdkRunner === 'function') {
|
|
345
|
+
try {
|
|
346
|
+
const sdkOut = normalizeSdkReport(options.sdkRunner(digest));
|
|
347
|
+
if (sdkOut) return sdkOut;
|
|
348
|
+
} catch {
|
|
349
|
+
// Fall back cleanly to deterministic local distiller
|
|
350
|
+
}
|
|
351
|
+
} else {
|
|
352
|
+
const inTestMode = process.env.NODE_ENV === 'test' || process.env.CTXTOP_TEST_MODE === '1';
|
|
353
|
+
const digestPath = digest.digestPath && fs.existsSync(digest.digestPath) ? digest.digestPath : null;
|
|
354
|
+
if (!inTestMode && digestPath && fs.existsSync(SDK_SCRIPT_PATH)) {
|
|
355
|
+
try {
|
|
356
|
+
const pythonBin = options.pythonBin || (process.platform === 'win32' ? 'python' : 'python3');
|
|
357
|
+
const stdout = execFileSync(pythonBin, [SDK_SCRIPT_PATH, digestPath], {
|
|
358
|
+
encoding: 'utf8',
|
|
359
|
+
timeout: Number(options.sdkTimeoutMs || 15_000),
|
|
360
|
+
stdio: ['ignore', 'pipe', 'pipe']
|
|
361
|
+
});
|
|
362
|
+
const sdkOut = normalizeSdkReport(JSON.parse(stdout));
|
|
363
|
+
if (sdkOut) return sdkOut;
|
|
364
|
+
} catch {
|
|
365
|
+
// Automatic fallback to zero-token local distiller
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
return distillLocally(digest);
|
|
372
|
+
}
|