opencode-model-router 2.7.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 (111) hide show
  1. package/CHANGELOG.md +583 -0
  2. package/README.md +20 -0
  3. package/package.json +5 -1
  4. package/src/commands/approvals.ts +354 -0
  5. package/src/commands/output.ts +34 -1
  6. package/src/compat/background.ts +2439 -0
  7. package/src/compat/child-session.ts +6 -0
  8. package/src/compat/turn-state.ts +215 -0
  9. package/src/compat/v2-client.ts +136 -17
  10. package/src/compat/v2-hooks.ts +2853 -109
  11. package/src/compat/v2-observations.ts +328 -0
  12. package/src/executor/capacity.ts +362 -0
  13. package/src/executor/child-guards.ts +40 -0
  14. package/src/executor/command.ts +265 -0
  15. package/src/executor/compile/edges.ts +809 -0
  16. package/src/executor/compile/estimate.ts +158 -0
  17. package/src/executor/compile/footprint.ts +829 -0
  18. package/src/executor/compile/index.ts +1080 -0
  19. package/src/executor/compile/parse.ts +1492 -0
  20. package/src/executor/compile/residue.ts +706 -0
  21. package/src/executor/compile/validate.ts +280 -0
  22. package/src/executor/create.ts +672 -0
  23. package/src/executor/expand.ts +551 -0
  24. package/src/executor/git.ts +1214 -0
  25. package/src/executor/host-preamble.ts +17 -0
  26. package/src/executor/instructions.ts +35 -0
  27. package/src/executor/integrate/bisect.ts +73 -0
  28. package/src/executor/integrate/checks.ts +1086 -0
  29. package/src/executor/integrate/land.ts +177 -0
  30. package/src/executor/integrate/phase-suite.ts +407 -0
  31. package/src/executor/integrate/queue.ts +3083 -0
  32. package/src/executor/integrate/run-resolver.ts +19 -0
  33. package/src/executor/launch.ts +652 -0
  34. package/src/executor/ledger.ts +2208 -0
  35. package/src/executor/observations.ts +212 -0
  36. package/src/executor/paths.ts +159 -0
  37. package/src/executor/platform.ts +39 -0
  38. package/src/executor/process-identity.ts +19 -0
  39. package/src/executor/qa-loop.ts +470 -0
  40. package/src/executor/recovery.ts +403 -0
  41. package/src/executor/runtime.ts +6233 -0
  42. package/src/executor/schedule.ts +246 -0
  43. package/src/executor/slots/env.ts +145 -0
  44. package/src/executor/slots/pool.ts +1564 -0
  45. package/src/executor/slots/provision.ts +853 -0
  46. package/src/executor/tool.ts +534 -0
  47. package/src/executor/types.ts +2064 -0
  48. package/src/executor/unattended.ts +488 -0
  49. package/src/guard/store.ts +3 -1
  50. package/src/index.ts +1789 -288
  51. package/src/router/config.ts +823 -26
  52. package/src/router/dispatch-header.ts +95 -2
  53. package/src/router/git-tools.ts +266 -19
  54. package/src/router/leases.ts +1469 -0
  55. package/src/router/logger.ts +44 -32
  56. package/src/router/protocol.ts +44 -10
  57. package/src/router/role-agents.ts +334 -20
  58. package/src/router/roles-config.ts +93 -1
  59. package/src/router/roles.ts +1 -1
  60. package/src/router/run-tools.ts +56 -4
  61. package/src/router/sessions.ts +11 -0
  62. package/src/router/tool-paths.ts +308 -0
  63. package/src/router/work-roots.ts +86 -0
  64. package/src/routing/advisor/findings.ts +25 -5
  65. package/src/routing/classify/index.ts +7 -1
  66. package/src/routing/classify/route-line.ts +96 -5
  67. package/src/routing/classify/rules.ts +11 -0
  68. package/src/routing/classify/types.ts +26 -0
  69. package/src/routing/commands/stats.ts +2 -2
  70. package/src/routing/outcomes/durations.ts +225 -0
  71. package/src/routing/outcomes/index.ts +59 -2
  72. package/src/routing/outcomes/persist.ts +409 -0
  73. package/src/routing/outcomes/signals.ts +17 -0
  74. package/src/routing/outcomes/stats.ts +170 -11
  75. package/src/routing/outcomes/timings.ts +836 -0
  76. package/src/routing/outcomes/types.ts +98 -0
  77. package/src/routing/roles/admission.ts +1028 -0
  78. package/src/routing/roles/approvals.ts +957 -0
  79. package/src/routing/roles/binding.ts +116 -13
  80. package/src/routing/roles/check-placement.ts +112 -0
  81. package/src/routing/roles/git-root.ts +500 -0
  82. package/src/routing/roles/orphans.ts +68 -0
  83. package/src/routing/roles/policy.ts +30 -3
  84. package/src/routing/roles/read-set.ts +325 -0
  85. package/src/routing/roles/work-root.ts +12 -2
  86. package/src/routing/wire/dispatch.ts +697 -30
  87. package/src/routing/wire/hint.ts +56 -8
  88. package/src/routing/wire/working-set.ts +58 -0
  89. package/src/util/linear-trim.ts +32 -0
  90. package/src/v2.ts +94 -49
  91. package/src/verify/batch.ts +7 -2
  92. package/src/verify/branch.ts +141 -0
  93. package/src/verify/canonical-path.ts +35 -0
  94. package/src/verify/deterministic.ts +268 -17
  95. package/src/verify/dispatch.ts +348 -37
  96. package/src/verify/dod.ts +46 -0
  97. package/src/verify/edges.ts +817 -0
  98. package/src/verify/exec.ts +52 -9
  99. package/src/verify/gate.ts +349 -16
  100. package/src/verify/git-top.ts +43 -0
  101. package/src/verify/head.ts +107 -0
  102. package/src/verify/pending.ts +1846 -18
  103. package/src/verify/perimeter.ts +1186 -0
  104. package/src/verify/pin.ts +109 -0
  105. package/src/verify/plan-task.ts +729 -0
  106. package/src/verify/reference.ts +297 -8
  107. package/src/verify/risk.ts +16 -3
  108. package/src/verify/runner.ts +706 -32
  109. package/src/verify/tree.ts +372 -16
  110. package/src/verify/types.ts +66 -2
  111. package/src/verify/wiring.ts +1594 -46
@@ -5,9 +5,12 @@
5
5
  * - swap the taxonomy line of the delegation protocol for `generateTaxonomy(...)` (a class moves only when the winner
6
6
  * has ≥ 5 recorded outcomes, so the line stays the shipped one until evidence exists, D2), and append the route-line
7
7
  * paragraph of `protocol.ts`;
8
- * - in advise only, add one extra system part, the per-turn hint: stable class and destination text, computed from the
9
- * latest user message with the RULES classifier only (a hint never costs a model call) and cached for the turn, so the
10
- * system prompt does not change between the steps of one turn.
8
+ * - in advise only, add the per-turn hint: stable class and destination text, computed from the latest user message with
9
+ * the RULES classifier only (a hint never costs a model call) and cached for the turn, so it does not change between the
10
+ * steps of one turn. Without a turn-state registry it is one extra system part; with one (Phase 1.2) nothing is pushed:
11
+ * the hint is kept per session and rendered by the `route-hint` provider into the turn-state tail, and the generated `R:`
12
+ * line is frozen per session (reused while the config object and the dispatching agent, model and permissions are the
13
+ * same) so no router system part changes between turns. Fresh routing evidence still reaches the model through the hint.
11
14
  *
12
15
  * The hint and the generated `R:` line come from the same kernel, but the hint is only emitted when the kernel says
13
16
  * `switched` for the class's static tier, i.e. when it agrees with a move the line itself could make (QA focus: a hint
@@ -15,7 +18,7 @@
15
18
  *
16
19
  * Roles mode (`routing.delegation: "roles"`, plan #84 T2.2.1): nothing is added or rewritten — no per-turn hint, no tier
17
20
  * `R:` line, no route-line paragraph. The roles protocol carries its own class → role line and route-line keys, and a
18
- * hint or a tier line would name tiers; a system part that changes per turn would also cost the orchestrator its
21
+ * hint or a tier line would name tiers; a router text that changes per turn would also cost the orchestrator its
19
22
  * prompt cache. The check is the roles protocol's heading among the router's own parts, i.e. the text the orchestrator
20
23
  * actually carries: a roles config with no enabled role falls back to the tiers protocol, augmented as in tiers mode.
21
24
  */
@@ -29,6 +32,7 @@ import {
29
32
  /** The roles heading only counts at the start of a line (QA-P22-2-4): a part that merely quotes it mid-line is not the roles protocol. */
30
33
  const ROLES_HEADING_LINE = /^## Role Delegation Protocol \(MANDATORY\)$/m;
31
34
 
35
+ import type { TurnStateRegistry } from "../../compat/turn-state";
32
36
  import { classify } from "../classify";
33
37
  import { CLASS_STATIC_TIER, type TaskFacts } from "../classify/types";
34
38
  import { buildLadder, decide, floorRankOf, generateTaxonomy, resolveChosen } from "../engine";
@@ -95,7 +99,8 @@ export interface ContextInput {
95
99
  export interface SystemAugmenter {
96
100
  /**
97
101
  * Called by the context hook after the legacy hook has pushed its text. Rewrites the protocol text in `system` in place
98
- * and pushes the hint, registering both in `added` (the texts whose vocabulary the adapter translates). Never throws.
102
+ * and pushes the hint, registering both in `added` (the texts whose vocabulary the adapter translates); with a turn-state
103
+ * registry the hint is kept for the `route-hint` provider instead and nothing is pushed. Never throws.
99
104
  */
100
105
  augment(input: ContextInput, system: string[], added: Set<string>): Promise<void>;
101
106
  }
@@ -105,6 +110,8 @@ export interface SystemAugmenterDeps {
105
110
  readonly getSession: (sessionID: string) => Promise<unknown>;
106
111
  readonly logger: WireLogger;
107
112
  readonly now?: () => number;
113
+ /** v2 only (Phase 1.2): when present the hint goes to the turn-state tail instead of the system array and the `R:` line is frozen per session. */
114
+ readonly turnState?: TurnStateRegistry;
108
115
  }
109
116
 
110
117
  function describeError(error: unknown): string {
@@ -116,10 +123,43 @@ export function createSystemAugmenter(deps: SystemAugmenterDeps): SystemAugmente
116
123
  // QA-2.2-9: the line depends on the config, the dispatching agent, its (and its session's) permissions and the orchestrator's model.
117
124
  const taxonomyMemo = new Map<string, { cfg: Prepared["cfg"]; at: number; line: string }>();
118
125
  const hints = new Map<string, { key: string; hint: string | null }>();
126
+ // Phase 1.2 (v2 only): the hint of the current request per session, read by the `route-hint` provider; and the frozen `R:` line.
127
+ const routeHints = new Map<string, string>();
128
+ const frozenLines = new Map<string, { memoKey: string; cfg: Prepared["cfg"]; line: string }>();
129
+
130
+ if (deps.turnState !== undefined) {
131
+ try {
132
+ deps.turnState.registerTurnStateProvider({
133
+ name: "route-hint",
134
+ order: 90,
135
+ render: (sid) => routeHints.get(sid),
136
+ });
137
+ } catch (error) {
138
+ deps.logger.warn("[router] turn state: the route-hint provider could not be registered", { error: describeError(error) });
139
+ }
140
+ }
119
141
 
120
142
  const taxonomyLine = (prepared: Prepared, view: AgentView, input: ContextInput): string => {
121
- const t = now();
122
143
  const memoKey = `${input.agent}\u0000${input.parentModel ?? ""}\u0000${JSON.stringify(view.parentRules)}`;
144
+ if (deps.turnState === undefined) return computedTaxonomyLine(prepared, view, input, memoKey);
145
+ // 1.2.4.d: reused while the key (agent name, parent model, parent rules) and the config object are unchanged, so the system prompt
146
+ // does not move between turns. The line is regenerated (an accepted cache break) only when one of those changes: a config/env
147
+ // change, a model switch, other rules. A changed agent catalog alone does not refresh it (a removed host agent can stay named).
148
+ const frozen = frozenLines.get(input.sessionID);
149
+ if (frozen !== undefined && frozen.memoKey === memoKey && frozen.cfg === prepared.cfg) {
150
+ frozenLines.delete(input.sessionID);
151
+ frozenLines.set(input.sessionID, frozen);
152
+ return frozen.line;
153
+ }
154
+ const line = computedTaxonomyLine(prepared, view, input, memoKey);
155
+ frozenLines.delete(input.sessionID);
156
+ frozenLines.set(input.sessionID, { memoKey, cfg: prepared.cfg, line });
157
+ while (frozenLines.size > HINT_MEMO_LIMIT) frozenLines.delete(frozenLines.keys().next().value as string);
158
+ return line;
159
+ };
160
+
161
+ const computedTaxonomyLine = (prepared: Prepared, view: AgentView, input: ContextInput, memoKey: string): string => {
162
+ const t = now();
123
163
  const memo = taxonomyMemo.get(memoKey);
124
164
  if (memo !== undefined && memo.cfg === prepared.cfg && t - memo.at < TAXONOMY_TTL_MS) return memo.line;
125
165
  const line = generateTaxonomy({
@@ -184,6 +224,8 @@ export function createSystemAugmenter(deps: SystemAugmenterDeps): SystemAugmente
184
224
 
185
225
  return {
186
226
  async augment(input, system, added): Promise<void> {
227
+ // A request that returns early below (roles, static, shadow, no orchestrator) must leave no hint of an earlier one behind.
228
+ routeHints.delete(input.sessionID);
187
229
  try {
188
230
  // Roles mode: no hint part, and the protocol text stays exactly as the legacy hook built it. Keyed on the roles
189
231
  // protocol the orchestrator actually carries (QA-P22-1-5): `delegation: "roles"` with no enabled role keeps the
@@ -211,8 +253,14 @@ export function createSystemAugmenter(deps: SystemAugmenterDeps): SystemAugmente
211
253
  }
212
254
  const hint = mode === "advise" ? await hintFor(prepared, view, input) : null;
213
255
  if (hint !== null) {
214
- added.add(hint);
215
- system.push(hint);
256
+ if (deps.turnState !== undefined) {
257
+ // The tail carries the hint (provider `route-hint`); nothing is pushed into the system array.
258
+ routeHints.set(input.sessionID, hint);
259
+ while (routeHints.size > HINT_MEMO_LIMIT) routeHints.delete(routeHints.keys().next().value as string);
260
+ } else {
261
+ added.add(hint);
262
+ system.push(hint);
263
+ }
216
264
  }
217
265
  } catch (error) {
218
266
  deps.logger.warn("[router] routing: the protocol could not be adapted to the engine; the shipped text stays", { error: describeError(error) });
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The working set of an orchestrator session (`docs/design/cross-repo.md`, Phase 1 step P1.4): the repository locations its role
3
+ * dispatches were bound to, so a later `root=` naming one of their worktrees is admitted by rule 2 (a worktree that a known
4
+ * repository lists). Per orchestrator session, at most {@link WORKING_SET_MAX} roots (the oldest evicted), de-duplicated by
5
+ * worktree (a re-bound worktree moves to the newest place, with its latest location). Forgotten on `session.deleted`.
6
+ */
7
+ import type { RepoLocation } from "../roles/admission";
8
+
9
+ /** Roots kept per orchestrator session; the oldest is evicted first. */
10
+ export const WORKING_SET_MAX = 16;
11
+
12
+ const sets = new Map<string, RepoLocation[]>();
13
+
14
+ /** Record that a dispatch of `orchestratorSessionID` was bound to `location`. */
15
+ export function addToWorkingSet(orchestratorSessionID: string, location: RepoLocation): void {
16
+ const current = sets.get(orchestratorSessionID) ?? [];
17
+ const next = current.filter((entry) => entry.worktree !== location.worktree);
18
+ next.push(location);
19
+ while (next.length > WORKING_SET_MAX) next.shift();
20
+ sets.set(orchestratorSessionID, next);
21
+ }
22
+
23
+ /** The bound locations of `orchestratorSessionID`, oldest first; [] when none. */
24
+ export function workingSetOf(orchestratorSessionID: string): readonly RepoLocation[] {
25
+ return [...(sets.get(orchestratorSessionID) ?? [])];
26
+ }
27
+
28
+ /** Drop the working set of a deleted session. */
29
+ export function forgetWorkingSet(orchestratorSessionID: string): void {
30
+ sets.delete(orchestratorSessionID);
31
+ }
32
+
33
+ /** Comparison key of a path: case-insensitive on Windows. */
34
+ function workingSetKey(p: string, platform: NodeJS.Platform): string {
35
+ return platform === "win32" ? p.toLowerCase() : p;
36
+ }
37
+
38
+ /**
39
+ * Remove one repository from every session's working set (SD-P4-12, `/router revoke`): every entry of the repository whose
40
+ * main worktree is the canonical path `match` (any of its worktrees), every entry bound to that worktree, and every entry
41
+ * backed by an approval of that path. Paths compare as text, case-insensitive on win32. Returns the number of entries removed.
42
+ */
43
+ export function dropFromWorkingSets(match: string, platform: NodeJS.Platform = process.platform): number {
44
+ const key = workingSetKey(match, platform);
45
+ const hit = (entry: RepoLocation): boolean =>
46
+ workingSetKey(entry.repository, platform) === key
47
+ || workingSetKey(entry.worktree, platform) === key
48
+ || (entry.approval !== undefined && workingSetKey(entry.approval, platform) === key);
49
+ let removed = 0;
50
+ for (const [sessionID, entries] of sets) {
51
+ const kept = entries.filter((entry) => !hit(entry));
52
+ if (kept.length === entries.length) continue;
53
+ removed += entries.length - kept.length;
54
+ if (kept.length === 0) sets.delete(sessionID);
55
+ else sets.set(sessionID, kept);
56
+ }
57
+ return removed;
58
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Linear-time trimming helpers.
3
+ *
4
+ * Regular expressions such as `/\/+$/` or `/^\s+|\s+$/` are polynomial on
5
+ * uncontrolled input (CodeQL js/polynomial-redos): on a long run of the
6
+ * repeated character that is not at the end, the engine retries the run from
7
+ * every start position. These helpers scan once from the relevant end.
8
+ */
9
+
10
+ /** Returns `value` without the trailing run of characters for which `isTrimmed` holds. */
11
+ export function trimEndWhile(value: string, isTrimmed: (char: string) => boolean): string {
12
+ let end = value.length;
13
+ while (end > 0 && isTrimmed(value[end - 1] as string)) end--;
14
+ return end === value.length ? value : value.slice(0, end);
15
+ }
16
+
17
+ /** Returns `value` without the leading run of characters for which `isTrimmed` holds. */
18
+ export function trimStartWhile(value: string, isTrimmed: (char: string) => boolean): string {
19
+ let start = 0;
20
+ while (start < value.length && isTrimmed(value[start] as string)) start++;
21
+ return start === 0 ? value : value.slice(start);
22
+ }
23
+
24
+ /** True for `/` and `\`. */
25
+ export function isPathSeparator(char: string): boolean {
26
+ return char === "/" || char === "\\";
27
+ }
28
+
29
+ /** True for `/` only. */
30
+ export function isSlash(char: string): boolean {
31
+ return char === "/";
32
+ }
package/src/v2.ts CHANGED
@@ -5,60 +5,105 @@ import { createV2Runtime } from "./compat/v2-client";
5
5
  import { registerV2Hooks } from "./compat/v2-hooks";
6
6
  import type { Ingest } from "./routing/outcomes/ingest";
7
7
  import type { BudgetSnapshot } from "./guard/enforce";
8
+ import type { PlanTaskVerifier } from "./executor/runtime";
9
+ import type { ExecutorChildGuardPort } from "./executor/types";
10
+ import { createExecutor, createExecutorAccess, prepareExecutor, type CreateExecutorOptions, type PreparedExecutor } from "./executor/create";
11
+ import { EXECUTOR_PLATFORM_REASON, executorPlatformSupported } from "./executor/platform";
12
+ import { loadConfig, resolveRolesRouting, resolveRouting } from "./router/config";
13
+ import { locationOutsideWorkRoots } from "./router/work-roots";
14
+ import { openV2Observations } from "./compat/v2-observations";
8
15
 
9
16
  /** Keep the routing engine shared; translate only the host API at this boundary. */
10
17
  export default {
11
18
  id: "opencode-model-router",
12
19
  server: ModelRouterPlugin,
13
20
  async setup(ctx: Plugin.Context) {
14
- const runtime = createV2Runtime(ctx);
15
- // The engine consumes directory/client only. V2 has no legacy HTTP server
16
- // URL or Bun shell context; do not invent either for the adapter.
17
- let ingest: Ingest | undefined;
18
- // #84 P2.1: the plugin's `/bypass` state, read by the role dispatch path (the router's own gate will not run while bypassed, S10/P-9).
19
- let isBypassed: (() => boolean) | undefined;
20
- let budgetSnapshot: ((childSessionID: string) => BudgetSnapshot) | undefined;
21
- // #84 P2.1 (handoff 22): the host's own stops of role children (step limit, context overflow), observed by the adapter from the
22
- // event stream and folded into the plugin's budget signals. The adapter hands its observer back once registered.
23
- let observeHostBudget: ((childSessionID: string, stepLimit: number | null) => boolean | "unobserved") | undefined;
24
- let roleLive: ((agent: string) => boolean) | undefined;
25
- let verifyEnabled: (() => boolean) | undefined;
26
- // QA-G-A3-2: the plugin's count of a role child's call refused outside its guard (role-authority refusals, permission denials).
27
- let recordRefusal: ((sessionID: string, agent: string | undefined, tool: string, args: unknown) => string | undefined) | undefined;
28
- const input = {
29
- directory: ctx.location.directory,
30
- worktree: ctx.location.project.directory,
31
- client: runtime.client,
32
- routerChildRunner: runtime.childRunner,
33
- routerHost: "v2" as const,
34
- // Step pricing reads the catalog the adapter already queries; the plugin's single telemetry ingest comes back
35
- // here so the event loop feeds the instance that also receives the verdicts (QA-2.1-7).
36
- routerCatalog: async () => (await ctx.model.list({ location: { directory: ctx.location.directory } })).data,
37
- // The agents of THIS plugin instance's location (QA-2.4-16): the host lists agents per location.
38
- routerAgents: async () => (await ctx.agent.list({ location: { directory: ctx.location.directory } })).data,
39
- ...(ctx.generate === undefined ? {} : { routerGenerate: ctx.generate }),
40
- // The same host call the adapter uses for the config-reload and narration notices (src/compat/v2-hooks.ts): a transcript entry that
41
- // does not resume the session (QA-2.4-R2-1).
42
- routerSynthetic: async (notice: { sessionID: string; text: string; description: string }) => {
43
- await ctx.session.synthetic({ sessionID: notice.sessionID, text: notice.text, description: notice.description, resume: false });
44
- },
45
- routerOnIngest: (created: Ingest) => { ingest = created; },
46
- routerOnBypassState: (read: () => boolean) => { isBypassed = read; },
47
- // QA-P21-1-3: the plugin's budget snapshot (guard state + read-only CAP state) for the adapter's budget notice.
48
- routerOnBudgetSnapshot: (read: (childSessionID: string) => BudgetSnapshot) => { budgetSnapshot = read; },
49
- routerHostBudget: (childSessionID: string, stepLimit: number | null) => observeHostBudget?.(childSessionID, stepLimit),
50
- // QA-P21-2-4: the adapter's "this role agent is registered" check; QA-P21-2 nit 3: whether router_verify is registered.
51
- routerRoleLive: (agent: string) => roleLive?.(agent),
52
- routerOnVerifyEnabled: (read: () => boolean) => { verifyEnabled = read; },
53
- routerOnRefusal: (record: NonNullable<typeof recordRefusal>) => { recordRefusal = record; },
54
- };
55
- const hooks = await ModelRouterPlugin(input as unknown as PluginInput);
56
- return registerV2Hooks(ctx, hooks, runtime, {
57
- ...(ingest ? { ingest } : {}), ...(isBypassed ? { isBypassed } : {}), ...(budgetSnapshot ? { budgetSnapshot } : {}),
58
- ...(verifyEnabled ? { routerVerifyEnabled: verifyEnabled } : {}),
59
- ...(recordRefusal ? { recordRefusal } : {}),
60
- onHostBudget: (observe) => { observeHostBudget = observe; },
61
- onRoleLive: (isLive) => { roleLive = isLive; },
62
- });
21
+ const observations = openV2Observations();
22
+ try {
23
+ const runtime = createV2Runtime(ctx);
24
+ const directory = ctx.location.directory;
25
+ const access = createExecutorAccess();
26
+ const cfg = loadConfig(directory), routing = resolveRouting(cfg, "v2"), rolesRouting = resolveRolesRouting(cfg, "v2");
27
+ // G-16: off Windows the executor is not assembled; start-up discovery runs no git and touches no executor home.
28
+ const discoveryDisabled = !executorPlatformSupported() ? EXECUTOR_PLATFORM_REASON
29
+ : rolesRouting.delegation !== "roles" ? "routing.delegation must be roles at start"
30
+ : routing.leases.mode !== "enforce" ? "routing.leases.mode must be enforce"
31
+ : cfg.enforcement?.verify?.require === "never" ? "enforcement.verify.require is never"
32
+ : locationOutsideWorkRoots(directory, rolesRouting.workRoots) ? "the location is outside routing.workRoots"
33
+ : null;
34
+ const prep: Promise<PreparedExecutor> = discoveryDisabled === null ? prepareExecutor(directory)
35
+ : Promise.resolve({ ok: false, reason: discoveryDisabled });
36
+ // The engine consumes directory/client only. V2 has no legacy HTTP server
37
+ // URL or Bun shell context; do not invent either for the adapter.
38
+ let ingest: Ingest | undefined;
39
+ // #84 P2.1: the plugin's `/bypass` state, read by the role dispatch path (the router's own gate will not run while bypassed, S10/P-9).
40
+ let isBypassed: (() => boolean) | undefined;
41
+ let budgetSnapshot: ((childSessionID: string) => BudgetSnapshot) | undefined;
42
+ // #84 P2.1 (handoff 22): the host's own stops of role children (step limit, context overflow), observed by the adapter from the
43
+ // event stream and folded into the plugin's budget signals. The adapter hands its observer back once registered.
44
+ let observeHostBudget: ((childSessionID: string, stepLimit: number | null) => boolean | "unobserved") | undefined;
45
+ let roleLive: ((agent: string) => boolean) | undefined;
46
+ let verifyEnabled: (() => boolean) | undefined;
47
+ // QA-G-A3-2: the plugin's count of a role child's call refused outside its guard (role-authority refusals, permission denials).
48
+ let recordRefusal: ((sessionID: string, agent: string | undefined, tool: string, args: unknown) => string | undefined) | undefined;
49
+ // Phase 5.1 D8: the plan-task verifier built over this plugin instance's dispatch verification engine.
50
+ let slotVerifier: PlanTaskVerifier | undefined;
51
+ let annotate: CreateExecutorOptions["annotate"];
52
+ // Publishes executor child rounds/caps process-wide; the slot-location plugin consumes each new round locally.
53
+ let executorChildGuard: ExecutorChildGuardPort | undefined;
54
+ const input = {
55
+ directory: ctx.location.directory,
56
+ worktree: ctx.location.project.directory,
57
+ client: runtime.client,
58
+ routerChildRunner: runtime.childRunner,
59
+ routerHost: "v2" as const,
60
+ routerObservations: observations,
61
+ routerExecutor: access,
62
+ routerOnPlanAnnotate: (port: NonNullable<typeof annotate>) => { annotate = port; },
63
+ // Step pricing reads the catalog the adapter already queries; the plugin's single telemetry ingest comes back
64
+ // here so the event loop feeds the instance that also receives the verdicts (QA-2.1-7).
65
+ routerCatalog: async () => (await ctx.model.list({ location: { directory: ctx.location.directory } })).data,
66
+ // The agents of THIS plugin instance's location (QA-2.4-16): the host lists agents per location.
67
+ routerAgents: async () => (await ctx.agent.list({ location: { directory: ctx.location.directory } })).data,
68
+ ...(ctx.generate === undefined ? {} : { routerGenerate: ctx.generate }),
69
+ // The same host call the adapter uses for the config-reload and narration notices (src/compat/v2-hooks.ts): a transcript entry that
70
+ // does not resume the session (QA-2.4-R2-1).
71
+ routerSynthetic: async (notice: { sessionID: string; text: string; description: string }) => {
72
+ await ctx.session.synthetic({ sessionID: notice.sessionID, text: notice.text, description: notice.description, resume: false });
73
+ },
74
+ routerOnIngest: (created: Ingest) => { ingest = created; },
75
+ routerOnBypassState: (read: () => boolean) => { isBypassed = read; },
76
+ // QA-P21-1-3: the plugin's budget snapshot (guard state + read-only CAP state) for the adapter's budget notice.
77
+ routerOnBudgetSnapshot: (read: (childSessionID: string) => BudgetSnapshot) => { budgetSnapshot = read; },
78
+ routerHostBudget: (childSessionID: string, stepLimit: number | null) => observeHostBudget?.(childSessionID, stepLimit),
79
+ // QA-P21-2-4: the adapter's "this role agent is registered" check; QA-P21-2 nit 3: whether router_verify is registered.
80
+ routerRoleLive: (agent: string) => roleLive?.(agent),
81
+ routerOnVerifyEnabled: (read: () => boolean) => { verifyEnabled = read; },
82
+ routerOnRefusal: (record: NonNullable<typeof recordRefusal>) => { recordRefusal = record; },
83
+ routerOnSlotVerifier: (verifier: PlanTaskVerifier) => { slotVerifier = verifier; },
84
+ routerOnExecutorChildGuard: (port: ExecutorChildGuardPort) => { executorChildGuard = port; },
85
+ };
86
+ const hooks = await ModelRouterPlugin(input as unknown as PluginInput);
87
+ const prepared = await prep;
88
+ if (!prepared.ok) access.clear(prepared.reason);
89
+ if (prepared.ok && runtime.childRunner === undefined) access.clear("the child runner is not available");
90
+ const registration = registerV2Hooks(ctx, hooks, runtime, {
91
+ observations,
92
+ executor: (host) => createExecutor({ routerHost: "v2", directory }, { host, prepared, access, observations, ...(annotate ? { annotate } : {}) }) ?? null,
93
+ ...(ingest ? { ingest } : {}), ...(isBypassed ? { isBypassed } : {}), ...(budgetSnapshot ? { budgetSnapshot } : {}),
94
+ ...(verifyEnabled ? { routerVerifyEnabled: verifyEnabled } : {}),
95
+ ...(recordRefusal ? { recordRefusal } : {}),
96
+ ...(slotVerifier ? { slotVerifier } : {}),
97
+ ...(executorChildGuard ? { executorChildGuard } : {}),
98
+ onHostBudget: (observe) => { observeHostBudget = observe; },
99
+ onRoleLive: (isLive) => { roleLive = isLive; },
100
+ });
101
+ if (observations === undefined) return registration;
102
+ const dispose = await registration;
103
+ let disposal: Promise<void> | undefined;
104
+ // Later cleanup calls can finish before the first drain: every caller must share its seal barrier.
105
+ // Start cleanup synchronously; the async wrapper converts synchronous throws to rejections.
106
+ return () => disposal ??= (async () => { await dispose(); })().finally(() => observations.close());
107
+ } catch (error) { observations?.close(); throw error; }
63
108
  },
64
109
  } satisfies Plugin.Plugin & { server: typeof ModelRouterPlugin };
@@ -52,6 +52,8 @@
52
52
  // 1. The coordinator is disposed -> { scoped: aborted BATCH_REASONS.disposed }.
53
53
  // 2. request.testScope === "full" -> runtime.direct(request). The resolved command runs as
54
54
  // written (2.1-T2 P5f). It cannot be merged, and S6 forbids widening a scoped run into it.
55
+ // 2a. request.crossLinkRoot set -> runtime.direct(request) (cross-repo P3a, SD-P3a-8). The
56
+ // coordinator plans with { command, cwd, changedFiles } only, so a union would drop W.
55
57
  // 3. runtime.batchWindowMs <= 0 -> runtime.direct(request). "batchWindowMs: 0 disables
56
58
  // batching": every request runs alone, still scoped.
57
59
  // 4. plan = runtime.plan(request, request.deadline), that is, planScopedRun (B6). Then:
@@ -784,7 +786,7 @@ export type OpenBatchScope = (meta: Parameters<OpenVerificationScope>[0]) => Bat
784
786
 
785
787
  /** The seams and settings of one gate (deviation D6). The window opener's values apply to its batch. */
786
788
  export interface BatchRuntime {
787
- /** 2.1's one-request hook, used for testScope "full" and batchWindowMs <= 0 (B2). */
789
+ /** 2.1's one-request hook, used for testScope "full", a crossLinkRoot request and batchWindowMs <= 0 (B2). */
788
790
  readonly direct: TestsPassHook;
789
791
  readonly plan: BatchPlanner;
790
792
  readonly openScope: OpenBatchScope;
@@ -1763,7 +1765,10 @@ export function createBatchCoordinator(options: BatchCoordinatorOptions = {}): B
1763
1765
 
1764
1766
  async function submit(runtime: BatchRuntime, request: TestsPassRequest): Promise<TestsPassRun> {
1765
1767
  if (disposed) return abortedRun(BATCH_REASONS.disposed);
1766
- if (request.testScope === "full" || !(runtime.batchWindowMs > 0)) return await runtime.direct(request);
1768
+ // B2 2a (cross-repo P3a, SD-P3a-8): a cross-link request is never batched; the union plan has no W.
1769
+ if (request.testScope === "full" || request.crossLinkRoot !== undefined || !(runtime.batchWindowMs > 0)) {
1770
+ return await runtime.direct(request);
1771
+ }
1767
1772
  // QA-2.2-9: planning comes first, as in 2.1's direct hook, so an exhausted deadline still gets
1768
1773
  // the planning outcome (NoAffected, S6) the direct path gives, and aborted only for a spec.
1769
1774
  // W7: a request in planning may join an open window, so it keeps the windows open.
@@ -0,0 +1,141 @@
1
+ /**
2
+ * src/verify/branch.ts — I7 (P0.2, S9/S12): did the verified working tree switch branch between two tree snapshots? Pure.
3
+ *
4
+ * The wiring compares the dispatch snapshot with the gate's (synchronous path), and the state recorded when a deferred
5
+ * producer returned with router_verify's fresh snapshot, then hands the worded reason to the gate (Artefact.branchSwitch).
6
+ * Kept out of tree.ts on purpose: several tests mock that module with `snapshotTree` alone.
7
+ */
8
+ import type { TreeSnapshot } from "./dispatch";
9
+ import type { HeadState, ReflogEntry } from "./head";
10
+ import { isSlash, trimEndWhile } from "../util/linear-trim";
11
+
12
+ /** The part of a snapshot (or of a deferred registration) the branch rule reads. */
13
+ export type BranchState = Pick<TreeSnapshot, "head" | "branch">;
14
+
15
+ /**
16
+ * Fail closed. Two known branches that differ are a switch, including a new branch at the same commit (`checkout -b`), and
17
+ * so is a detached HEAD at another commit (a commit on a detached HEAD cannot be told apart from a checkout without the
18
+ * reflog). With either side unknown, any HEAD move is a switch. Ancestry never excuses one: a descendant branch can still
19
+ * leave the producer's commit unchecked-out.
20
+ */
21
+ export function branchSwitched(before: BranchState, now: BranchState): boolean {
22
+ if (before.branch !== undefined && now.branch !== undefined) {
23
+ if (before.branch !== now.branch) return true;
24
+ return before.branch === null && before.head !== now.head;
25
+ }
26
+ return before.head !== now.head;
27
+ }
28
+
29
+ /** `branch feat/x`, `detached HEAD at <7-char sha>`, or `an unknown branch`. */
30
+ export function describeBranch(state: BranchState): string {
31
+ if (state.branch === undefined) return "an unknown branch";
32
+ if (state.branch === null) return `detached HEAD at ${state.head.slice(0, 7)}`;
33
+ return `branch ${state.branch}`;
34
+ }
35
+
36
+ /**
37
+ * QA-SYNC1-17: the window of a gate re-run after a restart on the journaled dispatch-time head: it runs from the dispatch to the
38
+ * gate after the restart, not only the dispatch.
39
+ */
40
+ export const AFTER_RESTART_WINDOW = "between the dispatch and the check after the restart";
41
+
42
+ /** The gate's unverifiable reason for a switch (Artefact.branchSwitch); each side describes itself. */
43
+ export function branchSwitchReason(
44
+ root: string,
45
+ before: BranchState,
46
+ now: BranchState,
47
+ when: "during the dispatch" | typeof AFTER_RESTART_WINDOW | "since the producer returned" | "since the attempt that introduced this acceptance",
48
+ ): string {
49
+ const verb = before.branch === null && now.branch === null ? "moved" : "switched";
50
+ return `the working tree ${root} ${verb} from ${describeBranch(before)} to ${describeBranch(now)} ${when}; the checks would verify another branch`;
51
+ }
52
+
53
+ /** router_verify: a branch was recorded when the producer returned, but the current tree could not be read. */
54
+ export function branchUnconfirmedReason(root: string): string {
55
+ return `cannot confirm the branch of ${root}: the working tree could not be read at router_verify, so the checks could verify another branch. Run router_verify again, or re-dispatch.`;
56
+ }
57
+
58
+ /** How a working tree moved between two head states. */
59
+ export type TreeMove = { readonly kind: "switched" | "rewritten" | "relocated"; readonly detail?: string };
60
+
61
+ function sameRoot(a: string, b: string, platform: NodeJS.Platform): boolean {
62
+ const norm = (p: string) => {
63
+ const slashed = trimEndWhile(p.replace(/\\/g, "/"), isSlash); // linear: no `/\/+$/` (polynomial on a run of "/")
64
+ return platform === "win32" ? slashed.toLowerCase() : slashed;
65
+ };
66
+ return norm(a) === norm(b);
67
+ }
68
+
69
+ /** A reflog subject with control characters removed, capped at 120 chars. */
70
+ function cleanSubject(subject: string): string {
71
+ return subject.replace(/[\u0000-\u001f\u007f-\u009f]/g, "").slice(0, 120);
72
+ }
73
+
74
+ /**
75
+ * The reflog subjects of entries that move HEAD and are the producer's own work: commits (initial, amend, merge), merges,
76
+ * cherry-pick, revert, am and a `pull` that is not a rebase. Matched up to the first colon, so a message cannot widen it.
77
+ * `pull --rebase` and a pull that rebased through config (`pull origin main (start): checkout …`) are refused: they replay
78
+ * the producer's commits onto another base.
79
+ */
80
+ const OWN_WORK = /^(?:commit(?: \([^)]*\))?|merge [^:]*|cherry-pick|revert|am|pull(?![^:]*(?:--rebase|\((?:start|pick|reword|edit|squash|fixup|drop|exec|break|label|reset|finish|continue|abort)\)))[^:]*)(?::|$)/i;
81
+
82
+ /**
83
+ * Did the tree move between `before` and `now`? Roots that differ are a relocation; two known branches that differ are a
84
+ * switch. `window` is the anchored HEAD reflog window since `before` (readReflogWindow: the entries newer than `before`
85
+ * plus the one that was newest then, newest first); pass it only when both states have a reflog count and the count did not
86
+ * shrink. The window must line up with both heads. An entry that left HEAD where it was (stash, unstage, a same-branch
87
+ * checkout, an abort) is ignored; one that moved HEAD must be the producer's own work (OWN_WORK), else it is a rewrite.
88
+ * Without a window, the fail-closed `branchSwitched` rule decides.
89
+ */
90
+ export function treeMove(
91
+ before: HeadState,
92
+ now: HeadState,
93
+ window: readonly ReflogEntry[] | undefined,
94
+ platform: NodeJS.Platform = process.platform,
95
+ ): TreeMove | undefined {
96
+ if (!sameRoot(before.root, now.root, platform)) return { kind: "relocated" };
97
+ if (before.branch !== now.branch) return { kind: "switched" };
98
+ // Every HEAD update writes a reflog entry: a reflog that shrank, or a HEAD that moved with no new entry, is another history
99
+ // in place (a replaced repository, an expired or edited reflog). Fail closed.
100
+ const counted = before.reflog !== undefined && now.reflog !== undefined;
101
+ if (counted) {
102
+ if (now.reflog! < before.reflog!) return { kind: "rewritten", detail: "the reflog has fewer entries than before" };
103
+ if (now.reflog === before.reflog && now.head !== before.head) return { kind: "rewritten", detail: "HEAD moved without a reflog entry" };
104
+ }
105
+ if (window === undefined) return branchSwitched(before, now) ? { kind: "switched" } : undefined;
106
+ const misaligned: TreeMove = { kind: "rewritten", detail: "the reflog window does not line up with the recorded HEAD" };
107
+ const grown = counted ? now.reflog! - before.reflog! : Math.max(0, window.length - 1);
108
+ if (grown === 0) {
109
+ // Nothing new: the heads are equal here (checked above when counted), and a window, when read, is the one old entry.
110
+ if (now.head !== before.head) return misaligned;
111
+ return window.length === 0 || (window.length === 1 && window[0]!.commit === now.head) ? undefined : misaligned;
112
+ }
113
+ if (window.length !== grown + 1) return misaligned;
114
+ if (window[window.length - 1]!.commit !== before.head || window[0]!.commit !== now.head) return misaligned;
115
+ for (let i = 0; i < window.length - 1; i++) {
116
+ const entry = window[i]!;
117
+ if (entry.commit === window[i + 1]!.commit) continue; // HEAD did not move.
118
+ if (!OWN_WORK.test(entry.subject)) {
119
+ return { kind: "rewritten", detail: entry.subject === "" ? "an unnamed reflog entry" : cleanSubject(entry.subject) };
120
+ }
121
+ }
122
+ return undefined;
123
+ }
124
+
125
+ /** The gate's unverifiable reason for a TreeMove. */
126
+ export function treeMoveReason(
127
+ root: string,
128
+ before: HeadState,
129
+ now: HeadState,
130
+ move: TreeMove,
131
+ when: "during the dispatch" | typeof AFTER_RESTART_WINDOW | "since the producer returned",
132
+ ): string {
133
+ switch (move.kind) {
134
+ case "switched":
135
+ return `${branchSwitchReason(root, before, now, when)}. Check out ${describeBranch(before)} again and re-dispatch, or send a fresh [acceptance] block on the current branch.`;
136
+ case "rewritten":
137
+ return `the working tree ${root} moved or was rewritten ${when} (reflog: "${move.detail ?? ""}"); the checks could verify a tree without the producer's work. Re-dispatch, or send a fresh [acceptance] block.`;
138
+ case "relocated":
139
+ return `the working tree ${root} is now ${now.root} ${when}; the checks would verify another tree. Re-dispatch in the intended worktree.`;
140
+ }
141
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * src/verify/canonical-path.ts — the canonical spelling of a path (QA-2.1-8, moved here by QA-1.3-16).
3
+ * A leaf module: it imports only node built-ins, so both the verify change-set store and the lease registry can use
4
+ * it without a dependency cycle.
5
+ */
6
+ import { basename, dirname, join, resolve } from "node:path";
7
+ import { realpathSync } from "node:fs";
8
+
9
+ /**
10
+ * QA-2.1-8: the canonical spelling of `path`, so a Windows 8.3 short name (`C:\Users\MARQUI~1\…`),
11
+ * a junction or symlink alias, and the long real path of one file key the same change-set entry.
12
+ * The native realpath of the path, or of its nearest existing ancestor with the missing tail
13
+ * appended (a deleted file keeps its directory's canonical spelling); lexical `resolve` when no
14
+ * ancestor resolves. A `realpath` that is not a function is replaced by the native one.
15
+ */
16
+ export function canonicalPath(
17
+ path: string,
18
+ realpath: (p: string) => string = realpathSync.native,
19
+ ): string {
20
+ const real: (p: string) => string = typeof realpath === "function" ? realpath : realpathSync.native;
21
+ const absolute = resolve(path);
22
+ let head = absolute;
23
+ const tail: string[] = [];
24
+ for (;;) {
25
+ try {
26
+ const found = real(head);
27
+ return tail.length === 0 ? found : join(found, ...tail.reverse());
28
+ } catch {
29
+ const parent = dirname(head);
30
+ if (parent === head) return absolute;
31
+ tail.push(basename(head));
32
+ head = parent;
33
+ }
34
+ }
35
+ }