opencode-agent-orchestration-kit 1.0.30 → 1.0.31

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 CHANGED
@@ -575,6 +575,18 @@ node opencode/scripts/replay-routing.mjs \
575
575
  --fixtures opencode/docs/ai/evolution/benchmarks/replay-fixtures.jsonl
576
576
  ```
577
577
 
578
+ Aggregate one or more sanitized replay reports into deterministic routing
579
+ metrics without calling a model or rereading raw evidence:
580
+
581
+ ```bash
582
+ node opencode/scripts/summarize-routing-metrics.mjs \
583
+ --corpus opencode/docs/ai/evolution/benchmarks/router-scenarios.jsonl \
584
+ --report /path/to/routing-replay-report.json
585
+ ```
586
+
587
+ Inconclusive observations are excluded from metric denominators. Token cost is
588
+ reported as unavailable until the replay report schema carries token evidence.
589
+
578
590
  An isolated live replay is available only through explicit opt-in. It may
579
591
  consume model tokens, is intentionally excluded from normal checks and CI, and
580
592
  does not persist model/provider configuration or raw output by default.
@@ -591,7 +603,7 @@ Validate only the canonical identity and current release note with:
591
603
 
592
604
  ```bash
593
605
  npm run check:version
594
- node scripts/version.mjs --check-tag v1.0.30
606
+ node scripts/version.mjs --check-tag v1.0.31
595
607
  ```
596
608
 
597
609
  Tag validation compares an explicitly supplied tag with the package identity.
@@ -72,7 +72,7 @@ Use these read-only checks from the repository root:
72
72
  ```bash
73
73
  node scripts/version.mjs
74
74
  npm run check:version
75
- node scripts/version.mjs --check-tag v1.0.30
75
+ node scripts/version.mjs --check-tag v1.0.31
76
76
  ```
77
77
 
78
78
  The tag check validates only the supplied value. It does not inspect the
@@ -73,5 +73,5 @@ Release upload require separate authorization and follow
73
73
  [the supply-chain runbook](supply-chain.md).
74
74
 
75
75
  For an explicitly planned release tag, validate it locally with
76
- `node scripts/version.mjs --check-tag v1.0.30`. This check does not create,
76
+ `node scripts/version.mjs --check-tag v1.0.31`. This check does not create,
77
77
  push, or publish the tag or a hosted release.
@@ -0,0 +1,68 @@
1
+ # v1.0.31 - Safe lifecycle and canonical release identity
2
+
3
+ This release adds deterministic routing metrics over sanitized replay reports
4
+ while preserving the kit's installation, upgrade, rollback, compatibility, and
5
+ supply-chain guarantees.
6
+
7
+ ## Highlights
8
+
9
+ - A new metrics aggregator consumes one or more Slice 2.2 replay reports only
10
+ when `operational_status` is `ok` and their corpus digest matches.
11
+ - Routing accuracy, forbidden-agent activation, premature writes, review
12
+ bypass, resume success, explicit human intervention, validation-failure
13
+ closure, and delegations per accepted task are reported with numerators,
14
+ denominators, values, and excluded inconclusive evidence.
15
+ - Zero-denominator metrics remain explicitly unavailable instead of being
16
+ converted into invented zeroes.
17
+ - Token cost remains explicitly unavailable with `token-evidence-absent`
18
+ because the v1 report contract contains no token-usage evidence.
19
+ - Reports are validated against a closed sanitized shape, including nested
20
+ writes, reviews, limitations, and portable values. Diagnostics do not echo
21
+ private input paths or unknown field names.
22
+ - The aggregator emits deterministic JSON and never calls a model, rereads raw
23
+ evidence, or makes automatic harness-optimization decisions.
24
+
25
+ ## Installation or upgrade
26
+
27
+ For a new installation, preview the complete ownership plan before applying it:
28
+
29
+ ```bash
30
+ ./install.sh --dry-run
31
+ ./install.sh
32
+ ```
33
+
34
+ For an existing manifest-owned installation, preview and apply the upgrade:
35
+
36
+ ```bash
37
+ ./upgrade.sh --dry-run
38
+ ./upgrade.sh
39
+ ./doctor.sh
40
+ ```
41
+
42
+ The supported runtime contract remains Node.js `^22.9.0 || ^24.0.0` with
43
+ OpenCode `>=1.14.41 <2.0.0`.
44
+
45
+ ## Migration
46
+
47
+ No ownership-manifest or configuration migration is required. The metrics
48
+ aggregator and its documentation are additive. Existing deterministic and
49
+ opt-in live replay commands keep their current interfaces.
50
+
51
+ ## Validation performed
52
+
53
+ Release readiness covers contract checks, bundled script tests, typechecking,
54
+ dependency and signature audits, installation smoke, package smoke, canonical
55
+ version/tag validation, private/public production parity, and public leak
56
+ scans.
57
+
58
+ The canonical deterministic corpus remains a 14-scenario sanitized fixture set.
59
+ Inconclusive evidence is excluded from metric denominators rather than treated
60
+ as a pass or failure.
61
+
62
+ ## Public safety boundary
63
+
64
+ The public release excludes private OpenCode configuration, local provider and
65
+ MCP wiring, credentials, authentication files, raw transcripts, private
66
+ evidence, user-specific absolute paths, machine-local state, and private
67
+ specification or planning documents. Local provider, search, and MCP
68
+ integrations are not part of this release.
@@ -122,9 +122,19 @@ Slice 2.1 validates the schema and its invariants statically. Slice 2.2 adds
122
122
  deterministic replays over synthetic fixtures and an isolated opt-in live
123
123
  adapter; both produce sanitized reports with a tri-state verdict.
124
124
 
125
- Slice 2.3 will consume only reports whose `operational_status` is `"ok"` and
126
- will not reread raw evidence. Slice 2.2 prepares that contract without
127
- implementing its metrics.
125
+ Slice 2.3 consumes only reports whose `operational_status` is `"ok"`, requires
126
+ the same `corpus_digest`, and does not reread raw evidence. The aggregator
127
+ calculates `routing_accuracy`, `forbidden_agent_activation_rate`,
128
+ `premature_write_rate`, `review_bypass_rate`, `resume_success_rate`,
129
+ `human_intervention_rate`, `validation_failure_closure_rate`, and
130
+ `delegations_per_accepted_task`. Every metric declares its numerator,
131
+ denominator, value, and `excluded_inconclusive`; a zero denominator produces
132
+ `unavailable`, never an invented zero.
133
+
134
+ `tokens_per_accepted_task` remains explicitly `unavailable` with
135
+ `token-evidence-absent` because v1 reports contain no token-usage evidence.
136
+ Output is deterministic and sanitized JSON. It includes no prompts, sessions,
137
+ paths, models, or providers and triggers no automatic optimization decision.
128
138
 
129
139
  ## Required Manifest
130
140
 
@@ -36,6 +36,19 @@ The contract checker validates the replay surface and scenario-ID
36
36
  correspondence but does not execute the live adapter. Live replay requires
37
37
  `--confirm-live`, can consume tokens, and remains outside normal checks and CI.
38
38
 
39
+ Slice 2.3 aggregates one or more sanitized reports without rereading raw
40
+ evidence:
41
+
42
+ ```bash
43
+ node scripts/summarize-routing-metrics.mjs \
44
+ --corpus docs/ai/evolution/benchmarks/router-scenarios.jsonl \
45
+ --report /path/to/routing-replay-report.json
46
+ ```
47
+
48
+ The aggregator requires `operational_status: "ok"` and the same
49
+ `corpus_digest`. It writes deterministic JSON to stdout, does not call models,
50
+ and does not make automatic harness-optimization decisions.
51
+
39
52
  Use `npm run check:quick` when only the fast contract checker is needed. Use
40
53
  `npm run check:release` for a clean dependency install followed by contracts,
41
54
  all script tests, typechecking, dependency audit, and installation smoke.
@@ -79,9 +92,9 @@ The harness check validates:
79
92
  disjoint required/forbidden and allowed/forbidden lists; coverage of all 12
80
93
  categories; and invariants for review, pre-spec writes, delegation budget,
81
94
  and evidence. This is a static check and does not execute replays;
82
- - routing replay surface: deterministic/live runners as regular files, one
83
- synthetic fixture per corpus ID, and documented tri-state, opt-in, and
84
- privacy contracts;
95
+ - routing replay surface: deterministic/live runners and the metrics aggregator
96
+ as regular files, one synthetic fixture per corpus ID, and documented
97
+ tri-state, opt-in, and privacy contracts;
85
98
  - presence of `docs/ai/harness/skill_registry.md` (soft check; warns when missing);
86
99
  - `agents/lead.md` contains `Skill Resolution` or a registry reference;
87
100
  - `developer`, `researcher`, `specifier`, `reviewer`, `designer`, and `scoper`
@@ -1159,6 +1159,7 @@ function checkRoutingReplaySurface() {
1159
1159
  const requiredFiles = [
1160
1160
  "scripts/replay-routing.mjs",
1161
1161
  "scripts/run-routing-live-replay.mjs",
1162
+ "scripts/summarize-routing-metrics.mjs",
1162
1163
  fixturesRel,
1163
1164
  ];
1164
1165
 
@@ -1204,7 +1205,9 @@ function checkRoutingReplaySurface() {
1204
1205
  const checks = contractText(read(checksRel));
1205
1206
  for (const token of [
1206
1207
  "node scripts/replay-routing.mjs",
1208
+ "node scripts/summarize-routing-metrics.mjs",
1207
1209
  "--corpus docs/ai/evolution/benchmarks/router-scenarios.jsonl",
1210
+ "--report",
1208
1211
  "--fixtures docs/ai/evolution/benchmarks/replay-fixtures.jsonl",
1209
1212
  "does not execute the live adapter",
1210
1213
  ]) {
@@ -1219,7 +1222,9 @@ function checkRoutingReplaySurface() {
1219
1222
  for (const token of [
1220
1223
  "Slice 2.3",
1221
1224
  '`operational_status` is `"ok"`',
1222
- "without implementing its metrics",
1225
+ "`excluded_inconclusive`",
1226
+ "`token-evidence-absent`",
1227
+ "does not reread raw evidence",
1223
1228
  ]) {
1224
1229
  if (!evolution.includes(token)) {
1225
1230
  fail(`${evolutionRel}: missing routing replay boundary token ${token}`);
@@ -106,6 +106,21 @@ test("routing replay surface rejects a missing deterministic runner", () => {
106
106
  }
107
107
  });
108
108
 
109
+ test("routing replay surface rejects a missing metrics aggregator", () => {
110
+ const cwd = makeFixture();
111
+ try {
112
+ fs.rmSync(path.join(cwd, "scripts/summarize-routing-metrics.mjs"));
113
+ const result = runHarness(cwd);
114
+ assert.notEqual(result.status, 0, "checker accepted a missing metrics aggregator");
115
+ assert.match(
116
+ result.stderr,
117
+ /scripts\/summarize-routing-metrics\.mjs: missing regular file/,
118
+ );
119
+ } finally {
120
+ fs.rmSync(cwd, { recursive: true, force: true });
121
+ }
122
+ });
123
+
109
124
  test("routing replay surface rejects fixture IDs that differ from the corpus", () => {
110
125
  const cwd = makeFixture();
111
126
  try {
@@ -798,12 +798,19 @@ function evaluateScenario(scenario, fixture, redact) {
798
798
  };
799
799
  }
800
800
 
801
- function buildReport(scenarios, observations, mode) {
801
+ export function computeCorpusDigest(scenarios) {
802
802
  const canonicalCorpus = `${scenarios
803
803
  .slice()
804
804
  .sort((left, right) => left.id.localeCompare(right.id))
805
805
  .map((scenario) => JSON.stringify(scenario))
806
806
  .join("\n")}\n`;
807
+ return `sha256:${crypto
808
+ .createHash("sha256")
809
+ .update(canonicalCorpus)
810
+ .digest("hex")}`;
811
+ }
812
+
813
+ function buildReport(scenarios, observations, mode) {
807
814
  const scenariosById = new Map(scenarios.map((scenario) => [scenario.id, scenario]));
808
815
  const observationsById = new Map(
809
816
  observations.map((observation) => [observation.scenario_id, observation]),
@@ -820,10 +827,7 @@ function buildReport(scenarios, observations, mode) {
820
827
  const status = aggregate(scenarioResults.map((result) => result.status));
821
828
  return {
822
829
  schema_version: 1,
823
- corpus_digest: `sha256:${crypto
824
- .createHash("sha256")
825
- .update(canonicalCorpus)
826
- .digest("hex")}`,
830
+ corpus_digest: computeCorpusDigest(scenarios),
827
831
  mode,
828
832
  operational_status: "ok",
829
833
  status,
@@ -0,0 +1,471 @@
1
+ #!/usr/bin/env node
2
+
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ import {
8
+ computeCorpusDigest,
9
+ validateScenarios,
10
+ } from "./replay-routing.mjs";
11
+
12
+ const reportKeys = [
13
+ "schema_version",
14
+ "corpus_digest",
15
+ "mode",
16
+ "operational_status",
17
+ "status",
18
+ "scenario_results",
19
+ ];
20
+ const resultKeys = [
21
+ "scenario_id",
22
+ "status",
23
+ "assertions",
24
+ "observed_agents",
25
+ "delegation_count",
26
+ "writes",
27
+ "review_sequence",
28
+ "observed_stop_condition",
29
+ "limitations",
30
+ ];
31
+ const assertionKeys = [
32
+ "id",
33
+ "status",
34
+ "reason_code",
35
+ "evidence_sequences",
36
+ ];
37
+ const assertionIds = [
38
+ "observation-integrity",
39
+ "root-agent",
40
+ "required-agents",
41
+ "forbidden-agents",
42
+ "skills",
43
+ "write-before-spec",
44
+ "review-policy",
45
+ "stop-condition",
46
+ "delegation-budget",
47
+ ];
48
+ const writeKeys = ["sequence", "agent", "tool"];
49
+ const reviewKeys = ["sequence", "agent", "verdict"];
50
+ const limitationKeys = ["code", "channels"];
51
+ const coverageChannels = [
52
+ "session_events",
53
+ "skill_events",
54
+ "tool_events",
55
+ "review_events",
56
+ "stop_events",
57
+ ];
58
+ const portableValuePattern = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
59
+ const sensitiveValuePatterns = [
60
+ /\/(?:Users|home)\//i,
61
+ /https?:\/\//i,
62
+ /\b(?:provider|model|endpoint|token|secret|prompt|thinking|reasoning|password|username|credential|api[_-]?key)\b/i,
63
+ ];
64
+ const humanRequiredStops = new Set([
65
+ "clarification-required",
66
+ "evidence-required",
67
+ "resume-checkpoint",
68
+ ]);
69
+
70
+ export class MetricsInputError extends Error {
71
+ constructor(message) {
72
+ super(message);
73
+ this.name = "MetricsInputError";
74
+ }
75
+ }
76
+
77
+ function fail(label, message) {
78
+ throw new MetricsInputError(`${label}: ${message}`);
79
+ }
80
+
81
+ function isObject(value) {
82
+ return value !== null && typeof value === "object" && !Array.isArray(value);
83
+ }
84
+
85
+ function requireExactKeys(value, expected, label) {
86
+ if (!isObject(value)) fail(label, "must be an object");
87
+ for (const key of expected) {
88
+ if (!Object.hasOwn(value, key)) fail(label, `missing field ${key}`);
89
+ }
90
+ for (const key of Object.keys(value)) {
91
+ if (!expected.includes(key)) fail(label, "unknown field");
92
+ }
93
+ }
94
+
95
+ function requirePortableValue(value, label) {
96
+ if (
97
+ typeof value !== "string"
98
+ || !portableValuePattern.test(value)
99
+ || sensitiveValuePatterns.some((pattern) => pattern.test(value))
100
+ ) {
101
+ fail(label, "must be a portable sanitized value");
102
+ }
103
+ }
104
+
105
+ function requireStatus(value, label) {
106
+ if (!["pass", "fail", "inconclusive"].includes(value)) {
107
+ fail(label, "invalid status");
108
+ }
109
+ }
110
+
111
+ function aggregate(statuses) {
112
+ if (statuses.includes("fail")) return "fail";
113
+ if (statuses.includes("inconclusive")) return "inconclusive";
114
+ return "pass";
115
+ }
116
+
117
+ function validateAssertion(value, expectedId, label) {
118
+ requireExactKeys(value, assertionKeys, label);
119
+ if (value.id !== expectedId) fail(label, `expected assertion ${expectedId}`);
120
+ requireStatus(value.status, label);
121
+ if (typeof value.reason_code !== "string" || value.reason_code.length === 0) {
122
+ fail(label, "reason_code must be a non-empty string");
123
+ }
124
+ requirePortableValue(value.reason_code, label);
125
+ if (
126
+ !Array.isArray(value.evidence_sequences)
127
+ || value.evidence_sequences.some((sequence) => !Number.isInteger(sequence) || sequence < 1)
128
+ ) {
129
+ fail(label, "evidence_sequences must contain positive integers");
130
+ }
131
+ }
132
+
133
+ function validateResult(value, scenarioId, label) {
134
+ requireExactKeys(value, resultKeys, label);
135
+ if (value.scenario_id !== scenarioId) fail(label, "scenario_id mismatch");
136
+ requireStatus(value.status, label);
137
+ if (!Array.isArray(value.assertions) || value.assertions.length !== assertionIds.length) {
138
+ fail(label, "assertions must contain the closed assertion set");
139
+ }
140
+ for (const [index, assertionId] of assertionIds.entries()) {
141
+ validateAssertion(value.assertions[index], assertionId, `${label} assertion ${index + 1}`);
142
+ }
143
+ if (value.status !== aggregate(value.assertions.map(({ status }) => status))) {
144
+ fail(label, "status does not match assertions");
145
+ }
146
+ if (!Number.isInteger(value.delegation_count) || value.delegation_count < 0) {
147
+ fail(label, "delegation_count must be a non-negative integer");
148
+ }
149
+ if (!Array.isArray(value.observed_agents)) {
150
+ fail(label, "observed_agents must be an array");
151
+ }
152
+ for (const agent of value.observed_agents) requirePortableValue(agent, label);
153
+ if (!Array.isArray(value.writes)) fail(label, "writes must be an array");
154
+ for (const [index, write] of value.writes.entries()) {
155
+ const itemLabel = `${label} write ${index + 1}`;
156
+ requireExactKeys(write, writeKeys, itemLabel);
157
+ if (!Number.isInteger(write.sequence) || write.sequence < 1) {
158
+ fail(itemLabel, "sequence must be a positive integer");
159
+ }
160
+ requirePortableValue(write.agent, itemLabel);
161
+ requirePortableValue(write.tool, itemLabel);
162
+ }
163
+ if (!Array.isArray(value.review_sequence)) {
164
+ fail(label, "review_sequence must be an array");
165
+ }
166
+ for (const [index, review] of value.review_sequence.entries()) {
167
+ const itemLabel = `${label} review ${index + 1}`;
168
+ requireExactKeys(review, reviewKeys, itemLabel);
169
+ if (!Number.isInteger(review.sequence) || review.sequence < 1) {
170
+ fail(itemLabel, "sequence must be a positive integer");
171
+ }
172
+ requirePortableValue(review.agent, itemLabel);
173
+ if (!["approved", "changes-requested", "blocked"].includes(review.verdict)) {
174
+ fail(itemLabel, "invalid verdict");
175
+ }
176
+ }
177
+ if (!Array.isArray(value.limitations)) fail(label, "limitations must be an array");
178
+ for (const [index, limitation] of value.limitations.entries()) {
179
+ const itemLabel = `${label} limitation ${index + 1}`;
180
+ requireExactKeys(limitation, limitationKeys, itemLabel);
181
+ requirePortableValue(limitation.code, itemLabel);
182
+ if (
183
+ !Array.isArray(limitation.channels)
184
+ || limitation.channels.some((channel) => !coverageChannels.includes(channel))
185
+ ) {
186
+ fail(itemLabel, "channels must contain known coverage channels");
187
+ }
188
+ }
189
+ if (
190
+ value.observed_stop_condition !== null
191
+ && (typeof value.observed_stop_condition !== "string"
192
+ || value.observed_stop_condition.length === 0)
193
+ ) {
194
+ fail(label, "observed_stop_condition must be null or a non-empty string");
195
+ }
196
+ if (value.observed_stop_condition !== null) {
197
+ requirePortableValue(value.observed_stop_condition, label);
198
+ }
199
+ }
200
+
201
+ function validateReport(report, index, scenarios, corpusDigest) {
202
+ const label = `report ${index + 1}`;
203
+ requireExactKeys(report, reportKeys, label);
204
+ if (report.schema_version !== 1) fail(label, "schema_version must be 1");
205
+ if (report.corpus_digest !== corpusDigest) fail(label, "corpus_digest mismatch");
206
+ if (!["deterministic", "live"].includes(report.mode)) fail(label, "invalid mode");
207
+ if (report.operational_status !== "ok") {
208
+ fail(label, "operational_status must be ok");
209
+ }
210
+ requireStatus(report.status, label);
211
+ if (
212
+ !Array.isArray(report.scenario_results)
213
+ || report.scenario_results.length !== scenarios.length
214
+ ) {
215
+ fail(label, "scenario_results must cover the corpus exactly");
216
+ }
217
+ const sortedResults = report.scenario_results
218
+ .slice()
219
+ .sort((left, right) => String(left?.scenario_id).localeCompare(String(right?.scenario_id)));
220
+ const sortedScenarios = scenarios
221
+ .slice()
222
+ .sort((left, right) => left.id.localeCompare(right.id));
223
+ for (const [resultIndex, scenario] of sortedScenarios.entries()) {
224
+ validateResult(sortedResults[resultIndex], scenario.id, `${label} result ${resultIndex + 1}`);
225
+ }
226
+ if (report.status !== aggregate(sortedResults.map(({ status }) => status))) {
227
+ fail(label, "status does not match scenario_results");
228
+ }
229
+ return sortedResults;
230
+ }
231
+
232
+ function assertionFor(result, id) {
233
+ return result.assertions.find((assertion) => assertion.id === id);
234
+ }
235
+
236
+ function availableMetric(numerator, denominator, excludedInconclusive) {
237
+ if (denominator === 0) {
238
+ return {
239
+ status: "unavailable",
240
+ reason: "no-conclusive-observations",
241
+ numerator: null,
242
+ denominator: null,
243
+ value: null,
244
+ excluded_inconclusive: excludedInconclusive,
245
+ };
246
+ }
247
+ return {
248
+ status: "available",
249
+ numerator,
250
+ denominator,
251
+ value: Number((numerator / denominator).toFixed(6)),
252
+ excluded_inconclusive: excludedInconclusive,
253
+ };
254
+ }
255
+
256
+ function assertionRate(observations, assertionId, countStatus) {
257
+ let numerator = 0;
258
+ let denominator = 0;
259
+ let excludedInconclusive = 0;
260
+ for (const { result } of observations) {
261
+ const assertion = assertionFor(result, assertionId);
262
+ if (assertion.status === "inconclusive") {
263
+ excludedInconclusive += 1;
264
+ continue;
265
+ }
266
+ denominator += 1;
267
+ if (assertion.status === countStatus) numerator += 1;
268
+ }
269
+ return availableMetric(numerator, denominator, excludedInconclusive);
270
+ }
271
+
272
+ function routingAccuracy(observations) {
273
+ const routingIds = ["root-agent", "required-agents", "delegation-budget"];
274
+ let numerator = 0;
275
+ let denominator = 0;
276
+ let excludedInconclusive = 0;
277
+ for (const { result } of observations) {
278
+ const assertions = routingIds.map((id) => assertionFor(result, id));
279
+ if (assertions.some(({ status }) => status === "inconclusive")) {
280
+ excludedInconclusive += 1;
281
+ continue;
282
+ }
283
+ denominator += 1;
284
+ if (assertions.every(({ status }) => status === "pass")) numerator += 1;
285
+ }
286
+ return availableMetric(numerator, denominator, excludedInconclusive);
287
+ }
288
+
289
+ function stopMetric(observations, {
290
+ category,
291
+ success,
292
+ }) {
293
+ let numerator = 0;
294
+ let denominator = 0;
295
+ let excludedInconclusive = 0;
296
+ for (const observation of observations) {
297
+ if (category !== undefined && observation.scenario.category !== category) continue;
298
+ const stop = assertionFor(observation.result, "stop-condition");
299
+ if (stop.status === "inconclusive") {
300
+ excludedInconclusive += 1;
301
+ continue;
302
+ }
303
+ denominator += 1;
304
+ if (success(observation, stop)) numerator += 1;
305
+ }
306
+ return availableMetric(numerator, denominator, excludedInconclusive);
307
+ }
308
+
309
+ export function summarizeRoutingMetrics({ scenarios, reports }) {
310
+ try {
311
+ validateScenarios(scenarios, { file: "corpus" });
312
+ } catch {
313
+ fail("corpus", "invalid schema");
314
+ }
315
+ if (!Array.isArray(reports) || reports.length === 0) {
316
+ fail("reports", "at least one report is required");
317
+ }
318
+ const corpusDigest = computeCorpusDigest(scenarios);
319
+ const scenariosById = new Map(scenarios.map((scenario) => [scenario.id, scenario]));
320
+ const observations = reports.flatMap((report, index) => validateReport(
321
+ report,
322
+ index,
323
+ scenarios,
324
+ corpusDigest,
325
+ ).map((result) => ({
326
+ result,
327
+ scenario: scenariosById.get(result.scenario_id),
328
+ })));
329
+ const accepted = observations.filter(({ result }) => result.status === "pass");
330
+ const delegationSum = accepted.reduce(
331
+ (sum, { result }) => sum + result.delegation_count,
332
+ 0,
333
+ );
334
+ const delegationExcluded = observations.filter(
335
+ ({ result }) => result.status === "inconclusive",
336
+ ).length;
337
+
338
+ return {
339
+ schema_version: 1,
340
+ corpus_digest: corpusDigest,
341
+ report_count: reports.length,
342
+ observation_count: observations.length,
343
+ accepted_task_count: accepted.length,
344
+ metrics: {
345
+ routing_accuracy: routingAccuracy(observations),
346
+ forbidden_agent_activation_rate: assertionRate(
347
+ observations,
348
+ "forbidden-agents",
349
+ "fail",
350
+ ),
351
+ premature_write_rate: assertionRate(observations, "write-before-spec", "fail"),
352
+ review_bypass_rate: assertionRate(observations, "review-policy", "fail"),
353
+ resume_success_rate: stopMetric(observations, {
354
+ category: "resume",
355
+ success: ({ result }, stop) => result.status === "pass" && stop.status === "pass",
356
+ }),
357
+ human_intervention_rate: stopMetric(observations, {
358
+ success: ({ result }, stop) => stop.status === "pass"
359
+ && humanRequiredStops.has(result.observed_stop_condition),
360
+ }),
361
+ validation_failure_closure_rate: stopMetric(observations, {
362
+ category: "validation-failure",
363
+ success: ({ result, scenario }, stop) => stop.status === "pass"
364
+ && result.observed_stop_condition === scenario.expected_stop_condition,
365
+ }),
366
+ delegations_per_accepted_task: accepted.length === 0
367
+ ? {
368
+ status: "unavailable",
369
+ reason: "no-accepted-tasks",
370
+ numerator: null,
371
+ denominator: null,
372
+ value: null,
373
+ excluded_inconclusive: delegationExcluded,
374
+ }
375
+ : availableMetric(delegationSum, accepted.length, delegationExcluded),
376
+ tokens_per_accepted_task: {
377
+ status: "unavailable",
378
+ reason: "token-evidence-absent",
379
+ numerator: null,
380
+ denominator: null,
381
+ value: null,
382
+ excluded_inconclusive: 0,
383
+ },
384
+ },
385
+ };
386
+ }
387
+
388
+ export function serializeMetrics(summary) {
389
+ return `${JSON.stringify(summary, null, 2)}\n`;
390
+ }
391
+
392
+ function parseArguments(args) {
393
+ let corpus;
394
+ const reports = [];
395
+ for (let index = 0; index < args.length; index += 1) {
396
+ const flag = args[index];
397
+ const value = args[index + 1];
398
+ if (!["--corpus", "--report"].includes(flag)) {
399
+ fail("arguments", "expected --corpus and one or more --report values");
400
+ }
401
+ if (value === undefined || value.startsWith("--")) {
402
+ fail("arguments", `${flag} requires a value`);
403
+ }
404
+ if (flag === "--corpus") {
405
+ if (corpus !== undefined) fail("arguments", "--corpus may only appear once");
406
+ corpus = value;
407
+ } else {
408
+ reports.push(value);
409
+ }
410
+ index += 1;
411
+ }
412
+ if (corpus === undefined || reports.length === 0) {
413
+ fail("arguments", "expected --corpus and one or more --report values");
414
+ }
415
+ return { corpus, reports };
416
+ }
417
+
418
+ function readJson(file, label) {
419
+ let contents;
420
+ try {
421
+ contents = fs.readFileSync(file, "utf8");
422
+ } catch {
423
+ fail(label, "unable to read");
424
+ }
425
+ try {
426
+ return JSON.parse(contents);
427
+ } catch {
428
+ fail(label, "invalid JSON");
429
+ }
430
+ }
431
+
432
+ function readJsonl(file) {
433
+ let contents;
434
+ try {
435
+ contents = fs.readFileSync(file, "utf8");
436
+ } catch {
437
+ fail("corpus", "unable to read");
438
+ }
439
+ const lines = contents.trimEnd().split("\n");
440
+ if (lines.length === 1 && lines[0] === "") fail("corpus", "missing records");
441
+ return lines.map((line, index) => {
442
+ try {
443
+ return JSON.parse(line);
444
+ } catch {
445
+ fail("corpus", `line ${index + 1} invalid JSON`);
446
+ }
447
+ });
448
+ }
449
+
450
+ function main() {
451
+ try {
452
+ const options = parseArguments(process.argv.slice(2));
453
+ const summary = summarizeRoutingMetrics({
454
+ scenarios: readJsonl(options.corpus),
455
+ reports: options.reports.map((report, index) => readJson(report, `report ${index + 1}`)),
456
+ });
457
+ process.stdout.write(serializeMetrics(summary));
458
+ } catch (error) {
459
+ const message = error instanceof MetricsInputError
460
+ ? error.message
461
+ : "metrics internal error";
462
+ process.stderr.write(`MetricsInputError: ${message}\n`);
463
+ process.exitCode = 2;
464
+ }
465
+ }
466
+
467
+ const modulePath = fs.realpathSync(fileURLToPath(import.meta.url));
468
+ const entryPath = process.argv[1] === undefined
469
+ ? null
470
+ : fs.realpathSync(path.resolve(process.argv[1]));
471
+ if (entryPath === modulePath) main();
@@ -0,0 +1,230 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { spawnSync } from "node:child_process";
6
+ import test from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ import { runReplay } from "./replay-routing.mjs";
10
+ import {
11
+ MetricsInputError,
12
+ serializeMetrics,
13
+ summarizeRoutingMetrics,
14
+ } from "./summarize-routing-metrics.mjs";
15
+
16
+ const scriptDir = path.dirname(fileURLToPath(import.meta.url));
17
+ const root = path.dirname(scriptDir);
18
+ const metricsPath = path.join(scriptDir, "summarize-routing-metrics.mjs");
19
+ const corpusPath = path.join(
20
+ root,
21
+ "docs/ai/evolution/benchmarks/router-scenarios.jsonl",
22
+ );
23
+ const fixturesPath = path.join(
24
+ root,
25
+ "docs/ai/evolution/benchmarks/replay-fixtures.jsonl",
26
+ );
27
+
28
+ function readJsonl(file) {
29
+ return fs
30
+ .readFileSync(file, "utf8")
31
+ .trimEnd()
32
+ .split("\n")
33
+ .map((line) => JSON.parse(line));
34
+ }
35
+
36
+ function canonicalInputs() {
37
+ return {
38
+ scenarios: readJsonl(corpusPath),
39
+ reports: [runReplay({ corpus: corpusPath, fixtures: fixturesPath })],
40
+ };
41
+ }
42
+
43
+ test("summarizes the canonical replay without inventing token evidence", () => {
44
+ const summary = summarizeRoutingMetrics(canonicalInputs());
45
+
46
+ assert.equal(summary.schema_version, 1);
47
+ assert.equal(summary.report_count, 1);
48
+ assert.equal(summary.observation_count, 14);
49
+ assert.equal(summary.accepted_task_count, 14);
50
+ assert.deepEqual(summary.metrics.routing_accuracy, {
51
+ status: "available",
52
+ numerator: 14,
53
+ denominator: 14,
54
+ value: 1,
55
+ excluded_inconclusive: 0,
56
+ });
57
+ assert.deepEqual(summary.metrics.forbidden_agent_activation_rate, {
58
+ status: "available",
59
+ numerator: 0,
60
+ denominator: 14,
61
+ value: 0,
62
+ excluded_inconclusive: 0,
63
+ });
64
+ assert.deepEqual(summary.metrics.premature_write_rate, {
65
+ status: "available",
66
+ numerator: 0,
67
+ denominator: 14,
68
+ value: 0,
69
+ excluded_inconclusive: 0,
70
+ });
71
+ assert.deepEqual(summary.metrics.review_bypass_rate, {
72
+ status: "available",
73
+ numerator: 0,
74
+ denominator: 14,
75
+ value: 0,
76
+ excluded_inconclusive: 0,
77
+ });
78
+ assert.deepEqual(summary.metrics.resume_success_rate, {
79
+ status: "available",
80
+ numerator: 1,
81
+ denominator: 1,
82
+ value: 1,
83
+ excluded_inconclusive: 0,
84
+ });
85
+ assert.deepEqual(summary.metrics.human_intervention_rate, {
86
+ status: "available",
87
+ numerator: 3,
88
+ denominator: 14,
89
+ value: 0.214286,
90
+ excluded_inconclusive: 0,
91
+ });
92
+ assert.deepEqual(summary.metrics.validation_failure_closure_rate, {
93
+ status: "available",
94
+ numerator: 1,
95
+ denominator: 1,
96
+ value: 1,
97
+ excluded_inconclusive: 0,
98
+ });
99
+ assert.deepEqual(summary.metrics.delegations_per_accepted_task, {
100
+ status: "available",
101
+ numerator: 14,
102
+ denominator: 14,
103
+ value: 1,
104
+ excluded_inconclusive: 0,
105
+ });
106
+ assert.deepEqual(summary.metrics.tokens_per_accepted_task, {
107
+ status: "unavailable",
108
+ reason: "token-evidence-absent",
109
+ numerator: null,
110
+ denominator: null,
111
+ value: null,
112
+ excluded_inconclusive: 0,
113
+ });
114
+ });
115
+
116
+ test("excludes inconclusive evidence instead of converting it to failure", () => {
117
+ const inputs = canonicalInputs();
118
+ const result = inputs.reports[0].scenario_results[0];
119
+ const rootAssertion = result.assertions.find(({ id }) => id === "root-agent");
120
+ rootAssertion.status = "inconclusive";
121
+ rootAssertion.reason_code = "session-events-incomplete";
122
+ result.status = "inconclusive";
123
+ inputs.reports[0].status = "inconclusive";
124
+
125
+ const summary = summarizeRoutingMetrics(inputs);
126
+ assert.deepEqual(summary.metrics.routing_accuracy, {
127
+ status: "available",
128
+ numerator: 13,
129
+ denominator: 13,
130
+ value: 1,
131
+ excluded_inconclusive: 1,
132
+ });
133
+ assert.equal(summary.accepted_task_count, 13);
134
+ });
135
+
136
+ test("uses unavailable for a zero denominator", () => {
137
+ const inputs = canonicalInputs();
138
+ const validation = inputs.reports[0].scenario_results.find(
139
+ ({ scenario_id: scenarioId }) => scenarioId === "validation-failure-blocks-close",
140
+ );
141
+ const stop = validation.assertions.find(({ id }) => id === "stop-condition");
142
+ stop.status = "inconclusive";
143
+ stop.reason_code = "stop-events-incomplete";
144
+ validation.status = "inconclusive";
145
+ inputs.reports[0].status = "inconclusive";
146
+
147
+ assert.deepEqual(
148
+ summarizeRoutingMetrics(inputs).metrics.validation_failure_closure_rate,
149
+ {
150
+ status: "unavailable",
151
+ reason: "no-conclusive-observations",
152
+ numerator: null,
153
+ denominator: null,
154
+ value: null,
155
+ excluded_inconclusive: 1,
156
+ },
157
+ );
158
+ });
159
+
160
+ test("rejects reports that are not operationally usable", () => {
161
+ const inputs = canonicalInputs();
162
+ inputs.reports[0].operational_status = "cleanup-failed";
163
+
164
+ assert.throws(
165
+ () => summarizeRoutingMetrics(inputs),
166
+ (error) => error instanceof MetricsInputError
167
+ && error.message === "report 1: operational_status must be ok",
168
+ );
169
+ });
170
+
171
+ test("rejects reports for a different corpus", () => {
172
+ const inputs = canonicalInputs();
173
+ inputs.reports[0].corpus_digest = `sha256:${"0".repeat(64)}`;
174
+
175
+ assert.throws(
176
+ () => summarizeRoutingMetrics(inputs),
177
+ (error) => error instanceof MetricsInputError
178
+ && error.message === "report 1: corpus_digest mismatch",
179
+ );
180
+ });
181
+
182
+ test("rejects unsanitized nested report fields without disclosing them", () => {
183
+ const inputs = canonicalInputs();
184
+ const result = inputs.reports[0].scenario_results.find(
185
+ ({ writes }) => writes.length > 0,
186
+ );
187
+ result.writes[0].provider_secret = "do-not-leak-this-value";
188
+
189
+ assert.throws(
190
+ () => summarizeRoutingMetrics(inputs),
191
+ (error) => error instanceof MetricsInputError
192
+ && error.message.endsWith("unknown field")
193
+ && !error.message.includes("provider_secret")
194
+ && !error.message.includes("do-not-leak"),
195
+ );
196
+ });
197
+
198
+ test("serialization is deterministic and newline terminated", () => {
199
+ const summary = summarizeRoutingMetrics(canonicalInputs());
200
+ assert.equal(serializeMetrics(summary), `${JSON.stringify(summary, null, 2)}\n`);
201
+ });
202
+
203
+ test("CLI diagnostics do not disclose input paths or report contents", () => {
204
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-routing-metrics-"));
205
+ try {
206
+ const privatePath = path.join(cwd, "private-provider-secret-report.json");
207
+ fs.writeFileSync(privatePath, JSON.stringify({
208
+ operational_status: "cleanup-failed",
209
+ secret: "do-not-leak-this-value",
210
+ }));
211
+ const result = spawnSync(
212
+ process.execPath,
213
+ [
214
+ metricsPath,
215
+ "--corpus",
216
+ corpusPath,
217
+ "--report",
218
+ privatePath,
219
+ ],
220
+ { encoding: "utf8" },
221
+ );
222
+
223
+ assert.equal(result.status, 2);
224
+ assert.equal(result.stdout, "");
225
+ assert.match(result.stderr, /^MetricsInputError: report 1:/);
226
+ assert.doesNotMatch(result.stderr, /private-provider|do-not-leak|secret-report/);
227
+ } finally {
228
+ fs.rmSync(cwd, { recursive: true, force: true });
229
+ }
230
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-agent-orchestration-kit",
3
- "version": "1.0.30",
3
+ "version": "1.0.31",
4
4
  "private": false,
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -16,7 +16,7 @@ import {
16
16
 
17
17
  const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
18
18
  const HASH = "a".repeat(64);
19
- const BASENAME = "opencode-agent-orchestration-kit-1.0.30.tgz";
19
+ const BASENAME = "opencode-agent-orchestration-kit-1.0.31.tgz";
20
20
  const REQUIRED = [
21
21
  "package/package.json",
22
22
  "package/supply-chain.json",
@@ -135,7 +135,7 @@ test("smokeTarball validates both archive listings before extraction", async ()
135
135
  await assert.rejects(
136
136
  smokeTarball({
137
137
  repositoryRoot: ROOT,
138
- tarball: "/public/opencode-agent-orchestration-kit-1.0.30.tgz",
138
+ tarball: "/public/opencode-agent-orchestration-kit-1.0.31.tgz",
139
139
  captureTarball(_source, destination) {
140
140
  fs.writeFileSync(destination, "fixture");
141
141
  return { size: 1 };
@@ -108,7 +108,7 @@ test("[V004] direct version entrypoints are exact and mutation-free", (t) => {
108
108
  for (const args of [["scripts/version.mjs"], ["scripts/manage-installation.mjs", "--version"]]) {
109
109
  const result = run(process.execPath, args, { HOME: home });
110
110
  assert.equal(result.status, 0, result.stderr);
111
- assert.equal(result.stdout, "opencode-agent-orchestration-kit 1.0.30\n");
111
+ assert.equal(result.stdout, "opencode-agent-orchestration-kit 1.0.31\n");
112
112
  assert.equal(fs.existsSync(target), false);
113
113
  }
114
114
  });
@@ -117,7 +117,7 @@ test("[V005] all lifecycle wrappers expose the canonical version", () => {
117
117
  for (const wrapper of ["install.sh", "upgrade.sh", "doctor.sh", "uninstall.sh", "rollback.sh"]) {
118
118
  const result = run(path.join(REPOSITORY_ROOT, wrapper), ["--version"]);
119
119
  assert.equal(result.status, 0, `${wrapper}: ${result.stderr}`);
120
- assert.equal(result.stdout, "opencode-agent-orchestration-kit 1.0.30\n", wrapper);
120
+ assert.equal(result.stdout, "opencode-agent-orchestration-kit 1.0.31\n", wrapper);
121
121
  }
122
122
  });
123
123