openmill 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1958 @@
1
+ #!/usr/bin/env node
2
+ import { parse } from "yaml";
3
+ import { Command, InvalidArgumentError } from "commander";
4
+ import { chmod, cp, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
5
+ import { createHash } from "node:crypto";
6
+ import { homedir } from "node:os";
7
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
8
+ import { closeSync, createWriteStream, existsSync, mkdirSync, openSync, readFileSync, realpathSync, rmSync, writeSync } from "node:fs";
9
+ import { createAdaptorServer } from "@hono/node-server";
10
+ import { DatabaseSync } from "node:sqlite";
11
+ import { fileURLToPath } from "node:url";
12
+ import { drizzle } from "drizzle-orm/node-sqlite";
13
+ import { migrate } from "drizzle-orm/node-sqlite/migrator";
14
+ import { and, asc, desc, eq, inArray, isNull, sql } from "drizzle-orm";
15
+ import { index, integer, primaryKey, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
16
+ import { Hono } from "hono";
17
+ import { validator } from "hono/validator";
18
+ import { z } from "zod";
19
+ import { execFile, spawn } from "node:child_process";
20
+ import { query } from "@anthropic-ai/claude-agent-sdk";
21
+ import pc from "picocolors";
22
+ import { request } from "node:http";
23
+ import { hc } from "hono/client";
24
+ import ora from "ora";
25
+ import * as p from "@clack/prompts";
26
+ import { stripVTControlCharacters } from "node:util";
27
+ // ../../packages/core/src/config.ts
28
+ const HARNESSES = ["claude"];
29
+ const EFFORTS = [
30
+ "low",
31
+ "medium",
32
+ "high",
33
+ "xhigh",
34
+ "max"
35
+ ];
36
+ const CONFIG_KEYS = [
37
+ "concurrency",
38
+ "harness",
39
+ "model",
40
+ "effort"
41
+ ];
42
+ const DEFAULT_CONFIG = {
43
+ concurrency: 2,
44
+ harness: "claude",
45
+ effort: "medium"
46
+ };
47
+ function isConfigKey(key) {
48
+ return CONFIG_KEYS.includes(key);
49
+ }
50
+ function parseOneOf(name, values) {
51
+ return (value) => values.includes(value) ? {
52
+ ok: true,
53
+ value
54
+ } : {
55
+ ok: false,
56
+ error: `${name} must be one of ${values.join(", ")}`
57
+ };
58
+ }
59
+ const parseHarness = parseOneOf("harness", HARNESSES);
60
+ const parseEffort = parseOneOf("effort", EFFORTS);
61
+ function parseModel(value) {
62
+ return value.trim() === "" ? {
63
+ ok: false,
64
+ error: "model must not be empty"
65
+ } : {
66
+ ok: true,
67
+ value: value.trim()
68
+ };
69
+ }
70
+ function parseConfigValue(key, value) {
71
+ switch (key) {
72
+ case "concurrency": {
73
+ const number = Number(value);
74
+ return Number.isInteger(number) && number > 0 ? {
75
+ ok: true,
76
+ value: number
77
+ } : {
78
+ ok: false,
79
+ error: "concurrency must be a positive integer"
80
+ };
81
+ }
82
+ case "harness": return parseHarness(value);
83
+ case "model": return parseModel(value);
84
+ case "effort": return parseEffort(value);
85
+ }
86
+ }
87
+ function resolveConfig(stored) {
88
+ const config = { ...DEFAULT_CONFIG };
89
+ if (typeof stored !== "object" || stored === null) return config;
90
+ for (const [key, raw] of Object.entries(stored)) {
91
+ if (!isConfigKey(key) || raw === void 0 || raw === null) continue;
92
+ const parsed = parseConfigValue(key, String(raw));
93
+ if (parsed.ok) Object.assign(config, { [key]: parsed.value });
94
+ }
95
+ return config;
96
+ }
97
+ // ../../packages/core/src/frontmatter.ts
98
+ const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
99
+ function splitFrontmatter(content) {
100
+ const match = FRONTMATTER.exec(content);
101
+ if (!match) return {
102
+ data: {},
103
+ body: content
104
+ };
105
+ const data = parse(match[1] ?? "");
106
+ if (data === null || data === void 0) return {
107
+ data: {},
108
+ body: content.slice(match[0].length)
109
+ };
110
+ if (typeof data !== "object" || Array.isArray(data)) throw new Error("frontmatter must be a YAML mapping");
111
+ return {
112
+ data,
113
+ body: content.slice(match[0].length)
114
+ };
115
+ }
116
+ // ../../packages/core/src/design-doc.ts
117
+ const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
118
+ function parseDesignDoc(content) {
119
+ let data;
120
+ try {
121
+ data = splitFrontmatter(content).data;
122
+ } catch (error) {
123
+ return {
124
+ kind: "invalid",
125
+ error: `invalid frontmatter: ${error.message}`
126
+ };
127
+ }
128
+ if (data.id === void 0 || data.id === null) return { kind: "no-id" };
129
+ if (typeof data.id !== "string" || !ID_PATTERN.test(data.id) || data.id.endsWith(".lock")) return {
130
+ kind: "invalid",
131
+ error: `id must match ${ID_PATTERN} (letters, digits, ".", "_", "-"), got ${JSON.stringify(data.id)}`
132
+ };
133
+ const dependsOn = parseDependsOn(data.depends_on);
134
+ if (typeof dependsOn === "string") return {
135
+ kind: "invalid",
136
+ error: dependsOn
137
+ };
138
+ if (data.project !== void 0 && (typeof data.project !== "string" || data.project === "")) return {
139
+ kind: "invalid",
140
+ error: "project must be a folder path"
141
+ };
142
+ return {
143
+ kind: "doc",
144
+ meta: {
145
+ id: data.id,
146
+ dependsOn,
147
+ project: data.project
148
+ }
149
+ };
150
+ }
151
+ function parseDependsOn(value) {
152
+ if (value === void 0 || value === null) return [];
153
+ const paths = Array.isArray(value) ? value : [value];
154
+ if (paths.some((path) => typeof path !== "string" || path === "")) return "depends_on must be a path or a list of paths";
155
+ return paths;
156
+ }
157
+ // ../../packages/core/src/graph.ts
158
+ function ancestors(graph, id) {
159
+ const seen = /* @__PURE__ */ new Set();
160
+ const stack = [...graph.get(id) ?? []];
161
+ while (stack.length > 0) {
162
+ const next = stack.pop();
163
+ if (!seen.has(next)) {
164
+ seen.add(next);
165
+ stack.push(...graph.get(next) ?? []);
166
+ }
167
+ }
168
+ return seen;
169
+ }
170
+ function findCycle(graph) {
171
+ const done = /* @__PURE__ */ new Set();
172
+ const path = [];
173
+ const onPath = /* @__PURE__ */ new Set();
174
+ function visit(id) {
175
+ if (onPath.has(id)) return [...path.slice(path.indexOf(id)), id];
176
+ if (done.has(id)) return;
177
+ path.push(id);
178
+ onPath.add(id);
179
+ for (const dep of graph.get(id) ?? []) {
180
+ const cycle = visit(dep);
181
+ if (cycle) return cycle;
182
+ }
183
+ path.pop();
184
+ onPath.delete(id);
185
+ done.add(id);
186
+ }
187
+ for (const id of graph.keys()) {
188
+ const cycle = visit(id);
189
+ if (cycle) return cycle;
190
+ }
191
+ }
192
+ function stackParent(graph, id) {
193
+ const deps = graph.get(id) ?? [];
194
+ if (deps.length === 0) return null;
195
+ return deps.find((candidate) => {
196
+ const below = ancestors(graph, candidate);
197
+ return deps.every((dep) => dep === candidate || below.has(dep));
198
+ });
199
+ }
200
+ function checkGraph(graph, ids) {
201
+ for (const [id, deps] of graph) {
202
+ const missing = deps.find((dep) => !graph.has(dep));
203
+ if (missing !== void 0) return {
204
+ ok: false,
205
+ error: `${id} depends on unknown job ${missing}`
206
+ };
207
+ }
208
+ const cycle = findCycle(graph);
209
+ if (cycle) return {
210
+ ok: false,
211
+ error: `dependency cycle: ${cycle.join(" -> ")}`
212
+ };
213
+ for (const id of ids) if (stackParent(graph, id) === void 0) return {
214
+ ok: false,
215
+ error: `${id} depends on ${(graph.get(id) ?? []).join(", ")}, which don't form one ancestor chain, so there is no single branch to stack on`
216
+ };
217
+ return { ok: true };
218
+ }
219
+ // ../../packages/core/src/states.ts
220
+ const TRANSITIONS = {
221
+ queued: [
222
+ "running",
223
+ "blocked",
224
+ "queued",
225
+ "cancelled"
226
+ ],
227
+ running: [
228
+ "done",
229
+ "needs_input",
230
+ "failed",
231
+ "paused",
232
+ "queued"
233
+ ],
234
+ needs_input: [
235
+ "queued",
236
+ "done",
237
+ "cancelled"
238
+ ],
239
+ paused: [
240
+ "queued",
241
+ "done",
242
+ "cancelled"
243
+ ],
244
+ failed: [
245
+ "queued",
246
+ "done",
247
+ "cancelled"
248
+ ],
249
+ done: ["queued", "cancelled"],
250
+ blocked: [
251
+ "queued",
252
+ "blocked",
253
+ "cancelled"
254
+ ],
255
+ cancelled: []
256
+ };
257
+ function assertTransition(from, to) {
258
+ if (!TRANSITIONS[from].includes(to)) throw new Error(`cannot move a job from ${from} to ${to}`);
259
+ }
260
+ const BLOCKING_STATES = [
261
+ "failed",
262
+ "needs_input",
263
+ "cancelled"
264
+ ];
265
+ const REQUEUEABLE_STATES = [
266
+ "paused",
267
+ "needs_input",
268
+ "failed"
269
+ ];
270
+ const HAND_OFF_STATES = REQUEUEABLE_STATES;
271
+ const UPDATABLE_STATES = ["queued", "blocked"];
272
+ // ../../packages/core/src/scheduling.ts
273
+ function waitingState(graph, jobs, id) {
274
+ for (const dep of graph.get(id) ?? []) {
275
+ const state = jobs.get(dep)?.state;
276
+ if (state !== void 0 && BLOCKING_STATES.includes(state)) return {
277
+ state: "blocked",
278
+ blockedReason: `dependency ${dep} is ${state}`
279
+ };
280
+ if (state === "blocked") return {
281
+ state: "blocked",
282
+ blockedReason: `dependency ${dep} is blocked`
283
+ };
284
+ }
285
+ return {
286
+ state: "queued",
287
+ blockedReason: null
288
+ };
289
+ }
290
+ function waitingUpdates(graph, jobs) {
291
+ const current = new Map(jobs);
292
+ const updates = /* @__PURE__ */ new Map();
293
+ let changed = true;
294
+ while (changed) {
295
+ changed = false;
296
+ for (const job of current.values()) {
297
+ if (job.state !== "queued" && job.state !== "blocked") continue;
298
+ const next = waitingState(graph, current, job.id);
299
+ if (next.state !== job.state || next.blockedReason !== job.blockedReason) {
300
+ current.set(job.id, {
301
+ ...job,
302
+ ...next
303
+ });
304
+ updates.set(job.id, next);
305
+ changed = true;
306
+ }
307
+ }
308
+ }
309
+ return updates;
310
+ }
311
+ function dependenciesSatisfied(graph, jobs, id) {
312
+ return (graph.get(id) ?? []).every((dep) => jobs.get(dep)?.state === "done");
313
+ }
314
+ function jobsToStart(graph, jobs, slots) {
315
+ const start = [];
316
+ for (const job of jobs.values()) {
317
+ if (start.length >= slots) break;
318
+ if (job.state === "queued" && dependenciesSatisfied(graph, jobs, job.id)) start.push(job.id);
319
+ }
320
+ return start;
321
+ }
322
+ // package.json
323
+ var name = "openmill";
324
+ var version = "0.1.0";
325
+ var description = "A local software factory that turns design docs into pull requests.";
326
+ // ../server/src/config-store.ts
327
+ async function readConfig(path) {
328
+ return resolveConfig(await readStored(path));
329
+ }
330
+ async function writeConfigValue(path, key, value) {
331
+ const stored = await readStored(path);
332
+ stored[key] = value;
333
+ await writeFile(path, `${JSON.stringify(stored, null, 2)}\n`);
334
+ return resolveConfig(stored);
335
+ }
336
+ async function readStored(path) {
337
+ try {
338
+ return JSON.parse(await readFile(path, "utf8"));
339
+ } catch (error) {
340
+ if (error.code === "ENOENT") return {};
341
+ throw error;
342
+ }
343
+ }
344
+ // ../server/src/paths.ts
345
+ function resolvePaths() {
346
+ const home = process.env.OPENMILL_HOME ?? join(homedir(), ".openmill");
347
+ return {
348
+ home,
349
+ db: join(home, "openmill.db"),
350
+ config: join(home, "config.json"),
351
+ socket: socketPath(home),
352
+ pid: join(home, "server.pid"),
353
+ log: join(home, "server.log"),
354
+ jobsDir: join(home, "jobs"),
355
+ worktreesDir: join(home, "worktrees")
356
+ };
357
+ }
358
+ function socketPath(home) {
359
+ if (process.platform === "win32") return `\\\\.\\pipe\\openmill-${shortHash(home)}`;
360
+ return join(home, "server.sock");
361
+ }
362
+ function repoDirName(repoPath) {
363
+ return `${basename(repoPath)}-${shortHash(repoPath)}`;
364
+ }
365
+ function shortHash(value) {
366
+ return createHash("sha256").update(value).digest("hex").slice(0, 8);
367
+ }
368
+ function jobDir(paths, repoPath, id) {
369
+ return join(paths.jobsDir, repoDirName(repoPath), id);
370
+ }
371
+ function worktreePath(paths, repoPath, id) {
372
+ return join(paths.worktreesDir, repoDirName(repoPath), id);
373
+ }
374
+ function branchName(id) {
375
+ return `openmill/${id}`;
376
+ }
377
+ // ../../packages/db/src/client.ts
378
+ const migrationsFolder = fileURLToPath(new URL("../drizzle", import.meta.url));
379
+ function createDb(path) {
380
+ const client = new DatabaseSync(path);
381
+ client.exec("PRAGMA journal_mode = WAL;");
382
+ client.exec("PRAGMA foreign_keys = ON;");
383
+ return drizzle({ client });
384
+ }
385
+ function openDb(path) {
386
+ const db = createDb(path);
387
+ migrate(db, { migrationsFolder });
388
+ return db;
389
+ }
390
+ // ../../packages/db/src/schema.ts
391
+ const now = sql`(unixepoch('subsec') * 1000)`;
392
+ const jobs = sqliteTable("jobs", {
393
+ key: integer().primaryKey({ autoIncrement: true }),
394
+ id: text().notNull(),
395
+ repoPath: text().notNull(),
396
+ docPath: text().notNull(),
397
+ docSnapshot: text().notNull(),
398
+ projectSnapshot: text(),
399
+ baseBranch: text(),
400
+ prBaseBranch: text(),
401
+ requestedBase: text(),
402
+ branchName: text().notNull(),
403
+ worktreePath: text().notNull(),
404
+ harness: text(),
405
+ model: text(),
406
+ effort: text(),
407
+ state: text().notNull().default("queued"),
408
+ blockedReason: text(),
409
+ prUrl: text(),
410
+ sessionId: text(),
411
+ createdAt: integer({ mode: "timestamp_ms" }).notNull().default(now),
412
+ updatedAt: integer({ mode: "timestamp_ms" }).notNull().default(now)
413
+ }, (table) => [uniqueIndex("jobs_repo_id").on(table.repoPath, table.id)]);
414
+ const jobDependencies = sqliteTable("job_dependencies", {
415
+ jobKey: integer().notNull().references(() => jobs.key, { onDelete: "cascade" }),
416
+ dependsOnKey: integer().notNull().references(() => jobs.key, { onDelete: "cascade" })
417
+ }, (table) => [primaryKey({ columns: [table.jobKey, table.dependsOnKey] }), index("job_dependencies_depends_on").on(table.dependsOnKey)]);
418
+ const runs = sqliteTable("runs", {
419
+ id: integer().primaryKey({ autoIncrement: true }),
420
+ jobKey: integer().notNull().references(() => jobs.key, { onDelete: "cascade" }),
421
+ harness: text().notNull(),
422
+ model: text(),
423
+ effort: text().notNull(),
424
+ sessionId: text(),
425
+ recovery: integer({ mode: "boolean" }).notNull().default(false),
426
+ startedAt: integer({ mode: "timestamp_ms" }).notNull().default(now),
427
+ endedAt: integer({ mode: "timestamp_ms" }),
428
+ result: text({ mode: "json" }).$type()
429
+ }, (table) => [index("runs_job").on(table.jobKey)]);
430
+ // ../../packages/db/src/queries.ts
431
+ function listJobs(db) {
432
+ return db.select().from(jobs).orderBy(asc(jobs.createdAt), asc(jobs.key)).all();
433
+ }
434
+ function getJob(db, key) {
435
+ return db.select().from(jobs).where(eq(jobs.key, key)).get();
436
+ }
437
+ function findJobsById(db, id) {
438
+ return db.select().from(jobs).where(eq(jobs.id, id)).orderBy(asc(jobs.key)).all();
439
+ }
440
+ function findJob(db, repoPath, id) {
441
+ return db.select().from(jobs).where(and(eq(jobs.repoPath, repoPath), eq(jobs.id, id))).get();
442
+ }
443
+ function insertJob(db, job) {
444
+ return db.insert(jobs).values(job).returning().get();
445
+ }
446
+ function updateJob(db, key, patch) {
447
+ db.update(jobs).set({
448
+ ...patch,
449
+ updatedAt: /* @__PURE__ */ new Date()
450
+ }).where(eq(jobs.key, key)).run();
451
+ }
452
+ function listDependencies(db) {
453
+ return db.select().from(jobDependencies).all().map((edge) => [edge.jobKey, edge.dependsOnKey]);
454
+ }
455
+ function setDependencies(db, jobKey, dependsOnKeys) {
456
+ db.delete(jobDependencies).where(eq(jobDependencies.jobKey, jobKey)).run();
457
+ if (dependsOnKeys.length > 0) db.insert(jobDependencies).values(dependsOnKeys.map((dependsOnKey) => ({
458
+ jobKey,
459
+ dependsOnKey
460
+ }))).run();
461
+ }
462
+ function insertRun(db, run) {
463
+ return db.insert(runs).values(run).returning().get();
464
+ }
465
+ function updateRun(db, id, patch) {
466
+ db.update(runs).set(patch).where(eq(runs.id, id)).run();
467
+ }
468
+ function latestRun(db, jobKey) {
469
+ return db.select().from(runs).where(eq(runs.jobKey, jobKey)).orderBy(desc(runs.id)).get();
470
+ }
471
+ function latestRuns(db, jobKeys) {
472
+ const latest = /* @__PURE__ */ new Map();
473
+ if (jobKeys.length === 0) return latest;
474
+ for (const run of db.select().from(runs).where(inArray(runs.jobKey, jobKeys)).orderBy(asc(runs.id)).all()) latest.set(run.jobKey, run);
475
+ return latest;
476
+ }
477
+ function unfinishedRuns(db) {
478
+ return db.select().from(runs).where(isNull(runs.endedAt)).orderBy(asc(runs.id)).all();
479
+ }
480
+ // ../server/src/api.ts
481
+ const addRequestSchema = z.object({
482
+ repo: z.string().min(1),
483
+ base: z.string().min(1).optional(),
484
+ harness: z.enum(HARNESSES).optional(),
485
+ model: z.string().min(1).optional(),
486
+ effort: z.enum(EFFORTS).optional(),
487
+ force: z.boolean().default(false),
488
+ docs: z.array(z.object({
489
+ id: z.string().min(1),
490
+ path: z.string().min(1),
491
+ content: z.string(),
492
+ project: z.object({
493
+ path: z.string(),
494
+ content: z.string()
495
+ }).optional(),
496
+ dependsOn: z.array(z.string()),
497
+ explicit: z.boolean()
498
+ })).min(1)
499
+ });
500
+ const jobQuerySchema = z.object({ repo: z.string().optional() });
501
+ const configSetSchema = z.object({ value: z.string() });
502
+ // ../server/src/errors.ts
503
+ var ApiError = class extends Error {
504
+ status;
505
+ constructor(status, message) {
506
+ super(message);
507
+ this.status = status;
508
+ }
509
+ };
510
+ // ../server/src/app.ts
511
+ function issues(error) {
512
+ return error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
513
+ }
514
+ function validate(target, schema) {
515
+ return validator(target, (value, c) => {
516
+ const parsed = schema.safeParse(value);
517
+ return parsed.success ? parsed.data : c.json({ error: issues(parsed.error) }, 400);
518
+ });
519
+ }
520
+ function createApp(mill, { version, onShutdown }) {
521
+ return new Hono().onError((error, c) => c.json({ error: error.message }, error instanceof ApiError ? error.status : 500)).get("/status", (c) => c.json({
522
+ ...mill.status(),
523
+ version
524
+ })).post("/shutdown", (c) => {
525
+ setImmediate(onShutdown);
526
+ return c.json({ ok: true });
527
+ }).post("/jobs", validate("json", addRequestSchema), async (c) => c.json({ jobs: await mill.add(c.req.valid("json")) })).get("/jobs", async (c) => c.json({ jobs: await mill.list() })).get("/jobs/:id", validate("query", jobQuerySchema), async (c) => {
528
+ const job = await mill.resolve(c.req.param("id"), c.req.valid("query").repo);
529
+ return c.json(mill.show(job));
530
+ }).post("/jobs/:id/stop", validate("query", jobQuerySchema), async (c) => {
531
+ const job = await mill.resolve(c.req.param("id"), c.req.valid("query").repo);
532
+ return c.json({ state: mill.stop(job) });
533
+ }).post("/jobs/:id/requeue", validate("query", jobQuerySchema), async (c) => {
534
+ const job = await mill.resolve(c.req.param("id"), c.req.valid("query").repo);
535
+ return c.json({ state: await mill.requeue(job) });
536
+ }).get("/config", (c) => c.json({ config: mill.getConfig() })).put("/config/:key", validate("json", configSetSchema), async (c) => {
537
+ const key = c.req.param("key");
538
+ const { value } = c.req.valid("json");
539
+ if (!isConfigKey(key)) throw new ApiError(400, `unknown config key ${key}`);
540
+ const parsed = parseConfigValue(key, value);
541
+ if (!parsed.ok) throw new ApiError(400, parsed.error);
542
+ return c.json({ config: await mill.setConfig(key, parsed.value) });
543
+ });
544
+ }
545
+ // ../server/src/exec.ts
546
+ function exec(command, args, cwd) {
547
+ return new Promise((resolve, reject) => {
548
+ execFile(command, args, {
549
+ cwd,
550
+ maxBuffer: 16777216
551
+ }, (error, stdout, stderr) => {
552
+ if (error) {
553
+ const detail = stderr.trim() || error.message;
554
+ reject(/* @__PURE__ */ new Error(`${command} ${args.join(" ")} failed: ${detail}`));
555
+ } else resolve(stdout);
556
+ });
557
+ });
558
+ }
559
+ // ../server/src/github.ts
560
+ const ghCli = {
561
+ async isOpenDraft(repo, url) {
562
+ const stdout = await exec("gh", [
563
+ "pr",
564
+ "view",
565
+ url,
566
+ "--json",
567
+ "isDraft,state"
568
+ ], repo);
569
+ const pr = JSON.parse(stdout);
570
+ return pr.isDraft && pr.state === "OPEN";
571
+ },
572
+ async findOpenDraft(repo, branch) {
573
+ const stdout = await exec("gh", [
574
+ "pr",
575
+ "list",
576
+ "--head",
577
+ branch,
578
+ "--state",
579
+ "open",
580
+ "--json",
581
+ "url,isDraft"
582
+ ], repo);
583
+ return JSON.parse(stdout).find((pr) => pr.isDraft)?.url;
584
+ }
585
+ };
586
+ // ../../packages/assets/src/index.ts
587
+ const WORKFLOW_SKILL = "autonomous-feature-pr";
588
+ const REVIEW_AGENTS = ["verifier", "code-simplifier"];
589
+ const pluginDir = fileURLToPath(new URL("..", import.meta.url));
590
+ const PLUGIN_NAME = "openmill";
591
+ fileURLToPath(new URL("../skills", import.meta.url));
592
+ const claudeAgentsDir = fileURLToPath(new URL("../agents/claude", import.meta.url));
593
+ fileURLToPath(new URL("../agents/codex", import.meta.url));
594
+ // ../server/src/harness/agents.ts
595
+ function loadClaudeAgents() {
596
+ const agents = {};
597
+ for (const name of REVIEW_AGENTS) {
598
+ const { data, body } = splitFrontmatter(readFileSync(join(claudeAgentsDir, `${name}.md`), "utf8"));
599
+ const agent = {
600
+ description: String(data.description ?? ""),
601
+ prompt: body.trim()
602
+ };
603
+ if (typeof data.tools === "string") agent.tools = data.tools.split(",").map((tool) => tool.trim());
604
+ if (typeof data.model === "string") agent.model = data.model;
605
+ agents[typeof data.name === "string" ? data.name : name] = agent;
606
+ }
607
+ return agents;
608
+ }
609
+ // ../server/src/harness/prompt.ts
610
+ function startPrompt(input) {
611
+ const facts = [
612
+ input.projectPath ? `The project overview is at ${input.projectPath}.` : void 0,
613
+ `You are already in your worktree on branch ${input.branch}, so don't create another branch or worktree.`,
614
+ `Open the draft PR against ${input.prBaseBranch}.`,
615
+ "No human is present. Wherever the skill says to ask or tell the user, stop and report needs_input with the question as reason."
616
+ ].filter(Boolean);
617
+ return `/${PLUGIN_NAME}:${WORKFLOW_SKILL} ${input.docPath}\n\n${facts.map((fact) => `- ${fact}`).join("\n")}\n`;
618
+ }
619
+ const HANDBACK_MESSAGE = "openmill handed this job back to you after a human worked on it. Check the worktree and the conversation, continue the workflow until the draft PR is open, then report the result.";
620
+ const RESTART_MESSAGE = "The openmill server restarted while you were working. Check the worktree, continue the workflow from where you stopped, then report the result.";
621
+ // ../server/src/harness/types.ts
622
+ const RUN_STATUSES = [
623
+ "done",
624
+ "needs_input",
625
+ "failed"
626
+ ];
627
+ const runResultSchema = z.object({
628
+ status: z.enum(RUN_STATUSES),
629
+ pr_url: z.string().optional(),
630
+ reason: z.string().optional()
631
+ }).refine((result) => result.status !== "done" || Boolean(result.pr_url), { message: "a done result needs pr_url" });
632
+ const runResultJsonSchema = {
633
+ type: "object",
634
+ properties: {
635
+ status: {
636
+ type: "string",
637
+ enum: RUN_STATUSES
638
+ },
639
+ pr_url: {
640
+ type: "string",
641
+ description: "The draft PR URL. Required when status is done."
642
+ },
643
+ reason: {
644
+ type: "string",
645
+ description: "Why the run stopped, or the question for a human."
646
+ }
647
+ },
648
+ required: ["status"],
649
+ additionalProperties: false
650
+ };
651
+ function resultEvent(output) {
652
+ const parsed = runResultSchema.safeParse(output);
653
+ if (!parsed.success) return {
654
+ type: "error",
655
+ error: `invalid result: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`
656
+ };
657
+ return {
658
+ type: "result",
659
+ result: parsed.data
660
+ };
661
+ }
662
+ // ../server/src/harness/claude.ts
663
+ function options(input, signal) {
664
+ const abortController = new AbortController();
665
+ signal.addEventListener("abort", () => abortController.abort(), { once: true });
666
+ return {
667
+ cwd: input.worktree,
668
+ plugins: [{
669
+ type: "local",
670
+ path: pluginDir
671
+ }],
672
+ agents: loadClaudeAgents(),
673
+ settingSources: ["user", "project"],
674
+ permissionMode: "bypassPermissions",
675
+ allowDangerouslySkipPermissions: true,
676
+ ...input.model ? { model: input.model } : {},
677
+ effort: input.effort,
678
+ outputFormat: {
679
+ type: "json_schema",
680
+ schema: runResultJsonSchema
681
+ },
682
+ abortController
683
+ };
684
+ }
685
+ const claudeHarness = {
686
+ start(input, signal) {
687
+ return events(query({
688
+ prompt: startPrompt(input),
689
+ options: options(input, signal)
690
+ }));
691
+ },
692
+ resume(sessionId, message, input, signal) {
693
+ return events(query({
694
+ prompt: message,
695
+ options: {
696
+ ...options(input, signal),
697
+ resume: sessionId
698
+ }
699
+ }));
700
+ }
701
+ };
702
+ async function* events(messages) {
703
+ for await (const message of messages) {
704
+ yield {
705
+ type: "message",
706
+ message
707
+ };
708
+ if (message.type === "system" && message.subtype === "init") yield {
709
+ type: "session",
710
+ sessionId: message.session_id
711
+ };
712
+ if (message.type === "result") {
713
+ if (message.subtype === "success" && !message.is_error) yield resultEvent(message.structured_output);
714
+ else {
715
+ const detail = "errors" in message ? message.errors.join("; ") : message.result;
716
+ yield {
717
+ type: "error",
718
+ error: `${message.subtype}: ${detail}`
719
+ };
720
+ }
721
+ }
722
+ }
723
+ }
724
+ // ../server/src/git.ts
725
+ const repoLocks = /* @__PURE__ */ new Map();
726
+ function withRepoLock(repo, task) {
727
+ const next = (repoLocks.get(repo) ?? Promise.resolve()).catch(() => {}).then(task);
728
+ repoLocks.set(repo, next);
729
+ return next;
730
+ }
731
+ async function gitRoot(dir) {
732
+ const stdout = await exec("git", ["rev-parse", "--show-toplevel"], dir);
733
+ return resolve(stdout.trim());
734
+ }
735
+ async function fetchDefaultBranch(repo) {
736
+ await exec("git", ["fetch", "origin"], repo);
737
+ const stdout = await exec("git", [
738
+ "ls-remote",
739
+ "--symref",
740
+ "origin",
741
+ "HEAD"
742
+ ], repo);
743
+ const match = /^ref: refs\/heads\/(\S+)\s+HEAD/m.exec(stdout);
744
+ if (!match?.[1]) throw new Error("could not find the default branch of origin");
745
+ return match[1];
746
+ }
747
+ async function branchExists(repo, branch) {
748
+ try {
749
+ await exec("git", [
750
+ "rev-parse",
751
+ "--verify",
752
+ "--quiet",
753
+ `refs/heads/${branch}`
754
+ ], repo);
755
+ return true;
756
+ } catch {
757
+ return false;
758
+ }
759
+ }
760
+ async function ensureWorktree(repo, path, branch, start) {
761
+ if (existsSync(path)) return;
762
+ await mkdir(dirname(path), { recursive: true });
763
+ await exec("git", ["worktree", "prune"], repo);
764
+ if (await branchExists(repo, branch)) await exec("git", [
765
+ "worktree",
766
+ "add",
767
+ path,
768
+ branch
769
+ ], repo);
770
+ else await exec("git", [
771
+ "worktree",
772
+ "add",
773
+ "--no-track",
774
+ path,
775
+ "-b",
776
+ branch,
777
+ start
778
+ ], repo);
779
+ }
780
+ // ../server/src/mill.ts
781
+ var Mill = class {
782
+ db;
783
+ paths;
784
+ harnesses;
785
+ github;
786
+ log;
787
+ active = /* @__PURE__ */ new Map();
788
+ config;
789
+ closed = false;
790
+ constructor(options) {
791
+ this.db = options.db;
792
+ this.paths = options.paths;
793
+ this.config = options.config;
794
+ this.harnesses = options.harnesses;
795
+ this.github = options.github;
796
+ this.log = options.log ?? (() => {});
797
+ }
798
+ async add(request) {
799
+ let repoPath;
800
+ try {
801
+ repoPath = await gitRoot(request.repo);
802
+ } catch {
803
+ throw new ApiError(400, `${request.repo} is not inside a git repository; pass --repo`);
804
+ }
805
+ const ids = /* @__PURE__ */ new Set();
806
+ for (const doc of request.docs) {
807
+ if (ids.has(doc.id)) throw new ApiError(400, `two docs in the batch share the id ${doc.id}`);
808
+ ids.add(doc.id);
809
+ }
810
+ const existing = new Map(listJobs(this.db).filter((job) => job.repoPath === repoPath).map((job) => [job.id, job]));
811
+ const plan = request.docs.map((doc) => {
812
+ const job = existing.get(doc.id);
813
+ return {
814
+ doc,
815
+ job,
816
+ action: planAction(doc, job, request.force)
817
+ };
818
+ });
819
+ const rejected = plan.filter((entry) => entry.action === "rejected");
820
+ if (rejected.length > 0) throw new ApiError(409, `already started: ${rejected.map((entry) => `${entry.doc.id} (${entry.job?.state})`).join(", ")}. Pass --force to re-queue.`);
821
+ const graph = this.repoGraph(repoPath);
822
+ for (const { doc, action } of plan) if (action !== "unchanged") graph.set(doc.id, doc.dependsOn);
823
+ const check = checkGraph(graph, graph.keys());
824
+ if (!check.ok) throw new ApiError(400, check.error);
825
+ const aborts = [];
826
+ this.db.transaction((tx) => {
827
+ const keys = new Map([...existing].map(([id, job]) => [id, job.key]));
828
+ const touched = [];
829
+ for (const { doc, job, action } of plan) {
830
+ const fields = {
831
+ docPath: doc.path,
832
+ docSnapshot: doc.content,
833
+ projectSnapshot: doc.project?.content ?? null,
834
+ ...request.base ? { requestedBase: request.base } : {},
835
+ ...request.harness ? { harness: request.harness } : {},
836
+ ...request.model ? { model: request.model } : {},
837
+ ...request.effort ? { effort: request.effort } : {}
838
+ };
839
+ if (action === "added") {
840
+ const row = insertJob(tx, {
841
+ id: doc.id,
842
+ repoPath,
843
+ branchName: branchName(doc.id),
844
+ worktreePath: worktreePath(this.paths, repoPath, doc.id),
845
+ ...fields
846
+ });
847
+ keys.set(doc.id, row.key);
848
+ touched.push({
849
+ key: row.key,
850
+ dependsOn: doc.dependsOn
851
+ });
852
+ } else if (job && action === "updated") {
853
+ updateJob(tx, job.key, fields);
854
+ touched.push({
855
+ key: job.key,
856
+ dependsOn: doc.dependsOn
857
+ });
858
+ } else if (job && action === "requeued") {
859
+ assertTransition(job.state, "queued");
860
+ updateJob(tx, job.key, {
861
+ ...fields,
862
+ state: "queued",
863
+ blockedReason: null,
864
+ prUrl: null,
865
+ sessionId: null
866
+ });
867
+ touched.push({
868
+ key: job.key,
869
+ dependsOn: doc.dependsOn
870
+ });
871
+ if (job.state === "running") aborts.push(job.key);
872
+ }
873
+ }
874
+ for (const { key, dependsOn } of touched) setDependencies(tx, key, dependsOn.map((id) => keys.get(id)));
875
+ });
876
+ for (const key of aborts) this.active.get(key)?.controller.abort("requeue");
877
+ this.schedule();
878
+ return plan.map(({ doc, action }) => ({
879
+ id: doc.id,
880
+ action
881
+ }));
882
+ }
883
+ async list() {
884
+ await this.detectHandFinished(listJobs(this.db));
885
+ const jobs = listJobs(this.db);
886
+ const runs = latestRuns(this.db, jobs.map((job) => job.key));
887
+ return jobs.map((job) => summary(job, runs.get(job.key)));
888
+ }
889
+ async resolve(id, repo) {
890
+ const matches = findJobsById(this.db, id);
891
+ if (matches.length === 0) throw new ApiError(404, `no job with id ${id}`);
892
+ if (matches.length === 1) return matches[0];
893
+ const root = repo ? await gitRoot(repo).catch(() => void 0) : void 0;
894
+ const match = matches.find((job) => job.repoPath === root);
895
+ if (!match) throw new ApiError(409, `${id} exists in several repos (${matches.map((job) => job.repoPath).join(", ")}); run the command inside one or pass --repo`);
896
+ return match;
897
+ }
898
+ show(job) {
899
+ const run = latestRun(this.db, job.key);
900
+ const current = getJob(this.db, job.key) ?? job;
901
+ return {
902
+ ...summary(current, run),
903
+ branch: current.branchName,
904
+ worktree: current.worktreePath,
905
+ prBaseBranch: current.prBaseBranch,
906
+ lastResult: run?.result ?? null,
907
+ logPath: run ? this.logPath(current, run) : null,
908
+ resumeCommand: current.sessionId ? resumeCommand(current.worktreePath, current.sessionId) : null
909
+ };
910
+ }
911
+ stop(job) {
912
+ if (job.state !== "running") {
913
+ const hint = job.state === "needs_input" || job.state === "failed" || job.state === "done" ? " It has no active run, so resume its session directly." : "";
914
+ throw new ApiError(409, `${job.id} is ${job.state}, not running.${hint}`);
915
+ }
916
+ updateJob(this.db, job.key, { state: "paused" });
917
+ this.active.get(job.key)?.controller.abort("stop");
918
+ this.schedule();
919
+ return "paused";
920
+ }
921
+ async requeue(job) {
922
+ if (!REQUEUEABLE_STATES.includes(job.state)) throw new ApiError(409, `${job.id} is ${job.state}; only paused, needs_input, or failed jobs can be requeued`);
923
+ const state = (await this.detectHandFinished([job])).has(job.key) ? "done" : "queued";
924
+ if (state === "queued") updateJob(this.db, job.key, {
925
+ state: "queued",
926
+ blockedReason: null
927
+ });
928
+ this.schedule();
929
+ return state;
930
+ }
931
+ getConfig() {
932
+ return this.config;
933
+ }
934
+ async setConfig(key, value) {
935
+ this.config = await writeConfigValue(this.paths.config, key, value);
936
+ this.schedule();
937
+ return this.config;
938
+ }
939
+ status() {
940
+ const jobs = listJobs(this.db);
941
+ return {
942
+ pid: process.pid,
943
+ running: this.active.size,
944
+ queued: jobs.filter((job) => job.state === "queued").length
945
+ };
946
+ }
947
+ schedule() {
948
+ if (this.closed) return;
949
+ const jobs = listJobs(this.db);
950
+ const byKey = new Map(jobs.map((job) => [job.key, job]));
951
+ const repos = Map.groupBy(jobs, (job) => job.repoPath);
952
+ const starts = [];
953
+ let slots = this.config.concurrency - this.active.size;
954
+ const edges = listDependencies(this.db);
955
+ for (const repoJobs of repos.values()) {
956
+ const graph = graphFor(repoJobs, byKey, edges);
957
+ const byId = new Map(repoJobs.map((job) => [job.id, job]));
958
+ const states = new Map(repoJobs.map((job) => [job.id, {
959
+ id: job.id,
960
+ state: this.active.has(job.key) ? "running" : job.state,
961
+ blockedReason: job.blockedReason
962
+ }]));
963
+ for (const [id, update] of waitingUpdates(graph, states)) {
964
+ updateJob(this.db, byId.get(id).key, update);
965
+ states.set(id, {
966
+ id,
967
+ ...update
968
+ });
969
+ }
970
+ for (const id of jobsToStart(graph, states, Math.max(0, slots))) {
971
+ starts.push(byId.get(id));
972
+ slots -= 1;
973
+ }
974
+ }
975
+ for (const job of starts) this.launch(job, job.sessionId ? {
976
+ kind: "resume",
977
+ sessionId: job.sessionId,
978
+ message: HANDBACK_MESSAGE
979
+ } : { kind: "start" });
980
+ }
981
+ recover() {
982
+ for (const run of unfinishedRuns(this.db)) {
983
+ const job = getJob(this.db, run.jobKey);
984
+ if (!job || job.state !== "running") {
985
+ updateRun(this.db, run.id, {
986
+ endedAt: /* @__PURE__ */ new Date(),
987
+ result: { status: "interrupted" }
988
+ });
989
+ continue;
990
+ }
991
+ if (!run.sessionId || run.recovery) {
992
+ const reason = run.sessionId ? "the server stopped again while resuming this run after a restart" : "the server stopped before the run reported a session id";
993
+ updateRun(this.db, run.id, {
994
+ endedAt: /* @__PURE__ */ new Date(),
995
+ result: {
996
+ status: "failed",
997
+ reason
998
+ }
999
+ });
1000
+ updateJob(this.db, job.key, { state: "failed" });
1001
+ continue;
1002
+ }
1003
+ updateRun(this.db, run.id, {
1004
+ endedAt: /* @__PURE__ */ new Date(),
1005
+ result: { status: "interrupted" }
1006
+ });
1007
+ this.launch(job, {
1008
+ kind: "resume",
1009
+ sessionId: run.sessionId,
1010
+ message: RESTART_MESSAGE
1011
+ }, true);
1012
+ }
1013
+ this.schedule();
1014
+ }
1015
+ async close() {
1016
+ this.closed = true;
1017
+ const runs = [...this.active.values()];
1018
+ for (const { controller } of runs) controller.abort("shutdown");
1019
+ await Promise.allSettled(runs.map((run) => run.done));
1020
+ }
1021
+ launch(job, mode, recovery = false) {
1022
+ const harness = job.harness ?? this.config.harness;
1023
+ const effort = job.effort ?? this.config.effort;
1024
+ const model = job.model ?? this.config.model ?? null;
1025
+ updateJob(this.db, job.key, {
1026
+ state: "running",
1027
+ blockedReason: null
1028
+ });
1029
+ const run = insertRun(this.db, {
1030
+ jobKey: job.key,
1031
+ harness,
1032
+ model,
1033
+ effort,
1034
+ recovery,
1035
+ sessionId: mode.kind === "resume" ? mode.sessionId : null
1036
+ });
1037
+ const controller = new AbortController();
1038
+ const done = this.execute(job, run, mode, controller.signal).catch((error) => this.log(`run ${run.id} crashed: ${String(error)}`)).finally(() => {
1039
+ this.active.delete(job.key);
1040
+ this.schedule();
1041
+ });
1042
+ this.active.set(job.key, {
1043
+ controller,
1044
+ done
1045
+ });
1046
+ }
1047
+ async execute(job, run, mode, signal) {
1048
+ let result;
1049
+ let error;
1050
+ const dir = jobDir(this.paths, job.repoPath, job.id);
1051
+ const logFile = this.logPath(job, run);
1052
+ await mkdir(join(dir, "runs"), { recursive: true });
1053
+ const log = createWriteStream(logFile, { flags: "a" });
1054
+ try {
1055
+ const harness = this.harnesses[run.harness];
1056
+ if (!harness) throw new Error(`unknown harness ${run.harness}`);
1057
+ const input = await this.prepare(job, run, dir);
1058
+ const events = mode.kind === "start" ? harness.start(input, signal) : harness.resume(mode.sessionId, mode.message, input, signal);
1059
+ for await (const event of events) switch (event.type) {
1060
+ case "message":
1061
+ log.write(`${JSON.stringify(event.message)}\n`);
1062
+ break;
1063
+ case "session":
1064
+ if (signal.aborted) break;
1065
+ updateRun(this.db, run.id, { sessionId: event.sessionId });
1066
+ updateJob(this.db, job.key, { sessionId: event.sessionId });
1067
+ break;
1068
+ case "result":
1069
+ result = event.result;
1070
+ break;
1071
+ case "error": error = event.error;
1072
+ }
1073
+ } catch (caught) {
1074
+ error = caught.message ?? String(caught);
1075
+ } finally {
1076
+ await new Promise((resolve) => log.end(resolve));
1077
+ }
1078
+ if (signal.aborted) {
1079
+ if (signal.reason !== "shutdown") updateRun(this.db, run.id, {
1080
+ endedAt: /* @__PURE__ */ new Date(),
1081
+ result: {
1082
+ status: "stopped",
1083
+ reason: String(signal.reason)
1084
+ }
1085
+ });
1086
+ return;
1087
+ }
1088
+ const record = await this.settle(job, result, error);
1089
+ updateRun(this.db, run.id, {
1090
+ endedAt: /* @__PURE__ */ new Date(),
1091
+ result: record
1092
+ });
1093
+ }
1094
+ async settle(job, result, error) {
1095
+ let record = result ?? {
1096
+ status: "failed",
1097
+ reason: error ?? "the run ended without a result"
1098
+ };
1099
+ if (record.status === "done") {
1100
+ const verified = await this.github.isOpenDraft(job.repoPath, record.pr_url).catch((caught) => caught);
1101
+ if (verified !== true) {
1102
+ const why = verified instanceof Error ? verified.message : "it is not an open draft";
1103
+ record = {
1104
+ ...record,
1105
+ status: "failed",
1106
+ reason: `could not verify PR ${record.pr_url}: ${why}`
1107
+ };
1108
+ }
1109
+ }
1110
+ if (getJob(this.db, job.key)?.state === "running") {
1111
+ assertTransition("running", record.status);
1112
+ updateJob(this.db, job.key, {
1113
+ state: record.status,
1114
+ ...record.status === "done" ? { prUrl: record.pr_url } : {}
1115
+ });
1116
+ }
1117
+ return record;
1118
+ }
1119
+ async prepare(job, run, dir) {
1120
+ const docPath = join(dir, `${job.id}.md`);
1121
+ let projectPath;
1122
+ await writeFile(docPath, job.docSnapshot);
1123
+ if (job.projectSnapshot !== null) {
1124
+ projectPath = join(dir, "project.md");
1125
+ await writeFile(projectPath, job.projectSnapshot);
1126
+ }
1127
+ const prBaseBranch = await withRepoLock(job.repoPath, async () => {
1128
+ let branches = {
1129
+ baseBranch: job.baseBranch,
1130
+ prBaseBranch: job.prBaseBranch
1131
+ };
1132
+ if (!branches.baseBranch || !branches.prBaseBranch) {
1133
+ branches = await this.branchBase(job);
1134
+ updateJob(this.db, job.key, branches);
1135
+ }
1136
+ await ensureWorktree(job.repoPath, job.worktreePath, job.branchName, branches.baseBranch);
1137
+ return branches.prBaseBranch;
1138
+ });
1139
+ return {
1140
+ id: job.id,
1141
+ worktree: job.worktreePath,
1142
+ docPath,
1143
+ projectPath,
1144
+ branch: job.branchName,
1145
+ prBaseBranch,
1146
+ model: run.model ?? void 0,
1147
+ effort: run.effort
1148
+ };
1149
+ }
1150
+ async branchBase(job) {
1151
+ const parentId = stackParent(this.repoGraph(job.repoPath), job.id);
1152
+ if (parentId) {
1153
+ const parent = findJob(this.db, job.repoPath, parentId);
1154
+ return {
1155
+ baseBranch: parent.branchName,
1156
+ prBaseBranch: parent.branchName
1157
+ };
1158
+ }
1159
+ if (job.requestedBase) return {
1160
+ baseBranch: job.requestedBase,
1161
+ prBaseBranch: job.requestedBase.replace(/^origin\//, "")
1162
+ };
1163
+ const branch = await fetchDefaultBranch(job.repoPath);
1164
+ return {
1165
+ baseBranch: `origin/${branch}`,
1166
+ prBaseBranch: branch
1167
+ };
1168
+ }
1169
+ async detectHandFinished(jobs) {
1170
+ const candidates = jobs.filter((job) => HAND_OFF_STATES.includes(job.state));
1171
+ const found = await Promise.all(candidates.map((job) => this.github.findOpenDraft(job.repoPath, job.branchName).catch((error) => {
1172
+ this.log(`gh pr list for ${job.id} failed: ${String(error)}`);
1173
+ })));
1174
+ const moved = /* @__PURE__ */ new Set();
1175
+ candidates.forEach((job, index) => {
1176
+ const url = found[index];
1177
+ const current = getJob(this.db, job.key);
1178
+ if (url && current && HAND_OFF_STATES.includes(current.state)) {
1179
+ updateJob(this.db, job.key, {
1180
+ state: "done",
1181
+ prUrl: url
1182
+ });
1183
+ moved.add(job.key);
1184
+ }
1185
+ });
1186
+ if (moved.size > 0) this.schedule();
1187
+ return moved;
1188
+ }
1189
+ logPath(job, run) {
1190
+ return join(jobDir(this.paths, job.repoPath, job.id), "runs", `${run.id}.jsonl`);
1191
+ }
1192
+ repoGraph(repoPath) {
1193
+ const jobs = listJobs(this.db);
1194
+ return graphFor(jobs.filter((job) => job.repoPath === repoPath), new Map(jobs.map((job) => [job.key, job])), listDependencies(this.db));
1195
+ }
1196
+ };
1197
+ function graphFor(repoJobs, byKey, edges) {
1198
+ const graph = new Map(repoJobs.map((job) => [job.id, []]));
1199
+ for (const [jobKey, dependsOnKey] of edges) {
1200
+ const job = byKey.get(jobKey);
1201
+ const dep = byKey.get(dependsOnKey);
1202
+ if (job && dep && graph.has(job.id)) graph.get(job.id)?.push(dep.id);
1203
+ }
1204
+ return graph;
1205
+ }
1206
+ function planAction(doc, job, force) {
1207
+ if (!job) return "added";
1208
+ if (!doc.explicit) return "unchanged";
1209
+ if (UPDATABLE_STATES.includes(job.state)) return "updated";
1210
+ if (force && job.state !== "cancelled") return "requeued";
1211
+ return "rejected";
1212
+ }
1213
+ function summary(job, run) {
1214
+ const runReason = job.state === "needs_input" || job.state === "failed" ? run?.result?.reason ?? null : null;
1215
+ return {
1216
+ id: job.id,
1217
+ repo: job.repoPath,
1218
+ state: job.state,
1219
+ reason: job.blockedReason ?? runReason,
1220
+ sessionId: job.sessionId,
1221
+ prUrl: job.prUrl
1222
+ };
1223
+ }
1224
+ function resumeCommand(worktree, sessionId) {
1225
+ return [
1226
+ "cd",
1227
+ shellQuote(worktree),
1228
+ "&&",
1229
+ "claude",
1230
+ "--resume",
1231
+ shellQuote(sessionId),
1232
+ "--plugin-dir",
1233
+ shellQuote(pluginDir),
1234
+ "--agents",
1235
+ shellQuote(JSON.stringify(loadClaudeAgents()))
1236
+ ].join(" ");
1237
+ }
1238
+ function shellQuote(value) {
1239
+ return /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
1240
+ }
1241
+ // ../server/src/server.ts
1242
+ async function startServer(options) {
1243
+ const paths = resolvePaths();
1244
+ await mkdir(paths.home, {
1245
+ recursive: true,
1246
+ mode: 448
1247
+ });
1248
+ acquireLock(paths.pid);
1249
+ let db;
1250
+ let mill;
1251
+ try {
1252
+ db = openDb(paths.db);
1253
+ mill = new Mill({
1254
+ db,
1255
+ paths,
1256
+ config: await readConfig(paths.config),
1257
+ harnesses: { claude: claudeHarness },
1258
+ github: ghCli,
1259
+ log: options.log
1260
+ });
1261
+ } catch (error) {
1262
+ rmSync(paths.pid, { force: true });
1263
+ throw error;
1264
+ }
1265
+ let closing;
1266
+ const closed = Promise.withResolvers();
1267
+ function close() {
1268
+ closing ??= (async () => {
1269
+ await new Promise((resolve) => server.close(() => resolve()));
1270
+ await mill.close();
1271
+ db.$client.close();
1272
+ rmSync(paths.pid, { force: true });
1273
+ closed.resolve();
1274
+ })();
1275
+ return closing;
1276
+ }
1277
+ const server = createAdaptorServer({ fetch: createApp(mill, {
1278
+ version: options.version,
1279
+ onShutdown: () => void close()
1280
+ }).fetch });
1281
+ await listen(server, paths.socket);
1282
+ mill.recover();
1283
+ return {
1284
+ closed: closed.promise,
1285
+ close
1286
+ };
1287
+ }
1288
+ async function listen(server, socket) {
1289
+ if (process.platform !== "win32") rmSync(socket, { force: true });
1290
+ const umask = process.umask(127);
1291
+ try {
1292
+ await new Promise((resolve, reject) => {
1293
+ server.once("error", reject);
1294
+ server.listen(socket, () => {
1295
+ server.off("error", reject);
1296
+ resolve();
1297
+ });
1298
+ });
1299
+ } finally {
1300
+ process.umask(umask);
1301
+ }
1302
+ if (process.platform !== "win32") await chmod(socket, 384);
1303
+ }
1304
+ function acquireLock(path) {
1305
+ for (let attempt = 0; attempt < 2; attempt += 1) try {
1306
+ const fd = openSync(path, "wx", 384);
1307
+ writeSync(fd, String(process.pid));
1308
+ closeSync(fd);
1309
+ return;
1310
+ } catch (error) {
1311
+ if (error.code !== "EEXIST") throw error;
1312
+ const pid = Number(readFileSync(path, "utf8").trim());
1313
+ if (Number.isInteger(pid) && pid > 0 && isAlive(pid)) throw new Error(`an openmill server is already running (pid ${pid})`, { cause: error });
1314
+ rmSync(path, { force: true });
1315
+ }
1316
+ throw new Error(`could not take the server lock at ${path}`);
1317
+ }
1318
+ function isAlive(pid) {
1319
+ try {
1320
+ process.kill(pid, 0);
1321
+ return true;
1322
+ } catch (error) {
1323
+ return error.code === "EPERM";
1324
+ }
1325
+ }
1326
+ // ../server/src/client.ts
1327
+ function socketFetch(socketPath) {
1328
+ return async (input, init) => {
1329
+ const req = new Request(input, init);
1330
+ const url = new URL(req.url);
1331
+ const payload = req.body ? Buffer.from(await req.arrayBuffer()) : void 0;
1332
+ return new Promise((resolve, reject) => {
1333
+ const outgoing = request({
1334
+ socketPath,
1335
+ method: req.method,
1336
+ path: `${url.pathname}${url.search}`,
1337
+ headers: Object.fromEntries(req.headers)
1338
+ }, (res) => {
1339
+ const chunks = [];
1340
+ res.on("data", (chunk) => chunks.push(chunk));
1341
+ res.on("end", () => {
1342
+ const headers = new Headers();
1343
+ for (const [name, value] of Object.entries(res.headers)) if (value !== void 0) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
1344
+ resolve(new Response(Buffer.concat(chunks), {
1345
+ status: res.statusCode ?? 500,
1346
+ headers
1347
+ }));
1348
+ });
1349
+ res.on("error", reject);
1350
+ });
1351
+ outgoing.on("error", reject);
1352
+ outgoing.end(payload);
1353
+ });
1354
+ };
1355
+ }
1356
+ function createClient(socketPath) {
1357
+ return hc("http://openmill", { fetch: socketFetch(socketPath) });
1358
+ }
1359
+ // src/ui.ts
1360
+ const STATE_COLORS = {
1361
+ queued: pc.blue,
1362
+ running: pc.cyan,
1363
+ needs_input: pc.yellow,
1364
+ paused: pc.magenta,
1365
+ done: pc.green,
1366
+ failed: pc.red,
1367
+ blocked: pc.yellow,
1368
+ cancelled: pc.dim
1369
+ };
1370
+ function state(value) {
1371
+ return (STATE_COLORS[value] ?? pc.reset)(value);
1372
+ }
1373
+ function warn(message) {
1374
+ console.error(`${pc.yellow("warning:")} ${message}`);
1375
+ }
1376
+ function fail(message) {
1377
+ console.error(`${pc.red("error:")} ${message}`);
1378
+ }
1379
+ function command(text) {
1380
+ return pc.bold(text);
1381
+ }
1382
+ async function spin(text, task) {
1383
+ const spinner = ora({
1384
+ text,
1385
+ stream: process.stderr,
1386
+ isSilent: !process.stderr.isTTY
1387
+ }).start();
1388
+ try {
1389
+ return await task();
1390
+ } finally {
1391
+ spinner.stop();
1392
+ }
1393
+ }
1394
+ // src/connect.ts
1395
+ const TIMEOUT_MS = 1e4;
1396
+ async function serverStatus(client) {
1397
+ try {
1398
+ const res = await client.status.$get();
1399
+ return res.ok ? await res.json() : void 0;
1400
+ } catch {
1401
+ return;
1402
+ }
1403
+ }
1404
+ async function isRunning(client) {
1405
+ return await serverStatus(client) !== void 0;
1406
+ }
1407
+ async function waitFor(condition, isDone = () => false) {
1408
+ const deadline = Date.now() + TIMEOUT_MS;
1409
+ while (Date.now() < deadline && !isDone()) {
1410
+ if (await condition()) return true;
1411
+ await new Promise((resolve) => setTimeout(resolve, 100));
1412
+ }
1413
+ return false;
1414
+ }
1415
+ async function stopServer(client) {
1416
+ await client.shutdown.$post();
1417
+ if (!await waitFor(async () => !await isRunning(client))) throw new Error("the openmill server didn't stop");
1418
+ }
1419
+ function localClient() {
1420
+ return createClient(resolvePaths().socket);
1421
+ }
1422
+ async function connect() {
1423
+ const client = localClient();
1424
+ const status = await serverStatus(client);
1425
+ if (status) {
1426
+ if (status.version === version) return client;
1427
+ if ((status.running ?? 0) > 0) {
1428
+ warn(`the server is running openmill ${status.version ?? "(unknown)"}, not ${version}. Run ${command("openmill server stop")} once its jobs finish.`);
1429
+ return client;
1430
+ }
1431
+ await spin("restarting the openmill server", () => stopServer(client));
1432
+ }
1433
+ return spin("starting the openmill server", () => start(client));
1434
+ }
1435
+ async function start(client) {
1436
+ const paths = resolvePaths();
1437
+ mkdirSync(paths.home, {
1438
+ recursive: true,
1439
+ mode: 448
1440
+ });
1441
+ const log = openSync(paths.log, "a");
1442
+ const child = spawn(process.execPath, [
1443
+ ...process.execArgv,
1444
+ process.argv[1],
1445
+ "server",
1446
+ "run"
1447
+ ], {
1448
+ detached: true,
1449
+ stdio: [
1450
+ "ignore",
1451
+ log,
1452
+ log
1453
+ ],
1454
+ windowsHide: true
1455
+ });
1456
+ child.unref();
1457
+ if (await waitFor(() => isRunning(client), () => child.exitCode !== null)) return client;
1458
+ throw new Error(`the openmill server didn't start; see ${paths.log}`);
1459
+ }
1460
+ // src/docs.ts
1461
+ const SKIPPED_DIRS = /* @__PURE__ */ new Set([".git", "node_modules"]);
1462
+ async function collectDocs(inputs, cwd) {
1463
+ const warnings = [];
1464
+ const errors = [];
1465
+ const byPath = /* @__PURE__ */ new Map();
1466
+ async function load(path, explicit) {
1467
+ const existing = byPath.get(path);
1468
+ if (existing) {
1469
+ existing.explicit ||= explicit;
1470
+ return;
1471
+ }
1472
+ let content;
1473
+ try {
1474
+ content = await readFile(path, "utf8");
1475
+ } catch {
1476
+ errors.push(`${path}: cannot read file`);
1477
+ return;
1478
+ }
1479
+ const parsed = parseDesignDoc(content);
1480
+ if (parsed.kind === "invalid") {
1481
+ errors.push(`${path}: ${parsed.error}`);
1482
+ return;
1483
+ }
1484
+ if (parsed.kind === "no-id") {
1485
+ if (explicit) warnings.push(`skipping ${path}: no id in frontmatter`);
1486
+ else errors.push(`${path}: is a dependency but has no id in frontmatter`);
1487
+ return;
1488
+ }
1489
+ const dir = dirname(path);
1490
+ const doc = {
1491
+ id: parsed.meta.id,
1492
+ path,
1493
+ content,
1494
+ project: parsed.meta.project ? await readProject(resolve(dir, parsed.meta.project), errors, path) : void 0,
1495
+ dependsOn: [],
1496
+ dependsOnPaths: parsed.meta.dependsOn.map((dep) => resolve(dir, dep)),
1497
+ explicit
1498
+ };
1499
+ byPath.set(path, doc);
1500
+ for (const dep of doc.dependsOnPaths) await load(dep, false);
1501
+ }
1502
+ for (const input of inputs) {
1503
+ const path = resolve(cwd, input);
1504
+ const info = await stat(path).catch(() => void 0);
1505
+ if (!info) errors.push(`${path}: no such file or directory`);
1506
+ else if (info.isDirectory()) for (const file of await markdownFiles(path)) await load(file, true);
1507
+ else await load(path, true);
1508
+ }
1509
+ const docs = [...byPath.values()].map(({ dependsOnPaths, ...doc }) => ({
1510
+ ...doc,
1511
+ dependsOn: dependsOnPaths.flatMap((dep) => byPath.get(dep)?.id ?? [])
1512
+ }));
1513
+ if (errors.length > 0) throw new Error(errors.join("\n"));
1514
+ if (docs.length === 0) throw new Error("no design docs with an id found");
1515
+ return {
1516
+ docs,
1517
+ warnings
1518
+ };
1519
+ }
1520
+ async function markdownFiles(dir) {
1521
+ const files = [];
1522
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
1523
+ const path = join(dir, entry.name);
1524
+ if (entry.isDirectory() && !SKIPPED_DIRS.has(entry.name)) files.push(...await markdownFiles(path));
1525
+ else if (entry.isFile() && extname(entry.name).toLowerCase() === ".md") files.push(path);
1526
+ }
1527
+ return files.toSorted();
1528
+ }
1529
+ async function readProject(folder, errors, docPath) {
1530
+ const overview = ["README.md", "index.md"].map((name) => join(folder, name)).find((path) => existsSync(path));
1531
+ if (!overview) {
1532
+ errors.push(`${docPath}: project ${folder} has no README.md or index.md`);
1533
+ return;
1534
+ }
1535
+ return {
1536
+ path: overview,
1537
+ content: await readFile(overview, "utf8")
1538
+ };
1539
+ }
1540
+ // src/system.ts
1541
+ const isWindows = process.platform === "win32";
1542
+ function quote(arg) {
1543
+ return /^[\w./:\\=@-]+$/.test(arg) ? arg : `"${arg.replaceAll("\"", "\\\"")}"`;
1544
+ }
1545
+ function run(command, args) {
1546
+ const [file, argv] = isWindows ? [[command, ...args].map(quote).join(" "), []] : [command, args];
1547
+ return new Promise((resolve) => {
1548
+ execFile(file, argv, {
1549
+ shell: isWindows,
1550
+ windowsHide: true,
1551
+ maxBuffer: 16777216
1552
+ }, (error, stdout, stderr) => {
1553
+ resolve({
1554
+ ok: !error,
1555
+ stdout: stdout.toString(),
1556
+ stderr: stderr.toString() || (error?.message ?? "")
1557
+ });
1558
+ });
1559
+ });
1560
+ }
1561
+ async function runOrThrow(command, args) {
1562
+ const result = await run(command, args);
1563
+ if (!result.ok) throw new Error(`${command} ${args.join(" ")} failed: ${result.stderr.trim()}`);
1564
+ return result.stdout;
1565
+ }
1566
+ async function hasCommand(command) {
1567
+ return (await run(command, ["--version"])).ok;
1568
+ }
1569
+ // src/plugin.ts
1570
+ const PLUGIN_ID = `${PLUGIN_NAME}@${PLUGIN_NAME}`;
1571
+ const PLUGIN_ENTRIES = [
1572
+ ".claude-plugin",
1573
+ "skills",
1574
+ "agents"
1575
+ ];
1576
+ function marketplaceManifest(version, description) {
1577
+ return {
1578
+ name: PLUGIN_NAME,
1579
+ owner: { name: PLUGIN_NAME },
1580
+ plugins: [{
1581
+ name: PLUGIN_NAME,
1582
+ source: `./${PLUGIN_NAME}`,
1583
+ version,
1584
+ description
1585
+ }]
1586
+ };
1587
+ }
1588
+ async function writeMarketplace(dir, version) {
1589
+ const target = join(dir, PLUGIN_NAME);
1590
+ await rm(target, {
1591
+ recursive: true,
1592
+ force: true
1593
+ });
1594
+ for (const entry of PLUGIN_ENTRIES) await cp(join(pluginDir, entry), join(target, entry), { recursive: true });
1595
+ const manifestPath = join(target, ".claude-plugin", "plugin.json");
1596
+ const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
1597
+ await writeFile(manifestPath, json({
1598
+ ...manifest,
1599
+ version
1600
+ }));
1601
+ await mkdir(join(dir, ".claude-plugin"), { recursive: true });
1602
+ await writeFile(join(dir, ".claude-plugin", "marketplace.json"), json(marketplaceManifest(version, manifest.description)));
1603
+ }
1604
+ async function listNames(args, key) {
1605
+ return JSON.parse(await runOrThrow("claude", args)).map((entry) => String(entry[key]));
1606
+ }
1607
+ async function installPlugin(dir) {
1608
+ if ((await listNames([
1609
+ "plugin",
1610
+ "marketplace",
1611
+ "list",
1612
+ "--json"
1613
+ ], "name")).includes("openmill")) await runOrThrow("claude", [
1614
+ "plugin",
1615
+ "marketplace",
1616
+ "update",
1617
+ PLUGIN_NAME
1618
+ ]);
1619
+ else await runOrThrow("claude", [
1620
+ "plugin",
1621
+ "marketplace",
1622
+ "add",
1623
+ dir
1624
+ ]);
1625
+ await runOrThrow("claude", [
1626
+ "plugin",
1627
+ (await listNames([
1628
+ "plugin",
1629
+ "list",
1630
+ "--json"
1631
+ ], "id")).includes(PLUGIN_ID) ? "update" : "install",
1632
+ PLUGIN_ID
1633
+ ]);
1634
+ }
1635
+ async function uninstallPlugin() {
1636
+ await run("claude", [
1637
+ "plugin",
1638
+ "uninstall",
1639
+ PLUGIN_ID
1640
+ ]);
1641
+ await run("claude", [
1642
+ "plugin",
1643
+ "marketplace",
1644
+ "remove",
1645
+ PLUGIN_NAME
1646
+ ]);
1647
+ }
1648
+ function json(value) {
1649
+ return `${JSON.stringify(value, null, 2)}\n`;
1650
+ }
1651
+ function meetsNodeVersion(version) {
1652
+ return Number(version.replace(/^v/, "").split(".")[0]) >= 24;
1653
+ }
1654
+ function isInside(path, dir) {
1655
+ const rel = relative(resolve(dir), resolve(path));
1656
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
1657
+ }
1658
+ function installedGlobalVersion(npmLsOutput, name) {
1659
+ return JSON.parse(npmLsOutput || "{}").dependencies?.[name]?.version;
1660
+ }
1661
+ // src/install.ts
1662
+ var Cancelled = class extends Error {};
1663
+ function interactive(options) {
1664
+ return !options.yes && Boolean(process.stdin.isTTY);
1665
+ }
1666
+ function answer(value) {
1667
+ if (p.isCancel(value)) throw new Cancelled();
1668
+ return value;
1669
+ }
1670
+ async function step(title, task) {
1671
+ const spinner = p.spinner();
1672
+ spinner.start(title);
1673
+ try {
1674
+ spinner.stop(`${title}${await task().then((note) => note ? pc.dim(` (${note})`) : "")}`);
1675
+ } catch (error) {
1676
+ spinner.error(title);
1677
+ throw error;
1678
+ }
1679
+ }
1680
+ async function checkPrerequisites() {
1681
+ if (!meetsNodeVersion(process.versions.node)) throw new Error(`openmill needs Node 24 or later, found ${process.versions.node}`);
1682
+ for (const tool of ["git", "gh"]) if (!await hasCommand(tool)) throw new Error(`${tool} isn't installed or isn't on PATH`);
1683
+ if (!(await run("gh", ["auth", "status"])).ok) p.log.warn(`gh isn't signed in. Run ${pc.bold("gh auth login")} before queuing jobs.`);
1684
+ const claude = await hasCommand("claude");
1685
+ if (!claude) p.log.warn("The claude CLI isn't on PATH, so the plugin step is skipped and resume commands won't work. Headless runs still work.");
1686
+ return { claude };
1687
+ }
1688
+ async function installGlobal() {
1689
+ const bin = realpathSync(process.argv[1]);
1690
+ if (!bin.split(/[\\/]/).includes("node_modules")) return "running from source, skipped";
1691
+ const root = (await runOrThrow("npm", ["root", "-g"])).trim();
1692
+ if (isInside(bin, realpathSync(root))) return "already global";
1693
+ if (installedGlobalVersion((await run("npm", [
1694
+ "ls",
1695
+ "-g",
1696
+ name,
1697
+ "--json",
1698
+ "--depth=0"
1699
+ ])).stdout, name) === version) return `${version} already installed`;
1700
+ await runOrThrow("npm", [
1701
+ "install",
1702
+ "-g",
1703
+ `${name}@${version}`
1704
+ ]);
1705
+ return version;
1706
+ }
1707
+ async function stopRunningServer(options) {
1708
+ const client = localClient();
1709
+ const status = await serverStatus(client);
1710
+ if (!status) return "not running";
1711
+ if ((status.running ?? 0) > 0) {
1712
+ if (!(interactive(options) && answer(await p.confirm({
1713
+ message: `${status.running} jobs are running. Stop the server anyway? Their runs will be aborted.`,
1714
+ initialValue: false
1715
+ })))) {
1716
+ p.log.warn(`Left the server running. Run ${pc.bold("openmill server stop")} once its jobs finish.`);
1717
+ return;
1718
+ }
1719
+ }
1720
+ await stopServer(client);
1721
+ return "stopped";
1722
+ }
1723
+ const CONFIG_PROMPTS = [{
1724
+ key: "concurrency",
1725
+ message: "How many jobs can run at once?"
1726
+ }, {
1727
+ key: "model",
1728
+ message: "Which model should agents use? Leave empty for the harness default."
1729
+ }];
1730
+ async function promptConfig(path) {
1731
+ const current = await readConfig(path);
1732
+ for (const { key, message } of CONFIG_PROMPTS) {
1733
+ const value = answer(await p.text({
1734
+ message,
1735
+ initialValue: String(current[key] ?? ""),
1736
+ validate: (input = "") => {
1737
+ const parsed = parseConfigValue(key, input);
1738
+ return input.trim() === "" || parsed.ok ? void 0 : parsed.error;
1739
+ }
1740
+ })).trim();
1741
+ const parsed = parseConfigValue(key, value);
1742
+ if (value !== "" && parsed.ok) await writeConfigValue(path, key, parsed.value);
1743
+ }
1744
+ }
1745
+ async function install(options) {
1746
+ const paths = resolvePaths();
1747
+ p.intro(pc.inverse(` openmill ${version} `));
1748
+ try {
1749
+ const { claude } = await checkPrerequisites();
1750
+ await step("Installing openmill globally", installGlobal);
1751
+ await step("Creating the openmill home", async () => {
1752
+ await mkdir(paths.home, {
1753
+ recursive: true,
1754
+ mode: 448
1755
+ });
1756
+ return paths.home;
1757
+ });
1758
+ if (claude) await step("Installing the Claude plugin", async () => {
1759
+ const dir = join(paths.home, "plugin");
1760
+ await writeMarketplace(dir, version);
1761
+ await installPlugin(dir);
1762
+ });
1763
+ await step("Stopping the old server", () => stopRunningServer(options));
1764
+ if (interactive(options)) await promptConfig(paths.config);
1765
+ p.note(`openmill add docs/feature.md\nopenmill ls`, "Next steps");
1766
+ p.outro("openmill is installed");
1767
+ } catch (error) {
1768
+ if (error instanceof Cancelled) {
1769
+ p.cancel("Install cancelled");
1770
+ process.exitCode = 1;
1771
+ return;
1772
+ }
1773
+ throw error;
1774
+ }
1775
+ }
1776
+ async function uninstall(options) {
1777
+ const paths = resolvePaths();
1778
+ p.intro(pc.inverse(" openmill uninstall "));
1779
+ try {
1780
+ const client = localClient();
1781
+ await step("Stopping the server", async () => {
1782
+ if (!await serverStatus(client)) return "not running";
1783
+ await stopServer(client);
1784
+ });
1785
+ if (await hasCommand("claude")) await step("Removing the Claude plugin", async () => {
1786
+ await uninstallPlugin();
1787
+ await rm(join(paths.home, "plugin"), {
1788
+ recursive: true,
1789
+ force: true
1790
+ });
1791
+ });
1792
+ await step("Removing the global package", async () => {
1793
+ await run("npm", [
1794
+ "uninstall",
1795
+ "-g",
1796
+ name
1797
+ ]);
1798
+ });
1799
+ if (options.purge) {
1800
+ if (!(options.yes || interactive(options) && answer(await p.confirm({
1801
+ message: `Delete ${paths.home}? This removes every job, worktree, log, and config value.`,
1802
+ initialValue: false
1803
+ })))) p.log.warn(`Kept ${paths.home}. Pass --yes with --purge to delete it without a prompt.`);
1804
+ else await step(`Deleting ${paths.home}`, async () => {
1805
+ await rm(paths.home, {
1806
+ recursive: true,
1807
+ force: true
1808
+ });
1809
+ });
1810
+ }
1811
+ p.outro("openmill is uninstalled");
1812
+ } catch (error) {
1813
+ if (error instanceof Cancelled) {
1814
+ p.cancel("Uninstall cancelled");
1815
+ process.exitCode = 1;
1816
+ return;
1817
+ }
1818
+ throw error;
1819
+ }
1820
+ }
1821
+ // src/output.ts
1822
+ async function unwrap(response) {
1823
+ const res = await response;
1824
+ const body = await res.json();
1825
+ if (!res.ok) {
1826
+ const message = body.error;
1827
+ throw new Error(typeof message === "string" ? message : "request failed");
1828
+ }
1829
+ return body;
1830
+ }
1831
+ function table(header, rows) {
1832
+ const widths = header.map((title, column) => Math.max(title.length, ...rows.map((row) => stripVTControlCharacters(row[column] ?? "").length)));
1833
+ return [header.map((title) => pc.dim(title)), ...rows].map((row) => row.map((cell, column) => cell + " ".repeat((widths[column] ?? 0) - stripVTControlCharacters(cell).length)).join(" ").trimEnd()).join("\n");
1834
+ }
1835
+ // src/index.ts
1836
+ function option(parse) {
1837
+ return (value) => {
1838
+ const parsed = parse(value);
1839
+ if (!parsed.ok) throw new InvalidArgumentError(parsed.error);
1840
+ return parsed.value;
1841
+ };
1842
+ }
1843
+ async function runningClient() {
1844
+ const client = localClient();
1845
+ if (await isRunning(client)) return client;
1846
+ console.log(pc.dim("not running"));
1847
+ }
1848
+ const program = new Command().name("openmill").description(description).version(version, "-v, --version");
1849
+ program.command("add").description("queue design docs as jobs").argument("<paths...>", "design docs or directories of them").option("--repo <path>", "target repo (default: the git root of the current directory)").option("--base <branch>", "base branch for jobs with no dependency").option("--harness <name>", "harness for these jobs", option(parseHarness)).option("--model <name>", "model for these jobs", option(parseModel)).option("--effort <level>", "effort for these jobs", option(parseEffort)).option("--force", "re-queue jobs that already started", false).action(async (paths, options) => {
1850
+ const { docs, warnings } = await collectDocs(paths, process.cwd());
1851
+ for (const warning of warnings) warn(warning);
1852
+ const client = await connect();
1853
+ const { jobs } = await spin(`queuing ${docs.length} docs`, () => unwrap(client.jobs.$post({ json: {
1854
+ repo: options.repo ?? process.cwd(),
1855
+ base: options.base,
1856
+ harness: options.harness,
1857
+ model: options.model,
1858
+ effort: options.effort,
1859
+ force: options.force,
1860
+ docs
1861
+ } })));
1862
+ for (const job of jobs) console.log(`${job.action === "unchanged" ? pc.dim(job.action) : pc.green(job.action)} ${pc.bold(job.id)}`);
1863
+ });
1864
+ program.command("ls").description("list jobs").action(async () => {
1865
+ const { jobs } = await unwrap((await connect()).jobs.$get());
1866
+ console.log(table([
1867
+ "ID",
1868
+ "STATE",
1869
+ "REASON",
1870
+ "SESSION",
1871
+ "PR"
1872
+ ], jobs.map((job) => [
1873
+ pc.bold(job.id),
1874
+ state(job.state),
1875
+ job.reason ?? "",
1876
+ pc.dim(job.sessionId ?? ""),
1877
+ job.prUrl ?? ""
1878
+ ])));
1879
+ });
1880
+ program.command("show").description("show a job and how to resume its session").argument("<id>").action(async (id) => {
1881
+ const job = await unwrap((await connect()).jobs[":id"].$get({
1882
+ param: { id },
1883
+ query: { repo: process.cwd() }
1884
+ }));
1885
+ const lines = [
1886
+ ["id", pc.bold(job.id)],
1887
+ ["repo", job.repo],
1888
+ ["state", `${state(job.state)}${job.reason ? ` (${job.reason})` : ""}`],
1889
+ ["branch", `${job.branch}${job.prBaseBranch ? ` -> ${job.prBaseBranch}` : ""}`],
1890
+ ["worktree", job.worktree],
1891
+ ["session", job.sessionId ?? "-"],
1892
+ ["pr", job.prUrl ?? "-"],
1893
+ ["log", job.logPath ?? "-"],
1894
+ ["result", job.lastResult ? JSON.stringify(job.lastResult) : "-"]
1895
+ ].map(([label, value]) => `${pc.dim(`${label}:`.padEnd(11))}${value}`);
1896
+ if (job.resumeCommand) lines.push("", "Resume the session:", ` ${command(job.resumeCommand)}`);
1897
+ console.log(lines.join("\n"));
1898
+ });
1899
+ program.command("stop").description("abort a running job so you can take it over").argument("<id>").action(async (id) => {
1900
+ const result = await unwrap((await connect()).jobs[":id"].stop.$post({
1901
+ param: { id },
1902
+ query: { repo: process.cwd() }
1903
+ }));
1904
+ console.log(`${pc.bold(id)} is ${state(result.state)}. Run ${command(`openmill show ${id}`)} for the resume command.`);
1905
+ });
1906
+ program.command("requeue").description("hand a paused, needs_input, or failed job back to the queue").argument("<id>").action(async (id) => {
1907
+ const result = await unwrap((await connect()).jobs[":id"].requeue.$post({
1908
+ param: { id },
1909
+ query: { repo: process.cwd() }
1910
+ }));
1911
+ console.log(`${pc.bold(id)} is ${state(result.state)}`);
1912
+ });
1913
+ const config = program.command("config").description("read and write config.json");
1914
+ config.command("get").argument("<key>", CONFIG_KEYS.join(", ")).action(async (key) => {
1915
+ if (!isConfigKey(key)) throw new Error(`unknown config key ${key}`);
1916
+ const { config: values } = await unwrap((await connect()).config.$get());
1917
+ console.log(String(values[key] ?? ""));
1918
+ });
1919
+ config.command("set").argument("<key>", CONFIG_KEYS.join(", ")).argument("<value>").action(async (key, value) => {
1920
+ await unwrap((await connect()).config[":key"].$put({
1921
+ param: { key },
1922
+ json: { value }
1923
+ }));
1924
+ });
1925
+ config.command("list").action(async () => {
1926
+ const { config: values } = await unwrap((await connect()).config.$get());
1927
+ console.log(table(["KEY", "VALUE"], CONFIG_KEYS.map((key) => [key, values[key] === void 0 ? pc.dim("(harness default)") : String(values[key])])));
1928
+ });
1929
+ const server = program.command("server").description("manage the background server");
1930
+ server.command("status").action(async () => {
1931
+ const client = await runningClient();
1932
+ if (!client) return;
1933
+ const status = await unwrap(client.status.$get());
1934
+ console.log(`${pc.green("running")} ${status.version} (pid ${status.pid}), ${status.running} running jobs, ${status.queued} queued`);
1935
+ });
1936
+ server.command("stop").action(async () => {
1937
+ const client = await runningClient();
1938
+ if (!client) return;
1939
+ await spin("stopping the server", () => stopServer(client));
1940
+ console.log("stopped");
1941
+ });
1942
+ server.command("run", { hidden: true }).description("run the server in the foreground").action(async () => {
1943
+ const running = await startServer({
1944
+ version,
1945
+ log: (message) => console.error(message)
1946
+ });
1947
+ for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => void running.close());
1948
+ await running.closed;
1949
+ });
1950
+ program.command("install").description("install openmill globally and set up the Claude plugin").option("-y, --yes", "accept defaults without prompting", false).action(install);
1951
+ program.command("uninstall").description("remove the Claude plugin and the global package").option("--purge", "also delete the openmill home directory", false).option("-y, --yes", "don't ask before deleting", false).action(uninstall);
1952
+ try {
1953
+ await program.parseAsync();
1954
+ } catch (error) {
1955
+ fail(error.message);
1956
+ process.exitCode = 1;
1957
+ }
1958
+ export {};