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.
Files changed (49) hide show
  1. package/README.md +32 -9
  2. package/docker/open-design/Dockerfile +2 -2
  3. package/docs/compatibility.md +28 -8
  4. package/docs/docker-open-design.md +8 -0
  5. package/docs/installation.md +9 -3
  6. package/docs/quickstart.md +6 -3
  7. package/docs/releases/v1.0.29.md +78 -0
  8. package/docs/releases/v1.0.30.md +64 -0
  9. package/docs/security.md +9 -0
  10. package/docs/superpowers.md +11 -4
  11. package/docs/supply-chain.md +145 -0
  12. package/docs/workflows.md +15 -0
  13. package/opencode/docs/ai/evolution/README.md +15 -2
  14. package/opencode/docs/ai/evolution/benchmarks/replay-fixtures.jsonl +14 -0
  15. package/opencode/docs/ai/evolution/benchmarks/router-scenarios.jsonl +14 -8
  16. package/opencode/docs/ai/harness/checks.md +29 -2
  17. package/opencode/docs/ai/harness/evidence.md +29 -0
  18. package/opencode/opencode.json +1 -1
  19. package/opencode/package-lock.json +92 -95
  20. package/opencode/package.json +2 -1
  21. package/opencode/scripts/check-harness.mjs +369 -29
  22. package/opencode/scripts/check-harness.test.mjs +377 -14
  23. package/opencode/scripts/collect-session-evidence.mjs +14 -0
  24. package/opencode/scripts/collect-session-evidence.test.mjs +142 -6
  25. package/opencode/scripts/replay-routing.mjs +1012 -0
  26. package/opencode/scripts/replay-routing.test.mjs +1454 -0
  27. package/opencode/scripts/run-routing-live-replay.mjs +1180 -0
  28. package/opencode/scripts/run-routing-live-replay.test.mjs +1906 -0
  29. package/package.json +25 -3
  30. package/scripts/check-compatibility.mjs +65 -12
  31. package/scripts/check-compatibility.test.mjs +228 -32
  32. package/scripts/check-supply-chain.mjs +635 -0
  33. package/scripts/check-supply-chain.test.mjs +944 -0
  34. package/scripts/check.sh +9 -5
  35. package/scripts/install-smoke.sh +1 -1
  36. package/scripts/opencode-compat-smoke.sh +97 -7
  37. package/scripts/package-smoke.mjs +357 -0
  38. package/scripts/package-smoke.sh +5 -0
  39. package/scripts/package-smoke.test.mjs +256 -0
  40. package/scripts/version.test.mjs +2 -2
  41. package/supply-chain.json +34 -0
  42. package/.github/CODEOWNERS +0 -1
  43. package/.github/ISSUE_TEMPLATE/bug_report.yml +0 -65
  44. package/.github/ISSUE_TEMPLATE/config.yml +0 -11
  45. package/.github/ISSUE_TEMPLATE/documentation.yml +0 -22
  46. package/.github/ISSUE_TEMPLATE/feature_request.yml +0 -43
  47. package/.github/PULL_REQUEST_TEMPLATE.md +0 -25
  48. package/.github/workflows/check.yml +0 -92
  49. package/.github/workflows/compatibility-canary.yml +0 -28
@@ -0,0 +1,1012 @@
1
+ #!/usr/bin/env node
2
+
3
+ import crypto from "node:crypto";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+
8
+ const fixtureKeys = [
9
+ "schema_version",
10
+ "scenario_id",
11
+ "observation_coverage",
12
+ "git_snapshot",
13
+ "events",
14
+ ];
15
+ const scenarioKeys = [
16
+ "schema_version",
17
+ "id",
18
+ "category",
19
+ "command_path",
20
+ "prompt",
21
+ "expected_root_agent",
22
+ "required_agents",
23
+ "forbidden_agents",
24
+ "allowed_skills",
25
+ "forbidden_skills",
26
+ "write_before_spec_policy",
27
+ "review_policy",
28
+ "expected_stop_condition",
29
+ "maximum_delegation_budget",
30
+ "required_evidence",
31
+ ];
32
+ const coverageChannels = [
33
+ "session_events",
34
+ "skill_events",
35
+ "tool_events",
36
+ "review_events",
37
+ "stop_events",
38
+ ];
39
+ const eventKeys = {
40
+ session_started: ["sequence", "type", "session_id", "parent_session_id", "agent"],
41
+ session_completed: ["sequence", "type", "session_id", "agent"],
42
+ skill_selected: ["sequence", "type", "session_id", "agent", "skill"],
43
+ tool_call_completed: ["sequence", "type", "session_id", "agent", "tool", "mutation"],
44
+ review_completed: ["sequence", "type", "session_id", "agent", "verdict"],
45
+ stop_observed: ["sequence", "type", "condition"],
46
+ run_error: ["sequence", "type", "code"],
47
+ };
48
+ const assertionIds = [
49
+ "observation-integrity",
50
+ "root-agent",
51
+ "required-agents",
52
+ "forbidden-agents",
53
+ "skills",
54
+ "write-before-spec",
55
+ "review-policy",
56
+ "stop-condition",
57
+ "delegation-budget",
58
+ ];
59
+ const portableIdentifierPattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
60
+ const reportValuePattern = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
61
+ const sensitiveMaterialPatterns = [
62
+ /\/(?:Users|home)\//i,
63
+ /https?:\/\//i,
64
+ /\b(?:provider|model|endpoint|token|secret|prompt|thinking|reasoning|password|username|credential|api[_-]?key)\b/i,
65
+ ];
66
+ const sensitiveScenarioPatterns = [
67
+ /\/(?:Users|home)\//i,
68
+ /https?:\/\//i,
69
+ /\b(?:provider|model|endpoint|token|secret|api[_-]?key)\b/i,
70
+ ];
71
+
72
+ export class ReplayInputError extends Error {
73
+ constructor(message) {
74
+ super(message);
75
+ this.name = "ReplayInputError";
76
+ }
77
+ }
78
+
79
+ function inputError(file, line, field, reason) {
80
+ throw new ReplayInputError(`${file}: line ${line} ${field} ${reason}`);
81
+ }
82
+
83
+ function isObject(value) {
84
+ return value !== null && typeof value === "object" && !Array.isArray(value);
85
+ }
86
+
87
+ function requireNonEmptyString(value, file, line, field) {
88
+ if (typeof value !== "string" || value.length === 0) {
89
+ inputError(file, line, field, "must be a non-empty string");
90
+ }
91
+ }
92
+
93
+ function validateExactKeys(record, expected, file, line, prefix = "") {
94
+ for (const key of expected) {
95
+ if (!Object.hasOwn(record, key)) {
96
+ inputError(file, line, `${prefix}${key}`, "missing field");
97
+ }
98
+ }
99
+ for (const key of Object.keys(record)) {
100
+ if (!expected.includes(key)) {
101
+ inputError(file, line, `${prefix}${key}`, "unknown field");
102
+ }
103
+ }
104
+ }
105
+
106
+ function parseJsonl(file) {
107
+ let contents;
108
+ try {
109
+ contents = fs.readFileSync(file, "utf8");
110
+ } catch {
111
+ inputError(file, 1, "record", "unable to read");
112
+ }
113
+
114
+ const physicalLines = contents.split("\n");
115
+ if (physicalLines.at(-1) === "") physicalLines.pop();
116
+ if (physicalLines.length === 0) inputError(file, 1, "record", "missing value");
117
+
118
+ return physicalLines.map((text, index) => {
119
+ const line = index + 1;
120
+ if (text.trim() === "") inputError(file, line, "record", "blank line");
121
+ let record;
122
+ try {
123
+ record = JSON.parse(text);
124
+ } catch {
125
+ inputError(file, line, "record", "invalid JSON");
126
+ }
127
+ if (!isObject(record)) inputError(file, line, "record", "must be an object");
128
+ return { record, line };
129
+ });
130
+ }
131
+
132
+ function parseArguments(argv) {
133
+ const allowed = new Set(["--corpus", "--fixtures", "--output"]);
134
+ const values = {};
135
+ for (let index = 0; index < argv.length; index += 2) {
136
+ const option = argv[index];
137
+ if (!allowed.has(option)) {
138
+ throw new ReplayInputError(`arguments: line 1 ${option ?? "argument"} unknown option`);
139
+ }
140
+ if (Object.hasOwn(values, option)) {
141
+ throw new ReplayInputError(`arguments: line 1 ${option} duplicate option`);
142
+ }
143
+ const value = argv[index + 1];
144
+ if (typeof value !== "string" || value.length === 0 || value.startsWith("--")) {
145
+ throw new ReplayInputError(`arguments: line 1 ${option} missing value`);
146
+ }
147
+ values[option] = value;
148
+ }
149
+ for (const option of ["--corpus", "--fixtures"]) {
150
+ if (!Object.hasOwn(values, option)) {
151
+ throw new ReplayInputError(`arguments: line 1 ${option} missing option`);
152
+ }
153
+ }
154
+ return {
155
+ corpus: values["--corpus"],
156
+ fixtures: values["--fixtures"],
157
+ output: values["--output"],
158
+ };
159
+ }
160
+
161
+ function validateScenario(record, file, line, ids) {
162
+ validateExactKeys(record, scenarioKeys, file, line);
163
+ if (record.schema_version !== 1) inputError(file, line, "schema_version", "unknown value");
164
+ requireNonEmptyString(record.id, file, line, "id");
165
+ if (ids.has(record.id)) inputError(file, line, "id", `duplicate value ${record.id}`);
166
+ ids.add(record.id);
167
+ requireNonEmptyString(record.expected_root_agent, file, line, "expected_root_agent");
168
+ requireNonEmptyString(record.expected_stop_condition, file, line, "expected_stop_condition");
169
+ for (const field of ["category", "command_path", "prompt"]) {
170
+ requireNonEmptyString(record[field], file, line, field);
171
+ }
172
+ for (const field of [
173
+ "required_agents",
174
+ "forbidden_agents",
175
+ "allowed_skills",
176
+ "forbidden_skills",
177
+ "required_evidence",
178
+ ]) {
179
+ if (!Array.isArray(record[field]) || record[field].some(
180
+ (value) => typeof value !== "string" || value.length === 0,
181
+ )) {
182
+ inputError(file, line, field, "must be an array of non-empty strings");
183
+ }
184
+ }
185
+ if (!["allowed", "forbidden", "not-applicable"].includes(
186
+ record.write_before_spec_policy,
187
+ )) {
188
+ inputError(file, line, "write_before_spec_policy", "unknown value");
189
+ }
190
+ if (!["required", "forbidden", "optional"].includes(record.review_policy)) {
191
+ inputError(file, line, "review_policy", "unknown value");
192
+ }
193
+ if (!Number.isInteger(record.maximum_delegation_budget)
194
+ || record.maximum_delegation_budget < 0) {
195
+ inputError(file, line, "maximum_delegation_budget", "must be a non-negative integer");
196
+ }
197
+ }
198
+
199
+ function validateFixture(record, file, line, scenarioIds) {
200
+ validateExactKeys(record, fixtureKeys, file, line);
201
+ if (record.schema_version !== 1) inputError(file, line, "schema_version", "unknown value");
202
+ requireNonEmptyString(record.scenario_id, file, line, "scenario_id");
203
+ if (!scenarioIds.has(record.scenario_id)) {
204
+ inputError(file, line, "scenario_id", `unknown value ${record.scenario_id}`);
205
+ }
206
+ if (!isObject(record.observation_coverage)) {
207
+ inputError(file, line, "observation_coverage", "must be an object");
208
+ }
209
+ validateExactKeys(
210
+ record.observation_coverage,
211
+ coverageChannels,
212
+ file,
213
+ line,
214
+ "observation_coverage.",
215
+ );
216
+ for (const channel of coverageChannels) {
217
+ if (!["complete", "partial", "unavailable"].includes(
218
+ record.observation_coverage[channel],
219
+ )) {
220
+ inputError(file, line, `observation_coverage.${channel}`, "unknown value");
221
+ }
222
+ }
223
+ if (!["clean", "changed", "unavailable"].includes(record.git_snapshot)) {
224
+ inputError(file, line, "git_snapshot", "unknown value");
225
+ }
226
+ if (!Array.isArray(record.events)) inputError(file, line, "events", "must be an array");
227
+
228
+ let previousSequence = 0;
229
+ const sessions = new Map();
230
+ let rootSeen = false;
231
+ for (const [index, event] of record.events.entries()) {
232
+ const prefix = `events[${index}].`;
233
+ if (!isObject(event)) inputError(file, line, `events[${index}]`, "must be an object");
234
+ if (!Object.hasOwn(event, "type")) inputError(file, line, `${prefix}type`, "missing field");
235
+ if (!Object.hasOwn(eventKeys, event.type)) {
236
+ inputError(file, line, `${prefix}type`, `unknown value ${String(event.type)}`);
237
+ }
238
+ validateExactKeys(event, eventKeys[event.type], file, line, prefix);
239
+ if (!Number.isInteger(event.sequence) || event.sequence <= previousSequence) {
240
+ inputError(file, line, `${prefix}sequence`, "must be strictly increasing");
241
+ }
242
+ previousSequence = event.sequence;
243
+
244
+ if (event.type === "session_started") {
245
+ requireNonEmptyString(event.session_id, file, line, `${prefix}session_id`);
246
+ requireNonEmptyString(event.agent, file, line, `${prefix}agent`);
247
+ if (sessions.has(event.session_id)) {
248
+ inputError(file, line, `${prefix}session_id`, `duplicate session ${event.session_id}`);
249
+ }
250
+ if (!rootSeen) {
251
+ if (event.parent_session_id !== null) {
252
+ inputError(file, line, `${prefix}parent_session_id`, "root must have null parent");
253
+ }
254
+ rootSeen = true;
255
+ } else {
256
+ requireNonEmptyString(
257
+ event.parent_session_id,
258
+ file,
259
+ line,
260
+ `${prefix}parent_session_id`,
261
+ );
262
+ if (!sessions.has(event.parent_session_id)) {
263
+ inputError(
264
+ file,
265
+ line,
266
+ `${prefix}parent_session_id`,
267
+ `unknown session ${event.parent_session_id}`,
268
+ );
269
+ }
270
+ }
271
+ sessions.set(event.session_id, event.agent);
272
+ continue;
273
+ }
274
+
275
+ if (event.type === "stop_observed") {
276
+ requireNonEmptyString(event.condition, file, line, `${prefix}condition`);
277
+ continue;
278
+ }
279
+ if (event.type === "run_error") {
280
+ requireNonEmptyString(event.code, file, line, `${prefix}code`);
281
+ if (!portableIdentifierPattern.test(event.code)) {
282
+ inputError(file, line, `${prefix}code`, "invalid portable identifier");
283
+ }
284
+ continue;
285
+ }
286
+
287
+ requireNonEmptyString(event.session_id, file, line, `${prefix}session_id`);
288
+ requireNonEmptyString(event.agent, file, line, `${prefix}agent`);
289
+ if (!sessions.has(event.session_id)) {
290
+ inputError(file, line, `${prefix}session_id`, `unknown session ${event.session_id}`);
291
+ }
292
+ if (sessions.get(event.session_id) !== event.agent) {
293
+ inputError(
294
+ file,
295
+ line,
296
+ `${prefix}agent`,
297
+ `does not match started agent ${sessions.get(event.session_id)}`,
298
+ );
299
+ }
300
+ if (event.type === "skill_selected") {
301
+ requireNonEmptyString(event.skill, file, line, `${prefix}skill`);
302
+ } else if (event.type === "tool_call_completed") {
303
+ requireNonEmptyString(event.tool, file, line, `${prefix}tool`);
304
+ if (!["read", "write", "unknown"].includes(event.mutation)) {
305
+ inputError(file, line, `${prefix}mutation`, "unknown value");
306
+ }
307
+ } else if (event.type === "review_completed") {
308
+ if (event.agent !== "reviewer") {
309
+ inputError(file, line, `${prefix}agent`, "must be reviewer");
310
+ }
311
+ if (!["approved", "changes-requested", "blocked"].includes(event.verdict)) {
312
+ inputError(file, line, `${prefix}verdict`, "unknown value");
313
+ }
314
+ }
315
+ }
316
+ if (!rootSeen) inputError(file, line, "events", "missing root session");
317
+ }
318
+
319
+ function assertion(id, status, reasonCode, evidenceSequences = []) {
320
+ return {
321
+ id,
322
+ status,
323
+ reason_code: reasonCode,
324
+ evidence_sequences: [...evidenceSequences].sort((left, right) => left - right),
325
+ };
326
+ }
327
+
328
+ function complete(fixture, channel) {
329
+ return fixture.observation_coverage[channel] === "complete";
330
+ }
331
+
332
+ function aggregate(statuses) {
333
+ if (statuses.includes("fail")) return "fail";
334
+ if (statuses.includes("inconclusive")) return "inconclusive";
335
+ return "pass";
336
+ }
337
+
338
+ function isSafeReportValue(kind, value) {
339
+ const patterns = kind === "scenario"
340
+ ? sensitiveScenarioPatterns
341
+ : sensitiveMaterialPatterns;
342
+ return typeof value === "string"
343
+ && reportValuePattern.test(value)
344
+ && !patterns.some((pattern) => pattern.test(value));
345
+ }
346
+
347
+ function createReportRedactor(scenarios, observations) {
348
+ const usedByKind = new Map();
349
+ const aliasesByKind = new Map();
350
+
351
+ function reserve(kind, value) {
352
+ if (!isSafeReportValue(kind, value)) return;
353
+ if (!usedByKind.has(kind)) usedByKind.set(kind, new Set());
354
+ usedByKind.get(kind).add(value);
355
+ }
356
+
357
+ for (const scenario of scenarios) reserve("scenario", scenario.id);
358
+ for (const observation of observations) {
359
+ for (const event of observation.events) {
360
+ if (Object.hasOwn(event, "agent")) reserve("agent", event.agent);
361
+ if (event.type === "tool_call_completed") reserve("tool", event.tool);
362
+ if (event.type === "run_error") reserve("code", event.code);
363
+ if (event.type === "stop_observed") reserve("condition", event.condition);
364
+ }
365
+ }
366
+
367
+ return function redact(kind, value) {
368
+ if (isSafeReportValue(kind, value)) return value;
369
+ if (!aliasesByKind.has(kind)) aliasesByKind.set(kind, new Map());
370
+ const aliases = aliasesByKind.get(kind);
371
+ if (aliases.has(value)) return aliases.get(value);
372
+ if (!usedByKind.has(kind)) usedByKind.set(kind, new Set());
373
+ const used = usedByKind.get(kind);
374
+ let ordinal = aliases.size + 1;
375
+ let alias = `redacted-${kind}-${ordinal}`;
376
+ while (used.has(alias)) {
377
+ ordinal += 1;
378
+ alias = `redacted-${kind}-${ordinal}`;
379
+ }
380
+ aliases.set(value, alias);
381
+ used.add(alias);
382
+ return alias;
383
+ };
384
+ }
385
+
386
+ function unique(values) {
387
+ const result = [];
388
+ for (const value of values) {
389
+ if (!result.includes(value)) result.push(value);
390
+ }
391
+ return result;
392
+ }
393
+
394
+ function evaluateScenario(scenario, fixture, redact) {
395
+ const starts = fixture.events.filter((event) => event.type === "session_started");
396
+ const root = starts[0];
397
+ const children = starts.slice(1);
398
+ const skills = fixture.events.filter((event) => event.type === "skill_selected");
399
+ const toolEvents = fixture.events.filter((event) => event.type === "tool_call_completed");
400
+ const writes = toolEvents.filter((event) => event.mutation === "write");
401
+ const unknownMutations = toolEvents.filter((event) => event.mutation === "unknown");
402
+ const reviews = fixture.events.filter((event) => event.type === "review_completed");
403
+ const stops = fixture.events.filter((event) => event.type === "stop_observed");
404
+ const runErrors = fixture.events.filter((event) => event.type === "run_error");
405
+ const completedSpecifiers = fixture.events.filter(
406
+ (event) => event.type === "session_completed" && event.agent === "specifier",
407
+ );
408
+ const assertions = [
409
+ assertion("observation-integrity", "pass", "observation-valid"),
410
+ ];
411
+
412
+ if (!complete(fixture, "session_events")) {
413
+ assertions.push(assertion("root-agent", "inconclusive", "session-events-incomplete"));
414
+ } else if (root.agent !== scenario.expected_root_agent) {
415
+ assertions.push(assertion(
416
+ "root-agent",
417
+ "fail",
418
+ "unexpected-root-agent",
419
+ [root.sequence],
420
+ ));
421
+ } else {
422
+ assertions.push(assertion(
423
+ "root-agent",
424
+ "pass",
425
+ "expected-root-observed",
426
+ [root.sequence],
427
+ ));
428
+ }
429
+
430
+ const firstSeenChildren = [];
431
+ for (const event of children) {
432
+ if (!firstSeenChildren.includes(event.agent)) firstSeenChildren.push(event.agent);
433
+ }
434
+ const requiredPositions = scenario.required_agents.map(
435
+ (agent) => firstSeenChildren.indexOf(agent),
436
+ );
437
+ if (requiredPositions.some((position) => position === -1)) {
438
+ assertions.push(complete(fixture, "session_events")
439
+ ? assertion("required-agents", "fail", "required-agent-missing")
440
+ : assertion("required-agents", "inconclusive", "session-events-incomplete"));
441
+ } else if (requiredPositions.some(
442
+ (position, index) => index > 0 && position <= requiredPositions[index - 1],
443
+ )) {
444
+ assertions.push(complete(fixture, "session_events")
445
+ ? assertion("required-agents", "fail", "required-agent-order-mismatch")
446
+ : assertion("required-agents", "inconclusive", "session-events-incomplete"));
447
+ } else if (!complete(fixture, "session_events")) {
448
+ assertions.push(assertion("required-agents", "inconclusive", "session-events-incomplete"));
449
+ } else {
450
+ assertions.push(assertion(
451
+ "required-agents",
452
+ "pass",
453
+ "required-agent-order-observed",
454
+ children
455
+ .filter((event) => scenario.required_agents.includes(event.agent))
456
+ .map((event) => event.sequence),
457
+ ));
458
+ }
459
+
460
+ const forbiddenAgentEvents = starts.filter(
461
+ (event) => scenario.forbidden_agents.includes(event.agent),
462
+ );
463
+ if (forbiddenAgentEvents.length > 0) {
464
+ assertions.push(assertion(
465
+ "forbidden-agents",
466
+ "fail",
467
+ "forbidden-agent-observed",
468
+ forbiddenAgentEvents.map((event) => event.sequence),
469
+ ));
470
+ } else if (!complete(fixture, "session_events")) {
471
+ assertions.push(assertion("forbidden-agents", "inconclusive", "session-events-incomplete"));
472
+ } else {
473
+ assertions.push(assertion(
474
+ "forbidden-agents",
475
+ "pass",
476
+ "no-forbidden-agent-observed",
477
+ ));
478
+ }
479
+
480
+ const forbiddenSkillEvents = skills.filter(
481
+ (event) => scenario.forbidden_skills.includes(event.skill),
482
+ );
483
+ const outsideAllowlistEvents = skills.filter(
484
+ (event) => !scenario.allowed_skills.includes(event.skill),
485
+ );
486
+ if (forbiddenSkillEvents.length > 0) {
487
+ assertions.push(assertion(
488
+ "skills",
489
+ "fail",
490
+ "forbidden-skill-observed",
491
+ forbiddenSkillEvents.map((event) => event.sequence),
492
+ ));
493
+ } else if (outsideAllowlistEvents.length > 0) {
494
+ assertions.push(assertion(
495
+ "skills",
496
+ "fail",
497
+ "skill-not-allowed",
498
+ outsideAllowlistEvents.map((event) => event.sequence),
499
+ ));
500
+ } else if (!complete(fixture, "skill_events")) {
501
+ assertions.push(assertion("skills", "inconclusive", "skill-events-incomplete"));
502
+ } else {
503
+ assertions.push(assertion(
504
+ "skills",
505
+ "pass",
506
+ "skill-allowlist-satisfied",
507
+ skills.map((event) => event.sequence),
508
+ ));
509
+ }
510
+
511
+ const writePolicy = scenario.write_before_spec_policy;
512
+ if (writePolicy === "allowed") {
513
+ assertions.push(assertion(
514
+ "write-before-spec",
515
+ "pass",
516
+ writes.length === 0 ? "no-write-observed" : "write-before-spec-allowed",
517
+ writes.map((event) => event.sequence),
518
+ ));
519
+ } else if (writePolicy === "not-applicable") {
520
+ if (writes.length > 0) {
521
+ assertions.push(assertion(
522
+ "write-before-spec",
523
+ "fail",
524
+ "write-observed-when-not-applicable",
525
+ writes.map((event) => event.sequence),
526
+ ));
527
+ } else if (fixture.git_snapshot === "changed") {
528
+ assertions.push(assertion(
529
+ "write-before-spec",
530
+ "fail",
531
+ "git-changed-when-write-not-applicable",
532
+ ));
533
+ } else if (unknownMutations.length > 0) {
534
+ assertions.push(assertion(
535
+ "write-before-spec",
536
+ "inconclusive",
537
+ "write-mutation-unknown",
538
+ unknownMutations.map((event) => event.sequence),
539
+ ));
540
+ } else if (complete(fixture, "tool_events") || fixture.git_snapshot === "clean") {
541
+ assertions.push(assertion("write-before-spec", "pass", "no-write-observed"));
542
+ } else {
543
+ assertions.push(assertion("write-before-spec", "inconclusive", "write-evidence-incomplete"));
544
+ }
545
+ } else {
546
+ const lastSpecifierCompletion = completedSpecifiers.at(-1)?.sequence;
547
+ const prematureWrites = writes.filter(
548
+ (event) => lastSpecifierCompletion === undefined
549
+ || event.sequence < lastSpecifierCompletion,
550
+ );
551
+ if (prematureWrites.length > 0) {
552
+ assertions.push(assertion(
553
+ "write-before-spec",
554
+ "fail",
555
+ "write-before-spec-completed",
556
+ prematureWrites.map((event) => event.sequence),
557
+ ));
558
+ } else if (unknownMutations.length > 0) {
559
+ assertions.push(assertion(
560
+ "write-before-spec",
561
+ "inconclusive",
562
+ "write-mutation-unknown",
563
+ unknownMutations.map((event) => event.sequence),
564
+ ));
565
+ } else if (fixture.git_snapshot === "changed" && writes.length === 0) {
566
+ assertions.push(assertion(
567
+ "write-before-spec",
568
+ "inconclusive",
569
+ "git-write-unsequenced",
570
+ ));
571
+ } else if (!complete(fixture, "tool_events")
572
+ || !complete(fixture, "session_events")) {
573
+ assertions.push(assertion(
574
+ "write-before-spec",
575
+ "inconclusive",
576
+ "write-or-session-events-incomplete",
577
+ ));
578
+ } else {
579
+ assertions.push(assertion(
580
+ "write-before-spec",
581
+ "pass",
582
+ writes.length === 0 ? "no-write-observed" : "write-after-spec-completed",
583
+ writes.map((event) => event.sequence),
584
+ ));
585
+ }
586
+ }
587
+
588
+ const reviewerStarts = starts.filter((event) => event.agent === "reviewer");
589
+ const lastWrite = writes.at(-1)?.sequence;
590
+ const lastReview = reviews.at(-1)?.sequence;
591
+ const unknownAfterReview = lastReview === undefined
592
+ ? []
593
+ : unknownMutations.filter((event) => event.sequence > lastReview);
594
+ const hasUnsequencedGitMutation = fixture.git_snapshot === "changed"
595
+ && writes.length === 0;
596
+ if (scenario.review_policy === "forbidden") {
597
+ if (reviewerStarts.length > 0 || reviews.length > 0) {
598
+ assertions.push(assertion(
599
+ "review-policy",
600
+ "fail",
601
+ "reviewer-forbidden",
602
+ [...reviewerStarts, ...reviews]
603
+ .map((event) => event.sequence)
604
+ .sort((left, right) => left - right),
605
+ ));
606
+ } else if (!complete(fixture, "session_events")
607
+ || !complete(fixture, "review_events")) {
608
+ assertions.push(assertion(
609
+ "review-policy",
610
+ "inconclusive",
611
+ "review-events-incomplete",
612
+ ));
613
+ } else {
614
+ assertions.push(assertion(
615
+ "review-policy",
616
+ "pass",
617
+ "review-forbidden-and-absent",
618
+ ));
619
+ }
620
+ } else if (scenario.review_policy === "required") {
621
+ if (reviews.length === 0) {
622
+ assertions.push(complete(fixture, "review_events")
623
+ ? assertion("review-policy", "fail", "required-review-missing")
624
+ : assertion("review-policy", "inconclusive", "review-events-incomplete"));
625
+ } else if (lastWrite !== undefined && lastReview < lastWrite
626
+ && complete(fixture, "review_events")) {
627
+ assertions.push(assertion(
628
+ "review-policy",
629
+ "fail",
630
+ "write-after-review",
631
+ [lastReview, lastWrite],
632
+ ));
633
+ } else if (unknownAfterReview.length > 0) {
634
+ assertions.push(assertion(
635
+ "review-policy",
636
+ "inconclusive",
637
+ "write-order-unknown-after-review",
638
+ [lastReview, ...unknownAfterReview.map((event) => event.sequence)],
639
+ ));
640
+ } else if (hasUnsequencedGitMutation) {
641
+ assertions.push(assertion(
642
+ "review-policy",
643
+ "inconclusive",
644
+ "git-write-unsequenced",
645
+ ));
646
+ } else if (!complete(fixture, "review_events")
647
+ || !complete(fixture, "tool_events")) {
648
+ assertions.push(assertion(
649
+ "review-policy",
650
+ "inconclusive",
651
+ "review-or-tool-events-incomplete",
652
+ ));
653
+ } else {
654
+ assertions.push(assertion(
655
+ "review-policy",
656
+ "pass",
657
+ "required-review-completed",
658
+ reviews.map((event) => event.sequence),
659
+ ));
660
+ }
661
+ } else if (reviews.length === 0) {
662
+ assertions.push(assertion("review-policy", "pass", "optional-review-absent"));
663
+ } else if (lastWrite !== undefined && lastReview < lastWrite
664
+ && !complete(fixture, "review_events")) {
665
+ assertions.push(assertion(
666
+ "review-policy",
667
+ "inconclusive",
668
+ "review-events-incomplete",
669
+ [lastReview, lastWrite],
670
+ ));
671
+ } else if (lastWrite !== undefined && lastReview < lastWrite) {
672
+ assertions.push(assertion(
673
+ "review-policy",
674
+ "fail",
675
+ "write-after-review",
676
+ [lastReview, lastWrite],
677
+ ));
678
+ } else if (unknownAfterReview.length > 0) {
679
+ assertions.push(assertion(
680
+ "review-policy",
681
+ "inconclusive",
682
+ "write-order-unknown-after-review",
683
+ [lastReview, ...unknownAfterReview.map((event) => event.sequence)],
684
+ ));
685
+ } else if (hasUnsequencedGitMutation) {
686
+ assertions.push(assertion(
687
+ "review-policy",
688
+ "inconclusive",
689
+ "git-write-unsequenced",
690
+ ));
691
+ } else if (!complete(fixture, "tool_events")) {
692
+ assertions.push(assertion(
693
+ "review-policy",
694
+ "inconclusive",
695
+ "tool-events-incomplete",
696
+ reviews.map((event) => event.sequence),
697
+ ));
698
+ } else {
699
+ assertions.push(assertion(
700
+ "review-policy",
701
+ "pass",
702
+ "optional-review-order-satisfied",
703
+ reviews.map((event) => event.sequence),
704
+ ));
705
+ }
706
+
707
+ const wrongStops = stops.filter(
708
+ (event) => event.condition !== scenario.expected_stop_condition,
709
+ );
710
+ const expectedStops = stops.filter(
711
+ (event) => event.condition === scenario.expected_stop_condition,
712
+ );
713
+ if (wrongStops.length > 0) {
714
+ assertions.push(assertion(
715
+ "stop-condition",
716
+ "fail",
717
+ "unexpected-stop-condition",
718
+ wrongStops.map((event) => event.sequence),
719
+ ));
720
+ } else if (runErrors.length > 0) {
721
+ assertions.push(assertion(
722
+ "stop-condition",
723
+ "inconclusive",
724
+ "run-error-observed",
725
+ runErrors.map((event) => event.sequence),
726
+ ));
727
+ } else if (expectedStops.length === 0) {
728
+ assertions.push(assertion("stop-condition", "inconclusive", "stop-not-observed"));
729
+ } else if (!complete(fixture, "stop_events")) {
730
+ assertions.push(assertion("stop-condition", "inconclusive", "stop-events-incomplete"));
731
+ } else {
732
+ assertions.push(assertion(
733
+ "stop-condition",
734
+ "pass",
735
+ "expected-stop-observed",
736
+ expectedStops.map((event) => event.sequence),
737
+ ));
738
+ }
739
+
740
+ if (children.length > scenario.maximum_delegation_budget) {
741
+ assertions.push(assertion(
742
+ "delegation-budget",
743
+ "fail",
744
+ "delegation-budget-exceeded",
745
+ children.map((event) => event.sequence),
746
+ ));
747
+ } else if (!complete(fixture, "session_events")) {
748
+ assertions.push(assertion(
749
+ "delegation-budget",
750
+ "inconclusive",
751
+ "session-events-incomplete",
752
+ ));
753
+ } else {
754
+ assertions.push(assertion(
755
+ "delegation-budget",
756
+ "pass",
757
+ "delegation-budget-satisfied",
758
+ children.map((event) => event.sequence),
759
+ ));
760
+ }
761
+
762
+ if (assertions.length !== assertionIds.length
763
+ || assertions.some((item, index) => item.id !== assertionIds[index])) {
764
+ throw new Error("internal assertion contract mismatch");
765
+ }
766
+
767
+ const observedAgents = [];
768
+ for (const event of starts) {
769
+ if (!observedAgents.includes(event.agent)) observedAgents.push(event.agent);
770
+ }
771
+ const limitations = runErrors.map((event) => ({
772
+ code: redact("code", event.code),
773
+ channels: coverageChannels.filter(
774
+ (channel) => fixture.observation_coverage[channel] !== "complete",
775
+ ),
776
+ }));
777
+
778
+ return {
779
+ scenario_id: redact("scenario", scenario.id),
780
+ status: aggregate(assertions.map((item) => item.status)),
781
+ assertions,
782
+ observed_agents: unique(observedAgents.map((agent) => redact("agent", agent))),
783
+ delegation_count: children.length,
784
+ writes: writes.map((event) => ({
785
+ sequence: event.sequence,
786
+ agent: redact("agent", event.agent),
787
+ tool: redact("tool", event.tool),
788
+ })),
789
+ review_sequence: reviews.map((event) => ({
790
+ sequence: event.sequence,
791
+ agent: redact("agent", event.agent),
792
+ verdict: event.verdict,
793
+ })),
794
+ observed_stop_condition: stops[0]?.condition !== undefined
795
+ ? redact("condition", stops[0].condition)
796
+ : null,
797
+ limitations,
798
+ };
799
+ }
800
+
801
+ function buildReport(scenarios, observations, mode) {
802
+ const canonicalCorpus = `${scenarios
803
+ .slice()
804
+ .sort((left, right) => left.id.localeCompare(right.id))
805
+ .map((scenario) => JSON.stringify(scenario))
806
+ .join("\n")}\n`;
807
+ const scenariosById = new Map(scenarios.map((scenario) => [scenario.id, scenario]));
808
+ const observationsById = new Map(
809
+ observations.map((observation) => [observation.scenario_id, observation]),
810
+ );
811
+ const redact = createReportRedactor(scenarios, observations);
812
+ const scenarioResults = [...scenariosById.keys()]
813
+ .sort()
814
+ .map((scenarioId) => evaluateScenario(
815
+ scenariosById.get(scenarioId),
816
+ observationsById.get(scenarioId),
817
+ redact,
818
+ ))
819
+ .sort((left, right) => left.scenario_id.localeCompare(right.scenario_id));
820
+ const status = aggregate(scenarioResults.map((result) => result.status));
821
+ return {
822
+ schema_version: 1,
823
+ corpus_digest: `sha256:${crypto
824
+ .createHash("sha256")
825
+ .update(canonicalCorpus)
826
+ .digest("hex")}`,
827
+ mode,
828
+ operational_status: "ok",
829
+ status,
830
+ scenario_results: scenarioResults,
831
+ };
832
+ }
833
+
834
+ function validateReplayRecords({
835
+ scenarios,
836
+ observations,
837
+ scenarioFile,
838
+ observationFile,
839
+ scenarioLines,
840
+ observationLines,
841
+ }) {
842
+ validateScenarios(scenarios, {
843
+ file: scenarioFile,
844
+ lines: scenarioLines,
845
+ });
846
+ const scenarioIds = new Set(scenarios.map((scenario) => scenario.id));
847
+ const fixtureById = new Map();
848
+ for (const [index, observation] of observations.entries()) {
849
+ const line = observationLines?.[index] ?? index + 1;
850
+ validateFixture(observation, observationFile, line, scenarioIds);
851
+ if (fixtureById.has(observation.scenario_id)) {
852
+ inputError(
853
+ observationFile,
854
+ line,
855
+ "scenario_id",
856
+ `duplicate value ${observation.scenario_id}`,
857
+ );
858
+ }
859
+ fixtureById.set(observation.scenario_id, observation);
860
+ }
861
+ for (const scenarioId of scenarioIds) {
862
+ if (!fixtureById.has(scenarioId)) {
863
+ inputError(
864
+ observationFile,
865
+ observations.length + 1,
866
+ "scenario_id",
867
+ `missing value ${scenarioId}`,
868
+ );
869
+ }
870
+ }
871
+ }
872
+
873
+ export function validateScenarios(scenarios, {
874
+ file = "scenarios",
875
+ lines,
876
+ } = {}) {
877
+ if (!Array.isArray(scenarios)) {
878
+ throw new ReplayInputError(`${file}: line 1 record must be an array`);
879
+ }
880
+ const scenarioIds = new Set();
881
+ for (const [index, scenario] of scenarios.entries()) {
882
+ validateScenario(
883
+ scenario,
884
+ file,
885
+ lines?.[index] ?? index + 1,
886
+ scenarioIds,
887
+ );
888
+ }
889
+ }
890
+
891
+ export function evaluateReplay({
892
+ scenarios,
893
+ observations,
894
+ mode = "deterministic",
895
+ }) {
896
+ if (!Array.isArray(scenarios)) {
897
+ throw new ReplayInputError("scenarios: line 1 record must be an array");
898
+ }
899
+ if (!Array.isArray(observations)) {
900
+ throw new ReplayInputError("observations: line 1 record must be an array");
901
+ }
902
+ if (!["deterministic", "live"].includes(mode)) {
903
+ throw new ReplayInputError("mode: line 1 value must be deterministic or live");
904
+ }
905
+ validateReplayRecords({
906
+ scenarios,
907
+ observations,
908
+ scenarioFile: "scenarios",
909
+ observationFile: "observations",
910
+ });
911
+ return buildReport(scenarios, observations, mode);
912
+ }
913
+
914
+ export function serializeReport(report) {
915
+ return `${JSON.stringify(report, null, 2)}\n`;
916
+ }
917
+
918
+ export function runReplay({ corpus, fixtures }) {
919
+ const scenarioLines = parseJsonl(corpus);
920
+ const fixtureLines = parseJsonl(fixtures);
921
+ const scenarios = scenarioLines.map(({ record }) => record);
922
+ const observations = fixtureLines.map(({ record }) => record);
923
+ validateReplayRecords({
924
+ scenarios,
925
+ observations,
926
+ scenarioFile: corpus,
927
+ observationFile: fixtures,
928
+ scenarioLines: scenarioLines.map(({ line }) => line),
929
+ observationLines: fixtureLines.map(({ line }) => line),
930
+ });
931
+ return buildReport(scenarios, observations, "deterministic");
932
+ }
933
+
934
+ function writeOutput(output, serialized) {
935
+ const parent = path.dirname(output);
936
+ let parentStat;
937
+ try {
938
+ parentStat = fs.lstatSync(parent);
939
+ } catch {
940
+ throw new ReplayInputError(
941
+ "output: line 1 parent must be an existing directory",
942
+ );
943
+ }
944
+ if (!parentStat.isDirectory()) {
945
+ throw new ReplayInputError(
946
+ "output: line 1 parent must be an existing directory",
947
+ );
948
+ }
949
+
950
+ try {
951
+ const outputStat = fs.lstatSync(output);
952
+ if (outputStat.isSymbolicLink()) {
953
+ throw new ReplayInputError("output: line 1 path must not be a symlink");
954
+ }
955
+ if (!outputStat.isFile()) {
956
+ throw new ReplayInputError("output: line 1 path must be a regular file");
957
+ }
958
+ } catch (error) {
959
+ if (error instanceof ReplayInputError) throw error;
960
+ if (error?.code !== "ENOENT") {
961
+ throw new ReplayInputError("output: line 1 path unable to inspect");
962
+ }
963
+ }
964
+
965
+ let descriptor;
966
+ try {
967
+ descriptor = fs.openSync(
968
+ output,
969
+ fs.constants.O_WRONLY
970
+ | fs.constants.O_CREAT
971
+ | fs.constants.O_TRUNC
972
+ | (fs.constants.O_NOFOLLOW ?? 0),
973
+ 0o600,
974
+ );
975
+ fs.fchmodSync(descriptor, 0o600);
976
+ fs.writeFileSync(descriptor, serialized, "utf8");
977
+ } catch (error) {
978
+ if (error instanceof ReplayInputError) throw error;
979
+ throw new ReplayInputError("output: line 1 path unable to write");
980
+ } finally {
981
+ if (descriptor !== undefined) fs.closeSync(descriptor);
982
+ }
983
+ }
984
+
985
+ function main() {
986
+ try {
987
+ const options = parseArguments(process.argv.slice(2));
988
+ const report = runReplay(options);
989
+ const serialized = serializeReport(report);
990
+ if (options.output !== undefined) writeOutput(options.output, serialized);
991
+ process.stdout.write(serialized);
992
+ process.exitCode = report.status === "pass"
993
+ ? 0
994
+ : report.status === "fail"
995
+ ? 1
996
+ : 3;
997
+ } catch (error) {
998
+ if (error instanceof ReplayInputError) {
999
+ process.stderr.write(`${error.name}: ${error.message}\n`);
1000
+ process.exitCode = 2;
1001
+ } else {
1002
+ process.stderr.write(`ReplayInputError: runner internal error\n`);
1003
+ process.exitCode = 2;
1004
+ }
1005
+ }
1006
+ }
1007
+
1008
+ const modulePath = fs.realpathSync(fileURLToPath(import.meta.url));
1009
+ const entryPath = process.argv[1] === undefined
1010
+ ? null
1011
+ : fs.realpathSync(path.resolve(process.argv[1]));
1012
+ if (entryPath === modulePath) main();