@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/forms.ts ADDED
@@ -0,0 +1,191 @@
1
+ // Questions to the user as forms (the user, 2026-10-20: a question the micromanager writes as text scrolls away, and a
2
+ // job then waits for an answer nobody saw). The micromanager asks with OpenCode's question tool; the form stays in the
3
+ // TUI until it is answered, and the answer comes back as the tool's result, which the plugin reads (tool.execute.after).
4
+ //
5
+ // The plugin cannot open a form itself (its context has no form domain in opencode 2.0.18), so it hands the
6
+ // micromanager the exact input to pass, and recognises its forms by their headers. Spike, 2026-10-20: several
7
+ // questions go into one form, `multiple: true` makes a question a multi-select, a "Type your own answer" option is
8
+ // added by OpenCode, there are no default ticks, and the turn waits until the user submits. The answer arrives as one
9
+ // list of labels per question: [["Auto-continue", "Parallel"], ["Start"]].
10
+
11
+ // One question as the question tool takes it.
12
+ export interface Question {
13
+ readonly question: string
14
+ readonly header: string // at most 30 characters
15
+ readonly options: readonly { readonly label: string; readonly description: string }[]
16
+ readonly multiple?: boolean
17
+ }
18
+
19
+ import { DEFAULT_OPTIONS, type JobOptions } from "@omacode/state/options"
20
+ export { DEFAULT_OPTIONS, type JobOptions }
21
+
22
+ const H = { options: "Job options", start: "Start job", access: "Open a path", git: "No git repository" } as const
23
+ const OPTION = { auto: "Auto-continue", parallel: "Parallel", review: "Review per task" } as const
24
+ const START = { start: "Start", change: "Change the plan", cancel: "Cancel" } as const
25
+ const ACCESS = { open: "Open it", closed: "Keep it closed" } as const
26
+ const ASK = { once: "Allow once", job: "Allow for this job", refuse: "Refuse" } as const
27
+ const GRANT = { job: "Allow for this job", refuse: "Refuse" } as const
28
+ export const GIT = { init: "Create a git repository", none: "Without isolation", cancel: "Cancel" } as const
29
+
30
+ // The text the micromanager passes to the question tool, ready to copy.
31
+ export const formInput = (questions: readonly Question[]): string => JSON.stringify({ questions })
32
+
33
+ // The start form: the job's options (ticked last time: said in the description, as a form has no default ticks) and
34
+ // the go. It doubles as the plan's approval: nothing that writes starts before "Start".
35
+ export function startForm(jobId: string, todos: number, startable: number, last: JobOptions = DEFAULT_OPTIONS): Question[] {
36
+ const was = (on: boolean) => (on ? " (on last time)" : "")
37
+ return [
38
+ {
39
+ header: H.options,
40
+ question: `How should ${jobId} run?`,
41
+ multiple: true,
42
+ options: [
43
+ { label: OPTION.auto, description: `Work the todo list without stopping; pause only for questions to you${was(last.auto)}` },
44
+ { label: OPTION.parallel, description: `Start every task that can start at once, not one after another${was(last.parallel)}` },
45
+ { label: OPTION.review, description: `A reviewer checks each change before it counts as done${was(last.review)}` },
46
+ ],
47
+ },
48
+ {
49
+ header: H.start,
50
+ question: `The plan has ${todos} todo${todos === 1 ? "" : "s"}, ${startable} can start now. Start ${jobId}?`,
51
+ options: [
52
+ { label: `${START.start} (Recommended)`, description: "Start the job with the options ticked above" },
53
+ { label: START.change, description: "Say what to change; the plan comes back to you" },
54
+ { label: START.cancel, description: "Drop the plan" },
55
+ ],
56
+ },
57
+ ]
58
+ }
59
+
60
+ // The question about a path only the user can open (request_access on a refused path).
61
+ export function accessForm(path: string, why: string, rule: string): Question[] {
62
+ return [{
63
+ header: H.access,
64
+ question: `A worker needs ${path}, which is refused by default (${rule}). What it needs there: ${why}. Open it for this job?`,
65
+ options: [
66
+ { label: ACCESS.open, description: "The workers of this job may read and write there while this server runs" },
67
+ { label: ACCESS.closed, description: "It stays closed for this job; the question will not come back" },
68
+ ],
69
+ }]
70
+ }
71
+
72
+ // The question about a worker's paused permission request (src/ask.ts).
73
+ export function askForm(id: string, task: string, request: string, why: string): Question[] {
74
+ return [{
75
+ header: `Request ${id}`,
76
+ question: `Worker ${task} asks to run ${request}. ${why} Allow it?`,
77
+ options: [
78
+ { label: ASK.once, description: "This one call" },
79
+ { label: ASK.job, description: "This exact request for the rest of the job" },
80
+ { label: ASK.refuse, description: "The worker carries on without it" },
81
+ ],
82
+ }]
83
+ }
84
+
85
+ // The question about a variable or a host a worker asks for (src/grants.ts). A host asked for while the job's commands
86
+ // hold a secret names that secret: the two together are what it takes to send it away.
87
+ export function grantForm(id: string, kind: "env" | "network", name: string, task: string, why: string, secrets: readonly string[] = []): Question[] {
88
+ const what = kind === "env"
89
+ ? `the variable ${name} in its shell commands (its value never reaches a model)`
90
+ : `to reach ${name} from its shell commands${secrets.length ? `. These commands already hold ${secrets.join(", ")}; with ${name} open they could send ${secrets.length > 1 ? "them" : "it"} there` : ""}`
91
+ return [{
92
+ header: `Grant ${id}`,
93
+ question: `Worker ${task} asks for ${what}. Why: ${why.slice(0, 300)}. Allow it?`,
94
+ options: [
95
+ { label: GRANT.job, description: kind === "env" ? "Every command of this job's workers gets it" : "Every command of this job's workers may reach it" },
96
+ { label: GRANT.refuse, description: "The worker carries on without it; it will not ask again" },
97
+ ],
98
+ }]
99
+ }
100
+
101
+ // The question about several grants of one worker session at once (src/grants.ts). The worker asked for a variable and a
102
+ // host while the first answer was still open; the user answers both in one form, each on its own.
103
+ export function grantBatchForm(items: readonly { readonly id: string; readonly kind: "env" | "network"; readonly name: string; readonly why: string; readonly secrets?: readonly string[] }[], task: string): Question[] {
104
+ return items.map((item) => ({
105
+ header: `Grant ${item.id}`,
106
+ question: `Worker ${task} asks for ${item.kind === "env" ? `the variable ${item.name} in its shell commands (its value never reaches a model)` : `to reach ${item.name} from its shell commands${item.secrets?.length ? `. These commands already hold ${item.secrets.join(", ")}; with ${item.name} open they could send ${item.secrets.length > 1 ? "them" : "it"} there` : ""}`}. Why: ${item.why.slice(0, 300)}. Allow it?`,
107
+ options: [
108
+ { label: GRANT.job, description: item.kind === "env" ? "Every command of this job's workers gets it" : "Every command of this job's workers may reach it" },
109
+ { label: GRANT.refuse, description: "The worker carries on without it; it will not ask again" },
110
+ ],
111
+ }))
112
+ }
113
+
114
+ // The question when the project is no git repository (src/worktree/git.ts): the recommended way first.
115
+ export function gitForm(path: string, files: number, size: string, recommend: "init" | "none", excluded: readonly string[]): Question[] {
116
+ const init = { label: `${GIT.init}${recommend === "init" ? " (Recommended)" : ""}`, description: `git init and a first commit${excluded.length ? `; left out: ${excluded.join(", ")}` : ""}` }
117
+ const none = { label: `${GIT.none}${recommend === "none" ? " (Recommended)" : ""}`, description: "Workers change the folder directly, one task after another; checks run, nothing is committed" }
118
+ return [{
119
+ header: H.git,
120
+ question: `${path} is not a git repository (${files} files, ${size}). How should the workers work there?`,
121
+ options: [...(recommend === "init" ? [init, none] : [none, init]), { label: GIT.cancel, description: "Start nothing" }],
122
+ }]
123
+ }
124
+
125
+ // What one answered form of the micromanager means. The answer is matched on the labels the plugin wrote; a label the
126
+ // user typed themselves ("Type your own answer") is kept as `said` and never taken for a yes.
127
+ export type Answer =
128
+ | { readonly kind: "start"; readonly decision?: "start" | "change" | "cancel"; readonly options: JobOptions; readonly said?: string }
129
+ | { readonly kind: "access"; readonly open?: boolean; readonly question: string; readonly said?: string }
130
+ | { readonly kind: "ask"; readonly id: string; readonly decision?: "once" | "job" | "refuse"; readonly said?: string }
131
+ | { readonly kind: "git"; readonly decision?: "init" | "none" | "cancel"; readonly said?: string }
132
+ | { readonly kind: "grant"; readonly id: string; readonly granted?: boolean; readonly said?: string }
133
+ | { readonly kind: "grants"; readonly answers: readonly { readonly id: string; readonly granted?: boolean; readonly said?: string }[] }
134
+
135
+ const is = (answer: string, label: string) => answer.trim().toLowerCase().replace(/\s*\(recommended\)\s*$/, "") === label.toLowerCase()
136
+ const pick = <K extends string>(answers: readonly string[], labels: Record<K, string>): { key?: K; said?: string } => {
137
+ for (const a of answers) {
138
+ const key = (Object.keys(labels) as K[]).find((k) => is(a, labels[k]))
139
+ if (key) return { key }
140
+ }
141
+ const said = answers.find((a) => a.trim())
142
+ return said ? { said: said.trim() } : {}
143
+ }
144
+
145
+ export function readForm(questions: readonly Partial<Question>[], answers: readonly (readonly string[])[]): Answer | undefined {
146
+ const at = (header: string) => questions.findIndex((q) => q.header === header)
147
+ const of = (i: number) => (i >= 0 ? answers[i] ?? [] : [])
148
+ if (at(H.start) >= 0) {
149
+ const ticked = of(at(H.options))
150
+ const { key, said } = pick(of(at(H.start)), START)
151
+ const options = { auto: ticked.some((a) => is(a, OPTION.auto)), parallel: ticked.some((a) => is(a, OPTION.parallel)), review: ticked.some((a) => is(a, OPTION.review)) }
152
+ return { kind: "start", options, ...(key ? { decision: key } : {}), ...(said ? { said } : {}) }
153
+ }
154
+ if (at(H.access) >= 0) {
155
+ const { key, said } = pick(of(at(H.access)), ACCESS)
156
+ return { kind: "access", question: questions[at(H.access)]!.question ?? "", ...(key ? { open: key === "open" } : {}), ...(said ? { said } : {}) }
157
+ }
158
+ if (at(H.git) >= 0) {
159
+ const { key, said } = pick(of(at(H.git)), GIT)
160
+ return { kind: "git", ...(key ? { decision: key } : {}), ...(said ? { said } : {}) }
161
+ }
162
+ const grants = questions.map((q, i) => ({ q, i })).filter(({ q }) => /^Grant G\d+$/.test(q.header ?? ""))
163
+ if (grants.length) {
164
+ // One form with several grant questions is a batch (src/grants.ts): the user answered each of them on its own.
165
+ if (grants.length > 1) {
166
+ return {
167
+ kind: "grants",
168
+ answers: grants.map(({ q, i }) => {
169
+ const { key, said } = pick(of(i), GRANT)
170
+ return { id: q.header!.split(" ")[1]!, ...(key ? { granted: key === "job" } : {}), ...(said ? { said } : {}) }
171
+ }),
172
+ }
173
+ }
174
+ const { q, i } = grants[0]!
175
+ const { key, said } = pick(of(i), GRANT)
176
+ return { kind: "grant", id: q.header!.split(" ")[1]!, ...(key ? { granted: key === "job" } : {}), ...(said ? { said } : {}) }
177
+ }
178
+ const ask = questions.findIndex((q) => /^Request A\d+$/.test(q.header ?? ""))
179
+ if (ask >= 0) {
180
+ const { key, said } = pick(of(ask), ASK)
181
+ return { kind: "ask", id: questions[ask]!.header!.split(" ")[1]!, ...(key ? { decision: key } : {}), ...(said ? { said } : {}) }
182
+ }
183
+ return undefined
184
+ }
185
+
186
+ // The answer lists out of the question tool's result: { output: { answers } } or { metadata: { answers } }.
187
+ export function answersOf(result: unknown): string[][] | undefined {
188
+ const r = result as { output?: { answers?: unknown }; metadata?: { answers?: unknown } } | undefined
189
+ const a = r?.metadata?.answers ?? r?.output?.answers
190
+ return Array.isArray(a) && a.every((x) => Array.isArray(x)) ? (a as unknown[][]).map((x) => x.map(String)) : undefined
191
+ }
package/src/gate.ts ADDED
@@ -0,0 +1,90 @@
1
+ // G0, the local-first gate (design.md §20, §21): four guards on a job's or task's text, answered on the machine.
2
+ //
3
+ // Until our own GLiNER fine-tune passes the guard bench, a "yes" never routes or blocks on its own: it asks the
4
+ // user (Phase A9 showed the available fine-tune flags legitimate security work as harmful). The user's answer
5
+ // sets the job's flags: local only, uncensored allowed, or on as it is.
6
+
7
+ import type { Decider } from "./backends.ts"
8
+ import { GUARD_FLOOR, GUARDS } from "./catalog.ts"
9
+
10
+ import type { GateResult, Guard, JobFlags } from "@omacode/state/schema"
11
+ export type { GateResult, Guard, JobFlags }
12
+
13
+ // The same text scored 0.59 and 2e-8 for injection in two runs of Phase D, so every text is scored twice and the
14
+ // higher score counts: a guard errs towards asking the user.
15
+ export async function checkGuards(decider: Decider, text: string, job?: string, task?: string, repeats = 2): Promise<GateResult> {
16
+ const scores: Partial<Record<Guard, number>> = {}
17
+ let checked = false
18
+ let decision: string | undefined
19
+ for (let i = 0; i < repeats; i++) {
20
+ const asked = await decider.ask("G0", { text }, GUARDS, { localOnly: true, job, task })
21
+ decision ??= asked.id
22
+ for (const g of Object.keys(GUARDS) as Guard[]) {
23
+ const a = asked.decision.answers[g]
24
+ if (a?.type === "noul") scores[g] = Math.max(scores[g] ?? 0, a.noul)
25
+ }
26
+ checked ||= asked.backend !== "rules" && Object.keys(asked.decision.answers).length > 0
27
+ }
28
+ return { flagged: (Object.keys(scores) as Guard[]).filter((g) => scores[g]! >= GUARD_FLOOR), scores, checked, decision }
29
+ }
30
+
31
+ const CHUNK = 1500
32
+ const MAX_CHUNKS = 6
33
+
34
+ // Indirect injection (E2b): text a worker did not write but reads (web pages, research notes, a worker's question)
35
+ // is checked for injection alone, in chunks, since an injection can hide anywhere in a long page. Returns the highest
36
+ // score, or undefined when nothing local answered.
37
+ export async function injectionScore(decider: Decider, text: string, job?: string, task?: string): Promise<number | undefined> {
38
+ const chunks: string[] = []
39
+ for (let i = 0; i < text.length && chunks.length < MAX_CHUNKS; i += CHUNK) chunks.push(text.slice(i, i + CHUNK))
40
+ let best: number | undefined
41
+ for (const chunk of chunks) {
42
+ const asked = await decider.ask("G0.injection", { text: chunk }, { injection: GUARDS.injection }, { localOnly: true, job, task })
43
+ const a = asked.decision.answers.injection
44
+ if (asked.backend !== "rules" && a?.type === "noul") best = Math.max(best ?? 0, a.noul)
45
+ }
46
+ return best
47
+ }
48
+
49
+ export const injected = (score: number | undefined): boolean => (score ?? 0) >= GUARD_FLOOR
50
+
51
+ // What the job does when nothing local could check it. "local" is the privacy-first default (user, 2026-10-04).
52
+ export type Unchecked = "local" | "user" | "cloud"
53
+
54
+ // cloudOnly: sensitive and refusal_likely only choose local models, and there are none; only injection and harmful
55
+ // ask the user. (Cloud Jev on the guard bench, 2026-10-05: injection and harmful 100 % recall with 0 % false alarms,
56
+ // sensitive a false alarm on 92 % of harmless cases.)
57
+ export function flagsWithoutUser(result: GateResult, unchecked: Unchecked = "local", cloudOnly = false): JobFlags | "ask_user" {
58
+ if (!result.checked) return unchecked === "user" ? "ask_user" : { localOnly: unchecked === "local", gate: result }
59
+ const asks = cloudOnly ? result.flagged.filter((g) => g === "injection" || g === "harmful") : result.flagged
60
+ return asks.length === 0 ? { gate: result } : "ask_user"
61
+ }
62
+
63
+ // The question the micromanager puts to the user when the gate flagged something.
64
+ export function gateQuestion(result: GateResult, cloudOnly = false): string {
65
+ const what: Record<Guard, string> = {
66
+ injection: "the text may try to change the agents' rules (injection)",
67
+ harmful: "it may ask for help to harm people or attack systems you do not own",
68
+ refusal_likely: "a censored model would likely refuse it, so it may need a local uncensored model",
69
+ sensitive: "it may hold data that should stay on this machine",
70
+ }
71
+ const lines = result.flagged.map((g) => `- ${what[g]} (${(result.scores[g] ?? 0).toFixed(2)})`)
72
+ return [
73
+ "The local check flagged this job:",
74
+ ...lines,
75
+ "The check is not calibrated yet, so you decide. Answer with one of:",
76
+ ...(cloudOnly
77
+ ? ['"continue" (go on as normal, in the cloud) or "stop". Local models are switched off for now.']
78
+ : ['"always local" (keep everything on this machine), "use uncensored" (local uncensored models only),', '"continue" (go on as normal), or "stop".']),
79
+ ].join("\n")
80
+ }
81
+
82
+ // The user's answer to the gate question; exact phrases, matched before any model.
83
+ export function gateAnswer(text: string): JobFlags | "stop" | undefined {
84
+ const t = text.trim().toLowerCase().replace(/[.!"]+$/g, "").replace(/^"/, "")
85
+ if (t === "always local" || t === "only local") return { localOnly: true }
86
+ if (t === "use uncensored" || t === "uncensored") return { localOnly: true, uncensored: true }
87
+ if (t === "continue" || t === "go on") return {}
88
+ if (t === "stop") return "stop"
89
+ return undefined
90
+ }
package/src/grants.ts ADDED
@@ -0,0 +1,239 @@
1
+ // A worker's request for a variable or a host the sandbox keeps from it (src/shell/sandbox.ts). A test that needs
2
+ // DATABASE_URL, or a build that fetches from a host beyond the package registries, used to fail with no way to ask.
3
+ // Now the worker calls request_env or request_network with the name and why; the plugin decides in steps:
4
+ // - never: a variable on the never list (sockets into the desktop, agent sockets, the plugin's own credentials), a
5
+ // variable that is not set where the server runs, or a name or host refused before in this job;
6
+ // - Jev: a variable that is a setting, not a secret (NODE_ENV, RUST_LOG), or a public host while the job holds no
7
+ // secret, when Jev is sure;
8
+ // - the user, with a form through the micromanager: everything else, and always a secret-looking variable or a host
9
+ // asked for while the job's commands hold a secret (the form names it: a secret and an open host together are what
10
+ // it takes to send the secret away).
11
+ // A grant holds for the job and is kept in its control file (src/control.ts), names and hosts only. The worker sees a
12
+ // variable's name, never its value, and no model ever does: Jev gets the value's shape at most.
13
+
14
+ import { formInput, grantBatchForm, grantForm } from "./forms.ts"
15
+ import { ENV_ALLOW, looksSecret, neverHanded, REGISTRIES } from "./sandbox.ts"
16
+
17
+ export type GrantKind = "env" | "network"
18
+ export type GrantedBy = "jev" | "user" | "timeout"
19
+
20
+ export const GRANT_TIMEOUT_MS = 10 * 60_000
21
+ // How sure Jev must be that a variable is a setting, or a host harmless, to grant it without the user.
22
+ export const GRANT_FLOOR = 0.9
23
+
24
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/
25
+ // A host, or "*." and a host of at least two labels ("*.com" is no host).
26
+ const DOMAIN = /^(\*\.)?([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/
27
+
28
+ // What is wrong with a requested name or host, or undefined when it is one.
29
+ export function badName(kind: GrantKind, name: string): string | undefined {
30
+ if (kind === "env") return NAME.test(name) ? undefined : `"${name}" is no variable name: letters, digits and _, not starting with a digit`
31
+ return DOMAIN.test(name) ? undefined : `"${name}" is no host name: a name like api.example.com or *.example.com, without scheme, port or path`
32
+ }
33
+
34
+ const matches = (name: string, pattern: string) => (pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern)
35
+ const covers = (host: string, pattern: string) => host === pattern || (pattern.startsWith("*.") && host.endsWith(pattern.slice(1)) && host !== pattern.slice(2))
36
+
37
+ // The facts a request is decided on.
38
+ export interface GrantFacts {
39
+ readonly kind: GrantKind
40
+ readonly name: string // a variable's name, or a host, lowercased
41
+ readonly open: readonly string[] // the user's "env" / "network" setting and the job's grants
42
+ readonly refused: readonly string[] // what the user refused in this job
43
+ readonly value?: string // env: its value where the server runs; undefined when it is not set
44
+ readonly sandboxed: boolean // network: without the sandbox nothing restricts it
45
+ readonly secrets: readonly string[] // the secret-looking variables the job's commands hold
46
+ }
47
+
48
+ export type Triage =
49
+ | { readonly verdict: "open"; readonly text: string } // nothing to grant: the worker has it already
50
+ | { readonly verdict: "refused"; readonly text: string }
51
+ | { readonly verdict: "jev" | "user"; readonly reason: string }
52
+
53
+ export function triage(f: GrantFacts): Triage {
54
+ if (f.kind === "env") {
55
+ if (neverHanded(f.name)) return { verdict: "refused", text: `${f.name} is never handed to a worker command: it opens the user's desktop, an agent socket or the plugin's own credentials. Carry on without it.` }
56
+ if (f.value === undefined) return { verdict: "refused", text: `${f.name} is not set where the server runs, so there is nothing to hand on. If your task needs it, say so in your report: the user has to set it.` }
57
+ if ([...ENV_ALLOW, ...f.open].some((p) => matches(f.name, p))) return { verdict: "open", text: `${f.name} is handed to your commands already. If a command still misses it, it is not the environment: look at how the command reads it.` }
58
+ if (f.refused.includes(f.name)) return { verdict: "refused", text: `The user refused ${f.name} for this job. Do not ask again; carry on without it and say in your report what it was for.` }
59
+ if (looksSecret(f.name, f.value)) return { verdict: "user", reason: "its name or value looks like a secret" }
60
+ return { verdict: "jev", reason: "a setting, if Jev is sure it is no secret" }
61
+ }
62
+ if (!f.sandboxed) return { verdict: "open", text: "Your commands run without a sandbox, so the network is not restricted. If a host is unreachable, it is not the plugin." }
63
+ if ([...REGISTRIES, ...f.open].some((p) => covers(f.name, p))) return { verdict: "open", text: `${f.name} is open to your commands already. If it is still unreachable, the cause is elsewhere (DNS, the host, a proxy setting of the tool).` }
64
+ if (f.refused.includes(f.name)) return { verdict: "refused", text: `The user refused ${f.name} for this job. Do not ask again; carry on without it and say in your report what it was for.` }
65
+ if (f.secrets.length) return { verdict: "user", reason: `the job's commands hold ${f.secrets.join(", ")}` }
66
+ return { verdict: "jev", reason: "a public host, if Jev is sure it sends nothing private" }
67
+ }
68
+
69
+ // What Jev may see of a value: its length and the kinds of characters, never the value itself.
70
+ export function valueShape(value: string): string {
71
+ const kinds = [
72
+ /[a-z]/.test(value) && "lowercase letters", /[A-Z]/.test(value) && "uppercase letters", /\d/.test(value) && "digits",
73
+ /[^A-Za-z0-9]/.test(value) && "other characters",
74
+ ].filter(Boolean)
75
+ return `${value.length} characters${kinds.length ? `: ${kinds.join(", ")}` : ""}`
76
+ }
77
+
78
+ // Jev's question about a request it may decide: the statement it gives the probability of.
79
+ export function harmlessQuestion(kind: GrantKind): { readonly type: "noul"; readonly instructions: string } {
80
+ return kind === "env"
81
+ ? { type: "noul", instructions: "This environment variable is a configuration setting (a mode, a log level, a flag, a path or a port), not a secret such as a token, key, password or a URL with credentials." }
82
+ : { type: "noul", instructions: "This host is a public documentation, package, source or API host that a build or a test of a coding project plausibly needs, and reaching it from the project's commands sends nothing private." }
83
+ }
84
+
85
+ export function grantState(kind: GrantKind, name: string, why: string, task: string, value?: string): string {
86
+ const what = kind === "env" ? `the environment variable ${name} (value: ${valueShape(value ?? "")})` : `network access to the host ${name}`
87
+ return `A coding agent's shell commands run in a sandbox. Working on "${task}", it asks for ${what}. Its reason: ${why}`
88
+ }
89
+
90
+ export interface GrantRequest {
91
+ readonly kind: GrantKind
92
+ readonly name: string
93
+ readonly why: string
94
+ readonly sessionID: string // the waiting worker
95
+ readonly parent: string // the micromanager session that puts the form to the user
96
+ readonly task: string
97
+ readonly project: string
98
+ readonly jobId: string
99
+ readonly secrets: readonly string[] // network: the secret-looking variables the job holds, named in the form
100
+ }
101
+
102
+ export interface PendingGrant extends GrantRequest {
103
+ readonly id: string // "G1", the form's header
104
+ readonly at: number
105
+ }
106
+
107
+ export type GrantAnswer = { readonly granted: boolean; readonly by: GrantedBy }
108
+
109
+ interface Waiting extends PendingGrant {
110
+ readonly answer: Promise<GrantAnswer>
111
+ readonly settle: (answer: GrantAnswer) => void
112
+ timer?: ReturnType<typeof setTimeout>
113
+ }
114
+
115
+ // The requests waiting for the user. The worker's tool call waits on its promise; the form's answer, the worker's end
116
+ // or the timeout settles it.
117
+ //
118
+ // The requests of one worker session wait together: a worker that needs a variable and a host asks for both while the
119
+ // first answer is still open, and the user sees one form with a question per item instead of two rounds of waiting.
120
+ // Every item keeps its own answer: the user may allow one and refuse the other.
121
+ export class GrantRequests {
122
+ readonly #pending = new Map<string, Waiting>()
123
+ readonly #journal: (entry: Record<string, unknown>) => void
124
+ readonly #timeoutMs: number
125
+ #n = 0
126
+
127
+ constructor(journal: (entry: Record<string, unknown>) => void = () => {}, timeoutMs = GRANT_TIMEOUT_MS) {
128
+ this.#journal = journal
129
+ this.#timeoutMs = timeoutMs
130
+ }
131
+
132
+ // A request for the same name of the same job that waits already: the second worker waits on the first one's form.
133
+ open(request: GrantRequest): { pending: PendingGrant; answer: Promise<GrantAnswer>; fresh: boolean; batch: PendingGrant[] } {
134
+ const same = [...this.#pending.values()].find((p) => p.project === request.project && p.jobId === request.jobId && p.kind === request.kind && p.name === request.name)
135
+ if (same) return { pending: strip(same), answer: same.answer, fresh: false, batch: this.#batchOf(same.sessionID) }
136
+ const id = `G${++this.#n}`
137
+ let settle!: (answer: GrantAnswer) => void
138
+ const answer = new Promise<GrantAnswer>((resolve) => (settle = resolve))
139
+ const waiting: Waiting = { ...request, id, at: Date.now(), answer, settle }
140
+ waiting.timer = setTimeout(() => {
141
+ if (!this.#pending.delete(id)) return
142
+ this.#journal({ kind: "grant", event: "timeout", id, grant: request.kind, name: request.name, sessionID: request.sessionID, job: request.jobId })
143
+ settle({ granted: false, by: "timeout" })
144
+ }, this.#timeoutMs)
145
+ waiting.timer.unref?.()
146
+ this.#pending.set(id, waiting)
147
+ this.#journal({ kind: "grant", event: "asked", id, grant: request.kind, name: request.name, why: request.why.slice(0, 300), sessionID: request.sessionID, job: request.jobId })
148
+ // The worker asked for this while another of its requests was still open: the user is asked about both at once, so
149
+ // the micromanager is told again about the whole batch.
150
+ const batch = this.#batchOf(request.sessionID)
151
+ return { pending: strip(waiting), answer, fresh: true, batch }
152
+ }
153
+
154
+ // The requests of one worker session that wait right now: the batch the user answers in one form.
155
+ #batchOf(sessionID: string): PendingGrant[] {
156
+ return [...this.#pending.values()].filter((p) => p.sessionID === sessionID).map(strip)
157
+ }
158
+
159
+ // The requests of one worker session that wait right now.
160
+ batch(sessionID: string): PendingGrant[] {
161
+ return this.#batchOf(sessionID)
162
+ }
163
+
164
+ get(id: string): PendingGrant | undefined {
165
+ const p = this.#pending.get(id)
166
+ return p && strip(p)
167
+ }
168
+
169
+ // The user's answer. Returns the request it settled, or undefined when none waits under this id any more.
170
+ answer(id: string, granted: boolean): PendingGrant | undefined {
171
+ const p = this.#take(id)
172
+ if (!p) return undefined
173
+ this.#journal({ kind: "grant", event: "answered", id, grant: p.kind, name: p.name, granted, sessionID: p.sessionID, job: p.jobId, waitedMs: Date.now() - p.at })
174
+ p.settle({ granted, by: "user" })
175
+ return strip(p)
176
+ }
177
+
178
+ // The user's answers to a batch: one answer per item, the items that wait under it. Returns the requests it settled.
179
+ answerBatch(answers: readonly { readonly id: string; readonly granted?: boolean }[]): PendingGrant[] {
180
+ const settled: PendingGrant[] = []
181
+ for (const a of answers) {
182
+ if (a.granted === undefined) continue // typed text is no answer: the item keeps waiting
183
+ const p = this.answer(a.id, a.granted)
184
+ if (p) settled.push(p)
185
+ }
186
+ return settled
187
+ }
188
+
189
+ // The requests of workers that ended: refused quietly, nobody waits for them any more.
190
+ drop(sessionIDs: readonly string[]): PendingGrant[] {
191
+ const dropped = [...this.#pending.values()].filter((p) => sessionIDs.includes(p.sessionID))
192
+ for (const p of dropped) {
193
+ this.#take(p.id)
194
+ this.#journal({ kind: "grant", event: "dropped", id: p.id, grant: p.kind, name: p.name, sessionID: p.sessionID, job: p.jobId })
195
+ p.settle({ granted: false, by: "timeout" })
196
+ }
197
+ return dropped.map(strip)
198
+ }
199
+
200
+ #take(id: string): Waiting | undefined {
201
+ const p = this.#pending.get(id)
202
+ if (!p) return undefined
203
+ this.#pending.delete(id)
204
+ clearTimeout(p.timer)
205
+ return p
206
+ }
207
+ }
208
+
209
+ function strip(p: Waiting): PendingGrant {
210
+ const { settle: _s, timer: _t, answer: _a, ...shown } = p
211
+ return shown
212
+ }
213
+
214
+ // The note that wakes the micromanager: the form to put to the user, as it is.
215
+ export function grantNote(p: PendingGrant, timeoutMs = GRANT_TIMEOUT_MS): string {
216
+ const what = p.kind === "env" ? `the variable ${p.name}` : `the host ${p.name}`
217
+ return `[micromanager] ${p.id}: worker ${p.task} waits for ${what} (${p.why.slice(0, 300)}). Only the user can grant it: ask them with the question tool, with exactly this input (a form that waits for their answer; it reaches the plugin by itself), then end your turn:\n${formInput(grantForm(p.id, p.kind, p.name, p.task, p.why, p.secrets))}\nWithout an answer it is refused in ${Math.round(timeoutMs / 60_000)} minutes and the worker carries on without it.`
218
+ }
219
+
220
+ // The note that wakes the micromanager for a whole batch: the requests of one worker session that wait together. The
221
+ // user answers them in one form, each on its own, so one round of waiting covers them all.
222
+ export function grantBatchNote(batch: readonly PendingGrant[], timeoutMs = GRANT_TIMEOUT_MS): string {
223
+ if (batch.length === 1) return grantNote(batch[0]!, timeoutMs)
224
+ const what = batch.map((p) => `${p.id}: ${p.kind === "env" ? `the variable ${p.name}` : `the host ${p.name}`} (${p.why.slice(0, 300)})`).join("; ")
225
+ const form = grantBatchForm(batch.map((p) => ({ id: p.id, kind: p.kind, name: p.name, why: p.why, secrets: p.secrets })), batch[0]!.task)
226
+ return `[micromanager] ${batch.length} requests of worker ${batch[0]!.task} wait together: ${what}. Only the user can grant them: ask them with the question tool, with exactly this input (one form with a question per request; it waits for their answer and reaches the plugin by itself), then end your turn:\n${formInput(form)}\nWithout an answer they are refused in ${Math.round(timeoutMs / 60_000)} minutes and the worker carries on without them.`
227
+ }
228
+
229
+ // What the worker reads once its request is decided.
230
+ export function grantResult(kind: GrantKind, name: string, granted: boolean, by: "jev" | GrantedBy): string {
231
+ if (granted) {
232
+ return kind === "env"
233
+ ? `${name} is granted for this job (${by === "jev" ? "a setting" : "the user said yes"}): every shell command you start from now on has it. Run the command again.`
234
+ : `${name} is open for this job (${by === "jev" ? "a public host" : "the user said yes"}): every shell command you start from now on may reach it. Run the command again.`
235
+ }
236
+ return by === "timeout"
237
+ ? `${name} is not granted: nobody answered in time. Carry on without it, and say in your report what you needed it for. Report STATUS: NEEDS_CONTEXT only if you genuinely cannot proceed without it.`
238
+ : `${name} is refused for this job. Do not ask again or try it another way; carry on without it, and say in your report what you needed it for.`
239
+ }
package/src/graph.ts ADDED
@@ -0,0 +1,74 @@
1
+ // The code graph an explorer starts from: graphify's graph of the session worktree (graphify-out/), built from the
2
+ // tree-sitter AST without an LLM, so its call and import edges need no checking. `graphify update` re-extracts only
3
+ // what changed, so a later explorer of the same session waits seconds at most (jev-tutor, 92 files: 3.6 s cold).
4
+ //
5
+ // The worktree lives under .micromanager/, which the user's checkout already ignores; a .gitignore inside
6
+ // graphify-out/ keeps it out of the worktree's own git status too, so no commit of the session picks it up.
7
+
8
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs"
9
+ import { join } from "node:path"
10
+
11
+ import { exec as defaultExec, type Exec } from "./integration.ts"
12
+
13
+ export const GRAPH_DIR = "graphify-out"
14
+
15
+ export interface Graph {
16
+ readonly commit: string // the worktree's HEAD the graph was built from
17
+ }
18
+
19
+ // Builds or updates the graph of dir; undefined when graphify is missing or fails (the explorer then works without).
20
+ export async function updateGraph(dir: string, run: Exec = defaultExec): Promise<Graph | undefined> {
21
+ const head = await run("git", ["rev-parse", "--short", "HEAD"], { cwd: dir })
22
+ if (head.code !== 0) return undefined
23
+ // --force: the graph follows the code, also when a refactor removed symbols (graphify keeps the bigger graph otherwise).
24
+ const r = await run("graphify", ["update", ".", "--force"], { cwd: dir, timeoutMs: 120_000 })
25
+ if (r.code !== 0 || r.timedOut || !existsSync(join(dir, GRAPH_DIR, "graph.json"))) return undefined
26
+ const ignore = join(dir, GRAPH_DIR, ".gitignore")
27
+ if (!existsSync(ignore)) {
28
+ mkdirSync(join(dir, GRAPH_DIR), { recursive: true })
29
+ writeFileSync(ignore, "*\n")
30
+ }
31
+ return { commit: head.stdout.trim() }
32
+ }
33
+
34
+ // One build per worktree and commit: explorers started in one message share it.
35
+ export class Graphs {
36
+ readonly #run: Exec
37
+ readonly #builds = new Map<string, { commit: string; graph: Promise<Graph | undefined> }>()
38
+
39
+ constructor(run: Exec = defaultExec) {
40
+ this.#run = run
41
+ }
42
+
43
+ async get(dir: string): Promise<Graph | undefined> {
44
+ const head = (await this.#run("git", ["rev-parse", "--short", "HEAD"], { cwd: dir })).stdout.trim()
45
+ const known = this.#builds.get(dir)
46
+ if (known && known.commit === head) return known.graph
47
+ const graph = updateGraph(dir, this.#run)
48
+ this.#builds.set(dir, { commit: head, graph })
49
+ return graph
50
+ }
51
+ }
52
+
53
+ export const GRAPH_ACTIONS = ["explain", "path", "affected", "query"] as const
54
+ export type GraphAction = (typeof GRAPH_ACTIONS)[number]
55
+ const MAX_OUTPUT = 12_000
56
+
57
+ // One question to the graph of dir, as the code_graph tool answers it.
58
+ export async function queryGraph(dir: string, action: string, symbol: string, to = "", run: Exec = defaultExec): Promise<string> {
59
+ if (!(GRAPH_ACTIONS as readonly string[]).includes(action)) return `Unknown action "${action}"; use one of ${GRAPH_ACTIONS.join(", ")}.`
60
+ if (!symbol.trim()) return "Name a symbol (or words, for query)."
61
+ if (action === "path" && !to.trim()) return "path needs both symbol and to."
62
+ const args = action === "path" ? ["path", symbol, to] : action === "query" ? ["query", symbol, "--budget", "3000"] : [action, symbol]
63
+ const r = await run("graphify", args, { cwd: dir, timeoutMs: 60_000 })
64
+ const out = `${r.stdout}${r.code !== 0 ? `\n${r.stderr}` : ""}`.trim() || "(no answer)"
65
+ return out.length > MAX_OUTPUT ? `${out.slice(0, MAX_OUTPUT)}\n[cut at ${MAX_OUTPUT} characters; ask about a narrower symbol]` : out
66
+ }
67
+
68
+ // The lines of an explorer's brief that point it at the graph.
69
+ export function graphBrief(graph: Graph): string {
70
+ return `A code graph of this directory (commit ${graph.commit}) is ready. ${GRAPH_DIR}/GRAPH_REPORT.md maps the modules and
71
+ their central symbols. For any question about who calls, uses or imports what, ask the code_graph tool first, before
72
+ grep or reading files: its call and import edges come from the syntax tree of every file, so one call replaces a
73
+ search through the code. Read code only to explain what you found; edges marked INFERRED are guesses to check.`
74
+ }
@@ -0,0 +1 @@
1
+ export { default } from "@omacode/guard"
@@ -0,0 +1 @@
1
+ export * from "@omacode/guard/wire"