0xray 4.0.28 → 4.0.29
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/.gitignore.default +1 -0
- package/.grok-plugin/plugin.json +1 -1
- package/.xray/features.json +1 -1
- package/README.md +2 -1
- package/dist/.gitignore.default +1 -0
- package/dist/CHANGELOG.md +8 -0
- package/dist/README.md +2 -1
- package/dist/cli/index.js +52 -44
- package/dist/integrations/cursor/README.md +21 -2
- package/dist/integrations/cursor/hooks/xray-cloud-hook.sh +61 -4
- package/dist/integrations/openclaw/plugin/xray-pre-tool/package.json +1 -1
- package/llms.txt +1 -0
- package/package.json +1 -1
- package/scripts/node/bridge-mcp-wiring.cjs +2 -1
- package/scripts/node/consumer-gitignore.cjs +1 -0
- package/scripts/node/consumer-install-smoke.mjs +9 -72
- package/scripts/node/install-bridges.cjs +1015 -14
- package/scripts/node/postinstall.cjs +6 -59
- package/scripts/node/unwear-cursor-hooks.cjs +21 -0
- package/scripts/node/wear-cursor-hooks.cjs +17 -0
- package/scripts/node/wear-vendored-repertoire.cjs +35 -0
- package/src/integrations/openclaw/plugin/xray-pre-tool/package.json +1 -1
- package/xray/features.json +1 -1
|
@@ -189,7 +189,7 @@ function writePluginMcpJson(pluginDir, targetDir, log, label) {
|
|
|
189
189
|
}
|
|
190
190
|
|
|
191
191
|
function deployProjectMcpJson(targetDir, log) {
|
|
192
|
-
deployPortableProjectMcpJson(targetDir);
|
|
192
|
+
if (!deployPortableProjectMcpJson(targetDir)) return;
|
|
193
193
|
log("mcp-config", "project .mcp.json deployed (7 xray servers, portable)", "info");
|
|
194
194
|
}
|
|
195
195
|
|
|
@@ -732,6 +732,19 @@ const CURSOR_HOOK_SCRIPTS = [
|
|
|
732
732
|
"before-shell-execution.sh",
|
|
733
733
|
];
|
|
734
734
|
|
|
735
|
+
/** Five Cursor hook events 0xray ships. preCompact is one of them.
|
|
736
|
+
* Dogfood `.cursor/hooks` also holds the shared runner and invoke-probe.sh;
|
|
737
|
+
* those are not hook events. */
|
|
738
|
+
const CURSOR_HOOK_EVENTS = [
|
|
739
|
+
["preToolUse", "pre-tool-use.sh"],
|
|
740
|
+
["preCompact", "pre-compact.sh"],
|
|
741
|
+
["afterFileEdit", "after-file-edit.sh"],
|
|
742
|
+
["beforeShellExecution", "before-shell-execution.sh"],
|
|
743
|
+
["beforeReadFile", "before-read-file.sh"],
|
|
744
|
+
];
|
|
745
|
+
|
|
746
|
+
const CURSOR_WEAR_BACKUP = "hooks.json.xray-before";
|
|
747
|
+
|
|
735
748
|
const CLOUD_SAFE_CURSOR_HOOKS = {
|
|
736
749
|
version: 1,
|
|
737
750
|
hooks: {
|
|
@@ -860,8 +873,8 @@ function fastenCursorHooksAtUnsafe(targetDir, packageRoot, log) {
|
|
|
860
873
|
if (fs.existsSync(dest)) {
|
|
861
874
|
try {
|
|
862
875
|
existing = JSON.parse(fs.readFileSync(dest, "utf8"));
|
|
863
|
-
} catch {
|
|
864
|
-
|
|
876
|
+
} catch (err) {
|
|
877
|
+
throw new Error(`cursor-wear: refusing to edit ${dest}: ${err.message}. Wrote nothing.`);
|
|
865
878
|
}
|
|
866
879
|
}
|
|
867
880
|
const template = resolveCursorHooksTemplate(packageRoot);
|
|
@@ -870,8 +883,13 @@ function fastenCursorHooksAtUnsafe(targetDir, packageRoot, log) {
|
|
|
870
883
|
return null;
|
|
871
884
|
}
|
|
872
885
|
const next = mergeCloudSafeCursorHooks(existing);
|
|
873
|
-
|
|
874
|
-
fs.
|
|
886
|
+
const body = `${JSON.stringify(next, null, 2)}\n`;
|
|
887
|
+
const previousText = fs.existsSync(dest) ? fs.readFileSync(dest, "utf8") : null;
|
|
888
|
+
if (previousText !== body) {
|
|
889
|
+
saveCursorWearSnapshot(targetDir, previousText, body);
|
|
890
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
891
|
+
fs.writeFileSync(dest, body);
|
|
892
|
+
}
|
|
875
893
|
log("cursor-bridge", existing ? "hooks.json rewritten cloud-safe" : "hooks.json fastened", "info", {
|
|
876
894
|
path: dest,
|
|
877
895
|
scripts: copied,
|
|
@@ -978,27 +996,978 @@ function reloadCursorHostHooks(log) {
|
|
|
978
996
|
}
|
|
979
997
|
}
|
|
980
998
|
|
|
999
|
+
function consumerDistHooksReady(packageRoot) {
|
|
1000
|
+
const dir = path.join(packageRoot, "dist", "integrations", "cursor", "hooks");
|
|
1001
|
+
if (!fs.existsSync(path.join(dir, "xray-cloud-hook.sh"))) return false;
|
|
1002
|
+
return CURSOR_HOOK_EVENTS.every(([, script]) => fs.existsSync(path.join(dir, script)));
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
function installedHookCommand(fromDir, packageRoot, scriptName) {
|
|
1006
|
+
const abs = path.join(packageRoot, "dist", "integrations", "cursor", "hooks", scriptName);
|
|
1007
|
+
return path.relative(fromDir, abs).split(path.sep).join("/");
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
function installedCursorHookEntries(fromDir, packageRoot) {
|
|
1011
|
+
const hooks = {};
|
|
1012
|
+
for (const [event, script] of CURSOR_HOOK_EVENTS) {
|
|
1013
|
+
hooks[event] = [{ command: installedHookCommand(fromDir, packageRoot, script) }];
|
|
1014
|
+
}
|
|
1015
|
+
return hooks;
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
/**
|
|
1019
|
+
* Ours only when the command points at the installed dist hook.
|
|
1020
|
+
* Legacy one-liners count only when they launch that same dist `.js`.
|
|
1021
|
+
* A user's `.cursor/hooks/pre-compact.sh` is not ours.
|
|
1022
|
+
*/
|
|
1023
|
+
function isXrayHookCommand(command) {
|
|
1024
|
+
const cmd = String(command || "").trim();
|
|
1025
|
+
if (!cmd) return false;
|
|
1026
|
+
if (/(?:^|[/\\])node_modules\/0xray\/dist\/integrations\/cursor\/hooks\/[\w.-]+\.sh$/.test(cmd)) {
|
|
1027
|
+
return true;
|
|
1028
|
+
}
|
|
1029
|
+
return (
|
|
1030
|
+
/XRAY_AI_PATH=/.test(cmd) &&
|
|
1031
|
+
/node_modules\/0xray\/dist\/integrations\/cursor\/hooks\/[\w.-]+\.js/.test(cmd)
|
|
1032
|
+
);
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
function shellWithoutComments(text) {
|
|
1036
|
+
return String(text)
|
|
1037
|
+
.split("\n")
|
|
1038
|
+
.map((line) => {
|
|
1039
|
+
if (/^\s*#/.test(line)) return "";
|
|
1040
|
+
const hash = line.indexOf("#");
|
|
1041
|
+
return hash === -1 ? line : line.slice(0, hash);
|
|
1042
|
+
})
|
|
1043
|
+
.join("\n");
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
function commandAlreadyRunsXrayHook(command, targetDir) {
|
|
1047
|
+
if (isXrayHookCommand(command)) return true;
|
|
1048
|
+
const match = /^(?:\.\/)?\.cursor\/hooks\/([\w.-]+\.sh)$/.exec(String(command || "").trim());
|
|
1049
|
+
if (!match || !targetDir) return false;
|
|
1050
|
+
const abs = path.join(path.resolve(targetDir), ".cursor", "hooks", match[1]);
|
|
1051
|
+
try {
|
|
1052
|
+
return shellWithoutComments(fs.readFileSync(abs, "utf8")).includes("xray-cloud-hook.sh");
|
|
1053
|
+
} catch {
|
|
1054
|
+
return false;
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
function scanJsonc(text) {
|
|
1059
|
+
let hasComments = false;
|
|
1060
|
+
let i = 0;
|
|
1061
|
+
let inString = false;
|
|
1062
|
+
let escape = false;
|
|
1063
|
+
while (i < text.length) {
|
|
1064
|
+
const c = text[i];
|
|
1065
|
+
const n = text[i + 1];
|
|
1066
|
+
if (inString) {
|
|
1067
|
+
if (escape) escape = false;
|
|
1068
|
+
else if (c === "\\") escape = true;
|
|
1069
|
+
else if (c === '"') inString = false;
|
|
1070
|
+
i += 1;
|
|
1071
|
+
continue;
|
|
1072
|
+
}
|
|
1073
|
+
if (c === '"') {
|
|
1074
|
+
inString = true;
|
|
1075
|
+
i += 1;
|
|
1076
|
+
continue;
|
|
1077
|
+
}
|
|
1078
|
+
if (c === "/" && n === "/") {
|
|
1079
|
+
hasComments = true;
|
|
1080
|
+
i += 2;
|
|
1081
|
+
while (i < text.length && text[i] !== "\n") i += 1;
|
|
1082
|
+
continue;
|
|
1083
|
+
}
|
|
1084
|
+
if (c === "/" && n === "*") {
|
|
1085
|
+
hasComments = true;
|
|
1086
|
+
const end = text.indexOf("*/", i + 2);
|
|
1087
|
+
if (end < 0) return { ok: false, reason: "unclosed block comment", hasComments: true };
|
|
1088
|
+
i = end + 2;
|
|
1089
|
+
continue;
|
|
1090
|
+
}
|
|
1091
|
+
i += 1;
|
|
1092
|
+
}
|
|
1093
|
+
if (inString) return { ok: false, reason: "unclosed string", hasComments };
|
|
1094
|
+
return { ok: true, hasComments };
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
function stripJsonComments(text) {
|
|
1098
|
+
let out = "";
|
|
1099
|
+
let i = 0;
|
|
1100
|
+
let inString = false;
|
|
1101
|
+
let escape = false;
|
|
1102
|
+
while (i < text.length) {
|
|
1103
|
+
const c = text[i];
|
|
1104
|
+
const n = text[i + 1];
|
|
1105
|
+
if (inString) {
|
|
1106
|
+
out += c;
|
|
1107
|
+
if (escape) escape = false;
|
|
1108
|
+
else if (c === "\\") escape = true;
|
|
1109
|
+
else if (c === '"') inString = false;
|
|
1110
|
+
i += 1;
|
|
1111
|
+
continue;
|
|
1112
|
+
}
|
|
1113
|
+
if (c === '"') {
|
|
1114
|
+
inString = true;
|
|
1115
|
+
out += c;
|
|
1116
|
+
i += 1;
|
|
1117
|
+
continue;
|
|
1118
|
+
}
|
|
1119
|
+
if (c === "/" && n === "/") {
|
|
1120
|
+
i += 2;
|
|
1121
|
+
while (i < text.length && text[i] !== "\n") i += 1;
|
|
1122
|
+
out += " ";
|
|
1123
|
+
continue;
|
|
1124
|
+
}
|
|
1125
|
+
if (c === "/" && n === "*") {
|
|
1126
|
+
const end = text.indexOf("*/", i + 2);
|
|
1127
|
+
if (end < 0) break;
|
|
1128
|
+
i = end + 2;
|
|
1129
|
+
out += " ";
|
|
1130
|
+
continue;
|
|
1131
|
+
}
|
|
1132
|
+
out += c;
|
|
1133
|
+
i += 1;
|
|
1134
|
+
}
|
|
1135
|
+
return out;
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
function refuseHooksEdit(hooksPath, reason) {
|
|
1139
|
+
throw new Error(`cursor-wear: refusing to edit ${hooksPath}: ${reason}. Wrote nothing.`);
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
function assertUniqueJsonKeys(text) {
|
|
1143
|
+
const tokens = tokenizeJsonc(text);
|
|
1144
|
+
const visit = (idx) => {
|
|
1145
|
+
const token = tokens[idx];
|
|
1146
|
+
if (!token) return;
|
|
1147
|
+
if (token.type === "{") {
|
|
1148
|
+
const obj = objectPairs(tokens, idx);
|
|
1149
|
+
for (const pair of obj.pairs) visit(pair.valIdx);
|
|
1150
|
+
return;
|
|
1151
|
+
}
|
|
1152
|
+
if (token.type === "[") {
|
|
1153
|
+
const close = matchingBracket(tokens, idx);
|
|
1154
|
+
for (const el of arrayElements(tokens, idx, close)) visit(el.startIdx);
|
|
1155
|
+
}
|
|
1156
|
+
};
|
|
1157
|
+
if (tokens.length) visit(0);
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
function parseHooksText(text, hooksPath) {
|
|
1161
|
+
const scan = scanJsonc(text);
|
|
1162
|
+
if (!scan.ok) refuseHooksEdit(hooksPath, scan.reason);
|
|
1163
|
+
try {
|
|
1164
|
+
assertUniqueJsonKeys(text);
|
|
1165
|
+
} catch (err) {
|
|
1166
|
+
refuseHooksEdit(hooksPath, err.message || String(err));
|
|
1167
|
+
}
|
|
1168
|
+
let parsed;
|
|
1169
|
+
try {
|
|
1170
|
+
parsed = JSON.parse(stripJsonComments(text));
|
|
1171
|
+
} catch (err) {
|
|
1172
|
+
refuseHooksEdit(hooksPath, `hooks.json is not valid JSONC (${err.message})`);
|
|
1173
|
+
}
|
|
1174
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
1175
|
+
refuseHooksEdit(hooksPath, "hooks.json must be a JSON object");
|
|
1176
|
+
}
|
|
1177
|
+
return { parsed, hasComments: scan.hasComments };
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
function tokenizeJsonc(text) {
|
|
1181
|
+
const tokens = [];
|
|
1182
|
+
let i = 0;
|
|
1183
|
+
while (i < text.length) {
|
|
1184
|
+
const c = text[i];
|
|
1185
|
+
if (/\s/.test(c)) {
|
|
1186
|
+
i += 1;
|
|
1187
|
+
continue;
|
|
1188
|
+
}
|
|
1189
|
+
if (c === "/" && text[i + 1] === "/") {
|
|
1190
|
+
i += 2;
|
|
1191
|
+
while (i < text.length && text[i] !== "\n") i += 1;
|
|
1192
|
+
continue;
|
|
1193
|
+
}
|
|
1194
|
+
if (c === "/" && text[i + 1] === "*") {
|
|
1195
|
+
const end = text.indexOf("*/", i + 2);
|
|
1196
|
+
if (end < 0) throw new Error("unclosed block comment");
|
|
1197
|
+
i = end + 2;
|
|
1198
|
+
continue;
|
|
1199
|
+
}
|
|
1200
|
+
if (c === '"') {
|
|
1201
|
+
const start = i;
|
|
1202
|
+
i += 1;
|
|
1203
|
+
let escape = false;
|
|
1204
|
+
while (i < text.length) {
|
|
1205
|
+
if (escape) {
|
|
1206
|
+
escape = false;
|
|
1207
|
+
i += 1;
|
|
1208
|
+
continue;
|
|
1209
|
+
}
|
|
1210
|
+
if (text[i] === "\\") {
|
|
1211
|
+
escape = true;
|
|
1212
|
+
i += 1;
|
|
1213
|
+
continue;
|
|
1214
|
+
}
|
|
1215
|
+
if (text[i] === '"') {
|
|
1216
|
+
i += 1;
|
|
1217
|
+
break;
|
|
1218
|
+
}
|
|
1219
|
+
i += 1;
|
|
1220
|
+
}
|
|
1221
|
+
tokens.push({ type: "string", start, end: i, value: JSON.parse(text.slice(start, i)) });
|
|
1222
|
+
continue;
|
|
1223
|
+
}
|
|
1224
|
+
if ("{}[],:".includes(c)) {
|
|
1225
|
+
tokens.push({ type: c, start: i, end: i + 1 });
|
|
1226
|
+
i += 1;
|
|
1227
|
+
continue;
|
|
1228
|
+
}
|
|
1229
|
+
const atom = /^(?:-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)/.exec(text.slice(i));
|
|
1230
|
+
if (atom) {
|
|
1231
|
+
tokens.push({ type: "atom", start: i, end: i + atom[0].length, value: atom[0] });
|
|
1232
|
+
i += atom[0].length;
|
|
1233
|
+
continue;
|
|
1234
|
+
}
|
|
1235
|
+
throw new Error(`unexpected token at ${i}`);
|
|
1236
|
+
}
|
|
1237
|
+
return tokens;
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
function matchingBracket(tokens, openIdx) {
|
|
1241
|
+
const open = tokens[openIdx] && tokens[openIdx].type;
|
|
1242
|
+
if (open !== "{" && open !== "[") return -1;
|
|
1243
|
+
const close = open === "{" ? "}" : "]";
|
|
1244
|
+
let depth = 0;
|
|
1245
|
+
for (let i = openIdx; i < tokens.length; i += 1) {
|
|
1246
|
+
const type = tokens[i].type;
|
|
1247
|
+
if (type === "{" || type === "[") depth += 1;
|
|
1248
|
+
else if (type === "}" || type === "]") {
|
|
1249
|
+
depth -= 1;
|
|
1250
|
+
if (depth === 0) return type === close ? i : -1;
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
return -1;
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
function objectPairs(tokens, openIdx) {
|
|
1257
|
+
const closeIdx = matchingBracket(tokens, openIdx);
|
|
1258
|
+
if (closeIdx < 0) throw new Error("unbalanced braces");
|
|
1259
|
+
const pairs = [];
|
|
1260
|
+
let i = openIdx + 1;
|
|
1261
|
+
while (i < closeIdx) {
|
|
1262
|
+
const keyTok = tokens[i];
|
|
1263
|
+
if (!keyTok || keyTok.type !== "string" || !tokens[i + 1] || tokens[i + 1].type !== ":") {
|
|
1264
|
+
throw new Error("unexpected object entry");
|
|
1265
|
+
}
|
|
1266
|
+
const valIdx = i + 2;
|
|
1267
|
+
const val = tokens[valIdx];
|
|
1268
|
+
if (!val) throw new Error("missing value");
|
|
1269
|
+
let valEnd = valIdx;
|
|
1270
|
+
if (val.type === "{" || val.type === "[") {
|
|
1271
|
+
valEnd = matchingBracket(tokens, valIdx);
|
|
1272
|
+
if (valEnd < 0) throw new Error("unbalanced braces");
|
|
1273
|
+
}
|
|
1274
|
+
if (pairs.some((pair) => pair.key === keyTok.value)) {
|
|
1275
|
+
throw new Error(`duplicate key ${JSON.stringify(keyTok.value)}`);
|
|
1276
|
+
}
|
|
1277
|
+
pairs.push({ key: keyTok.value, keyIdx: i, valIdx, valEnd });
|
|
1278
|
+
i = valEnd + 1;
|
|
1279
|
+
if (i < closeIdx && tokens[i] && tokens[i].type === ",") i += 1;
|
|
1280
|
+
}
|
|
1281
|
+
return { closeIdx, pairs };
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
function arrayElements(tokens, openIdx, closeIdx) {
|
|
1285
|
+
const elements = [];
|
|
1286
|
+
let i = openIdx + 1;
|
|
1287
|
+
while (i < closeIdx) {
|
|
1288
|
+
const token = tokens[i];
|
|
1289
|
+
if (!token || token.type === ",") {
|
|
1290
|
+
i += 1;
|
|
1291
|
+
continue;
|
|
1292
|
+
}
|
|
1293
|
+
let end = i;
|
|
1294
|
+
if (token.type === "{" || token.type === "[") {
|
|
1295
|
+
end = matchingBracket(tokens, i);
|
|
1296
|
+
if (end < 0) throw new Error("unbalanced braces");
|
|
1297
|
+
}
|
|
1298
|
+
elements.push({ startIdx: i, endIdx: end });
|
|
1299
|
+
i = end + 1;
|
|
1300
|
+
}
|
|
1301
|
+
return elements;
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
function commandOfObject(tokens, startIdx) {
|
|
1305
|
+
const obj = objectPairs(tokens, startIdx);
|
|
1306
|
+
const cmd = obj.pairs.find((pair) => pair.key === "command");
|
|
1307
|
+
if (!cmd) return null;
|
|
1308
|
+
const val = tokens[cmd.valIdx];
|
|
1309
|
+
if (!val || val.type !== "string") return null;
|
|
1310
|
+
return { value: val.value, token: val };
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
function applyTextEdits(text, edits) {
|
|
1314
|
+
const ordered = edits.slice().sort((a, b) => b.start - a.start || b.end - a.end);
|
|
1315
|
+
let out = text;
|
|
1316
|
+
for (const edit of ordered) {
|
|
1317
|
+
out = out.slice(0, edit.start) + edit.insert + out.slice(edit.end);
|
|
1318
|
+
}
|
|
1319
|
+
return out;
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
function ownedDeletionEdits(tokens, elements) {
|
|
1323
|
+
const claimed = new Set();
|
|
1324
|
+
const edits = [];
|
|
1325
|
+
for (const el of elements) {
|
|
1326
|
+
const startTok = tokens[el.startIdx];
|
|
1327
|
+
const endTok = tokens[el.endIdx];
|
|
1328
|
+
let start = startTok.start;
|
|
1329
|
+
let end = endTok.end;
|
|
1330
|
+
const next = tokens[el.endIdx + 1];
|
|
1331
|
+
const prev = tokens[el.startIdx - 1];
|
|
1332
|
+
if (next && next.type === "," && !claimed.has(next.start)) {
|
|
1333
|
+
claimed.add(next.start);
|
|
1334
|
+
end = next.end;
|
|
1335
|
+
} else if (prev && prev.type === "," && !claimed.has(prev.start)) {
|
|
1336
|
+
claimed.add(prev.start);
|
|
1337
|
+
start = prev.start;
|
|
1338
|
+
}
|
|
1339
|
+
edits.push({ start, end, insert: "" });
|
|
1340
|
+
}
|
|
1341
|
+
return edits;
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
function renderEventEntry(command) {
|
|
1345
|
+
return `{ "command": ${JSON.stringify(command)} }`;
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
function editJsoncHooks(text, xrayByEvent, targetDir) {
|
|
1349
|
+
let tokens;
|
|
1350
|
+
try {
|
|
1351
|
+
tokens = tokenizeJsonc(text);
|
|
1352
|
+
} catch (err) {
|
|
1353
|
+
throw new Error(err.message || String(err));
|
|
1354
|
+
}
|
|
1355
|
+
if (!tokens.length || tokens[0].type !== "{") throw new Error("hooks.json must be a JSON object");
|
|
1356
|
+
const root = objectPairs(tokens, 0);
|
|
1357
|
+
const edits = [];
|
|
1358
|
+
const hooksPair = root.pairs.find((pair) => pair.key === "hooks");
|
|
1359
|
+
if (!hooksPair) {
|
|
1360
|
+
const inner = Object.entries(xrayByEvent)
|
|
1361
|
+
.map(([event, entries]) => `"${event}": [${renderEventEntry(entries[0].command)}]`)
|
|
1362
|
+
.join(", ");
|
|
1363
|
+
const needsComma = root.pairs.length > 0;
|
|
1364
|
+
edits.push({
|
|
1365
|
+
start: tokens[root.closeIdx].start,
|
|
1366
|
+
end: tokens[root.closeIdx].start,
|
|
1367
|
+
insert: `${needsComma ? ", " : ""}"hooks": { ${inner} }`,
|
|
1368
|
+
});
|
|
1369
|
+
return applyTextEdits(text, edits);
|
|
1370
|
+
}
|
|
1371
|
+
if (tokens[hooksPair.valIdx].type !== "{") throw new Error("hooks is not an object");
|
|
1372
|
+
const hooksObj = objectPairs(tokens, hooksPair.valIdx);
|
|
1373
|
+
const missing = [];
|
|
1374
|
+
for (const [event, entries] of Object.entries(xrayByEvent)) {
|
|
1375
|
+
const command = entries[0].command;
|
|
1376
|
+
const pair = hooksObj.pairs.find((item) => item.key === event);
|
|
1377
|
+
if (!pair) {
|
|
1378
|
+
missing.push([event, command]);
|
|
1379
|
+
continue;
|
|
1380
|
+
}
|
|
1381
|
+
if (tokens[pair.valIdx].type !== "[") throw new Error(`${event} is not an array`);
|
|
1382
|
+
const elements = arrayElements(tokens, pair.valIdx, pair.valEnd);
|
|
1383
|
+
const owned = [];
|
|
1384
|
+
let coveredByRunner = false;
|
|
1385
|
+
for (const el of elements) {
|
|
1386
|
+
if (tokens[el.startIdx].type !== "{") continue;
|
|
1387
|
+
const cmd = commandOfObject(tokens, el.startIdx);
|
|
1388
|
+
if (!cmd) continue;
|
|
1389
|
+
if (isXrayHookCommand(cmd.value)) owned.push({ el, cmd });
|
|
1390
|
+
else if (commandAlreadyRunsXrayHook(cmd.value, targetDir)) coveredByRunner = true;
|
|
1391
|
+
}
|
|
1392
|
+
if (coveredByRunner) {
|
|
1393
|
+
if (owned.length > 0) edits.push(...ownedDeletionEdits(tokens, owned.map((item) => item.el)));
|
|
1394
|
+
continue;
|
|
1395
|
+
}
|
|
1396
|
+
if (owned.length === 0) {
|
|
1397
|
+
edits.push({
|
|
1398
|
+
start: tokens[pair.valEnd].start,
|
|
1399
|
+
end: tokens[pair.valEnd].start,
|
|
1400
|
+
insert: `${elements.length > 0 ? ", " : ""}${renderEventEntry(command)}`,
|
|
1401
|
+
});
|
|
1402
|
+
continue;
|
|
1403
|
+
}
|
|
1404
|
+
const first = owned[0];
|
|
1405
|
+
if (first.cmd.value !== command) {
|
|
1406
|
+
edits.push({
|
|
1407
|
+
start: first.cmd.token.start,
|
|
1408
|
+
end: first.cmd.token.end,
|
|
1409
|
+
insert: JSON.stringify(command),
|
|
1410
|
+
});
|
|
1411
|
+
}
|
|
1412
|
+
if (owned.length > 1) {
|
|
1413
|
+
edits.push(...ownedDeletionEdits(tokens, owned.slice(1).map((item) => item.el)));
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
if (missing.length > 0) {
|
|
1417
|
+
const rendered = missing
|
|
1418
|
+
.map(([event, command]) => `"${event}": [${renderEventEntry(command)}]`)
|
|
1419
|
+
.join(", ");
|
|
1420
|
+
edits.push({
|
|
1421
|
+
start: tokens[hooksObj.closeIdx].start,
|
|
1422
|
+
end: tokens[hooksObj.closeIdx].start,
|
|
1423
|
+
insert: `${hooksObj.pairs.length > 0 ? ", " : ""}${rendered}`,
|
|
1424
|
+
});
|
|
1425
|
+
}
|
|
1426
|
+
return applyTextEdits(text, edits);
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
function renderWornHooks(originalText, hooksPath, xrayByEvent, targetDir) {
|
|
1430
|
+
parseHooksText(originalText, hooksPath);
|
|
1431
|
+
try {
|
|
1432
|
+
return editJsoncHooks(originalText, xrayByEvent, targetDir);
|
|
1433
|
+
} catch (err) {
|
|
1434
|
+
refuseHooksEdit(hooksPath, err.message || String(err));
|
|
1435
|
+
}
|
|
1436
|
+
return "";
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
function stripOwnedHookEntries(text) {
|
|
1440
|
+
const tokens = tokenizeJsonc(text);
|
|
1441
|
+
if (!tokens.length || tokens[0].type !== "{") return text;
|
|
1442
|
+
const root = objectPairs(tokens, 0);
|
|
1443
|
+
const hooksPair = root.pairs.find((pair) => pair.key === "hooks");
|
|
1444
|
+
if (!hooksPair || tokens[hooksPair.valIdx].type !== "{") return text;
|
|
1445
|
+
const hooksObj = objectPairs(tokens, hooksPair.valIdx);
|
|
1446
|
+
const owned = [];
|
|
1447
|
+
for (const pair of hooksObj.pairs) {
|
|
1448
|
+
if (tokens[pair.valIdx].type !== "[") continue;
|
|
1449
|
+
const elements = arrayElements(tokens, pair.valIdx, pair.valEnd);
|
|
1450
|
+
for (const el of elements) {
|
|
1451
|
+
if (tokens[el.startIdx].type !== "{") continue;
|
|
1452
|
+
const cmd = commandOfObject(tokens, el.startIdx);
|
|
1453
|
+
if (cmd && isXrayHookCommand(cmd.value)) owned.push(el);
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
return stripDanglingCommas(stripEmptyShippedEvents(applyTextEdits(text, ownedDeletionEdits(tokens, owned))));
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
function stripDanglingCommas(text) {
|
|
1460
|
+
const tokens = tokenizeJsonc(text);
|
|
1461
|
+
const edits = [];
|
|
1462
|
+
for (let i = 0; i < tokens.length; i += 1) {
|
|
1463
|
+
if (tokens[i].type !== ",") continue;
|
|
1464
|
+
const next = tokens[i + 1];
|
|
1465
|
+
if (next && (next.type === "}" || next.type === "]")) {
|
|
1466
|
+
edits.push({ start: tokens[i].start, end: next.start, insert: "" });
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
return applyTextEdits(text, edits);
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
function stripEmptyShippedEvents(text) {
|
|
1473
|
+
const shipped = new Set(CURSOR_HOOK_EVENTS.map(([event]) => event));
|
|
1474
|
+
const tokens = tokenizeJsonc(text);
|
|
1475
|
+
if (!tokens.length || tokens[0].type !== "{") return text;
|
|
1476
|
+
const root = objectPairs(tokens, 0);
|
|
1477
|
+
const hooksPair = root.pairs.find((pair) => pair.key === "hooks");
|
|
1478
|
+
if (!hooksPair || tokens[hooksPair.valIdx].type !== "{") return text;
|
|
1479
|
+
const hooksObj = objectPairs(tokens, hooksPair.valIdx);
|
|
1480
|
+
const empty = [];
|
|
1481
|
+
for (const pair of hooksObj.pairs) {
|
|
1482
|
+
if (!shipped.has(pair.key) || tokens[pair.valIdx].type !== "[") continue;
|
|
1483
|
+
if (arrayElements(tokens, pair.valIdx, pair.valEnd).length === 0) {
|
|
1484
|
+
empty.push({ startIdx: pair.keyIdx, endIdx: pair.valEnd });
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
return applyTextEdits(text, ownedDeletionEdits(tokens, empty));
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
/**
|
|
1491
|
+
* Keep every non-0xray entry. Add or replace only 0xray's shipped commands.
|
|
1492
|
+
* A second pass on the result is stable (same keys, same commands).
|
|
1493
|
+
*/
|
|
1494
|
+
function mergeInstalledCursorHooks(existing, xrayByEvent) {
|
|
1495
|
+
const sourceHooks =
|
|
1496
|
+
existing && existing.hooks && typeof existing.hooks === "object" && !Array.isArray(existing.hooks)
|
|
1497
|
+
? existing.hooks
|
|
1498
|
+
: {};
|
|
1499
|
+
const names = Object.keys(sourceHooks);
|
|
1500
|
+
for (const name of Object.keys(xrayByEvent)) {
|
|
1501
|
+
if (!names.includes(name)) names.push(name);
|
|
1502
|
+
}
|
|
1503
|
+
const hooks = {};
|
|
1504
|
+
for (const name of names) {
|
|
1505
|
+
const current = Array.isArray(sourceHooks[name]) ? sourceHooks[name] : [];
|
|
1506
|
+
const shipped = xrayByEvent[name];
|
|
1507
|
+
if (!shipped) {
|
|
1508
|
+
hooks[name] = current.slice();
|
|
1509
|
+
continue;
|
|
1510
|
+
}
|
|
1511
|
+
const command = shipped[0].command;
|
|
1512
|
+
let replaced = false;
|
|
1513
|
+
const next = [];
|
|
1514
|
+
for (const entry of current) {
|
|
1515
|
+
const cmd = entry && typeof entry === "object" ? entry.command : "";
|
|
1516
|
+
if (isXrayHookCommand(cmd)) {
|
|
1517
|
+
if (!replaced) {
|
|
1518
|
+
next.push({ ...entry, command });
|
|
1519
|
+
replaced = true;
|
|
1520
|
+
}
|
|
1521
|
+
continue;
|
|
1522
|
+
}
|
|
1523
|
+
next.push(entry);
|
|
1524
|
+
}
|
|
1525
|
+
if (!replaced) next.push({ command });
|
|
1526
|
+
hooks[name] = next;
|
|
1527
|
+
}
|
|
1528
|
+
const doc = {};
|
|
1529
|
+
if (existing && typeof existing === "object" && !Array.isArray(existing)) {
|
|
1530
|
+
for (const key of Object.keys(existing)) {
|
|
1531
|
+
if (key !== "hooks") doc[key] = existing[key];
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
if (doc.version == null) doc.version = 1;
|
|
1535
|
+
doc.hooks = hooks;
|
|
1536
|
+
return doc;
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
function serializeHooksDoc(doc) {
|
|
1540
|
+
return `${JSON.stringify(doc, null, 2)}\n`;
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
function wearStateDir(targetDir) {
|
|
1544
|
+
return path.join(path.resolve(targetDir), ".xray", "state", "cursor-hook-wear");
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
/**
|
|
1548
|
+
* The snapshot lives in the project, outside node_modules. Append its path to
|
|
1549
|
+
* $GIT_DIR/info/exclude when nothing already ignores it. exclude is local git
|
|
1550
|
+
* metadata, so a fresh repo's `git status` does not grow a new `.gitignore`.
|
|
1551
|
+
*/
|
|
1552
|
+
function ensureWearStateGitignored(targetDir) {
|
|
1553
|
+
const stateDir = wearStateDir(targetDir);
|
|
1554
|
+
const probe = path.join(stateDir, "meta.json");
|
|
1555
|
+
try {
|
|
1556
|
+
execFileSync("git", ["check-ignore", "-q", "--", probe], {
|
|
1557
|
+
cwd: targetDir,
|
|
1558
|
+
stdio: "ignore",
|
|
1559
|
+
});
|
|
1560
|
+
return;
|
|
1561
|
+
} catch (err) {
|
|
1562
|
+
const notARepo = !err || err.code === "ENOENT" || err.status === 128;
|
|
1563
|
+
const notIgnored = Boolean(err && err.status === 1);
|
|
1564
|
+
if (notARepo || !notIgnored) return;
|
|
1565
|
+
}
|
|
1566
|
+
let top = "";
|
|
1567
|
+
let excludeRel = "";
|
|
1568
|
+
try {
|
|
1569
|
+
top = execFileSync("git", ["rev-parse", "--show-toplevel"], {
|
|
1570
|
+
cwd: targetDir,
|
|
1571
|
+
encoding: "utf8",
|
|
1572
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1573
|
+
}).trim();
|
|
1574
|
+
excludeRel = execFileSync("git", ["rev-parse", "--git-path", "info/exclude"], {
|
|
1575
|
+
cwd: targetDir,
|
|
1576
|
+
encoding: "utf8",
|
|
1577
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1578
|
+
}).trim();
|
|
1579
|
+
} catch {
|
|
1580
|
+
return;
|
|
1581
|
+
}
|
|
1582
|
+
if (!top || !excludeRel) return;
|
|
1583
|
+
const rel = path.relative(top, stateDir).split(path.sep).join("/");
|
|
1584
|
+
if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return;
|
|
1585
|
+
const pattern = `${rel}/`;
|
|
1586
|
+
const excludeFile = path.resolve(targetDir, excludeRel);
|
|
1587
|
+
try {
|
|
1588
|
+
fs.mkdirSync(path.dirname(excludeFile), { recursive: true });
|
|
1589
|
+
const existing = fs.existsSync(excludeFile) ? fs.readFileSync(excludeFile, "utf8") : "";
|
|
1590
|
+
if (existing.split("\n").some((line) => line.trim() === pattern)) return;
|
|
1591
|
+
const suffix = existing.length === 0 || existing.endsWith("\n") ? "" : "\n";
|
|
1592
|
+
fs.appendFileSync(excludeFile, `${suffix}${pattern}\n`);
|
|
1593
|
+
} catch {
|
|
1594
|
+
// exclude not writable — snapshot is still under .xray/state/
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
|
|
1598
|
+
function wearStatePaths(targetDir) {
|
|
1599
|
+
const dir = wearStateDir(targetDir);
|
|
1600
|
+
return {
|
|
1601
|
+
dir,
|
|
1602
|
+
meta: path.join(dir, "meta.json"),
|
|
1603
|
+
backup: path.join(dir, CURSOR_WEAR_BACKUP),
|
|
1604
|
+
written: path.join(dir, "hooks.json.written"),
|
|
1605
|
+
};
|
|
1606
|
+
}
|
|
1607
|
+
|
|
1608
|
+
function textHasDistHookEntries(text) {
|
|
1609
|
+
return /node_modules\/0xray\/dist\/integrations\/cursor\/hooks\/[\w.-]+\.sh/.test(String(text || ""));
|
|
1610
|
+
}
|
|
1611
|
+
|
|
1612
|
+
function userBytesBeforeWear(previousText) {
|
|
1613
|
+
if (previousText == null) return null;
|
|
1614
|
+
if (!textHasDistHookEntries(previousText)) return previousText;
|
|
1615
|
+
return stripOwnedHookEntries(previousText);
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
function assertCursorWearGit(targetDir) {
|
|
1619
|
+
try {
|
|
1620
|
+
execFileSync("git", ["--version"], { stdio: "ignore" });
|
|
1621
|
+
} catch {
|
|
1622
|
+
throw new Error("cursor-wear: git is missing");
|
|
1623
|
+
}
|
|
1624
|
+
let bare = "";
|
|
1625
|
+
try {
|
|
1626
|
+
bare = execFileSync("git", ["rev-parse", "--is-bare-repository"], {
|
|
1627
|
+
cwd: targetDir,
|
|
1628
|
+
encoding: "utf8",
|
|
1629
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1630
|
+
}).trim();
|
|
1631
|
+
} catch {
|
|
1632
|
+
throw new Error("cursor-wear: not a git work tree");
|
|
1633
|
+
}
|
|
1634
|
+
if (bare === "true") throw new Error("cursor-wear: bare repository");
|
|
1635
|
+
let inside = "";
|
|
1636
|
+
try {
|
|
1637
|
+
inside = execFileSync("git", ["rev-parse", "--is-inside-work-tree"], {
|
|
1638
|
+
cwd: targetDir,
|
|
1639
|
+
encoding: "utf8",
|
|
1640
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1641
|
+
}).trim();
|
|
1642
|
+
} catch {
|
|
1643
|
+
throw new Error("cursor-wear: not a git work tree");
|
|
1644
|
+
}
|
|
1645
|
+
if (inside !== "true") throw new Error("cursor-wear: not a git work tree");
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
function isGitTracked(targetDir, rel) {
|
|
1649
|
+
try {
|
|
1650
|
+
execFileSync("git", ["ls-files", "--error-unmatch", "--", rel], {
|
|
1651
|
+
cwd: targetDir,
|
|
1652
|
+
stdio: "ignore",
|
|
1653
|
+
});
|
|
1654
|
+
return true;
|
|
1655
|
+
} catch {
|
|
1656
|
+
return false;
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
function byteMismatch(expected, actual) {
|
|
1661
|
+
if (expected == null && actual == null) return "both missing";
|
|
1662
|
+
if (expected == null) return `file exists (${actual.length} bytes) but the snapshot has no written copy`;
|
|
1663
|
+
if (actual == null) return `file is missing; snapshot wrote ${expected.length} bytes`;
|
|
1664
|
+
const a = expected.toString("utf8");
|
|
1665
|
+
const b = actual.toString("utf8");
|
|
1666
|
+
let i = 0;
|
|
1667
|
+
const n = Math.min(a.length, b.length);
|
|
1668
|
+
while (i < n && a.charCodeAt(i) === b.charCodeAt(i)) i += 1;
|
|
1669
|
+
return `differs at byte ${i} (snapshot ${expected.length} bytes, file ${actual.length} bytes)`;
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
function removeWearExcludeLine(targetDir) {
|
|
1673
|
+
let top = "";
|
|
1674
|
+
let excludeRel = "";
|
|
1675
|
+
try {
|
|
1676
|
+
top = execFileSync("git", ["rev-parse", "--show-toplevel"], {
|
|
1677
|
+
cwd: targetDir,
|
|
1678
|
+
encoding: "utf8",
|
|
1679
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1680
|
+
}).trim();
|
|
1681
|
+
excludeRel = execFileSync("git", ["rev-parse", "--git-path", "info/exclude"], {
|
|
1682
|
+
cwd: targetDir,
|
|
1683
|
+
encoding: "utf8",
|
|
1684
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1685
|
+
}).trim();
|
|
1686
|
+
} catch {
|
|
1687
|
+
return;
|
|
1688
|
+
}
|
|
1689
|
+
if (!top || !excludeRel) return;
|
|
1690
|
+
const rel = path.relative(top, wearStateDir(targetDir)).split(path.sep).join("/");
|
|
1691
|
+
if (!rel || rel.startsWith("..")) return;
|
|
1692
|
+
const pattern = `${rel}/`;
|
|
1693
|
+
const excludeFile = path.resolve(targetDir, excludeRel);
|
|
1694
|
+
if (!fs.existsSync(excludeFile)) return;
|
|
1695
|
+
const lines = fs.readFileSync(excludeFile, "utf8").split("\n");
|
|
1696
|
+
const next = lines.filter((line) => line.trim() !== pattern);
|
|
1697
|
+
if (next.length === lines.length) return;
|
|
1698
|
+
fs.writeFileSync(excludeFile, next.join("\n"));
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1701
|
+
function saveCursorWearSnapshot(targetDir, previousText, writtenBody) {
|
|
1702
|
+
ensureWearStateGitignored(targetDir);
|
|
1703
|
+
const paths = wearStatePaths(targetDir);
|
|
1704
|
+
fs.mkdirSync(paths.dir, { recursive: true });
|
|
1705
|
+
let existed;
|
|
1706
|
+
let cursorDirExisted;
|
|
1707
|
+
let also = [];
|
|
1708
|
+
if (fs.existsSync(paths.meta)) {
|
|
1709
|
+
const prev = JSON.parse(fs.readFileSync(paths.meta, "utf8"));
|
|
1710
|
+
existed = Boolean(prev.existed);
|
|
1711
|
+
cursorDirExisted = Boolean(prev.cursorDirExisted);
|
|
1712
|
+
also = Array.isArray(prev.also) ? prev.also : [];
|
|
1713
|
+
} else {
|
|
1714
|
+
existed = previousText != null;
|
|
1715
|
+
cursorDirExisted = fs.existsSync(path.join(targetDir, ".cursor"));
|
|
1716
|
+
}
|
|
1717
|
+
const backup = existed ? userBytesBeforeWear(previousText) : null;
|
|
1718
|
+
if (backup != null) fs.writeFileSync(paths.backup, backup);
|
|
1719
|
+
else if (fs.existsSync(paths.backup)) fs.unlinkSync(paths.backup);
|
|
1720
|
+
const meta = { version: 1, existed, cursorDirExisted, also };
|
|
1721
|
+
fs.writeFileSync(paths.written, writtenBody);
|
|
1722
|
+
fs.writeFileSync(paths.meta, `${JSON.stringify(meta, null, 2)}\n`);
|
|
1723
|
+
return { paths, meta };
|
|
1724
|
+
}
|
|
1725
|
+
|
|
1726
|
+
function saveWearState(paths, meta) {
|
|
1727
|
+
fs.mkdirSync(paths.dir, { recursive: true });
|
|
1728
|
+
fs.writeFileSync(paths.meta, `${JSON.stringify(meta, null, 2)}\n`);
|
|
1729
|
+
}
|
|
1730
|
+
|
|
1731
|
+
function resolveGitToplevel(targetDir) {
|
|
1732
|
+
try {
|
|
1733
|
+
const top = execFileSync("git", ["rev-parse", "--show-toplevel"], {
|
|
1734
|
+
cwd: targetDir,
|
|
1735
|
+
encoding: "utf8",
|
|
1736
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1737
|
+
}).trim();
|
|
1738
|
+
if (!top) return null;
|
|
1739
|
+
const resolved = path.resolve(top);
|
|
1740
|
+
if (resolved === path.resolve(targetDir)) return null;
|
|
1741
|
+
return resolved;
|
|
1742
|
+
} catch {
|
|
1743
|
+
return null;
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
function linkedWearRoots(targetDir) {
|
|
1748
|
+
const roots = [];
|
|
1749
|
+
const add = (root) => {
|
|
1750
|
+
if (!root) return;
|
|
1751
|
+
const resolved = path.resolve(root);
|
|
1752
|
+
if (resolved === path.resolve(targetDir)) return;
|
|
1753
|
+
if (roots.some((item) => path.resolve(item) === resolved)) return;
|
|
1754
|
+
roots.push(resolved);
|
|
1755
|
+
};
|
|
1756
|
+
add(resolveCursorWorkspaceRoot(targetDir));
|
|
1757
|
+
add(resolveGitToplevel(targetDir));
|
|
1758
|
+
roots.sort();
|
|
1759
|
+
return roots;
|
|
1760
|
+
}
|
|
1761
|
+
|
|
1762
|
+
function removeDirIfEmpty(dir) {
|
|
1763
|
+
try {
|
|
1764
|
+
fs.rmdirSync(dir);
|
|
1765
|
+
} catch {
|
|
1766
|
+
// still holds user files
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
function assertWearSnapshotReusable(resolvedTarget, hooksPath) {
|
|
1771
|
+
const paths = wearStatePaths(resolvedTarget);
|
|
1772
|
+
if (!fs.existsSync(paths.meta)) return;
|
|
1773
|
+
const current = fs.existsSync(hooksPath) ? fs.readFileSync(hooksPath) : null;
|
|
1774
|
+
const written = fs.existsSync(paths.written) ? fs.readFileSync(paths.written) : null;
|
|
1775
|
+
const same =
|
|
1776
|
+
(current == null && written == null) ||
|
|
1777
|
+
(current != null && written != null && current.equals(written));
|
|
1778
|
+
if (same) return;
|
|
1779
|
+
throw new Error(`cursor-wear: ${hooksPath} differs from the last wear; refusing to overwrite`);
|
|
1780
|
+
}
|
|
1781
|
+
|
|
1782
|
+
/**
|
|
1783
|
+
* Merge the five shipped Cursor hooks into the target project's
|
|
1784
|
+
* `.cursor/hooks.json`. Writes only `targetDir`. An event whose command
|
|
1785
|
+
* already runs xray-cloud-hook.sh is left alone, so a committed suited
|
|
1786
|
+
* hooks.json is not given a second copy. Pass `{ outerRoots: true }` to also
|
|
1787
|
+
* write outer paths; each one is printed.
|
|
1788
|
+
* The snapshot is `<project>/.xray/state/cursor-hook-wear/` (gitignored, not packed).
|
|
1789
|
+
* An already-worn file is never stored as the pre-wear backup.
|
|
1790
|
+
* A second wear reuses the snapshot only when hooks.json still matches the last write.
|
|
1791
|
+
*/
|
|
1792
|
+
function wearCursorHooks(targetDir, packageRoot, log, opts) {
|
|
1793
|
+
const write = typeof log === "function" ? log : () => {};
|
|
1794
|
+
const options = opts || {};
|
|
1795
|
+
const resolvedTarget = path.resolve(targetDir);
|
|
1796
|
+
const resolvedPackage = path.resolve(packageRoot);
|
|
1797
|
+
assertCursorWearGit(resolvedTarget);
|
|
1798
|
+
if (!isConsumerInstall(resolvedPackage, resolvedTarget) || !consumerDistHooksReady(resolvedPackage)) {
|
|
1799
|
+
return fastenCursorHooksAt(resolvedTarget, resolvedPackage, write);
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
const hooksPath = path.join(resolvedTarget, ".cursor", "hooks.json");
|
|
1803
|
+
assertWearSnapshotReusable(resolvedTarget, hooksPath);
|
|
1804
|
+
const xrayByEvent = installedCursorHookEntries(resolvedTarget, resolvedPackage);
|
|
1805
|
+
const originalText = fs.existsSync(hooksPath) ? fs.readFileSync(hooksPath, "utf8") : null;
|
|
1806
|
+
const body =
|
|
1807
|
+
originalText == null
|
|
1808
|
+
? serializeHooksDoc(mergeInstalledCursorHooks(null, xrayByEvent))
|
|
1809
|
+
: renderWornHooks(originalText, hooksPath, xrayByEvent, resolvedTarget);
|
|
1810
|
+
const changed = originalText == null || body !== originalText;
|
|
1811
|
+
const statePaths = wearStatePaths(resolvedTarget);
|
|
1812
|
+
const alreadyWorn = textHasDistHookEntries(originalText || "");
|
|
1813
|
+
let snap = null;
|
|
1814
|
+
if (changed || alreadyWorn || fs.existsSync(statePaths.meta)) {
|
|
1815
|
+
snap = saveCursorWearSnapshot(resolvedTarget, originalText, body);
|
|
1816
|
+
}
|
|
1817
|
+
if (changed) {
|
|
1818
|
+
fs.mkdirSync(path.dirname(hooksPath), { recursive: true });
|
|
1819
|
+
fs.writeFileSync(hooksPath, body);
|
|
1820
|
+
} else if (!snap) {
|
|
1821
|
+
write("cursor-bridge", "hooks.json already runs these hooks", "info", { path: hooksPath });
|
|
1822
|
+
}
|
|
1823
|
+
|
|
1824
|
+
if (options.outerRoots === true) {
|
|
1825
|
+
if (!snap) snap = saveCursorWearSnapshot(resolvedTarget, originalText, body);
|
|
1826
|
+
snap.meta.also = linkedWearRoots(resolvedTarget);
|
|
1827
|
+
saveWearState(snap.paths, snap.meta);
|
|
1828
|
+
for (const extra of snap.meta.also) {
|
|
1829
|
+
wearCursorHooks(extra, resolvedPackage, write, { outerRoots: false });
|
|
1830
|
+
process.stdout.write(`cursor-wear: wrote outer hooks at ${extra}\n`);
|
|
1831
|
+
}
|
|
1832
|
+
saveWearState(snap.paths, snap.meta);
|
|
1833
|
+
}
|
|
1834
|
+
write("cursor-bridge", "hooks.json wired to installed dist", "info", { path: hooksPath });
|
|
1835
|
+
return hooksPath;
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1838
|
+
/**
|
|
1839
|
+
* Restore `.cursor/hooks.json` from the project snapshot only when the file
|
|
1840
|
+
* still matches what wear wrote and the restored bytes match that snapshot.
|
|
1841
|
+
* A mismatch or a file that cannot be parsed leaves the snapshot in place.
|
|
1842
|
+
*/
|
|
1843
|
+
function unwearCursorHooks(targetDir, log) {
|
|
1844
|
+
const write = typeof log === "function" ? log : () => {};
|
|
1845
|
+
const resolvedTarget = path.resolve(targetDir);
|
|
1846
|
+
assertCursorWearGit(resolvedTarget);
|
|
1847
|
+
const paths = wearStatePaths(resolvedTarget);
|
|
1848
|
+
const cursor = path.join(resolvedTarget, ".cursor");
|
|
1849
|
+
const hooksPath = path.join(cursor, "hooks.json");
|
|
1850
|
+
if (!fs.existsSync(paths.meta)) {
|
|
1851
|
+
process.stderr.write(`cursor-wear: no snapshot at ${paths.dir}\n`);
|
|
1852
|
+
return false;
|
|
1853
|
+
}
|
|
1854
|
+
let meta;
|
|
1855
|
+
try {
|
|
1856
|
+
meta = JSON.parse(fs.readFileSync(paths.meta, "utf8"));
|
|
1857
|
+
} catch (err) {
|
|
1858
|
+
process.stderr.write(
|
|
1859
|
+
`cursor-wear: snapshot does not match the current file (${err.message}); snapshot kept\n`,
|
|
1860
|
+
);
|
|
1861
|
+
return false;
|
|
1862
|
+
}
|
|
1863
|
+
const current = fs.existsSync(hooksPath) ? fs.readFileSync(hooksPath) : null;
|
|
1864
|
+
const written = fs.existsSync(paths.written) ? fs.readFileSync(paths.written) : null;
|
|
1865
|
+
const matches =
|
|
1866
|
+
Boolean(current && written && current.equals(written)) || (current == null && written == null);
|
|
1867
|
+
if (!matches) {
|
|
1868
|
+
let detail = byteMismatch(written, current);
|
|
1869
|
+
if (current) {
|
|
1870
|
+
try {
|
|
1871
|
+
parseHooksText(current.toString("utf8"), hooksPath);
|
|
1872
|
+
} catch (err) {
|
|
1873
|
+
detail = `cannot be parsed (${err.message})`;
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
process.stderr.write(`cursor-wear: ${hooksPath} ${detail}; snapshot kept\n`);
|
|
1877
|
+
return false;
|
|
1878
|
+
}
|
|
1879
|
+
if (meta.existed) {
|
|
1880
|
+
if (!fs.existsSync(paths.backup)) {
|
|
1881
|
+
process.stderr.write(`cursor-wear: ${hooksPath} backup missing; snapshot kept\n`);
|
|
1882
|
+
return false;
|
|
1883
|
+
}
|
|
1884
|
+
const backup = fs.readFileSync(paths.backup);
|
|
1885
|
+
fs.copyFileSync(paths.backup, hooksPath);
|
|
1886
|
+
if (!fs.readFileSync(hooksPath).equals(backup)) {
|
|
1887
|
+
process.stderr.write(
|
|
1888
|
+
`cursor-wear: ${hooksPath} restored bytes differ from the snapshot; snapshot kept\n`,
|
|
1889
|
+
);
|
|
1890
|
+
return false;
|
|
1891
|
+
}
|
|
1892
|
+
} else if (isGitTracked(resolvedTarget, ".cursor/hooks.json")) {
|
|
1893
|
+
process.stderr.write(`cursor-wear: ${hooksPath} is committed; refusing to delete it; snapshot kept\n`);
|
|
1894
|
+
return false;
|
|
1895
|
+
} else if (fs.existsSync(hooksPath)) {
|
|
1896
|
+
fs.unlinkSync(hooksPath);
|
|
1897
|
+
}
|
|
1898
|
+
const also = meta.also || [];
|
|
1899
|
+
fs.rmSync(paths.dir, { recursive: true, force: true });
|
|
1900
|
+
removeWearExcludeLine(resolvedTarget);
|
|
1901
|
+
const stateDir = path.join(resolvedTarget, ".xray", "state");
|
|
1902
|
+
removeDirIfEmpty(stateDir);
|
|
1903
|
+
removeDirIfEmpty(path.join(resolvedTarget, ".xray"));
|
|
1904
|
+
if (!meta.cursorDirExisted) removeDirIfEmpty(cursor);
|
|
1905
|
+
for (const extra of also) unwearCursorHooks(extra, write);
|
|
1906
|
+
write("cursor-bridge", "hooks.json restored", "info", { path: hooksPath });
|
|
1907
|
+
return true;
|
|
1908
|
+
}
|
|
1909
|
+
|
|
981
1910
|
function installCursorBridge(targetDir, packageRoot, log) {
|
|
982
|
-
const
|
|
983
|
-
const
|
|
984
|
-
|
|
985
|
-
fastenCursorHooksAt(
|
|
1911
|
+
const consumerDist = isConsumerInstall(packageRoot, targetDir) && consumerDistHooksReady(packageRoot);
|
|
1912
|
+
const dest = consumerDist
|
|
1913
|
+
? wearCursorHooks(targetDir, packageRoot, log)
|
|
1914
|
+
: fastenCursorHooksAt(targetDir, packageRoot, log);
|
|
1915
|
+
if (!consumerDist) {
|
|
1916
|
+
const workspace = resolveCursorWorkspaceRoot(targetDir);
|
|
1917
|
+
if (workspace && path.resolve(workspace) !== path.resolve(targetDir)) {
|
|
1918
|
+
fastenCursorHooksAt(workspace, packageRoot, log);
|
|
1919
|
+
}
|
|
986
1920
|
}
|
|
987
1921
|
reloadCursorHostHooks(log);
|
|
988
1922
|
return dest;
|
|
989
1923
|
}
|
|
990
1924
|
|
|
991
|
-
function installGitHooks(packageRoot, log) {
|
|
1925
|
+
function installGitHooks(packageRoot, log, cwd) {
|
|
992
1926
|
const installHooks = path.join(packageRoot, "scripts", "hooks", "install-hooks.cjs");
|
|
993
1927
|
if (!fs.existsSync(installHooks)) return;
|
|
994
1928
|
try {
|
|
995
|
-
|
|
1929
|
+
execFileSync(process.execPath, [installHooks], { stdio: "pipe", cwd: cwd || process.cwd() });
|
|
996
1930
|
log("hooks", "pre-commit hook installed", "info");
|
|
997
1931
|
} catch {
|
|
998
1932
|
// non-git or hook failure — not blocking
|
|
999
1933
|
}
|
|
1000
1934
|
}
|
|
1001
1935
|
|
|
1936
|
+
function assertSetupGit(targetDir) {
|
|
1937
|
+
assertCursorWearGit(targetDir);
|
|
1938
|
+
let top = "";
|
|
1939
|
+
try {
|
|
1940
|
+
top = execFileSync("git", ["rev-parse", "--show-toplevel"], {
|
|
1941
|
+
cwd: targetDir,
|
|
1942
|
+
encoding: "utf8",
|
|
1943
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1944
|
+
}).trim();
|
|
1945
|
+
} catch {
|
|
1946
|
+
throw new Error("cursor-wear: not a git work tree");
|
|
1947
|
+
}
|
|
1948
|
+
if (path.resolve(top) !== path.resolve(targetDir)) {
|
|
1949
|
+
throw new Error("setup: work tree points elsewhere");
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1953
|
+
function setupProjectBridges(opts) {
|
|
1954
|
+
const packageRoot = path.resolve(opts.packageRoot);
|
|
1955
|
+
const targetDir = path.resolve(opts.targetDir);
|
|
1956
|
+
const log =
|
|
1957
|
+
typeof opts.log === "function"
|
|
1958
|
+
? opts.log
|
|
1959
|
+
: () => {
|
|
1960
|
+
/* noop */
|
|
1961
|
+
};
|
|
1962
|
+
assertSetupGit(targetDir);
|
|
1963
|
+
deployProjectMcpJson(targetDir, log);
|
|
1964
|
+
installOpencodeBridge(targetDir, packageRoot, log);
|
|
1965
|
+
installGrokBridge(targetDir, packageRoot, log);
|
|
1966
|
+
installHermesBridge(targetDir, packageRoot, log);
|
|
1967
|
+
installOpenclawBridge(targetDir, packageRoot, log);
|
|
1968
|
+
if (opts.gitHooks === true) installGitHooks(packageRoot, log, targetDir);
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1002
1971
|
/**
|
|
1003
1972
|
* Framework dogfood: do not deploy consumer copies over the package,
|
|
1004
1973
|
* but keep Grok discovery hooks hot and enable Repertoire when it resolves.
|
|
@@ -1031,8 +2000,9 @@ function installFrameworkDogfoodWear(packageRoot, log) {
|
|
|
1031
2000
|
function installAllBridges(opts) {
|
|
1032
2001
|
const packageRoot = path.resolve(opts.packageRoot);
|
|
1033
2002
|
const targetDir = path.resolve(opts.targetDir);
|
|
2003
|
+
const logFn = opts.log;
|
|
1034
2004
|
const log =
|
|
1035
|
-
|
|
2005
|
+
logFn ||
|
|
1036
2006
|
((_component, _action, _status, _details) => {
|
|
1037
2007
|
/* noop */
|
|
1038
2008
|
});
|
|
@@ -1055,7 +2025,6 @@ function installAllBridges(opts) {
|
|
|
1055
2025
|
installHermesBridge(targetDir, packageRoot, log);
|
|
1056
2026
|
installOpenclawBridge(targetDir, packageRoot, log);
|
|
1057
2027
|
installCursorBridge(targetDir, packageRoot, log);
|
|
1058
|
-
installGitHooks(packageRoot, log);
|
|
1059
2028
|
|
|
1060
2029
|
log("install-bridges", "4-platform + cursor wear complete", "success");
|
|
1061
2030
|
}
|
|
@@ -1093,5 +2062,37 @@ module.exports = {
|
|
|
1093
2062
|
mergeCloudSafeCursorHooks,
|
|
1094
2063
|
isEnvAssignmentCursorCommand,
|
|
1095
2064
|
CURSOR_HOOK_SCRIPTS,
|
|
2065
|
+
CURSOR_HOOK_EVENTS,
|
|
1096
2066
|
CLOUD_SAFE_CURSOR_HOOKS,
|
|
1097
|
-
|
|
2067
|
+
wearCursorHooks,
|
|
2068
|
+
unwearCursorHooks,
|
|
2069
|
+
setupProjectBridges,
|
|
2070
|
+
mergeInstalledCursorHooks,
|
|
2071
|
+
isXrayHookCommand,
|
|
2072
|
+
installedHookCommand,
|
|
2073
|
+
consumerDistHooksReady,
|
|
2074
|
+
};
|
|
2075
|
+
|
|
2076
|
+
if (require.main === module) {
|
|
2077
|
+
if (process.argv[2] !== "setup") {
|
|
2078
|
+
process.stderr.write("setup: unknown command\n");
|
|
2079
|
+
process.exit(1);
|
|
2080
|
+
}
|
|
2081
|
+
const gitHooks = process.argv.includes("--git-hooks");
|
|
2082
|
+
try {
|
|
2083
|
+
setupProjectBridges({
|
|
2084
|
+
packageRoot: path.resolve(__dirname, "..", ".."),
|
|
2085
|
+
targetDir: path.resolve(process.cwd()),
|
|
2086
|
+
gitHooks,
|
|
2087
|
+
log: () => {},
|
|
2088
|
+
});
|
|
2089
|
+
process.stdout.write(
|
|
2090
|
+
gitHooks
|
|
2091
|
+
? "setup: wrote .mcp.json, chat bridges, and git hooks\n"
|
|
2092
|
+
: "setup: wrote .mcp.json and chat bridges\n",
|
|
2093
|
+
);
|
|
2094
|
+
} catch (err) {
|
|
2095
|
+
process.stderr.write(`${err && err.message ? err.message : err}\n`);
|
|
2096
|
+
process.exit(1);
|
|
2097
|
+
}
|
|
2098
|
+
}
|