opencode-model-router 2.7.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +219 -0
  2. package/package.json +1 -1
  3. package/src/commands/approvals.ts +354 -0
  4. package/src/commands/output.ts +12 -1
  5. package/src/compat/v2-hooks.ts +255 -53
  6. package/src/index.ts +328 -37
  7. package/src/router/config.ts +48 -2
  8. package/src/router/dispatch-header.ts +95 -2
  9. package/src/router/git-tools.ts +165 -9
  10. package/src/router/protocol.ts +5 -1
  11. package/src/router/role-agents.ts +110 -3
  12. package/src/router/roles-config.ts +83 -0
  13. package/src/router/roles.ts +1 -1
  14. package/src/router/sessions.ts +11 -0
  15. package/src/routing/classify/route-line.ts +96 -5
  16. package/src/routing/classify/types.ts +26 -0
  17. package/src/routing/outcomes/signals.ts +17 -0
  18. package/src/routing/roles/admission.ts +1028 -0
  19. package/src/routing/roles/approvals.ts +876 -0
  20. package/src/routing/roles/binding.ts +17 -4
  21. package/src/routing/roles/check-placement.ts +112 -0
  22. package/src/routing/roles/git-root.ts +500 -0
  23. package/src/routing/roles/policy.ts +9 -0
  24. package/src/routing/roles/read-set.ts +325 -0
  25. package/src/routing/roles/work-root.ts +9 -1
  26. package/src/routing/wire/dispatch.ts +611 -18
  27. package/src/routing/wire/working-set.ts +58 -0
  28. package/src/util/linear-trim.ts +32 -0
  29. package/src/verify/batch.ts +7 -2
  30. package/src/verify/branch.ts +135 -0
  31. package/src/verify/deterministic.ts +232 -10
  32. package/src/verify/dispatch.ts +284 -9
  33. package/src/verify/dod.ts +46 -0
  34. package/src/verify/edges.ts +817 -0
  35. package/src/verify/gate.ts +349 -16
  36. package/src/verify/git-top.ts +43 -0
  37. package/src/verify/head.ts +107 -0
  38. package/src/verify/pending.ts +155 -8
  39. package/src/verify/perimeter.ts +1180 -0
  40. package/src/verify/pin.ts +109 -0
  41. package/src/verify/reference.ts +82 -6
  42. package/src/verify/risk.ts +16 -3
  43. package/src/verify/runner.ts +706 -32
  44. package/src/verify/tree.ts +347 -8
  45. package/src/verify/types.ts +57 -0
  46. package/src/verify/wiring.ts +1324 -35
package/CHANGELOG.md CHANGED
@@ -7,6 +7,225 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.8.0] - 2026-10-13
11
+
12
+ ### Added
13
+
14
+ - **Approve repositories outside routing.repoParents with /router approve (OpenCode v2, roles mode; inert on v1)
15
+ (#107).** A role dispatch with `root=<path>` outside `routing.repoParents` is refused with a note composed from git
16
+ that names the repository and ends `Only the user can approve it: ask the user to run /router approve <path>, then
17
+ dispatch again.` The human types `/router approve <path>` in a top-level session: the router reads the repository's
18
+ identity from git (path, git common directory, root commits; origin and branch are shown), stores it and reloads the
19
+ role agents (`Role agents reloaded; dispatch again with root=<path>.`; if the reload fails, `Restart OpenCode to use
20
+ it.`); dispatch again with `root=<path>`. Only the main worktree of a repository can be approved, never a protected
21
+ location (a filesystem root, the user profile, the OpenCode config, data, state or cache directories, the directory
22
+ of the `OPENCODE_CONFIG` file, `~/.opencode`, the plugin install directory, the approvals store directory), nor a
23
+ repository that is or contains a `routing.repoParents` entry; `routing.repoExclude` wins, and the identity is checked
24
+ again at every use. After a revocation or expiry, an exact resume, `router_run` and `router_git_*` of a child bound
25
+ through the approval are refused. The approvals are stored in `opencode-model-router.repo-approvals.json` next to the router state file.
26
+ `/router repos` lists the approvals, their last use and expiry; `/router revoke <path>` removes one and drops the
27
+ repository from every working set. An approval expires `routing.repoApprovalDays` (new key, global only, 1–90, default
28
+ 14) days after its last use, and 90 days after approval at the latest. Worktrees of an approved repository outside its
29
+ main tree still need `routing.workRoots` or a restart. See
30
+ [Repositories outside routing.repoParents](docs/ROLES.md#repositories-outside-routingrepoparents).
31
+ - **Dependencies outside `node_modules` (OpenCode v2, roles mode; inert on v1) (#107).** A role dispatch's perimeter
32
+ also holds the repositories the work root declares a dependency on outside `node_modules` (owner decision D24, Tier
33
+ A): `file:`, `link:` and `portal:` specs in `package.json` (root and workspace manifests, `overrides`, `resolutions`,
34
+ `pnpm.overrides`); tsconfig/jsconfig `extends`, `references`, `paths`, `baseUrl`, `rootDirs`, `typeRoots`, `include`
35
+ and `files`; Python editable installs in a venv inside the work root (`.pth`, `.egg-link`, setuptools editable
36
+ finders); Go `replace` and `go.work use`. They are read as text, never evaluated, and bounded; no config key. An
37
+ admitted target is observed for I4, named in the verified-scope line and observed again at `router_verify` (S11), but
38
+ never pinned, so the reference does not cover it. A target that is not admitted is named `<name> (not admitted)`,
39
+ never refused. A working-set worktree that declares an edge into the work root is a consumer:
40
+ `links this work root (<via>)`, never the raw spec. A bound that cuts the reading at dispatch is logged:
41
+ `[verify] dispatch perimeter: declared dependency edges were cut by a bound`. See
42
+ [Dependencies outside node_modules](docs/VERIFICATION.md#dependencies-outside-node_modules).
43
+ - **Roles mode (OpenCode v2; cross-repo, #107, owner decision Q10): `repo=` also matches a worktree directory name.** A
44
+ route line's `repo=<name>` also matches a linked worktree whose directory name is `<name>` below `routing.repoParents`,
45
+ and binds that worktree (with `branch=`, the worktree of its repository on that branch). A repository and a worktree
46
+ directory sharing the name, or two such worktree directories of different repositories, are refused as ambiguous, each
47
+ candidate listed as `<worktree path> (repository <name>, branch <branch>)`.
48
+ - **Role dispatch header (OpenCode v2 roles mode; inert on v1) (#107).** A routed role dispatch with a work root and
49
+ read access now starts with a short header naming the role, the work root and, when known, the repository, branch and
50
+ head, so a role delegate is told where it works; the nonce line or carried acceptance block stays last. A header the
51
+ orchestrator copied from another dispatch is always stripped, and replaced only when the router adds its own. The
52
+ header is emitted only when it is relevant (owner decision Q8, invariant I9): `routing.repoParents` is set, the route
53
+ line declares `repo=`, `branch=` or `root=`, or the work root differs from the session directory; otherwise the
54
+ dispatch prompt is unchanged. No
55
+ header for a delegate's dispatch or a non-exact resume; with `dispatchHeader: false` there is no header either, except that a work root other
56
+ than the session directory still gets a minimal header (the identity and `Working directory:` paragraphs). The role
57
+ work-root rule now points to the `Working directory:` line. A read-only role is told "You read only in your working
58
+ directory." in the header wording, although its read set can also include the working set.
59
+ - **Checks in other repositories (OpenCode v2, roles mode) (#107).** A check of the `[acceptance]` block can run in
60
+ another repository of the read set: `check: testsPass cwd="<repo>" scope=full`. A relative `cwd=` stays inside the
61
+ work root; an absolute one must be in the read set; one outside it, or a `scope=` that is neither `affected` nor
62
+ `full`, is unverifiable and nothing runs. Changes are always captured in the work root; a change that no check root
63
+ covers is unverifiable (`is not covered by any check root`). A `testsPass` or `lintClean` check in another repository
64
+ must use `scope=full`; its failure there is unverifiable, never a fail, and it gets no reference. A working-set
65
+ worktree whose `node_modules` links into the work root is a consumer: a pass with a change and no tests, build, lint
66
+ or run check placed in it is UNVERIFIED, with the suggested check line. Consumers are discovered by package name
67
+ (a `node_modules` link into the work root) in the working set only; when discovery stops on its budget before
68
+ finishing a worktree, a pass with a change is UNVERIFIED (`consumer discovery stopped before finishing …`), so a
69
+ consumer may remain undiscovered. The link scan is bounded, and consumer discovery runs under the gate deadline. A
70
+ check placed in a consumer clears that incomplete-discovery caveat. When the change of the work root could not be
71
+ observed and no check covers it, the result is refused. A link target pinned at dispatch and
72
+ unchanged since keeps the reference exact (link pins). A tier dispatch on v2 refuses a per-check `cwd=`
73
+ (`a per-check cwd= is honoured only in roles mode`); `scope=` alone is ignored; v1 ignores both keys. A dispatch with
74
+ per-check keys may be deferred, see "Deferred verification across repositories" below. The configured roles protocol
75
+ (`routing.repoParents`) teaches the syntax.
76
+ - **Deferred verification across repositories (OpenCode v2, roles mode) (#107).** A role dispatch with a perimeter or
77
+ with per-check `cwd=`/`scope=` keys may now be deferred (`VERIFY:deferred`, the default). At return the router freezes
78
+ the perimeter (the statuses for I4 and I8, the working-set roots, the observed link targets, the placements and the
79
+ link pins). The dispatch is verified at once, not deferred, when I4 already refuses at return, when a linked
80
+ repository could not be observed within the deferral bound, and when a placement or a v2 tier per-check `cwd=` is
81
+ refused (the refusal reaches the verification, never the deferred finish). At
82
+ `router_verify` the I4 window is the dispatch (never decided again), consumers are discovered over the frozen
83
+ working-set roots, and link targets are observed again: one that changed since the producer returned, or cannot be
84
+ observed again, turns a pass UNVERIFIED with a caveat (a fail keeps it). Correction since P2e QA round 1: a pass held
85
+ back only by links that cannot be observed again is retryable instead: the handle is reported as not judged and stays
86
+ open, so call `router_verify` again (see `docs/VERIFICATION.md`, "Deferred verification across repositories"). A
87
+ placement whose path or git top changed since return runs nothing; one that cannot be checked now (an error other
88
+ than a missing directory) runs nothing and also stays open. Link pins kept for the deferred entry keep the reference
89
+ exact. With `routing.repoParents`
90
+ set, role dispatches are now deferred by default where they used to be synchronous; a "continue and finish" resume of
91
+ a deferred attempt cannot back a `deterministic` detection (see `docs/ROLES.md`).
92
+ - **Cross-repo work in roles mode (OpenCode v2; inert on v1) (#107).** New global-only keys `routing.repoParents`,
93
+ `routing.repoDepth` (1–4, default 2) and `routing.repoExclude` name the directories whose repositories role
94
+ dispatches may work in; registration adds `<parent>/*` `external_directory` allow patterns, so new clones need no
95
+ restart. The route line accepts `repo=<name>` and `branch=<ref>` (case kept), and the work root is bound through
96
+ admission (a git top level below a parent, or a worktree of a known repository). A role may read, glob and grep the
97
+ work root, the session's working set and the admissible repositories below the parents (reads outside the work root
98
+ are annotated `[router: read from <name> (<branch>) …]`) but edits only in its work root; edit refusals name the
99
+ other worktree or repository and the `repo=` dispatch needed. The verification perimeter snapshots the repository,
100
+ the working set and `node_modules`-linked repositories; an unattributable write there makes the result
101
+ unverifiable. The protocol and the tier dispatch header gain a cross-repo sentence. Limit: a worktree outside the
102
+ parents still needs a `routing.workRoots` glob or a restart.
103
+ - **Cross-repo hardening after two QA rounds.** Only fully qualified paths and explicit search roots reach the read set;
104
+ a relative path stays judged against the work root. A final admission gate checks `repoExclude` on the shown and the
105
+ canonical path and refuses a candidate that is a parent, an ancestor of one, or a link out of it, with no fallback to
106
+ the worktree rule. An invalid, duplicated or conflicting `repo=`/`branch=` is no longer ignored: it is an invalid
107
+ declaration, and the dispatch is refused with the note
108
+ (`<key>=<value> is not a valid repository name / branch name: no work root. Fix the route line.`, see the owner
109
+ decision Q9 entry under Changed). The verification perimeter is planned for every routed role dispatch with a work root whenever
110
+ `routing.repoParents` is set, even without `repo=`; a pass shows `verified scope: …` and link targets are named
111
+ `(not admitted)` or `(not observed)`.
112
+ - **`router_git_*` in other repositories (OpenCode v2, roles mode; inert on v1) (#107).** A role agent with an exact
113
+ binding and `read`, `glob` or `grep` in its grant may pass `root` to a `router_git_*` tool to read the history of
114
+ another repository of its read set, by absolute top-level path or by name below `routing.repoParents` (`repo=`
115
+ semantics, no branch). The output starts with the read-provenance line; git stays read-only. The argument exists only
116
+ when `routing.repoParents` is non-empty at start (restart after adding parents); tier agents and the orchestrator are
117
+ refused, and every refusal runs nothing (see `docs/ROLES.md`).
118
+ - **A consumer `testsPass` with `scope=affected` runs `vitest related` across a link (OpenCode v2, roles mode; inert on
119
+ v1) (#107).** An explicit `scope=affected` on a `testsPass` in another repository runs the consumer's tests related
120
+ to the change in the work root (vitest 5 only; jest, pytest and other vitest majors are unverifiable). A run that
121
+ selects no test, or misses a consumer test file that imports a package of the work root, is unverifiable; so is a
122
+ failure. A `testsPass` without `scope=` and a `lintClean` there still must use `scope=full` (see `docs/VERIFICATION.md`).
123
+
124
+ ### Changed
125
+
126
+ - **Worktrees of an excluded repository are refused (OpenCode v2, roles mode) (#107).** The linked worktrees of a
127
+ repository excluded by `routing.repoExclude` are now excluded with it: a `repo=`, `branch=` or `root=` route line that
128
+ names one is refused, and they are kept out of the read set.
129
+
130
+ - **A full-scope `testsPass` is no longer run synchronously when the producer changed nothing (OpenCode v2) (#107).**
131
+ Before, a dispatch with no changed files and config `testScope: "full"` ran the full suite synchronously before the
132
+ return. On OpenCode v2 such a dispatch (and one whose `testsPass` check has `scope=full`) now defers instead of
133
+ blocking the return; for a `delegate` this also means no synchronous ladder. Config `testScope` does not affect
134
+ `lintClean` (only a per-check `scope=full` runs lint unscoped), so a `lintClean`-only dispatch with no change still
135
+ passes without running anything. v1 is unchanged (owner decision OD-P2e-2).
136
+ - **Roles mode (OpenCode v2; cross-repo, #107, owner decision Q9): a refused declared target refuses the dispatch.** When
137
+ a role dispatch's route line declares `repo=`, `branch=` or `root=` (or an invalid `repo=`, `branch=` or `root=`: a
138
+ rejected, bare, duplicate or conflicting value, noted `root=<value> is not a valid absolute work root: no work root.
139
+ Fix the route line.`) and the router cannot bind a work root for it, the `task` call now fails with
140
+ `[router] role dispatch @<agent> refused: <note>` instead of running with no work root in the session directory. An
141
+ exact resume whose route line names a different target than the child's bound root is refused too (`this child is
142
+ bound to <work root>; a resume cannot change its work root: dispatch a new child`). A dispatch that declares nothing,
143
+ a delegate's dispatch and a resume that declares nothing or the bound target are unchanged.
144
+
145
+ ### Fixed
146
+
147
+ - **A dependency the producer adds during a deferred dispatch is frozen at return (OpenCode v2, roles mode) (#107).**
148
+ `router_verify` reported a dependency of the work root added during the dispatch as changed (`the linked repository
149
+ <name> at <root> changed since the producer returned; …`) every time. The work root's package links and declared
150
+ edges are now read again when the producer returns (owner decision D26): a new admitted dependency is observed then,
151
+ and `router_verify` compares it with that state; one that cannot be observed within the deferral bound, or more new
152
+ dependencies than the perimeter has room for, verify the dispatch at once (no handle); a new one that is not admitted
153
+ is named `<name> (not admitted)` in the verified-scope line. A dependency the producer removed during the dispatch is
154
+ no longer observed again at `router_verify`, unless the work root declares it again (then it is "changed").
155
+ - **A change set that mixes paths inside and outside the observed repository is no longer verified as a pass on the
156
+ inside paths alone.** The runner dropped the outside paths with a note and ran the scoped checks on the rest, and a
157
+ grader, which checks against and runs in the working directory, could not inspect them. The gate now reports
158
+ `unverifiable` ("the producer also changed files outside `<root>`: …", at most five paths named) on both the
159
+ deterministic and the grader path, where `<root>` is the git top-level the change set was observed in (for a deferred
160
+ `router_verify`, the one recorded at registration), so edits in sibling packages of one monorepo are not flagged. Any absolute changed path outside the repository, for example a
161
+ scratch file in the temp directory written by a write tool, mixed with repository edits, now makes the result
162
+ unverifiable; there is no temp-directory exemption (fail closed). A relative path that climbs out of the root
163
+ (`../x.ts`, resolved against the base) counts as outside. A change set that is entirely outside keeps its existing
164
+ message, and that all-outside safety net now also applies on the grader path (it used to run on the deterministic
165
+ path only).
166
+ - **`verify`: the pre-existing-failure reference is now approximate (cause `external-link`) when a package in a linked
167
+ `node_modules` is a link to a directory outside the repository**, for example an npm `file:` dependency or
168
+ `npm link`, a yarn/pnpm `link:`/`portal:` package, or a workspace link. Previously the rerun loaded that directory's
169
+ live code, so a failure caused by a change there was also reproduced at the reference and excused as pre-existing.
170
+ An approximate reference never excuses a failure, so such a run is now unverifiable.
171
+ - **`verify`: a package link to the repository root or to an ancestor of it is now an approximate reference too (cause
172
+ `root-link`).** The label is root-relative even when the linked `node_modules` itself lives outside the repository.
173
+ Only a real path whose parent directory is `node_modules` (or `node_modules/@scope`) counts as a package store and is
174
+ exempt from `external-link`; dot-entries such as `node_modules/.cache` are ignored. Residual limits: nested links
175
+ (`node_modules/<pkg>/node_modules/<dep>`, `.pnpm/*/node_modules/<dep>` for a transitive `link:`) and yarn PnP
176
+ `portal:`/`link:` are not detected. Cost: in a worktree whose `node_modules` is a junction to another checkout, every
177
+ package link into that checkout is an `external-link`, so failing tests there are unverifiable.
178
+ - **A branch switch of the verified working tree now makes the result unverifiable instead of passing on the other
179
+ branch.** Previously the diff between the two heads became the change set, so the checks verified another branch.
180
+ The dispatch reads a cheap head state (top-level, HEAD, branch name and the reflog entry count; one
181
+ `git rev-parse` and one `git rev-list --walk-reflogs --count HEAD`), kept even when the full snapshot is contaminated
182
+ or unavailable, and the gate reads it again. The gate reports `unverifiable` ("the working tree `<root>` switched
183
+ from `<A>` to `<B>` during the dispatch; the checks would verify another branch") for another branch name, and
184
+ "moved or was rewritten … (reflog: "<detail>")" for a same-branch history rewrite: a reflog that shrank, a HEAD
185
+ that moved without a reflog entry, a reflog window that does not start at the dispatch head and end at the current
186
+ head, or a reflog entry that moved HEAD for any reason other than a commit (including amend, initial and merge),
187
+ `merge`, `cherry-pick`, `revert`, `am` or `pull` without rebase (so checkout, reset, rebase, `pull --rebase` and an
188
+ unnamed `update-ref` count). Entries that left HEAD where it was (`git stash`, an unstaging `git reset`, a checkout
189
+ of the current branch, `merge --abort`, `cherry-pick --abort`) are ignored, and commits alone, also on a detached
190
+ HEAD, are not a move. A reflog count of 0 (reflogs disabled) leaves the decision to the branch-name rule. A
191
+ relocated top-level is reported too. The same checks with "since
192
+ the producer returned" cover a checkout between the producer's return and `router_verify`. `router_verify` now reads
193
+ the head state itself and no longer depends on the full snapshot for this check. Detached to detached at another
194
+ commit counts as a switch (reported as "moved"), and so does a new branch created at the same commit (fail closed).
195
+ Nothing is compared when there was no repository, or HEAD was unborn, at dispatch start (a producer that runs
196
+ `git init` or makes the first commit). If the dispatch head read failed, the dispatch snapshot's head and branch
197
+ stand in; only when both are unknown does the gate refuse ("cannot confirm the branch of `<root>`"). The dispatch
198
+ head read gets the whole `baselineTimeoutMs` per git process. `router_verify` gives the retryable form of that
199
+ message, and reports the handle as not judged, only when the head state cannot be read at all. On a move the commit diff is not run, so no path from the
200
+ other branch enters the change set. A switch the deferred finish already detected is carried to the required gate.
201
+ - **A pass on an empty change set is no longer reported as verified when the producer ran a tool whose writes the
202
+ router cannot observe** (`bash`, `router_run`, Code Mode `execute`, MCP and unknown tools). The result is
203
+ `unverifiable` with the caveat `no change was observed in <root> but the producer ran <tools>; a write those tools
204
+ made cannot be seen, so this is not a verified pass`, on the deterministic and the grader path, and at
205
+ `router_verify`. Read-only router tools (`router_git_*`, `router_request_authority`) and the context7 and Brave
206
+ documentation and search tools count as non-writing, matched by exact name; they also no longer discard an
207
+ in-flight change capture. The delegating tools `task`, `delegate` and `subagent` always count as writers (a nested
208
+ child's writes are not in the producer's lineage) but still do not contaminate captures. A writer is counted in the
209
+ before-hook once the guard allows the call, so a call that errors still counts. Tool names are matched
210
+ case-insensitively and sanitised in the caveat. Known limit: a user MCP server named `router`, `context7` or `brave`
211
+ that exposes those exact tool names would be treated as non-writing.
212
+ - **Roles mode: a carried role attempt now inherits the lineage's branch check and its unobservable-writer tally.** A
213
+ carried attempt is a resume that re-checks an earlier attempt's acceptance block. A branch switch since the attempt
214
+ that introduced the block (`... since the attempt that introduced this acceptance; ...`), or a switch any earlier
215
+ attempt already found (stored in the lineage; an inherited reason is prefixed "in an earlier attempt of this
216
+ acceptance: "), now makes it unverifiable. A carried attempt whose tree cannot be read, while the introducing attempt
217
+ recorded a branch, is unverifiable too. A "cannot confirm" reason is not recorded as the lineage's switch, and a
218
+ switch the deferred finish saw is folded into the attempt before the lineage records it. Carried attempts compare
219
+ names and heads only. Previously only the current dispatch's own window was checked.
220
+ - **OpenCode v2: a tier `subagent` call now passes the child session ID (from `result.output.sessionID`) to
221
+ verification**, so the child's edits and unobservable writers join the producer's lineage. Visible effects on
222
+ OpenCode v2 tier calls: a child's shell writes now count as unobservable writers; a child's edits reach the change
223
+ set; `VERIFY:deferred` tier calls now really defer and return a `vrf_` handle; and the trivial-dispatch skip,
224
+ outcome ingestion and false-refusal detection now run for tier children.
225
+ - **These verification fixes also change verdicts on OpenCode v1.** v1 shares the verification engine, and the v1
226
+ freeze allows integrity fixes; the changes only make verdicts stricter (a pass can become `unverifiable`, never the
227
+ reverse).
228
+
10
229
  ## [2.7.0] - 2026-10-10
11
230
 
12
231
  ### Added
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-model-router",
3
- "version": "2.7.0",
3
+ "version": "2.8.0",
4
4
  "description": "OpenCode plugin that routes tasks to tiered subagents (fast/medium/heavy) based on complexity",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -0,0 +1,354 @@
1
+ /**
2
+ * Cross-repo Phase 4 (P4.7): `/router approve <path>`, `/router repos` and `/router revoke <path>`
3
+ * (`docs/design/cross-repo-phase4-plan.md`, SD-P4-10..13, S1/S2).
4
+ *
5
+ * Only these commands write the approvals store (S1). What the human sees and what gets stored come from git at approve time
6
+ * (`inspectCandidate`), never from the dispatch text or the refusal note (S2). `repos` reads the store only (no git). Every
7
+ * repository-derived string passes through `displaySafe`. Whether the commands are available at all (v2 host, roles mode,
8
+ * `routing.repoParents` non-empty, a top-level human session: SD-P4-10) is decided by the `/router` handler, not here.
9
+ */
10
+ import * as fs from "node:fs";
11
+ import * as path from "node:path";
12
+
13
+ import {
14
+ applyApproval,
15
+ expiresAt,
16
+ inspectCandidate,
17
+ isApprovalValid,
18
+ readApprovals,
19
+ type ApprovalsEnv,
20
+ type IdentityDeps,
21
+ type InspectDeps,
22
+ type RepoApproval,
23
+ } from "../routing/roles/approvals";
24
+ import { displaySafe } from "../routing/roles/read-set";
25
+ import { permissionMatches } from "../router/read-only";
26
+ import { REPO_APPROVAL_CAP_DAYS } from "../router/roles-config";
27
+ import { dropFromWorkingSets } from "../routing/wire/working-set";
28
+
29
+ /** The `/router` subcommands of this module, in help order. */
30
+ export const ROUTER_APPROVAL_SUBCOMMANDS = ["approve", "repos", "revoke"] as const;
31
+ export type RouterApprovalSubcommand = (typeof ROUTER_APPROVAL_SUBCOMMANDS)[number];
32
+
33
+ /** Whether `sub` (lower-cased first word of the `/router` arguments) is one of {@link ROUTER_APPROVAL_SUBCOMMANDS}. */
34
+ export function isRouterApprovalSubcommand(sub: string): sub is RouterApprovalSubcommand {
35
+ return (ROUTER_APPROVAL_SUBCOMMANDS as readonly string[]).includes(sub);
36
+ }
37
+
38
+ /** What an `approve` or `revoke` changed in the store; carried by the command output for the v2 adapter (SD-P4-11). */
39
+ export interface ApprovalsChange {
40
+ readonly kind: "approve" | "revoke";
41
+ /** The canonical path of the approved or revoked repository. */
42
+ readonly path: string;
43
+ }
44
+
45
+ /**
46
+ * Non-enumerable key on the `/router` command output (its `parts` array) after an `approve` or `revoke` that wrote the store
47
+ * (SD-P4-11). The v2 command adapter then reloads the role agents before it sends the text on.
48
+ */
49
+ export const APPROVALS_CHANGED: unique symbol = Symbol.for("opencode-model-router.approvals-changed");
50
+
51
+ /** Mark `target` (the command output's `parts`) with `change`, non-enumerable, so serialisation and copies never carry it. */
52
+ export function markApprovalsChanged(target: object, change: ApprovalsChange): void {
53
+ Object.defineProperty(target, APPROVALS_CHANGED, { value: Object.freeze({ ...change }), enumerable: false, configurable: true, writable: false });
54
+ }
55
+
56
+ /** The change marked on `target` by {@link markApprovalsChanged}, or undefined. */
57
+ export function approvalsChangedOf(target: unknown): ApprovalsChange | undefined {
58
+ if (typeof target !== "object" || target === null) return undefined;
59
+ const value: unknown = Reflect.get(target, APPROVALS_CHANGED);
60
+ if (typeof value !== "object" || value === null) return undefined;
61
+ const kind: unknown = Reflect.get(value, "kind");
62
+ const where: unknown = Reflect.get(value, "path");
63
+ if ((kind !== "approve" && kind !== "revoke") || typeof where !== "string") return undefined;
64
+ return { kind, path: where };
65
+ }
66
+
67
+ /**
68
+ * The line the v2 command adapter appends after it reloaded the role agents for `change` (SD-P4-11). `applies` is
69
+ * `APPROVAL_RELOAD_APPLIES` (spike T6: a reload makes the host allow the approved directory); `reloadError` is set when the
70
+ * reload failed, which gives the restart line too.
71
+ */
72
+ export function approvalReloadLine(change: ApprovalsChange, applies: boolean, reloadError?: string): string {
73
+ const repo = displaySafe(change.path);
74
+ const failed = reloadError === undefined ? "" : `The role agents could not be reloaded (${displaySafe(reloadError)}). `;
75
+ if (change.kind === "approve") {
76
+ return reloadError === undefined && applies
77
+ ? `Role agents reloaded; dispatch again with root=${repo}.`
78
+ : `${failed}Restart OpenCode to use it.`;
79
+ }
80
+ return reloadError === undefined && applies
81
+ ? `Role agents reloaded; root=${repo} is no longer allowed.`
82
+ : `${failed}The router refuses root=${repo} now; restart OpenCode to remove its directory permission from the role agents.`;
83
+ }
84
+
85
+ /** Configuration and injectable I/O of {@link runRouterApprovals}. */
86
+ export interface RouterApprovalsOptions {
87
+ /** `routing.repoParents` (resolved). */
88
+ readonly parents: readonly string[];
89
+ /** `routing.repoExclude` (resolved). */
90
+ readonly exclude: readonly string[];
91
+ /** `routing.repoApprovalDays` (resolved). */
92
+ readonly days: number;
93
+ /**
94
+ * `routing.repoDepth` (resolved): a candidate below a parent but deeper than this is reported as one no approval applies to.
95
+ * Undefined: no depth check (every candidate inside a parent needs no approval).
96
+ */
97
+ readonly repoDepth?: number;
98
+ /** Store environment (tests: the store directory and the clock). */
99
+ readonly env?: ApprovalsEnv;
100
+ /** Git and filesystem of the candidate inspection (tests). */
101
+ readonly identity?: IdentityDeps;
102
+ /** Default `process.platform`. */
103
+ readonly platform?: NodeJS.Platform;
104
+ }
105
+
106
+ export interface RouterApprovalsResult {
107
+ readonly text: string;
108
+ /** Set when the store was written (approve, revoke). */
109
+ readonly change?: ApprovalsChange;
110
+ }
111
+
112
+ const DAY_MS = 86_400_000;
113
+
114
+ /**
115
+ * The path argument: the rest of the `/router` arguments, trimmed, with one pair of surrounding double or single quotes
116
+ * removed (so a path with spaces can be quoted, or typed as is). Undefined when empty.
117
+ */
118
+ export function parseApprovalPath(rest: string): string | undefined {
119
+ let text = rest.trim();
120
+ const q = text[0];
121
+ if (text.length >= 2 && (q === "\"" || q === "'") && text.endsWith(q)) text = text.slice(1, -1).trim();
122
+ return text === "" ? undefined : text;
123
+ }
124
+
125
+ function keyOf(p: string, platform: NodeJS.Platform): string {
126
+ return platform === "win32" ? p.toLowerCase() : p;
127
+ }
128
+
129
+ /** Normalized comparison form: resolved, no trailing separator except at a root, case-folded on win32. */
130
+ function cmpForm(p: string, platform: NodeJS.Platform): string {
131
+ let r = path.resolve(p);
132
+ const root = path.parse(r).root;
133
+ while (r.length > root.length && (r.endsWith(path.sep) || r.endsWith("/"))) r = r.slice(0, -1);
134
+ return keyOf(r, platform);
135
+ }
136
+
137
+ function realOrUndefined(p: string, realpath: (p: string) => string): string | undefined {
138
+ try {
139
+ const real = realpath(p);
140
+ return typeof real === "string" && real !== "" ? real : undefined;
141
+ } catch {
142
+ return undefined;
143
+ }
144
+ }
145
+
146
+ function realpathOf(opts: RouterApprovalsOptions): (p: string) => string {
147
+ return opts.identity?.realpath ?? ((p: string) => fs.realpathSync.native(p));
148
+ }
149
+
150
+ /** `form` with one trailing separator (comparison forms keep one only at a filesystem root). */
151
+ function withSep(form: string): string {
152
+ return form.endsWith(path.sep) || form.endsWith("/") ? form : `${form}${path.sep}`;
153
+ }
154
+
155
+ /** Whether comparison form `child` is strictly inside comparison form `parent`. */
156
+ function strictlyInside(child: string, parent: string): boolean {
157
+ return child !== parent && child.startsWith(withSep(parent));
158
+ }
159
+
160
+ /** How a candidate relates to `routing.repoParents`: it is a parent, contains one, or is `depth` levels below one. */
161
+ type ParentRelation =
162
+ | { readonly kind: "is" | "contains"; readonly parent: string }
163
+ | { readonly kind: "inside"; readonly parent: string; readonly depth: number };
164
+
165
+ /**
166
+ * How `canonical` relates to the `routing.repoParents` entries (each in its text and canonical form, case-insensitive on
167
+ * win32), or undefined when it is outside all of them. Being or containing a parent wins over being inside another one;
168
+ * among the parents holding it, the nearest (smallest depth) is reported. No git.
169
+ */
170
+ function parentRelation(canonical: string, opts: RouterApprovalsOptions, platform: NodeJS.Platform): ParentRelation | undefined {
171
+ const candidate = cmpForm(canonical, platform);
172
+ const realpath = realpathOf(opts);
173
+ let nearest: { parent: string; depth: number } | undefined;
174
+ let holder: ParentRelation | undefined;
175
+ for (const parent of opts.parents) {
176
+ if (parent.trim() === "" || !path.isAbsolute(parent)) continue;
177
+ const forms = new Set([cmpForm(parent, platform)]);
178
+ const real = realOrUndefined(parent, realpath);
179
+ if (real !== undefined) forms.add(cmpForm(real, platform));
180
+ for (const form of forms) {
181
+ if (candidate === form) return { kind: "is", parent };
182
+ if (strictlyInside(form, candidate)) holder ??= { kind: "contains", parent };
183
+ else if (strictlyInside(candidate, form)) {
184
+ const depth = candidate.slice(withSep(form).length).split(/[\\/]/).filter((part) => part !== "").length;
185
+ if (nearest === undefined || depth < nearest.depth) nearest = { parent, depth };
186
+ }
187
+ }
188
+ }
189
+ if (holder !== undefined) return holder;
190
+ return nearest === undefined ? undefined : { kind: "inside", ...nearest };
191
+ }
192
+
193
+ /** A time for the human: `YYYY-MM-DD HH:MM UTC`. */
194
+ function when(ms: number): string {
195
+ const d = new Date(ms);
196
+ return Number.isNaN(d.getTime()) ? "unknown" : `${d.toISOString().slice(0, 16).replace("T", " ")} UTC`;
197
+ }
198
+
199
+ /** A date for the human: `YYYY-MM-DD` (UTC). */
200
+ function day(ms: number): string {
201
+ const d = new Date(ms);
202
+ return Number.isNaN(d.getTime()) ? "unknown" : d.toISOString().slice(0, 10);
203
+ }
204
+
205
+ function usage(sub: "approve" | "revoke"): string {
206
+ return `Usage: /router ${sub} <path> (quote a path with spaces: /router ${sub} "D:\\my repo")`;
207
+ }
208
+
209
+ async function approve(rest: string, opts: RouterApprovalsOptions, platform: NodeJS.Platform): Promise<RouterApprovalsResult> {
210
+ const typed = parseApprovalPath(rest);
211
+ if (typed === undefined) return { text: usage("approve") };
212
+ const shown = displaySafe(typed);
213
+ const deps: InspectDeps = {
214
+ ...(opts.identity ?? {}),
215
+ exclude: opts.exclude,
216
+ platform,
217
+ ...(opts.env === undefined ? {} : { env: opts.env }),
218
+ // S2: what is shown and stored comes from git now, never from a cached inspection.
219
+ fresh: true,
220
+ };
221
+ const found = await inspectCandidate(typed, deps);
222
+ if (typeof found === "string") return { text: `Not approved: ${shown} ${displaySafe(found)}.\nNothing was stored.` };
223
+
224
+ const repo = displaySafe(found.path);
225
+ const relation = parentRelation(found.path, opts, platform);
226
+ if (relation !== undefined) {
227
+ const parent = displaySafe(relation.parent);
228
+ if (relation.kind !== "inside") {
229
+ // The router refuses a root that is or contains a parent, and its approval would be registered wider than the parents.
230
+ return {
231
+ text: `Not approved: ${repo} ${relation.kind === "is" ? "is" : "contains"} routing.repoParents entry ${parent}; `
232
+ + `a repository that is or contains a parent cannot be approved.\nNothing was stored.`,
233
+ };
234
+ }
235
+ const depth = opts.repoDepth;
236
+ if (depth !== undefined && relation.depth > depth) {
237
+ return {
238
+ text: `No approval applies: ${repo} is below ${parent} but deeper than routing.repoDepth (${String(depth)}); `
239
+ + `the router refuses it with or without an approval.\nNothing was stored.`,
240
+ };
241
+ }
242
+ return {
243
+ text: `No approval needed: ${repo} is inside routing.repoParents (${parent}); dispatch with root=${repo}.\nNothing was stored.`,
244
+ };
245
+ }
246
+
247
+ const outcome = await applyApproval(
248
+ { kind: "put", approval: { path: found.path, commonDir: found.commonDir, roots: found.roots, origin: found.origin }, days: opts.days },
249
+ opts.env,
250
+ );
251
+ if (outcome.status !== "written" || outcome.entry === undefined) {
252
+ const why = outcome.status === "refused"
253
+ ? outcome.message
254
+ : `the store was not changed (${outcome.status === "unchanged" ? outcome.reason : "no entry read back"})`;
255
+ return { text: `Not approved: ${repo}: ${displaySafe(why)}.` };
256
+ }
257
+ const entry = outcome.entry;
258
+ const roots = entry.roots.length;
259
+ const cap = entry.approvedAt + REPO_APPROVAL_CAP_DAYS * DAY_MS;
260
+ const lines = [
261
+ `Approved repository ${displaySafe(entry.path)}`,
262
+ ` origin: ${displaySafe(entry.origin)}`,
263
+ ` branch: ${displaySafe(found.branch)} @ ${displaySafe(found.head.slice(0, 12))}`,
264
+ ` roots: ${String(roots)} root commit${roots === 1 ? "" : "s"}`,
265
+ ` expires: ${day(expiresAt(entry, opts.days))} (${String(opts.days)} days after its last use; at the latest ${day(cap)})`,
266
+ `Stored in ${displaySafe(outcome.file)}.`,
267
+ ];
268
+ return { text: lines.join("\n"), change: { kind: "approve", path: entry.path } };
269
+ }
270
+
271
+ /** The `routing.repoExclude` pattern matching the stored path text (as on registration: text only, no filesystem), or undefined. */
272
+ function excludedByText(p: string, exclude: readonly string[], platform: NodeJS.Platform, matches: (input: string, pattern: string) => boolean): string | undefined {
273
+ const win = platform === "win32";
274
+ const forms = win && p.includes("/") ? [p, p.replace(/\//g, "\\")] : [p];
275
+ for (const form of forms) {
276
+ const input = win ? form.toLowerCase() : form;
277
+ const hit = exclude.find((pattern) => pattern.trim() !== "" && matches(input, win ? pattern.toLowerCase() : pattern));
278
+ if (hit !== undefined) return hit;
279
+ }
280
+ return undefined;
281
+ }
282
+
283
+ async function repos(opts: RouterApprovalsOptions, platform: NodeJS.Platform): Promise<RouterApprovalsResult> {
284
+ const read = readApprovals(opts.env);
285
+ const file = displaySafe(read.file);
286
+ if (read.invalid !== undefined) {
287
+ return { text: `The approvals file ${file} is invalid (${displaySafe(read.invalid)}); no approvals apply until it is fixed or removed.` };
288
+ }
289
+ const now = (opts.env?.now ?? Date.now)();
290
+ const lines: string[] = [];
291
+ if (read.approvals.length === 0) lines.push(`No approved repositories (${file}).`);
292
+ else lines.push(`Approved repositories (${file}):`);
293
+ for (const entry of read.approvals) {
294
+ const marks: string[] = [];
295
+ if (!isApprovalValid(entry, opts.days, now)) marks.push("expired");
296
+ const excluded = excludedByText(entry.path, opts.exclude, platform, permissionMatches);
297
+ if (excluded !== undefined) marks.push(`excluded by routing.repoExclude (${displaySafe(excluded)})`);
298
+ lines.push(`- ${displaySafe(entry.path)}${marks.length === 0 ? "" : ` [${marks.join("; ")}]`}`);
299
+ lines.push(` origin: ${displaySafe(entry.origin)}`);
300
+ lines.push(` approved: ${when(entry.approvedAt)}; last used: ${when(entry.lastUsedAt)}; expires: ${when(expiresAt(entry, opts.days))}`);
301
+ }
302
+ if (read.dropped.length > 0) lines.push(`${String(read.dropped.length)} invalid entr${read.dropped.length === 1 ? "y was" : "ies were"} ignored.`);
303
+ return { text: lines.join("\n") };
304
+ }
305
+
306
+ /** The stored approval that `typed` names: by text first (comparison form), then by its realpath. No git. */
307
+ function approvalNamed(approvals: readonly RepoApproval[], typed: string, opts: RouterApprovalsOptions, platform: NodeJS.Platform): RepoApproval | undefined {
308
+ if (!path.isAbsolute(typed)) return undefined;
309
+ const byText = cmpForm(typed, platform);
310
+ const hit = approvals.find((a) => cmpForm(a.path, platform) === byText);
311
+ if (hit !== undefined) return hit;
312
+ const real = realOrUndefined(typed, realpathOf(opts));
313
+ if (real === undefined) return undefined;
314
+ const byReal = cmpForm(real, platform);
315
+ return approvals.find((a) => cmpForm(a.path, platform) === byReal);
316
+ }
317
+
318
+ async function revoke(rest: string, opts: RouterApprovalsOptions, platform: NodeJS.Platform): Promise<RouterApprovalsResult> {
319
+ const typed = parseApprovalPath(rest);
320
+ if (typed === undefined) return { text: usage("revoke") };
321
+ const shown = displaySafe(typed);
322
+ const read = readApprovals(opts.env);
323
+ if (read.invalid !== undefined) {
324
+ return { text: `Not revoked: the approvals file ${displaySafe(read.file)} is invalid (${displaySafe(read.invalid)}); fix or remove it first.` };
325
+ }
326
+ const entry = approvalNamed(read.approvals, typed, opts, platform);
327
+ if (entry === undefined) return { text: `No approval for ${shown}; nothing was changed. /router repos lists the approved repositories.` };
328
+ const outcome = await applyApproval({ kind: "delete", path: entry.path }, opts.env);
329
+ if (outcome.status === "refused") return { text: `Not revoked: ${displaySafe(outcome.message)}.` };
330
+ if (outcome.status === "unchanged") return { text: `No approval for ${shown}; nothing was changed. /router repos lists the approved repositories.` };
331
+ const removed = dropFromWorkingSets(entry.path, platform);
332
+ const repo = displaySafe(entry.path);
333
+ const lines = [
334
+ `Revoked the approval of ${repo}.`,
335
+ removed === 0 ? "It was not in any working set." : `Removed from the working sets (${String(removed)} binding${removed === 1 ? "" : "s"}).`,
336
+ `A new dispatch with root=${repo} is refused.`,
337
+ ];
338
+ return { text: lines.join("\n"), change: { kind: "revoke", path: entry.path } };
339
+ }
340
+
341
+ /**
342
+ * Run `/router approve <path>`, `/router repos` or `/router revoke <path>`; `rest` is the argument text after the subcommand.
343
+ * Never throws: an unexpected error is reported and nothing is stored.
344
+ */
345
+ export async function runRouterApprovals(sub: RouterApprovalSubcommand, rest: string, opts: RouterApprovalsOptions): Promise<RouterApprovalsResult> {
346
+ const platform = opts.platform ?? process.platform;
347
+ try {
348
+ if (sub === "approve") return await approve(rest, opts, platform);
349
+ if (sub === "revoke") return await revoke(rest, opts, platform);
350
+ return await repos(opts, platform);
351
+ } catch (e) {
352
+ return { text: `/router ${sub} failed: ${displaySafe(e instanceof Error ? e.message : String(e))}` };
353
+ }
354
+ }
@@ -228,8 +228,18 @@ export function buildRoleLines(roles: Iterable<RoleSpec>): string[] {
228
228
  return lines.length === 0 ? [] : ["Roles:", ...lines];
229
229
  }
230
230
 
231
+ /**
232
+ * Cross-repo P4.7 (SD-P4-10): the help lines of `/router approve|repos|revoke`, listed only where they run (OpenCode v2, roles
233
+ * mode, `routing.repoParents` non-empty).
234
+ */
235
+ export const ROUTER_APPROVAL_HELP_LINES: readonly string[] = Object.freeze([
236
+ "- `/router approve <path>` — approve a repository outside `routing.repoParents` for role dispatches with `root=<path>` (identity from git; quote a path with spaces)",
237
+ "- `/router repos` — list the approved repositories, their last use and expiry",
238
+ "- `/router revoke <path>` — remove an approval and drop the repository from every working set",
239
+ ]);
240
+
231
241
  /** Bare `/router`. */
232
- export function buildRouterHelp(current: string, options: { stats?: boolean; roles?: Iterable<RoleSpec> } = {}): string {
242
+ export function buildRouterHelp(current: string, options: { stats?: boolean; roles?: Iterable<RoleSpec>; approvals?: boolean } = {}): string {
233
243
  const roleLines = options.roles === undefined ? [] : buildRoleLines(options.roles);
234
244
  return [
235
245
  `# Model Router`,
@@ -242,6 +252,7 @@ export function buildRouterHelp(current: string, options: { stats?: boolean; rol
242
252
  ...(options.stats === true
243
253
  ? ["- `/router stats [--since <ISO>]` — routing statistics from the decision log and outcome store (same table as `npm run routing:stats` (in a clone))"]
244
254
  : []),
255
+ ...(options.approvals === true ? ROUTER_APPROVAL_HELP_LINES : []),
245
256
  "- `/tiers`, `/preset`, `/budget`, `/bypass`, `/annotate-plan`",
246
257
  ...(roleLines.length > 0 ? ["", ...roleLines] : []),
247
258
  ].join("\n");