@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/backlog.ts ADDED
@@ -0,0 +1,436 @@
1
+ // The job backlog (design.md §25, P6): jobs that wait, one Markdown file each in <project>/.micromanager/backlog/,
2
+ // committed with the project. A job's follow-ups that nobody started and a trial whose attempts all failed become
3
+ // drafts here when the job ends, so nothing found on the way is lost with the session; the user or the micromanager
4
+ // starts an item later with plan_job backlog:<slug>, or as todos.
5
+ //
6
+ // Items are jobs, never a job's internal tasks: those are short-lived and live in the job file. The format is the same
7
+ // for every backend: a YAML front matter (a small subset: scalars, lists of scalars, lists of one-level maps, and
8
+ // JSON values) and a Markdown body; the GitHub backend (P7) puts the same text into an issue.
9
+
10
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"
11
+ import { tmpdir } from "node:os"
12
+ import { dirname, join } from "node:path"
13
+
14
+ import type { Question } from "./forms.ts"
15
+ import { exec, type Exec } from "./integration.ts"
16
+ import { checkProblem } from "./plan.ts"
17
+ import { scrub } from "./redact.ts"
18
+ import { failureDigest } from "./trials.ts"
19
+ import { stateDir } from "./store.ts"
20
+ import type { Job, Later, Task } from "./state.ts"
21
+
22
+ export type ItemStatus = "draft" | "ready" | "running" | "done" | "dropped"
23
+ export type ItemKind = "build" | "fix" | "optimize"
24
+
25
+ export interface BacklogItem {
26
+ readonly slug: string // the file name without .md
27
+ title: string
28
+ status: ItemStatus
29
+ order: number // lower runs first; steps of 10 leave room
30
+ kind: ItemKind
31
+ origin: "user" | "later" | "trial-failed"
32
+ from?: string // the job and task it came from: "job-…/T7"
33
+ job?: string // the job that works on it, once started
34
+ issue?: string // the GitHub issue it was published as (P7)
35
+ acceptance: { text: string; verify?: string }[]
36
+ checks: string[]
37
+ fitness?: Record<string, unknown> // a contract as the contract tool takes it (src/contract.ts)
38
+ created: string
39
+ body: string
40
+ }
41
+
42
+ const STATUSES = new Set<ItemStatus>(["draft", "ready", "running", "done", "dropped"])
43
+ const KINDS = new Set<ItemKind>(["build", "fix", "optimize"])
44
+
45
+ export function backlogDir(project: string): string {
46
+ return join(project, stateDir(project), "backlog")
47
+ }
48
+
49
+ // --- the front matter -------------------------------------------------------------------------------------------
50
+
51
+ type Value = string | number | boolean | null | Value[] | { [k: string]: Value }
52
+
53
+ function scalar(text: string): Value {
54
+ const t = text.trim()
55
+ if (t === "" || t === "~" || t === "null") return null
56
+ if (t === "true" || t === "false") return t === "true"
57
+ if (/^-?\d+(\.\d+)?$/.test(t)) return Number(t)
58
+ if (t.startsWith('"') || t.startsWith("{") || t.startsWith("[")) {
59
+ try {
60
+ return JSON.parse(t) as Value
61
+ } catch {
62
+ return t
63
+ }
64
+ }
65
+ if (t.startsWith("'") && t.endsWith("'") && t.length > 1) return t.slice(1, -1).replace(/''/g, "'")
66
+ return t.replace(/\s+#.*$/, "") // a comment after a plain value
67
+ }
68
+
69
+ // The subset of YAML the backlog writes, read back: "key: value", "key:" followed by "- item" lines, and an item that is
70
+ // a map of its own ("- text: …" with "verify: …" indented below it).
71
+ export function parseFrontMatter(text: string): Record<string, Value> {
72
+ const out: Record<string, Value> = {}
73
+ let list: Value[] | undefined
74
+ let map: Record<string, Value> | undefined
75
+ for (const raw of text.split("\n")) {
76
+ if (!raw.trim() || raw.trim().startsWith("#")) continue
77
+ const indent = raw.length - raw.trimStart().length
78
+ const line = raw.trim()
79
+ if (indent === 0) {
80
+ const m = line.match(/^([\w-]+):\s*(.*)$/)
81
+ if (!m) continue
82
+ list = undefined
83
+ map = undefined
84
+ if (m[2] === "") out[m[1]!] = list = []
85
+ else out[m[1]!] = scalar(m[2]!)
86
+ continue
87
+ }
88
+ if (!list) continue
89
+ if (line.startsWith("- ")) {
90
+ const item = line.slice(2)
91
+ const kv = item.match(/^([\w-]+):\s+(.*)$|^([\w-]+):$/)
92
+ if (kv && !item.startsWith('"')) {
93
+ map = { [kv[1] ?? kv[3]!]: scalar(kv[2] ?? "") }
94
+ list.push(map)
95
+ } else {
96
+ map = undefined
97
+ list.push(scalar(item))
98
+ }
99
+ } else if (map) {
100
+ const kv = line.match(/^([\w-]+):\s*(.*)$/)
101
+ if (kv) map[kv[1]!] = scalar(kv[2]!)
102
+ }
103
+ }
104
+ return out
105
+ }
106
+
107
+ // A string as the front matter writes it: plain when YAML reads it back as the same string, else JSON (a valid YAML
108
+ // double-quoted scalar).
109
+ function plain(s: string): string {
110
+ return /^[\w][\w ./@+()-]*$/.test(s) && !/^(true|false|null|~|-?\d+(\.\d+)?)$/.test(s) && !/\s$/.test(s) ? s : JSON.stringify(s)
111
+ }
112
+
113
+ export function renderItem(item: BacklogItem): string {
114
+ const lines = [
115
+ "---",
116
+ `title: ${plain(item.title)}`,
117
+ `status: ${item.status}`,
118
+ `order: ${item.order}`,
119
+ `kind: ${item.kind}`,
120
+ `origin: ${item.origin}`,
121
+ ...(item.from ? [`from: ${plain(item.from)}`] : []),
122
+ ...(item.job ? [`job: ${plain(item.job)}`] : []),
123
+ ...(item.issue ? [`issue: ${plain(item.issue)}`] : []),
124
+ `created: ${item.created}`,
125
+ ]
126
+ if (item.acceptance.length) {
127
+ lines.push("acceptance:")
128
+ for (const a of item.acceptance) lines.push(` - text: ${plain(a.text)}`, ...(a.verify ? [` verify: ${plain(a.verify)}`] : []))
129
+ }
130
+ if (item.checks.length) lines.push("checks:", ...item.checks.map((c) => ` - ${plain(c)}`))
131
+ if (item.fitness) lines.push(`fitness: ${JSON.stringify(item.fitness)}`)
132
+ lines.push("---", "", item.body.trim(), "")
133
+ return lines.join("\n")
134
+ }
135
+
136
+ // An item from its file's text; errors name what is wrong instead.
137
+ export function parseItem(text: string, slug: string): { item?: BacklogItem; errors: string[] } {
138
+ const m = text.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/)
139
+ if (!m) return { errors: [`${slug}: no front matter between --- lines`] }
140
+ const f = parseFrontMatter(m[1]!)
141
+ const errors: string[] = []
142
+ const title = typeof f.title === "string" ? f.title.trim() : ""
143
+ if (!title) errors.push(`${slug}: title is missing`)
144
+ const status = STATUSES.has(f.status as ItemStatus) ? (f.status as ItemStatus) : f.status === undefined ? "draft" : undefined
145
+ if (!status) errors.push(`${slug}: status must be one of ${[...STATUSES].join(", ")}`)
146
+ const kind = KINDS.has(f.kind as ItemKind) ? (f.kind as ItemKind) : f.kind === undefined ? "build" : undefined
147
+ if (!kind) errors.push(`${slug}: kind must be one of ${[...KINDS].join(", ")}`)
148
+ const acceptance = (Array.isArray(f.acceptance) ? f.acceptance : []).flatMap((a) => {
149
+ if (typeof a === "string") return [{ text: a }]
150
+ if (a && typeof a === "object" && !Array.isArray(a) && typeof a.text === "string") return [{ text: a.text, ...(typeof a.verify === "string" && a.verify ? { verify: a.verify } : {}) }]
151
+ return []
152
+ })
153
+ const checks = (Array.isArray(f.checks) ? f.checks : []).filter((c): c is string => typeof c === "string" && c.trim() !== "")
154
+ const fitness = f.fitness && typeof f.fitness === "object" && !Array.isArray(f.fitness) ? (f.fitness as Record<string, unknown>) : undefined
155
+ if (errors.length) return { errors }
156
+ return {
157
+ item: {
158
+ slug,
159
+ title,
160
+ status: status!,
161
+ order: typeof f.order === "number" ? f.order : 100,
162
+ kind: kind!,
163
+ origin: f.origin === "later" || f.origin === "trial-failed" ? f.origin : "user",
164
+ ...(typeof f.from === "string" ? { from: f.from } : {}),
165
+ ...(typeof f.job === "string" ? { job: f.job } : {}),
166
+ ...(typeof f.issue === "string" ? { issue: f.issue } : {}),
167
+ acceptance,
168
+ checks,
169
+ ...(fitness ? { fitness } : {}),
170
+ created: typeof f.created === "string" ? f.created : String(f.created ?? ""),
171
+ body: m[2]!.trim(),
172
+ },
173
+ errors,
174
+ }
175
+ }
176
+
177
+ // --- storage ----------------------------------------------------------------------------------------------------
178
+
179
+ // Where items live. Local files by default; the GitHub backend (P7) implements the same three calls.
180
+ export interface BacklogBackend {
181
+ list(project: string): BacklogItem[]
182
+ get(project: string, slug: string): BacklogItem | undefined
183
+ save(project: string, item: BacklogItem): string // where it went
184
+ }
185
+
186
+ export const localBackend: BacklogBackend = {
187
+ list(project) {
188
+ const dir = backlogDir(project)
189
+ if (!existsSync(dir)) return []
190
+ return readdirSync(dir)
191
+ .filter((f) => f.endsWith(".md"))
192
+ .flatMap((f) => parseItem(readFileSync(join(dir, f), "utf8"), f.slice(0, -3)).item ?? [])
193
+ .sort(byTurn)
194
+ },
195
+ get(project, slug) {
196
+ const path = join(backlogDir(project), `${slug}.md`)
197
+ return existsSync(path) ? parseItem(readFileSync(path, "utf8"), slug).item : undefined
198
+ },
199
+ save(project, item) {
200
+ const path = join(backlogDir(project), `${item.slug}.md`)
201
+ mkdirSync(dirname(path), { recursive: true })
202
+ const tmp = `${path}.${process.pid}.tmp`
203
+ writeFileSync(tmp, renderItem(item))
204
+ renameSync(tmp, path)
205
+ return path
206
+ },
207
+ }
208
+
209
+ // What runs first: the open items before the closed ones, ready before draft, then by order, then the oldest.
210
+ const RANK: Record<ItemStatus, number> = { running: 0, ready: 1, draft: 2, done: 3, dropped: 4 }
211
+ export function byTurn(a: BacklogItem, b: BacklogItem): number {
212
+ return RANK[a.status] - RANK[b.status] || a.order - b.order || a.created.localeCompare(b.created) || a.slug.localeCompare(b.slug)
213
+ }
214
+
215
+ // A file name from a title: lowercase words joined by dashes, at most six of them, unique among taken.
216
+ export function slugOf(title: string, taken: ReadonlySet<string>): string {
217
+ const base = title.toLowerCase().replace(/[äöüß]/g, (c) => ({ ä: "ae", ö: "oe", ü: "ue", ß: "ss" })[c]!).split(/[^a-z0-9]+/).filter(Boolean).slice(0, 6).join("-") || "item"
218
+ let slug = base
219
+ for (let n = 2; taken.has(slug); n++) slug = `${base}-${n}`
220
+ return slug
221
+ }
222
+
223
+ // --- drafts at a job's end --------------------------------------------------------------------------------------
224
+
225
+ function today(now: Date): string {
226
+ return now.toISOString().slice(0, 10)
227
+ }
228
+
229
+ // A follow-up a worker reported that no task of its job took up.
230
+ export function draftFromLater(l: Later, job: Job, taken: ReadonlySet<string>, now = new Date()): BacklogItem {
231
+ return {
232
+ slug: slugOf(l.what, taken),
233
+ title: l.what.slice(0, 120),
234
+ status: "draft",
235
+ order: 100,
236
+ kind: /\b(fix|bug|broken|fails?|crash)/i.test(l.what) ? "fix" : "build",
237
+ origin: "later",
238
+ from: `${job.id}/${l.from}`,
239
+ acceptance: [],
240
+ checks: [],
241
+ created: today(now),
242
+ body: [`## Goal\n${l.what}`, l.why ? `## Why\n${l.why}` : "", l.files.length ? `## Files\n${l.files.join(", ")}` : "", `Found by ${l.from} of ${job.id} (${job.goal.split("\n")[0]!.slice(0, 120)}).`].filter(Boolean).join("\n\n"),
243
+ }
244
+ }
245
+
246
+ // A task whose trial failed on every attempt (k = 0) and that nothing did over: too big or too unclear for one worker,
247
+ // so it comes back as a job of its own, with what each attempt hit.
248
+ export function draftFromTrial(job: Job, head: Task, failed: readonly Task[], checks: readonly string[], taken: ReadonlySet<string>, now = new Date()): BacklogItem {
249
+ const title = head.title.replace(/ \(attempt \d+\/\d+\)$/, "")
250
+ return {
251
+ slug: slugOf(title, taken),
252
+ title: title.slice(0, 120),
253
+ status: "draft",
254
+ order: 100,
255
+ kind: head.contract ? "optimize" : "build",
256
+ origin: "trial-failed",
257
+ from: `${job.id}/${head.id}`,
258
+ acceptance: [],
259
+ checks: [...checks],
260
+ created: today(now),
261
+ body: [`## Goal\n${head.description}`, `## What the ${failed.length} attempts hit\n${failureDigest(failed)}`, "Split it into smaller tasks before it runs again."].join("\n\n"),
262
+ }
263
+ }
264
+
265
+ // The goal plan_job plans from, for an item: its title, body, acceptance points and checks in words the planner reads.
266
+ export function goalOf(item: BacklogItem): string {
267
+ return [
268
+ item.title,
269
+ item.body,
270
+ item.acceptance.length ? `Acceptance:\n${item.acceptance.map((a) => `- ${a.text}${a.verify ? ` (checked with: ${a.verify})` : ""}`).join("\n")}` : "",
271
+ item.checks.length ? `Checks: ${item.checks.join("; ")}` : "",
272
+ item.fitness ? `Fitness contract to define first with the contract tool: ${JSON.stringify(item.fitness)}` : "",
273
+ `(backlog item ${item.slug})`,
274
+ ].filter(Boolean).join("\n\n")
275
+ }
276
+
277
+ // --- the backlog tool -------------------------------------------------------------------------------------------
278
+
279
+ // The micromanager's backlog tool: list, show, add or set an item. Returns its answer.
280
+ // add takes {"title", "kind", "goal", "acceptance": [{"text", "verify"}], "checks": [...], "fitness": {...}, "order",
281
+ // "status"}; set takes "status=ready" or "order=10".
282
+ export function backlogTool(project: string, action: string, slug: string, value: string, backend: BacklogBackend = localBackend, now = new Date()): string {
283
+ const a = action.trim().toLowerCase()
284
+ const items = backend.list(project)
285
+ if (a === "" || a === "list") {
286
+ const open = items.filter((i) => i.status !== "done" && i.status !== "dropped")
287
+ const closed = items.length - open.length
288
+ if (!items.length) return `The backlog of this project is empty (${relativeDir(project)}/).`
289
+ return [
290
+ `Backlog (${relativeDir(project)}/), in the order it runs:`,
291
+ ...open.map((i) => `- ${i.slug} [${i.status}, ${i.kind}, order ${i.order}] ${i.title}${i.job ? ` (job ${i.job})` : ""}${i.origin !== "user" ? ` · from ${i.from ?? i.origin}` : ""}`),
292
+ closed ? `${closed} done or dropped.` : "",
293
+ "Start one with plan_job and the goal backlog:<slug>, or write its tasks as todos.",
294
+ ].filter(Boolean).join("\n")
295
+ }
296
+ if (a === "show") {
297
+ const item = backend.get(project, slug.trim())
298
+ return item ? renderItem(item) : `There is no backlog item ${slug.trim()}.`
299
+ }
300
+ if (a === "add") {
301
+ let o: Record<string, unknown>
302
+ try {
303
+ o = JSON.parse(value) as Record<string, unknown>
304
+ } catch (err) {
305
+ return `Not added: value is no JSON object (${err instanceof Error ? err.message : String(err)}).`
306
+ }
307
+ const title = typeof o.title === "string" ? o.title.trim() : ""
308
+ if (!title) return "Not added: an item needs a title."
309
+ const kind = KINDS.has(o.kind as ItemKind) ? (o.kind as ItemKind) : "build"
310
+ const checks = (Array.isArray(o.checks) ? o.checks : []).map(String).map((c) => c.trim()).filter(Boolean)
311
+ const bad = checks.map(checkProblem).find(Boolean)
312
+ if (bad) return `Not added: ${bad}`
313
+ const item: BacklogItem = {
314
+ slug: slugOf(title, new Set(items.map((i) => i.slug))),
315
+ title: title.slice(0, 120),
316
+ status: o.status === "ready" ? "ready" : "draft",
317
+ order: typeof o.order === "number" ? o.order : 100,
318
+ kind,
319
+ origin: "user",
320
+ acceptance: (Array.isArray(o.acceptance) ? o.acceptance : []).flatMap((x) => {
321
+ const p = (typeof x === "string" ? { text: x } : x) as { text?: unknown; verify?: unknown }
322
+ return typeof p?.text === "string" && p.text.trim() ? [{ text: p.text.trim(), ...(typeof p.verify === "string" && p.verify.trim() ? { verify: p.verify.trim() } : {}) }] : []
323
+ }),
324
+ checks,
325
+ ...(o.fitness && typeof o.fitness === "object" && !Array.isArray(o.fitness) ? { fitness: o.fitness as Record<string, unknown> } : {}),
326
+ created: today(now),
327
+ body: `## Goal\n${typeof o.goal === "string" && o.goal.trim() ? o.goal.trim() : title}`,
328
+ }
329
+ if (kind === "optimize" && !item.fitness) item.body += "\n\nNeeds a fitness contract before it can run: what is measured, which way is better, what must not get worse."
330
+ return `Added ${item.slug} (${item.status}) to the backlog: ${backend.save(project, item)}.`
331
+ }
332
+ if (a === "set") {
333
+ const item = backend.get(project, slug.trim())
334
+ if (!item) return `There is no backlog item ${slug.trim()}.`
335
+ const m = value.trim().match(/^(status|order)\s*=\s*(\S+)$/i)
336
+ if (!m) return 'Not changed: value is "status=<draft|ready|running|done|dropped>" or "order=<number>".'
337
+ if (m[1]!.toLowerCase() === "status") {
338
+ if (!STATUSES.has(m[2] as ItemStatus)) return `Not changed: status is one of ${[...STATUSES].join(", ")}.`
339
+ item.status = m[2] as ItemStatus
340
+ } else {
341
+ const n = Number(m[2])
342
+ if (!Number.isFinite(n)) return "Not changed: order is a number."
343
+ item.order = n
344
+ }
345
+ backend.save(project, item)
346
+ return `${item.slug} is ${item.status}, order ${item.order}.`
347
+ }
348
+ return 'action is "list", "show", "add" or "set".'
349
+ }
350
+
351
+ function relativeDir(project: string): string {
352
+ return join(stateDir(project), "backlog")
353
+ }
354
+
355
+ // --- GitHub issues (P7, opt-in per repository) ------------------------------------------------------------------
356
+
357
+ // Issues labelled micromanager in a repository the user opted in ("githubBacklog" in micromanager.jsonc). The body
358
+ // holds the same front matter and Markdown as a file; an issue without one is read as a draft with its text as goal.
359
+ // Reading is free. Writing happens only in publishIssue, after the user's yes in a form.
360
+ export const ISSUE_LABEL = "micromanager"
361
+
362
+ // The repository a project's GitHub remote names, as gh sees it; undefined without gh, a remote or a login.
363
+ export async function githubRepo(project: string, run: Exec = exec): Promise<string | undefined> {
364
+ const r = await run("gh", ["repo", "view", "--json", "nameWithOwner", "-q", ".nameWithOwner"], { cwd: project, timeoutMs: 15_000 })
365
+ const name = r.stdout.trim().toLowerCase()
366
+ return r.code === 0 && /^[\w.-]+\/[\w.-]+$/.test(name) ? name : undefined
367
+ }
368
+
369
+ function issueItem(issue: { number: number; title: string; body?: string; state?: string; url?: string }): BacklogItem {
370
+ const slug = `gh-${issue.number}`
371
+ const parsed = issue.body ? parseItem(issue.body, slug).item : undefined
372
+ const closed = String(issue.state ?? "").toUpperCase() === "CLOSED"
373
+ if (parsed) return { ...parsed, title: issue.title || parsed.title, ...(closed ? { status: "done" as const } : {}), ...(issue.url ? { issue: issue.url } : {}) }
374
+ return { slug, title: issue.title, status: closed ? "done" : "draft", order: 100, kind: "build", origin: "user", acceptance: [], checks: [], created: "", body: `## Goal\n${issue.body?.trim() || issue.title}`, ...(issue.url ? { issue: issue.url } : {}) }
375
+ }
376
+
377
+ export async function githubIssues(project: string, repo: string, run: Exec = exec): Promise<{ items: BacklogItem[]; problem?: string }> {
378
+ const r = await run("gh", ["issue", "list", "--repo", repo, "--label", ISSUE_LABEL, "--state", "all", "--limit", "200", "--json", "number,title,body,state,url"], { cwd: project, timeoutMs: 30_000 })
379
+ if (r.code !== 0) return { items: [], problem: `gh could not list the issues of ${repo}: ${r.stderr.trim().slice(0, 200) || `exit ${r.code}`}` }
380
+ try {
381
+ return { items: (JSON.parse(r.stdout) as Parameters<typeof issueItem>[0][]).map(issueItem).sort(byTurn) }
382
+ } catch {
383
+ return { items: [], problem: `gh answered no issue list for ${repo}` }
384
+ }
385
+ }
386
+
387
+ export async function githubIssue(project: string, repo: string, number: number, run: Exec = exec): Promise<BacklogItem | undefined> {
388
+ const r = await run("gh", ["issue", "view", String(number), "--repo", repo, "--json", "number,title,body,state,url"], { cwd: project, timeoutMs: 30_000 })
389
+ if (r.code !== 0) return undefined
390
+ try {
391
+ return issueItem(JSON.parse(r.stdout) as Parameters<typeof issueItem>[0])
392
+ } catch {
393
+ return undefined
394
+ }
395
+ }
396
+
397
+ // A local item published as an issue, after the user's yes: the label made if it is missing, the issue created with
398
+ // the item's text as its body, and the item keeps the issue's address.
399
+ export async function publishIssue(project: string, item: BacklogItem, repo: string, run: Exec = exec, backend: BacklogBackend = localBackend): Promise<{ url?: string; problem?: string }> {
400
+ await run("gh", ["label", "create", ISSUE_LABEL, "--repo", repo, "--color", "5319e7", "--description", "a job for the micromanager", "--force"], { cwd: project, timeoutMs: 30_000 })
401
+ const scratch = mkdtempSync(join(tmpdir(), "mm-issue-"))
402
+ try {
403
+ const body = join(scratch, "body.md")
404
+ // What goes to GitHub is redacted; the local item keeps its real title and body.
405
+ const safe: BacklogItem = { ...item, title: scrub(item.title) }
406
+ writeFileSync(body, scrub(renderItem({ ...safe, issue: undefined })))
407
+ const r = await run("gh", ["issue", "create", "--repo", repo, "--title", safe.title, "--label", ISSUE_LABEL, "--body-file", body], { cwd: project, timeoutMs: 60_000 })
408
+ const url = r.stdout.trim().split("\n").find((l) => /^https:\/\/github\.com\//.test(l))
409
+ if (r.code !== 0 || !url) return { problem: `gh issue create failed: ${r.stderr.trim().slice(0, 200) || `exit ${r.code}`}` }
410
+ backend.save(project, { ...item, issue: url })
411
+ return { url }
412
+ } finally {
413
+ rmSync(scratch, { recursive: true, force: true })
414
+ }
415
+ }
416
+
417
+ const PUBLISH = { yes: "Publish it", no: "Keep it local" } as const
418
+
419
+ // The question before anything goes to GitHub: an issue is published content.
420
+ export function publishForm(item: BacklogItem, repo: string): Question[] {
421
+ return [{
422
+ header: `Publish ${item.slug}`.slice(0, 30),
423
+ question: `Publish backlog item ${item.slug} ("${item.title.slice(0, 100)}") as a GitHub issue in ${repo}, labelled ${ISSUE_LABEL}? Its whole text becomes the issue's body, visible to whoever can see the repository.`,
424
+ options: [
425
+ { label: PUBLISH.yes, description: `gh issue create in ${repo}` },
426
+ { label: PUBLISH.no, description: "Nothing leaves this machine" },
427
+ ],
428
+ }]
429
+ }
430
+
431
+ export function readPublish(header: string, answers: readonly string[]): { slug: string; yes?: boolean } | undefined {
432
+ const m = header.match(/^Publish (\S+)$/)
433
+ if (!m) return undefined
434
+ const a = answers.map((x) => x.trim().toLowerCase())
435
+ return { slug: m[1]!, ...(a.includes(PUBLISH.yes.toLowerCase()) ? { yes: true } : a.includes(PUBLISH.no.toLowerCase()) ? { yes: false } : {}) }
436
+ }
package/src/bench.ts ADDED
@@ -0,0 +1,163 @@
1
+ // The guard bench (design.md §21): every case of bench/guard_cases.json through the G0 backend, then recall and
2
+ // false-positive rate per guard at a range of floors. A floor for a backend is set from this, never guessed.
3
+
4
+ import { readFileSync } from "node:fs"
5
+
6
+ import type { Decider } from "./backends.ts"
7
+ import { GUARDS } from "./catalog.ts"
8
+ import { n7Questions, n7State, triage, type N7Context, type Verdict } from "./followups.ts"
9
+ import type { FollowUp } from "./state.ts"
10
+
11
+ export interface Case {
12
+ readonly text: string
13
+ readonly yes: readonly string[]
14
+ }
15
+
16
+ export interface GuardScore {
17
+ readonly guard: string
18
+ readonly floor: number
19
+ readonly recall: number // share of positives at or above the floor
20
+ readonly fpr: number // share of negatives at or above the floor
21
+ readonly positives: number
22
+ }
23
+
24
+ export function loadCases(path: string): Case[] {
25
+ return (JSON.parse(readFileSync(path, "utf8")) as { cases: Case[] }).cases
26
+ }
27
+
28
+ export async function scoreCases(decider: Decider, cases: readonly Case[]): Promise<{ text: string; yes: readonly string[]; p: Record<string, number> }[]> {
29
+ const out = []
30
+ for (const c of cases) {
31
+ const asked = await decider.ask("G0", { text: c.text }, GUARDS, { localOnly: true })
32
+ const p: Record<string, number> = {}
33
+ for (const g of Object.keys(GUARDS)) {
34
+ const a = asked.decision.answers[g]
35
+ if (a?.type === "noul") p[g] = a.noul
36
+ }
37
+ out.push({ text: c.text, yes: c.yes, p })
38
+ }
39
+ return out
40
+ }
41
+
42
+ export function sweep(rows: readonly { yes: readonly string[]; p: Record<string, number> }[], floors = [0.3, 0.5, 0.7, 0.9]): GuardScore[] {
43
+ return Object.keys(GUARDS).flatMap((guard) => {
44
+ const scored = rows.filter((r) => r.p[guard] !== undefined)
45
+ if (scored.length === 0) return [] // no answers for this guard: nothing to report, not 0 %
46
+ const pos = scored.filter((r) => r.yes.includes(guard))
47
+ const neg = scored.filter((r) => !r.yes.includes(guard))
48
+ return floors.map((floor) => ({
49
+ guard,
50
+ floor,
51
+ positives: pos.length,
52
+ recall: pos.length ? pos.filter((r) => r.p[guard]! >= floor).length / pos.length : 0,
53
+ fpr: neg.length ? neg.filter((r) => r.p[guard]! >= floor).length / neg.length : 0,
54
+ }))
55
+ })
56
+ }
57
+
58
+ export function formatSweep(scores: readonly GuardScore[]): string {
59
+ if (scores.length === 0) return "no answers from the G0 backend: is the decision server running and fast enough?"
60
+ const pct = (x: number) => `${(x * 100).toFixed(0)}%`.padStart(5)
61
+ return ["guard floor recall fpr", ...scores.map((s) => `${s.guard.padEnd(15)} ${s.floor.toFixed(1).padStart(5)} ${pct(s.recall)} ${pct(s.fpr)}`)].join("\n")
62
+ }
63
+
64
+ // Repeat-run check (Phase D: one goal scored 0.59, then 2e-8): the same cases scored twice, and per guard the largest
65
+ // change between the runs and how many cases crossed the floor.
66
+ export function drift(a: readonly { p: Record<string, number> }[], b: readonly { p: Record<string, number> }[], floor = 0.5): { guard: string; maxDelta: number; flips: number }[] {
67
+ return Object.keys(GUARDS).flatMap((guard) => {
68
+ const pairs = a.map((r, i) => [r.p[guard], b[i]?.p[guard]] as const).filter((x): x is readonly [number, number] => x[0] !== undefined && x[1] !== undefined)
69
+ if (pairs.length === 0) return []
70
+ return [{ guard, maxDelta: Math.max(...pairs.map(([x, y]) => Math.abs(x - y))), flips: pairs.filter(([x, y]) => (x >= floor) !== (y >= floor)).length }]
71
+ })
72
+ }
73
+
74
+ export function formatDrift(rows: readonly { guard: string; maxDelta: number; flips: number }[]): string {
75
+ return ["guard max change floor flips", ...rows.map((r) => `${r.guard.padEnd(15)} ${r.maxDelta.toFixed(3).padStart(10)} ${String(r.flips).padStart(12)}`)].join("\n")
76
+ }
77
+
78
+ // --- the N7 bench: a worker's follow-ups (bench/followup_cases.json) -----------------------------------------
79
+
80
+ export type Expect = "task" | "planned" | "user" | "later"
81
+
82
+ interface N7Job {
83
+ readonly goal: string
84
+ readonly acceptance: readonly string[]
85
+ readonly tasks: readonly { id: string; title: string; files: readonly string[]; done: boolean }[]
86
+ }
87
+
88
+ export interface N7Case {
89
+ readonly job: string
90
+ readonly finder: string
91
+ readonly followUp: FollowUp
92
+ readonly expect: Expect
93
+ readonly priority?: "high" | "normal" | "low"
94
+ }
95
+
96
+ export function loadN7(path: string): { jobs: Record<string, N7Job>; cases: N7Case[] } {
97
+ return JSON.parse(readFileSync(path, "utf8")) as { jobs: Record<string, N7Job>; cases: N7Case[] }
98
+ }
99
+
100
+ export function n7Context(job: N7Job, finder: string): N7Context {
101
+ const finderTask = job.tasks.find((t) => t.id === finder)!
102
+ const others = job.tasks.filter((t) => t.id !== finder)
103
+ return {
104
+ goal: job.goal,
105
+ acceptance: job.acceptance,
106
+ task: `${finderTask.id} ${finderTask.title}`,
107
+ otherTasks: others.map((t) => `${t.id} ${t.title}${t.done ? " (done)" : ""} (files: ${t.files.join(", ") || "none"})`),
108
+ openFiles: new Set(others.filter((t) => !t.done).flatMap((t) => t.files)),
109
+ doneFiles: new Set([...others.filter((t) => t.done), finderTask].flatMap((t) => t.files)),
110
+ }
111
+ }
112
+
113
+ // What a verdict means for the expected answer: the user's call and out of scope both land on the "later" list.
114
+ export function outcome(v: Verdict): Expect {
115
+ return v.kind === "task" ? "task" : v.kind === "planned" ? "planned" : v.reason === "user_should_decide" ? "user" : "later"
116
+ }
117
+
118
+ export interface N7Row {
119
+ readonly expect: Expect
120
+ readonly model?: Expect
121
+ readonly rules: Expect
122
+ readonly priority?: string
123
+ readonly modelPriority?: { choice: string; confidence: number }
124
+ }
125
+
126
+ export async function scoreN7(decider: Decider, data: { jobs: Record<string, N7Job>; cases: readonly N7Case[] }): Promise<N7Row[]> {
127
+ const rows: N7Row[] = []
128
+ for (const c of data.cases) {
129
+ const ctx = n7Context(data.jobs[c.job]!, c.finder)
130
+ const items = [c.followUp]
131
+ const asked = await decider.ask("N7", n7State(ctx, items), n7Questions(items))
132
+ const answered = asked.backend !== "rules" && Object.keys(asked.decision.answers).length > 0
133
+ const p = asked.decision.answers["priority.0"]
134
+ rows.push({
135
+ expect: c.expect,
136
+ model: answered ? outcome(triage(asked.decision.answers, items, ctx)[0]!) : undefined,
137
+ rules: outcome(triage({}, items, ctx)[0]!),
138
+ priority: c.priority,
139
+ modelPriority: p?.type === "choice" ? { choice: p.choice, confidence: p.confidence } : undefined,
140
+ })
141
+ }
142
+ return rows
143
+ }
144
+
145
+ export function formatN7(rows: readonly N7Row[]): string {
146
+ const classes: Expect[] = ["task", "planned", "user", "later"]
147
+ const coarse = (e: Expect | undefined) => (e === "user" ? "later" : e)
148
+ const line = (name: string, pick: (r: N7Row) => Expect | undefined) => {
149
+ const per = classes.map((k) => {
150
+ const of = rows.filter((r) => r.expect === k)
151
+ return `${k} ${of.filter((r) => pick(r) === k).length}/${of.length}`
152
+ })
153
+ const exact = rows.filter((r) => pick(r) === r.expect).length
154
+ const rough = rows.filter((r) => coarse(pick(r)) === coarse(r.expect)).length
155
+ return `${name.padEnd(6)} exact ${exact}/${rows.length} · task/planned/later ${rough}/${rows.length} · ${per.join(" · ")}`
156
+ }
157
+ const prio = rows.filter((r) => r.priority && r.modelPriority)
158
+ const prioLine = prio.length
159
+ ? `priority: ${prio.filter((r) => r.modelPriority!.choice === r.priority).length}/${prio.length} right, confidence ${prio.map((r) => r.modelPriority!.confidence.toFixed(2)).join(" ")}`
160
+ : "priority: no answers"
161
+ const model = rows.some((r) => r.model) ? line("model", (r) => r.model) : "model no answers (no Jev key, or the backend failed)"
162
+ return [model, line("rules", (r) => r.rules), prioLine].join("\n")
163
+ }
package/src/board.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "@omacode/state/board"