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
|
@@ -30,6 +30,237 @@ export function suppressSqliteWarning({ force = false } = {}) {
|
|
|
30
30
|
|
|
31
31
|
let probedModule = undefined;
|
|
32
32
|
|
|
33
|
+
function extractFtsTokens(rawQuery = '') {
|
|
34
|
+
const cleaned = String(rawQuery || '')
|
|
35
|
+
.replace(/\bNEAR\s*\([^)]*\)/gi, ' ')
|
|
36
|
+
.replace(/[A-Za-z0-9_]+\s*:/g, ' ')
|
|
37
|
+
.replace(/['"*()]/g, ' ')
|
|
38
|
+
.trim();
|
|
39
|
+
if (!cleaned) return { mode: 'EMPTY', include: [], exclude: [] };
|
|
40
|
+
|
|
41
|
+
if (/\s+NOT\s+/i.test(cleaned)) {
|
|
42
|
+
const [incPart, ...excParts] = cleaned.split(/\s+NOT\s+/i);
|
|
43
|
+
const include = incPart.split(/\s+(?:AND\s+|OR\s+)?/i).map(t => t.trim().toLowerCase()).filter(Boolean);
|
|
44
|
+
const exclude = excParts.join(' ').split(/\s+/).map(t => t.trim().toLowerCase()).filter(Boolean);
|
|
45
|
+
return { mode: 'AND', include, exclude };
|
|
46
|
+
}
|
|
47
|
+
if (/\s+OR\s+/i.test(cleaned)) {
|
|
48
|
+
const include = cleaned.split(/\s+OR\s+|\s+/i).map(t => t.trim().toLowerCase()).filter(t => t && t !== 'or' && t !== 'and');
|
|
49
|
+
return { mode: 'OR', include, exclude: [] };
|
|
50
|
+
}
|
|
51
|
+
const include = cleaned.split(/\s+AND\s+|\s+/i).map(t => t.trim().toLowerCase()).filter(t => t && t !== 'and');
|
|
52
|
+
return { mode: 'AND', include, exclude: [] };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function evaluateFtsMatch(haystack = '', rawQuery = '') {
|
|
56
|
+
const text = String(haystack || '').toLowerCase();
|
|
57
|
+
const { mode, include, exclude } = extractFtsTokens(rawQuery);
|
|
58
|
+
if (mode === 'EMPTY' || include.length === 0) return 0;
|
|
59
|
+
for (const ex of exclude) {
|
|
60
|
+
if (text.includes(ex)) return 0;
|
|
61
|
+
}
|
|
62
|
+
if (mode === 'OR') {
|
|
63
|
+
return include.some(tok => text.includes(tok)) ? 1 : 0;
|
|
64
|
+
}
|
|
65
|
+
return include.every(tok => text.includes(tok)) ? 1 : 0;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function evaluateFtsBm25(haystack = '', rawQuery = '') {
|
|
69
|
+
const text = String(haystack || '').toLowerCase();
|
|
70
|
+
const { include } = extractFtsTokens(rawQuery);
|
|
71
|
+
if (include.length === 0) return 0.0;
|
|
72
|
+
let score = 0;
|
|
73
|
+
for (const tok of include) {
|
|
74
|
+
let idx = 0;
|
|
75
|
+
while ((idx = text.indexOf(tok, idx)) !== -1) {
|
|
76
|
+
score += 1;
|
|
77
|
+
idx += tok.length;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return score > 0 ? -score : 0.0;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function evaluateFtsSnippet(haystack = '', rawQuery = '', openTag = '[', closeTag = ']', ellipsis = '...', maxTokens = 16) {
|
|
84
|
+
const rawStr = String(haystack || '');
|
|
85
|
+
const { include } = extractFtsTokens(rawQuery);
|
|
86
|
+
const segments = rawStr.includes('\x1f') ? rawStr.split('\x1f') : [rawStr];
|
|
87
|
+
let chosenSegment = segments[segments.length - 1] || '';
|
|
88
|
+
if (include.length > 0) {
|
|
89
|
+
for (const seg of segments) {
|
|
90
|
+
const lowerSeg = seg.toLowerCase();
|
|
91
|
+
if (include.some(tok => lowerSeg.includes(tok))) {
|
|
92
|
+
chosenSegment = seg;
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (!chosenSegment || include.length === 0) return chosenSegment.slice(0, 120);
|
|
98
|
+
let out = chosenSegment;
|
|
99
|
+
for (const tok of include) {
|
|
100
|
+
const escaped = tok.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
101
|
+
const re = new RegExp(`(${escaped})`, 'gi');
|
|
102
|
+
if (re.test(out)) {
|
|
103
|
+
out = out.replace(re, `${openTag}$1${closeTag}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const words = out.split(/\s+/);
|
|
107
|
+
const limit = Math.max(4, Number(maxTokens) || 16);
|
|
108
|
+
if (words.length > limit) {
|
|
109
|
+
let matchWordIdx = 0;
|
|
110
|
+
const lowerInclude = include.map(t => t.toLowerCase());
|
|
111
|
+
for (let i = 0; i < words.length; i++) {
|
|
112
|
+
const wLower = words[i].toLowerCase();
|
|
113
|
+
if (lowerInclude.some(tok => wLower.includes(tok))) {
|
|
114
|
+
matchWordIdx = i;
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const startIdx = Math.max(0, Math.min(words.length - limit, matchWordIdx - Math.floor(limit / 3)));
|
|
119
|
+
const endIdx = startIdx + limit;
|
|
120
|
+
const prefix = startIdx > 0 ? ellipsis : '';
|
|
121
|
+
const suffix = endIdx < words.length ? ellipsis : '';
|
|
122
|
+
return `${prefix}${words.slice(startIdx, endIdx).join(' ')}${suffix}`;
|
|
123
|
+
}
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function createFts5PolyfillClass(RawDatabaseSync) {
|
|
128
|
+
const Fts5PolyfillDatabaseSync = class DatabaseSync extends RawDatabaseSync {
|
|
129
|
+
constructor(...args) {
|
|
130
|
+
super(...args);
|
|
131
|
+
this._activeFtsQuery = '';
|
|
132
|
+
this._ftsColsCache = new Map();
|
|
133
|
+
try {
|
|
134
|
+
if (typeof this.function === 'function') {
|
|
135
|
+
this.function('__hz_fts_match', (haystack, q) => {
|
|
136
|
+
this._activeFtsQuery = String(q ?? '');
|
|
137
|
+
return evaluateFtsMatch(haystack, q);
|
|
138
|
+
});
|
|
139
|
+
this.function('__hz_fts_bm25', (haystack) => {
|
|
140
|
+
return evaluateFtsBm25(haystack, this._activeFtsQuery);
|
|
141
|
+
});
|
|
142
|
+
this.function('__hz_fts_snippet', (haystack, openTag, closeTag, ellipsis, maxTok) => {
|
|
143
|
+
return evaluateFtsSnippet(haystack, this._activeFtsQuery, openTag, closeTag, ellipsis, maxTok);
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
} catch {
|
|
147
|
+
// Ignore if custom functions cannot be registered
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
_getTableColumns(tableName) {
|
|
152
|
+
if (this._ftsColsCache.has(tableName)) return this._ftsColsCache.get(tableName);
|
|
153
|
+
try {
|
|
154
|
+
const rows = super.prepare(`PRAGMA table_info(${tableName})`).all();
|
|
155
|
+
const cols = rows.map(r => r.name).filter(Boolean);
|
|
156
|
+
if (cols.length > 0) {
|
|
157
|
+
this._ftsColsCache.set(tableName, cols);
|
|
158
|
+
return cols;
|
|
159
|
+
}
|
|
160
|
+
} catch {}
|
|
161
|
+
return [];
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
_buildConcatExpr(tableName) {
|
|
165
|
+
const cols = this._getTableColumns(tableName);
|
|
166
|
+
if (cols.length === 0) return `''`;
|
|
167
|
+
return `(${cols.map(c => `COALESCE(CAST(${tableName}.${c} AS TEXT), '')`).join(" || char(31) || ")})`;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
exec(sql) {
|
|
171
|
+
let rewritten = String(sql || '');
|
|
172
|
+
// Strip FTS5 optimize command on polyfilled tables
|
|
173
|
+
rewritten = rewritten.replace(
|
|
174
|
+
/INSERT\s+INTO\s+([A-Za-z0-9_]+)\s*\(\s*\1\s*\)\s*VALUES\s*\(\s*'optimize'\s*\)\s*;?/gi,
|
|
175
|
+
''
|
|
176
|
+
);
|
|
177
|
+
// Rewrite CREATE VIRTUAL TABLE ... USING fts5(...) into standard SQLite table preserving /* fts5 */ marker
|
|
178
|
+
rewritten = rewritten.replace(
|
|
179
|
+
/CREATE\s+VIRTUAL\s+TABLE\s+(IF\s+NOT\s+EXISTS\s+)?([A-Za-z0-9_]+)\s+USING\s+fts5\s*\(([\s\S]*?)\)/gi,
|
|
180
|
+
(_, ifNotExists = '', tableName, rawCols) => {
|
|
181
|
+
const cols = rawCols
|
|
182
|
+
.split(',')
|
|
183
|
+
.map(part => part.trim())
|
|
184
|
+
.filter(part => part && !part.includes('='))
|
|
185
|
+
.map(part => part.replace(/\bUNINDEXED\b/gi, '').trim().split(/\s+/)[0])
|
|
186
|
+
.filter(Boolean);
|
|
187
|
+
this._ftsColsCache.set(tableName, cols);
|
|
188
|
+
const colDefs = cols.map(c => `${c} TEXT`).join(', ');
|
|
189
|
+
return `CREATE TABLE ${ifNotExists}${tableName} (/* fts5 */ ${colDefs})`;
|
|
190
|
+
}
|
|
191
|
+
);
|
|
192
|
+
if (!rewritten.trim()) return;
|
|
193
|
+
return super.exec(rewritten);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
prepare(sql) {
|
|
197
|
+
let rewritten = String(sql || '');
|
|
198
|
+
const hasFtsSyntax = /\bMATCH\s+\?|\bbm25\s*\(|\bsnippet\s*\(/i.test(rewritten);
|
|
199
|
+
if (hasFtsSyntax) {
|
|
200
|
+
rewritten = rewritten.replace(
|
|
201
|
+
/snippet\s*\(\s*([A-Za-z0-9_]+)\s*,\s*(-?\d+)\s*,\s*('[^']*')\s*,\s*('[^']*')\s*,\s*('[^']*')\s*,\s*(\d+)\s*\)/gi,
|
|
202
|
+
(_, tbl, colIdxStr, openTag, closeTag, ellipsis, maxTok) => {
|
|
203
|
+
const colIdx = Number(colIdxStr);
|
|
204
|
+
const cols = this._getTableColumns(tbl);
|
|
205
|
+
const targetExpr = (colIdx >= 0 && cols[colIdx])
|
|
206
|
+
? `COALESCE(CAST(${tbl}.${cols[colIdx]} AS TEXT), '')`
|
|
207
|
+
: this._buildConcatExpr(tbl);
|
|
208
|
+
return `__hz_fts_snippet(${targetExpr}, ${openTag}, ${closeTag}, ${ellipsis}, ${maxTok})`;
|
|
209
|
+
}
|
|
210
|
+
);
|
|
211
|
+
rewritten = rewritten.replace(
|
|
212
|
+
/bm25\s*\(\s*([A-Za-z0-9_]+)\s*\)/gi,
|
|
213
|
+
(_, tbl) => `__hz_fts_bm25(${this._buildConcatExpr(tbl)})`
|
|
214
|
+
);
|
|
215
|
+
rewritten = rewritten.replace(
|
|
216
|
+
/([A-Za-z0-9_]+)\s+MATCH\s+\?/gi,
|
|
217
|
+
(_, tbl) => `__hz_fts_match(${this._buildConcatExpr(tbl)}, ?)`
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const stmt = super.prepare(rewritten);
|
|
222
|
+
if (!hasFtsSyntax) return stmt;
|
|
223
|
+
|
|
224
|
+
const self = this;
|
|
225
|
+
const origAll = stmt.all.bind(stmt);
|
|
226
|
+
const origGet = stmt.get.bind(stmt);
|
|
227
|
+
stmt.all = (...args) => {
|
|
228
|
+
if (args.length > 0) self._activeFtsQuery = String(args[0] ?? '');
|
|
229
|
+
return origAll(...args);
|
|
230
|
+
};
|
|
231
|
+
stmt.get = (...args) => {
|
|
232
|
+
if (args.length > 0) self._activeFtsQuery = String(args[0] ?? '');
|
|
233
|
+
return origGet(...args);
|
|
234
|
+
};
|
|
235
|
+
return stmt;
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
Object.defineProperty(Fts5PolyfillDatabaseSync, 'name', { value: 'DatabaseSync' });
|
|
239
|
+
return Fts5PolyfillDatabaseSync;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function ensureFts5CapableModule(mod) {
|
|
243
|
+
if (!mod || typeof mod.DatabaseSync !== 'function') return mod;
|
|
244
|
+
const RawDb = mod.DatabaseSync;
|
|
245
|
+
let hasNativeFts5 = false;
|
|
246
|
+
if (typeof process === 'undefined' || process.env?.CTXTOP_FORCE_FTS5_POLYFILL !== '1') {
|
|
247
|
+
try {
|
|
248
|
+
const mem = new RawDb(':memory:');
|
|
249
|
+
mem.exec('CREATE VIRTUAL TABLE __fts5_probe USING fts5(c);');
|
|
250
|
+
mem.close();
|
|
251
|
+
hasNativeFts5 = true;
|
|
252
|
+
} catch {
|
|
253
|
+
hasNativeFts5 = false;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (hasNativeFts5) return mod;
|
|
257
|
+
const PolyfilledDb = createFts5PolyfillClass(RawDb);
|
|
258
|
+
return {
|
|
259
|
+
...mod,
|
|
260
|
+
DatabaseSync: PolyfilledDb
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
|
|
33
264
|
/**
|
|
34
265
|
* Probes for built-in node:sqlite module via process.getBuiltinModule.
|
|
35
266
|
*
|
|
@@ -60,8 +291,9 @@ export function probeSqliteBuiltin({ forceFallback = false, getBuiltinModuleOver
|
|
|
60
291
|
}
|
|
61
292
|
|
|
62
293
|
try {
|
|
63
|
-
const
|
|
64
|
-
if (
|
|
294
|
+
const rawMod = getBuiltin('node:sqlite');
|
|
295
|
+
if (rawMod && typeof rawMod.DatabaseSync === 'function') {
|
|
296
|
+
const mod = getBuiltinModuleOverride ? rawMod : ensureFts5CapableModule(rawMod);
|
|
65
297
|
if (!getBuiltinModuleOverride) probedModule = mod;
|
|
66
298
|
return mod;
|
|
67
299
|
}
|
|
@@ -7,3 +7,6 @@ export * from './db/index.mjs';
|
|
|
7
7
|
export * from './sensors/index.mjs';
|
|
8
8
|
export * from './offloader/index.mjs';
|
|
9
9
|
export * from './ipc/index.mjs';
|
|
10
|
+
export * from '../core/rsl_triage.mjs';
|
|
11
|
+
export * from '../core/rsl_distiller.mjs';
|
|
12
|
+
export * from '../core/rsl_ledger.mjs';
|
|
@@ -48,19 +48,26 @@ export function detectDirtySnapshots(stepEvents = [], workspacePath = '') {
|
|
|
48
48
|
const ts = Number(ev.timestampMs || (ev.createdAt ? Date.parse(ev.createdAt) : 0) || ev.timestamp || 0);
|
|
49
49
|
if (!Number.isFinite(ts) || ts <= 0) continue;
|
|
50
50
|
const canonical = canonicalizePath(target);
|
|
51
|
-
const prev = lastTouchMap.get(canonical)
|
|
52
|
-
|
|
51
|
+
const prev = lastTouchMap.get(canonical);
|
|
52
|
+
const nextTs = prev ? Math.max(prev.ts, ts) : ts;
|
|
53
|
+
lastTouchMap.set(canonical, { ts: nextTs, rawPath: String(target).trim(), canonical });
|
|
53
54
|
}
|
|
54
55
|
}
|
|
55
56
|
|
|
56
57
|
const dirtySnapshotPaths = [];
|
|
57
|
-
for (const [
|
|
58
|
+
for (const [canonical, entry] of lastTouchMap.entries()) {
|
|
59
|
+
const lastTouchMs = entry.ts;
|
|
58
60
|
if (!Number.isFinite(lastTouchMs) || lastTouchMs <= 0) continue;
|
|
59
61
|
try {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
+
const candidatePath = fs.existsSync(entry.rawPath)
|
|
63
|
+
? entry.rawPath
|
|
64
|
+
: (workspacePath && fs.existsSync(path.resolve(workspacePath, entry.rawPath))
|
|
65
|
+
? path.resolve(workspacePath, entry.rawPath)
|
|
66
|
+
: canonical);
|
|
67
|
+
if (fs.existsSync(candidatePath)) {
|
|
68
|
+
const stat = fs.statSync(candidatePath);
|
|
62
69
|
if (stat.mtimeMs > lastTouchMs + 500) {
|
|
63
|
-
dirtySnapshotPaths.push(
|
|
70
|
+
dirtySnapshotPaths.push(canonical);
|
|
64
71
|
}
|
|
65
72
|
}
|
|
66
73
|
} catch {
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* @file src/hooks/antigravity_rsl_hook.mjs
|
|
4
|
+
* Google Antigravity Lifecycle Hook Adapter for Highbeam RSL (`SessionStart`, `PreToolUse`,
|
|
5
|
+
* `PostToolUse`, `Stop`). Runs synchronously in <30ms with 0 LLM tokens by default.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
import { atomicWriteFileSync } from '../core/atomic_io.mjs';
|
|
12
|
+
import {
|
|
13
|
+
resolveWorkspaceRoot,
|
|
14
|
+
sanitizeRslSessionId,
|
|
15
|
+
snapshotTestSuiteBaseline,
|
|
16
|
+
recordStepOutcome,
|
|
17
|
+
buildContrastiveDigest
|
|
18
|
+
} from '../core/rsl_triage.mjs';
|
|
19
|
+
import { distillContrastiveDigest } from '../core/rsl_distiller.mjs';
|
|
20
|
+
import {
|
|
21
|
+
getRslLedgerPath,
|
|
22
|
+
ingestDistilledHeuristics,
|
|
23
|
+
evaluatePromotedPreToolGuards,
|
|
24
|
+
RSL_PKG_ROOT
|
|
25
|
+
} from '../core/rsl_ledger.mjs';
|
|
26
|
+
|
|
27
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
28
|
+
|
|
29
|
+
function parseCliFlags(argv = []) {
|
|
30
|
+
const out = {};
|
|
31
|
+
for (const arg of argv) {
|
|
32
|
+
if (arg.startsWith('--event=')) out.event = arg.slice('--event='.length).trim();
|
|
33
|
+
else if (arg.startsWith('--mode=')) out.mode = arg.slice('--mode='.length).trim();
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function readStdinJsonQuick(maxTimeoutMs = 150) {
|
|
39
|
+
return new Promise((resolve) => {
|
|
40
|
+
if (process.stdin.isTTY) {
|
|
41
|
+
resolve({});
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
let raw = '';
|
|
45
|
+
let settled = false;
|
|
46
|
+
let settleTimer = null;
|
|
47
|
+
|
|
48
|
+
const done = (val) => {
|
|
49
|
+
if (settled) return;
|
|
50
|
+
settled = true;
|
|
51
|
+
clearTimeout(maxTimer);
|
|
52
|
+
if (settleTimer) clearTimeout(settleTimer);
|
|
53
|
+
try {
|
|
54
|
+
process.stdin.pause();
|
|
55
|
+
} catch {
|
|
56
|
+
// Ignore
|
|
57
|
+
}
|
|
58
|
+
resolve(val);
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const tryParse = () => {
|
|
62
|
+
try {
|
|
63
|
+
const trimmed = raw.trim();
|
|
64
|
+
return trimmed ? JSON.parse(trimmed) : {};
|
|
65
|
+
} catch {
|
|
66
|
+
return {};
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const maxTimer = setTimeout(() => done(tryParse()), maxTimeoutMs);
|
|
71
|
+
process.stdin.setEncoding('utf8');
|
|
72
|
+
process.stdin.on('data', (chunk) => {
|
|
73
|
+
raw += chunk;
|
|
74
|
+
if (settleTimer) clearTimeout(settleTimer);
|
|
75
|
+
if (raw.trim().endsWith('}')) {
|
|
76
|
+
settleTimer = setTimeout(() => {
|
|
77
|
+
try {
|
|
78
|
+
done(JSON.parse(raw));
|
|
79
|
+
} catch {
|
|
80
|
+
// Wait for end or timeout
|
|
81
|
+
}
|
|
82
|
+
}, 2);
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
process.stdin.on('end', () => done(tryParse()));
|
|
86
|
+
process.stdin.on('error', () => done({}));
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function resolveAntigravityEvent(payload = {}, options = {}) {
|
|
91
|
+
const explicit = options.event || payload.hookEventName || payload.hook_event_name;
|
|
92
|
+
if (explicit) return String(explicit).trim();
|
|
93
|
+
if ('fullyIdle' in payload || 'terminationReason' in payload || 'executionNum' in payload) {
|
|
94
|
+
return 'Stop';
|
|
95
|
+
}
|
|
96
|
+
if (payload.toolCall || payload.tool_name) {
|
|
97
|
+
return 'error' in payload ? 'PostToolUse' : 'PreToolUse';
|
|
98
|
+
}
|
|
99
|
+
return 'SessionStart';
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Programmatic handler for Antigravity RSL hook events.
|
|
104
|
+
* @param {object} [payload={}]
|
|
105
|
+
* @param {object} [options={}]
|
|
106
|
+
*/
|
|
107
|
+
export function handleAntigravityRslHook(payload = {}, options = {}) {
|
|
108
|
+
const event = resolveAntigravityEvent(payload, options);
|
|
109
|
+
const workspaceRoot = resolveWorkspaceRoot(payload, options);
|
|
110
|
+
const sessionId = sanitizeRslSessionId(
|
|
111
|
+
payload.conversationId || payload.session_id || payload.sessionId || options.sessionId || 'default'
|
|
112
|
+
);
|
|
113
|
+
|
|
114
|
+
if (event === 'SessionStart') {
|
|
115
|
+
const snapshot = snapshotTestSuiteBaseline(workspaceRoot, sessionId, options);
|
|
116
|
+
return {
|
|
117
|
+
exitCode: 0,
|
|
118
|
+
stdoutJson: {},
|
|
119
|
+
event,
|
|
120
|
+
snapshot
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (event === 'PreToolUse') {
|
|
125
|
+
const verdict = evaluatePromotedPreToolGuards(workspaceRoot, 'antigravity', payload);
|
|
126
|
+
const stdoutJson = verdict.decision === 'deny'
|
|
127
|
+
? { decision: 'deny', reason: verdict.reason }
|
|
128
|
+
: { decision: 'allow' };
|
|
129
|
+
return {
|
|
130
|
+
exitCode: 0,
|
|
131
|
+
stdoutJson,
|
|
132
|
+
event,
|
|
133
|
+
verdict
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (event === 'PostToolUse') {
|
|
138
|
+
const recorded = recordStepOutcome(payload, { ...options, platform: 'antigravity' });
|
|
139
|
+
return {
|
|
140
|
+
exitCode: 0,
|
|
141
|
+
stdoutJson: {},
|
|
142
|
+
event,
|
|
143
|
+
recorded
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (event === 'Stop') {
|
|
148
|
+
if (payload.fullyIdle === false) {
|
|
149
|
+
return {
|
|
150
|
+
exitCode: 0,
|
|
151
|
+
stdoutJson: { decision: 'allow' },
|
|
152
|
+
event,
|
|
153
|
+
skippedReason: 'fullyIdle_false'
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const digest = buildContrastiveDigest(payload, { ...options, platform: 'antigravity' });
|
|
158
|
+
const hasLedger = fs.existsSync(getRslLedgerPath(workspaceRoot));
|
|
159
|
+
let distillation = null;
|
|
160
|
+
let ledgerResult = null;
|
|
161
|
+
|
|
162
|
+
if (digest.tainted) {
|
|
163
|
+
ledgerResult = ingestDistilledHeuristics(workspaceRoot, {}, digest, options);
|
|
164
|
+
} else if (digest.triggered || hasLedger) {
|
|
165
|
+
distillation = digest.triggered
|
|
166
|
+
? distillContrastiveDigest(digest, { mode: options.mode || 'local' })
|
|
167
|
+
: { is_valid_learning: false, mode: 'local', heuristics: [] };
|
|
168
|
+
ledgerResult = ingestDistilledHeuristics(workspaceRoot, distillation, digest, options);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return {
|
|
172
|
+
exitCode: 0,
|
|
173
|
+
stdoutJson: { decision: 'allow' },
|
|
174
|
+
event,
|
|
175
|
+
digest,
|
|
176
|
+
distillation,
|
|
177
|
+
ledgerResult
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return {
|
|
182
|
+
exitCode: 0,
|
|
183
|
+
stdoutJson: {},
|
|
184
|
+
event
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Registers or removes the `"ctxtop-rsl-postmortem"` hook group in `<workspaceRoot>/.agents/hooks.json`.
|
|
190
|
+
* @param {string} workspaceRoot
|
|
191
|
+
* @param {object} [options={}]
|
|
192
|
+
*/
|
|
193
|
+
export function syncAntigravityWorkspaceRslHooks(workspaceRoot, options = {}) {
|
|
194
|
+
const baseRoot = path.resolve(workspaceRoot || process.cwd());
|
|
195
|
+
const hooksPath = path.join(baseRoot, '.agents', 'hooks.json');
|
|
196
|
+
const pkgRoot = String(options.pkgRoot || RSL_PKG_ROOT).replace(/\\/g, '/').replace(/\/+$/, '');
|
|
197
|
+
const hookScript = `${pkgRoot}/src/hooks/antigravity_rsl_hook.mjs`;
|
|
198
|
+
const enabled = options.enabled !== false;
|
|
199
|
+
|
|
200
|
+
let doc = {};
|
|
201
|
+
if (fs.existsSync(hooksPath)) {
|
|
202
|
+
try {
|
|
203
|
+
const parsed = JSON.parse(fs.readFileSync(hooksPath, 'utf8'));
|
|
204
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) doc = { ...parsed };
|
|
205
|
+
} catch {
|
|
206
|
+
doc = {};
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (options.remove) {
|
|
211
|
+
delete doc['ctxtop-rsl-postmortem'];
|
|
212
|
+
} else {
|
|
213
|
+
doc['ctxtop-rsl-postmortem'] = {
|
|
214
|
+
enabled,
|
|
215
|
+
SessionStart: [
|
|
216
|
+
{ type: 'command', command: `node "${hookScript}" --event=SessionStart`, timeout: 5 }
|
|
217
|
+
],
|
|
218
|
+
PostToolUse: [
|
|
219
|
+
{
|
|
220
|
+
matcher: '*',
|
|
221
|
+
hooks: [
|
|
222
|
+
{ type: 'command', command: `node "${hookScript}" --event=PostToolUse`, timeout: 5 }
|
|
223
|
+
]
|
|
224
|
+
}
|
|
225
|
+
],
|
|
226
|
+
Stop: [
|
|
227
|
+
{ type: 'command', command: `node "${hookScript}" --event=Stop`, timeout: 15 }
|
|
228
|
+
]
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
fs.mkdirSync(path.dirname(hooksPath), { recursive: true });
|
|
233
|
+
atomicWriteFileSync(hooksPath, `${JSON.stringify(doc, null, 2)}\n`);
|
|
234
|
+
return { hooksPath, enabled };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const isMain = process.argv[1] && path.resolve(process.argv[1]) === __filename;
|
|
238
|
+
if (isMain) {
|
|
239
|
+
const flags = parseCliFlags(process.argv.slice(2));
|
|
240
|
+
readStdinJsonQuick()
|
|
241
|
+
.then((payload) => {
|
|
242
|
+
const res = handleAntigravityRslHook(payload, flags);
|
|
243
|
+
process.stdout.write(`${JSON.stringify(res.stdoutJson ?? {})}\n`);
|
|
244
|
+
process.exit(0);
|
|
245
|
+
})
|
|
246
|
+
.catch(() => {
|
|
247
|
+
process.stdout.write('{"decision":"allow"}\n');
|
|
248
|
+
process.exit(0);
|
|
249
|
+
});
|
|
250
|
+
}
|