opencode-model-router 2.8.0 → 2.9.1

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 (91) hide show
  1. package/CHANGELOG.md +372 -0
  2. package/README.md +22 -2
  3. package/package.json +5 -1
  4. package/src/commands/output.ts +23 -1
  5. package/src/compat/background.ts +2439 -0
  6. package/src/compat/child-session.ts +6 -0
  7. package/src/compat/turn-state.ts +215 -0
  8. package/src/compat/v2-client.ts +136 -17
  9. package/src/compat/v2-hooks.ts +2656 -114
  10. package/src/compat/v2-observations.ts +328 -0
  11. package/src/executor/capacity.ts +362 -0
  12. package/src/executor/child-guards.ts +40 -0
  13. package/src/executor/command.ts +265 -0
  14. package/src/executor/compile/edges.ts +809 -0
  15. package/src/executor/compile/estimate.ts +158 -0
  16. package/src/executor/compile/footprint.ts +829 -0
  17. package/src/executor/compile/index.ts +1080 -0
  18. package/src/executor/compile/parse.ts +1492 -0
  19. package/src/executor/compile/residue.ts +706 -0
  20. package/src/executor/compile/validate.ts +280 -0
  21. package/src/executor/create.ts +672 -0
  22. package/src/executor/expand.ts +551 -0
  23. package/src/executor/git.ts +1214 -0
  24. package/src/executor/host-preamble.ts +17 -0
  25. package/src/executor/instructions.ts +35 -0
  26. package/src/executor/integrate/bisect.ts +73 -0
  27. package/src/executor/integrate/checks.ts +1086 -0
  28. package/src/executor/integrate/land.ts +177 -0
  29. package/src/executor/integrate/phase-suite.ts +407 -0
  30. package/src/executor/integrate/queue.ts +3083 -0
  31. package/src/executor/integrate/run-resolver.ts +19 -0
  32. package/src/executor/launch.ts +652 -0
  33. package/src/executor/ledger.ts +2208 -0
  34. package/src/executor/observations.ts +212 -0
  35. package/src/executor/paths.ts +159 -0
  36. package/src/executor/platform.ts +39 -0
  37. package/src/executor/process-identity.ts +19 -0
  38. package/src/executor/qa-loop.ts +470 -0
  39. package/src/executor/recovery.ts +403 -0
  40. package/src/executor/runtime.ts +6233 -0
  41. package/src/executor/schedule.ts +246 -0
  42. package/src/executor/slots/env.ts +145 -0
  43. package/src/executor/slots/pool.ts +1564 -0
  44. package/src/executor/slots/provision.ts +853 -0
  45. package/src/executor/tool.ts +534 -0
  46. package/src/executor/types.ts +2064 -0
  47. package/src/executor/unattended.ts +488 -0
  48. package/src/guard/store.ts +3 -1
  49. package/src/index.ts +1498 -288
  50. package/src/router/config.ts +776 -25
  51. package/src/router/git-tools.ts +106 -15
  52. package/src/router/leases.ts +1469 -0
  53. package/src/router/logger.ts +44 -32
  54. package/src/router/protocol.ts +40 -10
  55. package/src/router/role-agents.ts +224 -17
  56. package/src/router/roles-config.ts +10 -1
  57. package/src/router/roles.ts +1 -1
  58. package/src/router/run-tools.ts +56 -4
  59. package/src/router/tool-paths.ts +308 -0
  60. package/src/router/work-roots.ts +86 -0
  61. package/src/routing/advisor/findings.ts +25 -5
  62. package/src/routing/classify/index.ts +7 -1
  63. package/src/routing/classify/rules.ts +11 -0
  64. package/src/routing/commands/stats.ts +2 -2
  65. package/src/routing/outcomes/durations.ts +225 -0
  66. package/src/routing/outcomes/index.ts +59 -2
  67. package/src/routing/outcomes/persist.ts +409 -0
  68. package/src/routing/outcomes/stats.ts +170 -11
  69. package/src/routing/outcomes/timings.ts +836 -0
  70. package/src/routing/outcomes/types.ts +98 -0
  71. package/src/routing/roles/approvals.ts +86 -5
  72. package/src/routing/roles/binding.ts +99 -9
  73. package/src/routing/roles/orphans.ts +68 -0
  74. package/src/routing/roles/policy.ts +21 -3
  75. package/src/routing/roles/work-root.ts +3 -1
  76. package/src/routing/wire/dispatch.ts +86 -12
  77. package/src/routing/wire/hint.ts +56 -8
  78. package/src/v2.ts +94 -49
  79. package/src/verify/branch.ts +8 -2
  80. package/src/verify/canonical-path.ts +35 -0
  81. package/src/verify/deterministic.ts +38 -9
  82. package/src/verify/dispatch.ts +64 -28
  83. package/src/verify/exec.ts +52 -9
  84. package/src/verify/pending.ts +1691 -10
  85. package/src/verify/perimeter.ts +12 -6
  86. package/src/verify/plan-task.ts +729 -0
  87. package/src/verify/reference.ts +216 -3
  88. package/src/verify/tree.ts +30 -13
  89. package/src/verify/types.ts +9 -2
  90. package/src/verify/wiring.ts +290 -31
  91. package/tiers.json +5 -5
@@ -43,6 +43,8 @@
43
43
 
44
44
  export interface PluginLogger {
45
45
  warn(message: string, extra?: Record<string, unknown>): void;
46
+ /** An informational entry (level `info`), posted like `warn`; optional so bare logger stubs stay valid. */
47
+ info?(message: string, extra?: Record<string, unknown>): void;
46
48
  /**
47
49
  * Await every post still in flight, so a shutting-down process does not drop
48
50
  * warnings it already decided to emit. Never rejects: a failing flush must
@@ -105,6 +107,9 @@ export function createPluginLogger(client?: unknown): PluginLogger {
105
107
  warn(message) {
106
108
  console.warn(`${CONSOLE_PREFIX} ${message}`);
107
109
  },
110
+ info(message) {
111
+ console.info(`${CONSOLE_PREFIX} ${message}`);
112
+ },
108
113
  // console.warn is synchronous, so there is never anything to wait for.
109
114
  flush: () => Promise.resolve(),
110
115
  };
@@ -114,40 +119,47 @@ export function createPluginLogger(client?: unknown): PluginLogger {
114
119
  // stays bounded on a long-lived server rather than growing for its lifetime.
115
120
  const inFlight = new Set<Promise<void>>();
116
121
 
122
+ const post = (level: "warn" | "info", message: string, extra?: Record<string, unknown>): void => {
123
+ const toConsole = () => (level === "warn" ? console.warn : console.info)(`${CONSOLE_PREFIX} ${message}`);
124
+ let result: unknown;
125
+ try {
126
+ // Bound to `app` on purpose — see (1) in the module comment. Calling
127
+ // the detached reference would throw on every real client.
128
+ result = log.call(app, {
129
+ body: {
130
+ service: LOG_SERVICE,
131
+ level,
132
+ message,
133
+ ...(extra ? { extra } : {}),
134
+ },
135
+ });
136
+ } catch {
137
+ // A synchronous throw means the transport is unusable; say it somewhere.
138
+ toConsole();
139
+ return;
140
+ }
141
+ // Fire-and-forget: never await, but never leave a rejection unhandled
142
+ // either, and do not lose the diagnostic when the post fails — whether it
143
+ // fails by rejecting or by resolving with an error. See (2) above.
144
+ const settled: Promise<void> = Promise.resolve(result)
145
+ .then((value) => {
146
+ if (isErrorResult(value)) toConsole();
147
+ })
148
+ .catch(toConsole);
149
+ // Tracked so `flush` can wait for it. `settled` already absorbs its own
150
+ // failures, so nothing here can reject. See (3) above.
151
+ inFlight.add(settled);
152
+ void settled.finally(() => {
153
+ inFlight.delete(settled);
154
+ });
155
+ };
156
+
117
157
  return {
118
158
  warn(message, extra) {
119
- const toConsole = () => console.warn(`${CONSOLE_PREFIX} ${message}`);
120
- let result: unknown;
121
- try {
122
- // Bound to `app` on purpose — see (1) in the module comment. Calling
123
- // the detached reference would throw on every real client.
124
- result = log.call(app, {
125
- body: {
126
- service: LOG_SERVICE,
127
- level: "warn",
128
- message,
129
- ...(extra ? { extra } : {}),
130
- },
131
- });
132
- } catch {
133
- // A synchronous throw means the transport is unusable; say it somewhere.
134
- toConsole();
135
- return;
136
- }
137
- // Fire-and-forget: never await, but never leave a rejection unhandled
138
- // either, and do not lose the diagnostic when the post fails — whether it
139
- // fails by rejecting or by resolving with an error. See (2) above.
140
- const settled: Promise<void> = Promise.resolve(result)
141
- .then((value) => {
142
- if (isErrorResult(value)) toConsole();
143
- })
144
- .catch(toConsole);
145
- // Tracked so `flush` can wait for it. `settled` already absorbs its own
146
- // failures, so nothing here can reject. See (3) above.
147
- inFlight.add(settled);
148
- void settled.finally(() => {
149
- inFlight.delete(settled);
150
- });
159
+ post("warn", message, extra);
160
+ },
161
+ info(message, extra) {
162
+ post("info", message, extra);
151
163
  },
152
164
  async flush() {
153
165
  await Promise.allSettled([...inFlight]);
@@ -1,3 +1,4 @@
1
+ import { resolveRouting } from "./config";
1
2
  import type { RouterConfig, Preset, ModeConfig } from "./config";
2
3
  import type { RoleKind, RoleSpec } from "./roles";
3
4
  import { ROLE_MENU_INTENT, ROUTER_BUDGET_NOTE_PREFIX } from "./prompts";
@@ -54,15 +55,18 @@ export function buildRolesProtocol(cfg: RouterConfig, roles: ReadonlyMap<string,
54
55
  const taxonomy = generateRolesTaxonomy(new Map(enabled.map((spec) => [spec.agent, spec] as const)));
55
56
  const researcher = agentOf("research");
56
57
  const editor = agentOf("implement") ?? agentOf("general");
57
- const runner = agentOf("run");
58
58
  const compose = researcher !== undefined && editor !== undefined
59
59
  ? ` Compose: ${researcher} first, then paste its findings into the ${editor} dispatch.`
60
60
  : "";
61
+ const cost = editor !== undefined
62
+ ? `Cost: edit+run without a router-gated check gets the top tier. Slice non-design work into \`class=implement needs=edit d=deterministic\` ${editor} dispatches with \`check: testsPass\`; if a slice must run commands, add \`VERIFY:required\`.`
63
+ : "";
61
64
  // QA-P22-1-8: a tier agent is the exception for a command `router_run` refuses, never the default.
62
65
  // QA-P22-2-1: keyed on the router_run grant of ANY enabled role (the implementer holds it too), not on a `run` role.
63
66
  const rawShell = enabled.some((spec) => spec.authority.allow.includes("router_run"))
64
67
  ? `Only when \`router_run\` refuses a command that is not on its allowlist, ask the user or dispatch a tier agent explicitly.`
65
68
  : `For a command, ask the user or dispatch a tier agent explicitly.`;
69
+ const background = buildBackgroundDispatchesBlock(cfg);
66
70
  // Cross-repo (P1.7): one sentence, only when `routing.repoParents` is configured; otherwise the text is unchanged.
67
71
  const crossRepo = (cfg.routing?.repoParents?.length ?? 0) > 0
68
72
  ? ` Cross-repo: name another repository with repo=<name> (and branch=<ref> when it has several worktrees) instead of root=; each dispatch edits one repository, and a role may read the others below routing.repoParents. A check may run in another repository of the read set with cwd= and must then use scope=full, e.g. \`check: testsPass cwd="<repo>" scope=full\`.`
@@ -70,26 +74,28 @@ export function buildRolesProtocol(cfg: RouterConfig, roles: ReadonlyMap<string,
70
74
  return [
71
75
  ROLES_PROTOCOL_HEADING,
72
76
  ``,
73
- `You are the orchestrator: delegate execution to role agents with \`subagent(agent="<role>", prompt="...")\` and answer the user yourself. Reading, searching and running commands are execution; you may make about 2 direct read-only calls per turn to settle a question. Run independent dispatches in parallel, in one message.`,
77
+ `Delegate execution via \`subagent(agent="<role>", prompt="...")\`; answer the user. Reads/searches/commands are execution; about 2 direct read-only calls/turn may settle a question. Parallelize independent dispatches in one message.`,
74
78
  ``,
75
- `Roles (pick by intent; the router narrows each grant to the task):`,
79
+ `Roles by intent (grants narrowed to task):`,
76
80
  ...menu,
77
81
  ...(taxonomy ? [``, taxonomy] : []),
78
82
  ``,
79
- `The router picks each dispatch's model: never set \`model\` or pick a tier; name the role.`,
83
+ `Router picks the model: never set \`model\` or pick a tier; name the role.`,
80
84
  ``,
81
85
  // QA-P22-1-1: `tier`/`pin` are not in the template; only a plan's `[tier:X]` tag is transcribed.
82
- `Route line: when present it must be the FIRST line of the prompt (the router removes it; a malformed one is refused for a role): \`[route class=<c> risk=<r> scope=<s> needs=<n,..> d=<d> budget=<n> root=<path>]\`, every key optional. class=search|recon|mechanical|implement|debug|design|review|other; risk=low|medium|high; scope=single|multi|repo; needs=shell|web|edit|network|external_dir (\`edit\` unlocks editing, \`shell\` router_run, where the role allows); d=deterministic|grader|none (counts only when the prompt's \`[acceptance]\` block backs it); budget=tool calls (up to twice the role's); root=the absolute work root. Only when the plan step carries \`[tier:X]\`, add \`tier=X pin\`; never otherwise.`,
86
+ `Optional route: FIRST prompt line (router removes it; a malformed one is refused for a role): \`[route class=<c> risk=<r> scope=<s> needs=<n,..> d=<d> budget=<n> root=<path>]\`; keys optional. class=search|recon|mechanical|implement|debug|design|review|other; risk=low|medium|high; scope=single|multi|repo; needs=shell|web|edit|network|external_dir (\`edit\`=editing, \`shell\`=router_run, role permitting); d=deterministic|grader|none (counts only when the prompt's \`[acceptance]\` block backs it); budget=tool calls (max 2x role budget); root=absolute work root. Only when the plan step carries \`[tier:X]\`, add \`tier=X pin\`; never otherwise.`,
83
87
  ``,
84
- `Work root: a role works only in the session directory or one git worktree of this repo; for a worktree put \`root=<absolute path>\` on the route line (quote a path with spaces) and in ENVIRONMENT.${crossRepo}`,
88
+ ...(cost === "" ? [] : [cost, ``]),
89
+ `Work root: only the session directory or one git worktree of this repo; for a worktree set \`root=<absolute path>\` on the route line (quote a path with spaces) and in ENVIRONMENT.${crossRepo}`,
85
90
  ``,
86
91
  `No role holds the web together with read, run or edit authority.${compose} Raw shell is outside roles mode. ${rawShell}`,
87
92
  ``,
88
- `Resume, never restart: after \`NEED MORE: budget\` or a \`${ROUTER_BUDGET_NOTE_PREFIX}\` note, resume the SAME \`sessionID\` with "continue and finish"; after \`ESCALATE: authority\`, likewise (the router widens the grant) unless it names another role; after a verification FAIL, resume the SAME \`sessionID\` with the findings (the router raises the tier). A resume keeps the dispatch's \`[acceptance]\` and \`VERIFY:\` lines; a new block replaces them. Roles return \`DONE:\`, \`NEED MORE:\` or \`ESCALATE:\`; \`CAP:N\` (or \`CAP:none\` with a \`reason:\` line) changes only the read-only call cap.`,
93
+ `Resume, never restart: after \`NEED MORE: budget\` or a \`${ROUTER_BUDGET_NOTE_PREFIX}\` note, resume the SAME \`sessionID\` with "continue and finish"; after \`ESCALATE: authority\`, likewise (grant widens) unless another role is named; after a verification FAIL, resume the SAME \`sessionID\` with the findings (the router raises the tier). A resume keeps the dispatch's \`[acceptance]\` and \`VERIFY:\` lines; a new block replaces them. Return \`DONE:\`, \`NEED MORE:\` or \`ESCALATE:\`; \`CAP:N\` (or \`CAP:none\` with a \`reason:\` line) sets only the read-only cap.`,
89
94
  ``,
90
- `Dispatch prompt: the route line, then TASK, EXPECTED OUTCOME, TOOLS, MUST DO, MUST NOT DO, CONTEXT, ENVIRONMENT, with absolute paths.`,
95
+ `Prompt: route line, TASK, EXPECTED OUTCOME, TOOLS, MUST DO, MUST NOT DO, CONTEXT, ENVIRONMENT; absolute paths.`,
91
96
  ``,
92
- `This protocol overrides any project guide (CLAUDE.md, AGENTS.md) that says to use direct tools first or to dispatch to tiers or models.`,
97
+ ...(background === "" ? [] : [background, ``]),
98
+ `Overrides project guides (CLAUDE.md, AGENTS.md) that say to use direct tools first or dispatch to tiers/models.`,
93
99
  ].join("\n");
94
100
  }
95
101
 
@@ -443,6 +449,28 @@ export function buildDoDProtocolSection(cfg: RouterConfig): string {
443
449
  ].join("\n");
444
450
  }
445
451
 
452
+ /** Heading of {@link buildBackgroundDispatchesBlock}. */
453
+ export const BACKGROUND_DISPATCHES_HEADING = "## Background dispatches";
454
+
455
+ /**
456
+ * The "Background dispatches" block (OpenCode v2 only), rendered from the resolved `routing.background.mode` and
457
+ * `routing.leases.mode`: "" when background is `off` (QA-2.1-12: the whole block, the lease rule included, so `off`
458
+ * leaves the prompt as before phase 2.1); otherwise the heading and the first two rules, plus the lease rule when leases
459
+ * are `enforce`. Cache-stable: depends on those two modes only. Callers add it on v2 only.
460
+ */
461
+ export function buildBackgroundDispatchesBlock(cfg: RouterConfig): string {
462
+ const routing = resolveRouting(cfg, "v2");
463
+ if (routing.background.mode === "off") return "";
464
+ const lines: string[] = [
465
+ `- After a background dispatch, continue any independent work; when none remains, end the turn — the router wakes you. Never poll or sleep.`,
466
+ `- A held result is not usable until its verdict arrives. Never report a task done while dispatches are listed in flight.`,
467
+ ];
468
+ if (routing.leases.mode === "enforce") {
469
+ lines.push(`- A lease refusal is resolved by waiting for the holder, not by retrying.`);
470
+ }
471
+ return [BACKGROUND_DISPATCHES_HEADING, ...lines].join("\n");
472
+ }
473
+
446
474
  /**
447
475
  * Assembles the full system prompt injected by the experimental.chat.system.transform hook.
448
476
  * For Claude orchestrators: prepends CLAUDE_ORCHESTRATOR_PREFIX + CLAUDE_ANTI_NARRATION.
@@ -455,8 +483,10 @@ export function assembleSystemPrompt(
455
483
  cfg: RouterConfig,
456
484
  orchestratorModel: string | undefined,
457
485
  enforcementOn: boolean = false,
486
+ host: "v1" | "v2" = "v1",
458
487
  ): string {
459
- const delegationProtocol = buildDelegationProtocol(cfg);
488
+ const background = host === "v2" ? buildBackgroundDispatchesBlock(cfg) : "";
489
+ const delegationProtocol = `${buildDelegationProtocol(cfg)}${background === "" ? "" : `\n\n${background}`}`;
460
490
  const dodSection = enforcementOn ? `\n\n---\n\n${buildDoDProtocolSection(cfg)}` : "";
461
491
  if (!isClaudeModel(orchestratorModel)) {
462
492
  return `${delegationProtocol}${dodSection}`;
@@ -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,16 +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
28
  import { CONTEXT7_DOC_TOOLS, permissionMatches, type PermissionMap } from "./read-only";
24
29
  import { isApprovalValid, type RepoApproval } from "../routing/roles/approvals";
25
30
  import { ACTION_CLASS, HOST_NATIVE_ROLE_NAMES, resolveRoleTable, SHIPPED_ROLE_SPECS, type AuthorityAction, type RoleSpec, type RoleTable } from "./roles";
26
- import { workRootProblem } from "./roles-config";
31
+ import { workRootGlobIndex, workRootProblem } from "./roles-config";
32
+ import { locationOutsideWorkRoots } from "./work-roots";
27
33
 
28
34
  /**
29
35
  * Steps above the largest guard budget a role dispatch can reach. The guard's `NEED MORE: budget`
@@ -84,20 +90,28 @@ export function roleHasLocalActions(spec: Pick<RoleSpec, "authority">): boolean
84
90
  /**
85
91
  * A role's max permission policy (v2 action names, ordered, last match wins): `* deny` first,
86
92
  * then an allow per {@link roleHostActions}, then `external_directory` allows for `externalDirectory`
87
- * (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;
88
95
  * the `read` rules are rebuilt by the plugin-agent policy with the sensitive-read asks after the
89
96
  * grant (a role without `read` gets `read: { "*": "deny" }`).
90
97
  */
91
98
  export function roleMaxPermission(
92
99
  spec: Pick<RoleSpec, "authority">,
93
- opts: { context7: boolean; externalDirectory: readonly string[] },
100
+ opts: { context7: boolean; externalDirectory: readonly string[]; externalDirectoryDeny?: readonly string[] },
94
101
  ): PermissionMap {
95
102
  const own: PermissionMap = { "*": "deny" };
96
103
  for (const name of roleHostActions(spec, opts)) own[name] = "allow";
97
104
  const patterns = roleHasLocalActions(spec)
98
105
  ? [...new Set(opts.externalDirectory)].filter((pattern) => pattern !== "" && !/^[*?]+$/.test(pattern))
99
106
  : [];
100
- 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
+ }
101
115
  for (const action of ROLE_DENIED_ACTIONS) own[action] = "deny";
102
116
  return pluginAgentPolicy({ permission: own }, { context7: opts.context7, host: "v2" }).permission;
103
117
  }
@@ -126,7 +140,7 @@ function validModel(model: unknown): model is string {
126
140
  export function buildRoleAgentDefinition(
127
141
  spec: RoleSpec,
128
142
  floor: Pick<TierConfig, "model" | "variant">,
129
- opts: { context7: boolean; externalDirectory: readonly string[] },
143
+ opts: { context7: boolean; externalDirectory: readonly string[]; externalDirectoryDeny?: readonly string[] },
130
144
  ): Record<string, unknown> {
131
145
  if (!validModel(floor.model)) throw new Error(`role ${spec.agent}: floor tier ${spec.tierRange.floor} has no provider/model reference`);
132
146
  const steps = roleAgentSteps(spec);
@@ -173,7 +187,8 @@ const WORKTREE_LIST_TIMEOUT_MS = 10_000;
173
187
  */
174
188
  export async function listWorktrees(directory: string): Promise<string[]> {
175
189
  const started = performance.now();
176
- 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));
177
192
  const trusted = await inheritedSafeDirectoryArgs(executable, WORKTREE_LIST_TIMEOUT_MS);
178
193
  const result = await spawnBounded(executable, [...hardeningArgs(), ...trusted, "worktree", "list", "--porcelain"], directory, {
179
194
  env: gitEnvironment(), timeoutMs: Math.max(1, WORKTREE_LIST_TIMEOUT_MS - (performance.now() - started)), maxBytes: 1024 * 1024,
@@ -228,6 +243,87 @@ export function approvedRootPattern(path: string, realpath: Realpath = nativeRea
228
243
  return after === undefined ? { pattern: join(canonical, "*") } : { problem: `canonical form ${canonical} ${after}` };
229
244
  }
230
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
+
231
327
  /**
232
328
  * The `external_directory` allow pattern of one `routing.workRoots` entry (P-11): the static
233
329
  * directory before the first wildcard in its canonical long form, then the glob tail verbatim
@@ -238,7 +334,7 @@ export function approvedRootPattern(path: string, realpath: Realpath = nativeRea
238
334
  export function workRootPattern(entry: string, realpath: Realpath = nativeRealpath): { pattern?: string; problem?: string } {
239
335
  const problem = workRootProblem(entry);
240
336
  if (problem !== undefined) return { problem };
241
- const globAt = entry.search(/[*?[\]{}]/);
337
+ const globAt = workRootGlobIndex(entry);
242
338
  if (globAt === -1) {
243
339
  const pattern = worktreeRootPattern(entry, realpath);
244
340
  return pattern === undefined ? { problem: "does not resolve to a directory in canonical long form" } : { pattern };
@@ -374,18 +470,25 @@ export interface RoleRegistration {
374
470
  readonly replaced: readonly string[];
375
471
  /** `external_directory` allow patterns written into local roles. */
376
472
  readonly externalDirectory: readonly string[];
473
+ /** `external_directory` deny patterns written after every allow. */
474
+ readonly externalDirectoryDenied: readonly string[];
377
475
  /** True when registration failed and no role agent was registered. */
378
476
  readonly failed: boolean;
379
477
  }
380
478
 
381
479
  const NONE: RoleRegistration = Object.freeze({
382
- 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,
383
482
  });
384
483
 
385
484
  export interface RoleRegistrationOptions {
386
485
  /** The context7 MCP server is configured (its documentation tools become direct tools). */
387
486
  context7: boolean;
388
- /** 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
+ */
389
492
  directory: string;
390
493
  /** The host's own agents at setup (name → seed definition); a removed #81 entry falls back to it. */
391
494
  seed: Readonly<Record<string, Record<string, unknown>>>;
@@ -400,6 +503,16 @@ export interface RoleRegistrationOptions {
400
503
  listWorktrees?: (directory: string) => Promise<string[]>;
401
504
  resolveTable?: (cfg: RouterConfig, host: "v1" | "v2", opts: { context7?: boolean }) => RoleTable;
402
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;
403
516
  /** Clock in epoch ms for the approval expiry; default `Date.now`. */
404
517
  now?: () => number;
405
518
  }
@@ -439,14 +552,22 @@ export async function registerRoleAgents(
439
552
  let built: Map<string, Record<string, unknown>>;
440
553
  let table: RoleTable;
441
554
  let externalDirectory: string[] = [];
555
+ let externalDirectoryDenied: string[] = [];
442
556
  try {
443
557
  table = (opts.resolveTable ?? resolveRoleTable)(cfg, "v2", { context7: opts.context7 });
444
558
  const tiers = resolveActiveTiers(cfg);
559
+ const hasLocalActions = [...table.roles.values()].some(roleHasLocalActions);
445
560
  let worktrees: string[] = [];
446
- 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) {
447
567
  try {
448
568
  worktrees = await (opts.listWorktrees ?? listWorktrees)(opts.directory);
449
569
  } catch (error) {
570
+ worktreeListingProblem = errorText(error);
450
571
  opts.warn("roles:worktrees", `${PREFIX}the repository's worktrees could not be listed (${errorText(error)}); role agents get no worktree external_directory rule`);
451
572
  }
452
573
  }
@@ -454,12 +575,97 @@ export async function registerRoleAgents(
454
575
  const found = externalDirectoryPatterns(worktrees, routing.workRoots, opts.realpath ?? nativeRealpath, routing.repoParents, approved.paths);
455
576
  for (const problem of [...approved.problems, ...found.problems]) opts.warn(`roles:external:${problem}`, `${PREFIX}${problem}`);
456
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
+ }
457
661
  built = new Map();
458
662
  for (const [name, spec] of table.roles) {
459
663
  const floor = tiers[spec.tierRange.floor];
460
664
  if (floor === undefined) throw new Error(`role ${name}: floor tier ${spec.tierRange.floor} is not in the active preset`);
461
- built.set(name, buildRoleAgentDefinition(spec, floor, { context7: opts.context7, externalDirectory }));
665
+ built.set(name, buildRoleAgentDefinition(spec, floor, { context7: opts.context7, externalDirectory, externalDirectoryDeny: externalDirectoryDenied }));
462
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);
463
669
  } catch (error) {
464
670
  return fail(agents, opts, error);
465
671
  }
@@ -483,6 +689,7 @@ export async function registerRoleAgents(
483
689
  removed: Object.freeze(removed),
484
690
  replaced: Object.freeze([...table.replacedRoles]),
485
691
  externalDirectory: Object.freeze([...externalDirectory]),
692
+ externalDirectoryDenied: Object.freeze([...externalDirectoryDenied]),
486
693
  failed: false,
487
694
  });
488
695
  }
@@ -199,9 +199,18 @@ export function sanitizeRun(value: unknown): Sanitized<Partial<RunConfig>> {
199
199
  * canonical long form: a segment like `PROGRA~1` is an 8.3 short name that can alias another
200
200
  * directory (R6/P-11).
201
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
+
202
211
  export function workRootProblem(entry: string): string | undefined {
203
212
  if (entry === "") return "is empty";
204
- const globAt = entry.search(/[*?[\]{}]/);
213
+ const globAt = workRootGlobIndex(entry);
205
214
  const prefix = globAt === -1 ? entry : entry.slice(0, globAt);
206
215
  const normalised = prefix.replace(/\\/g, "/");
207
216
  let rest: string;
@@ -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 on the router's `Working directory:` line, else in ENVIRONMENT; without either 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`.";