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
@@ -59,11 +59,12 @@
59
59
  * absolute, drive, UNC or URL path or a `..` segment, but a symlink or junction inside
60
60
  * the work root, and the contents of an `@response` file, are repository content.
61
61
  */
62
- import { realpathSync, statSync } from "node:fs";
62
+ import { lstatSync, realpathSync, statSync } from "node:fs";
63
63
  import { createRequire } from "node:module";
64
64
  import { homedir } from "node:os";
65
65
  import { posix, win32 } from "node:path";
66
66
  import { tool } from "@opencode-ai/plugin";
67
+ import { applySlotEnv, slotEnvFor, type SlotBin, type SlotEnv } from "../executor/slots/env";
67
68
  import type { RunConfig } from "./roles";
68
69
  import {
69
70
  checkWorkRootAnswer, dropPartialCredential, envLookup, errorMessage, firstOutside, isFullPath, readBoundedRegularFile as readBounded,
@@ -175,7 +176,11 @@ export interface RunPlan {
175
176
  * any configuration, so it was removed rather than kept as a dead knob: credential-like
176
177
  * variables are always dropped.
177
178
  */
178
- export interface RunHost { platform: NodeJS.Platform; env: NodeJS.ProcessEnv; nodeExecPath?: string }
179
+ export interface RunHost {
180
+ platform: NodeJS.Platform; env: NodeJS.ProcessEnv; nodeExecPath?: string;
181
+ /** The executor-slot environment for a work root (default: the slot registry); null outside a slot. */
182
+ slotEnv?: (cwd: string, p: NodeJS.Platform) => SlotEnv | null;
183
+ }
179
184
 
180
185
  class RunRefused extends Error {}
181
186
  const refuse = (message: string) => new RunRefused(message);
@@ -423,6 +428,52 @@ function stemOf(path: string): string {
423
428
  return win32.basename(path).replace(/\.(exe|com|cmd|bat|ps1|js)$/i, "").toLowerCase();
424
429
  }
425
430
 
431
+ /** The file is one of the recorded executables: same path (folded on win32), size and mtime as at provisioning (QA-2.4-27). */
432
+ function matchesSnapshot(found: string, bins: readonly SlotBin[], platform: NodeJS.Platform): boolean {
433
+ const key = (p: string): string => (platform === "win32" ? p.replace(/\//g, "\\").toLowerCase() : p);
434
+ const wanted = key(pathApi(platform).normalize(found));
435
+ const recorded = bins.find((bin) => key(pathApi(platform).normalize(bin.path)) === wanted);
436
+ if (recorded === undefined) return false;
437
+ try {
438
+ const st = lstatSync(found);
439
+ return st.size === recorded.size && st.mtimeMs === recorded.mtimeMs;
440
+ } catch { return false; }
441
+ }
442
+
443
+ /**
444
+ * The one narrow exception to "no executable inside the work root" (QA-2.4-6): when the work root is an
445
+ * executor slot, a BARE name is looked up first in the slot's own tool directories (`.venv\Scripts` / `.venv/bin`,
446
+ * `node_modules/.bin`), so `pytest` or `vitest` runs the slot's install. The file must match the snapshot (path, size,
447
+ * mtime) the pool recorded right after provisioning (`SlotEnv.bins`): anything an agent wrote there later falls back to
448
+ * PATH. It must be a regular file whose real path is inside the slot root; a virtualenv interpreter may instead be a
449
+ * link to one outside every guarded directory. The same name rules apply as everywhere (no shells, node or npm,
450
+ * `.exe`/`.com` only on win32). On Windows the Node tools in `node_modules\.bin` are `.cmd`/`.ps1` shims, which are not
451
+ * executables here, so only Python `.exe` files (the virtualenv's `Scripts`) are taken from the slot on that platform;
452
+ * on POSIX the `.bin` entries are links to the package scripts and are taken. Absolute paths, names not found there, and every work root that is not
453
+ * a slot fall through unchanged. The integration checks' pytest interpreter uses the same lookup (QA N-A).
454
+ */
455
+ export function slotToolExecutable(program: string, slotEnv: SlotEnv | null, host: RunHost, guards: () => readonly string[]): string | undefined {
456
+ if (slotEnv === null || !/^[A-Za-z0-9_][A-Za-z0-9_.+-]{0,99}$/.test(program)) return undefined;
457
+ const win = host.platform === "win32";
458
+ if (win && /\.(cmd|bat|ps1)$/i.test(program)) return undefined;
459
+ const P = pathApi(host.platform);
460
+ const name = win && !/\.(exe|com)$/i.test(program) ? `${program}.exe` : program;
461
+ for (const dir of slotEnv.prependPath) {
462
+ const file = foundFile(P.join(dir, name), host.platform);
463
+ if (file === undefined) continue;
464
+ const inSlot = insideAny(file.real, [slotEnv.root]);
465
+ const linkedOut = !inSlot && P.basename(dir).toLowerCase() !== ".bin" && !insideAny(file.real, guards());
466
+ if (!inSlot && !linkedOut) continue;
467
+ if (!insideAny(file.found, [slotEnv.root])) continue;
468
+ if (!matchesSnapshot(file.found, slotEnv.bins, host.platform)) continue;
469
+ refuseProgramStem(stemOf(program), program);
470
+ refuseProgramStem(stemOf(file.real), program);
471
+ if (win && (!/\.(exe|com)$/i.test(file.found) || !/\.(exe|com)$/i.test(file.real))) continue;
472
+ return file.found;
473
+ }
474
+ return undefined;
475
+ }
476
+
426
477
  /**
427
478
  * The node that runs npm-cli.js (verify/runner.ts F.1 rules): the explicit seam; else
428
479
  * process.execPath when the runtime really is node (opencode hosts plugins in Bun);
@@ -737,6 +788,7 @@ export function planRun(input: RunInput, root: string, config: RunConfig, host:
737
788
  let shell: string | undefined;
738
789
  let guards: string[] | undefined;
739
790
  const guarded = () => (guards ??= workRootGuards(root));
791
+ const slotEnv = (host.slotEnv ?? slotEnvFor)(root, host.platform);
740
792
  if (command !== undefined) {
741
793
  if (!Array.isArray(command.argv) || command.argv.length === 0 || command.argv.some(part => typeof part !== "string" || part === "")) {
742
794
  throw refuse(`routing.run.commands.${name} has no valid argv`);
@@ -765,7 +817,7 @@ export function planRun(input: RunInput, root: string, config: RunConfig, host:
765
817
  shell = launch.shell;
766
818
  argv = [launch.cli, ...launch.flags, ...fixed, ...args];
767
819
  } else {
768
- executable = resolveCommandExecutable(program!, host, guarded());
820
+ executable = slotToolExecutable(program!, slotEnv, host, guarded) ?? resolveCommandExecutable(program!, host, guarded());
769
821
  argv = [...fixed, ...args];
770
822
  }
771
823
  } else if (scriptAllowed(config.scripts ?? [], name)) {
@@ -786,7 +838,7 @@ export function planRun(input: RunInput, root: string, config: RunConfig, host:
786
838
  }
787
839
  return {
788
840
  kind: command !== undefined ? "command" : "script", name, executable, argv, cwd: root,
789
- env: runEnvironment(host.env, host.platform, shell, { guards: guarded() }), timeoutMs,
841
+ env: applySlotEnv(runEnvironment(host.env, host.platform, shell, { guards: guarded() }), slotEnv, host.platform), timeoutMs,
790
842
  };
791
843
  }
792
844
 
@@ -0,0 +1,308 @@
1
+ /**
2
+ * Phase 1.3: what a host tool call touches. A pure extractor (imports only `node:path`, no
3
+ * filesystem): the file lease registry (leases.ts) and its wiring ask `toolTargets` which files a
4
+ * call reads or writes, which roots it searches, and where it runs.
5
+ *
6
+ * Paths are resolved lexically (`path.resolve`) against the session directory; canonicalization
7
+ * (symlinks, junctions, case) is the registry's job. Never throws.
8
+ */
9
+ import { isAbsolute, resolve } from "node:path";
10
+
11
+ export type Access = "read" | "write" | "search" | "run" | "none";
12
+
13
+ export interface ToolTargets {
14
+ access: Access;
15
+ /** Read/write targets: absolute, resolved lexically against cwd, deduped, first-seen order. */
16
+ paths: string[];
17
+ /** Search roots (search), the run cwd (run), the shell workdir (informational). */
18
+ roots: string[];
19
+ /** Tools whose effects cannot be extracted from the arguments. */
20
+ uncovered?: "shell" | "execute";
21
+ /**
22
+ * A `router_git_*` call whose paths are relative to the repository top level but the caller gave no absolute
23
+ * `gitRoot`: `access` stays as classified while `paths` and `roots` are empty, so the call has no concrete target
24
+ * and the caller treats it as an unknown target.
25
+ */
26
+ gitRootRequired?: true;
27
+ }
28
+
29
+ /** Optional context for `toolTargets`. */
30
+ export interface ToolTargetsOptions {
31
+ /** Absolute repository top level: the base of `router_git_*` paths (git-tools.ts takes them relative to it). */
32
+ gitRoot?: string;
33
+ }
34
+
35
+ /** The tools that mutate the workspace; mirrors `WRITE_TOOLS` in src/verify/dispatch.ts (pinned by a test). */
36
+ export const WRITE_CLASS: ReadonlySet<string> = new Set(["write", "edit", "multiedit", "patch", "apply_patch"]);
37
+
38
+ /** The apply_patch header lines that name a file; verbatim from the dispatch.ts change-set parser. */
39
+ const PATCH_HEADER = /^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/gm;
40
+
41
+ /**
42
+ * Path argument keys: the ones `extractChangedFile` (src/verify/dispatch.ts) reads plus the host's `file_path`.
43
+ * Every non-empty string among them is a target (the host may honour any of them, so first-wins is unsafe).
44
+ */
45
+ const PATH_KEYS = ["filePath", "path", "file", "file_path"] as const;
46
+
47
+ /** The path arguments the v2 host reads from a `patch` / `apply_patch` call besides its headers. */
48
+ const HOST_PATCH_PATH_KEYS = ["filePath", "path", "file_path"] as const;
49
+
50
+ /** The apply_patch argument keys the v2 host reads, in order; the first string wins (even when empty). */
51
+ const PATCH_KEYS = ["patchText", "patch_text", "patch", "input"] as const;
52
+
53
+ /** The header prefixes of the v2 host's patch format (`patchPaths` in src/compat/v2-hooks.ts). */
54
+ const HOST_PATCH_HEADERS = ["*** Add File:", "*** Update File:", "*** Delete File:", "*** Move to:"] as const;
55
+
56
+ function record(value: unknown): Record<string, unknown> {
57
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
58
+ }
59
+
60
+ /** The paths named by an apply_patch call's headers (Add, Update, Delete, Move to), trimmed, in order of appearance. */
61
+ export function applyPatchHeaderPaths(args: unknown): string[] {
62
+ const a = args && typeof args === "object" ? args as Record<string, unknown> : {};
63
+ const patch = typeof a.patchText === "string" ? a.patchText : typeof a.patch === "string" ? a.patch : "";
64
+ return [...patch.matchAll(PATCH_HEADER)].map(m => m[1].trim());
65
+ }
66
+
67
+ /**
68
+ * The paths of a patch as the v2 host parses it (same semantics as `patchPaths` in src/compat/v2-hooks.ts, which this
69
+ * module may not import): header lines may have leading blanks. Undefined when a header names no path or no header is
70
+ * found, i.e. the patch is unreadable and its targets unknown.
71
+ */
72
+ function hostPatchPaths(a: Record<string, unknown>): string[] | undefined {
73
+ const text = PATCH_KEYS.map(key => a[key]).find(value => typeof value === "string");
74
+ if (typeof text !== "string") return undefined;
75
+ const paths: string[] = [];
76
+ for (const raw of text.split(/\r?\n/)) {
77
+ const line = raw.trimStart();
78
+ const header = HOST_PATCH_HEADERS.find(prefix => line.startsWith(prefix));
79
+ if (header === undefined) continue;
80
+ const path = line.slice(header.length).trim();
81
+ if (path === "") return undefined;
82
+ paths.push(path);
83
+ }
84
+ return paths.length > 0 ? paths : undefined;
85
+ }
86
+
87
+ /** win32 spellings `path.resolve` would rewrite wrongly: the device prefixes `\\?\`, `\\.\`, `\??\`. */
88
+ const WIN_DEVICE = /^(?:[\\/]{2}[.?]|[\\/]\?\?)[\\/]/;
89
+ /** A win32 path rooted without a drive (`\x`): its drive is the process's, not the session's. */
90
+ const WIN_ROOTED_NO_DRIVE = /^[\\/](?![\\/])/;
91
+
92
+ /**
93
+ * `p` resolved against `base`; undefined when it would stay relative (no absolute base, relative `p`). On win32 a
94
+ * device-prefixed path (`\\?\C:\x`, `\??\C:\x`) and a path rooted without a drive (`\x`) are returned unchanged:
95
+ * `path.resolve` would turn them into `C:\??\C:\x` and `<baseDrive>:\x`, defeating the lease registry, whose `keyOf`
96
+ * understands the first and fails closed on the second.
97
+ */
98
+ function absolute(p: string, base: string): string | undefined {
99
+ if (process.platform === "win32" && (WIN_DEVICE.test(p) || WIN_ROOTED_NO_DRIVE.test(p))) return p;
100
+ if (isAbsolute(base)) return resolve(base, p);
101
+ return isAbsolute(p) ? resolve(p) : undefined;
102
+ }
103
+
104
+ function dedupe(values: readonly string[]): string[] {
105
+ return [...new Set(values)];
106
+ }
107
+
108
+ function nonEmpty(value: unknown): string | undefined {
109
+ return typeof value === "string" && value.length > 0 ? value : undefined;
110
+ }
111
+
112
+ /** Every non-empty string among the path keys of `a`. */
113
+ function pathArgs(a: Record<string, unknown>): string[] {
114
+ const out: string[] = [];
115
+ for (const key of PATH_KEYS) {
116
+ const value = nonEmpty(a[key]);
117
+ if (value !== undefined) out.push(value);
118
+ }
119
+ return out;
120
+ }
121
+
122
+ function resolved(values: readonly (string | undefined)[], cwd: string): string[] {
123
+ const out: string[] = [];
124
+ for (const value of values) {
125
+ if (value === undefined) continue;
126
+ const p = absolute(value, cwd);
127
+ if (p !== undefined) out.push(p);
128
+ }
129
+ return dedupe(out);
130
+ }
131
+
132
+ /** `path` argument (or cwd) as search roots. */
133
+ function searchRoots(a: Record<string, unknown>, cwd: string): string[] {
134
+ return resolved([nonEmpty(a.path) ?? cwd], cwd);
135
+ }
136
+
137
+ const GLOB_CHARS = /[*?[\]{}()!]/;
138
+
139
+ /** The directory spelling of the glob-free `fixed` segments; undefined when there is none to anchor at. */
140
+ function joinPrefix(fixed: readonly string[], first: string | undefined): string | undefined {
141
+ if (fixed.length === 0) return first === "" ? "/" : undefined;
142
+ const joined = fixed.join("/");
143
+ if (joined === "") return "/";
144
+ return /^[A-Za-z]:$/.test(joined) ? `${joined}/` : joined;
145
+ }
146
+
147
+ /**
148
+ * The static prefix of a relative pattern that leaves the search root (`..` first once lexically normalised), or
149
+ * undefined. A wildcard segment may match nothing (`**`) or one directory (`*`), so a `..` after it may cancel it or
150
+ * climb one level further: with `dropWildcards` the wildcards that precede the last `..` are dropped before the `..`
151
+ * are resolved (the widest reading), without it they count as one ordinary segment each. The first wildcard that is
152
+ * left ends the prefix.
153
+ */
154
+ function relativePrefix(raw: readonly string[], dropWildcards: boolean): string | undefined {
155
+ const lastUp = raw.lastIndexOf("..");
156
+ const normal: string[] = [];
157
+ for (let index = 0; index < raw.length; index++) {
158
+ const segment = raw[index] ?? "";
159
+ if (segment === "..") {
160
+ if (normal.length > 0 && normal[normal.length - 1] !== "..") normal.pop();
161
+ else normal.push("..");
162
+ } else if (dropWildcards && index < lastUp && GLOB_CHARS.test(segment)) {
163
+ continue;
164
+ } else {
165
+ normal.push(segment);
166
+ }
167
+ }
168
+ if (normal[0] !== "..") return undefined;
169
+ const cut = normal.findIndex(segment => GLOB_CHARS.test(segment));
170
+ const fixed = cut < 0 ? normal.slice(0, -1) : normal.slice(0, cut); // no wildcard: the pattern names one entry
171
+ return joinPrefix(fixed, "..");
172
+ }
173
+
174
+ /**
175
+ * The directories a glob pattern is anchored at when it leaves the search root: the leading glob-free segments of an
176
+ * absolute pattern or of a relative one that starts with `..` once normalised. A relative pattern with a wildcard
177
+ * ahead of a `..` (`**` + `/../../w1/**`) has two readings, wildcard dropped and wildcard as one segment; both
178
+ * prefixes are returned. Empty when the pattern stays inside the search root.
179
+ */
180
+ function globPrefixes(pattern: string): string[] {
181
+ const segments = pattern.split(/[\\/]/);
182
+ if (!isAbsolute(pattern)) {
183
+ const raw = segments.filter(segment => segment !== "" && segment !== ".");
184
+ return dedupe([relativePrefix(raw, true), relativePrefix(raw, false)].filter((p): p is string => p !== undefined));
185
+ }
186
+ const fixed: string[] = [];
187
+ let sawGlob = false;
188
+ for (const segment of segments) {
189
+ if (GLOB_CHARS.test(segment)) { sawGlob = true; break; }
190
+ fixed.push(segment);
191
+ }
192
+ if (!sawGlob) fixed.pop(); // no wildcard: the pattern names one entry, search its directory
193
+ const prefix = joinPrefix(fixed, segments[0]);
194
+ return prefix === undefined ? [] : [prefix];
195
+ }
196
+
197
+ function none(): ToolTargets {
198
+ return { access: "none", paths: [], roots: [] };
199
+ }
200
+
201
+ function writeTargets(tool: string, a: Record<string, unknown>, cwd: string): ToolTargets {
202
+ if (tool === "patch" || tool === "apply_patch") {
203
+ // An unreadable patch has unknown targets: a write of nothing the caller can name. The host also honours the
204
+ // path arguments `filePath`, `path` and `file_path` of a patch call (`toolCallPaths` in src/compat/v2-hooks.ts).
205
+ const keyed = HOST_PATCH_PATH_KEYS.map(key => nonEmpty(a[key]));
206
+ return { access: "write", paths: resolved([...(hostPatchPaths(a) ?? []), ...keyed], cwd), roots: [] };
207
+ }
208
+ const raw = pathArgs(a);
209
+ if (tool === "multiedit" && Array.isArray(a.edits)) {
210
+ for (const edit of a.edits) raw.push(...pathArgs(record(edit)));
211
+ }
212
+ return { access: "write", paths: resolved(raw, cwd), roots: [] };
213
+ }
214
+
215
+ /**
216
+ * Whether `router_git_diff` reads the working tree. The tool runs `git diff [--stat|--name-only|--cached]
217
+ * [<ref>] -- <pathspec>` (gitArgv in git-tools.ts):
218
+ * - no ref: the working tree against the index, a working-tree read;
219
+ * - one ref: the working tree against that commit, a working-tree read;
220
+ * - `--cached` (mode "cached"): the index against HEAD or the ref, no working-tree read;
221
+ * - a range (`a..b`, `a...b`): commit against commit, no working-tree read.
222
+ * Only the last two are `none`.
223
+ */
224
+ function gitDiffReadsWorkingTree(a: Record<string, unknown>): boolean {
225
+ if (a.mode === "cached") return false;
226
+ const ref = nonEmpty(a.ref)?.trim() ?? "";
227
+ return !ref.includes("..");
228
+ }
229
+
230
+ /**
231
+ * A `router_git_*` result: paths are relative to the repository top level, so resolved against `gitRoot`; without an
232
+ * absolute `gitRoot` there is no concrete target (`paths` and `roots` stay empty, `gitRootRequired` is set). A
233
+ * path-less call covers the top level.
234
+ */
235
+ function gitTargets(result: ToolTargets, a: Record<string, unknown>, opts: ToolTargetsOptions | undefined): ToolTargets {
236
+ const gitRoot = nonEmpty(opts?.gitRoot);
237
+ if (gitRoot === undefined || !isAbsolute(gitRoot)) return { ...result, paths: [], roots: [], gitRootRequired: true };
238
+ const dir = nonEmpty(a.path);
239
+ return result.access === "read"
240
+ ? { ...result, paths: dir === undefined ? [] : resolved([dir], gitRoot) }
241
+ : { ...result, roots: resolved([dir ?? gitRoot], gitRoot) };
242
+ }
243
+
244
+ function classify(tool: string, a: Record<string, unknown>, cwd: string, opts?: ToolTargetsOptions): ToolTargets {
245
+ switch (tool) {
246
+ case "read":
247
+ return { access: "read", paths: resolved(pathArgs(a), cwd), roots: [] };
248
+ case "write":
249
+ case "edit":
250
+ case "multiedit":
251
+ case "patch":
252
+ case "apply_patch":
253
+ return writeTargets(tool, a, cwd);
254
+ case "list":
255
+ case "grep":
256
+ return { access: "search", paths: [], roots: searchRoots(a, cwd) };
257
+ case "glob": {
258
+ const roots = searchRoots(a, cwd);
259
+ const pattern = nonEmpty(a.pattern);
260
+ const prefixes = pattern === undefined ? [] : globPrefixes(pattern);
261
+ if (prefixes.length > 0) {
262
+ const base = roots[0] ?? cwd;
263
+ roots.push(...resolved(prefixes, base));
264
+ }
265
+ return { access: "search", paths: [], roots: dedupe(roots) };
266
+ }
267
+ case "router_run": {
268
+ const dir = nonEmpty(a.cwd) ?? cwd;
269
+ return { access: "run", paths: [], roots: resolved([dir], cwd) };
270
+ }
271
+ case "router_git_blame": {
272
+ // A blame at a ref reads committed content only; without one it reads the working-tree file.
273
+ if ((nonEmpty(a.ref)?.trim() ?? "") !== "") return none();
274
+ return gitTargets({ access: "read", paths: [], roots: [] }, a, opts);
275
+ }
276
+ case "router_git_diff":
277
+ return gitDiffReadsWorkingTree(a) ? gitTargets({ access: "search", paths: [], roots: [] }, a, opts) : none();
278
+ case "router_git_status":
279
+ case "router_git_ls_files":
280
+ return gitTargets({ access: "search", paths: [], roots: [] }, a, opts);
281
+ case "router_git_log":
282
+ case "router_git_show":
283
+ return none();
284
+ case "shell":
285
+ return { access: "none", paths: [], roots: resolved([nonEmpty(a.workdir) ?? cwd], cwd), uncovered: "shell" };
286
+ case "execute":
287
+ return { access: "none", paths: [], roots: [], uncovered: "execute" };
288
+ default:
289
+ return none();
290
+ }
291
+ }
292
+
293
+ /**
294
+ * What the tool call `tool(args)` touches, with `cwd` (absolute) as the base for relative paths. `router_git_*` paths
295
+ * are relative to the repository top level and resolve against `opts.gitRoot` (a path-less search covers the top
296
+ * level); without an absolute one the result has no `paths` or `roots` and carries `gitRootRequired: true`. A
297
+ * device-prefixed (`\\?\`, `\\.\`, `\??\`) or drive-less rooted (`\x`) path is returned unchanged on win32 (the
298
+ * registry's `keyOf` decides). Never throws.
299
+ */
300
+ export function toolTargets(tool: string, args: unknown, cwd: string, opts?: ToolTargetsOptions): ToolTargets {
301
+ const name = typeof tool === "string" ? tool.toLowerCase() : "";
302
+ try {
303
+ return classify(name, record(args), typeof cwd === "string" ? cwd : "", opts);
304
+ } catch {
305
+ // Unreachable for string inputs; a write-class tool stays a write so a lease is not skipped.
306
+ return WRITE_CLASS.has(name) ? { access: "write", paths: [], roots: [] } : none();
307
+ }
308
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * DF-1-1: whether a location (the host's `ctx.directory`) lies inside one of the configured `routing.workRoots` entries.
3
+ * An entry is an absolute path or an absolute glob with the semantics of the `external_directory` rule the role agents get
4
+ * for it (`workRootPattern` in role-agents.ts) as the host matches it (`permissionMatches`, QA-DF1-25): `*` matches any run of
5
+ * characters and crosses separators, `?` one character, every other character (`[`, `]`, `{`, `}` included) is literal. As
6
+ * in `workRootPattern`, the static directory before the first glob character (`workRootGlobIndex`) is resolved to its
7
+ * canonical form and the glob tail is kept verbatim; the location is canonical too (`realpathSync.native`; a path that does
8
+ * not resolve is used as written). The location is inside an entry when it or one of its ancestors matches it. Separators
9
+ * are normalized; on win32 the match ignores case. Unset or empty `workRoots`: every location counts as inside (nothing
10
+ * changes for a user without them).
11
+ */
12
+ import { realpathSync } from "node:fs";
13
+ import { posix, win32 } from "node:path";
14
+ import { isSlash, trimEndWhile } from "../util/linear-trim";
15
+ import { permissionMatches } from "./read-only";
16
+ import { workRootGlobIndex } from "./roles-config";
17
+
18
+ type Realpath = (path: string) => string;
19
+ const nativeRealpath: Realpath = (path) => realpathSync.native(path);
20
+
21
+ function normalize(path: string, platform: NodeJS.Platform): string {
22
+ const forward = path.replace(/\\/g, "/");
23
+ const trimmed = /^[A-Za-z]:\/$|^\/$/.test(forward) ? forward : trimEndWhile(forward, isSlash);
24
+ return platform === "win32" ? trimmed.toLowerCase() : trimmed;
25
+ }
26
+
27
+ function canonical(path: string, realpath: Realpath): string {
28
+ try {
29
+ return realpath(path);
30
+ } catch {
31
+ return path;
32
+ }
33
+ }
34
+
35
+ /** The entry with its static directory in canonical form and its glob tail verbatim (as `workRootPattern` builds it). */
36
+ function canonicalEntry(entry: string, realpath: Realpath): string {
37
+ const globAt = workRootGlobIndex(entry);
38
+ if (globAt === -1) return canonical(entry, realpath);
39
+ const prefix = entry.slice(0, globAt);
40
+ const cut = Math.max(prefix.lastIndexOf("/"), prefix.lastIndexOf("\\"));
41
+ const directory = entry.slice(0, cut + 1);
42
+ const tail = entry.slice(cut + 1);
43
+ const resolved = canonical(directory, realpath);
44
+ return /[\\/]$/.test(resolved) ? resolved + tail : `${resolved}/${tail}`;
45
+ }
46
+
47
+ /** True only when `workRoots` is non-empty and no entry contains `directory`. */
48
+ export function locationOutsideWorkRoots(
49
+ directory: string,
50
+ workRoots: readonly string[] | undefined,
51
+ platform: NodeJS.Platform = process.platform,
52
+ realpath: Realpath = nativeRealpath,
53
+ ): boolean {
54
+ const paths = platform === "win32" ? win32 : posix;
55
+ const entries = (workRoots ?? []).filter((entry) => typeof entry === "string" && entry.trim() !== "" && paths.isAbsolute(entry));
56
+ if (entries.length === 0) return false;
57
+ const location = normalize(canonical(paths.resolve(directory), realpath), platform);
58
+ const candidates: string[] = [];
59
+ for (let at = location; ; ) {
60
+ candidates.push(at);
61
+ const cut = at.lastIndexOf("/");
62
+ if (cut <= 0) break;
63
+ const parent = at.slice(0, cut);
64
+ // `D:/x` → `D:/`, the drive root, not `D:`.
65
+ at = /^[a-z]:$/i.test(parent) ? `${parent}/` : parent;
66
+ if (candidates.includes(at)) break;
67
+ }
68
+ for (const entry of entries) {
69
+ const pattern = normalize(canonicalEntry(entry, realpath), platform);
70
+ if (candidates.some((candidate) => entryMatches(candidate, pattern, platform))) return false;
71
+ }
72
+ return true;
73
+ }
74
+
75
+ /**
76
+ * The host's match of an `external_directory` pattern (`permissionMatches`) for `platform`. Both sides are normalized first
77
+ * (`normalize`: lower case on win32), so the host matcher's own case folding, which follows the running process, only
78
+ * matters for a posix `platform` under a win32 process (tests): there a case-only difference must not match.
79
+ */
80
+ function entryMatches(candidate: string, pattern: string, platform: NodeJS.Platform): boolean {
81
+ if (!permissionMatches(candidate, pattern)) return false;
82
+ if (platform === "win32" || process.platform !== "win32") return true;
83
+ // The same translation as `permissionMatches`, without its win32 case folding.
84
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
85
+ return new RegExp(`^${escaped}$`, "s").test(candidate);
86
+ }
@@ -56,6 +56,7 @@ export const FINDING_IDS = [
56
56
  "role-budget-low",
57
57
  "role-range-clamped",
58
58
  "role-binding-unknown",
59
+ "role-child-stale-resume",
59
60
  "native-explore-aliased",
60
61
  "role-usage-share",
61
62
  "roles-none-enabled",
@@ -89,6 +90,7 @@ export const FINDING_TARGET: Readonly<Record<FindingId, FindingTarget>> = {
89
90
  "role-budget-low": "router",
90
91
  "role-range-clamped": "router",
91
92
  "role-binding-unknown": "router",
93
+ "role-child-stale-resume": "router",
92
94
  "native-explore-aliased": "router",
93
95
  "role-usage-share": "router",
94
96
  "roles-none-enabled": "router",
@@ -267,6 +269,10 @@ export interface AdvisorExtras {
267
269
  readonly roleStats?: RoleStatsTable | null;
268
270
  /** Dispatch rows WITHOUT a role in the same window (tier dispatches); with `roleStats` it gives the role usage share. */
269
271
  readonly tierDispatches?: number;
272
+ /** `countUnknownBindings` over the same decision-log window; absent = unknown. */
273
+ readonly unknownBindings?: Readonly<{ fresh: number; resumed: number }>;
274
+ /** Process-lifetime orphan actions, independent of the decision-log window. */
275
+ readonly orphanCounters?: Readonly<{ refused: number; lost: number }>;
270
276
  }
271
277
 
272
278
  /** A role whose budget ran out in at least this share of its dispatches (and at least {@link ROLE_STATS_MIN_DISPATCHES} of them) has a budget that is too low. */
@@ -758,12 +764,10 @@ const roleBudgetLow: Check = (input) => {
758
764
  return findings;
759
765
  };
760
766
 
761
- /** Child sessions that could not be bound to a role dispatch: their outcomes are not attributed. */
767
+ /** Fresh child sessions that could not be bound to a role dispatch: their outcomes are not attributed. */
762
768
  const roleBindingUnknown: Check = (input) => {
763
- const stats = input.extras.roleStats;
764
- if (stats === undefined || stats === null || !rolesOnV2(input)) return [];
765
- let total = stats.unattributed.unknownBindings;
766
- for (const row of stats.byRoleTier) total += row.unknownBindings;
769
+ const total = input.extras.unknownBindings?.fresh ?? 0;
770
+ if (!rolesOnV2(input)) return [];
767
771
  if (total <= 0) return [];
768
772
  return [{
769
773
  id: "role-binding-unknown",
@@ -774,6 +778,21 @@ const roleBindingUnknown: Check = (input) => {
774
778
  }];
775
779
  };
776
780
 
781
+ /** Historical unbound resumes and this process's refusals are informational, never notice-worthy. */
782
+ const roleChildStaleResume: Check = (input) => {
783
+ if (!rolesOnV2(input)) return [];
784
+ const pending = input.extras.unknownBindings?.resumed ?? 0;
785
+ const cleaned = input.extras.orphanCounters?.refused ?? 0;
786
+ if (pending <= 0 && cleaned <= 0) return [];
787
+ return [{
788
+ id: "role-child-stale-resume",
789
+ severity: "info",
790
+ subject: "",
791
+ message: `Stale role-child resumes: ${pending} resumed unknown-binding row${pending === 1 ? "" : "s"} in the decision-log window (pending); ${cleaned} stale resume${cleaned === 1 ? "" : "s"} refused by this process (cleaned). Start a fresh role task instead of resuming a child whose dispatch binding was lost.`,
792
+ snippet: resolveRouting(input.cfg, "v2").orphans.resume === "allow" ? json({ routing: { orphans: { resume: "refuse" } } }) : null,
793
+ }];
794
+ };
795
+
777
796
  /** The share of role dispatches among all dispatches: tells whether the orchestrator follows the roles protocol or keeps naming tiers. */
778
797
  const roleUsageShare: Check = (input) => {
779
798
  const stats = input.extras.roleStats;
@@ -809,6 +828,7 @@ const CHECKS: ReadonlyArray<readonly [string, Check]> = [
809
828
  ["native-explore", nativeExploreAliased],
810
829
  ["role-budget", roleBudgetLow],
811
830
  ["role-binding", roleBindingUnknown],
831
+ ["role-stale-resume", roleChildStaleResume],
812
832
  ["role-usage", roleUsageShare],
813
833
  ];
814
834
 
@@ -20,7 +20,7 @@ import {
20
20
  } from "./backends/shared";
21
21
  import { createTypeSafeBackend } from "./backends/typesafe";
22
22
  import { applyRouteLine, parseRouteLine, type RouteLinePositions } from "./route-line";
23
- import { analyzeRules, needMatchesOf, type NeedMatch } from "./rules";
23
+ import { analyzeRules, highRiskTermOf, needMatchesOf, type NeedMatch } from "./rules";
24
24
 
25
25
  export type { NeedMatch } from "./rules";
26
26
  import { hasCredentialSignal } from "./scrub";
@@ -288,6 +288,12 @@ export function classifyNeedMatches(input: ClassifyInput, deps: Pick<ClassifyDep
288
288
  return needMatchesOf(ruleTextOf(input, parsed), { ...(input.cwd === undefined ? {} : { cwd: input.cwd }) });
289
289
  }
290
290
 
291
+ /** Role decision-log metadata only; reads the same bounded, route-line-stripped text as the rules, never a backend. */
292
+ export function classifyRiskTerm(input: ClassifyInput, deps: Pick<ClassifyDeps, "routeLinePositions">): string | undefined {
293
+ const parsed = parseRouteLine(typeof input.prompt === "string" ? input.prompt : "", { positions: deps.routeLinePositions ?? "first" });
294
+ return highRiskTermOf(ruleTextOf(input, parsed));
295
+ }
296
+
291
297
  /** Steps 1–3: route line, rules, route line applied. */
292
298
  function prepare(input: ClassifyInput, deps: ClassifyDeps): Prepared {
293
299
  const parsed = parseRouteLine(typeof input.prompt === "string" ? input.prompt : "", routeLineOptions(deps));
@@ -665,3 +665,14 @@ export function analyzeRules(
665
665
  export function classifyByRules(text: string, cfg: RulesConfig, ctx?: { cwd?: string }): TaskFacts {
666
666
  return analyzeRules(text, cfg, ctx).facts;
667
667
  }
668
+
669
+ /** Observability only: the first high-risk hit under R11's exact section/negation rules, without surrounding task text. */
670
+ export function highRiskTermOf(text: string): string | undefined {
671
+ const raw = collapseLongRuns(String(text ?? "").slice(0, RULES_MAX_CHARS));
672
+ const { riskText, prohibitionText } = splitSections(prepareBody(raw));
673
+ const hit = firstHit(HIGH_RISK_RES, riskText, false) ?? firstHit(HIGH_RISK_RES, prohibitionText, true);
674
+ if (hit === null) return undefined;
675
+ const word = hit.text.toLowerCase();
676
+ // Multiword/command regexes can span arbitrary arguments, and credential names can be private: log only a table id for those.
677
+ return /^[a-z-]{1,40}$/.test(word) ? word : `term-${hit.index}`;
678
+ }
@@ -20,7 +20,7 @@ import { homedir, tmpdir } from "node:os";
20
20
  import { dirname, join } from "node:path";
21
21
  import { fileURLToPath } from "node:url";
22
22
  import { resolveRouting, type RouterConfig } from "../../router/config";
23
- import { acquireOutcomes, createPersister, nodePersistDeps, resolveOutcomesDir, runStatsCli } from "../outcomes";
23
+ import { acquireOutcomes, createPersister, createSideLogs, nodePersistDeps, resolveOutcomesDir, runStatsCli } from "../outcomes";
24
24
  import { ingestSettings } from "../outcomes/ingest";
25
25
  import type { OutcomesBundle } from "../outcomes";
26
26
 
@@ -85,7 +85,7 @@ export async function runStatsCommand(args: string, deps: StatsCommandDeps): Pro
85
85
  stderr: (text) => {
86
86
  stderr += text;
87
87
  },
88
- });
88
+ }, deps.host === "v2" ? { open: (dir) => createSideLogs(dir, persistDeps) } : undefined); // 1.1.4: the side-log sections are v2 only
89
89
  return { stdout, stderr, exit };
90
90
  } catch (error) {
91
91
  deps.logger.warn("[router] /router stats failed", { error: describeError(error) });