opencode-model-router 2.7.0 → 2.8.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 (46) hide show
  1. package/CHANGELOG.md +219 -0
  2. package/package.json +1 -1
  3. package/src/commands/approvals.ts +354 -0
  4. package/src/commands/output.ts +12 -1
  5. package/src/compat/v2-hooks.ts +255 -53
  6. package/src/index.ts +328 -37
  7. package/src/router/config.ts +48 -2
  8. package/src/router/dispatch-header.ts +95 -2
  9. package/src/router/git-tools.ts +165 -9
  10. package/src/router/protocol.ts +5 -1
  11. package/src/router/role-agents.ts +110 -3
  12. package/src/router/roles-config.ts +83 -0
  13. package/src/router/roles.ts +1 -1
  14. package/src/router/sessions.ts +11 -0
  15. package/src/routing/classify/route-line.ts +96 -5
  16. package/src/routing/classify/types.ts +26 -0
  17. package/src/routing/outcomes/signals.ts +17 -0
  18. package/src/routing/roles/admission.ts +1028 -0
  19. package/src/routing/roles/approvals.ts +876 -0
  20. package/src/routing/roles/binding.ts +17 -4
  21. package/src/routing/roles/check-placement.ts +112 -0
  22. package/src/routing/roles/git-root.ts +500 -0
  23. package/src/routing/roles/policy.ts +9 -0
  24. package/src/routing/roles/read-set.ts +325 -0
  25. package/src/routing/roles/work-root.ts +9 -1
  26. package/src/routing/wire/dispatch.ts +611 -18
  27. package/src/routing/wire/working-set.ts +58 -0
  28. package/src/util/linear-trim.ts +32 -0
  29. package/src/verify/batch.ts +7 -2
  30. package/src/verify/branch.ts +135 -0
  31. package/src/verify/deterministic.ts +232 -10
  32. package/src/verify/dispatch.ts +284 -9
  33. package/src/verify/dod.ts +46 -0
  34. package/src/verify/edges.ts +817 -0
  35. package/src/verify/gate.ts +349 -16
  36. package/src/verify/git-top.ts +43 -0
  37. package/src/verify/head.ts +107 -0
  38. package/src/verify/pending.ts +155 -8
  39. package/src/verify/perimeter.ts +1180 -0
  40. package/src/verify/pin.ts +109 -0
  41. package/src/verify/reference.ts +82 -6
  42. package/src/verify/risk.ts +16 -3
  43. package/src/verify/runner.ts +706 -32
  44. package/src/verify/tree.ts +347 -8
  45. package/src/verify/types.ts +57 -0
  46. package/src/verify/wiring.ts +1324 -35
@@ -0,0 +1,109 @@
1
+ /**
2
+ * src/verify/pin.ts
3
+ *
4
+ * Cross-repo P2d.2 (docs/design/cross-repo.md, OD3 = fail closed): the pin of a linked repository. At dispatch each admitted
5
+ * link target of W is snapshotted together with a bounded digest of its ignored files (`node_modules` excluded). At
6
+ * materialize the link counts as exact when both are unchanged; it is `external-link` when the target changed, the digest is
7
+ * over its bounds, the target is not admitted, or the target is not a git repository. A target's own external links are
8
+ * followed one level; a link one level deeper makes the target's pin unusable.
9
+ *
10
+ * Pure apart from the injected deps: nothing here runs git.
11
+ */
12
+ import type { TreeSnapshot } from "./dispatch";
13
+ import { perimeterKey } from "./git-top";
14
+ import { linkedTargets } from "./perimeter";
15
+
16
+ export type PinWhy = "not-observed" | "not-admitted" | "not-git" | "over-bounds" | "deep-link";
17
+
18
+ export type LinkPin =
19
+ | {
20
+ readonly kind: "pinned";
21
+ readonly root: string;
22
+ readonly head: string;
23
+ readonly fingerprint: string;
24
+ readonly ignored: string;
25
+ readonly nested: readonly LinkPin[];
26
+ }
27
+ | { readonly kind: "unpinnable"; readonly root: string; readonly why: PinWhy };
28
+
29
+ /** What `pinTarget` needs; all injected so no git is run here. */
30
+ export interface PinDeps {
31
+ snapshot(dir: string): Promise<TreeSnapshot | undefined>;
32
+ admitted(dir: string): boolean;
33
+ externalLinks(dir: string): string[];
34
+ }
35
+
36
+ /** The default link discovery: the external package links of `dir` (perimeter.ts linkedTargets). */
37
+ export const defaultExternalLinks: (dir: string) => string[] = linkedTargets;
38
+
39
+ function unpinnable(root: string, why: PinWhy): LinkPin {
40
+ return { kind: "unpinnable", root, why };
41
+ }
42
+
43
+ /** The pin of one root from its dispatch-time snapshot (no links followed). */
44
+ export function pinOf(root: string, snapshot: TreeSnapshot | undefined, admitted: boolean): LinkPin {
45
+ if (!admitted) return unpinnable(root, "not-admitted");
46
+ if (snapshot === undefined) return unpinnable(root, "not-observed");
47
+ if (snapshot.root === undefined) return unpinnable(root, "not-git");
48
+ if (snapshot.ignored === "over-bounds") return unpinnable(root, "over-bounds");
49
+ if (snapshot.ignored === undefined) return unpinnable(root, "not-observed");
50
+ return { kind: "pinned", root, head: snapshot.head, fingerprint: snapshot.fingerprint, ignored: snapshot.ignored, nested: [] };
51
+ }
52
+
53
+ /** UNC and device paths (`\\host\share`, `//host/share`, `\\?\`, `\\.\`): never touched, decided by text alone. */
54
+ function isUncOrDevice(dir: string): boolean {
55
+ return /^[\\/]{2}/.test(dir);
56
+ }
57
+
58
+ /** True only for a non-UNC directory that is admitted; checked before any snapshot or link discovery on it. */
59
+ function mayTouch(dir: string, deps: PinDeps): boolean {
60
+ return !isUncOrDevice(dir) && deps.admitted(dir);
61
+ }
62
+
63
+ /** True only when both pins are pinned and identical, nested pins included (order-independent by root key). */
64
+ export function samePin(a: LinkPin, b: LinkPin): boolean {
65
+ if (a.kind !== "pinned" || b.kind !== "pinned") return false;
66
+ if (perimeterKey(a.root) !== perimeterKey(b.root)) return false;
67
+ if (a.head !== b.head || a.fingerprint !== b.fingerprint || a.ignored !== b.ignored) return false;
68
+ if (a.nested.length !== b.nested.length) return false;
69
+ const byKey = new Map<string, LinkPin>();
70
+ for (const pin of b.nested) {
71
+ const key = perimeterKey(pin.root);
72
+ if (byKey.has(key)) return false;
73
+ byKey.set(key, pin);
74
+ }
75
+ const seen = new Set<string>();
76
+ for (const pin of a.nested) {
77
+ const key = perimeterKey(pin.root);
78
+ const other = byKey.get(key);
79
+ if (other === undefined || seen.has(key) || !samePin(pin, other)) return false;
80
+ seen.add(key);
81
+ }
82
+ return true;
83
+ }
84
+
85
+ /**
86
+ * Pins `root` and, one level deep, the targets of its own external links. A target that itself has external links makes the
87
+ * whole root unpinnable (`deep-link`, OD3); an unpinnable nested pin makes the root unpinnable with its reason. A UNC or
88
+ * device path, or a directory that is not admitted, is `not-admitted` before any snapshot or link discovery on it (I11/I12).
89
+ * Never throws.
90
+ */
91
+ export async function pinTarget(root: string, deps: PinDeps): Promise<LinkPin> {
92
+ try {
93
+ // I11/I12: refuse UNC/device paths by text and non-admitted directories before any fs or git call on them.
94
+ if (!mayTouch(root, deps)) return unpinnable(root, "not-admitted");
95
+ const own = pinOf(root, await deps.snapshot(root), true);
96
+ if (own.kind !== "pinned") return own;
97
+ const nested: LinkPin[] = [];
98
+ for (const target of deps.externalLinks(root)) {
99
+ if (!mayTouch(target, deps)) return unpinnable(root, "not-admitted");
100
+ if (deps.externalLinks(target).length > 0) return unpinnable(root, "deep-link");
101
+ const pin = pinOf(target, await deps.snapshot(target), true);
102
+ if (pin.kind !== "pinned") return unpinnable(root, pin.why);
103
+ nested.push(pin);
104
+ }
105
+ return { ...own, nested };
106
+ } catch {
107
+ return unpinnable(root, "not-observed");
108
+ }
109
+ }
@@ -731,6 +731,9 @@ import { tmpdir as osTmpdir } from "node:os";
731
731
  import { posix as pathPosix, win32 as pathWin32 } from "node:path";
732
732
  import type { ArgvSeam, ExecOptions, ExecResult } from "./types";
733
733
  import type { TreeSnapshot } from "./dispatch";
734
+ import { gitTopOf, perimeterKey } from "./git-top";
735
+ // Type-only: pin.ts imports perimeter.ts, which imports this module; samePin is loaded lazily in step 7.
736
+ import type { LinkPin } from "./pin";
734
737
  import type { PluginLogger } from "../router/logger";
735
738
 
736
739
  // --- Seams --------------------------------------------------------------------
@@ -804,6 +807,11 @@ export interface ReferenceDeps extends CaptureDeps {
804
807
  randomSuffix?: () => string;
805
808
  /** Default HEARTBEAT_INTERVAL_MS: how often a materialized dir's mtime is refreshed while in use. */
806
809
  heartbeatMs?: number;
810
+ /**
811
+ * Cross-repo P2.6: the current pin of a link target's repository top, computed by the caller (pin.ts pinTarget). With
812
+ * DispatchReference.pins, a package link into a pinned repository unchanged since dispatch is exact instead of external-link.
813
+ */
814
+ pinNow?: (root: string) => Promise<LinkPin>;
807
815
  }
808
816
 
809
817
  // --- Data types ---------------------------------------------------------------
@@ -823,6 +831,8 @@ export interface DispatchReference {
823
831
  readonly captureReasons: readonly InexactReason[];
824
832
  /** now() when the capture resolved. */
825
833
  readonly capturedAt: number;
834
+ /** Cross-repo P2.6: the dispatch-time pins of linked repositories (pin.ts); see ReferenceDeps.pinNow. */
835
+ readonly pins?: readonly LinkPin[];
826
836
  }
827
837
 
828
838
  export type InexactCause =
@@ -834,6 +844,8 @@ export type InexactCause =
834
844
  | "untracked-unsafe-path"
835
845
  | "dependency-drift"
836
846
  | "workspace-link-drift"
847
+ | "external-link"
848
+ | "root-link"
837
849
  | "index-flags"
838
850
  | "checkout-conversion";
839
851
 
@@ -903,6 +915,20 @@ const ADD_LOCK_UNSUPPORTED = /unknown option\W+(?:reason|lock)\b/;
903
915
  export const STALE_REFERENCE_AGE_MS = 60 * 60 * 1000;
904
916
  /** A live reference dir's mtime is refreshed this often, far below STALE_REFERENCE_AGE_MS (QA-1.5-4). */
905
917
  export const HEARTBEAT_INTERVAL_MS = 5 * 60 * 1000;
918
+ /**
919
+ * Package-store layouts (pnpm `.pnpm/x@1/node_modules/x`, a global virtual store, a custom virtualStoreDir) all place the
920
+ * package directly under a node_modules dir (or its @scope): a package link whose real path is such a directory is store-like
921
+ * (P0.4, step 7 below; cross-repo P1.8 link discovery, perimeter.ts).
922
+ */
923
+ export function isStoreLikeLink(real: string, platform: string): boolean {
924
+ const p = platform === "win32" ? pathWin32 : pathPosix;
925
+ const fold = (s: string): string => (platform === "win32" ? s.toLowerCase() : s);
926
+ const parent = p.dirname(real);
927
+ const parentName = fold(p.basename(parent));
928
+ if (parentName === "node_modules") return true;
929
+ return parentName.startsWith("@") && fold(p.basename(p.dirname(parent))) === "node_modules";
930
+ }
931
+
906
932
  /** Equals the baselineTimeoutMs default (§1.4); callers pass the configured value. */
907
933
  export const DEFAULT_CAPTURE_TIMEOUT_MS = 15_000;
908
934
  export const DEFAULT_MATERIALIZE_TIMEOUT_MS = 30_000;
@@ -1778,6 +1804,8 @@ export async function materialize(
1778
1804
  }
1779
1805
 
1780
1806
  // 5. Discovery of ignored entries; nothing ignored is ever copied.
1807
+ // A directory-only pattern (`node_modules/`) never matches a symlink, so a symlinked node_modules
1808
+ // it does not ignore is an untracked entry (inexact via its untracked reason), never a link candidate.
1781
1809
  const ignored = await git(["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"]);
1782
1810
  if (budget.spent()) return await abandon("aborted", "aborted during ignored-file discovery");
1783
1811
  if (!ignored || ignored.code !== 0) return await abandon("error", ignored?.stderr.trim() ?? "ignored-file discovery failed");
@@ -1790,7 +1818,9 @@ export async function materialize(
1790
1818
  }
1791
1819
 
1792
1820
  // 6. Link node_modules (section 5), parents before children (git's order).
1793
- const linkTargets: string[] = [];
1821
+ // Each target keeps the root-relative path of the candidate node_modules it came from,
1822
+ // so drift reasons never leak a path outside root (a node_modules that is itself a link).
1823
+ const linkTargets: { readonly target: string; readonly label: string }[] = [];
1794
1824
  for (const entry of candidates) {
1795
1825
  if (budget.spent()) return await abandon("aborted", "aborted while linking node_modules");
1796
1826
  const rel = entry.replace(/\/$/, "");
@@ -1822,7 +1852,7 @@ export async function materialize(
1822
1852
  }
1823
1853
  links.push(linkPath);
1824
1854
  await fs.symlink(target, linkPath, platform === "win32" ? "junction" : "dir");
1825
- linkTargets.push(target);
1855
+ linkTargets.push({ target, label: rel });
1826
1856
  }
1827
1857
 
1828
1858
  // 7. Drift checks (section 2 c and d). Porcelain `git diff` rewrites the index
@@ -1849,8 +1879,45 @@ export async function materialize(
1849
1879
  for (const rel of splitZ(diff.stdout)) changed.add(rel);
1850
1880
  for (const rel of splitZ(nowUntracked.stdout)) if (!ref.untracked.has(rel)) changed.add(rel);
1851
1881
  const realRoot = p.resolve(await fs.realpath(root));
1882
+ const fold = (s: string) => (platform === "win32" ? s.toLowerCase() : s);
1852
1883
  const workspaceDirs = new Set<string>();
1853
- for (const target of linkTargets) {
1884
+ // P0.4: package links whose real path is outside the repository (and not a store-like
1885
+ // path under a node_modules segment) load code the reference cannot pin.
1886
+ const externalLinks = new Set<string>();
1887
+ // A package link to the root itself, or to an ancestor of it, would load the live tree.
1888
+ const rootLinks = new Set<string>();
1889
+ // Package-store layouts (pnpm `.pnpm/x@1/node_modules/x`, a global virtual store, a custom
1890
+ // virtualStoreDir) all place the package directly under a node_modules dir (or its @scope).
1891
+ const storeLike = (real: string): boolean => isStoreLikeLink(real, platform);
1892
+ // Cross-repo P2.6 (OD3, fail closed): an outside link whose git top was pinned at dispatch (ref.pins) and has the same
1893
+ // pin now (deps.pinNow) is exact. No pin, an unpinnable or changed pin, no pinNow, or a throw keeps external-link.
1894
+ const pins = ref.pins ?? [];
1895
+ const pinNow = deps.pinNow;
1896
+ const usePins = pins.length > 0 && pinNow !== undefined;
1897
+ const pinVerdicts = new Map<string, Promise<boolean>>();
1898
+ const pinnedUnchanged = async (real: string): Promise<boolean> => {
1899
+ try {
1900
+ if (pinNow === undefined) return false;
1901
+ const top = gitTopOf(real);
1902
+ if (top === undefined) return false;
1903
+ const key = perimeterKey(top);
1904
+ const dispatchPin = pins.find((pin) => perimeterKey(pin.root) === key);
1905
+ if (dispatchPin === undefined || dispatchPin.kind !== "pinned") return false;
1906
+ let verdict = pinVerdicts.get(key);
1907
+ if (verdict === undefined) {
1908
+ verdict = (async () => {
1909
+ // Lazy: a static import would close the cycle reference -> pin -> perimeter -> reference.
1910
+ const { samePin } = await import("./pin");
1911
+ return samePin(dispatchPin, await pinNow(dispatchPin.root));
1912
+ })().catch(() => false);
1913
+ pinVerdicts.set(key, verdict);
1914
+ }
1915
+ return await verdict;
1916
+ } catch {
1917
+ return false;
1918
+ }
1919
+ };
1920
+ for (const { target, label } of linkTargets) {
1854
1921
  for (const entry of await packageEntries(fs, target, platform)) {
1855
1922
  const stats = await lstatOrMissing(fs, entry);
1856
1923
  if (!stats || !stats.isSymbolicLink()) continue;
@@ -1862,12 +1929,21 @@ export async function materialize(
1862
1929
  continue;
1863
1930
  }
1864
1931
  const base = [realRoot, root].find((candidateRoot) => isStrictlyInside(real, candidateRoot, platform));
1865
- if (!base) continue;
1932
+ if (!base) {
1933
+ // Dot-entries (`.cache`, `.bin`) are tool state, not packages.
1934
+ if (!p.basename(entry).startsWith(".")) {
1935
+ const entryLabel = [label, ...p.relative(target, entry).split(p.sep)].join("/");
1936
+ if (insideOrEqual(realRoot, real, platform) || insideOrEqual(root, real, platform)) rootLinks.add(entryLabel);
1937
+ else if (!storeLike(real) && !(usePins && (await pinnedUnchanged(real)))) externalLinks.add(entryLabel);
1938
+ }
1939
+ continue;
1940
+ }
1866
1941
  const rel = p.relative(base, real).split(p.sep).join("/");
1867
1942
  if (!rel.split("/").includes("node_modules")) workspaceDirs.add(rel);
1868
1943
  }
1869
1944
  }
1870
- const fold = (s: string) => (platform === "win32" ? s.toLowerCase() : s);
1945
+ for (const rel of [...rootLinks].sort(byCodeUnit)) reasons.push({ cause: "root-link", path: rel });
1946
+ for (const rel of [...externalLinks].sort(byCodeUnit)) reasons.push({ cause: "external-link", path: rel });
1871
1947
  // Section 2 (c) and (d) over a set of drifted paths; run on the step-7 set and, in step 7b, on
1872
1948
  // the paths its re-diff adds (#88), so a late edit is judged like any other drift.
1873
1949
  const driftReasons = (paths: readonly string[]) => {
@@ -2182,4 +2258,4 @@ async function gcInner(
2182
2258
  }
2183
2259
  }
2184
2260
  }
2185
- }
2261
+ }
@@ -33,7 +33,8 @@
33
33
  * | 7 | a test file (incl. snapshots) was modified (added, changed, renamed) | medium |
34
34
  * | 8 | a non-test file was deleted or any file was renamed | medium |
35
35
  * | 9 | config / lock / CI / test-setup file changed (see isConfigPath) | medium |
36
- * | 10 | scoping impossible (Unverifiable, S6) | medium |
36
+ * | 10 | scoping impossible (Unverifiable, S6), or the full suite runs | medium |
37
+ * | | (FullScopePlan: REASONS.fullScope instead) | |
37
38
  * | 11 | producer tier "fast" | medium |
38
39
  * | 12 | no reference captured | +1 step (max high) |
39
40
  *
@@ -50,12 +51,22 @@ import type { ChangedPath, StaticScoping } from "./runner";
50
51
  export type RiskLevel = "low" | "medium" | "high";
51
52
  export type ProducerTier = "fast" | "medium" | "heavy" | (string & {});
52
53
 
54
+ /**
55
+ * Cross-repo P2e (QA-1 #6): the scoping "plan" of a DoD whose every testsPass check runs the full suite (`scope=full`, or the
56
+ * dispatch's full scope): nothing is planned, so it is neither scoped nor S6. Row 10 then rates it medium with the neutral
57
+ * REASONS.fullScope instead of REASONS.unverifiable.
58
+ */
59
+ export interface FullScopePlan {
60
+ readonly fullScope: true;
61
+ }
62
+ export const FULL_SCOPE_PLAN: FullScopePlan = { fullScope: true };
63
+
53
64
  export interface RiskInput {
54
65
  readonly changedFiles: readonly ChangedPath[];
55
66
  /** Whether a reference (baseline) exists for this delegation. Only presence matters. */
56
67
  readonly reference: boolean;
57
68
  readonly producerTier: ProducerTier;
58
- readonly scopingPlan: StaticScoping;
69
+ readonly scopingPlan: StaticScoping | FullScopePlan;
59
70
  /** Git root; absolute changed paths are made relative to it before classification. */
60
71
  readonly root?: string;
61
72
  }
@@ -79,6 +90,7 @@ export const REASONS = {
79
90
  deletedOrRenamed: "files were deleted or renamed",
80
91
  configChanged: "config, lock or CI files changed",
81
92
  unverifiable: "scoping impossible (S6): the change cannot be verified by scoped tests",
93
+ fullScope: "the full suite runs (scope=full)",
82
94
  noAffected: "no affected tests found by static scoping",
83
95
  fastTier: "produced by the fast tier",
84
96
  noReference: "no reference captured: risk raised one step",
@@ -257,7 +269,8 @@ export function assessRisk(input: RiskInput): RiskAssessment {
257
269
  hit("medium", REASONS.configChanged);
258
270
  }
259
271
 
260
- if ("unverifiable" in scopingPlan && scopingPlan.unverifiable === true) hit("medium", REASONS.unverifiable);
272
+ if ("fullScope" in scopingPlan && scopingPlan.fullScope === true) hit("medium", REASONS.fullScope);
273
+ else if ("unverifiable" in scopingPlan && scopingPlan.unverifiable === true) hit("medium", REASONS.unverifiable);
261
274
  else if ("noAffected" in scopingPlan && scopingPlan.noAffected === true) reasons.push(REASONS.noAffected);
262
275
 
263
276
  if (producerTier === "fast") hit("medium", REASONS.fastTier);