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.
- package/.antigravity-plugin/plugin.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/CHECKSUMS.sha256 +59 -42
- package/README.md +351 -330
- package/bin/ah-statusline.mjs +30 -0
- package/bin/ctxtop.mjs +330 -5
- package/config/default_flightcheck.json +19 -0
- package/config/modelCatalog.json +165 -0
- package/hooks/handlers/compact-lifecycle.mjs +323 -8
- package/hooks/handlers/config-change.mjs +402 -0
- package/hooks/handlers/hookIo.mjs +56 -0
- package/hooks/handlers/post-model-switch.mjs +111 -0
- package/hooks/handlers/post-tool-use.mjs +117 -16
- package/hooks/handlers/pre-model-switch.mjs +823 -24
- package/hooks/handlers/pre-tool-use.mjs +271 -4
- package/hooks/handlers/stop-gate.mjs +297 -11
- package/hooks/handlers/user-prompt-submit.mjs +224 -0
- package/hooks/hooks.json +50 -0
- package/hooks/post_tool_use.mjs +8 -0
- package/hooks/register.js +48 -9
- package/hooks/session_start.mjs +11 -1
- package/hooks/stop.mjs +11 -1
- package/package.json +11 -4
- package/packages/antigravity/package.json +1 -1
- package/packages/claude-code/package.json +1 -1
- package/packages/core/package.json +1 -1
- package/packages/engine-node/package.json +1 -1
- package/packages/mcp/package.json +1 -1
- package/packages/mcp/src/server.mjs +1 -1
- package/packages/pro/package.json +1 -1
- package/plugin.json +1 -1
- package/sidecars/horizon-daemon/server.mjs +38 -2
- package/skills/handoff/SKILL.md +8 -0
- package/src/adapters/antigravity/index.mjs +31 -1
- package/src/adapters/claude-code/index.mjs +40 -1
- package/src/cli/horizon_hud.mjs +254 -52
- package/src/config/modelCatalog.json +84 -0
- package/src/core/bucket_b_runtime.mjs +1200 -0
- package/src/core/constants.mjs +191 -4
- package/src/core/detectors_det01_to_16.mjs +54 -5
- package/src/core/doc_indexer.mjs +338 -0
- package/src/core/layer5_hygiene.mjs +118 -0
- package/src/core/parser.mjs +2 -1
- package/src/core/paths.mjs +3 -2
- 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/session_auditor.mjs +658 -0
- package/src/core/shield_manager.mjs +1417 -0
- package/src/core/task_quota_router.mjs +1 -1
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +874 -47
- package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +13 -6
- package/src/core-isomorphic/config/anthropicModelCatalog.json +404 -1
- package/src/core-isomorphic/config/catalogLoader.mjs +546 -46
- package/src/core-isomorphic/config/horizonConfig.mjs +47 -1
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +266 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +18 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +98 -12
- package/src/core-isomorphic/economics/driftLatency.mjs +114 -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 +191 -191
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +154 -5
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +103 -11
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +311 -1
- package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +16 -0
- package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/src/core-isomorphic/index.js +1 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +36 -12
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +293 -237
- package/src/core-isomorphic/ui/modViews.mjs +35 -9
- package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
- package/src/diagnostics/doctorEngine.mjs +95 -3
- package/src/engine-node/db/probe.mjs +234 -2
- package/src/engine-node/index.mjs +3 -0
- package/src/engine-node/sensors/blindspots.mjs +13 -6
- package/src/hooks/antigravity_rsl_hook.mjs +250 -0
- package/src/hooks/claude_rsl_hook.mjs +288 -0
- package/src/hooks/post_invocation.mjs +196 -4
- package/src/hooks/pre_invocation.mjs +732 -22
- package/src/hooks/session_start.mjs +39 -1
- package/src/utils/modelSwitchTelemetry.mjs +308 -0
- package/src/utils/sessionCalibration.mjs +657 -0
- package/src/webview/horizon_panel.html +1325 -317
|
@@ -0,0 +1,969 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core/rsl_ledger.mjs
|
|
3
|
+
* Stage 3 Dual-Platform ExpeL Importance Ledger & Simultaneous Carrier Compiler.
|
|
4
|
+
*
|
|
5
|
+
* Compiles validated heuristics simultaneously into:
|
|
6
|
+
* - Carrier A: `.agents/rules/rsl-<slug>.md` AND `.claude/rules/rsl-<slug>.md`
|
|
7
|
+
* - Carrier B: `.agents/skills/rsl-<slug>/SKILL.md` AND `.claude/skills/rsl-<slug>/SKILL.md`
|
|
8
|
+
* - Carrier C: `.agents/hooks.json` (`PreToolUse`) AND `.claude/settings.json` (`PreToolUse`)
|
|
9
|
+
*
|
|
10
|
+
* Governs lifecycle weights (`importance: 2` init, `+1` clean reuse, `-1` repeat violation,
|
|
11
|
+
* `<= 0` dual-platform deletion, `>= 5` or `>= 2` repeat violations -> deterministic hook promotion).
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import os from 'node:os';
|
|
17
|
+
import { fileURLToPath } from 'node:url';
|
|
18
|
+
import { atomicWriteFileSync } from './atomic_io.mjs';
|
|
19
|
+
import { RSL_CONSTANTS } from './constants.mjs';
|
|
20
|
+
import { auditClaudeAutoMemory } from './shield_manager.mjs';
|
|
21
|
+
import { toKebabSlug } from './rsl_distiller.mjs';
|
|
22
|
+
import {
|
|
23
|
+
extractRuleDirectives,
|
|
24
|
+
doRuleScopesOverlap,
|
|
25
|
+
detectRuleClashes,
|
|
26
|
+
auditWorkspaceRuleClashes,
|
|
27
|
+
buildConsolidatedSpecMarkdown
|
|
28
|
+
} from './rsl_clash_auditor.mjs';
|
|
29
|
+
|
|
30
|
+
export {
|
|
31
|
+
extractRuleDirectives,
|
|
32
|
+
doRuleScopesOverlap,
|
|
33
|
+
detectRuleClashes,
|
|
34
|
+
auditWorkspaceRuleClashes,
|
|
35
|
+
buildConsolidatedSpecMarkdown
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
39
|
+
export const RSL_PKG_ROOT = path.resolve(__dirname, '..', '..').replace(/\\/g, '/');
|
|
40
|
+
|
|
41
|
+
const ANTIGRAVITY_RSL_HOOK_RE = /src[\\/]hooks[\\/]antigravity_rsl_hook\.mjs/i;
|
|
42
|
+
const CLAUDE_RSL_HOOK_RE = /src[\\/]hooks[\\/]claude_rsl_hook\.mjs/i;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Resolves `<workspaceRoot>/.agents/telemetry/rsl_ledger.json`.
|
|
46
|
+
* @param {string} workspaceRoot
|
|
47
|
+
* @returns {string}
|
|
48
|
+
*/
|
|
49
|
+
export function getRslLedgerPath(workspaceRoot = process.cwd()) {
|
|
50
|
+
return path.join(path.resolve(workspaceRoot), '.agents', 'telemetry', 'rsl_ledger.json');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function createEmptyLedger() {
|
|
54
|
+
return {
|
|
55
|
+
schemaVersion: '2026.11.1',
|
|
56
|
+
updatedAt: new Date().toISOString(),
|
|
57
|
+
stats: {
|
|
58
|
+
taintedSessions: 0,
|
|
59
|
+
prunedCount: 0,
|
|
60
|
+
lastSessionId: null,
|
|
61
|
+
lastPlatform: null
|
|
62
|
+
},
|
|
63
|
+
items: {}
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Reads `.agents/telemetry/rsl_ledger.json` safely.
|
|
69
|
+
* @param {string} [workspaceRoot=process.cwd()]
|
|
70
|
+
* @returns {object}
|
|
71
|
+
*/
|
|
72
|
+
export function readRslLedger(workspaceRoot = process.cwd()) {
|
|
73
|
+
const ledgerPath = getRslLedgerPath(workspaceRoot);
|
|
74
|
+
if (!fs.existsSync(ledgerPath)) {
|
|
75
|
+
return createEmptyLedger();
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
const parsed = JSON.parse(fs.readFileSync(ledgerPath, 'utf8'));
|
|
79
|
+
if (!parsed || typeof parsed !== 'object') return createEmptyLedger();
|
|
80
|
+
return {
|
|
81
|
+
schemaVersion: parsed.schemaVersion || '2026.11.1',
|
|
82
|
+
updatedAt: parsed.updatedAt || new Date().toISOString(),
|
|
83
|
+
stats: {
|
|
84
|
+
taintedSessions: Number(parsed.stats?.taintedSessions || 0),
|
|
85
|
+
prunedCount: Number(parsed.stats?.prunedCount || 0),
|
|
86
|
+
lastSessionId: parsed.stats?.lastSessionId || null,
|
|
87
|
+
lastPlatform: parsed.stats?.lastPlatform || null
|
|
88
|
+
},
|
|
89
|
+
items: parsed.items && typeof parsed.items === 'object' ? parsed.items : {}
|
|
90
|
+
};
|
|
91
|
+
} catch {
|
|
92
|
+
return createEmptyLedger();
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Atomically persists `.agents/telemetry/rsl_ledger.json`.
|
|
98
|
+
* @param {string} workspaceRoot
|
|
99
|
+
* @param {object} ledger
|
|
100
|
+
*/
|
|
101
|
+
export function writeRslLedger(workspaceRoot, ledger) {
|
|
102
|
+
const ledgerPath = getRslLedgerPath(workspaceRoot);
|
|
103
|
+
fs.mkdirSync(path.dirname(ledgerPath), { recursive: true });
|
|
104
|
+
const payload = {
|
|
105
|
+
...ledger,
|
|
106
|
+
updatedAt: new Date().toISOString()
|
|
107
|
+
};
|
|
108
|
+
atomicWriteFileSync(ledgerPath, `${JSON.stringify(payload, null, 2)}\n`);
|
|
109
|
+
return ledgerPath;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Rewrites Antigravity `@[label](path)` inline includes into canonical `@path` pointers
|
|
114
|
+
* so target files are not expanded prior to the 24,000-byte truncation check.
|
|
115
|
+
* Also strips Claude-only `$ARGUMENTS` syntax.
|
|
116
|
+
*
|
|
117
|
+
* @param {string} text
|
|
118
|
+
* @returns {string}
|
|
119
|
+
*/
|
|
120
|
+
export function rewriteAntigravityReferences(text = '') {
|
|
121
|
+
return String(text || '')
|
|
122
|
+
.replace(/@\[[^\]]*\]\(([^)\s]+)\)/g, (_, target) => `@${target.replace(/\\/g, '/')}`)
|
|
123
|
+
.replace(/\$ARGUMENTS\b/gi, '')
|
|
124
|
+
.trim();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Rewrites Antigravity `@[label](path)` and bare `@path/file` tokens into backtick-wrapped paths
|
|
129
|
+
* for Claude Code `.claude/rules/` (preventing eager `@path` file imports).
|
|
130
|
+
*
|
|
131
|
+
* @param {string} text
|
|
132
|
+
* @returns {string}
|
|
133
|
+
*/
|
|
134
|
+
export function rewriteClaudeReferences(text = '') {
|
|
135
|
+
return String(text || '')
|
|
136
|
+
.replace(/@\[[^\]]*\]\(([^)\s]+)\)/g, (_, target) => `\`${target.replace(/\\/g, '/')}\``)
|
|
137
|
+
.replace(/(^|[^a-zA-Z0-9_`])@([a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)+|\.[a-zA-Z0-9_.-]+|[a-zA-Z0-9_.-]+\.[a-z]{1,6})/g, '$1`$2`')
|
|
138
|
+
.trim();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Enforces strict Agent Skills third-person description hygiene without `"You are"`,
|
|
143
|
+
* `"PROACTIVELY"`, or `$ARGUMENTS`.
|
|
144
|
+
*
|
|
145
|
+
* @param {string} desc
|
|
146
|
+
* @param {string} slug
|
|
147
|
+
* @returns {string}
|
|
148
|
+
*/
|
|
149
|
+
export function sanitizeSkillDescription(desc = '', slug = 'workflow') {
|
|
150
|
+
let clean = String(desc || '')
|
|
151
|
+
.replace(/\bYou are\b[^.]*\.?/gi, '')
|
|
152
|
+
.replace(/\bPROACTIVELY\b/gi, '')
|
|
153
|
+
.replace(/\$ARGUMENTS\b/gi, '')
|
|
154
|
+
.replace(/\s+/g, ' ')
|
|
155
|
+
.trim();
|
|
156
|
+
if (!/\bUse when\b/i.test(clean)) {
|
|
157
|
+
clean = `Use when executing the ${slug} workflow${clean ? `: ${clean}` : ''}.`;
|
|
158
|
+
}
|
|
159
|
+
if (!/\bDo not use\b/i.test(clean)) {
|
|
160
|
+
clean = `${clean.replace(/\.+$/, '')}. Do not use for unrelated tasks.`;
|
|
161
|
+
}
|
|
162
|
+
return clean;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function truncateToUtf8ByteCap(text, maxBytes = RSL_CONSTANTS.MAX_RULE_FILE_BYTES) {
|
|
166
|
+
if (Buffer.byteLength(text, 'utf8') <= maxBytes) return text;
|
|
167
|
+
const lines = text.split('\n');
|
|
168
|
+
const out = [];
|
|
169
|
+
let currentBytes = 0;
|
|
170
|
+
const suffix = '\n<!-- truncated by Highbeam RSL 24KB budget -->\n';
|
|
171
|
+
const limit = maxBytes - Buffer.byteLength(suffix, 'utf8');
|
|
172
|
+
for (const line of lines) {
|
|
173
|
+
const lineBytes = Buffer.byteLength(`${line}\n`, 'utf8');
|
|
174
|
+
if (currentBytes + lineBytes > limit) break;
|
|
175
|
+
out.push(line);
|
|
176
|
+
currentBytes += lineBytes;
|
|
177
|
+
}
|
|
178
|
+
return `${out.join('\n')}${suffix}`;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Estimates aggregate rule tokens across `AGENTS.md`, `GEMINI.md`, and `.agents/rules/*.md`.
|
|
183
|
+
* @param {string} workspaceRoot
|
|
184
|
+
* @returns {{ totalBytes: number, totalTokens: number, budgetTokens: number, pct: number, files: Array<object> }}
|
|
185
|
+
*/
|
|
186
|
+
export function measureWorkspaceRuleBudget(workspaceRoot = process.cwd()) {
|
|
187
|
+
const baseRoot = path.resolve(workspaceRoot);
|
|
188
|
+
const files = [];
|
|
189
|
+
let totalBytes = 0;
|
|
190
|
+
|
|
191
|
+
for (const topFile of ['AGENTS.md', 'GEMINI.md']) {
|
|
192
|
+
const abs = path.join(baseRoot, topFile);
|
|
193
|
+
if (fs.existsSync(abs)) {
|
|
194
|
+
try {
|
|
195
|
+
const bytes = fs.statSync(abs).size;
|
|
196
|
+
totalBytes += bytes;
|
|
197
|
+
files.push({ path: topFile, bytes, tokens: Math.ceil(bytes / 4) });
|
|
198
|
+
} catch {
|
|
199
|
+
// Ignore
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const agRulesDir = path.join(baseRoot, '.agents', 'rules');
|
|
205
|
+
if (fs.existsSync(agRulesDir)) {
|
|
206
|
+
try {
|
|
207
|
+
for (const ent of fs.readdirSync(agRulesDir, { withFileTypes: true })) {
|
|
208
|
+
if (!ent.isFile() || !ent.name.endsWith('.md')) continue;
|
|
209
|
+
const abs = path.join(agRulesDir, ent.name);
|
|
210
|
+
const bytes = fs.statSync(abs).size;
|
|
211
|
+
totalBytes += bytes;
|
|
212
|
+
files.push({
|
|
213
|
+
path: `.agents/rules/${ent.name}`,
|
|
214
|
+
bytes,
|
|
215
|
+
tokens: Math.ceil(bytes / 4)
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
} catch {
|
|
219
|
+
// Ignore
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const totalTokens = Math.ceil(totalBytes / 4);
|
|
224
|
+
const budgetTokens = RSL_CONSTANTS.AGGREGATE_RULE_TOKEN_BUDGET;
|
|
225
|
+
return {
|
|
226
|
+
totalBytes,
|
|
227
|
+
totalTokens,
|
|
228
|
+
budgetTokens,
|
|
229
|
+
pct: Math.min(100, Math.round((totalTokens / budgetTokens) * 100)),
|
|
230
|
+
files
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function buildAntigravityRuleMarkdown(item) {
|
|
235
|
+
const globs = String(item.globs || '').trim();
|
|
236
|
+
const trigger = globs ? 'glob' : 'model_decision';
|
|
237
|
+
const desc = rewriteAntigravityReferences(item.description || item.when_condition || item.slug).replace(/"/g, '\\"');
|
|
238
|
+
const whenTxt = rewriteAntigravityReferences(item.when_condition || '');
|
|
239
|
+
const guideTxt = rewriteAntigravityReferences(item.then_guidance || '');
|
|
240
|
+
|
|
241
|
+
const fmLines = [
|
|
242
|
+
'---',
|
|
243
|
+
`trigger: ${trigger}`
|
|
244
|
+
];
|
|
245
|
+
if (trigger === 'glob') {
|
|
246
|
+
fmLines.push(`globs: "${globs.replace(/"/g, '')}"`);
|
|
247
|
+
}
|
|
248
|
+
fmLines.push(`description: "${desc}"`);
|
|
249
|
+
fmLines.push('---');
|
|
250
|
+
|
|
251
|
+
const body = [
|
|
252
|
+
...fmLines,
|
|
253
|
+
'',
|
|
254
|
+
`# RSL Learned Heuristic: ${item.slug}`,
|
|
255
|
+
'',
|
|
256
|
+
`- **Condition**: ${whenTxt}`,
|
|
257
|
+
`- **Guidance**: ${guideTxt}`,
|
|
258
|
+
`- **Importance**: ${item.importance} (${item.sourcePlatform || 'dual'} origin)`,
|
|
259
|
+
''
|
|
260
|
+
].join('\n');
|
|
261
|
+
|
|
262
|
+
return truncateToUtf8ByteCap(body, RSL_CONSTANTS.MAX_RULE_FILE_BYTES - 128);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function buildClaudeRuleMarkdown(item) {
|
|
266
|
+
const paths = Array.isArray(item.paths) && item.paths.length > 0
|
|
267
|
+
? item.paths
|
|
268
|
+
: String(item.globs || '')
|
|
269
|
+
.split(',')
|
|
270
|
+
.map((p) => p.trim())
|
|
271
|
+
.filter(Boolean);
|
|
272
|
+
|
|
273
|
+
const whenTxt = rewriteClaudeReferences(item.when_condition || '');
|
|
274
|
+
const guideTxt = rewriteClaudeReferences(item.then_guidance || '');
|
|
275
|
+
|
|
276
|
+
const fmLines = ['---'];
|
|
277
|
+
if (paths.length > 0) {
|
|
278
|
+
fmLines.push('paths:');
|
|
279
|
+
for (const p of paths) {
|
|
280
|
+
fmLines.push(` - "${p.replace(/"/g, '')}"`);
|
|
281
|
+
}
|
|
282
|
+
} else {
|
|
283
|
+
fmLines.push(`description: "${rewriteClaudeReferences(item.description || item.slug).replace(/"/g, '\\"')}"`);
|
|
284
|
+
}
|
|
285
|
+
fmLines.push('---');
|
|
286
|
+
|
|
287
|
+
return [
|
|
288
|
+
...fmLines,
|
|
289
|
+
'',
|
|
290
|
+
`# RSL Learned Heuristic: ${item.slug}`,
|
|
291
|
+
'',
|
|
292
|
+
`- **Condition**: ${whenTxt}`,
|
|
293
|
+
`- **Guidance**: ${guideTxt}`,
|
|
294
|
+
`- **Importance**: ${item.importance} (${item.sourcePlatform || 'dual'} origin)`,
|
|
295
|
+
''
|
|
296
|
+
].join('\n');
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function buildAntigravitySkillMarkdown(item) {
|
|
300
|
+
const slug = toKebabSlug(item.slug);
|
|
301
|
+
const desc = sanitizeSkillDescription(
|
|
302
|
+
rewriteAntigravityReferences(item.description || item.when_condition),
|
|
303
|
+
slug
|
|
304
|
+
);
|
|
305
|
+
const steps = Array.isArray(item.steps) && item.steps.length > 0
|
|
306
|
+
? item.steps.map((s, idx) => `${idx + 1}. ${rewriteAntigravityReferences(s.replace(/^\d+\.\s*/, ''))}`)
|
|
307
|
+
: [`1. ${rewriteAntigravityReferences(item.then_guidance)}`];
|
|
308
|
+
|
|
309
|
+
return [
|
|
310
|
+
'---',
|
|
311
|
+
`name: rsl-${slug}`,
|
|
312
|
+
`description: "${desc.replace(/"/g, '\\"')}"`,
|
|
313
|
+
'---',
|
|
314
|
+
'',
|
|
315
|
+
`# RSL Workflow: ${slug}`,
|
|
316
|
+
'',
|
|
317
|
+
'## When to Apply',
|
|
318
|
+
rewriteAntigravityReferences(item.when_condition || desc),
|
|
319
|
+
'',
|
|
320
|
+
'## Verified Steps',
|
|
321
|
+
...steps,
|
|
322
|
+
'',
|
|
323
|
+
'## Validation',
|
|
324
|
+
'Verify the targeted command or test suite passes with zero skipped assertions.',
|
|
325
|
+
''
|
|
326
|
+
].join('\n');
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function buildClaudeSkillMarkdown(item) {
|
|
330
|
+
const slug = toKebabSlug(item.slug);
|
|
331
|
+
const desc = sanitizeSkillDescription(
|
|
332
|
+
rewriteClaudeReferences(item.description || item.when_condition),
|
|
333
|
+
slug
|
|
334
|
+
);
|
|
335
|
+
const steps = Array.isArray(item.steps) && item.steps.length > 0
|
|
336
|
+
? item.steps.map((s, idx) => `${idx + 1}. ${rewriteClaudeReferences(s.replace(/^\d+\.\s*/, ''))}`)
|
|
337
|
+
: [`1. ${rewriteClaudeReferences(item.then_guidance)}`];
|
|
338
|
+
|
|
339
|
+
return [
|
|
340
|
+
'---',
|
|
341
|
+
`name: rsl-${slug}`,
|
|
342
|
+
`description: "${desc.replace(/"/g, '\\"')}"`,
|
|
343
|
+
'argument-hint: "[target]"',
|
|
344
|
+
'allowed-tools: Read Bash',
|
|
345
|
+
'---',
|
|
346
|
+
'',
|
|
347
|
+
`# RSL Workflow: ${slug}`,
|
|
348
|
+
'',
|
|
349
|
+
'## When to Apply',
|
|
350
|
+
rewriteClaudeReferences(item.when_condition || desc),
|
|
351
|
+
'',
|
|
352
|
+
'## Verified Steps',
|
|
353
|
+
...steps,
|
|
354
|
+
'',
|
|
355
|
+
'## Validation',
|
|
356
|
+
'Verify the targeted command or test suite passes cleanly.',
|
|
357
|
+
''
|
|
358
|
+
].join('\n');
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function removeDualCarrierFiles(workspaceRoot, slug) {
|
|
362
|
+
const safeSlug = toKebabSlug(slug);
|
|
363
|
+
const targets = [
|
|
364
|
+
path.join(workspaceRoot, '.agents', 'rules', `rsl-${safeSlug}.md`),
|
|
365
|
+
path.join(workspaceRoot, '.claude', 'rules', `rsl-${safeSlug}.md`)
|
|
366
|
+
];
|
|
367
|
+
for (const file of targets) {
|
|
368
|
+
try {
|
|
369
|
+
if (fs.existsSync(file)) fs.rmSync(file, { force: true });
|
|
370
|
+
} catch {
|
|
371
|
+
// Non-fatal
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
const skillDirs = [
|
|
375
|
+
path.join(workspaceRoot, '.agents', 'skills', `rsl-${safeSlug}`),
|
|
376
|
+
path.join(workspaceRoot, '.claude', 'skills', `rsl-${safeSlug}`)
|
|
377
|
+
];
|
|
378
|
+
for (const dir of skillDirs) {
|
|
379
|
+
try {
|
|
380
|
+
if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true, force: true });
|
|
381
|
+
} catch {
|
|
382
|
+
// Non-fatal
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Synchronizes promoted Carrier C (`PreToolUse`) deterministic deny guards into
|
|
389
|
+
* both `<workspaceRoot>/.agents/hooks.json` and `<workspaceRoot>/.claude/settings.json`
|
|
390
|
+
* (never setting `disableAllHooks: true`).
|
|
391
|
+
*
|
|
392
|
+
* @param {string} workspaceRoot
|
|
393
|
+
* @param {object} ledger
|
|
394
|
+
* @param {object} [options={}]
|
|
395
|
+
*/
|
|
396
|
+
export function syncPromotedDualHooks(workspaceRoot, ledger, options = {}) {
|
|
397
|
+
const baseRoot = path.resolve(workspaceRoot);
|
|
398
|
+
const pkgRoot = String(options.pkgRoot || RSL_PKG_ROOT).replace(/\\/g, '/').replace(/\/+$/, '');
|
|
399
|
+
const promoted = Object.values(ledger?.items || {}).filter(
|
|
400
|
+
(it) =>
|
|
401
|
+
it &&
|
|
402
|
+
it.status === 'active' &&
|
|
403
|
+
(it.promotedHook === true ||
|
|
404
|
+
it.carrier === 'pre_tool_hook' ||
|
|
405
|
+
Number(it.importance || 0) >= RSL_CONSTANTS.PROMOTE_HOOK_IMPORTANCE ||
|
|
406
|
+
Number(it.violationCount || 0) >= RSL_CONSTANTS.REPEAT_VIOLATION_THRESHOLD)
|
|
407
|
+
);
|
|
408
|
+
|
|
409
|
+
// 1. Antigravity `.agents/hooks.json`
|
|
410
|
+
const agHooksPath = path.join(baseRoot, '.agents', 'hooks.json');
|
|
411
|
+
let agDoc = {};
|
|
412
|
+
if (fs.existsSync(agHooksPath)) {
|
|
413
|
+
try {
|
|
414
|
+
const parsed = JSON.parse(fs.readFileSync(agHooksPath, 'utf8'));
|
|
415
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
416
|
+
agDoc = { ...parsed };
|
|
417
|
+
}
|
|
418
|
+
} catch {
|
|
419
|
+
agDoc = {};
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
if (promoted.length > 0) {
|
|
424
|
+
const agMatchers = Array.from(
|
|
425
|
+
new Set(
|
|
426
|
+
promoted
|
|
427
|
+
.flatMap((it) => String(it.toolMatcher || 'run_command|edit_file|write_file').split('|'))
|
|
428
|
+
.map((s) => s.trim())
|
|
429
|
+
.filter(Boolean)
|
|
430
|
+
)
|
|
431
|
+
);
|
|
432
|
+
agDoc['ctxtop-rsl-guards'] = {
|
|
433
|
+
enabled: true,
|
|
434
|
+
PreToolUse: [
|
|
435
|
+
{
|
|
436
|
+
matcher: agMatchers.join('|') || '*',
|
|
437
|
+
hooks: [
|
|
438
|
+
{
|
|
439
|
+
type: 'command',
|
|
440
|
+
command: `node "${pkgRoot}/src/hooks/antigravity_rsl_hook.mjs" --event=PreToolUse`,
|
|
441
|
+
timeout: 5
|
|
442
|
+
}
|
|
443
|
+
]
|
|
444
|
+
}
|
|
445
|
+
]
|
|
446
|
+
};
|
|
447
|
+
fs.mkdirSync(path.dirname(agHooksPath), { recursive: true });
|
|
448
|
+
atomicWriteFileSync(agHooksPath, `${JSON.stringify(agDoc, null, 2)}\n`);
|
|
449
|
+
} else if ('ctxtop-rsl-guards' in agDoc) {
|
|
450
|
+
delete agDoc['ctxtop-rsl-guards'];
|
|
451
|
+
if (fs.existsSync(agHooksPath)) {
|
|
452
|
+
atomicWriteFileSync(agHooksPath, `${JSON.stringify(agDoc, null, 2)}\n`);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// 2. Claude Code `.claude/settings.json` (never sets disableAllHooks: true)
|
|
457
|
+
const ccSettingsPath = path.join(baseRoot, '.claude', 'settings.json');
|
|
458
|
+
let ccDoc = {};
|
|
459
|
+
if (fs.existsSync(ccSettingsPath)) {
|
|
460
|
+
try {
|
|
461
|
+
const parsed = JSON.parse(fs.readFileSync(ccSettingsPath, 'utf8'));
|
|
462
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
463
|
+
ccDoc = { ...parsed };
|
|
464
|
+
}
|
|
465
|
+
} catch {
|
|
466
|
+
ccDoc = {};
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
if (promoted.length > 0) {
|
|
471
|
+
const ccMatchers = Array.from(
|
|
472
|
+
new Set(
|
|
473
|
+
promoted
|
|
474
|
+
.flatMap((it) => String(it.claudeToolMatcher || 'Bash|PowerShell|Edit|MultiEdit|Write').split('|'))
|
|
475
|
+
.map((s) => s.trim())
|
|
476
|
+
.filter(Boolean)
|
|
477
|
+
)
|
|
478
|
+
);
|
|
479
|
+
const prevHooks = ccDoc.hooks && typeof ccDoc.hooks === 'object' && !Array.isArray(ccDoc.hooks)
|
|
480
|
+
? { ...ccDoc.hooks }
|
|
481
|
+
: {};
|
|
482
|
+
const existingPre = Array.isArray(prevHooks.PreToolUse) ? prevHooks.PreToolUse : [];
|
|
483
|
+
const filteredPre = existingPre.filter((entry) => {
|
|
484
|
+
const cmds = [
|
|
485
|
+
entry?.command,
|
|
486
|
+
...(Array.isArray(entry?.hooks) ? entry.hooks.map((h) => h?.command) : [])
|
|
487
|
+
].map((c) => String(c || ''));
|
|
488
|
+
return !cmds.some((c) => CLAUDE_RSL_HOOK_RE.test(c) && c.includes('--event=PreToolUse'));
|
|
489
|
+
});
|
|
490
|
+
|
|
491
|
+
filteredPre.push({
|
|
492
|
+
matcher: ccMatchers.join('|') || 'Bash|PowerShell|Edit|MultiEdit|Write',
|
|
493
|
+
hooks: [
|
|
494
|
+
{
|
|
495
|
+
type: 'command',
|
|
496
|
+
command: `node "${pkgRoot}/src/hooks/claude_rsl_hook.mjs" --event=PreToolUse`
|
|
497
|
+
}
|
|
498
|
+
]
|
|
499
|
+
});
|
|
500
|
+
|
|
501
|
+
ccDoc.hooks = {
|
|
502
|
+
...prevHooks,
|
|
503
|
+
PreToolUse: filteredPre
|
|
504
|
+
};
|
|
505
|
+
if (ccDoc.disableAllHooks === true) {
|
|
506
|
+
delete ccDoc.disableAllHooks;
|
|
507
|
+
}
|
|
508
|
+
fs.mkdirSync(path.dirname(ccSettingsPath), { recursive: true });
|
|
509
|
+
atomicWriteFileSync(ccSettingsPath, `${JSON.stringify(ccDoc, null, 2)}\n`);
|
|
510
|
+
} else if (ccDoc.hooks && Array.isArray(ccDoc.hooks.PreToolUse)) {
|
|
511
|
+
const filteredPre = ccDoc.hooks.PreToolUse.filter((entry) => {
|
|
512
|
+
const cmds = [
|
|
513
|
+
entry?.command,
|
|
514
|
+
...(Array.isArray(entry?.hooks) ? entry.hooks.map((h) => h?.command) : [])
|
|
515
|
+
].map((c) => String(c || ''));
|
|
516
|
+
return !cmds.some((c) => CLAUDE_RSL_HOOK_RE.test(c) && c.includes('--event=PreToolUse'));
|
|
517
|
+
});
|
|
518
|
+
if (filteredPre.length !== ccDoc.hooks.PreToolUse.length) {
|
|
519
|
+
if (filteredPre.length > 0) ccDoc.hooks.PreToolUse = filteredPre;
|
|
520
|
+
else delete ccDoc.hooks.PreToolUse;
|
|
521
|
+
atomicWriteFileSync(ccSettingsPath, `${JSON.stringify(ccDoc, null, 2)}\n`);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
return {
|
|
526
|
+
promotedCount: promoted.length,
|
|
527
|
+
agHooksPath,
|
|
528
|
+
ccSettingsPath
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/**
|
|
533
|
+
* Compiles a single active heuristic simultaneously into `.agents/` and `.claude/`.
|
|
534
|
+
*
|
|
535
|
+
* @param {string} workspaceRoot
|
|
536
|
+
* @param {object} item
|
|
537
|
+
* @param {object} [options={}]
|
|
538
|
+
*/
|
|
539
|
+
export function compileHeuristicDualTargets(workspaceRoot, item, options = {}) {
|
|
540
|
+
const baseRoot = path.resolve(workspaceRoot);
|
|
541
|
+
const slug = toKebabSlug(item.slug);
|
|
542
|
+
const written = [];
|
|
543
|
+
|
|
544
|
+
if (item.carrier === 'skill_workflow') {
|
|
545
|
+
const agSkillPath = path.join(baseRoot, '.agents', 'skills', `rsl-${slug}`, 'SKILL.md');
|
|
546
|
+
const ccSkillPath = path.join(baseRoot, '.claude', 'skills', `rsl-${slug}`, 'SKILL.md');
|
|
547
|
+
fs.mkdirSync(path.dirname(agSkillPath), { recursive: true });
|
|
548
|
+
fs.mkdirSync(path.dirname(ccSkillPath), { recursive: true });
|
|
549
|
+
atomicWriteFileSync(agSkillPath, buildAntigravitySkillMarkdown(item));
|
|
550
|
+
atomicWriteFileSync(ccSkillPath, buildClaudeSkillMarkdown(item));
|
|
551
|
+
written.push(agSkillPath, ccSkillPath);
|
|
552
|
+
} else {
|
|
553
|
+
const agRuleContent = buildAntigravityRuleMarkdown(item);
|
|
554
|
+
const ccRuleContent = buildClaudeRuleMarkdown(item);
|
|
555
|
+
const agRulePath = path.join(baseRoot, '.agents', 'rules', `rsl-${slug}.md`);
|
|
556
|
+
const ccRulePath = path.join(baseRoot, '.claude', 'rules', `rsl-${slug}.md`);
|
|
557
|
+
|
|
558
|
+
const budget = measureWorkspaceRuleBudget(baseRoot);
|
|
559
|
+
const existingBytes = fs.existsSync(agRulePath) ? fs.statSync(agRulePath).size : 0;
|
|
560
|
+
const projectedTokens = budget.totalTokens - Math.ceil(existingBytes / 4) + Math.ceil(Buffer.byteLength(agRuleContent, 'utf8') / 4);
|
|
561
|
+
|
|
562
|
+
if (projectedTokens <= RSL_CONSTANTS.AGGREGATE_RULE_TOKEN_BUDGET || options.force === true) {
|
|
563
|
+
fs.mkdirSync(path.dirname(agRulePath), { recursive: true });
|
|
564
|
+
fs.mkdirSync(path.dirname(ccRulePath), { recursive: true });
|
|
565
|
+
atomicWriteFileSync(agRulePath, agRuleContent);
|
|
566
|
+
atomicWriteFileSync(ccRulePath, ccRuleContent);
|
|
567
|
+
written.push(agRulePath, ccRulePath);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
return { slug, written };
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
function globMatchesFile(globPattern = '', filePath = '') {
|
|
575
|
+
const posixFile = String(filePath || '').replace(/\\/g, '/').toLowerCase();
|
|
576
|
+
if (!posixFile) return false;
|
|
577
|
+
const parts = String(globPattern || '')
|
|
578
|
+
.split(',')
|
|
579
|
+
.map((p) => p.trim().toLowerCase())
|
|
580
|
+
.filter(Boolean);
|
|
581
|
+
for (const pat of parts) {
|
|
582
|
+
if (pat.startsWith('*.') && posixFile.endsWith(pat.slice(1))) return true;
|
|
583
|
+
if (pat.endsWith('/**') && posixFile.startsWith(pat.slice(0, -3))) return true;
|
|
584
|
+
if (posixFile === pat || posixFile.endsWith(`/${pat}`)) return true;
|
|
585
|
+
}
|
|
586
|
+
return false;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* Applies ExpeL `+1` clean reuse / `-1` repeat error feedback to existing active heuristics,
|
|
591
|
+
* ingests newly distilled heuristics at `importance: 2`, prunes `<= 0` items from both
|
|
592
|
+
* `.agents/` and `.claude/`, and promotes `>= 5` (or `>= 2` repeat violations) to hooks.
|
|
593
|
+
*
|
|
594
|
+
* @param {string} workspaceRoot
|
|
595
|
+
* @param {object} distilledReport
|
|
596
|
+
* @param {object} [sessionContext={}]
|
|
597
|
+
* @param {object} [options={}]
|
|
598
|
+
*/
|
|
599
|
+
export function ingestDistilledHeuristics(workspaceRoot, distilledReport = {}, sessionContext = {}, options = {}) {
|
|
600
|
+
const baseRoot = path.resolve(workspaceRoot || process.cwd());
|
|
601
|
+
const ledger = readRslLedger(baseRoot);
|
|
602
|
+
ledger.stats.lastSessionId = sessionContext.sessionId || ledger.stats.lastSessionId;
|
|
603
|
+
ledger.stats.lastPlatform = sessionContext.platform || ledger.stats.lastPlatform;
|
|
604
|
+
|
|
605
|
+
if (sessionContext.tainted || sessionContext.status === 'TAINTED_REWARD_HACK') {
|
|
606
|
+
ledger.stats.taintedSessions += 1;
|
|
607
|
+
writeRslLedger(baseRoot, ledger);
|
|
608
|
+
return {
|
|
609
|
+
ok: false,
|
|
610
|
+
tainted: true,
|
|
611
|
+
upvoted: [],
|
|
612
|
+
downvoted: [],
|
|
613
|
+
pruned: [],
|
|
614
|
+
promoted: [],
|
|
615
|
+
added: [],
|
|
616
|
+
quarantined: []
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
const upvoted = [];
|
|
621
|
+
const downvoted = [];
|
|
622
|
+
const pruned = [];
|
|
623
|
+
const promoted = [];
|
|
624
|
+
const added = [];
|
|
625
|
+
const quarantined = [];
|
|
626
|
+
|
|
627
|
+
const touchedFiles = Array.isArray(sessionContext.touchedFiles) ? sessionContext.touchedFiles : [];
|
|
628
|
+
const unresolvedErrors = Array.isArray(sessionContext.unresolvedErrors) ? sessionContext.unresolvedErrors : [];
|
|
629
|
+
const pairs = Array.isArray(sessionContext.contrastivePairs) ? sessionContext.contrastivePairs : [];
|
|
630
|
+
const sessionErrorsText = [
|
|
631
|
+
...unresolvedErrors.map((e) => `${e.toolName || ''}:${e.errorText || ''}`),
|
|
632
|
+
...pairs.map((p) => `${p.toolName || ''}:${p.errorText || ''}`)
|
|
633
|
+
]
|
|
634
|
+
.join('\n')
|
|
635
|
+
.toLowerCase();
|
|
636
|
+
|
|
637
|
+
// 1. ExpeL feedback on existing active heuristics
|
|
638
|
+
for (const item of Object.values(ledger.items)) {
|
|
639
|
+
if (!item || item.status !== 'active') continue;
|
|
640
|
+
const sig = String(item.errorSignature || '').toLowerCase();
|
|
641
|
+
const sigErrPart = sig.includes(':') ? sig.split(':').slice(1).join(':').trim() : sig;
|
|
642
|
+
const matchedError = Boolean(sigErrPart && sigErrPart.length >= 6 && sessionErrorsText.includes(sigErrPart.slice(0, 32)));
|
|
643
|
+
|
|
644
|
+
if (matchedError) {
|
|
645
|
+
item.importance = Math.max(0, Number(item.importance || 0) - 1);
|
|
646
|
+
item.violationCount = Number(item.violationCount || 0) + 1;
|
|
647
|
+
item.updatedAt = new Date().toISOString();
|
|
648
|
+
downvoted.push(item.slug);
|
|
649
|
+
if (item.importance <= 0) {
|
|
650
|
+
item.status = 'pruned';
|
|
651
|
+
item.promotedHook = false;
|
|
652
|
+
ledger.stats.prunedCount += 1;
|
|
653
|
+
removeDualCarrierFiles(baseRoot, item.slug);
|
|
654
|
+
pruned.push(item.slug);
|
|
655
|
+
} else {
|
|
656
|
+
if (item.violationCount >= RSL_CONSTANTS.REPEAT_VIOLATION_THRESHOLD) {
|
|
657
|
+
item.promotedHook = true;
|
|
658
|
+
promoted.push(item.slug);
|
|
659
|
+
}
|
|
660
|
+
compileHeuristicDualTargets(baseRoot, item, options);
|
|
661
|
+
}
|
|
662
|
+
continue;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
const touchedMatchingFile = touchedFiles.some((f) => globMatchesFile(item.globs, f));
|
|
666
|
+
if (touchedMatchingFile && sessionContext.terminationReason !== 'ERROR') {
|
|
667
|
+
item.importance = Number(item.importance || RSL_CONSTANTS.INITIAL_IMPORTANCE) + 1;
|
|
668
|
+
item.cleanUses = Number(item.cleanUses || 0) + 1;
|
|
669
|
+
item.updatedAt = new Date().toISOString();
|
|
670
|
+
upvoted.push(item.slug);
|
|
671
|
+
if (item.importance >= RSL_CONSTANTS.PROMOTE_HOOK_IMPORTANCE && !item.promotedHook) {
|
|
672
|
+
item.promotedHook = true;
|
|
673
|
+
promoted.push(item.slug);
|
|
674
|
+
}
|
|
675
|
+
compileHeuristicDualTargets(baseRoot, item, options);
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
// 2. Ingest newly distilled heuristics (initialized at importance: 2)
|
|
680
|
+
const incoming = Array.isArray(distilledReport?.heuristics) ? distilledReport.heuristics : [];
|
|
681
|
+
for (const h of incoming) {
|
|
682
|
+
const slug = toKebabSlug(h.slug);
|
|
683
|
+
if (!slug) continue;
|
|
684
|
+
const existing = ledger.items[slug];
|
|
685
|
+
if (existing && existing.status === 'active') {
|
|
686
|
+
// Do not duplicate; reinforce if same pattern surfaced again cleanly or already handled above
|
|
687
|
+
continue;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
const item = {
|
|
691
|
+
slug,
|
|
692
|
+
carrier: h.carrier || 'rule_model_decision',
|
|
693
|
+
importance: RSL_CONSTANTS.INITIAL_IMPORTANCE,
|
|
694
|
+
status: 'active',
|
|
695
|
+
promotedHook: h.carrier === 'pre_tool_hook',
|
|
696
|
+
violationCount: h.carrier === 'pre_tool_hook' ? RSL_CONSTANTS.REPEAT_VIOLATION_THRESHOLD : 0,
|
|
697
|
+
cleanUses: 0,
|
|
698
|
+
sourcePlatform: sessionContext.platform || 'antigravity',
|
|
699
|
+
description: h.description || '',
|
|
700
|
+
globs: h.globs || '',
|
|
701
|
+
paths: Array.isArray(h.paths) ? h.paths : [],
|
|
702
|
+
when_condition: h.when_condition || '',
|
|
703
|
+
then_guidance: h.then_guidance || '',
|
|
704
|
+
steps: Array.isArray(h.steps) ? h.steps : [],
|
|
705
|
+
errorSignature: h.errorSignature || '',
|
|
706
|
+
toolMatcher: h.toolMatcher || 'run_command|edit_file|write_file',
|
|
707
|
+
claudeToolMatcher: h.claudeToolMatcher || 'Bash|PowerShell|Edit|MultiEdit|Write',
|
|
708
|
+
denyPattern: h.denyPattern || '',
|
|
709
|
+
evidence_step_ids: Array.isArray(h.evidence_step_ids) ? h.evidence_step_ids : [],
|
|
710
|
+
createdAt: new Date().toISOString(),
|
|
711
|
+
updatedAt: new Date().toISOString()
|
|
712
|
+
};
|
|
713
|
+
|
|
714
|
+
const isRuleCandidate = item.carrier !== 'skill_workflow';
|
|
715
|
+
const clashReport = isRuleCandidate
|
|
716
|
+
? auditWorkspaceRuleClashes(baseRoot, item)
|
|
717
|
+
: { candidateClashes: [] };
|
|
718
|
+
if (clashReport.candidateClashes.length > 0 && options.allowClashingRules !== true) {
|
|
719
|
+
item.status = 'quarantined_conflict';
|
|
720
|
+
item.promotedHook = false;
|
|
721
|
+
item.quarantinedConflict = clashReport.candidateClashes[0];
|
|
722
|
+
ledger.items[slug] = item;
|
|
723
|
+
quarantined.push(slug);
|
|
724
|
+
continue;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
ledger.items[slug] = item;
|
|
728
|
+
compileHeuristicDualTargets(baseRoot, item, options);
|
|
729
|
+
added.push(slug);
|
|
730
|
+
if (item.promotedHook) promoted.push(slug);
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
syncPromotedDualHooks(baseRoot, ledger, options);
|
|
734
|
+
writeRslLedger(baseRoot, ledger);
|
|
735
|
+
|
|
736
|
+
return {
|
|
737
|
+
ok: true,
|
|
738
|
+
tainted: false,
|
|
739
|
+
upvoted,
|
|
740
|
+
downvoted,
|
|
741
|
+
pruned,
|
|
742
|
+
promoted: Array.from(new Set(promoted)),
|
|
743
|
+
added,
|
|
744
|
+
quarantined
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/**
|
|
749
|
+
* Promotes a heuristic slug to `importance >= 5` and compiles dual-platform `PreToolUse` hooks.
|
|
750
|
+
* @param {string} workspaceRoot
|
|
751
|
+
* @param {string} slug
|
|
752
|
+
* @param {object} [options={}]
|
|
753
|
+
*/
|
|
754
|
+
export function promoteHeuristic(workspaceRoot, slug, options = {}) {
|
|
755
|
+
const baseRoot = path.resolve(workspaceRoot || process.cwd());
|
|
756
|
+
const safeSlug = toKebabSlug(slug);
|
|
757
|
+
const ledger = readRslLedger(baseRoot);
|
|
758
|
+
const item = ledger.items[safeSlug];
|
|
759
|
+
if (!item) {
|
|
760
|
+
return { ok: false, error: `Heuristic "${safeSlug}" not found in RSL ledger` };
|
|
761
|
+
}
|
|
762
|
+
item.status = 'active';
|
|
763
|
+
item.importance = Math.max(RSL_CONSTANTS.PROMOTE_HOOK_IMPORTANCE, Number(item.importance || 0));
|
|
764
|
+
item.promotedHook = true;
|
|
765
|
+
item.updatedAt = new Date().toISOString();
|
|
766
|
+
compileHeuristicDualTargets(baseRoot, item, options);
|
|
767
|
+
const hooks = syncPromotedDualHooks(baseRoot, ledger, options);
|
|
768
|
+
writeRslLedger(baseRoot, ledger);
|
|
769
|
+
return { ok: true, slug: safeSlug, item, hooks };
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/**
|
|
773
|
+
* Prunes a heuristic slug (`importance = 0`, deletes files from both `.agents/` and `.claude/`).
|
|
774
|
+
* @param {string} workspaceRoot
|
|
775
|
+
* @param {string} slug
|
|
776
|
+
* @param {object} [options={}]
|
|
777
|
+
*/
|
|
778
|
+
export function pruneHeuristic(workspaceRoot, slug, options = {}) {
|
|
779
|
+
const baseRoot = path.resolve(workspaceRoot || process.cwd());
|
|
780
|
+
const safeSlug = toKebabSlug(slug);
|
|
781
|
+
const ledger = readRslLedger(baseRoot);
|
|
782
|
+
const item = ledger.items[safeSlug];
|
|
783
|
+
if (!item) {
|
|
784
|
+
removeDualCarrierFiles(baseRoot, safeSlug);
|
|
785
|
+
return { ok: false, error: `Heuristic "${safeSlug}" not found in RSL ledger` };
|
|
786
|
+
}
|
|
787
|
+
if (item.status !== 'pruned') {
|
|
788
|
+
ledger.stats.prunedCount += 1;
|
|
789
|
+
}
|
|
790
|
+
item.status = 'pruned';
|
|
791
|
+
item.importance = 0;
|
|
792
|
+
item.promotedHook = false;
|
|
793
|
+
item.updatedAt = new Date().toISOString();
|
|
794
|
+
removeDualCarrierFiles(baseRoot, safeSlug);
|
|
795
|
+
const hooks = syncPromotedDualHooks(baseRoot, ledger, options);
|
|
796
|
+
writeRslLedger(baseRoot, ledger);
|
|
797
|
+
return { ok: true, slug: safeSlug, item, hooks };
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
/**
|
|
801
|
+
* Directly adjusts heuristic importance (`+delta` or `-delta`), triggering automatic pruning at `<= 0`
|
|
802
|
+
* or hook promotion at `>= 5` across both Antigravity and Claude Code.
|
|
803
|
+
*/
|
|
804
|
+
export function adjustHeuristicImportance(workspaceRoot, slug, delta = 1, options = {}) {
|
|
805
|
+
const baseRoot = path.resolve(workspaceRoot || process.cwd());
|
|
806
|
+
const safeSlug = toKebabSlug(slug);
|
|
807
|
+
const ledger = readRslLedger(baseRoot);
|
|
808
|
+
const item = ledger.items[safeSlug];
|
|
809
|
+
if (!item) return { ok: false, error: `Heuristic "${safeSlug}" not found` };
|
|
810
|
+
|
|
811
|
+
const next = Number(item.importance || 0) + Number(delta || 0);
|
|
812
|
+
if (next <= 0) {
|
|
813
|
+
return pruneHeuristic(baseRoot, safeSlug, options);
|
|
814
|
+
}
|
|
815
|
+
item.status = 'active';
|
|
816
|
+
item.importance = next;
|
|
817
|
+
if (delta < 0) item.violationCount = Number(item.violationCount || 0) + 1;
|
|
818
|
+
else if (delta > 0) item.cleanUses = Number(item.cleanUses || 0) + 1;
|
|
819
|
+
item.updatedAt = new Date().toISOString();
|
|
820
|
+
|
|
821
|
+
if (next >= RSL_CONSTANTS.PROMOTE_HOOK_IMPORTANCE || item.violationCount >= RSL_CONSTANTS.REPEAT_VIOLATION_THRESHOLD) {
|
|
822
|
+
item.promotedHook = true;
|
|
823
|
+
}
|
|
824
|
+
compileHeuristicDualTargets(baseRoot, item, options);
|
|
825
|
+
const hooks = syncPromotedDualHooks(baseRoot, ledger, options);
|
|
826
|
+
writeRslLedger(baseRoot, ledger);
|
|
827
|
+
return { ok: true, slug: safeSlug, item, hooks };
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* Fast (<5ms) runtime evaluation of promoted Carrier C `PreToolUse` guards.
|
|
832
|
+
*
|
|
833
|
+
* @param {string} workspaceRoot
|
|
834
|
+
* @param {'antigravity' | 'claude'} platform
|
|
835
|
+
* @param {object} [payload={}]
|
|
836
|
+
*/
|
|
837
|
+
export function evaluatePromotedPreToolGuards(workspaceRoot, platform = 'antigravity', payload = {}) {
|
|
838
|
+
const baseRoot = path.resolve(workspaceRoot || process.cwd());
|
|
839
|
+
const ledgerPath = getRslLedgerPath(baseRoot);
|
|
840
|
+
if (!fs.existsSync(ledgerPath)) {
|
|
841
|
+
return { decision: 'allow', matchedSlug: null, reason: null };
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
const ledger = readRslLedger(baseRoot);
|
|
845
|
+
const promoted = Object.values(ledger.items || {}).filter(
|
|
846
|
+
(it) =>
|
|
847
|
+
it &&
|
|
848
|
+
it.status === 'active' &&
|
|
849
|
+
Boolean(it.denyPattern) &&
|
|
850
|
+
(it.promotedHook === true ||
|
|
851
|
+
it.carrier === 'pre_tool_hook' ||
|
|
852
|
+
Number(it.importance || 0) >= RSL_CONSTANTS.PROMOTE_HOOK_IMPORTANCE)
|
|
853
|
+
);
|
|
854
|
+
if (promoted.length === 0) {
|
|
855
|
+
return { decision: 'allow', matchedSlug: null, reason: null };
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
const toolName = String(payload.toolCall?.name || payload.tool_name || payload.toolName || '');
|
|
859
|
+
const args = payload.toolCall?.args || payload.tool_input || payload.toolInput || {};
|
|
860
|
+
const haystack = [
|
|
861
|
+
args.CommandLine,
|
|
862
|
+
args.command,
|
|
863
|
+
args.cmd,
|
|
864
|
+
args.script,
|
|
865
|
+
args.file_path,
|
|
866
|
+
args.TargetFile,
|
|
867
|
+
args.Path,
|
|
868
|
+
args.path,
|
|
869
|
+
args.content,
|
|
870
|
+
args.Replacement
|
|
871
|
+
]
|
|
872
|
+
.filter((v) => typeof v === 'string' && v.length > 0)
|
|
873
|
+
.join('\n')
|
|
874
|
+
.toLowerCase();
|
|
875
|
+
|
|
876
|
+
if (!haystack) {
|
|
877
|
+
return { decision: 'allow', matchedSlug: null, reason: null };
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
for (const item of promoted) {
|
|
881
|
+
const matcherStr = platform === 'claude' ? item.claudeToolMatcher : item.toolMatcher;
|
|
882
|
+
if (matcherStr && toolName) {
|
|
883
|
+
try {
|
|
884
|
+
const re = new RegExp(`^(?:${matcherStr})$`, 'i');
|
|
885
|
+
if (!re.test(toolName)) continue;
|
|
886
|
+
} catch {
|
|
887
|
+
// Ignore malformed matcher
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
const needle = String(item.denyPattern || '').trim().toLowerCase();
|
|
891
|
+
if (needle && haystack.includes(needle)) {
|
|
892
|
+
return {
|
|
893
|
+
decision: 'deny',
|
|
894
|
+
matchedSlug: item.slug,
|
|
895
|
+
reason: `[Highbeam RSL Guard: rsl-${item.slug}] Blocked repeated pattern "${item.denyPattern}". ${item.then_guidance || ''}`.trim()
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
return { decision: 'allow', matchedSlug: null, reason: null };
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/**
|
|
904
|
+
* Returns consolidated dual-platform RSL summary for CLI, Daemon, WebView, and StatusLine.
|
|
905
|
+
*
|
|
906
|
+
* @param {string} [workspaceRoot=process.cwd()]
|
|
907
|
+
* @param {object} [options={}]
|
|
908
|
+
*/
|
|
909
|
+
export function getRslSummary(workspaceRoot = process.cwd(), options = {}) {
|
|
910
|
+
const baseRoot = path.resolve(workspaceRoot || process.cwd());
|
|
911
|
+
const ledger = readRslLedger(baseRoot);
|
|
912
|
+
const allItems = Object.values(ledger.items || {});
|
|
913
|
+
const activeItems = allItems.filter((it) => it && it.status === 'active');
|
|
914
|
+
const activeRules = activeItems.filter((it) => it.carrier !== 'skill_workflow').length;
|
|
915
|
+
const activeSkills = activeItems.filter((it) => it.carrier === 'skill_workflow').length;
|
|
916
|
+
const promotedHooks = activeItems.filter(
|
|
917
|
+
(it) =>
|
|
918
|
+
it.promotedHook === true ||
|
|
919
|
+
it.carrier === 'pre_tool_hook' ||
|
|
920
|
+
Number(it.importance || 0) >= RSL_CONSTANTS.PROMOTE_HOOK_IMPORTANCE
|
|
921
|
+
).length;
|
|
922
|
+
|
|
923
|
+
const budget = measureWorkspaceRuleBudget(baseRoot);
|
|
924
|
+
const clashAudit = auditWorkspaceRuleClashes(baseRoot);
|
|
925
|
+
const quarantinedItems = allItems.filter((it) => it && it.status === 'quarantined_conflict');
|
|
926
|
+
const activeClashes = clashAudit.clashes.slice(0, 5);
|
|
927
|
+
const claudeMemoryAudit = auditClaudeAutoMemory({
|
|
928
|
+
cwd: baseRoot,
|
|
929
|
+
homeDir: options.homeDir || os.homedir(),
|
|
930
|
+
memoryDir: options.memoryDir,
|
|
931
|
+
memoryFilePath: options.memoryFilePath
|
|
932
|
+
});
|
|
933
|
+
|
|
934
|
+
const topHeuristics = activeItems
|
|
935
|
+
.slice()
|
|
936
|
+
.sort((a, b) => Number(b.importance || 0) - Number(a.importance || 0))
|
|
937
|
+
.slice(0, 10)
|
|
938
|
+
.map((it) => ({
|
|
939
|
+
slug: it.slug,
|
|
940
|
+
carrier: it.carrier,
|
|
941
|
+
importance: Number(it.importance || 0),
|
|
942
|
+
promotedHook: Boolean(it.promotedHook),
|
|
943
|
+
sourcePlatform: it.sourcePlatform || 'dual',
|
|
944
|
+
globs: it.globs || '',
|
|
945
|
+
description: it.description || ''
|
|
946
|
+
}));
|
|
947
|
+
|
|
948
|
+
return {
|
|
949
|
+
workspaceRoot: baseRoot,
|
|
950
|
+
ledgerPath: getRslLedgerPath(baseRoot),
|
|
951
|
+
activeRules,
|
|
952
|
+
activeSkills,
|
|
953
|
+
promotedHooks,
|
|
954
|
+
totalActive: activeItems.length,
|
|
955
|
+
clashCount: clashAudit.clashCount + quarantinedItems.length,
|
|
956
|
+
quarantinedCount: quarantinedItems.length,
|
|
957
|
+
activeClashes,
|
|
958
|
+
prunedCount: Number(ledger.stats?.prunedCount || 0),
|
|
959
|
+
taintedSessions: Number(ledger.stats?.taintedSessions || 0),
|
|
960
|
+
lastSessionId: ledger.stats?.lastSessionId || null,
|
|
961
|
+
lastPlatform: ledger.stats?.lastPlatform || null,
|
|
962
|
+
ruleBudgetTokens: budget.totalTokens,
|
|
963
|
+
ruleBudgetMaxTokens: budget.budgetTokens,
|
|
964
|
+
ruleBudgetPct: budget.pct,
|
|
965
|
+
claudeMemoryAudit,
|
|
966
|
+
topHeuristics,
|
|
967
|
+
items: options.includeAll ? allItems : activeItems
|
|
968
|
+
};
|
|
969
|
+
}
|