@omacode/micromanager 0.0.0-stage → 0.1.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 (109) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +27 -2
  3. package/evolver/mm_evolve/__init__.py +1 -0
  4. package/evolver/mm_evolve/entry.py +3 -0
  5. package/evolver/mm_evolve/evaluator.py +119 -0
  6. package/evolver/mm_evolve/llm.py +76 -0
  7. package/evolver/mm_evolve/run.py +89 -0
  8. package/evolver/mm_evolve/spec.py +62 -0
  9. package/evolver/pyproject.toml +21 -0
  10. package/evolver/uv.lock +772 -0
  11. package/package.json +55 -4
  12. package/skills/THIRD_PARTY.md +58 -0
  13. package/skills/code-review/SKILL.md +46 -0
  14. package/skills/deliberate/SKILL.md +39 -0
  15. package/skills/diagnosing-bugs/SKILL.md +75 -0
  16. package/skills/receiving-code-review/SKILL.md +36 -0
  17. package/skills/research/SKILL.md +18 -0
  18. package/skills/tdd/SKILL.md +56 -0
  19. package/skills/tdd/mocking.md +59 -0
  20. package/skills/tdd/tests.md +77 -0
  21. package/skills/verification-before-completion/SKILL.md +50 -0
  22. package/src/agenda.ts +56 -0
  23. package/src/agents.ts +74 -0
  24. package/src/ask.ts +243 -0
  25. package/src/backends.ts +144 -0
  26. package/src/backlog.ts +436 -0
  27. package/src/bench.ts +163 -0
  28. package/src/board.ts +1 -0
  29. package/src/brief.ts +151 -0
  30. package/src/browser.ts +624 -0
  31. package/src/budget.ts +73 -0
  32. package/src/catalog.ts +214 -0
  33. package/src/checkchange.ts +180 -0
  34. package/src/checkpoint.ts +99 -0
  35. package/src/cli.ts +117 -0
  36. package/src/compact.ts +162 -0
  37. package/src/config.ts +340 -0
  38. package/src/context/capture.ts +1 -0
  39. package/src/context/digest.ts +1 -0
  40. package/src/context/embed.ts +1 -0
  41. package/src/context/index.ts +2 -0
  42. package/src/context/ledger.ts +1 -0
  43. package/src/context/manager.ts +1 -0
  44. package/src/context/memory.ts +1 -0
  45. package/src/context/policy.ts +1 -0
  46. package/src/context/prices.ts +1 -0
  47. package/src/context/recall.ts +1 -0
  48. package/src/context/rules.ts +1 -0
  49. package/src/context/search.ts +1 -0
  50. package/src/context/status.ts +1 -0
  51. package/src/context/store.ts +1 -0
  52. package/src/context/summary.ts +1 -0
  53. package/src/context/tokens.ts +1 -0
  54. package/src/context/tools.ts +1 -0
  55. package/src/continuation.ts +122 -0
  56. package/src/contract.ts +342 -0
  57. package/src/contractround.ts +225 -0
  58. package/src/control.ts +1 -0
  59. package/src/dataset.ts +133 -0
  60. package/src/decide.ts +690 -0
  61. package/src/eval.ts +66 -0
  62. package/src/evolver.ts +369 -0
  63. package/src/followups.ts +50 -0
  64. package/src/forms.ts +191 -0
  65. package/src/gate.ts +90 -0
  66. package/src/grants.ts +239 -0
  67. package/src/graph.ts +74 -0
  68. package/src/guard/index.ts +1 -0
  69. package/src/guard/wire.ts +1 -0
  70. package/src/helpers.ts +105 -0
  71. package/src/hooks.ts +199 -0
  72. package/src/integration.ts +4 -0
  73. package/src/jev.ts +141 -0
  74. package/src/journal.ts +1 -0
  75. package/src/look.ts +390 -0
  76. package/src/memory.ts +1 -0
  77. package/src/native.ts +2455 -0
  78. package/src/nogit.ts +112 -0
  79. package/src/outcomes.ts +210 -0
  80. package/src/pick.ts +112 -0
  81. package/src/pipelines.ts +252 -0
  82. package/src/plan.ts +449 -0
  83. package/src/plugin.ts +3187 -0
  84. package/src/policy.ts +84 -0
  85. package/src/pools.ts +1 -0
  86. package/src/profile.ts +186 -0
  87. package/src/progress.ts +1 -0
  88. package/src/redact.ts +1 -0
  89. package/src/registry.ts +207 -0
  90. package/src/roles.ts +1 -0
  91. package/src/routing.ts +1 -0
  92. package/src/runner.ts +1506 -0
  93. package/src/sandbox.ts +4 -0
  94. package/src/scheduler.ts +200 -0
  95. package/src/session.ts +269 -0
  96. package/src/shell/decide.ts +1 -0
  97. package/src/shell/index.ts +2 -0
  98. package/src/shell/sandbox.ts +1 -0
  99. package/src/shell/wire.ts +1 -0
  100. package/src/skills.ts +111 -0
  101. package/src/state.ts +1 -0
  102. package/src/store.ts +1 -0
  103. package/src/switcher.ts +1 -0
  104. package/src/tools.ts +480 -0
  105. package/src/trials.ts +247 -0
  106. package/src/usage.ts +1 -0
  107. package/src/wait.ts +180 -0
  108. package/src/watchdog.ts +498 -0
  109. package/src/worktree/git.ts +378 -0
package/src/decide.ts ADDED
@@ -0,0 +1,690 @@
1
+ // Every permission request goes to Jev first. Jev answers it itself when it is sure enough for the request's
2
+ // risk and nothing says the user must decide; everything else goes to the user unchanged.
3
+ //
4
+ // Order: hard rules (never automatic) -> the job's own area -> Jev -> floors per risk class. Without Jev (no key,
5
+ // an error) the request goes to the user: nothing is decided on a guess.
6
+ //
7
+ // A shell request that only reads inside the job's own worktree skips Jev entirely (readsOnlyInside): a worker
8
+ // cannot change anything with it, and its own confidence on `git status --porcelain` (0.75) sits below the read
9
+ // floor (0.80), so asking only turned inspection into denials. A writer's command that stays in its own task worktree
10
+ // skips Jev too (staysInWorktree), and a reader's command that does not only read is refused without asking.
11
+ //
12
+ // external_directory is layered, not a blanket "never":
13
+ // 1. a hard rule no layer can pass: the user's keys and credential stores, their home itself, the system
14
+ // directories, the secret files inside ~/.config, another job's branch in the repository's own git data. The
15
+ // user's `allowOutside` setting is the one thing that lifts it, and only for the paths it names (below);
16
+ // 2. the job's own area: any worktree under <project>/.micromanager/worktrees/, this job's integration
17
+ // worktree included. Path-based, never a substring: `worktrees-old` is not `worktrees`;
18
+ // 3. task-vouched: a path the task text names with its full path, for a read only (a named path is a vouch for
19
+ // reading it, not for changing it);
20
+ // 4. everything else is the user, as it always was.
21
+
22
+ import { execFileSync } from "node:child_process"
23
+ import { existsSync } from "node:fs"
24
+ import { homedir } from "node:os"
25
+ import { basename, dirname, isAbsolute, join, normalize } from "node:path"
26
+
27
+ import type { Decision, Jev, Question } from "./jev.ts"
28
+ import { WRITERS } from "./profile.ts"
29
+ import { MICROMANAGER, roleByAgent } from "./roles.ts"
30
+ import { stateDir } from "./store.ts"
31
+
32
+ export interface PermissionRequest {
33
+ readonly sessionID: string
34
+ readonly agent: string // the agent asking: "micromanager", "coder", …
35
+ readonly action: string // "shell", "edit", "subagent", "external_directory", …
36
+ readonly resources: readonly string[] // commands, paths, or the sub-agent to start
37
+ readonly directory?: string
38
+ readonly task?: string // what the asking agent is working on, when known
39
+ }
40
+
41
+ export type Verdict = "allow" | "deny" | "user"
42
+
43
+ export interface Outcome {
44
+ readonly verdict: Verdict
45
+ readonly reason: string
46
+ readonly confidence?: number
47
+ readonly probability?: number // Jev's probability of the chosen option, logged next to its confidence
48
+ readonly risk?: number
49
+ readonly needsUser?: number
50
+ readonly latencyMs?: number
51
+ }
52
+
53
+ export interface Floors {
54
+ readonly read: number // reading, searching, docs on the web
55
+ readonly write: number // changes inside the project, running commands, starting a worker
56
+ readonly needsUser: number // at or above: the user decides
57
+ readonly risk: number // Jev's risk score (0 read … 2 irreversible) at or above: the user decides
58
+ }
59
+
60
+ // write 0.85: live a test sub-agent's pytest runs scored 0.82, so 0.92 sent every test run to the user; the
61
+ // destructive cases are caught before (hard rules) and beside it (needs_user, risk).
62
+ export const DEFAULT_FLOORS: Floors = { read: 0.8, write: 0.85, needsUser: 0.5, risk: 1.5 }
63
+
64
+ const READ_ACTIONS = new Set(["read", "glob", "grep", "list", "webfetch", "websearch", "lsp", "skill", "question"])
65
+
66
+ // Never decided by Jev, whatever it says. The user's allowOutside is passed to every test, so a path the user named
67
+ // falls through to the layers below instead of stopping here.
68
+ const ALWAYS_USER: readonly { readonly test: (r: PermissionRequest, allowed: readonly string[]) => boolean; readonly why: string }[] = [
69
+ {
70
+ test: (r, allowed) => r.action === "external_directory" && r.resources.some((p) => forbiddenOutside(p, allowed)),
71
+ why: "a path no layer may allow",
72
+ },
73
+ { test: (r) => r.action === "read" && r.resources.some((p) => /(^|\/)\.env(\.|$)/.test(p) && !p.endsWith(".example")), why: "a .env file" },
74
+ {
75
+ test: (r) =>
76
+ r.action === "shell" &&
77
+ r.resources.some((c) =>
78
+ /\bgit\s+(push|reset\s+--hard|clean\s+-[a-z]*f)|\bsudo\b|\bmkfs|\bdd\s+if=|\bchmod\s+-R|\bcurl\b[^|]*\|\s*(ba|z)?sh|\bwget\b[^|]*\|\s*(ba|z)?sh/.test(c) ||
79
+ removesOutside(c),
80
+ ),
81
+ why: "a destructive or irreversible command",
82
+ },
83
+ { test: (r) => r.action === "shell" && r.resources.some(installsIntoSystem), why: "installs software into the system" },
84
+ ]
85
+
86
+ // Package installs outside the project's own environment (a venv, node_modules) change the machine.
87
+ export function installsIntoSystem(command: string): boolean {
88
+ if (/\b(pacman|yay|paru|apt(-get)?|dnf|brew|snap|flatpak)\s+(-S\b|install\b)/.test(command)) return true
89
+ if (/\bnpm\s+(i|install)\s+(-g|--global)\b/.test(command) || /\b(cargo|go)\s+install\b/.test(command)) return true
90
+ for (const match of command.matchAll(/(\S*?)\b(pip3?|python3?\s+-m\s+pip)\s+install\b/g)) {
91
+ const prefix = match[1] ?? ""
92
+ if (!/venv|\.venv|\/env\//.test(prefix) && !/\buv\s+pip\b/.test(command)) return true
93
+ }
94
+ return false
95
+ }
96
+
97
+ // `rm -r`/`rm -f` on an absolute path, the home directory, a parent directory or a bare wildcard; a relative
98
+ // path inside the project (a cache, a build directory) is left to Jev.
99
+ // The targets of each `rm -r`/`rm -f` in a command line (an empty list: an `rm` without a target).
100
+ export function rmTargets(command: string): string[][] {
101
+ const out: string[][] = []
102
+ for (const match of command.matchAll(/\brm\s+((?:-[a-zA-Z]+(?:\s+|$))+)([^;&|]*)/g)) {
103
+ if (!/[rRf]/.test(match[1] ?? "")) continue
104
+ out.push((match[2] ?? "").trim().split(/\s+/).filter(Boolean))
105
+ }
106
+ return out
107
+ }
108
+
109
+ const OUTSIDE = (t: string) => /^(\/|~|\$HOME|\.\.|\*$|\.$|\.\/?\*?$)/.test(t) || t.includes("/../")
110
+
111
+ export function removesOutside(command: string): boolean {
112
+ return rmTargets(command).some((targets) => targets.length === 0 || targets.some(OUTSIDE))
113
+ }
114
+
115
+ // What git and the file system say about a path the command wants to delete (relative to the project).
116
+ export interface PathFacts {
117
+ readonly path: string
118
+ readonly exists: boolean
119
+ readonly tracked: boolean | undefined // undefined: not a git repository, so nobody knows
120
+ readonly ignored: boolean | undefined
121
+ }
122
+
123
+ export type Inspect = (directory: string, paths: readonly string[]) => PathFacts[]
124
+
125
+ export const inspectPaths: Inspect = (directory, paths) => {
126
+ const git = (args: string[]): { ok: boolean; out: string } => {
127
+ try {
128
+ return { ok: true, out: execFileSync("git", ["-C", directory, ...args], { encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] }) }
129
+ } catch {
130
+ return { ok: false, out: "" }
131
+ }
132
+ }
133
+ const repo = git(["rev-parse", "--is-inside-work-tree"]).out.trim() === "true"
134
+ return paths.map((path) => ({
135
+ path,
136
+ exists: existsSync(isAbsolute(path) ? path : join(directory, path)),
137
+ tracked: repo ? git(["ls-files", "--", path]).out.trim() !== "" : undefined,
138
+ ignored: repo ? git(["check-ignore", "-q", "--", path]).ok : undefined,
139
+ }))
140
+ }
141
+
142
+ function relevanceFacts(facts: readonly PathFacts[]): string {
143
+ const say = (f: PathFacts) =>
144
+ `- ${f.path}: ${f.exists ? "exists" : "does not exist"}, ${f.tracked ? "under version control" : "not under version control"}, ${f.ignored ? "ignored by git (.gitignore)" : "not ignored by git"}`
145
+ return `Paths the command deletes:\n${facts.map(say).join("\n")}`
146
+ }
147
+
148
+ const HOME = homedir()
149
+ // Directories outside the project that no layer may allow, each named with what it holds. These are refused whole
150
+ // because nearly everything inside them is a secret, so a per-file rule would be theatre: .ssh, .aws and .gnupg are
151
+ // private keys, .netrc and the keyring are logins, .password-store is a password database.
152
+ //
153
+ // ~/.config is deliberately NOT on this list. It holds application configuration as much as tokens — 61 application
154
+ // directories on the user's own machine and not one file matching the names the old whole-directory ban claimed to
155
+ // protect — and refusing it whole made a real task impossible (2026-10-07: a worker could not read
156
+ // ~/.config/omarchy/shell.json for the plugin id that decides whether a system service restarts in a loop). What is
157
+ // refused there is the secret files themselves, below, at the granularity that actually protects them.
158
+ const FORBIDDEN_OUTSIDE: readonly { readonly dir: string; readonly what: string }[] = [
159
+ { dir: join(HOME, ".ssh"), what: "the user's keys in ~/.ssh" },
160
+ { dir: join(HOME, ".aws"), what: "the user's AWS credentials in ~/.aws" },
161
+ { dir: join(HOME, ".gnupg"), what: "the user's GPG keys in ~/.gnupg" },
162
+ { dir: join(HOME, ".password-store"), what: "the user's password store in ~/.password-store" },
163
+ { dir: join(HOME, ".local", "share", "keyrings"), what: "the user's keyring in ~/.local/share/keyrings" },
164
+ { dir: join(HOME, ".netrc"), what: "the user's login credentials in ~/.netrc" },
165
+ // The system itself. /var and /sys stay whole on purpose: they are read-mostly, so refusing them costs a worker
166
+ // little (nothing a task needs lives only there, and a reading tool asks about a file it names), while narrowing
167
+ // them to a file list would mean guessing at every package's and the kernel's own state files.
168
+ { dir: "/etc", what: "the system directory /etc" },
169
+ { dir: "/usr", what: "the system directory /usr" },
170
+ { dir: "/boot", what: "the system directory /boot" },
171
+ { dir: "/var", what: "the system directory /var" },
172
+ { dir: "/proc", what: "the system directory /proc" },
173
+ { dir: "/sys", what: "the system directory /sys" },
174
+ ]
175
+
176
+ // The secret files inside ~/.config, matched case-insensitively against the LAST path segment only. The segment is the
177
+ // point: `*token*` is a rule about a file's own name (huggingface_token, .netrc_token, a service-token.json), not about
178
+ // a directory that happens to contain the word somewhere in its parents — a directory called token-store is a config
179
+ // directory, and refusing it would reproduce the bug this list replaces.
180
+ const SECRET_IN_CONFIG: readonly RegExp[] = [
181
+ /^auth\.json$/, // opencode's own stored credentials
182
+ /^credentials(\..*)?$/, // ~/.aws/credentials' shape, and the git-credential-store default
183
+ /^\.credentials$/, // python keyring's file of the same name
184
+ /^hosts\.yml$/, // the GitHub CLI's token store
185
+ /^logins\.json$/, // a Firefox profile's saved logins
186
+ /^key[34]\.db$/, // Firefox's own key databases
187
+ /\.kdbx$/, // keepass databases
188
+ /token/, // huggingface_token, *-token.json, .token
189
+ /_token$/, // the explicit spelling of the same, kept so the rule reads as one rule per convention
190
+ /\.secret$/, // *.secret, and npm's own .npmrc-adjacent secrets
191
+ /^secrets\./, // secrets.json, secrets.yaml, secrets.toml
192
+ ]
193
+
194
+ // Another job's worktree metadata and branches live under .git/; a worker never reaches them, whatever its task says.
195
+ const GIT_DATA = /(^|\/)\.git\/(worktrees|refs)\//
196
+
197
+ // What the journal and the refusal messages call the user's own setting, so every layer words it the same way.
198
+ export const ALLOW_OUTSIDE_REASON = "the user's allowOutside setting"
199
+
200
+ // What the journal says when the user opened one refused path for one job, and when they turned it down. Both name the
201
+ // user on purpose: a record that only said "allowed" or "denied" would read as though nothing had ever been wrong,
202
+ // and an operator reading the journal after the fact could not tell a rule from an exception to it.
203
+ export const GRANT_OUTSIDE_REASON = "the user opened this path for this job"
204
+ export const REFUSED_OUTSIDE_REASON = "the user refused this path for this job"
205
+
206
+ // The user's own `allowOutside` setting: absolute paths or path prefixes the user has decided a worker may reach, even
207
+ // where the rules above refuse. Matching is on whole segments like every other path rule here, so an entry never opens
208
+ // a sibling that merely shares its name (/home/u/.config-x is not /home/u/.config), and the entries are compared
209
+ // through the same normalisation, so `~`, a trailing slash and `..` cannot smuggle a path past a rule.
210
+ export function allowedOutside(resource: string, allowed: readonly string[] = []): boolean {
211
+ const path = normalizeOutside(resource)
212
+ if (path.length === 0 || path === ".") return false
213
+ return allowed.some((entry) => {
214
+ const base = normalizeOutside(entry)
215
+ return base.length > 0 && under(path, base)
216
+ })
217
+ }
218
+
219
+ // `~` expanded, a trailing `/*` or `/` dropped, `..` resolved lexically. No filesystem access: a path that does not
220
+ // exist yet has to be classified the same way as one that does.
221
+ //
222
+ // Exported because a grant the user gave is remembered as a path, and the only thing that may decide whether a later
223
+ // request is "the same path" is the same normalisation the rules use. A second copy here would drift from it.
224
+ export function normalizeOutside(path: string): string {
225
+ const trimmed = path.trim()
226
+ const bare = trimmed.replace(/\/+$/, "").replace(/(?<=[^/])\/\*+$/, "")
227
+ const expanded = bare === "~" ? HOME : bare.startsWith("~/") ? join(HOME, bare.slice(2)) : bare
228
+ return expanded.length === 0 ? trimmed : normalize(expanded)
229
+ }
230
+
231
+ function under(path: string, base: string): boolean {
232
+ if (base === "/") return path.startsWith("/")
233
+ return path === base || path.startsWith(`${base}/`)
234
+ }
235
+
236
+ // The user's own `allowOutside`, checked first: it is the one thing that lifts the rules below, and it is only ever the
237
+ // user's own list, never a task's or a vouch's. A refusal that survives it survives everything.
238
+ export function forbiddenOutside(resource: string, allowed: readonly string[] = []): boolean {
239
+ if (allowedOutside(resource, allowed)) return false
240
+ const path = normalizeOutside(resource)
241
+ if (path === "/") return true // the whole file system
242
+ if (path.length === 0 || path === ".") return false
243
+ // The home directory itself stays refused whatever the per-path rules above say: a request for `~` is a request to
244
+ // sweep everything in it at once, and the rules for its subdirectories are no answer to that. Naming `~` in
245
+ // allowOutside is the one way past it, and only because the user wrote it down.
246
+ if (path === HOME) return true
247
+ if (FORBIDDEN_OUTSIDE.some((f) => under(path, f.dir))) return true
248
+ // ~/.config is not refused whole; its secret files are, by name, last segment only.
249
+ if (under(path, join(HOME, ".config")) && SECRET_IN_CONFIG.some((pattern) => pattern.test(basename(path).toLowerCase()))) return true
250
+ return GIT_DATA.test(path)
251
+ }
252
+
253
+ // Why a refusal is written down with, or undefined when nothing refuses the path: what the rule protects, and for a
254
+ // secret file the file's own name, so a worker is told which file was the problem rather than being told about a whole
255
+ // directory. undefined rather than a wrong sentence, so a caller cannot put a reason on a path no rule refused.
256
+ export function forbiddenOutsideWhat(resource: string): string | undefined {
257
+ const path = normalizeOutside(resource)
258
+ if (path === "/") return "the whole file system"
259
+ if (path === HOME) return "the home directory itself"
260
+ const dir = FORBIDDEN_OUTSIDE.find((f) => under(path, f.dir))
261
+ if (dir) return dir.what
262
+ const config = join(HOME, ".config")
263
+ if (under(path, config)) {
264
+ const name = basename(path).toLowerCase()
265
+ if (SECRET_IN_CONFIG.some((pattern) => pattern.test(name))) return `${name}, a credential file in ~/.config`
266
+ }
267
+ if (GIT_DATA.test(path)) return "another job's branches and worktree metadata in the repository's own git data"
268
+ return undefined
269
+ }
270
+
271
+ export function hardRule(request: PermissionRequest, allowed: readonly string[] = []): string | undefined {
272
+ return ALWAYS_USER.find((rule) => rule.test(request, allowed))?.why
273
+ }
274
+
275
+ const READ_PROGRAMS = new Set([
276
+ "ls", "cat", "head", "tail", "wc", "sort", "uniq", "grep", "rg", "which", "command", "type", "echo", "printf", "pwd", "file",
277
+ "stat", "du", "df", "tree", "diff", "cut", "tr", "basename", "dirname", "realpath", "env", "date", "true", "test", "[",
278
+ // Reading programs a worker reaches for constantly (a live run denied 67 read-only commands without these).
279
+ "sed", "awk", "jq", "md5sum", "sha256sum", "xxd", "od", "column", "comm", "nl", "fold", "tac", "expr", "seq",
280
+ ])
281
+ // A reading program with a writing form: `sed -i` rewrites the file, `awk -i inplace` (gawk) does the same,
282
+ // `find -delete`/`-exec` change or run things, and `sort -o` writes its output to a file. The flag decides, not the
283
+ // program.
284
+ const MUTATING: readonly [string, RegExp][] = [
285
+ ["sed", /(^|\s)-{1,2}(i\b|i\.\w|in-place\b)/],
286
+ ["awk", /(^|\s)-{1,2}(i\b|in-place\b)/],
287
+ ["find", /(^|\s)-(delete|exec|execdir|ok|fprint)\w*/],
288
+ ["sort", /(^|\s)-{1,2}(o\S*|output)/],
289
+ ]
290
+ // git's read subcommands. Everything else (add, commit, checkout, reset, stash, push, fetch, …) writes, so an
291
+ // unknown subcommand is a write: the list is a whitelist, not a blacklist.
292
+ const GIT_READS = new Set([
293
+ "status", "diff", "log", "show", "branch", "ls-files", "rev-parse", "blame", "ls-tree", "cat-file", "merge-base",
294
+ "describe", "for-each-ref", "shortlog", "rev-list", "diff-tree", "whatchanged", "name-rev", "var", "count-objects",
295
+ "show-ref", "check-ignore", "check-attr", "grep",
296
+ ])
297
+ // Global git flags that carry a value: the subcommand only starts after them.
298
+ const GIT_VALUE_FLAGS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--config-env"])
299
+ const VERSION = /^\S+\s+(--version|-V|version)\b/
300
+ const ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/
301
+ const REDIRECT = /(^|\s)(\d?>>?|&>)\s*(\/dev\/null|&\d|\d)/
302
+ // A redirect to a real path writes it, so it belongs to a write even when the program only reads.
303
+ const WRITING_REDIRECT = /(^|\s)(\d?>>?|&>)\s*(?!\/dev\/null\b|&\d\b|\d\b)\S/
304
+
305
+ // Wrappers that only run the command behind them. Their own arguments are dropped so the wrapped command decides:
306
+ // `timeout 120 pytest` is a write (pytest reads nothing), `timeout 120 git status` a read. `env` is in the list
307
+ // because `env rm -rf …` runs rm; a bare `env` prints the environment and stays a read.
308
+ const TIMEOUT_VALUE_FLAGS = new Set(["-k", "--kill-after", "-s", "--signal"])
309
+ const WRAPPERS: Record<string, (args: readonly string[]) => number> = {
310
+ timeout: (args) => {
311
+ let i = 1
312
+ while (i < args.length && (args[i] ?? "").startsWith("-")) i += TIMEOUT_VALUE_FLAGS.has(args[i]!) ? 2 : 1
313
+ return i + 1 // the duration, then the command
314
+ },
315
+ nohup: (args) => (args[1]?.startsWith("--") ? 2 : 1),
316
+ nice: (args) => (args[1] === "-n" ? 3 : args[1]?.startsWith("-") ? 2 : 1),
317
+ stdbuf: (args) => (args[1] && /^-[ioe]$/.test(args[1]) ? 3 : args[1]?.startsWith("-") ? 2 : 1),
318
+ env: (args) => {
319
+ let i = 1
320
+ while (i < args.length && (ENV_ASSIGNMENT.test(args[i] ?? "") || (args[i] ?? "").startsWith("-"))) i++
321
+ return i
322
+ },
323
+ }
324
+
325
+ // The command that actually runs, behind any wrapper and any leading VAR=value assignments.
326
+ function unwrap(tokens: readonly string[]): readonly string[] {
327
+ let rest = tokens
328
+ for (;;) {
329
+ while (rest.length > 0 && ENV_ASSIGNMENT.test(rest[0] ?? "")) rest = rest.slice(1)
330
+ const program = (rest[0] ?? "").replace(/^.*\//, "")
331
+ const consumed = WRAPPERS[program]?.(rest) ?? 0
332
+ if (consumed <= 0 || consumed >= rest.length) return rest
333
+ rest = rest.slice(consumed)
334
+ }
335
+ }
336
+
337
+ // Where git's subcommand starts, behind the global flags: `git -C /repo status`, `git --no-pager diff`,
338
+ // `git -c user.name=x commit`.
339
+ function gitSubcommand(tokens: readonly string[]): number {
340
+ let i = 1 // tokens[0] is git
341
+ while (i < tokens.length && (tokens[i] ?? "").startsWith("-")) {
342
+ i += GIT_VALUE_FLAGS.has(tokens[i]!) && !(tokens[i] ?? "").includes("=") ? 2 : 1
343
+ }
344
+ return i
345
+ }
346
+
347
+ // git reads when its subcommand only reads. `remote` and `branch` read while they only look: `git branch new`
348
+ // creates one and `git remote add` writes, so a bare word behind them is a write.
349
+ function gitReads(tokens: readonly string[], at: number): boolean {
350
+ const sub = tokens[at] ?? ""
351
+ const rest = tokens.slice(at + 1)
352
+ if (sub === "remote" || sub === "branch") return rest.every((token) => token.startsWith("-"))
353
+ if (sub === "worktree") return rest[0] === "list"
354
+ if (sub === "reflog") return rest.length === 0 || rest[0] === "show" || rest[0]!.startsWith("-")
355
+ return GIT_READS.has(sub)
356
+ }
357
+
358
+ // One `&&`, `||`, `;` or `|` step of a command line: every step has to read for the line to read. Splitting after the
359
+ // redirects are stripped, so `2>&1` is not an `&&`.
360
+ export function segments(command: string): string[] {
361
+ return command
362
+ .trim()
363
+ .split(/(?:&&|\|\||;|\|)/)
364
+ .map((part) => part.trim())
365
+ .filter(Boolean)
366
+ }
367
+
368
+ function readsSegment(segment: string): boolean {
369
+ // A command substitution can hide anything, so a line that carries one is not classified as a read.
370
+ if (/\$\(|`/.test(segment)) return false
371
+ if (WRITING_REDIRECT.test(segment)) return false
372
+ const command = segment.replace(REDIRECT, "$1$2$3")
373
+ const tokens = unwrap(command.split(/\s+/).filter(Boolean))
374
+ const program = (tokens[0] ?? "").replace(/^.*\//, "")
375
+ if (program === "git") {
376
+ const at = gitSubcommand(tokens)
377
+ return at < tokens.length && gitReads(tokens, at)
378
+ }
379
+ const mutating = MUTATING.find(([name]) => name === program)
380
+ if (mutating) return !mutating[1].test(command)
381
+ return READ_PROGRAMS.has(program) || VERSION.test(command)
382
+ }
383
+
384
+ // A shell request that only reads: every resource, and every step inside each resource, is a known reading program
385
+ // (OpenCode passes a pipe or a chain as several resources, one segment each).
386
+ export function readsOnly(commands: readonly string[]): boolean {
387
+ return commands.length > 0 && commands.every((raw) => {
388
+ const parts = segments(raw)
389
+ return parts.length > 0 && parts.every(readsSegment)
390
+ })
391
+ }
392
+
393
+ // Every absolute path the command mentions, after the same lexical normalisation readsOnly uses.
394
+ export function absolutePaths(command: string): string[] {
395
+ return command
396
+ .split(/\s+/)
397
+ .map((token) => normalizeOutside(token.replace(/^--?[\w-]+=/, "")))
398
+ .filter((token) => isAbsolute(token))
399
+ }
400
+
401
+ // A read that stays inside the job's own area: nothing can change, and the paths it names cannot leave the
402
+ // worktree, so it needs no Jev and no user. Relative paths are the worker's own directory by definition.
403
+ export function readsOnlyInside(request: PermissionRequest, root: string): boolean {
404
+ if (request.action !== "shell") return false
405
+ const area = normalizeOutside(root)
406
+ if (area.length === 0) return false
407
+ return (
408
+ readsOnly(request.resources) &&
409
+ request.resources.every((command) => absolutePaths(command).every((path) => under(path, area)))
410
+ )
411
+ }
412
+
413
+ // The task worktree a directory lies in (<project>/.micromanager/worktrees/<job>--T<id>, or .jev-micromanager in a
414
+ // project from before the rename), or undefined. Only a task's
415
+ // own worktree, never the job's integration worktree: that one is the merge train's target and the readers' tree, so
416
+ // nothing may change it outside a merge. A project inside a larger repository works in <worktree>/<rel>; the area is
417
+ // the whole worktree either way.
418
+ const TASK_WORKTREE = /^(.*\/\.(?:jev-)?micromanager\/worktrees\/[^/]+--T[\w.]+)(?:\/|$)/
419
+
420
+ export function taskWorktree(directory: string | undefined): string | undefined {
421
+ return directory ? normalizeOutside(directory).match(TASK_WORKTREE)?.[1] : undefined
422
+ }
423
+
424
+ // Programs whose effect reaches past the worktree whatever their arguments say: other processes, services, the
425
+ // network, the desktop, the user's accounts.
426
+ const BEYOND_WORKTREE = new Set([
427
+ "kill", "pkill", "killall", "systemctl", "journalctl", "loginctl", "crontab", "at", "docker", "podman", "ssh", "scp",
428
+ "sftp", "rsync", "curl", "wget", "nc", "ncat", "socat", "shutdown", "reboot", "poweroff", "mount", "umount", "chown",
429
+ "su", "doas", "xdg-open", "open", "notify-send", "hyprctl", "gh", "flatpak", "snap",
430
+ ])
431
+ // git inside a worktree: reading, and changing the working tree and the index. The refs, the stash and the config are
432
+ // shared with the user's checkout and every other worktree, so commit, checkout, branch, reset, stash, fetch, … stay Jev's.
433
+ // `branch` and `remote` are left to gitReads, which tells `git branch` from `git branch -D x` by the arguments.
434
+ const GIT_IN_WORKTREE = new Set([...[...GIT_READS].filter((sub) => sub !== "branch" && sub !== "remote"), "add", "restore", "rm", "mv", "apply", "grep", "check-ignore", "ls-tree", "cat-file"])
435
+ const PUBLISH = /\b(npm|pnpm|yarn|cargo|twine|gem|poetry|uv)\s+(publish|upload|login|adduser)\b/
436
+ // Paths outside the worktree that a command may still name: scratch space and the standard streams.
437
+ const SCRATCH = ["/tmp", "/dev/null", "/dev/stdout", "/dev/stderr"]
438
+
439
+ // A command a writer runs in its own task worktree that stays there: every path it names is inside the worktree or
440
+ // scratch space, it names no home directory, and no step is a program that acts beyond the tree (processes, services,
441
+ // network, publishing) or a git command that moves shared refs. What it does is the worker's business: the worktree is a
442
+ // throwaway checkout, and only the task's checks and the merge train bring its content anywhere. This judges the command
443
+ // line, not what a program does once it runs, exactly as the test-runner allow rules do: running the project's own code
444
+ // is what a writer is for.
445
+ //
446
+ // cwd is the directory the worker runs in, which for a project below the repository root is <worktree>/<rel>: a `..`
447
+ // there can stay in the worktree (`../.venv/bin/python`), so a relative path is resolved against it. A `cd` anywhere in
448
+ // the request makes that guess unsafe, and then any `..` leaves the fast path.
449
+ export function staysInWorktree(request: PermissionRequest, worktree: string, cwd: string = worktree): boolean {
450
+ if (request.action !== "shell" || request.resources.length === 0) return false
451
+ const area = normalizeOutside(worktree)
452
+ if (area.length === 0) return false
453
+ const allowed = (path: string) => under(path, area) || SCRATCH.some((dir) => path === dir || under(path, dir))
454
+ const moves = request.resources.some((command) => segments(command).some((segment) => /^cd(\s|$)/.test(segment)))
455
+ // One argument as a path, or undefined when it is none. A lone "/" or "//" is a division or a comment in inline code
456
+ // (`node -e '… r) / f'`, live run 2026-10-13) or a pattern (`grep -E "^ /"`), never a path a command works in.
457
+ const pathOf = (token: string): string | undefined => {
458
+ const value = token.startsWith("-") && token.includes("=") ? token.slice(token.indexOf("=") + 1) : token
459
+ const bare = value.replace(/^['"(]+|['",;)]+$/g, "")
460
+ if (/^\/+$/.test(bare)) return undefined
461
+ if (isAbsolute(bare)) return normalizeOutside(bare)
462
+ if (/(^|\/)\.\.(\/|$)/.test(bare)) return moves ? "/" : normalize(join(cwd, bare))
463
+ return undefined
464
+ }
465
+ return request.resources.every((command) => {
466
+ if (PUBLISH.test(command)) return false
467
+ if (/(^|[\s"'=:])(~|\$\{?HOME\b)/.test(command)) return false
468
+ return segments(command).every((segment) => {
469
+ const tokens = unwrap(segment.split(/\s+/).filter(Boolean))
470
+ const program = (tokens[0] ?? "").replace(/^.*\//, "")
471
+ if (BEYOND_WORKTREE.has(program) || program.startsWith("omarchy")) return false
472
+ if (program === "git") {
473
+ const at = gitSubcommand(tokens)
474
+ if (!GIT_IN_WORKTREE.has(tokens[at] ?? "") && !gitReads(tokens, at)) return false
475
+ }
476
+ // The program itself may live anywhere (/usr/bin/python3); its arguments may not.
477
+ return tokens.slice(1).every((token) => {
478
+ const path = pathOf(token)
479
+ return path === undefined || allowed(path)
480
+ })
481
+ })
482
+ })
483
+ }
484
+
485
+ export function riskClass(request: PermissionRequest): "read" | "write" {
486
+ if (READ_ACTIONS.has(request.action)) return "read"
487
+ return request.action === "shell" && readsOnly(request.resources) ? "read" : "write"
488
+ }
489
+
490
+ // The job's own area: any worktree under <directory>/.micromanager/worktrees/ (src/store.ts stateDir), this job's integration worktree
491
+ // included. Compared segment by segment, so a sibling that merely starts with the same name is outside.
492
+ export function inJobArea(directory: string | undefined, path: string): boolean {
493
+ if (!directory) return false
494
+ const area = normalizeOutside(join(directory, stateDir(directory), "worktrees"))
495
+ return under(normalizeOutside(path), area)
496
+ }
497
+
498
+ // The absolute paths a task text names, `~` expanded. A named file vouches for its directory too, as the plugin's own
499
+ // reader rule does (src/plugin.ts namedInTask): a task that says "…/src/main.py" is about that directory.
500
+ const TASK_PATH = /(?:^|[\s"'`(<[])((?:~|\/)[\w.@+~-]*(?:\/[\w.@+-]+)*)/g
501
+ const NAMED_FILE = /\.[a-z0-9]{1,5}$/i
502
+
503
+ export function taskNamesPath(task: string | undefined, path: string): boolean {
504
+ if (!task) return false
505
+ const want = normalizeOutside(path)
506
+ if (want.length === 0) return false
507
+ return [...task.matchAll(TASK_PATH)]
508
+ .map((match) => normalizeOutside(match[1] ?? ""))
509
+ .flatMap((named) => (NAMED_FILE.test(named) ? [named, dirname(named)] : [named]))
510
+ .some((named) => want === named || under(want, named))
511
+ }
512
+
513
+ // OpenCode asks for external_directory the same way whether a path is read or written, and riskClass() calls the
514
+ // action a write because it is not one of the reading tools. So what decides is the asking agent's role: the roles
515
+ // that change files are not reading, every other one is (the same split the plugin makes at its own layer).
516
+ function readsOutside(request: PermissionRequest): boolean {
517
+ if (riskClass(request) === "read") return true
518
+ return !WRITERS.has(roleByAgent(request.agent)?.id ?? "code")
519
+ }
520
+
521
+ // Layer 2 and 3 of the external_directory policy: the job's own area is mechanical, the user's own allowOutside is
522
+ // their standing decision, everything else is the user unless the task names the path and nothing is written to it.
523
+ // Vouching for a path is not vouching for a write.
524
+ //
525
+ // The allowOutside reason names the setting on purpose. A record that said only "allowed" would leave an operator
526
+ // asking whether anything was wrong with the request; this one says the user's own policy opened it.
527
+ export function externalVerdict(request: PermissionRequest, allowed: readonly string[] = []): Outcome | undefined {
528
+ if (request.action !== "external_directory" || request.resources.length === 0) return undefined
529
+ if (request.resources.every((path) => inJobArea(request.directory, path))) {
530
+ return { verdict: "allow", reason: "inside the job's own worktrees" }
531
+ }
532
+ if (request.resources.every((path) => allowedOutside(path, allowed))) {
533
+ return { verdict: "allow", reason: ALLOW_OUTSIDE_REASON }
534
+ }
535
+ if (readsOutside(request) && request.resources.every((path) => taskNamesPath(request.task, path))) {
536
+ return { verdict: "allow", reason: "a read of a directory the task names" }
537
+ }
538
+ return undefined
539
+ }
540
+
541
+ function describe(request: PermissionRequest): string {
542
+ const what =
543
+ request.action === "subagent"
544
+ ? `wants to start the sub-agent ${request.resources.join(", ")}`
545
+ : `wants permission for "${request.action}" on: ${request.resources.join(" | ")}`
546
+ const role = roleByAgent(request.agent)
547
+ const lines = [
548
+ `A coding agent in OpenCode (agent "${request.agent}") ${what}.`,
549
+ role ? `Its role is "${role.id}": ${role.description}` : "",
550
+ request.agent === MICROMANAGER.agent ? `It is the orchestrator: ${MICROMANAGER.description}` : "",
551
+ request.directory ? `Project directory: ${request.directory}` : "",
552
+ request.task ? `What it is working on:\n${request.task}` : "",
553
+ ]
554
+ return lines.filter(Boolean).join("\n")
555
+ }
556
+
557
+ export const RELEVANCE_QUESTION: Question = {
558
+ type: "score",
559
+ instructions: "How much do the paths this command deletes matter?",
560
+ criteria: [
561
+ "regenerable: a cache, build output or temporary files",
562
+ "project files that cannot simply be regenerated",
563
+ "user data, or files that matter outside the project",
564
+ ],
565
+ }
566
+
567
+ export const PERMISSION_QUESTIONS: Record<string, Question> = {
568
+ answer: {
569
+ type: "choice",
570
+ instructions: "Should this request be allowed?",
571
+ criteria: { allow: "Allow it: it fits the task and is safe to do.", deny: "Deny it: it does not fit the task or is unsafe." },
572
+ },
573
+ needs_user: {
574
+ type: "noul",
575
+ instructions: "Only the user can decide this: a matter of taste, money, data outside the project, or an effect that cannot be undone.",
576
+ },
577
+ risk: {
578
+ type: "score",
579
+ instructions: "How risky is this action?",
580
+ criteria: ["read only", "changes files in the project", "irreversible or outside the project"],
581
+ },
582
+ }
583
+
584
+ export function judge(decision: Decision, request: PermissionRequest, floors: Floors = DEFAULT_FLOORS): Outcome {
585
+ const answer = decision.answers.answer
586
+ const needs = decision.answers.needs_user
587
+ const risk = decision.answers.risk
588
+ if (answer?.type !== "choice" || needs?.type !== "noul" || risk?.type !== "score") {
589
+ return { verdict: "user", reason: "Jev left a question unanswered", latencyMs: decision.latencyMs }
590
+ }
591
+ const base = {
592
+ confidence: answer.confidence,
593
+ probability: answer.probabilities[answer.choice],
594
+ risk: risk.score,
595
+ needsUser: needs.noul,
596
+ latencyMs: decision.latencyMs,
597
+ }
598
+ if (needs.noul >= floors.needsUser) return { ...base, verdict: "user", reason: "Jev: the user must decide this" }
599
+ const relevance = decision.answers.path_relevance
600
+ if (relevance?.type === "score" && relevance.score >= 0.5) {
601
+ return { ...base, verdict: "user", reason: `Jev: the deleted paths matter (${relevance.score.toFixed(2)})` }
602
+ }
603
+ if (risk.score >= floors.risk) return { ...base, verdict: "user", reason: "Jev: too risky to decide alone" }
604
+ const cls = riskClass(request) === "read" && risk.score < 0.5 ? "read" : "write"
605
+ const floor = cls === "read" ? floors.read : floors.write
606
+ if (answer.confidence < floor) {
607
+ return { ...base, verdict: "user", reason: `Jev unsure (${answer.confidence.toFixed(2)} < ${floor} for ${cls})` }
608
+ }
609
+ return { ...base, verdict: answer.choice === "allow" ? "allow" : "deny", reason: `Jev: ${answer.choice} (${cls})` }
610
+ }
611
+
612
+ // preset: the user's policy for this kind of request ("N13.shell": "fixed:allow", design.md §22). It applies after
613
+ // the hard rules and the deleted-path check, which it can never switch off, and replaces Jev.
614
+ //
615
+ // root: the job's worktree (or the project root), where a read needs nobody. It defaults to the request's own
616
+ // directory so a caller that knows nothing more still gets the fast path.
617
+ //
618
+ // allowed: the user's own `allowOutside` setting, the paths they decided a worker may reach. It is threaded into the
619
+ // hard rules (forbiddenOutside) and into the external_directory layers, never asked about: it is a decision the user
620
+ // already made in the config, not one for Jev to re-litigate per request. Default empty: with no setting, a caller's
621
+ // behaviour is exactly what it was before the setting existed.
622
+ export async function decide(
623
+ jev: Jev | undefined,
624
+ request: PermissionRequest,
625
+ floors: Floors = DEFAULT_FLOORS,
626
+ inspect: Inspect = inspectPaths,
627
+ preset?: "allow" | "deny" | "user",
628
+ root: string | undefined = request.directory,
629
+ allowed: readonly string[] = [],
630
+ // Whether the worker's commands run in the sandbox (src/shell/sandbox.ts). Without it a writer's command in its worktree
631
+ // is no longer allowed on its text alone: what the program does is unchecked, so Jev is asked as before.
632
+ sandboxed = true,
633
+ ): Promise<Outcome> {
634
+ const rule = hardRule(request, allowed)
635
+ if (rule) return { verdict: "user", reason: `always the user: ${rule}` }
636
+ // A read-only command inside the job's own worktree: it changes nothing and names no path outside, and Jev's own
637
+ // confidence on these sits under the read floor, so asking it only turned a worker's inspection into a denial.
638
+ // A preset that sends this kind of request to the user still wins: it is the user's own decision.
639
+ const presetRules = preset === "user" || preset === "deny"
640
+ if (!presetRules && request.action !== "external_directory" && root !== undefined && readsOnlyInside(request, root)) {
641
+ return { verdict: "allow", reason: "read-only command inside the job's worktree" }
642
+ }
643
+ // A writer's own task worktree is its sandbox. Asking Jev there turned a worker's verification into denials (live
644
+ // runs: 478 "Jev unsure" refusals on writes, among them `npm test`, a render, a screenshot and `git restore` in a
645
+ // worktree nobody else uses), and a worker that cannot check its work cannot finish it. Deleting a tracked file there
646
+ // is allowed too: git has it, and the task's diff shows it before anything merges.
647
+ const role = roleByAgent(request.agent)?.id
648
+ if (!presetRules && request.action === "shell" && role !== undefined) {
649
+ const worktree = WRITERS.has(role) ? taskWorktree(root) : undefined
650
+ if (sandboxed && worktree && staysInWorktree(request, worktree, root)) {
651
+ return { verdict: "allow", reason: "a command inside the task's own worktree" }
652
+ }
653
+ // A reader's shell asks about every command its rules do not list, so that a chain of reading programs reaches the
654
+ // read-only check above instead of a flat deny. What does not read is refused here, with the reason, and Jev is
655
+ // not asked to decide whether a role that only reads may write.
656
+ if (!WRITERS.has(role) && !readsOnly(request.resources)) {
657
+ return { verdict: "deny", reason: `a ${request.agent} only reads, and this command changes something; run read-only commands only (no writing redirects, no sed -i), or report what you needed it for` }
658
+ }
659
+ }
660
+ const outside = presetRules ? undefined : externalVerdict(request, allowed)
661
+ if (outside) return outside
662
+ // Layer 3: anything else outside the project is the user's, as it was before the layers existed (a preset never
663
+ // reached this far either: an ask outside the project was never the policy's to answer).
664
+ // A preset still wins over allowOutside, as it does over the job area and the task's own paths: the user wrote both,
665
+ // and a per-request policy is the narrower word.
666
+ if (request.action === "external_directory") {
667
+ return { verdict: "user", reason: "always the user: access outside the project" }
668
+ }
669
+ // Deleting inside the project: first what the paths are; files under version control are the user's call.
670
+ const deleted = request.action === "shell" ? request.resources.flatMap((c) => rmTargets(c).flat()) : []
671
+ let facts: PathFacts[] = []
672
+ if (deleted.length > 0) {
673
+ if (!request.directory) return { verdict: "user", reason: "deletes files, and the project directory is unknown" }
674
+ facts = inspect(request.directory, deleted)
675
+ const kept = facts.find((f) => f.tracked !== false)
676
+ if (kept) {
677
+ const why = kept.tracked === undefined ? "not a git repository" : "under version control"
678
+ return { verdict: "user", reason: `deletes ${kept.path} (${why})` }
679
+ }
680
+ }
681
+ if (preset) return { verdict: preset, reason: `preset by the user's policy (${preset})` }
682
+ if (!jev) return { verdict: "user", reason: "no Jev key" }
683
+ try {
684
+ const state = facts.length > 0 ? `${describe(request)}\n${relevanceFacts(facts)}` : describe(request)
685
+ const questions = facts.length > 0 ? { ...PERMISSION_QUESTIONS, path_relevance: RELEVANCE_QUESTION } : PERMISSION_QUESTIONS
686
+ return judge(await jev.ask(state, questions), request, floors)
687
+ } catch (err) {
688
+ return { verdict: "user", reason: `Jev failed: ${err instanceof Error ? err.message : String(err)}` }
689
+ }
690
+ }