@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/cli.ts ADDED
@@ -0,0 +1,117 @@
1
+ // Command line: npm run eval -- [--floor 0.8] [--backend typesafe] [--journal path]
2
+ // npm run export-dataset -- [--target openjev|gliner|router] [--out file] [--journal path]
3
+ // npm run bench-guards -- [--cases bench/guard_cases.json] [--url http://127.0.0.1:8781/v1/systemone] [--repeat]
4
+ // npm run bench-n7 -- [--cases bench/followup_cases.json]
5
+ // node src/cli.ts status [--project dir] [--all] [--watch] (an ASCII board of the newest job, or of all)
6
+ // node src/cli.ts sandboxed --dir D -- <command…> (one command in the writer's sandbox of D, offline;
7
+ // the evolver's candidates run under it, src/evolver.ts)
8
+
9
+ import { spawnSync } from "node:child_process"
10
+ import { writeFileSync } from "node:fs"
11
+
12
+ import { DEFAULT_BACKENDS, Decider, makeAskers } from "./backends.ts"
13
+ import { drift, formatDrift, formatN7, formatSweep, loadCases, loadN7, scoreCases, scoreN7, sweep } from "./bench.ts"
14
+ import { apiKey } from "./jev.ts"
15
+ import { glinerRows, openJevRows } from "./dataset.ts"
16
+ import { evaluate, formatReport } from "./eval.ts"
17
+ import { journalPath, readJournal } from "./journal.ts"
18
+ import { board } from "./board.ts"
19
+ import { listJobs } from "./store.ts"
20
+ import { outcomesPath, readOutcomes, routerRows } from "./outcomes.ts"
21
+ import { cleanEnv, rulesFor, startSandbox } from "./sandbox.ts"
22
+
23
+ function flag(args: readonly string[], name: string): string | undefined {
24
+ const i = args.indexOf(`--${name}`)
25
+ return i >= 0 ? args[i + 1] : undefined
26
+ }
27
+
28
+ // A word as the shell reads it back: single-quoted unless it needs nothing.
29
+ const quote = (w: string) => (/^[\w@%+=:,./-]+$/.test(w) ? w : `'${w.replace(/'/g, "'\\''")}'`)
30
+
31
+ export async function main(argv: readonly string[]): Promise<number> {
32
+ const [command, ...args] = argv
33
+ if (command === "sandboxed") {
34
+ // Model-written code the evolver measures: it may write its own directory and nothing else, reaches no network
35
+ // beyond the package registries, and gets the cleaned environment. Without a sandbox it does not run at all.
36
+ const dir = flag(args, "dir")
37
+ const sep = args.indexOf("--")
38
+ if (!dir || sep < 0 || sep === args.length - 1) {
39
+ console.error("usage: sandboxed --dir D -- <command…>")
40
+ return 2
41
+ }
42
+ const box = await startSandbox()
43
+ if (!box.available) {
44
+ console.error(`no sandbox here (${box.reason}); the command is not run`)
45
+ return 126
46
+ }
47
+ try {
48
+ // The held-out corpus lies in the plugin's state directory, which the sandbox keeps from every worker; the
49
+ // evaluator measuring the best candidate on it (MM_CORPUS_DIR) may read that one directory, read-only.
50
+ const rules = rulesFor({ role: "code", writer: true, dir, worktree: dir, domains: [] })
51
+ const corpus = process.env.MM_CORPUS === "heldout" ? process.env.MM_CORPUS_DIR : undefined
52
+ const allowed = corpus ? { ...rules, filesystem: { ...rules.filesystem, allowRead: [...rules.filesystem.allowRead, corpus] } } : rules
53
+ const wrapped = await box.wrap(args.slice(sep + 1).map(quote).join(" "), allowed)
54
+ const r = spawnSync("bash", ["-c", wrapped], { cwd: dir, stdio: "inherit", env: cleanEnv(process.env, ["MM_CORPUS", "MM_CORPUS_DIR", "MM_REPEAT"]) })
55
+ return r.status ?? 1
56
+ } finally {
57
+ await box.stop()
58
+ }
59
+ }
60
+ if (command === "status") {
61
+ const project = flag(args, "project") ?? process.cwd()
62
+ const draw = () => {
63
+ const jobs = listJobs(project)
64
+ const shown = args.includes("--all") ? jobs : jobs.slice(0, 1)
65
+ const width = Math.max(80, (process.stdout.columns ?? 120) - 2)
66
+ return shown.length ? shown.map((j) => board(j, width)).join("\n\n") : `no micromanager job in ${project}`
67
+ }
68
+ if (!args.includes("--watch")) {
69
+ console.log(draw())
70
+ return 0
71
+ }
72
+ for (;;) {
73
+ process.stdout.write(`\x1b[2J\x1b[H${draw()}\n\n(redraws every 2 s; ctrl-c ends)\n`)
74
+ await new Promise((r) => setTimeout(r, 2000))
75
+ }
76
+ }
77
+ if (command === "bench-guards") {
78
+ const config = { ...DEFAULT_BACKENDS, urls: { ...DEFAULT_BACKENDS.urls, gliner: flag(args, "url") ?? DEFAULT_BACKENDS.urls.gliner } }
79
+ const decider = new Decider(config, makeAskers(config, undefined), () => {})
80
+ const cases = loadCases(flag(args, "cases") ?? "bench/guard_cases.json")
81
+ const rows = await scoreCases(decider, cases)
82
+ console.log(formatSweep(sweep(rows)))
83
+ if (args.includes("--repeat")) console.log(`\nrepeat run:\n${formatDrift(drift(rows, await scoreCases(decider, cases)))}`)
84
+ return 0
85
+ }
86
+ if (command === "bench-n7") {
87
+ // N7 runs on cloud Jev by default; the journal is not written, so bench runs never become training rows.
88
+ const decider = new Decider(DEFAULT_BACKENDS, makeAskers(DEFAULT_BACKENDS, apiKey()), () => {})
89
+ console.log(formatN7(await scoreN7(decider, loadN7(flag(args, "cases") ?? "bench/followup_cases.json"))))
90
+ return 0
91
+ }
92
+ const entries = readJournal(flag(args, "journal") ?? journalPath())
93
+ if (command === "eval") {
94
+ const floor = Number(flag(args, "floor") ?? 0.8)
95
+ console.log(formatReport(evaluate(entries, floor, flag(args, "backend")), floor))
96
+ return 0
97
+ }
98
+ if (command === "export-dataset") {
99
+ const targetName = flag(args, "target") ?? "openjev"
100
+ if (targetName !== "openjev" && targetName !== "gliner" && targetName !== "router") {
101
+ console.error(`unknown target ${targetName}: openjev, gliner or router`)
102
+ return 2
103
+ }
104
+ // router: the outcome log (src/outcomes.ts), one row per task with a trial's attempts joined, not the journal.
105
+ const rows = targetName === "router" ? routerRows(readOutcomes(flag(args, "outcomes") ?? outcomesPath())) : targetName === "gliner" ? glinerRows(entries) : openJevRows(entries)
106
+ const text = rows.map((r) => JSON.stringify(r)).join("\n") + (rows.length ? "\n" : "")
107
+ const out = flag(args, "out")
108
+ if (out) writeFileSync(out, text)
109
+ else process.stdout.write(text)
110
+ console.error(`${rows.length} ${targetName} rows${out ? ` -> ${out}` : ""}`)
111
+ return 0
112
+ }
113
+ console.error("usage: cli.ts eval|export-dataset|bench-guards|bench-n7 [options]")
114
+ return 2
115
+ }
116
+
117
+ if (import.meta.main) process.exit(await main(process.argv.slice(2)))
package/src/compact.ts ADDED
@@ -0,0 +1,162 @@
1
+ // Jev compaction of the micromanager's context (the user's request after reading about Jev token savings, 2026-10-05).
2
+ // The orchestrator is the biggest consumer: in a real session it carried 360k input tokens, its workers 10-40k each,
3
+ // because every turn resends every old tool result (task reports, reads, refused attempts).
4
+ //
5
+ // Before each of its turns, old and large tool results become candidates; Jev answers per candidate whether the
6
+ // micromanager still needs it; the ones it does not are replaced by a one-line stub that says how to get them back. The
7
+ // context hook's messages are what the provider gets (Phase E spike: a replaced tool result never reached the model),
8
+ // and the hook is awaited, so Jev can answer in time.
9
+ //
10
+ // A decision sticks: a pruned result stays pruned in every later turn, so the history's prefix does not change back
11
+ // and forth (prompt caches). A kept one is asked again only after it has aged.
12
+
13
+ import { NOUL_FLOOR } from "./catalog.ts"
14
+ import type { Decider } from "./backends.ts"
15
+ import type { Question } from "./jev.ts"
16
+
17
+ // The context hook's message shapes (opencode 2.0.18, seen in the spike).
18
+ interface Part {
19
+ type?: string
20
+ id?: string
21
+ name?: string
22
+ input?: unknown
23
+ text?: string
24
+ result?: { type?: string; value?: unknown }
25
+ }
26
+ interface Message {
27
+ role?: string
28
+ content?: Part[] | string
29
+ }
30
+
31
+ export interface Candidate {
32
+ readonly id: string // the tool call id
33
+ readonly tool: string
34
+ readonly input: string
35
+ readonly size: number // characters of its result
36
+ readonly age: number // assistant turns since it came in
37
+ readonly head: string // the start of the result, for the decision
38
+ }
39
+
40
+ export interface CompactOptions {
41
+ readonly keepTurns: number // results of the last turns are never candidates
42
+ readonly minChars: number // smaller results are not worth a decision
43
+ readonly startChars: number // compaction starts when candidates hold this much
44
+ readonly reaskAge: number // a kept result is asked about again after this many more turns
45
+ readonly ruleAge: number // without an answer, results older than this go
46
+ readonly tools?: ReadonlySet<string> // only these tools' results are candidates (absent: all)
47
+ readonly subject?: string // who the context belongs to, for Jev's question (default: the orchestrator)
48
+ }
49
+
50
+ export const DEFAULT_COMPACT: CompactOptions = { keepTurns: 2, minChars: 800, startChars: 20_000, reaskAge: 6, ruleAge: 8 }
51
+
52
+ const valueOf = (p: Part) => (typeof p.result?.value === "string" ? p.result.value : p.result?.value === undefined ? "" : JSON.stringify(p.result.value))
53
+
54
+ export function stub(c: Pick<Candidate, "tool" | "input" | "size">): string {
55
+ return `[micromanager: this earlier ${c.tool} result (${c.size} characters; ${c.input.slice(0, 120)}) was dropped from your context, as it is no longer needed; call the tool again if you need it]`
56
+ }
57
+
58
+ // Old, large tool results, with their call's input and their age in assistant turns.
59
+ export function candidates(messages: readonly Message[], o: CompactOptions = DEFAULT_COMPACT): Candidate[] {
60
+ const inputs = new Map<string, string>()
61
+ const out: Candidate[] = []
62
+ let assistantTurns = 0
63
+ const seen: { part: Part; at: number }[] = []
64
+ for (const m of messages) {
65
+ if (!Array.isArray(m.content)) continue
66
+ if (m.role === "assistant") {
67
+ assistantTurns++
68
+ for (const p of m.content) if (p.type === "tool-call" && p.id) inputs.set(p.id, JSON.stringify(p.input ?? {}))
69
+ }
70
+ if (m.role === "tool") for (const p of m.content) if (p.type === "tool-result" && p.id) seen.push({ part: p, at: assistantTurns })
71
+ }
72
+ for (const { part, at } of seen) {
73
+ const text = valueOf(part)
74
+ const age = assistantTurns - at
75
+ if (age < o.keepTurns || text.length < o.minChars || text.startsWith("[micromanager: this earlier") || text.startsWith("[context: ")) continue
76
+ if (o.tools && !o.tools.has(part.name ?? "")) continue
77
+ out.push({ id: part.id!, tool: part.name ?? "tool", input: inputs.get(part.id!) ?? "", size: text.length, age, head: text.slice(0, 400) })
78
+ }
79
+ return out
80
+ }
81
+
82
+ // Replaces the results of the given calls in place; returns the characters removed.
83
+ export function prune(messages: Message[], drop: ReadonlyMap<string, Candidate>): number {
84
+ let removed = 0
85
+ for (const m of messages) {
86
+ if (m.role !== "tool" || !Array.isArray(m.content)) continue
87
+ for (const p of m.content) {
88
+ const c = p.type === "tool-result" && p.id ? drop.get(p.id) : undefined
89
+ if (!c || !p.result) continue
90
+ const before = valueOf(p).length
91
+ p.result = { type: "text", value: stub(c) }
92
+ removed += before - stub(c).length
93
+ }
94
+ }
95
+ return removed
96
+ }
97
+
98
+ export function compactQuestions(cands: readonly Candidate[], subject = "orchestrator"): Record<string, Question> {
99
+ return Object.fromEntries(cands.map((c, i) => [`needed.${i}`, {
100
+ type: "noul",
101
+ instructions: `The ${subject} still needs the result of call ${i} (${c.tool}, ${c.input.slice(0, 160)}) to finish ${subject === "orchestrator" ? "the user's request" : "its task"}: it is not yet acted on, and no later result replaces it.`,
102
+ } satisfies Question]))
103
+ }
104
+
105
+ // The last user request and the orchestrator's last words: what "still needed" is judged against.
106
+ function focus(messages: readonly Message[]): { request: string; latest: string } {
107
+ const text = (m: Message) => (typeof m.content === "string" ? m.content : (m.content ?? []).filter((p) => p.type === "text").map((p) => p.text ?? "").join(" "))
108
+ const users = messages.filter((m) => m.role === "user")
109
+ const assistants = messages.filter((m) => m.role === "assistant").map(text).filter(Boolean)
110
+ return { request: text(users.at(-1) ?? {}).slice(0, 2000), latest: (assistants.at(-1) ?? "").slice(0, 1500) }
111
+ }
112
+
113
+ export class Compactor {
114
+ readonly #decider: Decider | undefined
115
+ readonly #o: CompactOptions
116
+ readonly #journal: (entry: Record<string, unknown>) => void
117
+ readonly #pruned = new Map<string, Map<string, Candidate>>() // session -> call id -> what was dropped
118
+ readonly #kept = new Map<string, Map<string, number>>() // session -> call id -> its age when kept
119
+
120
+ constructor(decider: Decider | undefined, journal: (entry: Record<string, unknown>) => void, options: Partial<CompactOptions> = {}) {
121
+ this.#decider = decider
122
+ this.#journal = journal
123
+ this.#o = { ...DEFAULT_COMPACT, ...options }
124
+ }
125
+
126
+ // One turn of the micromanager: decides on new candidates when it is worth it, then prunes everything decided so far.
127
+ async apply(sessionID: string, messages: unknown): Promise<{ removed: number; asked: number }> {
128
+ if (!Array.isArray(messages)) return { removed: 0, asked: 0 }
129
+ const { asked, pruned } = await this.judge(sessionID, messages)
130
+ const removed = prune(messages as Message[], pruned)
131
+ if (asked) this.#journal({ kind: "compaction", sessionID, asked, pruned: pruned.size, removedChars: removed })
132
+ return { removed, asked }
133
+ }
134
+
135
+ // Decides on new candidates when it is worth it and returns everything dropped so far, without touching the
136
+ // messages: the context manager applies it at its next epoch (src/context/manager.ts).
137
+ async judge(sessionID: string, messages: unknown): Promise<{ asked: number; pruned: ReadonlyMap<string, Candidate> }> {
138
+ if (!Array.isArray(messages)) return { asked: 0, pruned: new Map() }
139
+ const msgs = messages as Message[]
140
+ const pruned = this.#pruned.get(sessionID) ?? new Map<string, Candidate>()
141
+ const kept = this.#kept.get(sessionID) ?? new Map<string, number>()
142
+ this.#pruned.set(sessionID, pruned)
143
+ this.#kept.set(sessionID, kept)
144
+ const cands = candidates(msgs, this.#o).filter((c) => !pruned.has(c.id))
145
+ const open = cands.filter((c) => !kept.has(c.id) || c.age - kept.get(c.id)! >= this.#o.reaskAge)
146
+ const load = cands.reduce((n, c) => n + c.size, 0)
147
+ let asked = 0
148
+ if (open.length && load >= this.#o.startChars) {
149
+ const answers = this.#decider
150
+ ? (await this.#decider.ask("N14", { ...focus(msgs), results: open.map((c, i) => ({ call: i, tool: c.tool, input: c.input.slice(0, 300), age: c.age, start: c.head })) }, compactQuestions(open, this.#o.subject), { job: sessionID }).catch(() => undefined))?.decision.answers ?? {}
151
+ : {}
152
+ asked = open.length
153
+ open.forEach((c, i) => {
154
+ const a = answers[`needed.${i}`]
155
+ const needed = a?.type === "noul" ? a.noul >= NOUL_FLOOR : c.age < this.#o.ruleAge
156
+ if (needed) kept.set(c.id, c.age)
157
+ else pruned.set(c.id, c)
158
+ })
159
+ }
160
+ return { asked, pruned }
161
+ }
162
+ }
package/src/config.ts ADDED
@@ -0,0 +1,340 @@
1
+ // ~/.config/opencode/micromanager.jsonc: optional overrides of the routing (JSON with // comments).
2
+
3
+ import { existsSync, readFileSync } from "node:fs"
4
+ import { homedir } from "node:os"
5
+ import { join } from "node:path"
6
+
7
+ import { DEFAULT_FLOORS, type Floors } from "./decide.ts"
8
+ import { validatePolicies, type PolicySet } from "./policy.ts"
9
+ import { DEFAULT_REGISTRY, mergeRegistry, type ModelEntry } from "./registry.ts"
10
+ import { DEFAULT_ROUTING, type Routing } from "./routing.ts"
11
+ import { ROLES } from "./roles.ts"
12
+ import { DEFAULT_GRACE, DEFAULT_PICK, DEFAULT_TRIALS, MAX_TRIALS, type Grace, type Pick as TrialPick } from "./trials.ts"
13
+ import type { NotifyMode } from "./scheduler.ts"
14
+ import { DEFAULT_REDACT, parseRedact, type RedactSettings } from "@omacode/core/redact-config"
15
+ import { stripComments } from "@omacode/core/jsonc"
16
+
17
+ export { DEFAULT_REDACT, parseRedact, stripComments, type RedactSettings }
18
+
19
+ // The name before 2026-10-19 (jev-micromanager.jsonc) is still read while the new one does not exist.
20
+ export function configPath(): string {
21
+ const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config")
22
+ const path = join(base, "opencode", "micromanager.jsonc")
23
+ const old = join(base, "opencode", "jev-micromanager.jsonc")
24
+ return !existsSync(path) && existsSync(old) ? old : path
25
+ }
26
+
27
+ import {
28
+ loadPicks,
29
+ NO_PICKS,
30
+ parsePicks,
31
+ parseRouting,
32
+ picksPath,
33
+ savePicks,
34
+ type Picks,
35
+ } from "@omacode/state/picks"
36
+ export { loadPicks, NO_PICKS, parsePicks, parseRouting, picksPath, savePicks, type Picks }
37
+
38
+ export function parseFloors(text: string): Floors {
39
+ const raw = (JSON.parse(stripComments(text)) as { floors?: Record<string, unknown> }).floors ?? {}
40
+ const floors: Record<string, number> = { ...DEFAULT_FLOORS }
41
+ for (const [key, value] of Object.entries(raw)) {
42
+ if (!(key in DEFAULT_FLOORS)) throw new Error(`unknown floor ${JSON.stringify(key)}`)
43
+ const max = key === "risk" ? 2 : 1
44
+ if (typeof value !== "number" || value < 0 || value > max) throw new Error(`floors.${key} must be a number from 0 to ${max}`)
45
+ floors[key] = value
46
+ }
47
+ return floors as unknown as Floors
48
+ }
49
+
50
+ // "decisions": the global policy per decision key, e.g. { "N6.pipeline": "fixed:P1", "N5": "ask" } (design.md §22).
51
+ export function parseDecisions(text: string): PolicySet {
52
+ const raw = (JSON.parse(stripComments(text)) as { decisions?: unknown }).decisions ?? {}
53
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("decisions must be an object")
54
+ const errors = validatePolicies(raw as Record<string, unknown>)
55
+ if (errors.length > 0) throw new Error(errors.join("; "))
56
+ return raw as PolicySet
57
+ }
58
+
59
+ // "registry": models to add or change by id, e.g. [{ "id": "llamaswap/mimo", "disabled": true }] (design.md §19).
60
+ export function parseRegistry(text: string): ModelEntry[] {
61
+ const raw = (JSON.parse(stripComments(text)) as { registry?: unknown }).registry ?? []
62
+ if (!Array.isArray(raw) || !raw.every((e) => typeof e === "object" && e !== null && typeof (e as { id?: unknown }).id === "string" && (e as { id: string }).id.includes("/"))) {
63
+ throw new Error('registry must be a list of objects with an "id" like "provider/model"')
64
+ }
65
+ return mergeRegistry(DEFAULT_REGISTRY, raw as Partial<ModelEntry>[])
66
+ }
67
+
68
+ // "notify": desktop notifications when a job needs the user or ends ("jobs", the default), also per task ("tasks"),
69
+ // or never ("off"). Updates in the micromanager's session come either way.
70
+ export function parseNotify(text: string): NotifyMode {
71
+ const raw = (JSON.parse(stripComments(text)) as { notify?: unknown }).notify ?? "jobs"
72
+ if (raw !== "jobs" && raw !== "tasks" && raw !== "off") throw new Error('notify must be "jobs", "tasks" or "off"')
73
+ return raw
74
+ }
75
+
76
+ // "budget": per job, { "tokens": 4000000, "requests": 800, "cost": 5 }; the defaults below, capped by hard ceilings
77
+ // so a typo cannot make a job unbounded (design.md §10.2).
78
+ export interface Budget {
79
+ readonly tokens?: number
80
+ readonly requests?: number
81
+ readonly cost?: number
82
+ }
83
+
84
+ // No limits unless the config sets them (the user's choice, 2026-10-05: a job cut at a limit wastes its work).
85
+ export const DEFAULT_BUDGET: Budget = {}
86
+ const CEILINGS = { tokens: 50_000_000, requests: 5000, cost: 1000 } as const
87
+
88
+ export function parseBudget(text: string): Budget {
89
+ const raw = (JSON.parse(stripComments(text)) as { budget?: unknown }).budget
90
+ if (raw === undefined) return DEFAULT_BUDGET
91
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("budget must be an object")
92
+ const out: Record<string, number> = { ...DEFAULT_BUDGET }
93
+ for (const [key, value] of Object.entries(raw)) {
94
+ if (!(key in CEILINGS)) throw new Error(`unknown budget ${JSON.stringify(key)}`)
95
+ if (typeof value !== "number" || value <= 0) throw new Error(`budget.${key} must be a positive number`)
96
+ out[key] = Math.min(value, CEILINGS[key as keyof typeof CEILINGS])
97
+ }
98
+ return out
99
+ }
100
+
101
+ // "checkTimeout": how long one check of a task may run, in seconds (default 300). A check that hangs must not hold
102
+ // the job's gate for ever, and a long build needs more than the default. The job may lower or raise it for itself
103
+ // (src/state.ts Job.checkTimeoutMs); the default stays 300 s.
104
+ export const DEFAULT_CHECK_TIMEOUT_MS = 300_000
105
+ const CHECK_TIMEOUT_CEILING_MS = 3_600_000
106
+
107
+ export function parseCheckTimeout(text: string): number {
108
+ const raw = (JSON.parse(stripComments(text)) as { checkTimeout?: unknown }).checkTimeout
109
+ if (raw === undefined) return DEFAULT_CHECK_TIMEOUT_MS
110
+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw <= 0) throw new Error("checkTimeout must be a number of seconds above 0")
111
+ return Math.min(Math.round(raw * 1000), CHECK_TIMEOUT_CEILING_MS)
112
+ }
113
+
114
+ // "parallel": tasks of one job at the same time (default 3, at most 6); 1 runs them one after another.
115
+ // "perModel": sessions of one cloud model at the same time (default 2, at most 4); a local model serves one.
116
+ export function parseParallel(text: string): { parallel: number; perModel: number } {
117
+ const raw = JSON.parse(stripComments(text)) as { parallel?: unknown; perModel?: unknown }
118
+ const int = (v: unknown, name: string, def: number, max: number) => {
119
+ if (v === undefined) return def
120
+ if (typeof v !== "number" || !Number.isInteger(v) || v < 1) throw new Error(`${name} must be a whole number from 1`)
121
+ return Math.min(v, max)
122
+ }
123
+ return { parallel: int(raw.parallel, "parallel", 3, 6), perModel: int(raw.perModel, "perModel", 2, 4) }
124
+ }
125
+
126
+ // "trials": attempts a hard writer task runs as at once, each on another model (default 1: one worker, then a retry;
127
+ // set 2-4 for a trial; src/trials.ts).
128
+ export function parseTrials(text: string): number {
129
+ const raw = (JSON.parse(stripComments(text)) as { trials?: unknown }).trials
130
+ if (raw === undefined) return DEFAULT_TRIALS
131
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 1) throw new Error("trials must be a whole number from 1")
132
+ return Math.min(raw, MAX_TRIALS)
133
+ }
134
+
135
+ // "trialDeadline": minutes a trial decided by score (an attempt measured against a fitness contract, src/contract.ts)
136
+ // waits after its first passing attempt for the others; then the best of the passed ones is merged. Default 20.
137
+ export function parseTrialDeadline(text: string): number {
138
+ const raw = (JSON.parse(stripComments(text)) as { trialDeadline?: unknown }).trialDeadline
139
+ if (raw === undefined) return 20
140
+ if (typeof raw !== "number" || !(raw > 0)) throw new Error("trialDeadline must be a number of minutes above 0")
141
+ return raw
142
+ }
143
+
144
+ // "trialPick": who decides a trial, by agent ("designer") or role id ("visual"), "*" for the rest: "first", "best" or
145
+ // "user" (src/trials.ts; a contract always decides by score). Keys not named keep their default.
146
+ export function parseTrialPick(text: string): Record<string, TrialPick> {
147
+ const raw = (JSON.parse(stripComments(text)) as { trialPick?: unknown }).trialPick
148
+ const out: Record<string, TrialPick> = { ...DEFAULT_PICK }
149
+ if (raw === undefined) return out
150
+ const shape = 'trialPick must be { "<agent or *>": "first" | "best" | "user" }'
151
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error(shape)
152
+ for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
153
+ if (v !== "first" && v !== "best" && v !== "user") throw new Error(shape)
154
+ const role = k === "*" ? undefined : ROLES.find((r) => r.agent === k || r.id === k)
155
+ if (k !== "*" && !role) throw new Error(`trialPick: unknown agent ${JSON.stringify(k)}`)
156
+ out[role?.id ?? "*"] = v
157
+ }
158
+ return out
159
+ }
160
+
161
+ // "trialGrace": the grace window of a "best" trial: the others get factor x the first passing attempt's time, at least
162
+ // minMinutes and at most maxMinutes. Default 0.5, 2 and 10.
163
+ export function parseTrialGrace(text: string): Grace {
164
+ const raw = (JSON.parse(stripComments(text)) as { trialGrace?: unknown }).trialGrace
165
+ if (raw === undefined) return DEFAULT_GRACE
166
+ const shape = 'trialGrace must be { "factor": 0.., "minMinutes": 0.., "maxMinutes": 0.. }'
167
+ if (typeof raw !== "object" || raw === null) throw new Error(shape)
168
+ const g = raw as { factor?: unknown; minMinutes?: unknown; maxMinutes?: unknown }
169
+ for (const v of [g.factor, g.minMinutes, g.maxMinutes]) if (v !== undefined && (typeof v !== "number" || v < 0)) throw new Error(shape)
170
+ const minutes = (v: unknown, d: number) => (v === undefined ? d : (v as number) * 60_000)
171
+ return { factor: (g.factor as number | undefined) ?? DEFAULT_GRACE.factor, minMs: minutes(g.minMinutes, DEFAULT_GRACE.minMs), maxMs: minutes(g.maxMinutes, DEFAULT_GRACE.maxMs) }
172
+ }
173
+
174
+ // "cloudOnly": true (the default for now, the user's choice of 2026-10-05) routes no task to a local model and asks
175
+ // cloud Jev for the guards instead of the local GLiNER server. false brings the local fleet and GLiNER back.
176
+ export function parseCloudOnly(text: string): boolean {
177
+ const raw = (JSON.parse(stripComments(text)) as { cloudOnly?: unknown }).cloudOnly ?? true
178
+ if (typeof raw !== "boolean") throw new Error("cloudOnly must be true or false")
179
+ return raw
180
+ }
181
+
182
+ // "githubBacklog": the GitHub repositories ("owner/name") whose issues labelled micromanager are part of the backlog
183
+ // (src/backlog.ts, design.md §25 P7). Off for every other project: an issue is published content, so each repository is
184
+ // opted in by name. Reading them is free; an issue is only ever created after the user says so in a form.
185
+ export function parseGithubBacklog(text: string): readonly string[] {
186
+ const raw = (JSON.parse(stripComments(text)) as { githubBacklog?: unknown }).githubBacklog ?? []
187
+ if (!Array.isArray(raw) || raw.some((r) => typeof r !== "string" || !/^[\w.-]+\/[\w.-]+$/.test(r))) throw new Error('githubBacklog must be a list of repositories, e.g. ["owner/name"]')
188
+ return raw.map((r: string) => r.toLowerCase())
189
+ }
190
+
191
+ // "evolver": { "maxEvalSeconds": 600 }: the longest full measurement for which the plugin still offers the evolver
192
+ // (src/evolver.ts). Long ones are what a multi-step algorithm takes; a quick stage in the contract keeps them affordable.
193
+ export function parseEvolver(text: string): number {
194
+ const raw = (JSON.parse(stripComments(text)) as { evolver?: { maxEvalSeconds?: unknown } }).evolver?.maxEvalSeconds
195
+ if (raw === undefined) return 600
196
+ if (typeof raw !== "number" || !(raw > 0)) throw new Error("evolver.maxEvalSeconds must be a number of seconds above 0")
197
+ return raw
198
+ }
199
+
200
+ // "allowOutside": absolute paths (or path prefixes) a worker may reach even where src/decide.ts refuses, e.g.
201
+ // ["/home/u/.config/omarchy"]. Empty by default: the user's list is the only thing that lifts those rules, and it lifts
202
+ // nothing until they write it. A wrong entry here is a widened rule, so the value is checked, not cast: a list of
203
+ // non-empty strings, each of which resolves to an absolute path. `~` is left to src/decide.ts to expand, so what the
204
+ // user wrote is what they can see in the journal.
205
+ export function parseAllowOutside(text: string): readonly string[] {
206
+ const raw = (JSON.parse(stripComments(text)) as { allowOutside?: unknown }).allowOutside ?? []
207
+ if (!Array.isArray(raw)) throw new Error('allowOutside must be a list of absolute paths, e.g. ["/home/u/.config/omarchy"]')
208
+ const out: string[] = []
209
+ for (const entry of raw) {
210
+ if (typeof entry !== "string" || entry.trim() === "") {
211
+ throw new Error(`allowOutside must be a list of absolute paths; ${JSON.stringify(entry)} is not one`)
212
+ }
213
+ const path = entry.trim()
214
+ // A relative entry is a silent no-op or, worse, a guess at the cwd of whatever asked; say so instead.
215
+ if (!path.startsWith("/") && path !== "~" && !path.startsWith("~/")) {
216
+ throw new Error(`allowOutside entries must be absolute paths (or start with ~), got ${JSON.stringify(entry)}`)
217
+ }
218
+ // The entry is kept as written (src/decide.ts normalises it when it matches), so the journal shows the user their
219
+ // own words. A repeated entry is dropped: a list that lists the same path twice says nothing a list says once.
220
+ if (!out.includes(path)) out.push(path)
221
+ }
222
+ return out
223
+ }
224
+
225
+ // "sandbox": run worker commands in the sandbox (src/shell/sandbox.ts; default true). "env": names of variables worker
226
+ // commands keep beyond the allowlist ("DATABASE_URL", or "MYAPP_*"). "network": domains worker commands may reach
227
+ // beyond the package registries ("api.example.com", "*.example.com", "host:8443"). Both lists are the user's standing
228
+ // grants for every job; a single job's grants come from request_env / request_network.
229
+ export function parseSandbox(text: string): { sandbox: boolean; env: readonly string[]; network: readonly string[] } {
230
+ const raw = JSON.parse(stripComments(text)) as { sandbox?: unknown; env?: unknown; network?: unknown }
231
+ const sandbox = raw.sandbox ?? true
232
+ if (typeof sandbox !== "boolean") throw new Error("sandbox must be true or false")
233
+ const list = (value: unknown, name: string, ok: RegExp, example: string): string[] => {
234
+ if (value === undefined) return []
235
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string" && ok.test(v))) throw new Error(`${name} must be a list like ${example}`)
236
+ return [...new Set(value as string[])]
237
+ }
238
+ return {
239
+ sandbox,
240
+ env: list(raw.env, "env", /^[A-Za-z_][A-Za-z0-9_]*\*?$/, '["DATABASE_URL", "MYAPP_*"]'),
241
+ network: list(raw.network, "network", /^(\*\.)?[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(:\d{1,5})?$/, '["api.example.com", "*.example.com"]'),
242
+ }
243
+ }
244
+
245
+ // The memory (src/context/): on by default; "embedding" names the local service install.sh --embedding sets up, false
246
+ // for keyword search only. The model id is recorded with every vector, so a new size re-embeds rather than mixes.
247
+ export interface MemorySettings {
248
+ readonly enabled: boolean
249
+ readonly embedding: { readonly url: string; readonly model: string } | false
250
+ }
251
+
252
+ export const DEFAULT_MEMORY: MemorySettings = { enabled: true, embedding: { url: "http://127.0.0.1:8093", model: "qwen3-embedding-4b" } }
253
+
254
+ export function parseMemory(text: string): MemorySettings {
255
+ const raw = (JSON.parse(stripComments(text)) as { memory?: unknown }).memory
256
+ if (raw === undefined) return DEFAULT_MEMORY
257
+ if (typeof raw === "boolean") return { ...DEFAULT_MEMORY, enabled: raw }
258
+ if (typeof raw !== "object" || raw === null) throw new Error('memory must be true, false or { "embedding": { "url": …, "model": … } | false }')
259
+ const m = raw as { enabled?: unknown; embedding?: unknown }
260
+ if (m.enabled !== undefined && typeof m.enabled !== "boolean") throw new Error("memory.enabled must be true or false")
261
+ let embedding: MemorySettings["embedding"] = DEFAULT_MEMORY.embedding
262
+ if (m.embedding === false) embedding = false
263
+ else if (m.embedding !== undefined) {
264
+ const e = m.embedding as { url?: unknown; model?: unknown }
265
+ if (typeof e !== "object" || e === null || (e.url !== undefined && typeof e.url !== "string") || (e.model !== undefined && typeof e.model !== "string")) throw new Error('memory.embedding must be { "url": "http://…", "model": "qwen3-embedding-4b" } or false')
266
+ embedding = { url: String(e.url ?? (DEFAULT_MEMORY.embedding as { url: string }).url), model: String(e.model ?? (DEFAULT_MEMORY.embedding as { model: string }).model) }
267
+ }
268
+ return { enabled: m.enabled ?? true, embedding }
269
+ }
270
+
271
+ // With cloudOnly, local models stay in the registry (they show up in the journal's ranking) but are never routed to.
272
+ export function cloudRegistry(registry: readonly ModelEntry[]): ModelEntry[] {
273
+ return registry.map((m) => (m.location === "local" ? { ...m, disabled: true } : m))
274
+ }
275
+
276
+ export interface Settings {
277
+ readonly cloudOnly: boolean
278
+ readonly parallel: number
279
+ readonly perModel: number
280
+ readonly trials: number
281
+ readonly trialDeadline: number // minutes
282
+ readonly budget: Budget
283
+ // How long one check may run, in milliseconds (default 300 s). A job may override it (src/state.ts).
284
+ readonly checkTimeoutMs: number
285
+ readonly notify: NotifyMode
286
+ readonly routing: Routing
287
+ readonly floors: Floors
288
+ readonly decisions: PolicySet
289
+ readonly registry: readonly ModelEntry[]
290
+ readonly allowOutside: readonly string[]
291
+ readonly githubBacklog: readonly string[]
292
+ readonly evolverMaxEvalSeconds: number
293
+ readonly sandbox: boolean
294
+ readonly env: readonly string[]
295
+ readonly network: readonly string[]
296
+ readonly memory: MemorySettings
297
+ readonly redact: RedactSettings
298
+ readonly trialPick: Readonly<Record<string, TrialPick>>
299
+ readonly trialGrace: Grace
300
+ }
301
+
302
+ // The settings a config file that is missing or broken falls back to. One place, so the two returns below cannot drift
303
+ // apart and a setting added here is never left out of the error path.
304
+ const DEFAULTS: Omit<Settings, "registry"> = {
305
+ cloudOnly: true,
306
+ parallel: 3,
307
+ perModel: 2,
308
+ trials: DEFAULT_TRIALS,
309
+ trialDeadline: 20,
310
+ budget: DEFAULT_BUDGET,
311
+ checkTimeoutMs: DEFAULT_CHECK_TIMEOUT_MS,
312
+ notify: "jobs",
313
+ routing: DEFAULT_ROUTING,
314
+ floors: DEFAULT_FLOORS,
315
+ decisions: {},
316
+ allowOutside: [],
317
+ githubBacklog: [],
318
+ evolverMaxEvalSeconds: 600,
319
+ sandbox: true,
320
+ env: [],
321
+ network: [],
322
+ memory: DEFAULT_MEMORY,
323
+ redact: DEFAULT_REDACT,
324
+ trialPick: DEFAULT_PICK,
325
+ trialGrace: DEFAULT_GRACE,
326
+ }
327
+
328
+ export function loadSettings(path = configPath()): Settings & { error?: string } {
329
+ let text: string
330
+ try {
331
+ text = readFileSync(path, "utf8")
332
+ } catch {
333
+ return { ...DEFAULTS, registry: DEFAULT_REGISTRY } // no file: the defaults
334
+ }
335
+ try {
336
+ return { ...DEFAULTS, cloudOnly: parseCloudOnly(text), ...parseParallel(text), trials: parseTrials(text), trialDeadline: parseTrialDeadline(text), budget: parseBudget(text), checkTimeoutMs: parseCheckTimeout(text), notify: parseNotify(text), routing: parseRouting(text), floors: parseFloors(text), decisions: parseDecisions(text), registry: parseRegistry(text), allowOutside: parseAllowOutside(text), githubBacklog: parseGithubBacklog(text), evolverMaxEvalSeconds: parseEvolver(text), ...parseSandbox(text), memory: parseMemory(text), redact: parseRedact(text), trialPick: parseTrialPick(text), trialGrace: parseTrialGrace(text) }
337
+ } catch (err) {
338
+ return { ...DEFAULTS, registry: DEFAULT_REGISTRY, error: `${path}: ${String(err)}` }
339
+ }
340
+ }
@@ -0,0 +1 @@
1
+ export * from "@omacode/context/capture"
@@ -0,0 +1 @@
1
+ export * from "@omacode/context/digest"
@@ -0,0 +1 @@
1
+ export * from "@omacode/context/embed"
@@ -0,0 +1,2 @@
1
+ export { default } from "@omacode/context"
2
+ export * from "@omacode/context"
@@ -0,0 +1 @@
1
+ export * from "@omacode/context/ledger"
@@ -0,0 +1 @@
1
+ export * from "@omacode/context/manager"
@@ -0,0 +1 @@
1
+ export * from "@omacode/context/memory"
@@ -0,0 +1 @@
1
+ export * from "@omacode/context/policy"
@@ -0,0 +1 @@
1
+ export * from "@omacode/context/prices"
@@ -0,0 +1 @@
1
+ export * from "@omacode/context/recall"
@@ -0,0 +1 @@
1
+ export * from "@omacode/context/rules"