oc-pilot 0.106.0 → 0.108.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/CHANGELOG.md +14 -0
- package/README.md +7 -5
- package/README.ru.md +6 -4
- package/dist/cli.js +9 -1
- package/dist/cli.js.map +1 -1
- package/dist/cli.test.js +24 -0
- package/dist/cli.test.js.map +1 -1
- package/dist/commands/cuckoo.js +96 -0
- package/dist/commands/cuckoo.js.map +1 -0
- package/dist/commands/hemorrhage.js +140 -0
- package/dist/commands/hemorrhage.js.map +1 -0
- package/dist/core/cuckoo.js +251 -0
- package/dist/core/cuckoo.js.map +1 -0
- package/dist/core/cuckoo.test.js +98 -0
- package/dist/core/cuckoo.test.js.map +1 -0
- package/dist/core/hemorrhage.js +238 -0
- package/dist/core/hemorrhage.js.map +1 -0
- package/dist/core/hemorrhage.test.js +138 -0
- package/dist/core/hemorrhage.test.js.map +1 -0
- package/dist/mcp-prompts.test.js +2 -0
- package/dist/mcp-prompts.test.js.map +1 -1
- package/dist/mcp.js +128 -0
- package/dist/mcp.js.map +1 -1
- package/dist/mcp.test.js +11 -0
- package/dist/mcp.test.js.map +1 -1
- package/dist/skills.test.js +8 -0
- package/dist/skills.test.js.map +1 -1
- package/dist/version.js +1 -1
- package/docs/integrations.md +5 -5
- package/package.json +1 -1
- package/skills/agent-self-review/SKILL.md +1 -1
- package/skills/commit-discipline/SKILL.md +1 -1
- package/skills/oc-pilot/SKILL.md +2 -0
- package/skills/secure-diff-gate/SKILL.md +1 -1
- package/skills/stack-review-packs/SKILL.md +1 -1
- package/skills/test-failure-triage/SKILL.md +1 -1
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { describeDiffSource, loadDiff } from "../core/diff-source.js";
|
|
2
|
+
import { PilotError } from "../core/errors.js";
|
|
3
|
+
import { runHemorrhage, } from "../core/hemorrhage.js";
|
|
4
|
+
import { writeOutput } from "../core/io.js";
|
|
5
|
+
import { log } from "../core/log.js";
|
|
6
|
+
import { COMMON_HELP, parseCommandArgs, resolveContext, withCommon } from "../core/options.js";
|
|
7
|
+
import { asBoolean, asString, parsePositiveInt, parseSeconds } from "../core/parse.js";
|
|
8
|
+
const OPTIONS = withCommon({
|
|
9
|
+
command: { type: "string" },
|
|
10
|
+
metric: { type: "string" },
|
|
11
|
+
direction: { type: "string" },
|
|
12
|
+
runs: { type: "string" },
|
|
13
|
+
warmup: { type: "string" },
|
|
14
|
+
threshold: { type: "string" },
|
|
15
|
+
"run-timeout": { type: "string" },
|
|
16
|
+
diff: { type: "string" },
|
|
17
|
+
stdin: { type: "boolean" },
|
|
18
|
+
staged: { type: "boolean" },
|
|
19
|
+
unstaged: { type: "boolean" },
|
|
20
|
+
base: { type: "string" },
|
|
21
|
+
"include-untracked": { type: "boolean" },
|
|
22
|
+
});
|
|
23
|
+
const HELP = `Использование:
|
|
24
|
+
oc-pilot hemorrhage --command "node bench.mjs" [опции]
|
|
25
|
+
|
|
26
|
+
Запускает один и тот же бенчмарк на HEAD и на diff в двух shadow
|
|
27
|
+
worktree, чередуя порядок, и сравнивает медианы, p95 и MAD.
|
|
28
|
+
--metric time меряет стенное время, --metric stdout берёт число из
|
|
29
|
+
вывода. Регрессия объявляется только при превышении порога, шума и
|
|
30
|
+
значимости Mann-Whitney (p < 0.05).
|
|
31
|
+
|
|
32
|
+
Опции:
|
|
33
|
+
--command <cmd> бенчмарк, печатающий число или работающий измеримо
|
|
34
|
+
--metric <time|stdout> что сравнивать (по умолчанию time)
|
|
35
|
+
--direction <lower|higher> что лучше (по умолчанию lower)
|
|
36
|
+
--runs <10> замеров на каждую сторону (3–50)
|
|
37
|
+
--warmup <2> прогревочных прогонов (0–10)
|
|
38
|
+
--threshold <5> порог регрессии в процентах (0–100)
|
|
39
|
+
--run-timeout <120s> таймаут одного прогона
|
|
40
|
+
--diff <file|-> готовый unified diff
|
|
41
|
+
--stdin читать diff из stdin
|
|
42
|
+
--staged только staged-изменения
|
|
43
|
+
--unstaged только unstaged-изменения
|
|
44
|
+
--base <ref> diff против ветки
|
|
45
|
+
--include-untracked добавить неотслеживаемые файлы
|
|
46
|
+
${COMMON_HELP}
|
|
47
|
+
|
|
48
|
+
Коды выхода:
|
|
49
|
+
0 регрессии нет
|
|
50
|
+
1 [PERFORMANCE REGRESSION]
|
|
51
|
+
2 ошибка бенчмарка или git
|
|
52
|
+
|
|
53
|
+
Примеры:
|
|
54
|
+
oc-pilot hemorrhage --command "node bench.mjs" --runs 10 --threshold 5
|
|
55
|
+
oc-pilot hemorrhage --command "node bench.mjs" --metric stdout --direction higher`;
|
|
56
|
+
function parseMetric(raw) {
|
|
57
|
+
if (raw === undefined || raw.trim() === "")
|
|
58
|
+
return "time";
|
|
59
|
+
if (raw === "time" || raw === "stdout")
|
|
60
|
+
return raw;
|
|
61
|
+
throw new PilotError(`Неизвестная метрика: ${raw}`, {
|
|
62
|
+
hint: "Используйте time или stdout.",
|
|
63
|
+
exitCode: 2,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
function parseDirection(raw) {
|
|
67
|
+
if (raw === undefined || raw.trim() === "")
|
|
68
|
+
return "lower";
|
|
69
|
+
if (raw === "lower" || raw === "higher")
|
|
70
|
+
return raw;
|
|
71
|
+
throw new PilotError(`Неизвестное направление: ${raw}`, {
|
|
72
|
+
hint: "Используйте lower или higher.",
|
|
73
|
+
exitCode: 2,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
function parseThreshold(raw) {
|
|
77
|
+
if (raw === undefined || raw.trim() === "")
|
|
78
|
+
return undefined;
|
|
79
|
+
const value = Number(raw);
|
|
80
|
+
if (!Number.isFinite(value) || value < 0 || value > 100) {
|
|
81
|
+
throw new PilotError(`Некорректный порог: ${raw}`, {
|
|
82
|
+
hint: "Используйте число от 0 до 100.",
|
|
83
|
+
exitCode: 2,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
return value;
|
|
87
|
+
}
|
|
88
|
+
export async function runHemorrhageCommand(argv) {
|
|
89
|
+
const { values, positionals } = parseCommandArgs(argv, OPTIONS);
|
|
90
|
+
if (asBoolean(values, "help")) {
|
|
91
|
+
process.stdout.write(`${HELP}\n`);
|
|
92
|
+
return 0;
|
|
93
|
+
}
|
|
94
|
+
if (positionals.length > 0) {
|
|
95
|
+
throw new PilotError("hemorrhage не принимает позиционных аргументов", {
|
|
96
|
+
hint: "Передайте бенчмарк через --command.",
|
|
97
|
+
exitCode: 2,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
const ctx = resolveContext(values);
|
|
101
|
+
const command = asString(values, "command");
|
|
102
|
+
if (!command) {
|
|
103
|
+
throw new PilotError("Нужна команда бенчмарка", {
|
|
104
|
+
hint: 'Например: --command "node bench.mjs".',
|
|
105
|
+
exitCode: 2,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
const data = await loadDiff(values, ctx, [], { optionalGit: true });
|
|
109
|
+
if (!data.diff.trim()) {
|
|
110
|
+
log.info("Изменений нет — сравнивать производительность нечего.");
|
|
111
|
+
return 0;
|
|
112
|
+
}
|
|
113
|
+
const runsRaw = asString(values, "runs");
|
|
114
|
+
const warmupRaw = asString(values, "warmup");
|
|
115
|
+
const timeoutRaw = asString(values, "run-timeout");
|
|
116
|
+
const report = await runHemorrhage(ctx.cwd, data.diff, {
|
|
117
|
+
command,
|
|
118
|
+
metric: parseMetric(asString(values, "metric")),
|
|
119
|
+
direction: parseDirection(asString(values, "direction")),
|
|
120
|
+
runs: runsRaw ? parsePositiveInt(runsRaw, "runs", 50) : undefined,
|
|
121
|
+
warmup: warmupRaw ? parsePositiveInt(warmupRaw, "warmup", 10) : undefined,
|
|
122
|
+
thresholdPct: parseThreshold(asString(values, "threshold")),
|
|
123
|
+
timeoutMs: timeoutRaw ? parseSeconds(timeoutRaw, "run-timeout") * 1000 : undefined,
|
|
124
|
+
});
|
|
125
|
+
const wrote = ctx.flags.json
|
|
126
|
+
? writeOutput(JSON.stringify({ source: describeDiffSource(data.source), ...report }, null, 2), ctx.flags.output)
|
|
127
|
+
: writeOutput(report.content, ctx.flags.output);
|
|
128
|
+
if (wrote)
|
|
129
|
+
log.success(`Результат сохранён: ${wrote}`);
|
|
130
|
+
if (report.status === "regression") {
|
|
131
|
+
log.error(report.summary);
|
|
132
|
+
return 1;
|
|
133
|
+
}
|
|
134
|
+
if (report.status === "improvement")
|
|
135
|
+
log.success(report.summary);
|
|
136
|
+
else
|
|
137
|
+
log.info(report.summary);
|
|
138
|
+
return 0;
|
|
139
|
+
}
|
|
140
|
+
//# sourceMappingURL=hemorrhage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hemorrhage.js","sourceRoot":"","sources":["../../src/commands/hemorrhage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AACtE,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EACL,aAAa,GAGd,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,cAAc,EAAE,UAAU,EAAmB,MAAM,oBAAoB,CAAC;AAChH,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAEvF,MAAM,OAAO,GAAe,UAAU,CAAC;IACrC,OAAO,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;IAC3B,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;IAC1B,SAAS,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;IAC7B,IAAI,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;IACxB,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;IAC1B,SAAS,EAAE,EAAE,IAA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AM,EAAE,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,EAC/E,GAAG,CAAC,KAAK,CAAC,MAAM,CACjB;QACH,CAAC,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAClD,IAAI,KAAK;QAAE,GAAG,CAAC,OAAO,CAAC,uBAAuB,KAAK,EAAE,CAAC,CAAC;IAEvD,IAAI,MAAM,CAAC,MAAM,KAAK,YAAY,EAAE,CAAC;QACnC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAC1B,OAAO,CAAC,CAAC;IACX,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,KAAK,aAAa;QAAE,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;;QAC5D,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAC9B,OAAO,CAAC,CAAC;AACX,CAAC"}
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
import { PilotError } from "./errors.js";
|
|
6
|
+
const DEFAULT_TIMEOUT_MS = 15_000;
|
|
7
|
+
const MAX_FILE_BYTES = 1024 * 1024;
|
|
8
|
+
const WORKER = String.raw `
|
|
9
|
+
const { readFileSync } = require("node:fs");
|
|
10
|
+
const vm = require("node:vm");
|
|
11
|
+
const payload = JSON.parse(readFileSync(process.argv[2], "utf8"));
|
|
12
|
+
const code = readFileSync(payload.file, "utf8");
|
|
13
|
+
const capabilities = [];
|
|
14
|
+
const output = [];
|
|
15
|
+
const record = (kind, detail) => {
|
|
16
|
+
const value = String(detail).slice(0, 200);
|
|
17
|
+
if (!capabilities.some((item) => item.kind === kind && item.detail === value)) {
|
|
18
|
+
capabilities.push({ kind: kind, detail: value });
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
const push = (...args) => {
|
|
22
|
+
if (output.length < 60) output.push(args.map((value) => String(value)).join(" "));
|
|
23
|
+
};
|
|
24
|
+
const denied = (kind, detail) => {
|
|
25
|
+
record(kind, detail);
|
|
26
|
+
const error = new Error("CAPABILITY_DENIED");
|
|
27
|
+
error.capability = kind;
|
|
28
|
+
throw error;
|
|
29
|
+
};
|
|
30
|
+
const fakeResponse = { ok: false, status: 403, text: async () => "", json: async () => ({}) };
|
|
31
|
+
const fsMock = {
|
|
32
|
+
readFileSync: (path) => { record("fs", "read:" + path); return ""; },
|
|
33
|
+
readFile: (path, options, callback) => { record("fs", "read:" + path); const cb = typeof options === "function" ? options : callback; if (cb) cb(null, ""); },
|
|
34
|
+
writeFileSync: (path) => { record("fs", "write:" + path); },
|
|
35
|
+
appendFileSync: (path) => { record("fs", "append:" + path); },
|
|
36
|
+
unlinkSync: (path) => { record("fs", "delete:" + path); },
|
|
37
|
+
rmSync: (path) => { record("fs", "delete:" + path); },
|
|
38
|
+
mkdirSync: (path) => { record("fs", "mkdir:" + path); },
|
|
39
|
+
readdirSync: (path) => { record("fs", "readdir:" + path); return []; },
|
|
40
|
+
existsSync: (path) => { record("fs", "exists:" + path); return false; },
|
|
41
|
+
openSync: (path) => { record("fs", "open:" + path); return 0; }
|
|
42
|
+
};
|
|
43
|
+
const netMock = {
|
|
44
|
+
fetch: (url) => { record("net", "fetch:" + url); return Promise.resolve(fakeResponse); },
|
|
45
|
+
request: (options) => { record("net", "request:" + (typeof options === "string" ? options : options && options.host)); return { on: () => {}, end: () => {}, write: () => {}, destroy: () => {} }; },
|
|
46
|
+
connect: (options) => { record("net", "connect:" + (typeof options === "string" ? options : options && options.host)); return { on: () => {}, end: () => {}, write: () => {}, destroy: () => {} }; }
|
|
47
|
+
};
|
|
48
|
+
const childMock = {
|
|
49
|
+
exec: (cmd, callback) => { record("child_process", "exec:" + cmd); if (typeof callback === "function") callback(null, "", ""); },
|
|
50
|
+
execSync: (cmd) => { record("child_process", "exec:" + cmd); return ""; },
|
|
51
|
+
spawn: (cmd) => { record("child_process", "spawn:" + cmd); return { on: () => {}, stdout: { on: () => {} }, stderr: { on: () => {} }, kill: () => {} }; },
|
|
52
|
+
spawnSync: (cmd) => { record("child_process", "spawn:" + cmd); return { status: 0, stdout: "", stderr: "" }; },
|
|
53
|
+
fork: (cmd) => { record("child_process", "fork:" + cmd); return { on: () => {}, kill: () => {} }; }
|
|
54
|
+
};
|
|
55
|
+
const envProxy = new Proxy({}, {
|
|
56
|
+
get: (_target, key) => { record("env", "get:" + String(key)); return undefined; },
|
|
57
|
+
has: () => true,
|
|
58
|
+
ownKeys: () => []
|
|
59
|
+
});
|
|
60
|
+
const processMock = {
|
|
61
|
+
env: envProxy,
|
|
62
|
+
exit: (code) => denied("exit", "exit:" + code),
|
|
63
|
+
cwd: () => "/sandbox",
|
|
64
|
+
platform: process.platform,
|
|
65
|
+
argv: [],
|
|
66
|
+
version: process.version,
|
|
67
|
+
nextTick: (fn) => fn()
|
|
68
|
+
};
|
|
69
|
+
const requireMock = (id) => {
|
|
70
|
+
record("require", id);
|
|
71
|
+
if (id === "fs" || id === "node:fs") return fsMock;
|
|
72
|
+
if (id === "http" || id === "node:http" || id === "https" || id === "node:https" || id === "net" || id === "node:net" || id === "dns" || id === "node:dns") return netMock;
|
|
73
|
+
if (id === "child_process" || id === "node:child_process") return childMock;
|
|
74
|
+
return {};
|
|
75
|
+
};
|
|
76
|
+
const context = vm.createContext({
|
|
77
|
+
console: { log: push, error: push, warn: push, info: push },
|
|
78
|
+
process: processMock,
|
|
79
|
+
fs: fsMock,
|
|
80
|
+
require: requireMock,
|
|
81
|
+
fetch: netMock.fetch,
|
|
82
|
+
http: netMock,
|
|
83
|
+
https: netMock,
|
|
84
|
+
net: netMock,
|
|
85
|
+
child_process: childMock,
|
|
86
|
+
module: { exports: {} },
|
|
87
|
+
exports: {},
|
|
88
|
+
Buffer: Buffer,
|
|
89
|
+
URL: URL,
|
|
90
|
+
setTimeout: () => 0,
|
|
91
|
+
clearTimeout: () => {},
|
|
92
|
+
setInterval: () => 0,
|
|
93
|
+
clearInterval: () => {}
|
|
94
|
+
});
|
|
95
|
+
let status = "clean";
|
|
96
|
+
let error;
|
|
97
|
+
if (/^\s*(?:import|export)\s/m.test(code)) {
|
|
98
|
+
record("import", "static module syntax");
|
|
99
|
+
status = "blocked";
|
|
100
|
+
} else {
|
|
101
|
+
try {
|
|
102
|
+
vm.runInContext(code, context, { filename: payload.file, timeout: payload.scriptTimeoutMs });
|
|
103
|
+
if (capabilities.length > 0) status = "capabilities";
|
|
104
|
+
} catch (caught) {
|
|
105
|
+
if (caught && caught.capability) status = "blocked";
|
|
106
|
+
else if (caught && /timed out/i.test(String(caught.message))) status = "timeout";
|
|
107
|
+
else status = "error";
|
|
108
|
+
error = caught && caught.message ? String(caught.message) : String(caught);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
process.stdout.write(JSON.stringify({ status: status, capabilities: capabilities, output: output, error: error }));
|
|
112
|
+
`;
|
|
113
|
+
function cap(output) {
|
|
114
|
+
return output.length > 2_000 ? output.slice(0, 2_000) : output;
|
|
115
|
+
}
|
|
116
|
+
function renderSummary(status, capabilities, error) {
|
|
117
|
+
const kinds = [...new Set(capabilities.map((item) => item.kind))];
|
|
118
|
+
if (status === "clean") {
|
|
119
|
+
return "[CAPABILITY CLEAN]: код не запросил fs, net, child_process, env, exit, require или import.";
|
|
120
|
+
}
|
|
121
|
+
if (status === "timeout") {
|
|
122
|
+
return "[CUCKOO TIMEOUT]: код не завершился за отведённое время.";
|
|
123
|
+
}
|
|
124
|
+
if (status === "error") {
|
|
125
|
+
return `[CUCKOO ERROR]: ${error ?? "код завершился с ошибкой"}`;
|
|
126
|
+
}
|
|
127
|
+
const list = kinds.join(", ") || "неизвестно";
|
|
128
|
+
if (status === "blocked") {
|
|
129
|
+
return `[CAPABILITY DENIED]: выполнение остановлено; запрошены: ${list} (${String(capabilities.length)}).`;
|
|
130
|
+
}
|
|
131
|
+
return `[CAPABILITY DENIED]: код запросил: ${list} (${String(capabilities.length)}).`;
|
|
132
|
+
}
|
|
133
|
+
/** Runs a JS/ESM file in an instrumented vm sandbox and reports every capability it reaches for. */
|
|
134
|
+
export function runCuckoo(cwd, file, options = {}) {
|
|
135
|
+
const absolute = resolve(cwd, file);
|
|
136
|
+
if (!existsSync(absolute)) {
|
|
137
|
+
throw new PilotError(`Файл не найден: ${file}`, { exitCode: 2 });
|
|
138
|
+
}
|
|
139
|
+
const stats = statSync(absolute);
|
|
140
|
+
if (!stats.isFile() || stats.size > MAX_FILE_BYTES) {
|
|
141
|
+
throw new PilotError("Cuckoo принимает один JS/ESM-файл до 1 МБ", { exitCode: 2 });
|
|
142
|
+
}
|
|
143
|
+
const timeoutMs = Math.max(100, Math.min(60_000, options.timeoutMs ?? DEFAULT_TIMEOUT_MS));
|
|
144
|
+
const dir = mkdtempSync(join(tmpdir(), "oc-pilot-cuckoo-"));
|
|
145
|
+
const worker = join(dir, "worker.cjs");
|
|
146
|
+
const payload = join(dir, "payload.json");
|
|
147
|
+
writeFileSync(worker, WORKER, "utf8");
|
|
148
|
+
writeFileSync(payload, JSON.stringify({ file: absolute, scriptTimeoutMs: timeoutMs }), "utf8");
|
|
149
|
+
try {
|
|
150
|
+
const env = { ...process.env, NODE_V8_COVERAGE: "" };
|
|
151
|
+
delete env.NODE_TEST_CONTEXT;
|
|
152
|
+
const result = spawnSync(process.execPath, [worker, payload], {
|
|
153
|
+
cwd,
|
|
154
|
+
env,
|
|
155
|
+
encoding: "utf8",
|
|
156
|
+
timeout: timeoutMs + 5_000,
|
|
157
|
+
killSignal: "SIGKILL",
|
|
158
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
159
|
+
});
|
|
160
|
+
if (result.error && result.error.code === "ETIMEDOUT") {
|
|
161
|
+
const report = {
|
|
162
|
+
status: "timeout",
|
|
163
|
+
file,
|
|
164
|
+
capabilities: [],
|
|
165
|
+
output: [],
|
|
166
|
+
summary: renderSummary("timeout", []),
|
|
167
|
+
content: "",
|
|
168
|
+
};
|
|
169
|
+
report.content = renderCuckoo(report);
|
|
170
|
+
return report;
|
|
171
|
+
}
|
|
172
|
+
if (result.status !== 0) {
|
|
173
|
+
const report = {
|
|
174
|
+
status: "error",
|
|
175
|
+
file,
|
|
176
|
+
capabilities: [],
|
|
177
|
+
output: [],
|
|
178
|
+
error: cap(result.stderr.trim() || result.stdout.trim() || "worker failed"),
|
|
179
|
+
summary: "",
|
|
180
|
+
content: "",
|
|
181
|
+
};
|
|
182
|
+
report.summary = renderSummary("error", [], report.error);
|
|
183
|
+
report.content = renderCuckoo(report);
|
|
184
|
+
return report;
|
|
185
|
+
}
|
|
186
|
+
let parsed;
|
|
187
|
+
try {
|
|
188
|
+
parsed = JSON.parse(result.stdout.trim());
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
const report = {
|
|
192
|
+
status: "error",
|
|
193
|
+
file,
|
|
194
|
+
capabilities: [],
|
|
195
|
+
output: [],
|
|
196
|
+
error: "worker вернул не JSON",
|
|
197
|
+
summary: "",
|
|
198
|
+
content: "",
|
|
199
|
+
};
|
|
200
|
+
report.summary = renderSummary("error", [], report.error);
|
|
201
|
+
report.content = renderCuckoo(report);
|
|
202
|
+
return report;
|
|
203
|
+
}
|
|
204
|
+
const capabilities = Array.isArray(parsed.capabilities)
|
|
205
|
+
? parsed.capabilities.filter((item) => Boolean(item) && typeof item.kind === "string" && typeof item.detail === "string")
|
|
206
|
+
: [];
|
|
207
|
+
const status = parsed.status === "clean" ||
|
|
208
|
+
parsed.status === "capabilities" ||
|
|
209
|
+
parsed.status === "blocked" ||
|
|
210
|
+
parsed.status === "timeout" ||
|
|
211
|
+
parsed.status === "error"
|
|
212
|
+
? parsed.status
|
|
213
|
+
: "error";
|
|
214
|
+
const report = {
|
|
215
|
+
status,
|
|
216
|
+
file,
|
|
217
|
+
capabilities,
|
|
218
|
+
output: Array.isArray(parsed.output)
|
|
219
|
+
? parsed.output.filter((line) => typeof line === "string").slice(0, 60)
|
|
220
|
+
: [],
|
|
221
|
+
error: typeof parsed.error === "string" ? parsed.error : undefined,
|
|
222
|
+
summary: renderSummary(status, capabilities, parsed.error),
|
|
223
|
+
content: "",
|
|
224
|
+
};
|
|
225
|
+
report.content = renderCuckoo(report);
|
|
226
|
+
return report;
|
|
227
|
+
}
|
|
228
|
+
finally {
|
|
229
|
+
rmSync(dir, { recursive: true, force: true });
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
export function renderCuckoo(report) {
|
|
233
|
+
const lines = [
|
|
234
|
+
`Cuckoo: ${report.status}`,
|
|
235
|
+
`File: ${report.file}`,
|
|
236
|
+
`Capabilities: ${String(report.capabilities.length)}`,
|
|
237
|
+
];
|
|
238
|
+
for (const capability of report.capabilities) {
|
|
239
|
+
lines.push(` ${capability.kind}: ${capability.detail}`);
|
|
240
|
+
}
|
|
241
|
+
if (report.output.length > 0) {
|
|
242
|
+
lines.push("Output:");
|
|
243
|
+
for (const line of report.output)
|
|
244
|
+
lines.push(` ${line}`);
|
|
245
|
+
}
|
|
246
|
+
if (report.error)
|
|
247
|
+
lines.push(`Error: ${report.error}`);
|
|
248
|
+
lines.push("", report.summary);
|
|
249
|
+
return `${lines.join("\n")}\n`;
|
|
250
|
+
}
|
|
251
|
+
//# sourceMappingURL=cuckoo.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cuckoo.js","sourceRoot":"","sources":["../../src/core/cuckoo.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACnF,OAAO,EAAE,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AAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC7B,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACtB,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,MAAM;YAAE,KAAK,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC;IAC5D,CAAC;IACD,IAAI,MAAM,CAAC,KAAK;QAAE,KAAK,CAAC,IAAI,CAAC,UAAU,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC;IACvD,KAAK,CAAC,IAAI,CAAC,EAAE,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;IAC/B,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;AACjC,CAAC"}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { renderCuckoo, runCuckoo } from "./cuckoo.js";
|
|
7
|
+
function makeDir(files) {
|
|
8
|
+
const dir = mkdtempSync(join(tmpdir(), "oc-pilot-cuckoo-"));
|
|
9
|
+
for (const [path, content] of Object.entries(files)) {
|
|
10
|
+
writeFileSync(join(dir, path), content, "utf8");
|
|
11
|
+
}
|
|
12
|
+
return dir;
|
|
13
|
+
}
|
|
14
|
+
test("runCuckoo reports a clean file with no capabilities", () => {
|
|
15
|
+
const dir = makeDir({ "safe.mjs": 'console.log("hello");\n' });
|
|
16
|
+
try {
|
|
17
|
+
const report = runCuckoo(dir, "safe.mjs");
|
|
18
|
+
assert.equal(report.status, "clean", report.summary);
|
|
19
|
+
assert.deepEqual(report.capabilities, []);
|
|
20
|
+
assert.deepEqual(report.output, ["hello"]);
|
|
21
|
+
assert.match(report.summary, /\[CAPABILITY CLEAN\]/);
|
|
22
|
+
}
|
|
23
|
+
finally {
|
|
24
|
+
rmSync(dir, { recursive: true, force: true });
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
test("runCuckoo records fs, net and env capabilities", () => {
|
|
28
|
+
const dir = makeDir({
|
|
29
|
+
"fs.mjs": 'const fs = require("fs"); fs.readFileSync("/etc/passwd");\n',
|
|
30
|
+
"net.mjs": 'fetch("https://example.com/data");\n',
|
|
31
|
+
"env.mjs": "process.env.SECRET;\n",
|
|
32
|
+
});
|
|
33
|
+
try {
|
|
34
|
+
const fsReport = runCuckoo(dir, "fs.mjs");
|
|
35
|
+
assert.equal(fsReport.status, "capabilities");
|
|
36
|
+
assert.ok(fsReport.capabilities.some((item) => item.kind === "fs"));
|
|
37
|
+
assert.match(fsReport.summary, /\[CAPABILITY DENIED\]/);
|
|
38
|
+
const netReport = runCuckoo(dir, "net.mjs");
|
|
39
|
+
assert.ok(netReport.capabilities.some((item) => item.kind === "net"));
|
|
40
|
+
const envReport = runCuckoo(dir, "env.mjs");
|
|
41
|
+
assert.ok(envReport.capabilities.some((item) => item.kind === "env"));
|
|
42
|
+
}
|
|
43
|
+
finally {
|
|
44
|
+
rmSync(dir, { recursive: true, force: true });
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
test("runCuckoo blocks process.exit and static imports", () => {
|
|
48
|
+
const dir = makeDir({
|
|
49
|
+
"exit.mjs": "process.exit(1);\n",
|
|
50
|
+
"import.mjs": 'import fs from "fs";\nconsole.log(fs);\n',
|
|
51
|
+
});
|
|
52
|
+
try {
|
|
53
|
+
const exitReport = runCuckoo(dir, "exit.mjs");
|
|
54
|
+
assert.equal(exitReport.status, "blocked");
|
|
55
|
+
assert.ok(exitReport.capabilities.some((item) => item.kind === "exit"));
|
|
56
|
+
const importReport = runCuckoo(dir, "import.mjs");
|
|
57
|
+
assert.equal(importReport.status, "blocked");
|
|
58
|
+
assert.ok(importReport.capabilities.some((item) => item.kind === "import"));
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
rmSync(dir, { recursive: true, force: true });
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
test("runCuckoo reports timeouts and ordinary errors", () => {
|
|
65
|
+
const dir = makeDir({
|
|
66
|
+
"loop.mjs": "while (true) {}\n",
|
|
67
|
+
"throw.mjs": 'throw new Error("boom");\n',
|
|
68
|
+
});
|
|
69
|
+
try {
|
|
70
|
+
const timeout = runCuckoo(dir, "loop.mjs", { timeoutMs: 200 });
|
|
71
|
+
assert.equal(timeout.status, "timeout", timeout.summary);
|
|
72
|
+
assert.match(timeout.summary, /\[CUCKOO TIMEOUT\]/);
|
|
73
|
+
const error = runCuckoo(dir, "throw.mjs");
|
|
74
|
+
assert.equal(error.status, "error");
|
|
75
|
+
assert.match(error.summary, /\[CUCKOO ERROR\]/);
|
|
76
|
+
assert.match(error.error ?? "", /boom/);
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
rmSync(dir, { recursive: true, force: true });
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
test("runCuckoo rejects a missing file and renderCuckoo shows capabilities", () => {
|
|
83
|
+
const dir = makeDir({
|
|
84
|
+
"fs.mjs": 'const fs = require("fs"); fs.writeFileSync("/tmp/x", "y");\n',
|
|
85
|
+
});
|
|
86
|
+
try {
|
|
87
|
+
assert.throws(() => runCuckoo(dir, "missing.mjs"), /Файл не найден/);
|
|
88
|
+
const report = runCuckoo(dir, "fs.mjs");
|
|
89
|
+
const text = renderCuckoo(report);
|
|
90
|
+
assert.match(text, /Cuckoo: capabilities/);
|
|
91
|
+
assert.match(text, /fs: write:/);
|
|
92
|
+
assert.match(text, /CAPABILITY DENIED/);
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
rmSync(dir, { recursive: true, force: true });
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
//# sourceMappingURL=cuckoo.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cuckoo.test.js","sourceRo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