opencode-model-router 2.8.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +364 -0
  2. package/README.md +20 -0
  3. package/package.json +5 -1
  4. package/src/commands/output.ts +23 -1
  5. package/src/compat/background.ts +2439 -0
  6. package/src/compat/child-session.ts +6 -0
  7. package/src/compat/turn-state.ts +215 -0
  8. package/src/compat/v2-client.ts +136 -17
  9. package/src/compat/v2-hooks.ts +2656 -114
  10. package/src/compat/v2-observations.ts +328 -0
  11. package/src/executor/capacity.ts +362 -0
  12. package/src/executor/child-guards.ts +40 -0
  13. package/src/executor/command.ts +265 -0
  14. package/src/executor/compile/edges.ts +809 -0
  15. package/src/executor/compile/estimate.ts +158 -0
  16. package/src/executor/compile/footprint.ts +829 -0
  17. package/src/executor/compile/index.ts +1080 -0
  18. package/src/executor/compile/parse.ts +1492 -0
  19. package/src/executor/compile/residue.ts +706 -0
  20. package/src/executor/compile/validate.ts +280 -0
  21. package/src/executor/create.ts +672 -0
  22. package/src/executor/expand.ts +551 -0
  23. package/src/executor/git.ts +1214 -0
  24. package/src/executor/host-preamble.ts +17 -0
  25. package/src/executor/instructions.ts +35 -0
  26. package/src/executor/integrate/bisect.ts +73 -0
  27. package/src/executor/integrate/checks.ts +1086 -0
  28. package/src/executor/integrate/land.ts +177 -0
  29. package/src/executor/integrate/phase-suite.ts +407 -0
  30. package/src/executor/integrate/queue.ts +3083 -0
  31. package/src/executor/integrate/run-resolver.ts +19 -0
  32. package/src/executor/launch.ts +652 -0
  33. package/src/executor/ledger.ts +2208 -0
  34. package/src/executor/observations.ts +212 -0
  35. package/src/executor/paths.ts +159 -0
  36. package/src/executor/platform.ts +39 -0
  37. package/src/executor/process-identity.ts +19 -0
  38. package/src/executor/qa-loop.ts +470 -0
  39. package/src/executor/recovery.ts +403 -0
  40. package/src/executor/runtime.ts +6233 -0
  41. package/src/executor/schedule.ts +246 -0
  42. package/src/executor/slots/env.ts +145 -0
  43. package/src/executor/slots/pool.ts +1564 -0
  44. package/src/executor/slots/provision.ts +853 -0
  45. package/src/executor/tool.ts +534 -0
  46. package/src/executor/types.ts +2064 -0
  47. package/src/executor/unattended.ts +488 -0
  48. package/src/guard/store.ts +3 -1
  49. package/src/index.ts +1498 -288
  50. package/src/router/config.ts +776 -25
  51. package/src/router/git-tools.ts +106 -15
  52. package/src/router/leases.ts +1469 -0
  53. package/src/router/logger.ts +44 -32
  54. package/src/router/protocol.ts +40 -10
  55. package/src/router/role-agents.ts +224 -17
  56. package/src/router/roles-config.ts +10 -1
  57. package/src/router/roles.ts +1 -1
  58. package/src/router/run-tools.ts +56 -4
  59. package/src/router/tool-paths.ts +308 -0
  60. package/src/router/work-roots.ts +86 -0
  61. package/src/routing/advisor/findings.ts +25 -5
  62. package/src/routing/classify/index.ts +7 -1
  63. package/src/routing/classify/rules.ts +11 -0
  64. package/src/routing/commands/stats.ts +2 -2
  65. package/src/routing/outcomes/durations.ts +225 -0
  66. package/src/routing/outcomes/index.ts +59 -2
  67. package/src/routing/outcomes/persist.ts +409 -0
  68. package/src/routing/outcomes/stats.ts +170 -11
  69. package/src/routing/outcomes/timings.ts +836 -0
  70. package/src/routing/outcomes/types.ts +98 -0
  71. package/src/routing/roles/approvals.ts +86 -5
  72. package/src/routing/roles/binding.ts +99 -9
  73. package/src/routing/roles/orphans.ts +68 -0
  74. package/src/routing/roles/policy.ts +21 -3
  75. package/src/routing/roles/work-root.ts +3 -1
  76. package/src/routing/wire/dispatch.ts +86 -12
  77. package/src/routing/wire/hint.ts +56 -8
  78. package/src/v2.ts +94 -49
  79. package/src/verify/branch.ts +8 -2
  80. package/src/verify/canonical-path.ts +35 -0
  81. package/src/verify/deterministic.ts +38 -9
  82. package/src/verify/dispatch.ts +64 -28
  83. package/src/verify/exec.ts +52 -9
  84. package/src/verify/pending.ts +1691 -10
  85. package/src/verify/perimeter.ts +12 -6
  86. package/src/verify/plan-task.ts +729 -0
  87. package/src/verify/reference.ts +216 -3
  88. package/src/verify/tree.ts +30 -13
  89. package/src/verify/types.ts +9 -2
  90. package/src/verify/wiring.ts +290 -31
@@ -5,6 +5,9 @@
5
5
  // Design: docs/qa/cost-aware-routing/phase-1.3.md "Design (1.3.1)" §7.
6
6
  // No I/O of its own: `runStatsCli` gets every read and write through `StatsCliIO`. Runnable under Node
7
7
  // type stripping (type-only imports use `import type`).
8
+ //
9
+ // Phase 1.1.4 (v2 only): the "Dispatch durations" and "Orchestrator cache-read share" sections are rendered from the
10
+ // timing and turn side logs, only when those rows exist; `runStatsCli` renders them for host v2 alone.
8
11
  // ---------------------------------------------------------------------------
9
12
 
10
13
  import type {
@@ -12,6 +15,8 @@ import type {
12
15
  CostUnit,
13
16
  CostUnitRow,
14
17
  DecisionRow,
18
+ DispatchTimingRow,
19
+ OrchestratorTurnRow,
15
20
  KeyStatsRow,
16
21
  LogRow,
17
22
  MeanStat,
@@ -23,6 +28,7 @@ import type {
23
28
  RoleStatsTable,
24
29
  RoleTierStatsRow,
25
30
  SavingsRow,
31
+ SideLogs,
26
32
  SignalKind,
27
33
  SignalKindStats,
28
34
  StatsCliIO,
@@ -33,6 +39,7 @@ import type {
33
39
  } from "./types";
34
40
  import { DECISIONS_MAX_GENERATIONS, FLOOR_LIFT_REASON, LADDER_STEP_KINDS, SIGNAL_KINDS, STATS_EXIT, isAnnotationRow, parseKey } from "./types";
35
41
  import { createOutcomeStore } from "./store";
42
+ import { createDurationModel } from "./durations";
36
43
  import { signalMass } from "./signals";
37
44
 
38
45
  // ---------------------------------------------------------------------------
@@ -536,6 +543,21 @@ export function summarizeRoles(store: OutcomeStoreView | null, rows: readonly Lo
536
543
  };
537
544
  }
538
545
 
546
+ /** Unknown bindings in `since ≤ ts < until`, once per decision and child (the same identity as `summarizeRoles`). */
547
+ export function countUnknownBindings(rows: readonly LogRow[], window: StatsWindow): { fresh: number; resumed: number } {
548
+ const counts = { fresh: 0, resumed: 0 };
549
+ const seen = new Set<string>();
550
+ for (const row of rows) {
551
+ if (row.kind !== "decision" || row.binding !== "unknown" || !rowInWindow(row.ts, window)) continue;
552
+ const id = JSON.stringify([row.decisionID, row.childSessionID]);
553
+ if (seen.has(id)) continue;
554
+ seen.add(id);
555
+ if (row.resume) counts.resumed += 1;
556
+ else counts.fresh += 1;
557
+ }
558
+ return counts;
559
+ }
560
+
539
561
  // ---------------------------------------------------------------------------
540
562
  // renderMarkdown
541
563
  // ---------------------------------------------------------------------------
@@ -567,9 +589,12 @@ function fmtRatioAmount(x: number): string {
567
589
  return fix(x, 2);
568
590
  }
569
591
 
570
- /** Keys contain `|`; a cell must neither break the table nor span lines. */
592
+ /**
593
+ * Keys contain `|`; a cell must neither break the table nor span lines. A backslash is escaped first, so a key that
594
+ * ends in `\` cannot turn the escaped `\|` back into a column separator.
595
+ */
571
596
  function cell(text: string): string {
572
- return text.replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
597
+ return text.replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
573
598
  }
574
599
 
575
600
  /**
@@ -687,6 +712,103 @@ export function renderRoleMarkdown(table: RoleStatsTable): string {
687
712
  return blocks.join("\n\n") + "\n";
688
713
  }
689
714
 
715
+ // ---------------------------------------------------------------------------
716
+ // Dispatch durations and orchestrator cache-read share (Phase 1.1.4; side logs timings.jsonl / turns.jsonl)
717
+ // ---------------------------------------------------------------------------
718
+
719
+ /** One role's dispatch durations (milliseconds, nearest rank) over the window. */
720
+ export interface DurationStatsRow {
721
+ readonly role: string;
722
+ readonly p50: number;
723
+ readonly p90: number;
724
+ readonly n: number;
725
+ }
726
+
727
+ /** Cache-read share of the orchestrator turns of the window: `cacheRead / (input + cacheRead + cacheWrite)` per turn. */
728
+ export interface CacheShareStats {
729
+ readonly p50: number;
730
+ readonly p10: number;
731
+ readonly turns: number;
732
+ }
733
+
734
+ /** Matches no real class: asks the duration model for its role level (no `(role, class)` or exact key can answer). */
735
+ const ROLE_LEVEL_CLASS = "\u0001";
736
+
737
+ function rowInWindow(ts: string, window: StatsWindow): boolean {
738
+ const since = finiteOrNull(window.since);
739
+ const until = finiteOrNull(window.until);
740
+ const t = Date.parse(ts);
741
+ return Number.isFinite(t) && (since === null || t >= since) && (until === null || t < until);
742
+ }
743
+
744
+ /**
745
+ * Role × p50/p90/n over the timing rows with `since ≤ ts < until`. The percentiles are the duration estimator's own
746
+ * (`createDurationModel`: succeeded rows with `capacity === null`, nearest rank), asked at its role level with no row
747
+ * limit, no age limit and a minimum of one sample, so this table and the estimator never disagree. Sorted by role.
748
+ * A row that ended more than `MAX_FUTURE_SKEW_MS` (timings.ts) after the current time is dropped by the model's `observe`
749
+ * (QA-1.1-21), so a clock-jump row is in neither the estimate nor this table. `n` is the p50's sample count; the model's
750
+ * `p90Source`/`p90N` (QA-1.1-22) are not shown (with p90MinSamples 1 the p90 level is the p50 level), so the table is unchanged.
751
+ */
752
+ export function summarizeDurations(rows: readonly DispatchTimingRow[], window: StatsWindow): DurationStatsRow[] {
753
+ const model = createDurationModel(
754
+ { readTimings: () => [], now: () => Date.now() },
755
+ // p90MinSamples 1: the report shows each role's own percentiles however few the samples (the estimator's own p90 rule,
756
+ // QA-1.1-10, hands thin levels to the prior, which would misreport a role here).
757
+ { window: Number.MAX_SAFE_INTEGER, maxAgeDays: 1e9, minSamples: 1, p90MinSamples: 1 },
758
+ );
759
+ const roles = new Set<string>();
760
+ for (const row of rows) {
761
+ if (!rowInWindow(row.ts, window)) continue;
762
+ model.observe(row);
763
+ if (row.outcome === "succeeded" && row.capacity === null) roles.add(row.role);
764
+ }
765
+ const out: DurationStatsRow[] = [];
766
+ for (const role of [...roles].sort(compareCodeUnits)) {
767
+ const estimate = model.estimate({ role, class: ROLE_LEVEL_CLASS, scope: "" });
768
+ if (estimate.n > 0) out.push({ role, p50: estimate.p50, p90: estimate.p90, n: estimate.n });
769
+ }
770
+ return out;
771
+ }
772
+
773
+ /** Nearest rank (rank = ceil(p * n), 1-based) on an ascending-sorted, non-empty list: the rule of durations.ts. */
774
+ function nearestRankOf(sorted: readonly number[], p: number): number {
775
+ const rank = Math.min(sorted.length, Math.max(1, Math.ceil(p * sorted.length)));
776
+ return sorted[rank - 1] as number;
777
+ }
778
+
779
+ /** p50 and p10 of the per-turn cache-read share over the turn rows with `since ≤ ts < until`; turns with no tokens are left out. `null` without a turn. */
780
+ export function summarizeCacheShare(rows: readonly OrchestratorTurnRow[], window: StatsWindow): CacheShareStats | null {
781
+ const shares: number[] = [];
782
+ for (const row of rows) {
783
+ if (!rowInWindow(row.ts, window)) continue;
784
+ const denominator = row.input + row.cacheRead + row.cacheWrite;
785
+ if (!Number.isFinite(denominator) || denominator <= 0 || !Number.isFinite(row.cacheRead)) continue;
786
+ shares.push(row.cacheRead / denominator);
787
+ }
788
+ if (shares.length === 0) return null;
789
+ shares.sort((a, b) => a - b);
790
+ return { p50: nearestRankOf(shares, 0.5), p10: nearestRankOf(shares, 0.1), turns: shares.length };
791
+ }
792
+
793
+ function fmtSeconds(ms: number): string {
794
+ return `${fix(ms / 1000, 1)}s`;
795
+ }
796
+
797
+ /** The "Dispatch durations" section; same determinism rules as {@link renderMarkdown}. */
798
+ export function renderDurationsMarkdown(rows: readonly DurationStatsRow[]): string {
799
+ const table = [
800
+ "| Role | p50 | p90 | n |",
801
+ "|---|---|---|---|",
802
+ ...rows.map((r) => `| ${cell(r.role)} | ${fmtSeconds(r.p50)} | ${fmtSeconds(r.p90)} | ${r.n} |`),
803
+ ].join("\n");
804
+ return ["### Dispatch durations", table].join("\n\n") + "\n";
805
+ }
806
+
807
+ /** The "Orchestrator cache-read share" line. */
808
+ export function renderCacheShareMarkdown(stats: CacheShareStats): string {
809
+ return `Orchestrator cache-read share: p50 ${(100 * stats.p50).toFixed(1)}%, p10 ${(100 * stats.p10).toFixed(1)}% over ${stats.turns} turn${stats.turns === 1 ? "" : "s"}\n`;
810
+ }
811
+
690
812
  // ---------------------------------------------------------------------------
691
813
  // Arguments and CLI
692
814
  // ---------------------------------------------------------------------------
@@ -799,6 +921,14 @@ export function parseStatsArgs(argv: readonly string[]): ParseStatsResult {
799
921
  return { ok: true, args: { since, until, json, dir, help } };
800
922
  }
801
923
 
924
+ /**
925
+ * Where `runStatsCli` reads the side logs (timings.jsonl, turns.jsonl) of the directory it reports on. Passed only by callers
926
+ * that render the 1.1.4 sections: the script, and `/router stats` on v2. Without it (v1) the output is unchanged.
927
+ */
928
+ export interface StatsSideLogs {
929
+ open(dir: string): Pick<SideLogs, "readTimings" | "readTurns">;
930
+ }
931
+
802
932
  function messageOf(error: unknown): string {
803
933
  return error instanceof Error ? error.message : String(error);
804
934
  }
@@ -808,7 +938,7 @@ function messageOf(error: unknown): string {
808
938
  * a usage error exits 2, a corrupt or too-new store exits 1 with a clear message, an unexpected error
809
939
  * writes `routing-stats: <message>` and exits 1. A missing store is an empty table with exit 0.
810
940
  */
811
- export async function runStatsCli(argv: readonly string[], io: StatsCliIO): Promise<number> {
941
+ export async function runStatsCli(argv: readonly string[], io: StatsCliIO, side?: StatsSideLogs): Promise<number> {
812
942
  try {
813
943
  const parsed = parseStatsArgs(argv);
814
944
  if (!parsed.ok) {
@@ -832,11 +962,22 @@ export async function runStatsCli(argv: readonly string[], io: StatsCliIO): Prom
832
962
  const store = createOutcomeStore();
833
963
  if (loaded.status === "ok") store.fromSnapshot(loaded.snapshot);
834
964
  const read = await source.readRows();
835
- if (loaded.status === "missing" && read.files.length === 0) {
965
+ // 1.1.4 (QA-1.1-12): where side logs are supplied (v2), they take part in the "no outcome data" decision and report their
966
+ // own skipped / newer-schema notes like the decision log does; without them (v1) nothing below changes.
967
+ const sideLogs = side === undefined ? null : side.open(source.dir);
968
+ const sideTimings = sideLogs === null ? null : await sideLogs.readTimings();
969
+ const sideTurns = sideLogs === null ? null : await sideLogs.readTurns();
970
+ const sideFiles = (sideTimings?.files.length ?? 0) + (sideTurns?.files.length ?? 0);
971
+ if (loaded.status === "missing" && read.files.length === 0 && sideFiles === 0) {
836
972
  // Not an error (a fresh install has nothing yet), but a typo in --dir looks exactly like this (QA-1.3-5).
837
973
  io.stderr(`routing-stats: no outcome data in ${source.dir}\n`);
838
974
  }
839
975
  if (read.skipped > 0) io.stderr(`routing-stats: skipped ${read.skipped} unreadable decision-log line(s)\n`);
976
+ for (const [label, result] of [["timing-log", sideTimings], ["turn-log", sideTurns]] as const) {
977
+ if (result === null) continue;
978
+ if (result.skipped > 0) io.stderr(`routing-stats: skipped ${result.skipped} unreadable ${label} line(s)\n`);
979
+ if (result.newer > 0) io.stderr(`routing-stats: skipped ${result.newer} ${label} row(s) written by a newer version\n`);
980
+ }
840
981
  if (
841
982
  read.generations >= DECISIONS_MAX_GENERATIONS &&
842
983
  read.oldestTs !== null &&
@@ -854,13 +995,31 @@ export async function runStatsCli(argv: readonly string[], io: StatsCliIO): Prom
854
995
  const table = summarize(store, read.rows, { since: args.since, until: args.until });
855
996
  const roles = summarizeRoles(store, read.rows, { since: args.since, until: args.until });
856
997
  const withRoles = hasRoleRows(roles);
857
- io.stdout(
858
- args.json
859
- ? JSON.stringify(withRoles ? { ...table, roles } : table, null, 2) + "\n"
860
- : withRoles
861
- ? `${renderMarkdown(table)}\n${renderRoleMarkdown(roles)}`
862
- : renderMarkdown(table),
863
- );
998
+
999
+ // 1.1.4: the side-log sections exist only where the caller supplies side logs (the script, and `/router stats` on v2),
1000
+ // and only when the window holds rows; without them the output is exactly what it was before.
1001
+ let durations: DurationStatsRow[] = [];
1002
+ let cacheShare: CacheShareStats | null = null;
1003
+ if (sideTimings !== null && sideTurns !== null) {
1004
+ const window = { since: args.since, until: args.until };
1005
+ durations = summarizeDurations(sideTimings.rows, window);
1006
+ cacheShare = summarizeCacheShare(sideTurns.rows, window);
1007
+ }
1008
+
1009
+ if (args.json) {
1010
+ const extra = {
1011
+ ...(withRoles ? { roles } : {}),
1012
+ ...(durations.length > 0 ? { durations } : {}),
1013
+ ...(cacheShare !== null ? { cacheShare } : {}),
1014
+ };
1015
+ io.stdout(JSON.stringify(Object.keys(extra).length > 0 ? { ...table, ...extra } : table, null, 2) + "\n");
1016
+ } else {
1017
+ const sections = [renderMarkdown(table)];
1018
+ if (withRoles) sections.push(renderRoleMarkdown(roles));
1019
+ if (durations.length > 0) sections.push(renderDurationsMarkdown(durations));
1020
+ if (cacheShare !== null) sections.push(renderCacheShareMarkdown(cacheShare));
1021
+ io.stdout(sections.join("\n"));
1022
+ }
864
1023
  return STATS_EXIT.ok;
865
1024
  } catch (error) {
866
1025
  try {