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,8 +5,9 @@
5
5
  * of the role table as a router-defined agent with the role's MAX policy: deny-by-default, only
6
6
  * the role's actions under their host names, `execute`/`subagent`/`task`/`delegate`/`shell`
7
7
  * denied explicitly, the read-only tiers' sensitive-read asks, and `external_directory` allowed
8
- * only for the repository's worktree roots (listed at registration) and the `routing.workRoots`
9
- * patterns. The definitions carry the plugin-agent marker, so the v2 adapter publishes them like
8
+ * only for the repository's worktree roots (listed at registration), configured work roots and
9
+ * the trusted executor slots root, with the executor home denied after every allow.
10
+ * The definitions carry the plugin-agent marker, so the v2 adapter publishes them like
10
11
  * #81 plugin agents (inherited denies only) and `protectedAgent()` holds for each of them (P-19):
11
12
  * the router's evaluate and context hooks then enforce the policy under a granting parent too.
12
13
  *
@@ -14,15 +15,21 @@
14
15
  * anything (I1/I8). A failure while resolving or building the roles registers no role agent at
15
16
  * all (fail closed); tier agents are never touched.
16
17
  */
17
- import { realpathSync } from "node:fs";
18
- import { join } from "node:path";
19
- import { resolveActiveTiers, resolveRolesRouting, type RouterConfig, type TierConfig } from "./config";
20
- import { GIT_TOOL_NAMES, gitEnvironment, gitExecutable, hardeningArgs, inheritedSafeDirectoryArgs, spawnBounded } from "./git-tools";
18
+ import { lstatSync, realpathSync, statSync } from "node:fs";
19
+ import { join, posix, resolve as resolvePath, win32 } from "node:path";
20
+ import { EXECUTOR_HOME_DIRNAME, resolveExecutorHome } from "../executor/paths";
21
+ import { resolveActiveTiers, resolveRolesRouting, resolveRouting, slotsDirProblem, type RouterConfig, type TierConfig } from "./config";
22
+ import {
23
+ GIT_TOOL_NAMES, gitEnvironment, gitExecutable, gitPointers, hardeningArgs, inheritedSafeDirectoryArgs, nearestRepository, spawnBounded,
24
+ workRootGuards,
25
+ } from "./git-tools";
21
26
  import { positiveBudget, REFUSAL_CAP, ROUTE_BUDGET_RAISE_MAX, TIER_GUARD_BUDGET } from "./guard-profile";
22
27
  import { PLUGIN_AGENT, pluginAgentMarker, pluginAgentPolicy, type PluginAgentMarker } from "./plugin-agents";
23
- import { CONTEXT7_DOC_TOOLS, type PermissionMap } from "./read-only";
28
+ import { CONTEXT7_DOC_TOOLS, permissionMatches, type PermissionMap } from "./read-only";
29
+ import { isApprovalValid, type RepoApproval } from "../routing/roles/approvals";
24
30
  import { ACTION_CLASS, HOST_NATIVE_ROLE_NAMES, resolveRoleTable, SHIPPED_ROLE_SPECS, type AuthorityAction, type RoleSpec, type RoleTable } from "./roles";
25
- import { workRootProblem } from "./roles-config";
31
+ import { workRootGlobIndex, workRootProblem } from "./roles-config";
32
+ import { locationOutsideWorkRoots } from "./work-roots";
26
33
 
27
34
  /**
28
35
  * Steps above the largest guard budget a role dispatch can reach. The guard's `NEED MORE: budget`
@@ -83,20 +90,28 @@ export function roleHasLocalActions(spec: Pick<RoleSpec, "authority">): boolean
83
90
  /**
84
91
  * A role's max permission policy (v2 action names, ordered, last match wins): `* deny` first,
85
92
  * then an allow per {@link roleHostActions}, then `external_directory` allows for `externalDirectory`
86
- * (local roles only; a bare `*` is never written), then the {@link ROLE_DENIED_ACTIONS} denies;
93
+ * (local roles only; a bare `*` is never written), then `externalDirectoryDeny` after every allow
94
+ * and the {@link ROLE_DENIED_ACTIONS} denies;
87
95
  * the `read` rules are rebuilt by the plugin-agent policy with the sensitive-read asks after the
88
96
  * grant (a role without `read` gets `read: { "*": "deny" }`).
89
97
  */
90
98
  export function roleMaxPermission(
91
99
  spec: Pick<RoleSpec, "authority">,
92
- opts: { context7: boolean; externalDirectory: readonly string[] },
100
+ opts: { context7: boolean; externalDirectory: readonly string[]; externalDirectoryDeny?: readonly string[] },
93
101
  ): PermissionMap {
94
102
  const own: PermissionMap = { "*": "deny" };
95
103
  for (const name of roleHostActions(spec, opts)) own[name] = "allow";
96
104
  const patterns = roleHasLocalActions(spec)
97
105
  ? [...new Set(opts.externalDirectory)].filter((pattern) => pattern !== "" && !/^[*?]+$/.test(pattern))
98
106
  : [];
99
- if (patterns.length > 0) own.external_directory = Object.fromEntries(patterns.map((pattern) => [pattern, "allow" as const]));
107
+ const denied = [...new Set(opts.externalDirectoryDeny ?? [])].filter((pattern) => pattern !== "");
108
+ if (patterns.length > 0 || denied.length > 0) {
109
+ // Drop overlapping keys from the allows too: updating a key would retain its earlier insertion order.
110
+ own.external_directory = Object.fromEntries([
111
+ ...patterns.filter((pattern) => !denied.includes(pattern)).map((pattern) => [pattern, "allow" as const]),
112
+ ...denied.map((pattern) => [pattern, "deny" as const]),
113
+ ]);
114
+ }
100
115
  for (const action of ROLE_DENIED_ACTIONS) own[action] = "deny";
101
116
  return pluginAgentPolicy({ permission: own }, { context7: opts.context7, host: "v2" }).permission;
102
117
  }
@@ -125,7 +140,7 @@ function validModel(model: unknown): model is string {
125
140
  export function buildRoleAgentDefinition(
126
141
  spec: RoleSpec,
127
142
  floor: Pick<TierConfig, "model" | "variant">,
128
- opts: { context7: boolean; externalDirectory: readonly string[] },
143
+ opts: { context7: boolean; externalDirectory: readonly string[]; externalDirectoryDeny?: readonly string[] },
129
144
  ): Record<string, unknown> {
130
145
  if (!validModel(floor.model)) throw new Error(`role ${spec.agent}: floor tier ${spec.tierRange.floor} has no provider/model reference`);
131
146
  const steps = roleAgentSteps(spec);
@@ -172,7 +187,8 @@ const WORKTREE_LIST_TIMEOUT_MS = 10_000;
172
187
  */
173
188
  export async function listWorktrees(directory: string): Promise<string[]> {
174
189
  const started = performance.now();
175
- const executable = gitExecutable();
190
+ // QA-62F-4: the executable is chosen outside the listed directory's work root, like the executor-home lookup.
191
+ const executable = gitExecutable(workRootGuards(directory));
176
192
  const trusted = await inheritedSafeDirectoryArgs(executable, WORKTREE_LIST_TIMEOUT_MS);
177
193
  const result = await spawnBounded(executable, [...hardeningArgs(), ...trusted, "worktree", "list", "--porcelain"], directory, {
178
194
  env: gitEnvironment(), timeoutMs: Math.max(1, WORKTREE_LIST_TIMEOUT_MS - (performance.now() - started)), maxBytes: 1024 * 1024,
@@ -205,6 +221,109 @@ export function worktreeRootPattern(root: string, realpath: Realpath = nativeRea
205
221
  return workRootProblem(canonical) === undefined ? join(canonical, "*") : undefined;
206
222
  }
207
223
 
224
+ /**
225
+ * The `external_directory` allow pattern of one approved repository (cross-repo Phase 4, SD-P4-15):
226
+ * `<path><sep>*` built like {@link worktreeRootPattern}, but only when the stored path still is its
227
+ * own canonical long form (`realpathSync.native(path)` equals `path` as text, case-insensitive on
228
+ * win32: a moved, replaced or junctioned folder gets no pattern) and both forms pass the P1.1 rules
229
+ * ({@link workRootProblem}). Undefined, with the reason, otherwise: fail closed. No git.
230
+ */
231
+ export function approvedRootPattern(path: string, realpath: Realpath = nativeRealpath): { pattern?: string; problem?: string } {
232
+ const problem = workRootProblem(path);
233
+ if (problem !== undefined) return { problem };
234
+ let canonical: string;
235
+ try {
236
+ canonical = realpath(path);
237
+ } catch {
238
+ return { problem: "does not resolve to a directory" };
239
+ }
240
+ const same = process.platform === "win32" ? canonical.toLowerCase() === path.toLowerCase() : canonical === path;
241
+ if (!same) return { problem: `resolves to ${canonical}, not the approved path` };
242
+ const after = workRootProblem(canonical);
243
+ return after === undefined ? { pattern: join(canonical, "*") } : { problem: `canonical form ${canonical} ${after}` };
244
+ }
245
+
246
+ /**
247
+ * QA-62C-1, QA-62C-13: the git common directory of the repository holding `directory`, read from disk without running
248
+ * git (used off Windows, where the executor never runs but a Windows host sharing the repository may). The nearest
249
+ * checkout ({@link nearestRepository}) is read by the hardened {@link gitPointers}: `.git` and `commondir` at most 4 KiB,
250
+ * regular files only, opened non-blocking, a linked `.git` and a network or device pointer refused. `common` is the
251
+ * git directory's `commondir` target when present, else the git directory (`<checkout>/.git` or what `gitdir:` names).
252
+ * `{}` when no repository is found or its `.git` names no git directory; `problem` when the pointers are refused or unreadable.
253
+ */
254
+ function gitCommonDirOnDisk(directory: string): { common?: string; problem?: string } {
255
+ const checkout = nearestRepository(resolvePath(directory));
256
+ if (checkout === undefined) return {};
257
+ try {
258
+ const pointers = gitPointers(checkout);
259
+ return pointers === undefined ? {} : { common: pointers.common };
260
+ } catch (error) {
261
+ return { problem: errorText(error) };
262
+ }
263
+ }
264
+
265
+ /** Executor directories may not exist yet; only ENOENT permits using a canonical parent and the literal basename. */
266
+ function executorDirectoryRoot(path: string, realpath: Realpath, requireSame = true): { root?: string; problem?: string } {
267
+ const problem = workRootProblem(path);
268
+ if (problem !== undefined) return { problem };
269
+ if (workRootGlobIndex(path) !== -1) return { problem: "must be a literal directory, not a glob" };
270
+ let canonical: string;
271
+ try {
272
+ canonical = realpath(path);
273
+ const same = process.platform === "win32" ? canonical.toLowerCase() === path.toLowerCase() : canonical === path;
274
+ if (requireSame && !same) return { problem: `resolves to ${canonical}, not the configured path` };
275
+ } catch (error) {
276
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") {
277
+ return { problem: "does not resolve to a directory" };
278
+ }
279
+ const api = /^[A-Za-z]:[\\/]/.test(path) ? win32 : posix;
280
+ try {
281
+ canonical = api.join(realpath(api.dirname(path)), api.basename(path));
282
+ } catch {
283
+ return { problem: "parent does not resolve to a directory" };
284
+ }
285
+ }
286
+ const after = workRootProblem(canonical);
287
+ if (after !== undefined) return { problem: `canonical form ${canonical} ${after}` };
288
+ if (workRootGlobIndex(canonical) !== -1) return { problem: "canonical directory contains a glob character" };
289
+ return { root: canonical };
290
+ }
291
+
292
+ /** D6: reject overlap with non-slot worktrees, but existing executor worktrees must not block future slots. */
293
+ function executorSlotsRootPattern(path: string, worktrees: readonly string[], realpath: Realpath): { pattern?: string; problem?: string } {
294
+ const problem = slotsDirProblem(path);
295
+ if (problem !== undefined) return { problem };
296
+ const canonical = executorDirectoryRoot(path, realpath);
297
+ if (canonical.root === undefined) return { problem: canonical.problem };
298
+ const after = slotsDirProblem(canonical.root);
299
+ if (after !== undefined) return { problem: `canonical form ${canonical.root} ${after}` };
300
+ for (const [index, worktree] of worktrees.entries()) {
301
+ let root: string;
302
+ try {
303
+ root = realpath(worktree);
304
+ } catch {
305
+ // Git can retain deleted (even locked) linked worktrees. Only a missing entry is harmless;
306
+ // an existing path without a canonical form, and the main checkout, must still fail closed.
307
+ if (index > 0) {
308
+ try {
309
+ lstatSync(worktree);
310
+ } catch (error) {
311
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") continue;
312
+ }
313
+ }
314
+ return { problem: `worktree ${worktree} has no canonical long form` };
315
+ }
316
+ // Executor worktrees live at <root>/<plan>/slot-N, integration or ci.
317
+ // Never exempt the first (main) checkout, or ordinary non-slot descendants.
318
+ const relative = dirKey(root).slice(dirKey(canonical.root).length + 1);
319
+ if (index > 0 && isOrContains(canonical.root, root) && /^[^/]+\/(?:slot-[1-9]\d{0,2}|integration|ci)$/.test(relative)) continue;
320
+ if ([path, canonical.root].some((slots) => [worktree, root].some((tree) => isOrContains(slots, tree) || isOrContains(tree, slots)))) {
321
+ return { problem: `is inside or an ancestor of worktree ${worktree}` };
322
+ }
323
+ }
324
+ return { pattern: join(canonical.root, "*") };
325
+ }
326
+
208
327
  /**
209
328
  * The `external_directory` allow pattern of one `routing.workRoots` entry (P-11): the static
210
329
  * directory before the first wildcard in its canonical long form, then the glob tail verbatim
@@ -215,7 +334,7 @@ export function worktreeRootPattern(root: string, realpath: Realpath = nativeRea
215
334
  export function workRootPattern(entry: string, realpath: Realpath = nativeRealpath): { pattern?: string; problem?: string } {
216
335
  const problem = workRootProblem(entry);
217
336
  if (problem !== undefined) return { problem };
218
- const globAt = entry.search(/[*?[\]{}]/);
337
+ const globAt = workRootGlobIndex(entry);
219
338
  if (globAt === -1) {
220
339
  const pattern = worktreeRootPattern(entry, realpath);
221
340
  return pattern === undefined ? { problem: "does not resolve to a directory in canonical long form" } : { pattern };
@@ -243,6 +362,8 @@ export function externalDirectoryPatterns(
243
362
  worktrees: readonly string[],
244
363
  workRoots: readonly string[],
245
364
  realpath: Realpath = nativeRealpath,
365
+ parents: readonly string[] = [],
366
+ approved: readonly string[] = [],
246
367
  ): { patterns: string[]; problems: string[] } {
247
368
  const patterns: string[] = [];
248
369
  const problems: string[] = [];
@@ -259,9 +380,83 @@ export function externalDirectoryPatterns(
259
380
  if (result.pattern === undefined) problems.push(`routing.workRoots entry ${entry} ${result.problem ?? "is not usable"}; not granted`);
260
381
  else add(result.pattern);
261
382
  }
383
+ // P1.6: one `<parent><sep>*` per `routing.repoParents` entry; the host's `*` crosses separators, so it covers every depth.
384
+ const parentDirs: string[] = [...parents];
385
+ for (const parent of parents) {
386
+ const result = workRootPattern(`${parent.replace(/[\\/]+$/, "")}/*`, realpath);
387
+ if (result.pattern === undefined) problems.push(`routing.repoParents entry ${parent} ${result.problem ?? "is not usable"}; not granted`);
388
+ else {
389
+ add(result.pattern);
390
+ parentDirs.push(result.pattern.replace(/[\\/]?\*$/, ""));
391
+ }
392
+ }
393
+ // Cross-repo Phase 4 (SD-P4-15): one `<path><sep>*` per approved repository, only with parents (I9); the caller passes
394
+ // approvals already checked for expiry and exclusion ({@link approvedRootsInForce}). Phase 4 QA (m3): never one that is or
395
+ // contains a parent (text or canonical form): its rule would be wider than the parents, and admission refuses it anyway.
396
+ if (parents.length > 0) {
397
+ for (const path of approved) {
398
+ const result = approvedRootPattern(path, realpath);
399
+ if (result.pattern === undefined) {
400
+ problems.push(`approved repository ${path} ${result.problem ?? "is not usable"}; not granted`);
401
+ continue;
402
+ }
403
+ const approvedDir = result.pattern.replace(/[\\/]?\*$/, "");
404
+ const held = parentDirs.find((dir) => dir.trim() !== "" && (isOrContains(path, dir) || isOrContains(approvedDir, dir)));
405
+ if (held !== undefined) problems.push(`approved repository ${path} is or contains routing.repoParents entry ${held}; not granted`);
406
+ else add(result.pattern);
407
+ }
408
+ }
262
409
  return { patterns, problems };
263
410
  }
264
411
 
412
+ /** Comparison form of a directory for the parent checks: `/` separators, no trailing one, case-folded on win32. Text only. */
413
+ function dirKey(p: string): string {
414
+ const unified = p.replace(/\\/g, "/").replace(/\/+$/, "");
415
+ return process.platform === "win32" ? unified.toLowerCase() : unified;
416
+ }
417
+
418
+ /** Whether directory `outer` is directory `inner` or contains it ({@link dirKey} forms; a filesystem root contains all). */
419
+ function isOrContains(outer: string, inner: string): boolean {
420
+ const o = dirKey(outer);
421
+ const i = dirKey(inner);
422
+ return o === "" || o === i || i.startsWith(`${o}/`);
423
+ }
424
+
425
+ /** One store entry as registration sees it (cross-repo Phase 4): read without git. */
426
+ export type ApprovedRoot = Pick<RepoApproval, "path" | "approvedAt" | "lastUsedAt">;
427
+
428
+ /**
429
+ * The approved repository paths registration may grant (SD-P4-15): none without `routing.repoParents` (I9); otherwise each
430
+ * approval that has not expired ({@link isApprovalValid} with `routing.repoApprovalDays`) and whose path text no
431
+ * `routing.repoExclude` glob matches (exclusion wins over an approval) and that is not, and does not contain, a
432
+ * `routing.repoParents` entry (Phase 4 QA m3: text, case-insensitive on win32; such an approval would be granted wider than
433
+ * the parents). Excluded and parent-holding ones are reported in `problems`; expired ones are dropped silently. No filesystem
434
+ * access, no git.
435
+ */
436
+ export function approvedRootsInForce(
437
+ approved: readonly ApprovedRoot[],
438
+ routing: { readonly repoParents: readonly string[]; readonly repoExclude: readonly string[]; readonly repoApprovalDays: number },
439
+ now: number,
440
+ ): { paths: string[]; problems: string[] } {
441
+ const paths: string[] = [];
442
+ const problems: string[] = [];
443
+ if (routing.repoParents.length === 0) return { paths, problems };
444
+ for (const entry of approved) {
445
+ if (typeof entry.path !== "string" || entry.path === "") continue;
446
+ if (!isApprovalValid(entry, routing.repoApprovalDays, now)) continue;
447
+ const held = routing.repoParents.find((parent) => parent.trim() !== "" && isOrContains(entry.path, parent));
448
+ if (held !== undefined) {
449
+ problems.push(`approved repository ${entry.path} is or contains routing.repoParents entry ${held}; not granted`);
450
+ continue;
451
+ }
452
+ const forms = process.platform === "win32" && entry.path.includes("/") ? [entry.path, entry.path.replace(/\//g, "\\")] : [entry.path];
453
+ const excluded = routing.repoExclude.find((glob) => glob.trim() !== "" && forms.some((form) => permissionMatches(form, glob)));
454
+ if (excluded !== undefined) problems.push(`approved repository ${entry.path} is excluded by routing.repoExclude (${excluded}); not granted`);
455
+ else if (!paths.includes(entry.path)) paths.push(entry.path);
456
+ }
457
+ return { paths, problems };
458
+ }
459
+
265
460
  // ---------------------------------------------------------------------------
266
461
  // Registration
267
462
  // ---------------------------------------------------------------------------
@@ -275,27 +470,51 @@ export interface RoleRegistration {
275
470
  readonly replaced: readonly string[];
276
471
  /** `external_directory` allow patterns written into local roles. */
277
472
  readonly externalDirectory: readonly string[];
473
+ /** `external_directory` deny patterns written after every allow. */
474
+ readonly externalDirectoryDenied: readonly string[];
278
475
  /** True when registration failed and no role agent was registered. */
279
476
  readonly failed: boolean;
280
477
  }
281
478
 
282
479
  const NONE: RoleRegistration = Object.freeze({
283
- registered: Object.freeze([]), removed: Object.freeze([]), replaced: Object.freeze([]), externalDirectory: Object.freeze([]), failed: false,
480
+ registered: Object.freeze([]), removed: Object.freeze([]), replaced: Object.freeze([]), externalDirectory: Object.freeze([]),
481
+ externalDirectoryDenied: Object.freeze([]), failed: false,
284
482
  });
285
483
 
286
484
  export interface RoleRegistrationOptions {
287
485
  /** The context7 MCP server is configured (its documentation tools become direct tools). */
288
486
  context7: boolean;
289
- /** The project directory: its repository's worktrees are listed. */
487
+ /**
488
+ * The project directory: its repository's worktrees are listed. When `routing.workRoots` is set and the directory lies
489
+ * outside every entry (`locationOutsideWorkRoots`), the executor slots root is not granted (QA-5.1-5) and the
490
+ * executor-home lookup runs only when worktrees were listed, to deny the home their allows cover (QA-62F-1).
491
+ */
290
492
  directory: string;
291
493
  /** The host's own agents at setup (name → seed definition); a removed #81 entry falls back to it. */
292
494
  seed: Readonly<Record<string, Record<string, unknown>>>;
293
495
  /** Logs `message` once per `key`. */
294
496
  warn: (key: string, message: string) => void;
497
+ /**
498
+ * Cross-repo Phase 4 (SD-P4-15): the entries of the repository approvals store, read without git. Each one in force
499
+ * ({@link approvedRootsInForce}) whose path is still its own canonical form gets a `<path><sep>*` rule. Absent: none.
500
+ */
501
+ approvedRoots?: readonly ApprovedRoot[];
295
502
  /** Injection points (tests). */
296
503
  listWorktrees?: (directory: string) => Promise<string[]>;
297
504
  resolveTable?: (cfg: RouterConfig, host: "v1" | "v2", opts: { context7?: boolean }) => RoleTable;
298
505
  realpath?: Realpath;
506
+ /** Replaces the executor-home lookup; its result is still canonicalized before granting slots access. */
507
+ executorHome?: (directory: string) => Promise<string>;
508
+ /**
509
+ * G-16: false when the plan executor cannot run on this platform (the caller asks `executorPlatformSupported`): the
510
+ * executor is treated as disabled, so no executor-home lookup runs and no slots root is granted. The executor home in
511
+ * the git common directory (found on disk by {@link gitCommonDirOnDisk}, no git) is still denied whenever that directory
512
+ * resolves, even before the home exists (QA-62C-1, QA-62C-14: a Windows host may run the executor on a repository
513
+ * shared with WSL). Absent: true.
514
+ */
515
+ executorPlatform?: boolean;
516
+ /** Clock in epoch ms for the approval expiry; default `Date.now`. */
517
+ now?: () => number;
299
518
  }
300
519
 
301
520
  const PREFIX = "roles mode (OpenCode v2 only): ";
@@ -333,26 +552,120 @@ export async function registerRoleAgents(
333
552
  let built: Map<string, Record<string, unknown>>;
334
553
  let table: RoleTable;
335
554
  let externalDirectory: string[] = [];
555
+ let externalDirectoryDenied: string[] = [];
336
556
  try {
337
557
  table = (opts.resolveTable ?? resolveRoleTable)(cfg, "v2", { context7: opts.context7 });
338
558
  const tiers = resolveActiveTiers(cfg);
559
+ const hasLocalActions = [...table.roles.values()].some(roleHasLocalActions);
339
560
  let worktrees: string[] = [];
340
- if ([...table.roles.values()].some(roleHasLocalActions)) {
561
+ let worktreeListingProblem: string | undefined;
562
+ // G-12: the worktrees are listed whatever `routing.workRoots` contains (a glob for later-created worktrees must not
563
+ // drop the existing ones). Outside every configured work root the executor home is still denied when worktrees were
564
+ // listed or the listing failed (QA-62F-1, QA-62F-9); only the executor slots-root grant is skipped there.
565
+ const outside = locationOutsideWorkRoots(opts.directory, routing.workRoots, process.platform, opts.realpath ?? nativeRealpath);
566
+ if (hasLocalActions) {
341
567
  try {
342
568
  worktrees = await (opts.listWorktrees ?? listWorktrees)(opts.directory);
343
569
  } catch (error) {
570
+ worktreeListingProblem = errorText(error);
344
571
  opts.warn("roles:worktrees", `${PREFIX}the repository's worktrees could not be listed (${errorText(error)}); role agents get no worktree external_directory rule`);
345
572
  }
346
573
  }
347
- const found = externalDirectoryPatterns(worktrees, routing.workRoots, opts.realpath ?? nativeRealpath);
348
- for (const problem of found.problems) opts.warn(`roles:external:${problem}`, `${PREFIX}${problem}`);
574
+ const approved = approvedRootsInForce(opts.approvedRoots ?? [], routing, (opts.now ?? Date.now)());
575
+ const found = externalDirectoryPatterns(worktrees, routing.workRoots, opts.realpath ?? nativeRealpath, routing.repoParents, approved.paths);
576
+ for (const problem of [...approved.problems, ...found.problems]) opts.warn(`roles:external:${problem}`, `${PREFIX}${problem}`);
349
577
  externalDirectory = found.patterns;
578
+ // slotsDir is trusted here: the project-controlled value was stripped before the config merge (D18).
579
+ const executorRouting = resolveRouting(cfg, "v2");
580
+ const slotsDir = executorRouting.executor.slotsDir;
581
+ const executorEnabled = opts.executorPlatform !== false
582
+ && executorRouting.leases.mode === "enforce" && cfg.enforcement?.verify?.require !== "never";
583
+ const executorProblems: Array<readonly [key: string, message: string]> = [];
584
+ // QA-62F-1, QA-62F-9: outside every work root, listed worktrees or configured roots can still cover the executor
585
+ // home in the git common directory, even when listing failed. Resolve the home (one read-only, guarded rev-parse)
586
+ // and deny it there; the slots-root grant below stays inside the work roots only.
587
+ if (executorEnabled && table.roles.size > 0 && (!outside || worktrees.length > 0 || worktreeListingProblem !== undefined)) {
588
+ const realpath = opts.realpath ?? nativeRealpath;
589
+ const homeDirectory = worktrees[0] ?? opts.directory;
590
+ let home: string | undefined;
591
+ try {
592
+ const resolved = await (opts.executorHome ?? resolveExecutorHome)(homeDirectory);
593
+ const canonical = executorDirectoryRoot(resolved, realpath, false);
594
+ if (canonical.root === undefined) throw new Error(canonical.problem ?? "has no canonical long form");
595
+ home = canonical.root;
596
+ externalDirectoryDenied = [join(home, "*")];
597
+ } catch (error) {
598
+ const problem = errorText(error);
599
+ // D7: Git's non-repository diagnostic means there is no executor to grant or protect. Other failures
600
+ // (including other exit-128 errors such as dubious ownership) still fail closed with one warning.
601
+ let notRepository = /(?:^|:\s*)(?:fatal:\s*)?not a git repository\b/i.test(problem);
602
+ if (!notRepository && opts.executorHome === undefined) {
603
+ // A missing/non-directory cwd prevents Git from starting, so it cannot emit its non-repository diagnostic.
604
+ // Only probe native lookups: an injected resolver may model a repository without creating it on disk.
605
+ try {
606
+ notRepository = !statSync(homeDirectory).isDirectory();
607
+ } catch (directoryError) {
608
+ notRepository = directoryError instanceof Error && "code" in directoryError
609
+ && (directoryError.code === "ENOENT" || directoryError.code === "ENOTDIR");
610
+ }
611
+ }
612
+ if (!notRepository) {
613
+ executorProblems.push(["roles:executor-home", `${PREFIX}the executor home could not be resolved (${problem}); the executor home is not denied and role agents get no slots external_directory rule`]);
614
+ }
615
+ }
616
+ // An unresolved home cannot be protected by a final deny: do not grant the slots root either (D6).
617
+ if (!outside && home !== undefined && hasLocalActions && (slotsDir !== null || process.platform === "win32")) {
618
+ // Match create.ts's location toplevel, not Git's first (main) worktree on another drive.
619
+ let toplevel: string | undefined;
620
+ try {
621
+ const directory = realpath(opts.directory);
622
+ for (const worktree of worktrees) {
623
+ try {
624
+ const tree = realpath(worktree);
625
+ if (isOrContains(tree, directory) && tree.length > (toplevel?.length ?? 0)) toplevel = tree;
626
+ } catch { /* Unresolved entries cannot select a drive; the slots overlap check still fails closed. */ }
627
+ }
628
+ } catch { /* A missing canonical location cannot select a default drive. */ }
629
+ const drive = /^([A-Za-z]):[\\/]/.exec(toplevel ?? "");
630
+ const root = slotsDir ?? (drive === null ? undefined : `${drive[1]}:\\.omr-slots`);
631
+ const slots = worktreeListingProblem !== undefined
632
+ ? { problem: `the worktree listing failed (${worktreeListingProblem})` }
633
+ : root === undefined
634
+ ? { problem: "the repository toplevel is not on a drive-letter path" }
635
+ : executorSlotsRootPattern(root, worktrees, realpath);
636
+ if (slots.pattern === undefined) {
637
+ executorProblems.push(["roles:executor-slots", `${PREFIX}executor slots root ${root ?? "(default)"} ${slots.problem ?? "is not usable"}; not granted`]);
638
+ } else if (!externalDirectory.includes(slots.pattern)) {
639
+ externalDirectory.push(slots.pattern);
640
+ }
641
+ }
642
+ } else if (opts.executorPlatform === false && table.roles.size > 0
643
+ && (!outside || worktrees.length > 0 || worktreeListingProblem !== undefined)) {
644
+ // QA-62C-1: the executor does not run on this platform, but a Windows host sharing the repository (WSL) may run it.
645
+ // Deny the executor home in the common directory, found on disk without running git, whether or not it exists yet
646
+ // (QA-62C-14: a deny on a missing path is harmless, and the Windows host may create it later); never grant the slots
647
+ // root here. A home that does not exist yet gets its canonical parent and the literal name, like the win32 branch.
648
+ const found = gitCommonDirOnDisk(worktrees[0] ?? opts.directory);
649
+ if (found.problem !== undefined) {
650
+ executorProblems.push(["roles:executor-home", `${PREFIX}the git common directory could not be read (${found.problem}); the executor home is not denied`]);
651
+ } else if (found.common !== undefined) {
652
+ const home = join(found.common, EXECUTOR_HOME_DIRNAME);
653
+ const canonical = executorDirectoryRoot(home, opts.realpath ?? nativeRealpath, false);
654
+ if (canonical.root !== undefined) {
655
+ externalDirectoryDenied = [join(canonical.root, "*")];
656
+ } else {
657
+ executorProblems.push(["roles:executor-home", `${PREFIX}the executor home ${home} ${canonical.problem ?? "has no canonical long form"}; the executor home is not denied`]);
658
+ }
659
+ }
660
+ }
350
661
  built = new Map();
351
662
  for (const [name, spec] of table.roles) {
352
663
  const floor = tiers[spec.tierRange.floor];
353
664
  if (floor === undefined) throw new Error(`role ${name}: floor tier ${spec.tierRange.floor} is not in the active preset`);
354
- built.set(name, buildRoleAgentDefinition(spec, floor, { context7: opts.context7, externalDirectory }));
665
+ built.set(name, buildRoleAgentDefinition(spec, floor, { context7: opts.context7, externalDirectory, externalDirectoryDeny: externalDirectoryDenied }));
355
666
  }
667
+ // Registration failure already emits its single notice; executor warnings apply only to registered definitions.
668
+ for (const [key, message] of executorProblems) opts.warn(key, message);
356
669
  } catch (error) {
357
670
  return fail(agents, opts, error);
358
671
  }
@@ -376,6 +689,7 @@ export async function registerRoleAgents(
376
689
  removed: Object.freeze(removed),
377
690
  replaced: Object.freeze([...table.replacedRoles]),
378
691
  externalDirectory: Object.freeze([...externalDirectory]),
692
+ externalDirectoryDenied: Object.freeze([...externalDirectoryDenied]),
379
693
  failed: false,
380
694
  });
381
695
  }
@@ -40,6 +40,8 @@ export const DEFAULT_RUN_COMMANDS: RunConfig["commands"] = Object.freeze({
40
40
  }),
41
41
  });
42
42
  export const DEFAULT_RUN_TIMEOUT_MS = 600_000;
43
+ /** `routing.repoDepth` default: repositories one or two levels below a parent (`D:/git/x`, `D:/git/org/x`). */
44
+ export const DEFAULT_REPO_DEPTH = 2;
43
45
  export const RUN_TIMEOUT_BOUNDS = { min: 1_000, max: 3_600_000 } as const;
44
46
  export const ROLES_V1_NOTICE = "roles delegation requires OpenCode v2; using tiers";
45
47
 
@@ -197,9 +199,18 @@ export function sanitizeRun(value: unknown): Sanitized<Partial<RunConfig>> {
197
199
  * canonical long form: a segment like `PROGRA~1` is an 8.3 short name that can alias another
198
200
  * directory (R6/P-11).
199
201
  */
202
+ /**
203
+ * QA-DF1-25: where the first glob character of a `routing.workRoots` entry is (`*`, `?`, `[`, `]`, `{`, `}`), or -1. Shared
204
+ * by the entry rules here, the `external_directory` patterns (`workRootPattern`) and the location matcher (`work-roots.ts`),
205
+ * so all three cut an entry's static prefix at the same place.
206
+ */
207
+ export function workRootGlobIndex(entry: string): number {
208
+ return entry.search(/[*?[\]{}]/);
209
+ }
210
+
200
211
  export function workRootProblem(entry: string): string | undefined {
201
212
  if (entry === "") return "is empty";
202
- const globAt = entry.search(/[*?[\]{}]/);
213
+ const globAt = workRootGlobIndex(entry);
203
214
  const prefix = globAt === -1 ? entry : entry.slice(0, globAt);
204
215
  const normalised = prefix.replace(/\\/g, "/");
205
216
  let rest: string;
@@ -243,6 +254,83 @@ export function sanitizeWorkRoots(value: unknown): Sanitized<string[]> {
243
254
  return { value: out, issues };
244
255
  }
245
256
 
257
+ /**
258
+ * A `routing.repoParents` entry (cross-repo, Phase 1): a literal, local, absolute directory in canonical long form. No glob
259
+ * (a parent is one directory), no network or device path, then {@link workRootProblem}'s rules (static prefix, no `.`/`..`,
260
+ * no 8.3 segment).
261
+ */
262
+ export function repoParentProblem(entry: string): string | undefined {
263
+ // Network and device paths first: `\\?\C:\x` carries a `?` but is refused for what it is.
264
+ if (/^[\\/]{2}/.test(entry)) return "is a network or device path; use a local directory";
265
+ if (/[*?[\]{}]/.test(entry)) return "contains a glob character; a parent is a literal directory";
266
+ return workRootProblem(entry);
267
+ }
268
+
269
+ function sanitizePathList(
270
+ key: "repoParents" | "repoExclude",
271
+ value: unknown,
272
+ problemOf: (entry: string) => string | undefined,
273
+ what: string,
274
+ ): Sanitized<string[]> {
275
+ const issues: RolesIssue[] = [];
276
+ if (value === undefined) return { value: undefined, issues };
277
+ if (!Array.isArray(value)) {
278
+ issues.push({ path: `routing.${key}`, message: `routing.${key} must be an array of ${what} (got ${show(value)}); ignored` });
279
+ return { value: undefined, issues };
280
+ }
281
+ const out: string[] = [];
282
+ value.forEach((entry: unknown, i) => {
283
+ const path = `routing.${key}[${i}]`;
284
+ if (typeof entry !== "string") {
285
+ issues.push({ path, message: `${path} must be a string (got ${show(entry)}); entry dropped` });
286
+ return;
287
+ }
288
+ const problem = problemOf(entry);
289
+ if (problem !== undefined) {
290
+ issues.push({ path, message: `${path} ${show(entry)} ${problem}; entry dropped` });
291
+ return;
292
+ }
293
+ if (!out.includes(entry)) out.push(entry);
294
+ });
295
+ return { value: out, issues };
296
+ }
297
+
298
+ export function sanitizeRepoParents(value: unknown): Sanitized<string[]> {
299
+ return sanitizePathList("repoParents", value, repoParentProblem, "absolute directories");
300
+ }
301
+
302
+ export function sanitizeRepoExclude(value: unknown): Sanitized<string[]> {
303
+ return sanitizePathList("repoExclude", value, workRootProblem, "absolute globs");
304
+ }
305
+
306
+ export function sanitizeRepoDepth(value: unknown): Sanitized<number> {
307
+ if (value === undefined) return { value: undefined, issues: [] };
308
+ if (typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 4) return { value, issues: [] };
309
+ return {
310
+ value: undefined,
311
+ issues: [{ path: "routing.repoDepth", message: `routing.repoDepth must be an integer from 1 to 4 (got ${show(value)}); ignored` }],
312
+ };
313
+ }
314
+
315
+ /** Days an approval of a repository outside the parents lasts after its last use (global only). */
316
+ export const DEFAULT_REPO_APPROVAL_DAYS = 14;
317
+ /** Hard cap: an approval never lasts longer than this many days after it was given, used or not. */
318
+ export const REPO_APPROVAL_CAP_DAYS = 90;
319
+
320
+ export function sanitizeRepoApprovalDays(value: unknown): Sanitized<number> {
321
+ if (value === undefined) return { value: undefined, issues: [] };
322
+ if (typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= REPO_APPROVAL_CAP_DAYS) {
323
+ return { value, issues: [] };
324
+ }
325
+ return {
326
+ value: undefined,
327
+ issues: [{
328
+ path: "routing.repoApprovalDays",
329
+ message: `routing.repoApprovalDays must be an integer from 1 to ${REPO_APPROVAL_CAP_DAYS} (got ${show(value)}); ignored`,
330
+ }],
331
+ };
332
+ }
333
+
246
334
  export function sanitizeRoleAgents(value: unknown): Sanitized<Record<string, RoleAgentCustomisation>> {
247
335
  const issues: RolesIssue[] = [];
248
336
  if (value === undefined) return { value: undefined, issues };
@@ -424,6 +512,10 @@ export function collectRolesIssues(rawRouting: unknown, rawRoleAgents: unknown):
424
512
  ...sanitizeExploration(r.exploration).issues,
425
513
  ...sanitizeRun(r.run).issues,
426
514
  ...sanitizeWorkRoots(r.workRoots).issues,
515
+ ...sanitizeRepoParents(r.repoParents).issues,
516
+ ...sanitizeRepoDepth(r.repoDepth).issues,
517
+ ...sanitizeRepoExclude(r.repoExclude).issues,
518
+ ...sanitizeRepoApprovalDays(r.repoApprovalDays).issues,
427
519
  ...sanitizeRoleAgents(rawRoleAgents).issues,
428
520
  ];
429
521
  }
@@ -163,7 +163,7 @@ const CANONICAL_TIERS: readonly string[] = ["fast", "medium", "heavy"];
163
163
 
164
164
  /** Work-root rule (§2.2, R3/R4) carried by every shipped role prompt. */
165
165
  export const WORK_ROOT_RULE =
166
- "Work root: work only inside this dispatch's work root, named in ENVIRONMENT or by `root=`; without one it is the session directory. Paths anywhere else are denied. If you have `router_run`, pass `cwd` = the work root.";
166
+ "Work root: work only inside this dispatch's work root, named on the router's `Working directory:` line, else in ENVIRONMENT; without either it is the session directory. The router's `Working directory:` line and the work root in this dispatch's ENVIRONMENT win over the working directory in the host's environment block. Paths anywhere else are denied. If you have `router_run`, pass `cwd` = the work root.";
167
167
  /** Return contract carried by every shipped role prompt. */
168
168
  export const RETURN_CONTRACT =
169
169
  "Return: start with `DONE:`, `NEED MORE:` or `ESCALATE:`, then the result with evidence as `file:line`.";