opencode-agent-orchestration-kit 1.0.28 → 1.0.30
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/README.md +32 -9
- package/docker/open-design/Dockerfile +2 -2
- package/docs/compatibility.md +28 -8
- package/docs/docker-open-design.md +8 -0
- package/docs/installation.md +9 -3
- package/docs/quickstart.md +6 -3
- package/docs/releases/v1.0.29.md +78 -0
- package/docs/releases/v1.0.30.md +64 -0
- package/docs/security.md +9 -0
- package/docs/superpowers.md +11 -4
- package/docs/supply-chain.md +145 -0
- package/docs/workflows.md +15 -0
- package/opencode/docs/ai/evolution/README.md +15 -2
- package/opencode/docs/ai/evolution/benchmarks/replay-fixtures.jsonl +14 -0
- package/opencode/docs/ai/evolution/benchmarks/router-scenarios.jsonl +14 -8
- package/opencode/docs/ai/harness/checks.md +29 -2
- package/opencode/docs/ai/harness/evidence.md +29 -0
- package/opencode/opencode.json +1 -1
- package/opencode/package-lock.json +92 -95
- package/opencode/package.json +2 -1
- package/opencode/scripts/check-harness.mjs +369 -29
- package/opencode/scripts/check-harness.test.mjs +377 -14
- package/opencode/scripts/collect-session-evidence.mjs +14 -0
- package/opencode/scripts/collect-session-evidence.test.mjs +142 -6
- package/opencode/scripts/replay-routing.mjs +1012 -0
- package/opencode/scripts/replay-routing.test.mjs +1454 -0
- package/opencode/scripts/run-routing-live-replay.mjs +1180 -0
- package/opencode/scripts/run-routing-live-replay.test.mjs +1906 -0
- package/package.json +25 -3
- package/scripts/check-compatibility.mjs +65 -12
- package/scripts/check-compatibility.test.mjs +228 -32
- package/scripts/check-supply-chain.mjs +635 -0
- package/scripts/check-supply-chain.test.mjs +944 -0
- package/scripts/check.sh +9 -5
- package/scripts/install-smoke.sh +1 -1
- package/scripts/opencode-compat-smoke.sh +97 -7
- package/scripts/package-smoke.mjs +357 -0
- package/scripts/package-smoke.sh +5 -0
- package/scripts/package-smoke.test.mjs +256 -0
- package/scripts/version.test.mjs +2 -2
- package/supply-chain.json +34 -0
- package/.github/CODEOWNERS +0 -1
- package/.github/ISSUE_TEMPLATE/bug_report.yml +0 -65
- package/.github/ISSUE_TEMPLATE/config.yml +0 -11
- package/.github/ISSUE_TEMPLATE/documentation.yml +0 -22
- package/.github/ISSUE_TEMPLATE/feature_request.yml +0 -43
- package/.github/PULL_REQUEST_TEMPLATE.md +0 -25
- package/.github/workflows/check.yml +0 -92
- package/.github/workflows/compatibility-canary.yml +0 -28
|
@@ -0,0 +1,1180 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
7
|
+
import { StringDecoder } from "node:string_decoder";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
|
|
10
|
+
import { collectExecutionTreeByRoot } from "./collect-session-evidence.mjs";
|
|
11
|
+
import {
|
|
12
|
+
evaluateReplay,
|
|
13
|
+
serializeReport,
|
|
14
|
+
validateScenarios,
|
|
15
|
+
} from "./replay-routing.mjs";
|
|
16
|
+
|
|
17
|
+
const scriptDir = path.dirname(fileURLToPath(import.meta.url));
|
|
18
|
+
const repositoryRoot = path.dirname(scriptDir);
|
|
19
|
+
const defaultCorpus = path.join(
|
|
20
|
+
repositoryRoot,
|
|
21
|
+
"docs",
|
|
22
|
+
"ai",
|
|
23
|
+
"evolution",
|
|
24
|
+
"benchmarks",
|
|
25
|
+
"router-scenarios.jsonl",
|
|
26
|
+
);
|
|
27
|
+
const coverageChannels = [
|
|
28
|
+
"session_events",
|
|
29
|
+
"skill_events",
|
|
30
|
+
"tool_events",
|
|
31
|
+
"review_events",
|
|
32
|
+
"stop_events",
|
|
33
|
+
];
|
|
34
|
+
const portableRoots = ["AGENTS.md", "agents", "commands", "skills", "tools", "references"];
|
|
35
|
+
const excludedNames = new Set([
|
|
36
|
+
".git",
|
|
37
|
+
".opencode",
|
|
38
|
+
".opencode-live",
|
|
39
|
+
"node_modules",
|
|
40
|
+
"artifacts",
|
|
41
|
+
"raw",
|
|
42
|
+
"opencode.json",
|
|
43
|
+
"opencode.jsonc",
|
|
44
|
+
]);
|
|
45
|
+
const ignoredRawEventTypes = new Set([
|
|
46
|
+
"text",
|
|
47
|
+
"thinking",
|
|
48
|
+
"message.part.updated",
|
|
49
|
+
"step_start",
|
|
50
|
+
"step_finish",
|
|
51
|
+
]);
|
|
52
|
+
const sessionScopedEventTypes = new Set([
|
|
53
|
+
...ignoredRawEventTypes,
|
|
54
|
+
"session.completed",
|
|
55
|
+
"skill.selected",
|
|
56
|
+
"tool.completed",
|
|
57
|
+
"review.completed",
|
|
58
|
+
"stop.observed",
|
|
59
|
+
]);
|
|
60
|
+
const sensitiveWarning =
|
|
61
|
+
"Warning: retained live replay output may contain sensitive prompts, paths, model/provider metadata, or reasoning.\n";
|
|
62
|
+
|
|
63
|
+
export const runtimeConfig = Object.freeze({
|
|
64
|
+
$schema: "https://opencode.ai/config.json",
|
|
65
|
+
default_agent: "lead",
|
|
66
|
+
share: "disabled",
|
|
67
|
+
permission: Object.freeze({
|
|
68
|
+
read: "allow",
|
|
69
|
+
glob: "allow",
|
|
70
|
+
grep: "allow",
|
|
71
|
+
list: "allow",
|
|
72
|
+
lsp: "allow",
|
|
73
|
+
edit: "ask",
|
|
74
|
+
bash: "ask",
|
|
75
|
+
webfetch: "deny",
|
|
76
|
+
websearch: "deny",
|
|
77
|
+
external_directory: "deny",
|
|
78
|
+
}),
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
export class LiveReplayError extends Error {
|
|
82
|
+
constructor(message) {
|
|
83
|
+
super(message);
|
|
84
|
+
this.name = "LiveReplayError";
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function requireValue(argv, index, option) {
|
|
89
|
+
const value = argv[index + 1];
|
|
90
|
+
if (typeof value !== "string" || value.length === 0 || value.startsWith("--")) {
|
|
91
|
+
throw new LiveReplayError(`${option} requires a value.`);
|
|
92
|
+
}
|
|
93
|
+
return value;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function parseLiveArguments(argv) {
|
|
97
|
+
const options = {};
|
|
98
|
+
const forbidden = new Set([
|
|
99
|
+
"--model",
|
|
100
|
+
"--provider",
|
|
101
|
+
"--variant",
|
|
102
|
+
"--auto",
|
|
103
|
+
"--attach",
|
|
104
|
+
"--password",
|
|
105
|
+
"--username",
|
|
106
|
+
]);
|
|
107
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
108
|
+
const option = argv[index];
|
|
109
|
+
if (forbidden.has(option)) {
|
|
110
|
+
throw new LiveReplayError(`${option} is forbidden for live replay.`);
|
|
111
|
+
}
|
|
112
|
+
if (option === "--confirm-live") {
|
|
113
|
+
if (options.confirmLive) throw new LiveReplayError(`${option} was provided twice.`);
|
|
114
|
+
options.confirmLive = true;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (!["--scenario", "--timeout-ms", "--retain-private-output"].includes(option)) {
|
|
118
|
+
throw new LiveReplayError(`Unknown argument: ${option ?? ""}`);
|
|
119
|
+
}
|
|
120
|
+
const value = requireValue(argv, index, option);
|
|
121
|
+
index += 1;
|
|
122
|
+
const key = option === "--scenario"
|
|
123
|
+
? "scenarioId"
|
|
124
|
+
: option === "--timeout-ms"
|
|
125
|
+
? "timeoutMs"
|
|
126
|
+
: "retainPrivateOutput";
|
|
127
|
+
if (Object.hasOwn(options, key)) throw new LiveReplayError(`${option} was provided twice.`);
|
|
128
|
+
options[key] = value;
|
|
129
|
+
}
|
|
130
|
+
if (!options.scenarioId) throw new LiveReplayError("--scenario is required.");
|
|
131
|
+
if (!options.confirmLive) throw new LiveReplayError("--confirm-live is required.");
|
|
132
|
+
if (options.timeoutMs !== undefined) {
|
|
133
|
+
if (!/^[1-9][0-9]*$/.test(options.timeoutMs)) {
|
|
134
|
+
throw new LiveReplayError("--timeout-ms must be a positive integer.");
|
|
135
|
+
}
|
|
136
|
+
options.timeoutMs = Number(options.timeoutMs);
|
|
137
|
+
if (!Number.isSafeInteger(options.timeoutMs)) {
|
|
138
|
+
throw new LiveReplayError("--timeout-ms must be a positive safe integer.");
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (options.retainPrivateOutput !== undefined
|
|
142
|
+
&& !path.isAbsolute(options.retainPrivateOutput)) {
|
|
143
|
+
throw new LiveReplayError("--retain-private-output must be an absolute path.");
|
|
144
|
+
}
|
|
145
|
+
return options;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function canonicalPath(candidate) {
|
|
149
|
+
return fs.realpathSync(candidate);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function isWithin(candidate, root) {
|
|
153
|
+
return candidate === root || candidate.startsWith(`${root}${path.sep}`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function existingAncestor(candidate) {
|
|
157
|
+
let current = path.resolve(candidate);
|
|
158
|
+
while (!fs.existsSync(current)) {
|
|
159
|
+
const parent = path.dirname(current);
|
|
160
|
+
if (parent === current) throw new LiveReplayError("Path has no existing ancestor.");
|
|
161
|
+
current = parent;
|
|
162
|
+
}
|
|
163
|
+
return current;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function assertNoSymlinkComponents(candidate) {
|
|
167
|
+
const resolved = path.resolve(candidate);
|
|
168
|
+
const ancestor = existingAncestor(resolved);
|
|
169
|
+
let current = path.parse(ancestor).root;
|
|
170
|
+
for (const component of ancestor.slice(current.length).split(path.sep).filter(Boolean)) {
|
|
171
|
+
current = path.join(current, component);
|
|
172
|
+
if (fs.lstatSync(current).isSymbolicLink()) {
|
|
173
|
+
throw new LiveReplayError("Path contains a symbolic link.");
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function resolveForContainment(candidate) {
|
|
179
|
+
const absolute = path.resolve(candidate);
|
|
180
|
+
const ancestor = existingAncestor(absolute);
|
|
181
|
+
const ancestorReal = canonicalPath(ancestor);
|
|
182
|
+
return path.join(ancestorReal, path.relative(ancestor, absolute));
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function validateRetainPath(candidate, protectedRoots, { requireEmpty = true } = {}) {
|
|
186
|
+
if (!path.isAbsolute(candidate)) {
|
|
187
|
+
throw new LiveReplayError("Retention path must be absolute.");
|
|
188
|
+
}
|
|
189
|
+
assertNoSymlinkComponents(candidate);
|
|
190
|
+
const resolved = resolveForContainment(candidate);
|
|
191
|
+
for (const protectedRoot of protectedRoots) {
|
|
192
|
+
if (!fs.existsSync(protectedRoot)) continue;
|
|
193
|
+
const protectedResolved = canonicalPath(protectedRoot);
|
|
194
|
+
if (isWithin(resolved, protectedResolved)) {
|
|
195
|
+
throw new LiveReplayError("Retention path overlaps a protected repository.");
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
let ancestor = existingAncestor(resolved);
|
|
199
|
+
while (true) {
|
|
200
|
+
if (fs.existsSync(path.join(ancestor, ".git"))) {
|
|
201
|
+
throw new LiveReplayError("Retention path must be outside every Git worktree.");
|
|
202
|
+
}
|
|
203
|
+
const parent = path.dirname(ancestor);
|
|
204
|
+
if (parent === ancestor) break;
|
|
205
|
+
ancestor = parent;
|
|
206
|
+
}
|
|
207
|
+
if (fs.existsSync(candidate)) {
|
|
208
|
+
const stat = fs.lstatSync(candidate);
|
|
209
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
210
|
+
throw new LiveReplayError("Retention path must be a directory without symlinks.");
|
|
211
|
+
}
|
|
212
|
+
if (requireEmpty && fs.readdirSync(candidate).length !== 0) {
|
|
213
|
+
throw new LiveReplayError("Retention directory must be empty.");
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return resolved;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function assertSafeTempPath(tempPath, sourceRoot, protectedRoots) {
|
|
220
|
+
if (!fs.existsSync(tempPath)) throw new LiveReplayError("Temporary path does not exist.");
|
|
221
|
+
const stat = fs.lstatSync(tempPath);
|
|
222
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
223
|
+
throw new LiveReplayError("Temporary path must be a real directory.");
|
|
224
|
+
}
|
|
225
|
+
const resolved = canonicalPath(tempPath);
|
|
226
|
+
const tempBase = canonicalPath(os.tmpdir());
|
|
227
|
+
if (!isWithin(resolved, tempBase) || resolved === tempBase) {
|
|
228
|
+
throw new LiveReplayError("Temporary path must be a unique child of the system temp directory.");
|
|
229
|
+
}
|
|
230
|
+
if (fs.readdirSync(resolved).length !== 0) {
|
|
231
|
+
throw new LiveReplayError("Temporary path must be newly created and empty.");
|
|
232
|
+
}
|
|
233
|
+
const roots = [sourceRoot, ...protectedRoots];
|
|
234
|
+
for (const protectedRoot of roots) {
|
|
235
|
+
if (!fs.existsSync(protectedRoot)) continue;
|
|
236
|
+
const protectedResolved = canonicalPath(protectedRoot);
|
|
237
|
+
if (isWithin(resolved, protectedResolved) || isWithin(protectedResolved, resolved)) {
|
|
238
|
+
throw new LiveReplayError("Temporary path overlaps a protected repository.");
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return resolved;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function copyPortableEntry(source, destination) {
|
|
245
|
+
const stat = fs.lstatSync(source);
|
|
246
|
+
if (stat.isSymbolicLink()) {
|
|
247
|
+
throw new LiveReplayError("Portable harness source contains a symbolic link.");
|
|
248
|
+
}
|
|
249
|
+
if (stat.isDirectory()) {
|
|
250
|
+
fs.mkdirSync(destination, { recursive: true, mode: 0o700 });
|
|
251
|
+
for (const entry of fs.readdirSync(source, { withFileTypes: true })) {
|
|
252
|
+
if (excludedNames.has(entry.name)) continue;
|
|
253
|
+
copyPortableEntry(path.join(source, entry.name), path.join(destination, entry.name));
|
|
254
|
+
}
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
if (!stat.isFile()) {
|
|
258
|
+
throw new LiveReplayError("Portable harness source contains an unsupported entry.");
|
|
259
|
+
}
|
|
260
|
+
fs.copyFileSync(source, destination, fs.constants.COPYFILE_EXCL);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function assertContainedPathWithoutSymlinks(sourceRoot, candidate) {
|
|
264
|
+
const sourceAbsolute = path.resolve(sourceRoot);
|
|
265
|
+
const candidateAbsolute = path.resolve(candidate);
|
|
266
|
+
if (!isWithin(candidateAbsolute, sourceAbsolute)) {
|
|
267
|
+
throw new LiveReplayError("Portable source path escapes the source repository.");
|
|
268
|
+
}
|
|
269
|
+
let current = sourceAbsolute;
|
|
270
|
+
for (const component of path.relative(sourceAbsolute, candidateAbsolute).split(path.sep)) {
|
|
271
|
+
if (!component) continue;
|
|
272
|
+
current = path.join(current, component);
|
|
273
|
+
const stat = fs.lstatSync(current);
|
|
274
|
+
if (stat.isSymbolicLink()) {
|
|
275
|
+
throw new LiveReplayError("Portable harness source contains a symbolic link.");
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
const sourceResolved = fs.realpathSync(sourceAbsolute);
|
|
279
|
+
const candidateResolved = fs.realpathSync(candidateAbsolute);
|
|
280
|
+
if (!isWithin(candidateResolved, sourceResolved)) {
|
|
281
|
+
throw new LiveReplayError("Portable source path escapes the source repository.");
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function runGit(tempRoot, args) {
|
|
286
|
+
const result = spawnSync("git", args, {
|
|
287
|
+
cwd: tempRoot,
|
|
288
|
+
encoding: "utf8",
|
|
289
|
+
shell: false,
|
|
290
|
+
});
|
|
291
|
+
if (result.status !== 0) {
|
|
292
|
+
throw new LiveReplayError("Unable to initialize disposable Git repository.");
|
|
293
|
+
}
|
|
294
|
+
return result.stdout;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function materializeRepository(tempRoot, sourceRoot) {
|
|
298
|
+
for (const name of portableRoots) {
|
|
299
|
+
const source = path.join(sourceRoot, name);
|
|
300
|
+
if (!fs.existsSync(source)) continue;
|
|
301
|
+
copyPortableEntry(source, path.join(tempRoot, name));
|
|
302
|
+
}
|
|
303
|
+
const corpusSource = path.join(
|
|
304
|
+
sourceRoot,
|
|
305
|
+
"docs",
|
|
306
|
+
"ai",
|
|
307
|
+
"evolution",
|
|
308
|
+
"benchmarks",
|
|
309
|
+
"router-scenarios.jsonl",
|
|
310
|
+
);
|
|
311
|
+
assertContainedPathWithoutSymlinks(sourceRoot, corpusSource);
|
|
312
|
+
const corpusDestination = path.join(
|
|
313
|
+
tempRoot,
|
|
314
|
+
"docs",
|
|
315
|
+
"ai",
|
|
316
|
+
"evolution",
|
|
317
|
+
"benchmarks",
|
|
318
|
+
"router-scenarios.jsonl",
|
|
319
|
+
);
|
|
320
|
+
fs.mkdirSync(path.dirname(corpusDestination), { recursive: true, mode: 0o700 });
|
|
321
|
+
copyPortableEntry(corpusSource, corpusDestination);
|
|
322
|
+
fs.writeFileSync(
|
|
323
|
+
path.join(tempRoot, "opencode.json"),
|
|
324
|
+
`${JSON.stringify(runtimeConfig, null, 2)}\n`,
|
|
325
|
+
{ encoding: "utf8", mode: 0o600 },
|
|
326
|
+
);
|
|
327
|
+
fs.writeFileSync(path.join(tempRoot, ".gitignore"), "/.opencode-live/\n", "utf8");
|
|
328
|
+
runGit(tempRoot, ["init", "--quiet"]);
|
|
329
|
+
runGit(tempRoot, ["add", "."]);
|
|
330
|
+
runGit(tempRoot, [
|
|
331
|
+
"-c",
|
|
332
|
+
"user.name=Routing Replay",
|
|
333
|
+
"-c",
|
|
334
|
+
"user.email=routing-replay.invalid",
|
|
335
|
+
"commit",
|
|
336
|
+
"--quiet",
|
|
337
|
+
"-m",
|
|
338
|
+
"baseline",
|
|
339
|
+
]);
|
|
340
|
+
if (runGit(tempRoot, ["status", "--porcelain=v1"]).trim() !== "") {
|
|
341
|
+
throw new LiveReplayError("Disposable repository baseline is not clean.");
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
export function spawnProcessWithTimeout(command, args, options) {
|
|
346
|
+
return new Promise((resolve, reject) => {
|
|
347
|
+
const useProcessGroup = process.platform !== "win32";
|
|
348
|
+
const child = spawn(command, args, {
|
|
349
|
+
cwd: options.cwd,
|
|
350
|
+
shell: false,
|
|
351
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
352
|
+
detached: useProcessGroup,
|
|
353
|
+
});
|
|
354
|
+
let settled = false;
|
|
355
|
+
let timedOut = false;
|
|
356
|
+
let terminating = false;
|
|
357
|
+
let terminationError = null;
|
|
358
|
+
let closeResult = null;
|
|
359
|
+
let killTimer;
|
|
360
|
+
let absoluteTimer;
|
|
361
|
+
const stdoutHandler = (chunk) => {
|
|
362
|
+
try {
|
|
363
|
+
options.onStdoutChunk?.(chunk);
|
|
364
|
+
} catch (error) {
|
|
365
|
+
terminateThenReject(error);
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
const stderrHandler = (chunk) => {
|
|
369
|
+
try {
|
|
370
|
+
options.onStderrChunk?.(chunk);
|
|
371
|
+
} catch (error) {
|
|
372
|
+
terminateThenReject(error);
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
function signalProcess(signal) {
|
|
377
|
+
try {
|
|
378
|
+
if (useProcessGroup && child.pid) {
|
|
379
|
+
process.kill(-child.pid, signal);
|
|
380
|
+
} else {
|
|
381
|
+
child.kill(signal);
|
|
382
|
+
}
|
|
383
|
+
} catch {
|
|
384
|
+
try {
|
|
385
|
+
child.kill(signal);
|
|
386
|
+
} catch {
|
|
387
|
+
// The process already exited.
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function cleanup({ destroyStreams = false } = {}) {
|
|
393
|
+
clearTimeout(timeout);
|
|
394
|
+
if (killTimer) clearTimeout(killTimer);
|
|
395
|
+
if (absoluteTimer) clearTimeout(absoluteTimer);
|
|
396
|
+
child.stdout?.off("data", stdoutHandler);
|
|
397
|
+
child.stderr?.off("data", stderrHandler);
|
|
398
|
+
child.removeListener("error", spawnErrorHandler);
|
|
399
|
+
child.removeListener("close", closeHandler);
|
|
400
|
+
if (destroyStreams) {
|
|
401
|
+
child.stdout?.destroy();
|
|
402
|
+
child.stderr?.destroy();
|
|
403
|
+
child.unref();
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function finish(result, { destroyStreams = false } = {}) {
|
|
408
|
+
if (settled) return;
|
|
409
|
+
settled = true;
|
|
410
|
+
cleanup({ destroyStreams });
|
|
411
|
+
resolve(result);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function rejectAfterTermination() {
|
|
415
|
+
if (settled) return;
|
|
416
|
+
signalProcess("SIGKILL");
|
|
417
|
+
settled = true;
|
|
418
|
+
cleanup({ destroyStreams: true });
|
|
419
|
+
reject(terminationError);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function scheduleForcedTermination() {
|
|
423
|
+
killTimer = setTimeout(() => {
|
|
424
|
+
signalProcess("SIGKILL");
|
|
425
|
+
if (terminationError) {
|
|
426
|
+
rejectAfterTermination();
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
finish(closeResult ?? {
|
|
430
|
+
exitCode: null,
|
|
431
|
+
timedOut: true,
|
|
432
|
+
cancelled: false,
|
|
433
|
+
}, { destroyStreams: true });
|
|
434
|
+
}, options.killGraceMs ?? 2_000);
|
|
435
|
+
absoluteTimer = setTimeout(() => {
|
|
436
|
+
if (terminationError) {
|
|
437
|
+
rejectAfterTermination();
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
signalProcess("SIGKILL");
|
|
441
|
+
finish(closeResult ?? {
|
|
442
|
+
exitCode: null,
|
|
443
|
+
timedOut: true,
|
|
444
|
+
cancelled: false,
|
|
445
|
+
}, { destroyStreams: true });
|
|
446
|
+
}, (options.killGraceMs ?? 2_000) + (options.absoluteGraceMs ?? 2_000));
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function terminateThenReject(error) {
|
|
450
|
+
if (settled || terminating) return;
|
|
451
|
+
terminating = true;
|
|
452
|
+
terminationError = error;
|
|
453
|
+
clearTimeout(timeout);
|
|
454
|
+
signalProcess("SIGTERM");
|
|
455
|
+
scheduleForcedTermination();
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
const timeout = setTimeout(() => {
|
|
459
|
+
if (settled || terminating) return;
|
|
460
|
+
terminating = true;
|
|
461
|
+
timedOut = true;
|
|
462
|
+
signalProcess("SIGTERM");
|
|
463
|
+
scheduleForcedTermination();
|
|
464
|
+
}, options.timeoutMs);
|
|
465
|
+
|
|
466
|
+
function spawnErrorHandler(error) {
|
|
467
|
+
if (settled) return;
|
|
468
|
+
if (terminating) return;
|
|
469
|
+
cleanup({ destroyStreams: true });
|
|
470
|
+
settled = true;
|
|
471
|
+
reject(error);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function closeHandler(exitCode, signal) {
|
|
475
|
+
closeResult = {
|
|
476
|
+
exitCode,
|
|
477
|
+
timedOut,
|
|
478
|
+
cancelled: !timedOut && signal !== null,
|
|
479
|
+
};
|
|
480
|
+
if (terminating) return;
|
|
481
|
+
finish({
|
|
482
|
+
exitCode,
|
|
483
|
+
timedOut,
|
|
484
|
+
cancelled: !timedOut && signal !== null,
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
child.stdout.on("data", stdoutHandler);
|
|
489
|
+
child.stderr.on("data", stderrHandler);
|
|
490
|
+
child.on("error", spawnErrorHandler);
|
|
491
|
+
child.on("close", closeHandler);
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
const defaultDeps = {
|
|
496
|
+
spawnProcess: spawnProcessWithTimeout,
|
|
497
|
+
makeTempDir: async () => fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-run-")),
|
|
498
|
+
collectExecutionTreeByRoot,
|
|
499
|
+
readOpenCodeDbPath: async () => path.join(
|
|
500
|
+
os.homedir(),
|
|
501
|
+
".local",
|
|
502
|
+
"share",
|
|
503
|
+
"opencode",
|
|
504
|
+
"opencode.db",
|
|
505
|
+
),
|
|
506
|
+
removeTree: async (target) => fs.rmSync(target, { recursive: true, force: true }),
|
|
507
|
+
wait: async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)),
|
|
508
|
+
};
|
|
509
|
+
|
|
510
|
+
async function collectStableTree(deps, dbPath, rootId) {
|
|
511
|
+
let previousSignature = null;
|
|
512
|
+
let previousTree = null;
|
|
513
|
+
for (let attempt = 0; attempt < 6; attempt += 1) {
|
|
514
|
+
let tree;
|
|
515
|
+
try {
|
|
516
|
+
tree = await deps.collectExecutionTreeByRoot(dbPath, rootId);
|
|
517
|
+
} catch {
|
|
518
|
+
return { tree: null, failed: true };
|
|
519
|
+
}
|
|
520
|
+
const signature = tree === null ? null : JSON.stringify(tree);
|
|
521
|
+
if (tree !== null && signature === previousSignature) {
|
|
522
|
+
return { tree, failed: false };
|
|
523
|
+
}
|
|
524
|
+
previousTree = tree;
|
|
525
|
+
previousSignature = signature;
|
|
526
|
+
if (attempt < 5) await (deps.wait ?? defaultDeps.wait)(250);
|
|
527
|
+
}
|
|
528
|
+
return { tree: previousTree, failed: true };
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function parseRawLines(stdout) {
|
|
532
|
+
const records = [];
|
|
533
|
+
let malformed = false;
|
|
534
|
+
for (const line of stdout.split("\n")) {
|
|
535
|
+
if (line.trim() === "") continue;
|
|
536
|
+
try {
|
|
537
|
+
const value = JSON.parse(line);
|
|
538
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
539
|
+
records.push(value);
|
|
540
|
+
} else {
|
|
541
|
+
malformed = true;
|
|
542
|
+
}
|
|
543
|
+
} catch {
|
|
544
|
+
malformed = true;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
return { records, malformed };
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
function explicitRootIds(records) {
|
|
551
|
+
const explicitIds = [];
|
|
552
|
+
const fallbackIds = [];
|
|
553
|
+
for (const record of records) {
|
|
554
|
+
if (record.type === "session.created"
|
|
555
|
+
&& record.properties?.info?.parentID === null
|
|
556
|
+
&& typeof record.properties.info.id === "string") {
|
|
557
|
+
if (!explicitIds.includes(record.properties.info.id)) {
|
|
558
|
+
explicitIds.push(record.properties.info.id);
|
|
559
|
+
}
|
|
560
|
+
} else if (record.type === "step_start" && typeof record.sessionID === "string"
|
|
561
|
+
&& !fallbackIds.includes(record.sessionID)) {
|
|
562
|
+
fallbackIds.push(record.sessionID);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
return explicitIds.length > 0 ? explicitIds : fallbackIds;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
function sessionRows(tree) {
|
|
569
|
+
if (!tree) return { rows: [], incomplete: true };
|
|
570
|
+
const root = tree.root_session;
|
|
571
|
+
if (!root
|
|
572
|
+
|| typeof root.session_id !== "string"
|
|
573
|
+
|| root.session_id.length === 0
|
|
574
|
+
|| root.parent_session_id !== null
|
|
575
|
+
|| typeof root.agent !== "string"
|
|
576
|
+
|| root.agent.length === 0
|
|
577
|
+
|| tree.root_session_id !== root.session_id) {
|
|
578
|
+
return { rows: [], incomplete: true };
|
|
579
|
+
}
|
|
580
|
+
const ordered = [root];
|
|
581
|
+
const known = new Set([root.session_id]);
|
|
582
|
+
const pending = [...(tree.child_sessions ?? [])];
|
|
583
|
+
const childIdCounts = new Map();
|
|
584
|
+
for (const row of pending) {
|
|
585
|
+
if (typeof row?.session_id !== "string" || !row.session_id) continue;
|
|
586
|
+
childIdCounts.set(row.session_id, (childIdCounts.get(row.session_id) ?? 0) + 1);
|
|
587
|
+
}
|
|
588
|
+
let incomplete = false;
|
|
589
|
+
for (let index = pending.length - 1; index >= 0; index -= 1) {
|
|
590
|
+
const row = pending[index];
|
|
591
|
+
if (!row
|
|
592
|
+
|| typeof row.session_id !== "string"
|
|
593
|
+
|| !row.session_id
|
|
594
|
+
|| typeof row.parent_session_id !== "string"
|
|
595
|
+
|| !row.parent_session_id
|
|
596
|
+
|| typeof row.agent !== "string"
|
|
597
|
+
|| !row.agent
|
|
598
|
+
|| row.session_id === root.session_id
|
|
599
|
+
|| childIdCounts.get(row.session_id) !== 1) {
|
|
600
|
+
pending.splice(index, 1);
|
|
601
|
+
incomplete = true;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
while (pending.length > 0) {
|
|
605
|
+
const nextIndex = pending.findIndex((row) => known.has(row.parent_session_id));
|
|
606
|
+
if (nextIndex === -1) {
|
|
607
|
+
incomplete = true;
|
|
608
|
+
break;
|
|
609
|
+
}
|
|
610
|
+
const [next] = pending.splice(nextIndex, 1);
|
|
611
|
+
ordered.push(next);
|
|
612
|
+
known.add(next.session_id);
|
|
613
|
+
}
|
|
614
|
+
return { rows: ordered, incomplete };
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
function normalizedObservation({
|
|
618
|
+
scenario,
|
|
619
|
+
records,
|
|
620
|
+
malformed,
|
|
621
|
+
tree,
|
|
622
|
+
rootError,
|
|
623
|
+
processResult,
|
|
624
|
+
gitSnapshot,
|
|
625
|
+
}) {
|
|
626
|
+
const events = [];
|
|
627
|
+
const coverage = Object.fromEntries(coverageChannels.map((channel) => [channel, "partial"]));
|
|
628
|
+
const normalizedTree = sessionRows(tree);
|
|
629
|
+
const rows = normalizedTree.rows;
|
|
630
|
+
const idMap = new Map();
|
|
631
|
+
const rowsById = new Map();
|
|
632
|
+
for (const [index, row] of rows.entries()) {
|
|
633
|
+
idMap.set(row.session_id, `session-${index + 1}`);
|
|
634
|
+
rowsById.set(row.session_id, row);
|
|
635
|
+
}
|
|
636
|
+
let sequence = 1;
|
|
637
|
+
const seenSessionIds = new Set();
|
|
638
|
+
let sessionCaptureIncomplete = rows.length === 0 || normalizedTree.incomplete;
|
|
639
|
+
for (const row of rows) {
|
|
640
|
+
const agent = typeof row.agent === "string" && row.agent.length > 0
|
|
641
|
+
? row.agent
|
|
642
|
+
: "unknown-agent";
|
|
643
|
+
if (typeof row.session_id !== "string" || row.session_id.length === 0
|
|
644
|
+
|| (row.parent_session_id !== null && !seenSessionIds.has(row.parent_session_id))
|
|
645
|
+
|| agent === "unknown-agent") {
|
|
646
|
+
sessionCaptureIncomplete = true;
|
|
647
|
+
}
|
|
648
|
+
events.push({
|
|
649
|
+
sequence: sequence++,
|
|
650
|
+
type: "session_started",
|
|
651
|
+
session_id: idMap.get(row.session_id),
|
|
652
|
+
parent_session_id: row.parent_session_id === null
|
|
653
|
+
? null
|
|
654
|
+
: idMap.get(row.parent_session_id),
|
|
655
|
+
agent,
|
|
656
|
+
});
|
|
657
|
+
seenSessionIds.add(row.session_id);
|
|
658
|
+
}
|
|
659
|
+
if (tree && !sessionCaptureIncomplete) coverage.session_events = "complete";
|
|
660
|
+
|
|
661
|
+
const degradedChannels = new Set();
|
|
662
|
+
const explicitRunErrors = [];
|
|
663
|
+
if (malformed) {
|
|
664
|
+
for (const channel of coverageChannels.filter((name) => name !== "session_events")) {
|
|
665
|
+
degradedChannels.add(channel);
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
for (const record of records) {
|
|
669
|
+
const properties = record.properties ?? {};
|
|
670
|
+
const scopedSessionId = properties.sessionID ?? record.sessionID;
|
|
671
|
+
const mappedSession = idMap.get(scopedSessionId);
|
|
672
|
+
if (record.type === "session.created") {
|
|
673
|
+
const info = properties.info;
|
|
674
|
+
const row = typeof info?.id === "string" ? rowsById.get(info.id) : undefined;
|
|
675
|
+
if (!row
|
|
676
|
+
|| row.parent_session_id !== info.parentID
|
|
677
|
+
|| row.agent !== info.agent) {
|
|
678
|
+
sessionCaptureIncomplete = true;
|
|
679
|
+
}
|
|
680
|
+
continue;
|
|
681
|
+
}
|
|
682
|
+
if (scopedSessionId !== undefined
|
|
683
|
+
&& sessionScopedEventTypes.has(record.type)
|
|
684
|
+
&& !mappedSession) {
|
|
685
|
+
sessionCaptureIncomplete = true;
|
|
686
|
+
}
|
|
687
|
+
if (ignoredRawEventTypes.has(record.type)) continue;
|
|
688
|
+
if (record.type === "capture.complete"
|
|
689
|
+
&& Array.isArray(properties.channels)
|
|
690
|
+
&& properties.channels.every(
|
|
691
|
+
(channel) => coverageChannels.includes(channel) && channel !== "session_events",
|
|
692
|
+
)) {
|
|
693
|
+
for (const channel of properties.channels) coverage[channel] = "complete";
|
|
694
|
+
} else if (record.type === "run.error") {
|
|
695
|
+
const code = typeof properties.code === "string"
|
|
696
|
+
&& /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(properties.code)
|
|
697
|
+
? properties.code
|
|
698
|
+
: "runtime-error";
|
|
699
|
+
explicitRunErrors.push(code);
|
|
700
|
+
} else if (record.type === "session.completed") {
|
|
701
|
+
const row = rowsById.get(scopedSessionId);
|
|
702
|
+
if (mappedSession && row) {
|
|
703
|
+
events.push({
|
|
704
|
+
sequence: sequence++,
|
|
705
|
+
type: "session_completed",
|
|
706
|
+
session_id: mappedSession,
|
|
707
|
+
agent: typeof row.agent === "string" && row.agent ? row.agent : "unknown-agent",
|
|
708
|
+
});
|
|
709
|
+
} else {
|
|
710
|
+
sessionCaptureIncomplete = true;
|
|
711
|
+
}
|
|
712
|
+
} else if (record.type === "skill.selected") {
|
|
713
|
+
const row = rowsById.get(scopedSessionId);
|
|
714
|
+
if (mappedSession && row && typeof properties.skill === "string" && properties.skill) {
|
|
715
|
+
events.push({
|
|
716
|
+
sequence: sequence++,
|
|
717
|
+
type: "skill_selected",
|
|
718
|
+
session_id: mappedSession,
|
|
719
|
+
agent: row.agent,
|
|
720
|
+
skill: properties.skill,
|
|
721
|
+
});
|
|
722
|
+
} else {
|
|
723
|
+
degradedChannels.add("skill_events");
|
|
724
|
+
}
|
|
725
|
+
} else if (record.type === "tool.completed") {
|
|
726
|
+
const row = rowsById.get(scopedSessionId);
|
|
727
|
+
if (mappedSession && row && typeof properties.tool === "string" && properties.tool) {
|
|
728
|
+
events.push({
|
|
729
|
+
sequence: sequence++,
|
|
730
|
+
type: "tool_call_completed",
|
|
731
|
+
session_id: mappedSession,
|
|
732
|
+
agent: row.agent,
|
|
733
|
+
tool: properties.tool,
|
|
734
|
+
mutation: ["read", "write", "unknown"].includes(properties.mutation)
|
|
735
|
+
? properties.mutation
|
|
736
|
+
: "unknown",
|
|
737
|
+
});
|
|
738
|
+
} else {
|
|
739
|
+
degradedChannels.add("tool_events");
|
|
740
|
+
}
|
|
741
|
+
} else if (record.type === "review.completed") {
|
|
742
|
+
const row = rowsById.get(scopedSessionId);
|
|
743
|
+
if (mappedSession && row?.agent === "reviewer"
|
|
744
|
+
&& ["approved", "changes-requested", "blocked"].includes(properties.verdict)) {
|
|
745
|
+
events.push({
|
|
746
|
+
sequence: sequence++,
|
|
747
|
+
type: "review_completed",
|
|
748
|
+
session_id: mappedSession,
|
|
749
|
+
agent: "reviewer",
|
|
750
|
+
verdict: properties.verdict,
|
|
751
|
+
});
|
|
752
|
+
} else {
|
|
753
|
+
degradedChannels.add("review_events");
|
|
754
|
+
}
|
|
755
|
+
} else if (record.type === "stop.observed") {
|
|
756
|
+
if ((scopedSessionId === undefined || mappedSession)
|
|
757
|
+
&& typeof properties.condition === "string"
|
|
758
|
+
&& properties.condition) {
|
|
759
|
+
events.push({
|
|
760
|
+
sequence: sequence++,
|
|
761
|
+
type: "stop_observed",
|
|
762
|
+
condition: properties.condition,
|
|
763
|
+
});
|
|
764
|
+
} else {
|
|
765
|
+
degradedChannels.add("stop_events");
|
|
766
|
+
}
|
|
767
|
+
} else {
|
|
768
|
+
const prefix = typeof record.type === "string" ? record.type.split(".")[0] : "";
|
|
769
|
+
const classified = {
|
|
770
|
+
skill: "skill_events",
|
|
771
|
+
tool: "tool_events",
|
|
772
|
+
review: "review_events",
|
|
773
|
+
stop: "stop_events",
|
|
774
|
+
}[prefix];
|
|
775
|
+
if (classified) {
|
|
776
|
+
degradedChannels.add(classified);
|
|
777
|
+
} else {
|
|
778
|
+
for (const channel of coverageChannels.filter((name) => name !== "session_events")) {
|
|
779
|
+
degradedChannels.add(channel);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
for (const channel of degradedChannels) coverage[channel] = "partial";
|
|
786
|
+
if (sessionCaptureIncomplete) coverage.session_events = "partial";
|
|
787
|
+
const errorCodes = [];
|
|
788
|
+
if (rootError) errorCodes.push(rootError);
|
|
789
|
+
if (sessionCaptureIncomplete && !rootError) errorCodes.push("capture-incomplete");
|
|
790
|
+
if (degradedChannels.size > 0) errorCodes.push("unknown-live-event");
|
|
791
|
+
errorCodes.push(...explicitRunErrors);
|
|
792
|
+
if (processResult.timedOut) errorCodes.push("timeout");
|
|
793
|
+
else if (processResult.cancelled) errorCodes.push("cancelled");
|
|
794
|
+
else if (processResult.exitCode !== 0) errorCodes.push("opencode-exit");
|
|
795
|
+
for (const code of errorCodes) {
|
|
796
|
+
events.push({ sequence: sequence++, type: "run_error", code });
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
if (events.length === 0 || events[0].type !== "session_started") {
|
|
800
|
+
events.unshift({
|
|
801
|
+
sequence: 1,
|
|
802
|
+
type: "session_started",
|
|
803
|
+
session_id: "session-1",
|
|
804
|
+
parent_session_id: null,
|
|
805
|
+
agent: "unknown-agent",
|
|
806
|
+
});
|
|
807
|
+
for (let index = 1; index < events.length; index += 1) {
|
|
808
|
+
events[index].sequence = index + 1;
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
return {
|
|
812
|
+
schema_version: 1,
|
|
813
|
+
scenario_id: scenario.id,
|
|
814
|
+
observation_coverage: coverage,
|
|
815
|
+
git_snapshot: gitSnapshot,
|
|
816
|
+
events,
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
function writeAll(descriptor, chunk) {
|
|
821
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
822
|
+
let offset = 0;
|
|
823
|
+
while (offset < buffer.length) {
|
|
824
|
+
offset += fs.writeSync(descriptor, buffer, offset, buffer.length - offset);
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
function openExclusiveRegular(file, { readable = false } = {}) {
|
|
829
|
+
let descriptor;
|
|
830
|
+
try {
|
|
831
|
+
descriptor = fs.openSync(
|
|
832
|
+
file,
|
|
833
|
+
(readable ? fs.constants.O_RDWR : fs.constants.O_WRONLY)
|
|
834
|
+
| fs.constants.O_CREAT
|
|
835
|
+
| fs.constants.O_EXCL
|
|
836
|
+
| (fs.constants.O_NOFOLLOW ?? 0),
|
|
837
|
+
0o600,
|
|
838
|
+
);
|
|
839
|
+
const stat = fs.fstatSync(descriptor);
|
|
840
|
+
if (!stat.isFile()) throw new LiveReplayError("Raw output must be a regular file.");
|
|
841
|
+
fs.fchmodSync(descriptor, 0o600);
|
|
842
|
+
return descriptor;
|
|
843
|
+
} catch (error) {
|
|
844
|
+
if (descriptor !== undefined) fs.closeSync(descriptor);
|
|
845
|
+
if (error instanceof LiveReplayError) throw error;
|
|
846
|
+
throw new LiveReplayError("Unable to create a secure output file.");
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
function createCaptureSink(descriptor, limitBytes) {
|
|
851
|
+
const decoder = new StringDecoder("utf8");
|
|
852
|
+
let captured = "";
|
|
853
|
+
let capturedBytes = 0;
|
|
854
|
+
let truncated = false;
|
|
855
|
+
return {
|
|
856
|
+
write(chunk) {
|
|
857
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
858
|
+
writeAll(descriptor, buffer);
|
|
859
|
+
const remaining = Math.max(0, limitBytes - capturedBytes);
|
|
860
|
+
if (remaining > 0) {
|
|
861
|
+
const selected = buffer.subarray(0, remaining);
|
|
862
|
+
captured += decoder.write(selected);
|
|
863
|
+
capturedBytes += selected.length;
|
|
864
|
+
}
|
|
865
|
+
if (buffer.length > remaining) truncated = true;
|
|
866
|
+
},
|
|
867
|
+
finish() {
|
|
868
|
+
captured += decoder.end();
|
|
869
|
+
return { text: captured, truncated };
|
|
870
|
+
},
|
|
871
|
+
};
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
function assertRegularContainedFile(file, directory, expectedIdentity) {
|
|
875
|
+
const stat = fs.lstatSync(file);
|
|
876
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
877
|
+
throw new LiveReplayError("Raw output path is not a regular file.");
|
|
878
|
+
}
|
|
879
|
+
if (expectedIdentity
|
|
880
|
+
&& (stat.dev !== expectedIdentity.dev || stat.ino !== expectedIdentity.ino)) {
|
|
881
|
+
throw new LiveReplayError("Raw output file identity changed.");
|
|
882
|
+
}
|
|
883
|
+
if (!isWithin(fs.realpathSync(file), fs.realpathSync(directory))) {
|
|
884
|
+
throw new LiveReplayError("Raw output path escaped its private directory.");
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
function copyDescriptorSecure(sourceDescriptor, destination) {
|
|
889
|
+
let destinationDescriptor;
|
|
890
|
+
try {
|
|
891
|
+
if (!fs.fstatSync(sourceDescriptor).isFile()) {
|
|
892
|
+
throw new LiveReplayError("Retained source must be a regular file.");
|
|
893
|
+
}
|
|
894
|
+
destinationDescriptor = openExclusiveRegular(destination);
|
|
895
|
+
const buffer = Buffer.allocUnsafe(64 * 1024);
|
|
896
|
+
let bytesRead;
|
|
897
|
+
let position = 0;
|
|
898
|
+
do {
|
|
899
|
+
bytesRead = fs.readSync(sourceDescriptor, buffer, 0, buffer.length, position);
|
|
900
|
+
if (bytesRead > 0) {
|
|
901
|
+
writeAll(destinationDescriptor, buffer.subarray(0, bytesRead));
|
|
902
|
+
position += bytesRead;
|
|
903
|
+
}
|
|
904
|
+
} while (bytesRead > 0);
|
|
905
|
+
fs.fchmodSync(destinationDescriptor, 0o600);
|
|
906
|
+
} catch (error) {
|
|
907
|
+
if (error instanceof LiveReplayError) throw error;
|
|
908
|
+
throw new LiveReplayError("Unable to retain private output securely.");
|
|
909
|
+
} finally {
|
|
910
|
+
if (destinationDescriptor !== undefined) fs.closeSync(destinationDescriptor);
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
function assertRetentionDirectoryIdentity(destination, expectedResolved) {
|
|
915
|
+
assertNoSymlinkComponents(destination);
|
|
916
|
+
const stat = fs.lstatSync(destination);
|
|
917
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()
|
|
918
|
+
|| fs.realpathSync(destination) !== expectedResolved) {
|
|
919
|
+
throw new LiveReplayError("Retention directory identity changed.");
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
function retainPrivateOutput(destination, rawDescriptors) {
|
|
924
|
+
if (!fs.existsSync(destination)) fs.mkdirSync(destination, { mode: 0o700 });
|
|
925
|
+
const expectedResolved = fs.realpathSync(destination);
|
|
926
|
+
assertRetentionDirectoryIdentity(destination, expectedResolved);
|
|
927
|
+
let directoryDescriptor;
|
|
928
|
+
try {
|
|
929
|
+
directoryDescriptor = fs.openSync(
|
|
930
|
+
destination,
|
|
931
|
+
fs.constants.O_RDONLY
|
|
932
|
+
| (fs.constants.O_DIRECTORY ?? 0)
|
|
933
|
+
| (fs.constants.O_NOFOLLOW ?? 0),
|
|
934
|
+
);
|
|
935
|
+
if (!fs.fstatSync(directoryDescriptor).isDirectory()) {
|
|
936
|
+
throw new LiveReplayError("Retention destination must remain a directory.");
|
|
937
|
+
}
|
|
938
|
+
fs.fchmodSync(directoryDescriptor, 0o700);
|
|
939
|
+
copyDescriptorSecure(rawDescriptors.stdout, path.join(destination, "stdout.jsonl"));
|
|
940
|
+
copyDescriptorSecure(rawDescriptors.stderr, path.join(destination, "stderr.log"));
|
|
941
|
+
assertRetentionDirectoryIdentity(destination, expectedResolved);
|
|
942
|
+
} finally {
|
|
943
|
+
if (directoryDescriptor !== undefined) fs.closeSync(directoryDescriptor);
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
function addLimitation(report, code) {
|
|
948
|
+
for (const result of report.scenario_results) {
|
|
949
|
+
if (!result.limitations.some((row) => row.code === code)) {
|
|
950
|
+
result.limitations.push({
|
|
951
|
+
code,
|
|
952
|
+
channels: [],
|
|
953
|
+
});
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
function addCleanupFailure(report) {
|
|
959
|
+
report.operational_status = "cleanup-failed";
|
|
960
|
+
addLimitation(report, "cleanup-failed");
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
function exitCodeForReport(report) {
|
|
964
|
+
if (report.operational_status !== "ok") return 2;
|
|
965
|
+
if (report.status === "pass") return 0;
|
|
966
|
+
if (report.status === "fail") return 1;
|
|
967
|
+
return 3;
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
function buildCommand(scenario, tempRoot) {
|
|
971
|
+
const args = ["run", "--format", "json", "--thinking"];
|
|
972
|
+
if (scenario.command_path !== "freeform") {
|
|
973
|
+
args.push("--command", scenario.command_path.replace(/^\//, ""));
|
|
974
|
+
} else if (scenario.expected_root_agent !== "lead") {
|
|
975
|
+
throw new LiveReplayError("Freeform live replay requires lead as the expected root.");
|
|
976
|
+
}
|
|
977
|
+
args.push("--dir", tempRoot, scenario.prompt);
|
|
978
|
+
return args;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
export async function runLiveReplay(options, deps = defaultDeps) {
|
|
982
|
+
let tempRoot;
|
|
983
|
+
let report;
|
|
984
|
+
let observation;
|
|
985
|
+
let postEvaluationFailure = false;
|
|
986
|
+
const rawDescriptors = {
|
|
987
|
+
stdout: undefined,
|
|
988
|
+
stderr: undefined,
|
|
989
|
+
};
|
|
990
|
+
try {
|
|
991
|
+
if (!options || typeof options !== "object") throw new LiveReplayError("Options are required.");
|
|
992
|
+
if (!options.scenarioId) throw new LiveReplayError("--scenario is required.");
|
|
993
|
+
if (!options.confirmLive) throw new LiveReplayError("--confirm-live is required.");
|
|
994
|
+
const timeoutMs = options.timeoutMs ?? 120_000;
|
|
995
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {
|
|
996
|
+
throw new LiveReplayError("timeoutMs must be a positive integer.");
|
|
997
|
+
}
|
|
998
|
+
const scenarios = options.scenarios ?? [];
|
|
999
|
+
try {
|
|
1000
|
+
validateScenarios(scenarios, { file: "live-corpus" });
|
|
1001
|
+
} catch {
|
|
1002
|
+
throw new LiveReplayError("Live replay corpus is invalid.");
|
|
1003
|
+
}
|
|
1004
|
+
const scenario = scenarios.find((row) => row.id === options.scenarioId);
|
|
1005
|
+
if (!scenario) throw new LiveReplayError("Unknown live replay scenario.");
|
|
1006
|
+
const sourceRoot = path.resolve(options.sourceRoot ?? repositoryRoot);
|
|
1007
|
+
const protectedRoots = [sourceRoot, ...(options.protectedRoots ?? [])];
|
|
1008
|
+
let retainDestination;
|
|
1009
|
+
if (options.retainPrivateOutput !== undefined) {
|
|
1010
|
+
retainDestination = validateRetainPath(options.retainPrivateOutput, protectedRoots);
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
const tempCandidate = await deps.makeTempDir();
|
|
1014
|
+
tempRoot = assertSafeTempPath(tempCandidate, sourceRoot, protectedRoots);
|
|
1015
|
+
materializeRepository(tempRoot, sourceRoot);
|
|
1016
|
+
const initialStatus = runGit(tempRoot, ["status", "--porcelain=v1"]);
|
|
1017
|
+
if (initialStatus.trim() !== "") {
|
|
1018
|
+
throw new LiveReplayError("Disposable repository is not clean before launch.");
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
const args = buildCommand(scenario, tempRoot);
|
|
1022
|
+
const rawDir = path.join(tempRoot, ".opencode-live");
|
|
1023
|
+
fs.mkdirSync(rawDir, { mode: 0o700 });
|
|
1024
|
+
const rawFiles = {
|
|
1025
|
+
stdout: path.join(rawDir, "stdout.jsonl"),
|
|
1026
|
+
stderr: path.join(rawDir, "stderr.log"),
|
|
1027
|
+
};
|
|
1028
|
+
let rawIdentities;
|
|
1029
|
+
let stdoutCapture;
|
|
1030
|
+
let stderrCapture;
|
|
1031
|
+
let processResult;
|
|
1032
|
+
try {
|
|
1033
|
+
rawDescriptors.stdout = openExclusiveRegular(rawFiles.stdout, { readable: true });
|
|
1034
|
+
rawDescriptors.stderr = openExclusiveRegular(rawFiles.stderr, { readable: true });
|
|
1035
|
+
rawIdentities = {
|
|
1036
|
+
stdout: fs.fstatSync(rawDescriptors.stdout),
|
|
1037
|
+
stderr: fs.fstatSync(rawDescriptors.stderr),
|
|
1038
|
+
};
|
|
1039
|
+
const captureLimitBytes = options.captureLimitBytes ?? 1024 * 1024;
|
|
1040
|
+
if (!Number.isSafeInteger(captureLimitBytes) || captureLimitBytes <= 0) {
|
|
1041
|
+
throw new LiveReplayError("captureLimitBytes must be a positive integer.");
|
|
1042
|
+
}
|
|
1043
|
+
stdoutCapture = createCaptureSink(rawDescriptors.stdout, captureLimitBytes);
|
|
1044
|
+
stderrCapture = createCaptureSink(
|
|
1045
|
+
rawDescriptors.stderr,
|
|
1046
|
+
Math.min(captureLimitBytes, 64 * 1024),
|
|
1047
|
+
);
|
|
1048
|
+
processResult = await deps.spawnProcess(
|
|
1049
|
+
options.executable ?? "opencode",
|
|
1050
|
+
args,
|
|
1051
|
+
{
|
|
1052
|
+
cwd: tempRoot,
|
|
1053
|
+
shell: false,
|
|
1054
|
+
timeoutMs,
|
|
1055
|
+
onStdoutChunk: (chunk) => stdoutCapture.write(chunk),
|
|
1056
|
+
onStderrChunk: (chunk) => stderrCapture.write(chunk),
|
|
1057
|
+
},
|
|
1058
|
+
);
|
|
1059
|
+
if (processResult.stdout !== undefined) stdoutCapture.write(processResult.stdout);
|
|
1060
|
+
if (processResult.stderr !== undefined) stderrCapture.write(processResult.stderr);
|
|
1061
|
+
} catch (error) {
|
|
1062
|
+
if (error instanceof LiveReplayError) throw error;
|
|
1063
|
+
throw new LiveReplayError("Unable to launch OpenCode.");
|
|
1064
|
+
}
|
|
1065
|
+
const rawStat = fs.lstatSync(rawDir);
|
|
1066
|
+
if (rawStat.isSymbolicLink() || !rawStat.isDirectory()
|
|
1067
|
+
|| !isWithin(fs.realpathSync(rawDir), tempRoot)) {
|
|
1068
|
+
throw new LiveReplayError("Raw capture directory escaped the disposable repository.");
|
|
1069
|
+
}
|
|
1070
|
+
assertRegularContainedFile(rawFiles.stdout, rawDir, rawIdentities.stdout);
|
|
1071
|
+
assertRegularContainedFile(rawFiles.stderr, rawDir, rawIdentities.stderr);
|
|
1072
|
+
const stdoutResult = stdoutCapture.finish();
|
|
1073
|
+
stderrCapture.finish();
|
|
1074
|
+
processResult = {
|
|
1075
|
+
...processResult,
|
|
1076
|
+
stdout: stdoutResult.text,
|
|
1077
|
+
captureTruncated: stdoutResult.truncated,
|
|
1078
|
+
};
|
|
1079
|
+
|
|
1080
|
+
const parsed = parseRawLines(processResult.stdout);
|
|
1081
|
+
const roots = explicitRootIds(parsed.records);
|
|
1082
|
+
let tree = null;
|
|
1083
|
+
let rootError = processResult.captureTruncated ? "capture-incomplete" : null;
|
|
1084
|
+
if (roots.length === 1) {
|
|
1085
|
+
try {
|
|
1086
|
+
const dbPath = await deps.readOpenCodeDbPath();
|
|
1087
|
+
const collected = await collectStableTree(deps, dbPath, roots[0]);
|
|
1088
|
+
tree = collected.tree;
|
|
1089
|
+
if (!tree || collected.failed) rootError = "capture-incomplete";
|
|
1090
|
+
} catch {
|
|
1091
|
+
rootError = "capture-incomplete";
|
|
1092
|
+
}
|
|
1093
|
+
} else {
|
|
1094
|
+
if (!rootError) {
|
|
1095
|
+
rootError = roots.length === 0 ? "root-session-unresolved" : "capture-incomplete";
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
const finalStatus = runGit(tempRoot, ["status", "--porcelain=v1"]);
|
|
1099
|
+
const gitSnapshot = finalStatus.trim() === "" ? "clean" : "changed";
|
|
1100
|
+
observation = normalizedObservation({
|
|
1101
|
+
scenario,
|
|
1102
|
+
records: parsed.records,
|
|
1103
|
+
malformed: parsed.malformed,
|
|
1104
|
+
tree,
|
|
1105
|
+
rootError,
|
|
1106
|
+
processResult,
|
|
1107
|
+
gitSnapshot,
|
|
1108
|
+
});
|
|
1109
|
+
report = evaluateReplay({
|
|
1110
|
+
scenarios: [scenario],
|
|
1111
|
+
observations: [observation],
|
|
1112
|
+
mode: "live",
|
|
1113
|
+
});
|
|
1114
|
+
|
|
1115
|
+
if (retainDestination) {
|
|
1116
|
+
const checkedDestination = validateRetainPath(
|
|
1117
|
+
retainDestination,
|
|
1118
|
+
protectedRoots,
|
|
1119
|
+
{ requireEmpty: false },
|
|
1120
|
+
);
|
|
1121
|
+
retainPrivateOutput(checkedDestination, rawDescriptors);
|
|
1122
|
+
(options.writeStderr ?? ((text) => process.stderr.write(text)))(sensitiveWarning);
|
|
1123
|
+
}
|
|
1124
|
+
} catch (error) {
|
|
1125
|
+
if (!report) {
|
|
1126
|
+
return {
|
|
1127
|
+
exitCode: 2,
|
|
1128
|
+
error: error instanceof LiveReplayError ? error.message : "Live replay runtime error.",
|
|
1129
|
+
};
|
|
1130
|
+
}
|
|
1131
|
+
postEvaluationFailure = true;
|
|
1132
|
+
addLimitation(report, "retention-failed");
|
|
1133
|
+
} finally {
|
|
1134
|
+
if (rawDescriptors.stdout !== undefined) fs.closeSync(rawDescriptors.stdout);
|
|
1135
|
+
if (rawDescriptors.stderr !== undefined) fs.closeSync(rawDescriptors.stderr);
|
|
1136
|
+
if (tempRoot) {
|
|
1137
|
+
try {
|
|
1138
|
+
await deps.removeTree(tempRoot);
|
|
1139
|
+
} catch {
|
|
1140
|
+
if (report) addCleanupFailure(report);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
return {
|
|
1145
|
+
exitCode: postEvaluationFailure ? 2 : exitCodeForReport(report),
|
|
1146
|
+
report,
|
|
1147
|
+
observation,
|
|
1148
|
+
};
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
function loadScenarios(file) {
|
|
1152
|
+
const contents = fs.readFileSync(file, "utf8").trim();
|
|
1153
|
+
return contents ? contents.split("\n").map((line) => JSON.parse(line)) : [];
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
async function main() {
|
|
1157
|
+
try {
|
|
1158
|
+
const options = parseLiveArguments(process.argv.slice(2));
|
|
1159
|
+
const result = await runLiveReplay({
|
|
1160
|
+
...options,
|
|
1161
|
+
sourceRoot: repositoryRoot,
|
|
1162
|
+
scenarios: loadScenarios(defaultCorpus),
|
|
1163
|
+
protectedRoots: [repositoryRoot],
|
|
1164
|
+
});
|
|
1165
|
+
if (result.report) process.stdout.write(serializeReport(result.report));
|
|
1166
|
+
if (result.error) process.stderr.write(`LiveReplayError: ${result.error}\n`);
|
|
1167
|
+
process.exitCode = result.exitCode;
|
|
1168
|
+
} catch (error) {
|
|
1169
|
+
const message = error instanceof LiveReplayError
|
|
1170
|
+
? error.message
|
|
1171
|
+
: "Live replay input error.";
|
|
1172
|
+
process.stderr.write(`LiveReplayError: ${message}\n`);
|
|
1173
|
+
process.exitCode = 2;
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
const entryPath = process.argv[1] === undefined ? null : fs.realpathSync(process.argv[1]);
|
|
1178
|
+
if (entryPath === fs.realpathSync(fileURLToPath(import.meta.url))) {
|
|
1179
|
+
await main();
|
|
1180
|
+
}
|