@soleone/factory 0.1.0 → 0.2.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.
package/dist/cli.mjs CHANGED
@@ -1,16 +1,21 @@
1
1
  #!/usr/bin/env node
2
- import { execFile, spawn } from "node:child_process";
3
- import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
- import { basename, join } from "node:path";
2
+ import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
5
4
  import { parseArgs, promisify } from "node:util";
6
- import { homedir } from "node:os";
7
- //#region src/agents.ts
5
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
6
+ import { mkdtemp, rm } from "node:fs/promises";
7
+ import { homedir, tmpdir } from "node:os";
8
+ import { execFile, spawn } from "node:child_process";
9
+ import { createServer } from "node:http";
10
+ import { fileURLToPath } from "node:url";
11
+ import { createInterface } from "node:readline";
12
+ //#region src/backend/agents.ts
8
13
  const LIMITS = {
9
14
  claude: /usage limit|You've hit your [\w' ]*limit|You've reached your [\w ]*limit|rate_limit_error/i,
10
15
  pi: /usage limit|usage_limit_reached|usage_not_included|rate_limit_exceeded/i
11
16
  };
12
17
  const AGENT_NAMES = Object.keys(LIMITS);
13
- function agent(name, model) {
18
+ function agent(name, { model, effort } = {}) {
14
19
  const pick = model ? ["--model", model] : [];
15
20
  if (name === "claude") return {
16
21
  name,
@@ -21,18 +26,73 @@ function agent(name, model) {
21
26
  "bypassPermissions",
22
27
  "--output-format",
23
28
  "json",
24
- ...pick
29
+ ...pick,
30
+ ...effort ? ["--effort", effort] : []
25
31
  ],
26
32
  limit: LIMITS.claude
27
33
  };
28
34
  if (name === "pi") return {
29
35
  name,
30
36
  command: "pi",
31
- args: ["-p", ...pick],
37
+ args: [
38
+ "-p",
39
+ ...pick,
40
+ ...effort ? ["--thinking", effort] : []
41
+ ],
32
42
  limit: LIMITS.pi
33
43
  };
34
44
  throw new Error(`unknown agent ${name} (known: ${AGENT_NAMES.join(", ")})`);
35
45
  }
46
+ /**
47
+ * How the Plan chat starts an agent: Pi in RPC mode, Claude Code streaming JSON both ways (chat.ts
48
+ * reads each). Only tools for looking and running commands; it changes the queue through the
49
+ * factory CLI. Claude Code's are bypassed like a run's, since nobody is there to answer a prompt.
50
+ * Each keeps the chat as session `id`, continued once `resume`; Pi's session files go in `folder`.
51
+ */
52
+ function chatAgent(name, { model, effort }, context, session) {
53
+ const pick = model ? ["--model", model] : [];
54
+ if (name === "claude") return {
55
+ command: "claude",
56
+ args: [
57
+ "-p",
58
+ "--input-format",
59
+ "stream-json",
60
+ "--output-format",
61
+ "stream-json",
62
+ "--verbose",
63
+ "--include-partial-messages",
64
+ "--replay-user-messages",
65
+ session.resume ? "--resume" : "--session-id",
66
+ session.id,
67
+ "--permission-mode",
68
+ "bypassPermissions",
69
+ "--tools",
70
+ "Read,Bash,Grep,Glob",
71
+ "--append-system-prompt",
72
+ context,
73
+ ...pick,
74
+ ...effort ? ["--effort", effort] : []
75
+ ]
76
+ };
77
+ if (name === "pi") return {
78
+ command: "pi",
79
+ args: [
80
+ "--mode",
81
+ "rpc",
82
+ "--session-id",
83
+ session.id,
84
+ "--session-dir",
85
+ session.folder,
86
+ "--tools",
87
+ "read,bash,grep,find,ls",
88
+ "--append-system-prompt",
89
+ context,
90
+ ...pick,
91
+ ...effort ? ["--thinking", effort] : []
92
+ ]
93
+ };
94
+ throw new Error(`unknown agent ${name} (known: ${AGENT_NAMES.join(", ")})`);
95
+ }
36
96
  /** Only the end of the log decides: the agent's own work earlier on may mention limits too. */
37
97
  function classify(agent, code, log) {
38
98
  const tail = log.slice(-8e3);
@@ -116,38 +176,557 @@ function wallClock(time, zone) {
116
176
  };
117
177
  }
118
178
  //#endregion
119
- //#region src/state.ts
179
+ //#region src/backend/state.ts
120
180
  const STATE = process.env.DATA ? join(process.env.DATA, "apps", "factory") : join(homedir(), ".local", "share", "factory");
121
- const key = (item) => `${item.repo} ${item.id}`;
122
- function readLedger(state) {
123
- const path = join(state, "ledger.jsonl");
124
- if (!existsSync(path)) return [];
125
- return readFileSync(path, "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line));
126
- }
127
- function appendLedger(state, entry) {
128
- appendFileSync(join(state, "ledger.jsonl"), `${JSON.stringify(entry)}\n`);
129
- }
130
- /** What the ledger says about each item: finished for good, or which agents already failed it. */
131
- function replay(ledger) {
132
- const finished = /* @__PURE__ */ new Set();
133
- const failedBy = /* @__PURE__ */ new Map();
134
- for (const entry of ledger) {
135
- if (entry.outcome === "done") finished.add(key(entry));
136
- if (entry.outcome !== "failed" && entry.outcome !== "timeout") continue;
137
- const agents = [...failedBy.get(key(entry)) ?? [], entry.agent];
138
- failedBy.set(key(entry), agents);
139
- if (agents.length >= 2) finished.add(key(entry));
181
+ const pidPath = (state) => join(state, "factory.pid");
182
+ function runningPid(state) {
183
+ if (!existsSync(pidPath(state))) return void 0;
184
+ const pid = Number(readFileSync(pidPath(state), "utf8"));
185
+ return alive(pid) ? pid : void 0;
186
+ }
187
+ function alive(pid) {
188
+ try {
189
+ process.kill(pid, 0);
190
+ return true;
191
+ } catch (error) {
192
+ if (error.code === "ESRCH") return false;
193
+ throw error;
140
194
  }
141
- return {
142
- finished,
143
- failedBy
144
- };
145
195
  }
146
196
  const LEVELS = [
147
197
  "auto",
148
198
  "skim",
149
199
  "decide"
150
200
  ];
201
+ const DEFAULTS = {
202
+ agents: {
203
+ claude: {},
204
+ pi: {}
205
+ },
206
+ chat: { agent: "pi" },
207
+ presets: [],
208
+ limit: 1,
209
+ timeout: 60,
210
+ auto: {
211
+ on: false,
212
+ levels: LEVELS,
213
+ plays: [],
214
+ repos: []
215
+ }
216
+ };
217
+ const settingsPath = (state) => join(state, "settings.json");
218
+ function readSettings(state) {
219
+ if (!existsSync(settingsPath(state))) return DEFAULTS;
220
+ return checkSettings(JSON.parse(readFileSync(settingsPath(state), "utf8")));
221
+ }
222
+ function writeSettings(state, settings) {
223
+ writeFileSync(settingsPath(state), `${JSON.stringify(checkSettings(settings), null, 2)}\n`);
224
+ }
225
+ /** Settings come from a file people edit and from the page, so they are checked on the way in. */
226
+ function checkSettings(raw) {
227
+ const settings = {
228
+ ...DEFAULTS,
229
+ ...raw,
230
+ auto: {
231
+ ...DEFAULTS.auto,
232
+ ...raw.auto
233
+ }
234
+ };
235
+ for (const name of Object.keys(settings.agents)) if (!AGENT_NAMES.includes(name)) throw new Error(`unknown agent ${name} (known: ${AGENT_NAMES.join(", ")})`);
236
+ if (!AGENT_NAMES.includes(settings.chat.agent)) throw new Error(`unknown chat agent ${settings.chat.agent} (known: ${AGENT_NAMES.join(", ")})`);
237
+ for (const preset of settings.presets) if (!AGENT_NAMES.includes(preset.agent)) throw new Error(`unknown preset agent ${preset.agent} (known: ${AGENT_NAMES.join(", ")})`);
238
+ if (Object.keys(settings.agents).length === 0) throw new Error("settings need at least one agent");
239
+ if (settings.limit !== null && !(Number.isInteger(settings.limit) && settings.limit > 0)) throw new Error(`limit wants a whole number above 0 or null, got ${settings.limit}`);
240
+ if (settings.until !== void 0 && !/^\d{1,2}:\d{2}$/.test(settings.until)) throw new Error(`until wants HH:MM, got ${settings.until}`);
241
+ if (!(Number.isInteger(settings.timeout) && settings.timeout > 0)) throw new Error(`timeout wants whole minutes above 0, got ${settings.timeout}`);
242
+ for (const level of settings.auto.levels) if (!LEVELS.includes(level)) throw new Error(`unknown level ${level}`);
243
+ return settings;
244
+ }
245
+ const candidatesPath = (state) => join(state, "candidates.json");
246
+ const refreshLock = (state) => join(state, "candidates.lock");
247
+ function readCandidates(state) {
248
+ if (!existsSync(candidatesPath(state))) return void 0;
249
+ return JSON.parse(readFileSync(candidatesPath(state), "utf8"));
250
+ }
251
+ function refreshingCandidates(state) {
252
+ if (!existsSync(refreshLock(state))) return false;
253
+ return alive(Number(readFileSync(refreshLock(state), "utf8")));
254
+ }
255
+ /** Asks workwork again, unless some process (the factory or serve) already is. */
256
+ async function refreshCandidates(state, workwork) {
257
+ if (refreshingCandidates(state)) return;
258
+ rmSync(refreshLock(state), { force: true });
259
+ try {
260
+ closeSync(openSync(refreshLock(state), "wx"));
261
+ } catch (error) {
262
+ if (error.code === "EEXIST") return;
263
+ throw error;
264
+ }
265
+ writeFileSync(refreshLock(state), `${process.pid}\n`);
266
+ try {
267
+ const items = JSON.parse(await output(workwork, ["--all", "--json"], process.cwd()));
268
+ const candidates = {
269
+ at: (/* @__PURE__ */ new Date()).toISOString(),
270
+ items
271
+ };
272
+ writeFileSync(candidatesPath(state), JSON.stringify(candidates));
273
+ } finally {
274
+ rmSync(refreshLock(state), { force: true });
275
+ }
276
+ }
277
+ async function output(command, args, cwd) {
278
+ const { stdout, stderr } = await promisify(execFile)(command, args, {
279
+ cwd,
280
+ maxBuffer: 67108864
281
+ });
282
+ process.stderr.write(stderr);
283
+ return stdout;
284
+ }
285
+ //#endregion
286
+ //#region src/backend/review.ts
287
+ const MINUTE$1 = 6e4;
288
+ /** The branch workwork has the agent push a candidate's work to. */
289
+ const workworkBranch = (item) => `workwork/${item.id.replace(/[^\w./@-]+/g, "-")}`;
290
+ /** The PR workwork had the agent open, found by the branch workwork names; scans name theirs per area, so they find none. */
291
+ async function findPr(item) {
292
+ const branch = workworkBranch(item);
293
+ return JSON.parse(await output("gh", [
294
+ "pr",
295
+ "list",
296
+ "--head",
297
+ branch,
298
+ "--state",
299
+ "all",
300
+ "--json",
301
+ "url"
302
+ ], item.repo))[0]?.url;
303
+ }
304
+ async function readPr(url) {
305
+ const raw = JSON.parse(await gh([
306
+ "pr",
307
+ "view",
308
+ url,
309
+ "--json",
310
+ "state,isDraft,title,body,additions,deletions,files,mergeable,isCrossRepository,statusCheckRollup"
311
+ ]));
312
+ return {
313
+ state: raw.state,
314
+ draft: raw.isDraft,
315
+ title: raw.title,
316
+ level: /^Level: (\w+)\s*$/m.exec(raw.body)?.[1],
317
+ additions: raw.additions,
318
+ deletions: raw.deletions,
319
+ files: raw.files.map((file) => file.path),
320
+ checks: checks(raw.statusCheckRollup),
321
+ conflicts: raw.mergeable === "UNKNOWN" ? null : raw.mergeable === "CONFLICTING",
322
+ fork: raw.isCrossRepository
323
+ };
324
+ }
325
+ /** Check runs have a conclusion, empty while running; commit statuses have a state. */
326
+ function checks(rollup) {
327
+ if (rollup.length === 0) return "none";
328
+ const results = rollup.map((check) => check.conclusion || check.state || "");
329
+ if (results.some((result) => /FAILURE|ERROR|CANCELLED|TIMED_OUT|ACTION_REQUIRED/.test(result))) return "failing";
330
+ if (results.some((result) => result === "" || result === "PENDING" || result === "EXPECTED")) return "pending";
331
+ return "passing";
332
+ }
333
+ /** What the review popup shows: the whole PR body and its diff, fetched only when opened. */
334
+ async function readPrDetails(url) {
335
+ const [view, diff] = await Promise.all([gh([
336
+ "pr",
337
+ "view",
338
+ url,
339
+ "--json",
340
+ "body"
341
+ ]), gh([
342
+ "pr",
343
+ "diff",
344
+ url
345
+ ])]);
346
+ return {
347
+ body: JSON.parse(view).body,
348
+ diff
349
+ };
350
+ }
351
+ const mergePr = (url) => gh([
352
+ "pr",
353
+ "merge",
354
+ url,
355
+ "--squash",
356
+ "--delete-branch"
357
+ ]);
358
+ const closePr = (url) => gh([
359
+ "pr",
360
+ "close",
361
+ url,
362
+ "--delete-branch"
363
+ ]);
364
+ /** A rebase that stopped on conflicts git can't resolve; nothing was pushed. */
365
+ var Conflicts = class extends Error {
366
+ files;
367
+ constructor(files) {
368
+ super(`Rebase stopped. Resolve these conflicts manually; no changes were pushed:\n${files.join("\n")}`);
369
+ this.files = files;
370
+ }
371
+ };
372
+ async function rebasePr(url) {
373
+ const pull = /^(https:\/\/github\.com\/[\w.-]+\/[\w.-]+)\/pull\/(\d+)$/.exec(url);
374
+ if (!pull) throw new Error("Rebase requires a github.com pull request URL");
375
+ const [, repo, number] = pull;
376
+ const pr = JSON.parse(await gh([
377
+ "pr",
378
+ "view",
379
+ url,
380
+ "--json",
381
+ "baseRefName,headRefName,isCrossRepository"
382
+ ]));
383
+ if (pr.isCrossRepository || pr.baseRefName === pr.headRefName) throw new Error("Rebase requires a separate PR branch in the same repository");
384
+ const dir = await mkdtemp(join(tmpdir(), "factory-rebase-"));
385
+ const git = (...args) => output("git", args, dir);
386
+ const remote = `${repo}.git`;
387
+ const base = "refs/factory/base";
388
+ const head = "refs/factory/head";
389
+ const branch = `refs/heads/${pr.headRefName}`;
390
+ try {
391
+ await git("init", "--quiet");
392
+ await git("config", "--add", "credential.https://github.com.helper", "");
393
+ await git("config", "--add", "credential.https://github.com.helper", "!gh auth git-credential");
394
+ await git("fetch", "--no-tags", remote, `refs/heads/${pr.baseRefName}:${base}`, `refs/pull/${number}/head:${head}`);
395
+ const before = (await git("rev-parse", head)).trim();
396
+ await git("checkout", "--quiet", "--detach", head);
397
+ try {
398
+ await git("rebase", "--rebase-merges", base);
399
+ } catch (error) {
400
+ const conflicts = (await git("diff", "--name-only", "--diff-filter=U")).trim();
401
+ if (!conflicts) throw error;
402
+ throw new Conflicts(conflicts.split("\n"));
403
+ }
404
+ await git("push", `--force-with-lease=${branch}:${before}`, remote, `HEAD:${branch}`);
405
+ } finally {
406
+ await rm(dir, {
407
+ recursive: true,
408
+ force: true
409
+ });
410
+ }
411
+ }
412
+ /** Run outside any repo, so --delete-branch only touches GitHub, never a local checkout. */
413
+ const gh = (args) => output("gh", args, tmpdir());
414
+ /**
415
+ * PR status for the page. gh takes a second or more per PR, so this answers from what it last
416
+ * fetched and refreshes open PRs in the background. While GitHub calculates mergeability, retry
417
+ * sooner so the page doesn't wait a minute after a rebase.
418
+ */
419
+ function prCache() {
420
+ const cache = /* @__PURE__ */ new Map();
421
+ function refresh(url) {
422
+ const entry = {
423
+ at: Date.now(),
424
+ pr: cache.get(url)?.pr
425
+ };
426
+ cache.set(url, entry);
427
+ readPr(url).then((pr) => entry.pr = pr, (error) => console.error(`factory: gh pr view ${url} failed: ${error.message}`));
428
+ }
429
+ return {
430
+ get(urls) {
431
+ const prs = {};
432
+ for (const url of urls) {
433
+ const entry = cache.get(url);
434
+ const interval = entry?.pr?.conflicts === null ? 5e3 : MINUTE$1;
435
+ if (!entry || (entry.pr?.state ?? "OPEN") === "OPEN" && Date.now() - entry.at > interval) refresh(url);
436
+ const pr = cache.get(url).pr;
437
+ if (pr) prs[url] = pr;
438
+ }
439
+ return prs;
440
+ },
441
+ /** Asks GitHub now, for an action that must not act on a stale answer. */
442
+ async fresh(url) {
443
+ const pr = await readPr(url);
444
+ cache.set(url, {
445
+ at: Date.now(),
446
+ pr
447
+ });
448
+ return pr;
449
+ }
450
+ };
451
+ }
452
+ //#endregion
453
+ //#region src/backend/types.ts
454
+ /** A candidate's identity across workwork runs. */
455
+ const itemKey = (item) => `${item.repo} ${item.id}`;
456
+ const onTrain = (car) => car !== void 0 && car.step !== "merged" && car.step !== "skipped";
457
+ /** The PR of the job's latest attempt that linked one. */
458
+ const prUrl = (job) => job.attempts.findLast((attempt) => attempt.url?.includes("/pull/"))?.url;
459
+ /** Merging from the page skips GitHub's own page, so it only goes ahead when nothing argues against it. */
460
+ const canMerge = (pr) => pr.state === "OPEN" && !pr.draft && pr.conflicts === false && (pr.checks === "passing" || pr.checks === "none");
461
+ const canRebase = (pr) => pr.state === "OPEN" && pr.conflicts === true && !pr.fork;
462
+ //#endregion
463
+ //#region src/backend/jobs.ts
464
+ /** An unexpected failure gets one more try by the same agent. */
465
+ const TRIES$1 = 2;
466
+ const path = (state) => join(state, "jobs.jsonl");
467
+ function append(state, event) {
468
+ appendFileSync(path(state), `${JSON.stringify(event)}\n`);
469
+ }
470
+ /** Every job ever, the queued ones in the order they will be taken: picks first, then auto. */
471
+ function readJobs(state) {
472
+ if (!existsSync(path(state))) return [];
473
+ const jobs = /* @__PURE__ */ new Map();
474
+ const failures = /* @__PURE__ */ new Map();
475
+ const picks = [];
476
+ const autos = [];
477
+ for (const line of readFileSync(path(state), "utf8").split("\n")) {
478
+ if (!line) continue;
479
+ const event = JSON.parse(line);
480
+ if (event.type === "add") {
481
+ const job = {
482
+ ...event.job,
483
+ added: event.at,
484
+ state: "queued",
485
+ attempts: [],
486
+ notes: []
487
+ };
488
+ jobs.set(job.id, job);
489
+ (job.source === "pick" ? picks : autos).push(job);
490
+ continue;
491
+ }
492
+ const job = jobs.get(event.id);
493
+ if (event.type === "remove") job.state = "removed";
494
+ if (event.type === "requeue") job.state = "queued";
495
+ if (event.type === "retry") {
496
+ job.state = "queued";
497
+ failures.set(job.id, 0);
498
+ }
499
+ if (event.type === "move") {
500
+ picks.splice(picks.indexOf(job), 1);
501
+ const before = picks.filter((pick) => pick.state === "queued")[event.index];
502
+ picks.splice(before ? picks.indexOf(before) : picks.length, 0, job);
503
+ }
504
+ if (event.type === "start") {
505
+ job.state = "running";
506
+ job.agent = event.agent;
507
+ }
508
+ if (event.type === "note") {
509
+ const { kind } = event.note;
510
+ const attempt = job.attempts.length + (kind === "answer" || kind === "train" ? 0 : 1);
511
+ job.notes.push({
512
+ ...event.note,
513
+ at: event.at,
514
+ attempt
515
+ });
516
+ if (kind === "answer") job.state = "queued";
517
+ }
518
+ if (event.type === "attempt") {
519
+ job.attempts.push(event.attempt);
520
+ const { outcome } = event.attempt;
521
+ if (job.notes.some((note) => note.kind === "ask" && note.attempt === job.attempts.length)) job.state = "blocked";
522
+ else if (outcome === "done") job.state = "done";
523
+ else if (outcome === "limited" || outcome === "stopped") job.state = "queued";
524
+ else {
525
+ const count = (failures.get(job.id) ?? 0) + 1;
526
+ failures.set(job.id, count);
527
+ job.state = count >= TRIES$1 ? "failed" : "queued";
528
+ }
529
+ }
530
+ }
531
+ for (const job of jobs.values()) {
532
+ const state = job.after && jobs.get(job.after).state;
533
+ if (job.state === "queued" && (state === "failed" || state === "removed")) job.state = "removed";
534
+ }
535
+ return [...picks, ...autos];
536
+ }
537
+ /** The next job this agent may take: queued for it, with the job it comes after done. */
538
+ function nextJob(jobs, agent) {
539
+ const done = (id) => !id || jobs.find((job) => job.id === id)?.state === "done";
540
+ return jobs.find((job) => job.state === "queued" && (job.agent ?? agent) === agent && done(job.after));
541
+ }
542
+ const ACTIVE = [
543
+ "queued",
544
+ "running",
545
+ "blocked"
546
+ ];
547
+ const sameWork = (item) => `${itemKey(item)} ${item.play} ${item.title}`;
548
+ /** Queues the items, skipping those already in the queue; returns the jobs it added. */
549
+ function addJobs(state, items, source, pin = {}) {
550
+ const at = (/* @__PURE__ */ new Date()).toISOString();
551
+ const active = new Set(readJobs(state).filter((job) => ACTIVE.includes(job.state)).map((job) => sameWork(job.item)));
552
+ return items.filter((item) => !active.has(sameWork(item))).map((item) => {
553
+ const job = {
554
+ id: randomBytes(4).toString("hex"),
555
+ item,
556
+ source,
557
+ ...pin
558
+ };
559
+ append(state, {
560
+ at,
561
+ type: "add",
562
+ job
563
+ });
564
+ return {
565
+ ...job,
566
+ added: at,
567
+ state: "queued",
568
+ attempts: [],
569
+ notes: []
570
+ };
571
+ });
572
+ }
573
+ /**
574
+ * Queues a job to rebase the job's PR and resolve its conflicts, unless one is already waiting. It
575
+ * keeps the job's workwork id, so the attempt links the same PR.
576
+ */
577
+ function queueConflicts(state, id, url, files) {
578
+ const job = readJobs(state).find((job) => job.id === id);
579
+ addJobs(state, [{
580
+ ...job.item,
581
+ play: "conflicts",
582
+ title: `Resolve conflicts: ${job.item.title}`
583
+ }], "pick", { prompt: conflictsPrompt(url, files) });
584
+ }
585
+ const conflictsPrompt = (url, files) => `Pull request ${url} conflicts with its base branch in:
586
+ ${files.map((file) => `- ${file}`).join("\n")}
587
+
588
+ 1. Check out its branch with \`gh pr checkout ${url}\`.
589
+ 2. Rebase it onto the freshly fetched base branch. Resolve each conflict so the intent of both sides survives; read the commits on both sides before choosing.
590
+ 3. Run the repo's checks and tests, and fix what the rebase broke.
591
+ 4. Push with \`git push --force-with-lease\`. Don't open a new pull request.
592
+
593
+ If a conflict can't be resolved without guessing what someone meant, don't push. Comment on the pull request with what's in the way instead.
594
+
595
+ End your reply with the pull request's URL.
596
+ `;
597
+ /**
598
+ * Queues a review of the job's PR by another agent, once the job is done. Like a conflicts job it
599
+ * keeps the job's workwork id, so it finds and links the same PR.
600
+ */
601
+ function queueReview(state, id, agent) {
602
+ const job = find(state, id, ...ACTIVE, "done");
603
+ if (job.agent === agent) throw new Error(`job ${id} is ${agent}'s own; pick another agent to review it`);
604
+ const branch = workworkBranch(job.item);
605
+ const item = {
606
+ ...job.item,
607
+ play: "review",
608
+ title: `Review: ${job.item.title}`
609
+ };
610
+ const prompt = reviewPrompt(branch, job.agent);
611
+ return addJobs(state, [item], "pick", {
612
+ agent,
613
+ prompt,
614
+ after: id
615
+ })[0];
616
+ }
617
+ const reviewPrompt = (branch, author = "another agent") => `Review the pull request ${author} opened from branch \`${branch}\`: \`gh pr view ${branch}\` and \`gh pr diff ${branch}\`.
618
+
619
+ 1. Check it out with \`gh pr checkout ${branch}\`, run the repo's checks and tests, and read the change against what its description says it does.
620
+ 2. Look for bugs, missed cases and changes nobody asked for. Skip style the linters already cover.
621
+ 3. Post what you found as one comment with \`gh pr comment ${branch} --body-file -\`: each finding with file, line and why it matters, or that you found nothing. Don't push, approve or merge.
622
+
623
+ If there's no such pull request, say so and end.
624
+
625
+ End your reply with the pull request's URL.
626
+ `;
627
+ /**
628
+ * Queues a task an agent reported as a follow-up of its job. Its own id, so the PR of the job it
629
+ * came from isn't taken for its own.
630
+ */
631
+ function queueFollowup(state, id, task) {
632
+ const job = find(state, id, ...ACTIVE, "done", "failed");
633
+ if (!job.notes.some((note) => note.followups?.includes(task))) throw new Error(`job ${id} reported no follow-up "${task}"`);
634
+ const item = {
635
+ ...job.item,
636
+ id: `${job.item.id}+followup`,
637
+ play: "followup",
638
+ title: task
639
+ };
640
+ const url = prUrl(job);
641
+ const prompt = `${task}
642
+
643
+ This came up while an agent worked on "${job.item.title}"${url ? ` (${url})` : ""}. Make it its own change on a new branch, and open a pull request for it.
644
+ `;
645
+ return addJobs(state, [item], "pick", { prompt })[0];
646
+ }
647
+ function find(state, id, ...states) {
648
+ const job = readJobs(state).find((job) => job.id === id);
649
+ if (!job) throw new Error(`no job ${id}`);
650
+ if (!states.includes(job.state)) throw new Error(`job ${id} is ${job.state}`);
651
+ return job;
652
+ }
653
+ /** Takes a job out of the queue or the results, and deletes the branches its attempts kept. */
654
+ async function removeJob(state, id) {
655
+ const job = find(state, id, "queued", "blocked", "done", "failed");
656
+ append(state, {
657
+ at: (/* @__PURE__ */ new Date()).toISOString(),
658
+ type: "remove",
659
+ id
660
+ });
661
+ const kept = job.attempts.flatMap((attempt) => attempt.branch ?? []);
662
+ if (kept.length === 0) return;
663
+ const branches = await output("git", [
664
+ "for-each-ref",
665
+ "--format=%(refname:short)",
666
+ "refs/heads/factory/"
667
+ ], job.item.repo);
668
+ const left = kept.filter((branch) => branches.split("\n").includes(branch));
669
+ if (left.length) await output("git", [
670
+ "branch",
671
+ "-D",
672
+ ...left
673
+ ], job.item.repo);
674
+ }
675
+ function retryJob(state, id) {
676
+ find(state, id, "failed");
677
+ append(state, {
678
+ at: (/* @__PURE__ */ new Date()).toISOString(),
679
+ type: "retry",
680
+ id
681
+ });
682
+ }
683
+ /** Moves a queued pick to index among the queued picks. */
684
+ function moveJob(state, id, index) {
685
+ if (find(state, id, "queued").source !== "pick") throw new Error(`job ${id} is not a pick`);
686
+ append(state, {
687
+ at: (/* @__PURE__ */ new Date()).toISOString(),
688
+ type: "move",
689
+ id,
690
+ index
691
+ });
692
+ }
693
+ /**
694
+ * An agent's note on the job it works, the user's answer to a blocked job, which queues it again,
695
+ * or what the merge train did with the job's PR.
696
+ */
697
+ function addNote(state, id, note) {
698
+ if (note.kind !== "train") find(state, id, note.kind === "answer" ? "blocked" : "running");
699
+ append(state, {
700
+ at: (/* @__PURE__ */ new Date()).toISOString(),
701
+ type: "note",
702
+ id,
703
+ note
704
+ });
705
+ }
706
+ function startJob(state, id, agent) {
707
+ append(state, {
708
+ at: (/* @__PURE__ */ new Date()).toISOString(),
709
+ type: "start",
710
+ id,
711
+ agent
712
+ });
713
+ }
714
+ function endJob(state, id, attempt) {
715
+ append(state, {
716
+ at: (/* @__PURE__ */ new Date()).toISOString(),
717
+ type: "attempt",
718
+ id,
719
+ attempt
720
+ });
721
+ }
722
+ /** A job whose run stopped before its agent started goes back to the queue, its agent kept. */
723
+ function requeueJob(state, id) {
724
+ append(state, {
725
+ at: (/* @__PURE__ */ new Date()).toISOString(),
726
+ type: "requeue",
727
+ id
728
+ });
729
+ }
151
730
  /** Cheapest attention first, and within a level one item per repo in turn so no repo takes the night. */
152
731
  function order(items, levels) {
153
732
  return LEVELS.filter((level) => levels.includes(level)).flatMap((level) => {
@@ -159,65 +738,76 @@ function order(items, levels) {
159
738
  return turns;
160
739
  });
161
740
  }
741
+ /** What auto mode would add next: wanted candidates that never had a job. */
742
+ function autoPicks(candidates, jobs, auto, count) {
743
+ const seen = new Set(jobs.map((job) => itemKey(job.item)));
744
+ return order(candidates.filter((item) => !seen.has(itemKey(item)) && (auto.plays.length === 0 || auto.plays.includes(item.play)) && (auto.repos.length === 0 || auto.repos.includes(item.repo))), auto.levels).slice(0, count);
745
+ }
162
746
  //#endregion
163
- //#region src/loop.ts
747
+ //#region src/backend/loop.ts
164
748
  const MINUTE = 6e4;
749
+ /** Auto mode keeps this many of its jobs queued per agent, so picks never drown in them. */
750
+ const AUTO_PER_AGENT = 5;
751
+ const STALE_CANDIDATES = 360 * MINUTE;
752
+ const livePath = (state, id) => join(state, "running", `${id}.json`);
165
753
  const URL$1 = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/(?:pull|issues)\/\d+/g;
166
- /** Runs workers until each has stopped; returns the run id. */
754
+ /** Works the queue until every agent is out of limits, until passes, or it's stopped; returns the run id. */
167
755
  async function run(options) {
756
+ const { state } = options;
168
757
  const id = (/* @__PURE__ */ new Date()).toISOString().slice(0, 19).replaceAll(":", "");
169
- const runDir = join(options.state, "runs", id);
758
+ const runDir = join(state, "runs", id);
170
759
  mkdirSync(runDir, { recursive: true });
171
- const queue = [];
172
- const claimed = /* @__PURE__ */ new Set();
173
- const children = /* @__PURE__ */ new Set();
760
+ mkdirSync(join(state, "running"), { recursive: true });
761
+ const agents = /* @__PURE__ */ new Set();
174
762
  const wakers = /* @__PURE__ */ new Set();
175
- const counts = {
176
- done: 0,
177
- failed: 0,
178
- limited: 0,
179
- timeout: 0
180
- };
181
- const workers = options.agents.map((agent) => ({
182
- agent: agent.name,
763
+ const workers = Object.entries(options.agents).map(([agent, tuning]) => ({
764
+ agent,
765
+ ...tuning,
183
766
  state: "idle",
184
767
  since: (/* @__PURE__ */ new Date()).toISOString(),
185
768
  limits: 0
186
769
  }));
187
- let started = 0;
188
770
  let stopping = false;
771
+ let killing = false;
772
+ let topping;
189
773
  function writeStatus() {
190
- const until = options.until && new Date(options.until).toISOString();
774
+ const until = options.until ? new Date(options.until).toISOString() : void 0;
775
+ const timeout = options.timeoutMs / MINUTE;
191
776
  const status = {
192
777
  pid: process.pid,
193
778
  run: id,
194
779
  until,
195
- workers,
196
- counts,
197
- queued: queue.length
780
+ limit: options.limit,
781
+ timeout,
782
+ workers
198
783
  };
199
- writeFileSync(join(options.state, "status.json"), `${JSON.stringify(status, null, 2)}\n`);
784
+ writeFileSync(join(state, "status.json"), `${JSON.stringify(status, null, 2)}\n`);
200
785
  }
201
786
  function set(worker, change) {
202
787
  Object.assign(worker, {
203
- item: void 0,
204
- until: void 0
788
+ job: void 0,
789
+ until: void 0,
790
+ reason: void 0
205
791
  }, change);
206
792
  worker.since = (/* @__PURE__ */ new Date()).toISOString();
207
793
  writeStatus();
208
794
  }
209
- function stop() {
795
+ /** Starts nothing new; agents keep working for the next run to finish, unless killed. */
796
+ function stop(kill) {
210
797
  stopping = true;
211
- for (const child of children) killGroup(child);
798
+ killing ||= kill;
799
+ if (kill) for (const pid of agents) killGroup(pid);
212
800
  for (const wake of wakers) wake();
213
801
  }
802
+ const handOff = () => stop(false);
803
+ const kill = () => stop(true);
804
+ const aborted = () => stop(options.signal?.reason === "kill");
214
805
  function ended() {
215
- if (stopping) return "stopped";
216
- if (options.until && Date.now() >= options.until) return "--until passed";
217
- if (options.maxItems && started >= options.maxItems) return "--max-items reached";
806
+ if (stopping) return "turned off";
807
+ if (options.until && Date.now() >= options.until) return "until passed";
218
808
  }
809
+ /** A wait that stopping cuts short. */
219
810
  function nap(ms) {
220
- if (options.sleep) return options.sleep(ms);
221
811
  return new Promise((resolve) => {
222
812
  const wake = () => {
223
813
  clearTimeout(timer);
@@ -228,205 +818,336 @@ async function run(options) {
228
818
  wakers.add(wake);
229
819
  });
230
820
  }
231
- function take(agent) {
232
- const { failedBy } = replay(readLedger(options.state));
233
- const index = queue.findIndex((item) => !failedBy.get(key(item))?.includes(agent));
234
- return index < 0 ? void 0 : queue.splice(index, 1)[0];
235
- }
236
- async function refill() {
237
- const candidates = JSON.parse(await output(options.workwork, ["--all", "--json"], process.cwd()));
238
- const { finished, failedBy } = replay(readLedger(options.state));
239
- const agents = workers.filter((worker) => worker.state !== "stopped").map((worker) => worker.agent);
240
- const known = /* @__PURE__ */ new Set([...queue.map(key), ...claimed]);
241
- const fresh = candidates.filter((item) => !finished.has(key(item)) && !known.has(key(item)) && agents.some((agent) => !failedBy.get(key(item))?.includes(agent)));
242
- queue.push(...order(fresh, options.levels));
243
- writeStatus();
821
+ /** Auto mode's part: keep a few of its jobs queued. Reads settings each time, so the toggle applies at once. */
822
+ function topUp() {
823
+ topping ??= fillFromAuto().catch((error) => log(`auto mode could not ask workwork: ${error.message}`)).finally(() => topping = void 0);
824
+ }
825
+ async function fillFromAuto() {
826
+ const { auto } = readSettings(state);
827
+ if (!auto.on) return;
828
+ const wanted = () => AUTO_PER_AGENT * workers.length - readJobs(state).filter((job) => job.source === "auto" && job.state === "queued").length;
829
+ if (wanted() <= 0) return;
830
+ const cached = readCandidates(state);
831
+ if (!cached || Date.now() - Date.parse(cached.at) > STALE_CANDIDATES) await refreshCandidates(state, options.workwork);
832
+ const candidates = readCandidates(state);
833
+ if (!candidates) return;
834
+ const added = addJobs(state, autoPicks(candidates.items, readJobs(state), auto, wanted()), "auto");
835
+ if (added.length) log(`auto mode queued ${added.length}`);
244
836
  }
245
- async function work(agent, worker) {
837
+ async function work(worker, handed) {
246
838
  let quickFailures = 0;
247
839
  while (!ended()) {
248
- const item = take(agent.name) ?? (await refill(), take(agent.name));
249
- if (!item) return set(worker, {
840
+ topUp();
841
+ let job;
842
+ let attempt;
843
+ if (handed) {
844
+ ({job} = handed);
845
+ set(worker, {
846
+ state: "working",
847
+ job: job.id
848
+ });
849
+ log(`${worker.agent} takes over ${job.id} from run ${handed.live.begun.run}`);
850
+ attempt = await finish(job, handed.live);
851
+ handed = void 0;
852
+ } else {
853
+ job = nextJob(readJobs(state), worker.agent);
854
+ if (!job) {
855
+ if (worker.state !== "idle") set(worker, { state: "idle" });
856
+ await nap(options.pollMs ?? 3e3);
857
+ continue;
858
+ }
859
+ startJob(state, job.id, worker.agent);
860
+ set(worker, {
861
+ state: "working",
862
+ job: job.id
863
+ });
864
+ log(`${worker.agent} starts ${job.id}: ${job.item.label} ${job.item.id}`);
865
+ attempt = await attemptJob(worker, job);
866
+ }
867
+ if (!attempt) {
868
+ if (!existsSync(livePath(state, job.id))) requeueJob(state, job.id);
869
+ break;
870
+ }
871
+ endJob(state, job.id, attempt);
872
+ rmSync(livePath(state, job.id), { force: true });
873
+ log(`${worker.agent} ${attempt.outcome} ${job.id} ${attempt.url ?? attempt.error ?? ""}`);
874
+ const seconds = (Date.parse(attempt.end) - Date.parse(attempt.start)) / 1e3;
875
+ quickFailures = attempt.outcome === "failed" && seconds < 60 ? quickFailures + 1 : 0;
876
+ if (quickFailures >= 3) return set(worker, {
250
877
  state: "stopped",
251
- reason: "nothing left to do"
878
+ reason: `3 failures in a row under a minute; last: ${attempt.error?.split("\n")[0] ?? "see its log"}`
252
879
  });
253
- started++;
254
- claimed.add(key(item));
255
- set(worker, {
256
- state: "working",
257
- item: `${item.label} ${item.id}`
258
- });
259
- log(`${agent.name} starts ${item.label} ${item.id}`);
260
- const entry = await attempt(agent, item);
261
- claimed.delete(key(item));
262
- if (!entry) break;
263
- appendLedger(options.state, entry);
264
- counts[entry.outcome]++;
265
- log(`${agent.name} ${entry.outcome} ${item.label} ${item.id} ${entry.url ?? entry.error ?? ""}`);
266
- const seconds = (Date.parse(entry.end) - Date.parse(entry.start)) / 1e3;
267
- quickFailures = entry.outcome === "failed" && !entry.error && seconds < 60 ? quickFailures + 1 : 0;
268
- if (entry.outcome === "limited") {
269
- started--;
270
- queue.unshift(item);
271
- }
272
- if (entry.outcome !== "limited" && quickFailures < 3) {
880
+ if (attempt.outcome !== "limited") {
273
881
  set(worker, { state: "idle" });
274
882
  continue;
275
883
  }
276
- quickFailures = 0;
277
884
  worker.limits++;
278
- if (worker.limits >= options.windows) return set(worker, {
885
+ if (options.limit !== null && worker.limits >= options.limit) return set(worker, {
279
886
  state: "stopped",
280
- reason: `limit ${worker.limits} of ${options.windows}`
887
+ reason: `limit ${worker.limits} of ${options.limit}`
281
888
  });
282
- const reset = entry.outcome === "limited" ? resetTime(readFileSync(entry.log, "utf8"), Date.now()) : void 0;
889
+ const reset = resetTime(readFileSync(attempt.log, "utf8"), Date.now());
283
890
  const wake = Math.min(reset === void 0 ? Date.now() + 30 * MINUTE : reset + 2 * MINUTE, options.until ?? Infinity);
284
891
  set(worker, {
285
892
  state: "sleeping",
286
893
  until: new Date(wake).toISOString()
287
894
  });
288
- log(`${agent.name} sleeps until ${new Date(wake).toISOString()}`);
289
- await nap(wake - Date.now());
895
+ log(`${worker.agent} hit limit ${worker.limits}, sleeps until ${new Date(wake).toISOString()}`);
896
+ await (options.sleep ?? nap)(wake - Date.now());
290
897
  }
291
898
  set(worker, {
292
899
  state: "stopped",
293
900
  reason: ended()
294
901
  });
295
902
  }
296
- /** One attempt at an item in a fresh worktree; undefined when the run was stopped meanwhile. */
297
- async function attempt(agent, item) {
298
- const slug = `${item.label}-${item.id}`.replace(/[^\w.-]+/g, "-");
903
+ /** One attempt in the agent's worktree for the repo; undefined when the run was stopped meanwhile. */
904
+ async function attemptJob(worker, job) {
905
+ const tuning = {
906
+ model: job.model ?? worker.model,
907
+ effort: job.effort ?? worker.effort
908
+ };
909
+ const agent$1 = agent(worker.agent, tuning);
910
+ const slug = `${job.id}-${job.attempts.length + 1}`;
299
911
  const dir = join(runDir, slug);
300
912
  mkdirSync(dir, { recursive: true });
301
913
  const logPath = join(dir, "agent.log");
302
- const worktree = join(options.state, "worktrees", id, slug);
303
- const start = (/* @__PURE__ */ new Date()).toISOString();
304
- const entry = (outcome, rest = {}) => ({
914
+ const repoKey = createHash("sha256").update(job.item.repo).digest("hex");
915
+ const worktree = join(state, "worktrees", agent$1.name, repoKey);
916
+ const begun = {
305
917
  run: id,
306
- id: item.id,
307
- repo: item.repo,
308
- play: item.play,
309
- level: item.level,
310
- agent: agent.name,
311
- start,
312
- end: (/* @__PURE__ */ new Date()).toISOString(),
313
- outcome,
314
- log: logPath,
315
- ...rest
316
- });
918
+ agent: agent$1.name,
919
+ ...tuning,
920
+ start: (/* @__PURE__ */ new Date()).toISOString(),
921
+ log: logPath
922
+ };
317
923
  let prompt;
318
924
  try {
319
- await output("git", [
320
- "fetch",
321
- "--quiet",
322
- "origin"
323
- ], item.repo);
324
- await output("git", [
325
- "worktree",
326
- "add",
327
- "--detach",
328
- worktree,
329
- (await output("git", [
330
- "symbolic-ref",
331
- "--short",
332
- "refs/remotes/origin/HEAD"
333
- ], item.repo)).trim()
334
- ], item.repo);
335
- prompt = await output(options.workwork, ["prompt", item.id], item.repo);
925
+ await checkout(worktree, job.item.repo);
926
+ prompt = job.prompt ?? await output(options.workwork, ["prompt", job.item.id], job.item.repo);
336
927
  } catch (error) {
337
- const kept = await settle(worktree, item.repo);
338
- return entry("failed", {
339
- error: error.message.trim(),
340
- worktree: kept ? worktree : void 0
341
- });
928
+ const message = error.message.trim();
929
+ writeFileSync(logPath, `${message}\n`);
930
+ return attempt(begun, "failed", { error: message.slice(0, 2e3) });
342
931
  }
343
- writeFileSync(join(dir, "prompt.md"), prompt);
344
- const { code, timedOut } = await spawnAgent(agent, prompt, worktree, logPath);
345
- const kept = await settle(worktree, item.repo);
932
+ writeFileSync(join(dir, "prompt.md"), prompt + earlier(job) + reporting(job, begun));
346
933
  if (stopping) return void 0;
347
- const text = readFileSync(logPath, "utf8");
348
- return entry(timedOut ? "timeout" : classify(agent, code, text), {
349
- url: text.match(URL$1)?.at(-1),
350
- worktree: kept ? worktree : void 0
934
+ const live = {
935
+ begun,
936
+ pid: startAgent(agent$1, worktree, dir, job.id),
937
+ worktree
938
+ };
939
+ writeFileSync(livePath(state, job.id), JSON.stringify(live));
940
+ return finish(job, live);
941
+ }
942
+ /** Waits for the agent, killing it at the timeout, and records what it did; undefined when the run hands it off. */
943
+ async function finish(job, { begun, pid, worktree }) {
944
+ const dir = dirname(begun.log);
945
+ const exit = join(dir, "exit");
946
+ const deadline = Date.parse(begun.start) + options.timeoutMs;
947
+ let timedOut = false;
948
+ agents.add(pid);
949
+ try {
950
+ while (!existsSync(exit) && alive(pid)) {
951
+ if (stopping && !killing) return void 0;
952
+ if (!timedOut && Date.now() >= deadline) {
953
+ timedOut = true;
954
+ killGroup(pid);
955
+ }
956
+ await nap(Math.max(0, Math.min(options.pollMs ?? 1e3, deadline - Date.now())));
957
+ }
958
+ } finally {
959
+ agents.delete(pid);
960
+ }
961
+ killGroup(pid);
962
+ const branch = await keepWork(worktree, `factory/${basename(dir)}`);
963
+ if (killing) return attempt(begun, "stopped", { branch });
964
+ const text = readFileSync(begun.log, "utf8");
965
+ const code = existsSync(exit) ? Number(readFileSync(exit, "utf8")) : 1;
966
+ const agent$2 = agent(begun.agent, begun);
967
+ const outcome = timedOut ? "timeout" : classify(agent$2, code, text);
968
+ const result = readJobs(state).find((other) => other.id === job.id).notes.findLast((note) => note.kind === "result" && note.attempt === job.attempts.length + 1);
969
+ return attempt(begun, outcome, {
970
+ url: outcome === "done" && await delivered(job.item) || result?.url || text.match(URL$1)?.at(-1),
971
+ branch
351
972
  });
352
973
  }
353
- function spawnAgent(agent, prompt, cwd, logPath) {
354
- return new Promise((resolve) => {
355
- const logFile = openSync(logPath, "w");
356
- const child = spawn(agent.command, agent.args, {
357
- cwd,
358
- detached: true,
359
- stdio: [
360
- "pipe",
361
- logFile,
362
- logFile
363
- ]
364
- });
365
- closeSync(logFile);
366
- children.add(child);
367
- let timedOut = false;
368
- const timer = setTimeout(() => {
369
- timedOut = true;
370
- killGroup(child);
371
- }, options.timeoutMs);
372
- const done = (code) => {
373
- clearTimeout(timer);
374
- children.delete(child);
375
- resolve({
376
- code,
377
- timedOut
378
- });
379
- };
380
- child.on("error", (error) => {
381
- appendFileSync(logPath, `factory: could not start ${agent.command}: ${error.message}\n`);
382
- done(127);
383
- });
384
- child.on("close", (code) => {
385
- killGroup(child);
386
- done(code ?? 1);
387
- });
388
- child.stdin.on("error", () => {});
389
- child.stdin.end(prompt);
974
+ /**
975
+ * Jobs the last run left running: those with a live agent go to this run's worker for that agent;
976
+ * the rest stopped before their agent started, so they go back to the queue.
977
+ */
978
+ const handed = /* @__PURE__ */ new Map();
979
+ for (const job of readJobs(state)) {
980
+ if (job.state !== "running") continue;
981
+ if (!existsSync(livePath(state, job.id))) {
982
+ requeueJob(state, job.id);
983
+ continue;
984
+ }
985
+ const live = JSON.parse(readFileSync(livePath(state, job.id), "utf8"));
986
+ handed.set(live.begun.agent, {
987
+ job,
988
+ live
390
989
  });
391
990
  }
392
- process.on("SIGTERM", stop);
393
- process.on("SIGINT", stop);
991
+ process.on("SIGTERM", handOff);
992
+ process.on("SIGINT", kill);
993
+ options.signal?.addEventListener("abort", aborted);
394
994
  writeStatus();
395
995
  try {
396
- await Promise.all(options.agents.map((agent, index) => work(agent, workers[index])));
996
+ await Promise.all(workers.map((worker) => work(worker, handed.get(worker.agent))));
397
997
  } catch (error) {
398
- stop();
998
+ kill();
399
999
  throw error;
400
1000
  } finally {
401
- process.off("SIGTERM", stop);
402
- process.off("SIGINT", stop);
1001
+ process.off("SIGTERM", handOff);
1002
+ process.off("SIGINT", kill);
1003
+ options.signal?.removeEventListener("abort", aborted);
1004
+ await topping;
403
1005
  writeStatus();
404
1006
  }
405
1007
  return id;
406
1008
  }
407
- /** Keeps a worktree holding unpushed commits or changes; removes it otherwise. Returns whether it was kept. */
408
- async function settle(worktree, repo) {
409
- if (!existsSync(worktree)) return false;
410
- const unpushed = await output("git", [
1009
+ const attempt = (begun, outcome, rest = {}) => ({
1010
+ ...begun,
1011
+ end: (/* @__PURE__ */ new Date()).toISOString(),
1012
+ outcome,
1013
+ ...rest
1014
+ });
1015
+ /**
1016
+ * The agent in its own process group, so a timeout or kill takes down everything it started, and
1017
+ * detached, so it outlives a run that hands it off. The shell in between reads the prompt from a file
1018
+ * and writes the exit code to one, both of which outlast this process. Returns the group's pid.
1019
+ */
1020
+ function startAgent(agent, cwd, dir, job) {
1021
+ const log = openSync(join(dir, "agent.log"), "w");
1022
+ const child = spawn("sh", [
1023
+ "-c",
1024
+ "dir=$1; shift; \"$@\" <\"$dir/prompt.md\"; echo $? >\"$dir/exit\"",
1025
+ "sh",
1026
+ dir,
1027
+ agent.command,
1028
+ ...agent.args
1029
+ ], {
1030
+ cwd,
1031
+ detached: true,
1032
+ stdio: [
1033
+ "ignore",
1034
+ log,
1035
+ log
1036
+ ],
1037
+ env: {
1038
+ ...process.env,
1039
+ FACTORY_JOB: job
1040
+ }
1041
+ });
1042
+ closeSync(log);
1043
+ child.unref();
1044
+ return child.pid;
1045
+ }
1046
+ const NOTE_LABEL = {
1047
+ note: "note",
1048
+ ask: "it asked",
1049
+ answer: "the user answered",
1050
+ result: "result",
1051
+ train: "merge train"
1052
+ };
1053
+ /** What earlier attempts said and kept, so a retry or an answered question picks up where they left off. */
1054
+ function earlier(job) {
1055
+ if (job.attempts.length === 0) return "";
1056
+ return `\n\n## Earlier attempts at this job\n${job.attempts.flatMap((attempt, i) => [`\nAttempt ${i + 1} (${attempt.agent}, ${attempt.outcome})${attempt.branch ? `: its work is kept on branch ${attempt.branch}; start from it with \`git checkout -B ${attempt.branch}\`` : ""}`, ...job.notes.filter((note) => note.attempt === i + 1).map((note) => `- ${NOTE_LABEL[note.kind]}: ${note.text}`)]).join("\n")}\n`;
1057
+ }
1058
+ /** How the agent reports back. Nobody watches a run, so this is all the user learns besides the PR. */
1059
+ function reporting(job, { agent, model, effort }) {
1060
+ const factory = `"${process.execPath}" "${process.argv[1]}"`;
1061
+ const signature = [
1062
+ agent,
1063
+ model,
1064
+ effort
1065
+ ].filter(Boolean).join(" · ");
1066
+ return `
1067
+ ---
1068
+ You run headless for factory as job ${job.id}, and nobody watches live. Report through its CLI:
1069
+
1070
+ - \`${factory} note "<text>"\` records something worth knowing later: what you found, tried, or what's in the way. A few per job, not a play-by-play.
1071
+ - Decide for yourself wherever a reasonable engineer would, and note the call you made so the user can revisit it. Asking parks the job until the user is back, often the next morning, so it's for the rare decision that's costly to get wrong and that you can't settle from the code, the docs or the task: deleting data, a public API change, two directions that would each waste the work of the other. Then run \`${factory} ask "<question, with the options and your recommendation>"\` and end there. Your work in this folder is kept, and the job goes on later with your notes, the answer and your work.
1072
+ - Before you end, run \`${factory} result "<what changed and why, in a sentence or two>" --confidence low|medium|high\`, adding \`--url <link>\` for the PR or issue you opened and \`--followup "<task>"\` for each task you saw that deserves its own job.
1073
+ - In a PR description you write, add the line \`Agent: ${signature}\`.
1074
+ `;
1075
+ }
1076
+ /** The PR the agent opened, as GitHub knows it; undefined when gh can't tell, and the log's last link stands in. */
1077
+ async function delivered(item) {
1078
+ try {
1079
+ return await findPr(item);
1080
+ } catch (error) {
1081
+ log(`gh can't find the PR for ${item.id}: ${error.message.trim().split("\n")[0]}`);
1082
+ return;
1083
+ }
1084
+ }
1085
+ /** The worktree at origin's fresh default branch; reused across jobs so installed dependencies survive. */
1086
+ async function checkout(worktree, repo) {
1087
+ await output("git", [
1088
+ "fetch",
1089
+ "--quiet",
1090
+ "origin"
1091
+ ], repo);
1092
+ const head = await output("git", [
1093
+ "ls-remote",
1094
+ "--symref",
1095
+ "origin",
1096
+ "HEAD"
1097
+ ], repo);
1098
+ const branch = /^ref: refs\/heads\/(\S+)\tHEAD$/m.exec(head)?.[1];
1099
+ if (!branch) throw new Error(`origin of ${repo} names no default branch`);
1100
+ const base = `origin/${branch}`;
1101
+ if (!existsSync(worktree)) {
1102
+ await output("git", ["worktree", "prune"], repo);
1103
+ await output("git", [
1104
+ "worktree",
1105
+ "add",
1106
+ "--quiet",
1107
+ "--detach",
1108
+ worktree,
1109
+ base
1110
+ ], repo);
1111
+ return;
1112
+ }
1113
+ await keepWork(worktree, `factory/leftover-${Date.now()}`, ["--remotes", "--branches"]);
1114
+ await output("git", [
1115
+ "checkout",
1116
+ "--quiet",
1117
+ "--force",
1118
+ "--detach",
1119
+ base
1120
+ ], worktree);
1121
+ await output("git", ["clean", "-fdq"], worktree);
1122
+ }
1123
+ /** Saves commits and changes that aren't on `saved` refs to a branch; returns its name, if there was any. */
1124
+ async function keepWork(worktree, branch, saved = ["--remotes"]) {
1125
+ if ((await output("git", ["status", "--porcelain"], worktree)).trim()) {
1126
+ await output("git", ["add", "-A"], worktree);
1127
+ await output("git", [
1128
+ "commit",
1129
+ "--quiet",
1130
+ "--no-verify",
1131
+ "-m",
1132
+ "factory: changes the agent left uncommitted"
1133
+ ], worktree);
1134
+ }
1135
+ if (!(await output("git", [
411
1136
  "log",
412
1137
  "--oneline",
413
1138
  "HEAD",
414
1139
  "--not",
415
- "--remotes"
416
- ], worktree);
417
- const changes = await output("git", ["status", "--porcelain"], worktree);
418
- if (unpushed.trim() || changes.trim()) return true;
1140
+ ...saved
1141
+ ], worktree)).trim()) return void 0;
419
1142
  await output("git", [
420
- "worktree",
421
- "remove",
1143
+ "branch",
422
1144
  "--force",
423
- worktree
424
- ], repo);
425
- return false;
1145
+ branch,
1146
+ "HEAD"
1147
+ ], worktree);
1148
+ return branch;
426
1149
  }
427
- function killGroup(child) {
428
- const pid = child.pid;
429
- if (pid === void 0) return;
1150
+ function killGroup(pid) {
430
1151
  for (const [signal, delay] of [["SIGTERM", 0], ["SIGKILL", 1e4]]) setTimeout(() => {
431
1152
  try {
432
1153
  process.kill(-pid, signal);
@@ -435,64 +1156,904 @@ function killGroup(child) {
435
1156
  }
436
1157
  }, delay).unref();
437
1158
  }
438
- async function output(command, args, cwd) {
439
- const { stdout, stderr } = await promisify(execFile)(command, args, {
440
- cwd,
441
- maxBuffer: 67108864
442
- });
443
- process.stderr.write(stderr);
444
- return stdout;
445
- }
446
1159
  function log(message) {
447
1160
  console.log(`${(/* @__PURE__ */ new Date()).toISOString()} ${message}`);
448
1161
  }
449
1162
  //#endregion
450
- //#region src/cli.ts
451
- const USAGE = `factory: works through workwork candidates with headless coding agents until the limits run out
1163
+ //#region src/backend/power.ts
1164
+ const logPath = (state) => join(state, "factory.log");
1165
+ /** `factory run <args>` in the background, outliving this process and whoever started it. */
1166
+ function turnOn(state, args) {
1167
+ const pid = runningPid(state);
1168
+ if (pid) throw new Error(`already on (pid ${pid})`);
1169
+ const log = openSync(logPath(state), "a");
1170
+ const child = spawn(process.execPath, [
1171
+ process.argv[1],
1172
+ "run",
1173
+ ...args
1174
+ ], {
1175
+ detached: true,
1176
+ stdio: [
1177
+ "ignore",
1178
+ log,
1179
+ log
1180
+ ]
1181
+ });
1182
+ child.unref();
1183
+ writeFileSync(pidPath(state), `${child.pid}\n`);
1184
+ return child.pid;
1185
+ }
1186
+ /**
1187
+ * Stops the run. Its agents keep working and the next run records what they did; with kill they get
1188
+ * SIGTERM, then SIGKILL after 10 seconds, and their jobs go back to the queue. Returns the pid it
1189
+ * stopped, if one was running.
1190
+ */
1191
+ async function turnOff(state, kill = false) {
1192
+ const pid = runningPid(state);
1193
+ if (!pid) return void 0;
1194
+ process.kill(pid, kill ? "SIGINT" : "SIGTERM");
1195
+ for (let waited = 0; alive(pid); waited++) {
1196
+ if (waited === 60) throw new Error(`pid ${pid} is still running after 30 seconds`);
1197
+ await new Promise((resolve) => setTimeout(resolve, 500));
1198
+ }
1199
+ rmSync(pidPath(state), { force: true });
1200
+ return pid;
1201
+ }
1202
+ //#endregion
1203
+ //#region src/backend/claude.ts
1204
+ const update = (event) => ({
1205
+ type: "message_update",
1206
+ assistantMessageEvent: event
1207
+ });
1208
+ function claudeChat(effort) {
1209
+ /** The reply being streamed, as Pi parts, and the index of the block streaming now. */
1210
+ let parts = [];
1211
+ let block = 0;
1212
+ /** Stop was clicked, so the run ending early isn't an error. */
1213
+ let aborted = false;
1214
+ return {
1215
+ /** What to write to Claude Code for one of Pi's commands, and what the page hears right away. */
1216
+ command(record) {
1217
+ if (record.type === "prompt") {
1218
+ aborted = false;
1219
+ return {
1220
+ write: [{
1221
+ type: "user",
1222
+ message: {
1223
+ role: "user",
1224
+ content: record.message
1225
+ }
1226
+ }],
1227
+ emit: [{ type: "agent_start" }]
1228
+ };
1229
+ }
1230
+ if (record.type === "abort") {
1231
+ aborted = true;
1232
+ return {
1233
+ write: [{
1234
+ type: "control_request",
1235
+ request_id: "abort",
1236
+ request: { subtype: "interrupt" }
1237
+ }],
1238
+ emit: []
1239
+ };
1240
+ }
1241
+ return {
1242
+ write: [],
1243
+ emit: []
1244
+ };
1245
+ },
1246
+ record(record) {
1247
+ if (record.parent_tool_use_id) return [];
1248
+ switch (record.type) {
1249
+ case "system":
1250
+ if (record.subtype !== "init") return [];
1251
+ return [{
1252
+ type: "response",
1253
+ command: "get_state",
1254
+ success: true,
1255
+ data: {
1256
+ model: { name: record.model },
1257
+ thinkingLevel: effort ?? "default"
1258
+ }
1259
+ }];
1260
+ case "stream_event": return stream(record.event);
1261
+ case "assistant": {
1262
+ const out = [];
1263
+ for (const each of record.message.content) {
1264
+ const piece = part(each);
1265
+ if (piece.type === "toolCall") out.push(update({
1266
+ type: "toolcall_end",
1267
+ contentIndex: block,
1268
+ toolCall: piece
1269
+ }));
1270
+ while (parts.length <= block) parts.push({ type: "thinking" });
1271
+ parts[block] = piece;
1272
+ }
1273
+ return out;
1274
+ }
1275
+ case "user": return user(record.message.content).flatMap((message) => [{
1276
+ type: "message_start",
1277
+ message
1278
+ }, {
1279
+ type: "message_end",
1280
+ message
1281
+ }]);
1282
+ case "result": {
1283
+ const settled = { type: "agent_settled" };
1284
+ if (!record.is_error || aborted) return [settled];
1285
+ return [{
1286
+ type: "response",
1287
+ command: "prompt",
1288
+ success: false,
1289
+ error: record.result ?? record.errors?.join("; ") ?? "Claude Code failed"
1290
+ }, settled];
1291
+ }
1292
+ default: return [];
1293
+ }
1294
+ }
1295
+ };
1296
+ /** Pi's stream events for one of the Messages API's. */
1297
+ function stream(event) {
1298
+ const contentIndex = event.index;
1299
+ switch (event.type) {
1300
+ case "message_start":
1301
+ parts = [];
1302
+ block = 0;
1303
+ return [{
1304
+ type: "message_start",
1305
+ message: {
1306
+ role: "assistant",
1307
+ content: []
1308
+ }
1309
+ }];
1310
+ case "content_block_start": {
1311
+ block = contentIndex ?? 0;
1312
+ const started = event.content_block;
1313
+ if (started.type === "text") return [update({
1314
+ type: "text_start",
1315
+ contentIndex
1316
+ })];
1317
+ if (started.type === "thinking") return [update({
1318
+ type: "thinking_start",
1319
+ contentIndex
1320
+ })];
1321
+ if (started.type === "tool_use" || started.type === "server_tool_use") return [update({
1322
+ type: "toolcall_start",
1323
+ contentIndex,
1324
+ id: started.id,
1325
+ toolName: toolName(started.name)
1326
+ })];
1327
+ return [];
1328
+ }
1329
+ case "content_block_delta":
1330
+ if (event.delta?.type !== "text_delta") return [];
1331
+ return [update({
1332
+ type: "text_delta",
1333
+ contentIndex,
1334
+ delta: event.delta.text
1335
+ })];
1336
+ case "message_stop": {
1337
+ const content = parts;
1338
+ parts = [];
1339
+ return [{
1340
+ type: "message_end",
1341
+ message: {
1342
+ role: "assistant",
1343
+ content
1344
+ }
1345
+ }];
1346
+ }
1347
+ default: return [];
1348
+ }
1349
+ }
1350
+ }
1351
+ /** One block of an assistant message as a Pi part. */
1352
+ function part(block) {
1353
+ if (block.type === "text") return {
1354
+ type: "text",
1355
+ text: block.text ?? ""
1356
+ };
1357
+ if (block.type === "tool_use" || block.type === "server_tool_use") {
1358
+ const input = block.input ?? {};
1359
+ const path = input.file_path ?? input.notebook_path;
1360
+ return {
1361
+ type: "toolCall",
1362
+ id: block.id,
1363
+ name: toolName(block.name),
1364
+ arguments: path === void 0 ? input : {
1365
+ ...input,
1366
+ path
1367
+ }
1368
+ };
1369
+ }
1370
+ return { type: "thinking" };
1371
+ }
1372
+ /** Claude Code's tools by the names the page shows steps for. */
1373
+ const TOOLS = {
1374
+ Bash: "bash",
1375
+ Read: "read",
1376
+ Edit: "edit",
1377
+ MultiEdit: "edit",
1378
+ NotebookEdit: "edit",
1379
+ Write: "write",
1380
+ Grep: "grep",
1381
+ Glob: "find"
1382
+ };
1383
+ const toolName = (name) => TOOLS[name] ?? name;
1384
+ /** A user message as Pi messages: the prompt, or the results of the tools the reply called. */
1385
+ function user(content) {
1386
+ if (typeof content === "string") return [{
1387
+ role: "user",
1388
+ content
1389
+ }];
1390
+ return content.filter((block) => block.type === "tool_result").map((result) => ({
1391
+ role: "toolResult",
1392
+ toolCallId: result.tool_use_id,
1393
+ content: [{
1394
+ type: "text",
1395
+ text: typeof result.content === "string" ? result.content : (result.content ?? []).flatMap((block) => block.text ?? []).join("\n")
1396
+ }],
1397
+ isError: result.is_error === true
1398
+ }));
1399
+ }
1400
+ //#endregion
1401
+ //#region src/backend/chat.ts
1402
+ /** Pi speaks the page's protocol already. */
1403
+ const pi = {
1404
+ command: (record) => ({
1405
+ write: [record],
1406
+ emit: []
1407
+ }),
1408
+ record: (record) => [record]
1409
+ };
1410
+ /**
1411
+ * One chat for planning the queue, shared by every open page, with the agent the settings name.
1412
+ * The page reads Pi's RPC records (see Pi's docs/rpc.md), whichever agent replies. The conversation
1413
+ * lasts until reset, and a page that opens later gets it replayed. It survives a restart of serve:
1414
+ * the agent keeps its session (Pi's in chat-sessions/, Claude Code's in its own folder) and the page's
1415
+ * records are in chat.jsonl.
1416
+ */
1417
+ function chat(state) {
1418
+ const savedPath = join(state, "chat.jsonl");
1419
+ const conversationPath = join(state, "chat.json");
1420
+ let session;
1421
+ const pages = /* @__PURE__ */ new Set();
1422
+ /** The agent session this chat continues; `prompted` once the agent has one to resume. */
1423
+ let conversation = existsSync(conversationPath) ? JSON.parse(readFileSync(conversationPath, "utf8")) : void 0;
1424
+ /** Every record of this conversation, minus the deltas of replies that have ended. */
1425
+ let log = existsSync(savedPath) ? readFileSync(savedPath, "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [];
1426
+ if (log.length > 0) log.push({ type: "exit" });
1427
+ function emit(record) {
1428
+ if (record.type === "message_end") log = log.filter((each) => each.type !== "message_update");
1429
+ log.push(record);
1430
+ if (record.type !== "message_update") appendFileSync(savedPath, `${JSON.stringify(record)}\n`);
1431
+ for (const page of pages) page.write(`data: ${JSON.stringify(record)}\n\n`);
1432
+ }
1433
+ function save(change) {
1434
+ conversation = change;
1435
+ writeFileSync(conversationPath, `${JSON.stringify(conversation)}\n`);
1436
+ }
1437
+ function start() {
1438
+ const { agent, ...tuning } = readSettings(state).chat;
1439
+ if (conversation?.agent !== agent) save({
1440
+ agent,
1441
+ id: randomUUID(),
1442
+ prompted: false
1443
+ });
1444
+ const { id, prompted } = conversation;
1445
+ const { command, args } = chatAgent(agent, tuning, context(), {
1446
+ id,
1447
+ resume: prompted,
1448
+ folder: join(state, "chat-sessions")
1449
+ });
1450
+ const protocol = agent === "claude" ? claudeChat(tuning.effort) : pi;
1451
+ const child = spawn(command, args, { cwd: state });
1452
+ createInterface({ input: child.stdout }).on("line", (line) => {
1453
+ if (line.startsWith("{") && session?.child === child) for (const record of protocol.record(JSON.parse(line))) emit(record);
1454
+ });
1455
+ child.stdin.on("error", () => {});
1456
+ let stderr = "";
1457
+ child.stderr.on("data", (data) => stderr = (stderr + data).slice(-2e3));
1458
+ child.on("error", (error) => {
1459
+ if (session?.child === child) session = void 0;
1460
+ emit({
1461
+ type: "exit",
1462
+ error: `Can't start ${command}: ${error.message}`
1463
+ });
1464
+ });
1465
+ child.on("exit", (code) => {
1466
+ if (session?.child !== child) return;
1467
+ session = void 0;
1468
+ emit({
1469
+ type: "exit",
1470
+ error: code ? stderr.trim() || `${command} exited with code ${code}` : void 0
1471
+ });
1472
+ });
1473
+ session = {
1474
+ child,
1475
+ protocol
1476
+ };
1477
+ send({ type: "get_state" });
1478
+ }
1479
+ function send(record) {
1480
+ if (!session) start();
1481
+ const { write, emit: heard } = session.protocol.command(record);
1482
+ for (const each of write) session.child.stdin.write(`${JSON.stringify(each)}\n`);
1483
+ for (const each of heard) emit(each);
1484
+ }
1485
+ return {
1486
+ /** Streams records to a page, starting with the conversation so far. */
1487
+ listen(response) {
1488
+ response.writeHead(200, {
1489
+ "content-type": "text/event-stream",
1490
+ "cache-control": "no-store"
1491
+ });
1492
+ response.write(": connected\n\n");
1493
+ for (const record of log) response.write(`data: ${JSON.stringify(record)}\n\n`);
1494
+ pages.add(response);
1495
+ response.on("close", () => pages.delete(response));
1496
+ },
1497
+ prompt(message) {
1498
+ send({
1499
+ type: "prompt",
1500
+ message
1501
+ });
1502
+ if (!conversation.prompted) save({
1503
+ ...conversation,
1504
+ prompted: true
1505
+ });
1506
+ },
1507
+ abort: () => session && send({ type: "abort" }),
1508
+ /** Answers a question from one of Pi's extensions, which Pi waits on; every page closes it. */
1509
+ answer(reply) {
1510
+ if (!session) return;
1511
+ send({
1512
+ type: "extension_ui_response",
1513
+ ...reply
1514
+ });
1515
+ emit({
1516
+ type: "extension_ui_answered",
1517
+ id: reply.id
1518
+ });
1519
+ },
1520
+ reset() {
1521
+ session?.child.stdin.end();
1522
+ session = void 0;
1523
+ for (const page of pages) page.write(`data: ${JSON.stringify({ type: "reset" })}\n\n`);
1524
+ log = [];
1525
+ rmSync(savedPath, { force: true });
1526
+ rmSync(conversationPath, { force: true });
1527
+ conversation = void 0;
1528
+ }
1529
+ };
1530
+ }
1531
+ function context() {
1532
+ const factory = `"${process.execPath}" "${process.argv[1]}"`;
1533
+ return `You run inside the web page of factory, which works a queue of workwork candidates with headless coding agents, often overnight. You help the user decide what to put in the queue.
1534
+
1535
+ - The current folder is factory's state. candidates.json holds every repo's candidates from workwork ({ at, items: [{ repo, label, id, play, level, title }] }); jobs.jsonl is the queue and results, one event per line. runs/ holds each attempt's prompt.md and agent.log.
1536
+ - \`${factory} status\` shows the queue and \`${factory} report --all\` past results. \`workwork prompt <id>\`, run in the candidate's repo, shows the full task.
1537
+ - To queue candidates: \`${factory} add <id>... --repo <repo>\`, optionally with \`--agent ${AGENT_NAMES.join("|")}\`. Picked jobs go ahead of auto ones.
1538
+ - \`--after <job>\` holds a job until that one is done. \`${factory} review <job> --agent <name>\` queues a review of a job's PR by another agent than the one that wrote it.
1539
+ - Levels: auto needs no review, skim a quick look, decide needs the user's judgment. Prefer a few that fit together over many that touch the same files, since those conflict when merged.
1540
+
1541
+ Propose what to queue and why, briefly, and add jobs only once the user agrees. Never start, stop or run the factory, never change files or git state, and never merge or close PRs: the user does those from the page.`;
1542
+ }
1543
+ //#endregion
1544
+ //#region src/backend/repos.ts
1545
+ /** Where workwork --all looks for repos, with the same fallback. */
1546
+ const SRC = process.env.SRC ?? process.cwd();
1547
+ /**
1548
+ * The GitHub user's own repos (not forked or archived) that aren't cloned anywhere under $SRC
1549
+ * yet, newest first.
1550
+ */
1551
+ async function clonableRepos() {
1552
+ const listed = JSON.parse(await output("gh", [
1553
+ "repo",
1554
+ "list",
1555
+ "--source",
1556
+ "--no-archived",
1557
+ "--limit",
1558
+ "5000",
1559
+ "--json",
1560
+ "nameWithOwner,description,createdAt"
1561
+ ], SRC));
1562
+ const local = findRepos(SRC, 4);
1563
+ const cloned = new Set(await Promise.all(local.map(originName)));
1564
+ const repos = listed.filter((repo) => !cloned.has(repo.nameWithOwner.toLowerCase())).map((repo) => ({
1565
+ name: repo.nameWithOwner,
1566
+ description: repo.description,
1567
+ createdAt: repo.createdAt
1568
+ })).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
1569
+ return {
1570
+ root: SRC,
1571
+ repos
1572
+ };
1573
+ }
1574
+ /** Clones `name` (owner/repo) to $SRC/<repo> and returns that path. */
1575
+ async function cloneRepo(name) {
1576
+ if (!/^[\w.-]+\/[\w.-]+$/.test(name)) throw new Error(`${name} isn't a GitHub owner/repo`);
1577
+ const path = join(SRC, name.split("/")[1]);
1578
+ if (existsSync(path)) throw new Error(`${path} already exists`);
1579
+ await output("gh", [
1580
+ "repo",
1581
+ "clone",
1582
+ name,
1583
+ path
1584
+ ], SRC);
1585
+ return path;
1586
+ }
1587
+ /** Repos under `dir`, searched the way workwork --all does. */
1588
+ function findRepos(dir, depth) {
1589
+ if (existsSync(join(dir, ".git"))) return [dir];
1590
+ if (depth === 0) return [];
1591
+ return readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").flatMap((entry) => findRepos(join(dir, entry.name), depth - 1));
1592
+ }
1593
+ /** owner/repo of the GitHub origin, lowercased; empty when there is none. */
1594
+ async function originName(repo) {
1595
+ const url = await output("git", [
1596
+ "remote",
1597
+ "get-url",
1598
+ "origin"
1599
+ ], repo).catch(() => "");
1600
+ return /github\.com[:/](.+?)(?:\.git)?\/?$/.exec(url.trim())?.[1].toLowerCase() ?? "";
1601
+ }
1602
+ //#endregion
1603
+ //#region src/backend/models.ts
1604
+ /** Every model each agent offers, its short list first. */
1605
+ function agentModels(name) {
1606
+ if (name === "pi") return piModels();
1607
+ if (name === "claude") return claudeModels();
1608
+ throw new Error(`unknown agent ${name}`);
1609
+ }
1610
+ const PI_LEVELS = [
1611
+ "off",
1612
+ "minimal",
1613
+ "low",
1614
+ "medium",
1615
+ "high",
1616
+ "xhigh",
1617
+ "max"
1618
+ ];
1619
+ /** Pi's scoped models (Ctrl+P in Pi, `enabledModels` in its settings) first, then all it knows. */
1620
+ async function piModels() {
1621
+ const settings = join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "settings.json");
1622
+ const scoped = existsSync(settings) ? JSON.parse(readFileSync(settings, "utf8")).enabledModels ?? [] : [];
1623
+ const known = (await ask("pi", [
1624
+ "--mode",
1625
+ "rpc",
1626
+ "--no-session",
1627
+ "--offline"
1628
+ ], { type: "get_available_models" }, (record) => record.type === "response" && record.command === "get_available_models")).data.models;
1629
+ const scope = new Set(scoped.flatMap((each) => matches(known, each)));
1630
+ const rest = known.filter((model) => !scope.has(model));
1631
+ return [...scope, ...rest].map((model) => ({
1632
+ value: `${model.provider}/${model.id}`,
1633
+ label: model.name,
1634
+ efforts: piLevels(model),
1635
+ scoped: scope.has(model)
1636
+ }));
1637
+ }
1638
+ function matches(known, pattern) {
1639
+ const glob = new RegExp(`^${pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replaceAll("*", ".*")}$`, "i");
1640
+ const full = known.filter((model) => glob.test(`${model.provider}/${model.id}`));
1641
+ return full.length > 0 ? full : known.filter((model) => glob.test(model.id));
1642
+ }
1643
+ /** Pi's own rule (pi-ai's getSupportedThinkingLevels): null rules a level out, xhigh and max must be named. */
1644
+ function piLevels({ reasoning, thinkingLevelMap: map = {} }) {
1645
+ if (!reasoning) return ["off"];
1646
+ return PI_LEVELS.filter((level) => map[level] === null ? false : level === "xhigh" || level === "max" ? level in map : true);
1647
+ }
1648
+ /**
1649
+ * Claude Code's current models, as it tells a host that starts it. Its aliases (opus, sonnet, fable,
1650
+ * haiku) are the current ones; full ids like claude-opus-4-8 are older.
1651
+ */
1652
+ async function claudeModels() {
1653
+ const answer = await ask("claude", [
1654
+ "-p",
1655
+ "--input-format",
1656
+ "stream-json",
1657
+ "--output-format",
1658
+ "stream-json",
1659
+ "--verbose"
1660
+ ], {
1661
+ type: "control_request",
1662
+ request_id: "models",
1663
+ request: { subtype: "initialize" }
1664
+ }, (record) => record.type === "control_response");
1665
+ if (answer.response.subtype !== "success") throw new Error(answer.response.error);
1666
+ return answer.response.response.models.filter((model) => model.value !== "default" && !model.value.startsWith("claude-")).map((model) => ({
1667
+ value: model.value,
1668
+ label: model.displayName,
1669
+ efforts: model.supportsEffort ? model.supportedEffortLevels ?? [] : [],
1670
+ scoped: true
1671
+ }));
1672
+ }
1673
+ /** Starts an agent, sends it one request on stdin, and resolves with the record that answers it. */
1674
+ function ask(command, args, request, answers) {
1675
+ const child = spawn(command, args, { cwd: homedir() });
1676
+ child.stdin.end(`${JSON.stringify(request)}\n`);
1677
+ return new Promise((resolve, reject) => {
1678
+ child.on("error", reject);
1679
+ child.on("exit", (code) => reject(/* @__PURE__ */ new Error(`${command} exited with code ${code} before answering`)));
1680
+ createInterface({ input: child.stdout }).on("line", (line) => {
1681
+ if (!line.startsWith("{")) return;
1682
+ const record = JSON.parse(line);
1683
+ if (!answers(record)) return;
1684
+ resolve(record);
1685
+ child.kill();
1686
+ });
1687
+ });
1688
+ }
1689
+ //#endregion
1690
+ //#region src/backend/train.ts
1691
+ const POLL = 1e4;
1692
+ const PATIENCE = 18e5;
1693
+ /** A PR gets this many tries at rebase-then-merge before the train gives up on it. */
1694
+ const TRIES = 3;
1695
+ /**
1696
+ * Merges PRs one after another per repo, since each merge moves the base under the next one.
1697
+ * Repos go in parallel. A PR that conflicts is rebased; one that can't be is skipped with the reason,
1698
+ * and when git stopped on conflicts, handed to `onConflicts` to queue for an agent. `onEnd` hears
1699
+ * how each PR's ride ended.
1700
+ */
1701
+ function mergeTrain(prs, onConflicts, onEnd) {
1702
+ const cars = /* @__PURE__ */ new Map();
1703
+ /** Each repo's last PR on the train; a new one waits for it, even from a later start. */
1704
+ const tracks = /* @__PURE__ */ new Map();
1705
+ /** GitHub's answer once mergeability is known and checks have finished. */
1706
+ async function settled(id, url) {
1707
+ const deadline = Date.now() + PATIENCE;
1708
+ for (;;) {
1709
+ const pr = await prs.fresh(url);
1710
+ if (pr.state !== "OPEN" || pr.conflicts !== null && pr.checks !== "pending") return pr;
1711
+ if (Date.now() > deadline) throw new Error("checks still running after 30 minutes");
1712
+ cars.set(id, { step: "waiting" });
1713
+ await new Promise((resolve) => setTimeout(resolve, POLL));
1714
+ }
1715
+ }
1716
+ async function land(id, url) {
1717
+ for (let tries = 1;; tries++) {
1718
+ const pr = await settled(id, url);
1719
+ if (pr.state !== "OPEN") throw new Error(`already ${pr.state.toLowerCase()}`);
1720
+ if (pr.conflicts) {
1721
+ if (pr.fork) throw new Error("conflicts in a fork");
1722
+ } else {
1723
+ if (!canMerge(pr)) throw new Error(blocker(pr));
1724
+ cars.set(id, { step: "merging" });
1725
+ try {
1726
+ await mergePr(url);
1727
+ await prs.fresh(url);
1728
+ return;
1729
+ } catch (error) {
1730
+ if (tries >= TRIES || pr.fork) throw error;
1731
+ }
1732
+ }
1733
+ if (tries >= TRIES) throw new Error(`still conflicting after ${TRIES} rebases`);
1734
+ cars.set(id, { step: "rebasing" });
1735
+ await rebasePr(url);
1736
+ }
1737
+ }
1738
+ return {
1739
+ cars: () => Object.fromEntries(cars),
1740
+ /** Smallest diffs first, so the ones most likely to clash merge last. */
1741
+ start(jobs) {
1742
+ const boarding = jobs.filter(({ id }) => !onTrain(cars.get(id)));
1743
+ const known = prs.get(boarding.map(({ url }) => url));
1744
+ const size = (url) => (known[url]?.additions ?? 0) + (known[url]?.deletions ?? 0);
1745
+ for (const { id, url } of boarding.toSorted((a, b) => size(a.url) - size(b.url))) {
1746
+ cars.set(id, { step: "queued" });
1747
+ const repo = url.replace(/\/pull\/\d+$/, "");
1748
+ const track = (tracks.get(repo) ?? Promise.resolve()).then(() => land(id, url)).then(() => {
1749
+ cars.set(id, { step: "merged" });
1750
+ onEnd(id, "merged");
1751
+ }, (error) => {
1752
+ let reason = error.message;
1753
+ if (error instanceof Conflicts) {
1754
+ onConflicts(id, url, error.files);
1755
+ reason = `conflicts in ${error.files.join(", ")}; a job to resolve them is queued`;
1756
+ }
1757
+ cars.set(id, {
1758
+ step: "skipped",
1759
+ reason
1760
+ });
1761
+ onEnd(id, `skipped: ${reason}`);
1762
+ });
1763
+ tracks.set(repo, track);
1764
+ }
1765
+ }
1766
+ };
1767
+ }
1768
+ function blocker(pr) {
1769
+ if (pr.draft) return "draft";
1770
+ if (pr.checks === "failing") return "checks failing";
1771
+ return "not ready to merge";
1772
+ }
1773
+ //#endregion
1774
+ //#region src/backend/web.ts
1775
+ /** The built page; under pn dev, Vite serves it instead and proxies /api and /runs here. */
1776
+ const WEB = fileURLToPath(new URL("./web", import.meta.url));
1777
+ const TYPES = {
1778
+ ".html": "text/html; charset=utf-8",
1779
+ ".js": "text/javascript",
1780
+ ".css": "text/css",
1781
+ ".svg": "image/svg+xml",
1782
+ ".woff2": "font/woff2"
1783
+ };
1784
+ /** The page and the API it uses: the same state and commands as the CLI, nothing more. */
1785
+ function serve(state, port, host) {
1786
+ const prs = prCache();
1787
+ const train = mergeTrain(prs, (id, url, files) => queueConflicts(state, id, url, files), (id, text) => addNote(state, id, {
1788
+ kind: "train",
1789
+ text
1790
+ }));
1791
+ const planner = chat(state);
1792
+ const models = /* @__PURE__ */ new Map();
1793
+ function modelsOf(name) {
1794
+ if (!models.has(name)) models.set(name, agentModels(name).catch((error) => {
1795
+ console.error(`factory: can't list ${name}'s models: ${error.message}`);
1796
+ models.delete(name);
1797
+ return [];
1798
+ }));
1799
+ return models.get(name);
1800
+ }
1801
+ /** Only cached candidates, so the page can't queue or run workwork for anything it names. */
1802
+ function candidates(wanted) {
1803
+ const cached = new Map(readCandidates(state)?.items.map((item) => [itemKey(item), item]));
1804
+ return wanted.map((each) => {
1805
+ const item = cached.get(itemKey(each));
1806
+ if (!item) throw new Error(`no candidate ${each.id} in ${each.repo}`);
1807
+ return item;
1808
+ });
1809
+ }
1810
+ function jobPr(id) {
1811
+ const job = readJobs(state).find((job) => job.id === id);
1812
+ const url = job && prUrl(job);
1813
+ if (!url) throw new Error(`job ${id} has no PR`);
1814
+ return url;
1815
+ }
1816
+ /** The job's PR, checked with GitHub just now. */
1817
+ async function openPr(id) {
1818
+ const url = jobPr(id);
1819
+ const pr = await prs.fresh(url);
1820
+ if (pr.state !== "OPEN") throw new Error(`${url} is already ${pr.state.toLowerCase()}`);
1821
+ return {
1822
+ url,
1823
+ pr
1824
+ };
1825
+ }
1826
+ const routes = {
1827
+ "GET /api/state": () => snapshot(state, (urls) => prs.get(urls), train.cars()),
1828
+ "GET /api/candidates": () => readCandidates(state) ?? {
1829
+ at: null,
1830
+ items: []
1831
+ },
1832
+ "POST /api/candidates/refresh": () => {
1833
+ refreshCandidates(state, "workwork").catch((error) => console.error(`factory: workwork failed: ${error.message}`));
1834
+ },
1835
+ "GET /api/repos": () => clonableRepos(),
1836
+ "POST /api/repos/clone": async (body) => {
1837
+ await cloneRepo(body.name);
1838
+ refreshCandidates(state, "workwork").catch((error) => console.error(`factory: workwork failed: ${error.message}`));
1839
+ },
1840
+ "GET /api/plays": async () => JSON.parse(await output("workwork", ["plays", "--json"], process.cwd())),
1841
+ "POST /api/candidates/prompt": (body) => {
1842
+ const [item] = candidates([body]);
1843
+ return output("workwork", ["prompt", item.id], item.repo);
1844
+ },
1845
+ "POST /api/jobs": (body) => addJobs(state, candidates(body.items), "pick", body.pin),
1846
+ "POST /api/jobs/remove": (_, id) => removeJob(state, id),
1847
+ "POST /api/jobs/retry": (_, id) => retryJob(state, id),
1848
+ "POST /api/jobs/answer": (body, id) => addNote(state, id, {
1849
+ kind: "answer",
1850
+ text: body.text
1851
+ }),
1852
+ "POST /api/jobs/followup": (body, id) => queueFollowup(state, id, body.task),
1853
+ "POST /api/jobs/review": (body, id) => queueReview(state, id, body.agent),
1854
+ "POST /api/jobs/move": (body, id) => moveJob(state, id, body.index),
1855
+ "GET /api/jobs/pr": (_, id) => readPrDetails(jobPr(id)),
1856
+ "POST /api/jobs/merge": async (_, id) => {
1857
+ const { url, pr } = await openPr(id);
1858
+ if (!canMerge(pr)) throw new Error(`${url} isn't ready to merge: see it on GitHub`);
1859
+ await mergePr(url);
1860
+ await prs.fresh(url);
1861
+ },
1862
+ "POST /api/jobs/rebase": async (_, id) => {
1863
+ const { url, pr } = await openPr(id);
1864
+ if (!canRebase(pr)) throw new Error(`${url} isn't ready to rebase: see it on GitHub`);
1865
+ await rebasePr(url);
1866
+ await prs.fresh(url);
1867
+ },
1868
+ "POST /api/train": (body) => train.start(body.ids.map((id) => ({
1869
+ id,
1870
+ url: jobPr(id)
1871
+ }))),
1872
+ "POST /api/chat": (body) => planner.prompt(body.message),
1873
+ "POST /api/chat/abort": () => planner.abort(),
1874
+ "POST /api/chat/answer": (body) => planner.answer(body),
1875
+ "POST /api/chat/reset": () => planner.reset(),
1876
+ "POST /api/jobs/close": async (_, id) => {
1877
+ const { url } = await openPr(id);
1878
+ await closePr(url);
1879
+ await prs.fresh(url);
1880
+ },
1881
+ "GET /api/models": async () => Object.fromEntries(await Promise.all(AGENT_NAMES.map(async (name) => [name, await modelsOf(name)]))),
1882
+ "PUT /api/settings": (body) => {
1883
+ const before = JSON.stringify(readSettings(state).chat);
1884
+ writeSettings(state, checkSettings(body));
1885
+ if (JSON.stringify(body.chat) !== before) planner.reset();
1886
+ },
1887
+ "POST /api/on": (body) => {
1888
+ checkSettings({
1889
+ ...readSettings(state),
1890
+ ...body
1891
+ });
1892
+ return turnOn(state, runArgs(body));
1893
+ },
1894
+ "POST /api/off": () => turnOff(state)
1895
+ };
1896
+ return createServer(async (request, response) => {
1897
+ const path = new URL(request.url ?? "/", "http://factory").pathname;
1898
+ const [, jobId, action] = /^\/api\/jobs\/(\w+)\/(\w+)$/.exec(path) ?? [];
1899
+ const route = routes[`${request.method} ${jobId ? `/api/jobs/${action}` : path}`];
1900
+ try {
1901
+ if (`${request.method} ${path}` === "GET /api/chat") return planner.listen(response);
1902
+ if (route) {
1903
+ const result = await route(await body(request), jobId);
1904
+ return send(response, "application/json", JSON.stringify(result ?? null));
1905
+ }
1906
+ const file = resolve(state, `.${path}`);
1907
+ if (file.startsWith(join(state, "runs") + sep) && isFile(file)) return send(response, "text/plain; charset=utf-8", readFileSync(file));
1908
+ const asset = resolve(WEB, `.${path}`);
1909
+ if (asset.startsWith(WEB + sep) && isFile(asset)) return send(response, TYPES[extname(asset)] ?? "application/octet-stream", readFileSync(asset));
1910
+ if (path.startsWith("/api/") || path.startsWith("/runs/")) {
1911
+ response.writeHead(404).end("not found");
1912
+ return;
1913
+ }
1914
+ const page = join(WEB, "index.html");
1915
+ if (!isFile(page)) return send(response, "text/plain", "The page isn't built: run `vp build`, or use `pn dev`.");
1916
+ send(response, TYPES[".html"], readFileSync(page));
1917
+ } catch (error) {
1918
+ response.writeHead(400, { "content-type": "application/json" }).end(JSON.stringify({ error: error.message }));
1919
+ }
1920
+ }).listen(port, host, () => {
1921
+ console.log(`factory: serving http://${host}:${port}`);
1922
+ if (host !== "127.0.0.1" && host !== "localhost") console.log("factory: anyone who reaches this address can run agents on this machine");
1923
+ });
1924
+ }
1925
+ function snapshot(state, prs, train) {
1926
+ const statusPath = join(state, "status.json");
1927
+ const candidates = readCandidates(state);
1928
+ const jobs = readJobs(state);
1929
+ return {
1930
+ on: runningPid(state) !== void 0,
1931
+ status: existsSync(statusPath) ? JSON.parse(readFileSync(statusPath, "utf8")) : null,
1932
+ settings: readSettings(state),
1933
+ jobs: jobs.map((job) => ({
1934
+ ...job,
1935
+ attempts: job.attempts.map((attempt) => ({
1936
+ ...attempt,
1937
+ log: relative(state, attempt.log)
1938
+ }))
1939
+ })),
1940
+ candidates: {
1941
+ at: candidates?.at ?? null,
1942
+ count: candidates?.items.length ?? 0,
1943
+ refreshing: refreshingCandidates(state)
1944
+ },
1945
+ prs: prs(jobs.flatMap((job) => job.state === "removed" ? [] : prUrl(job) ?? [])),
1946
+ train
1947
+ };
1948
+ }
1949
+ /** A run asked for from the page, as the flags `factory run` takes. */
1950
+ function runArgs({ agents, limit, until }) {
1951
+ const args = [
1952
+ "--agents",
1953
+ Object.keys(agents).join(","),
1954
+ "--limit",
1955
+ String(limit ?? "none")
1956
+ ];
1957
+ if (until) args.push("--until", until);
1958
+ for (const [name, { model, effort }] of Object.entries(agents)) {
1959
+ if (model) args.push("--model", `${name}=${model}`);
1960
+ if (effort) args.push("--effort", `${name}=${effort}`);
1961
+ }
1962
+ return args;
1963
+ }
1964
+ async function body(request) {
1965
+ let text = "";
1966
+ for await (const chunk of request) text += chunk;
1967
+ return text ? JSON.parse(text) : {};
1968
+ }
1969
+ function isFile(path) {
1970
+ return existsSync(path) && statSync(path).isFile();
1971
+ }
1972
+ function send(response, type, body) {
1973
+ response.writeHead(200, {
1974
+ "content-type": type,
1975
+ "cache-control": "no-store"
1976
+ }).end(body);
1977
+ }
1978
+ //#endregion
1979
+ //#region package.json
1980
+ var version = "0.2.1";
1981
+ //#endregion
1982
+ //#region src/backend/cli.ts
1983
+ const USAGE = `factory: works a queue of workwork candidates with headless coding agents
1984
+
1985
+ factory start [run options] turn the factory on, in the background
1986
+ factory run [run options] the same, in the foreground
1987
+ factory stop [--kill] turn it off; agents at work finish, and the next start records them;
1988
+ --kill stops them too and puts their jobs back in the queue
1989
+ factory status on or off, what each agent is doing, the queue
1990
+ factory add <id>... [--repo DIR] [--agent NAME] [--model M] [--effort E] [--after JOB]
1991
+ queue workwork candidates from DIR (default: here), ahead of auto jobs;
1992
+ --after: start once that job is done
1993
+ factory review <job> --agent NAME
1994
+ queue a review of the job's PR by another agent, once the job is done
1995
+ factory wait <job> [--timeout MIN]
1996
+ block until the job is done, failed or blocked; exits 1 at the timeout
1997
+ factory tail follow what happens to every job, one line each
1998
+ factory remove <job> take a job out of the queue or the results, with its kept branches
1999
+ factory retry <job> queue a failed job again, with the same agent
2000
+ factory answer <job> "<text>" answer the question a blocked job asked, and queue it again
2001
+ factory auto on|off let auto mode keep the queue topped up from workwork, or not
2002
+ factory report [--all] the last run (or every run): outcome, agent, job, PR/issue link or log
2003
+ factory serve [--port 7040] [--host 127.0.0.1]
2004
+ a web page to watch, browse candidates, queue them and turn it on or off
452
2005
 
453
- factory start [options] the loop in the background; prints where the log is
454
- factory run [options] the same loop in the foreground
455
- factory status running or not, what each worker is doing, counts
456
- factory stop stops the loop and its agents; unfinished items go back in the queue
457
- factory report [--all] the last run (or every run): outcome, agent, item, PR/issue link or log
2006
+ For the agent working a job (the job is $FACTORY_JOB, or --job ID):
2007
+ factory note "<text>" something worth knowing later
2008
+ factory ask "<question>" a decision for the user; the job waits for the answer once the agent ends
2009
+ factory result "<summary>" [--confidence low|medium|high] [--url LINK] [--followup "<task>"]...
2010
+ what the job delivered, and tasks that deserve their own job
458
2011
 
459
- Options:
460
- --until HH:MM start nothing new after this local time
461
- --windows N usage-limit windows per agent before it stops (default 2)
462
- --agents claude,pi one worker per agent (default claude,pi)
463
- --levels auto,skim,decide which attention levels to take (default all)
464
- --max-items N stop after starting N items
465
- --timeout MIN minutes before an agent is killed (default 60)
466
- --claude-model, --pi-model passed to the agent as --model
2012
+ Run options (defaults from settings.json):
2013
+ --agents claude,pi which registered agents work this run
2014
+ --limit N|none usage-limit hits per agent before it stops; none: wait for each reset
2015
+ --until HH:MM start nothing new after this local time
2016
+ --model NAME=MODEL e.g. --model claude=opus; repeat per agent
2017
+ --effort NAME=LEVEL e.g. --effort pi=high; repeat per agent
2018
+ --timeout MIN minutes before an agent is killed
467
2019
 
468
2020
  State: ${STATE}`;
469
- const PID = join(STATE, "factory.pid");
470
- const LOG = join(STATE, "factory.log");
471
2021
  async function main() {
472
2022
  const { values, positionals } = parseArgs({
473
2023
  allowPositionals: true,
474
2024
  options: {
2025
+ agents: { type: "string" },
2026
+ limit: { type: "string" },
475
2027
  until: { type: "string" },
476
- windows: {
2028
+ model: {
477
2029
  type: "string",
478
- default: "2"
2030
+ multiple: true
479
2031
  },
480
- agents: {
2032
+ effort: {
481
2033
  type: "string",
482
- default: "claude,pi"
2034
+ multiple: true
483
2035
  },
484
- levels: {
2036
+ timeout: { type: "string" },
2037
+ repo: { type: "string" },
2038
+ agent: { type: "string" },
2039
+ all: { type: "boolean" },
2040
+ kill: { type: "boolean" },
2041
+ job: { type: "string" },
2042
+ after: { type: "string" },
2043
+ confidence: { type: "string" },
2044
+ url: { type: "string" },
2045
+ followup: {
485
2046
  type: "string",
486
- default: "auto,skim,decide"
2047
+ multiple: true
487
2048
  },
488
- "max-items": { type: "string" },
489
- timeout: {
2049
+ port: {
490
2050
  type: "string",
491
- default: "60"
2051
+ default: "7040"
2052
+ },
2053
+ host: {
2054
+ type: "string",
2055
+ default: "127.0.0.1"
492
2056
  },
493
- "claude-model": { type: "string" },
494
- "pi-model": { type: "string" },
495
- all: { type: "boolean" },
496
2057
  help: {
497
2058
  type: "boolean",
498
2059
  short: "h"
@@ -503,122 +2064,244 @@ async function main() {
503
2064
  }
504
2065
  }
505
2066
  });
506
- const [command] = positionals;
2067
+ const [command, ...args] = positionals;
507
2068
  if (values.help || command === void 0) return console.log(USAGE);
508
- if (values.version) return console.log(version());
2069
+ if (values.version) return console.log(version);
509
2070
  mkdirSync(STATE, { recursive: true });
510
2071
  if (command === "status") return status();
511
- if (command === "stop") return stop();
512
2072
  if (command === "report") return console.log(report(values.all ?? false));
2073
+ if (command === "remove") {
2074
+ for (const id of args) await removeJob(STATE, id);
2075
+ return;
2076
+ }
2077
+ if (command === "retry") return args.forEach((id) => retryJob(STATE, id));
2078
+ if (command === "auto") return auto(args[0]);
2079
+ if (command === "answer") return addNote(STATE, args[0], {
2080
+ kind: "answer",
2081
+ text: text(args[1])
2082
+ });
2083
+ if (command === "note" || command === "ask") return addNote(STATE, ownJob(values.job), {
2084
+ kind: command,
2085
+ text: text(args[0])
2086
+ });
2087
+ if (command === "result") return result(args[0], values);
2088
+ if (command === "review") return review(args[0], values.agent);
2089
+ if (command === "wait") return wait(args[0], values.timeout);
2090
+ if (command === "tail") return tail();
2091
+ if (command === "add") return add(args, values);
2092
+ if (command === "serve") return void serve(STATE, count(values.port, "--port"), values.host);
2093
+ if (command === "stop") {
2094
+ const pid = await turnOff(STATE, values.kill);
2095
+ return console.log(pid ? `turned off (pid ${pid})` : "already off");
2096
+ }
513
2097
  if (command !== "start" && command !== "run") throw new Error(`unknown command ${command}\n\n${USAGE}`);
514
- const models = {
515
- claude: values["claude-model"],
516
- pi: values["pi-model"]
517
- };
518
- const levels = values.levels.split(",");
519
- for (const level of levels) if (![
520
- "auto",
521
- "skim",
522
- "decide"
523
- ].includes(level)) throw new Error(`unknown level ${level}`);
524
- const options = {
525
- agents: values.agents.split(",").map((name) => agent(name, models[name])),
526
- levels,
527
- windows: count(values.windows, "--windows"),
528
- until: values.until === void 0 ? void 0 : nextTime(values.until),
529
- maxItems: values["max-items"] === void 0 ? void 0 : count(values["max-items"], "--max-items"),
530
- timeoutMs: count(values.timeout, "--timeout") * 6e4,
531
- state: STATE,
532
- workwork: "workwork"
533
- };
534
- const pid = runningPid();
535
- if (pid && pid !== process.pid) throw new Error(`already running (pid ${pid}); factory status, or factory stop`);
536
- if (command === "start") return start();
537
- writeFileSync(PID, `${process.pid}\n`);
2098
+ const options = runOptions(values);
2099
+ if (command === "start") {
2100
+ const pid = turnOn(STATE, process.argv.slice(3));
2101
+ return console.log(`factory: on (pid ${pid}); log: ${logPath(STATE)}`);
2102
+ }
2103
+ const pid = runningPid(STATE);
2104
+ if (pid && pid !== process.pid) throw new Error(`already on (pid ${pid}); factory stop first`);
2105
+ writeFileSync(pidPath(STATE), `${process.pid}\n`);
538
2106
  try {
539
2107
  const id = await run(options);
540
2108
  console.log(report(false, id));
541
2109
  } finally {
542
- rmSync(PID, { force: true });
2110
+ rmSync(pidPath(STATE), { force: true });
543
2111
  }
544
2112
  }
545
- /** `factory run` with the same arguments, outliving this shell and whoever started it. */
546
- function start() {
547
- const log = openSync(LOG, "a");
548
- const child = spawn(process.execPath, [
549
- process.argv[1],
550
- "run",
551
- ...process.argv.slice(2).filter((arg) => arg !== "start")
552
- ], {
553
- detached: true,
554
- stdio: [
555
- "ignore",
556
- log,
557
- log
558
- ]
2113
+ /** The run's options: flags where given, settings.json for the rest. */
2114
+ function runOptions(values) {
2115
+ const settings = readSettings(STATE);
2116
+ const names = values.agents?.split(",") ?? Object.keys(settings.agents);
2117
+ const agents = {};
2118
+ for (const name of names) {
2119
+ agent(name);
2120
+ agents[name] = { ...settings.agents[name] };
2121
+ }
2122
+ for (const field of ["model", "effort"]) for (const pair of values[field] ?? []) {
2123
+ const [name, value] = pair.split("=");
2124
+ if (!agents[name] || !value) throw new Error(`--${field} wants NAME=VALUE for an agent of this run, got ${pair}`);
2125
+ agents[name][field] = value;
2126
+ }
2127
+ const limit = values.limit === void 0 ? settings.limit : values.limit === "none" ? null : count(values.limit, "--limit");
2128
+ const until = values.until ?? settings.until;
2129
+ return {
2130
+ agents,
2131
+ limit,
2132
+ until: until === void 0 ? void 0 : nextTime(until),
2133
+ timeoutMs: count(values.timeout ?? String(settings.timeout), "--timeout") * 6e4,
2134
+ state: STATE,
2135
+ workwork: "workwork"
2136
+ };
2137
+ }
2138
+ async function add(ids, values) {
2139
+ if (ids.length === 0) throw new Error("factory add wants at least one workwork id");
2140
+ const repo = resolve(values.repo ?? ".");
2141
+ const candidates = JSON.parse(await output("workwork", ["--json"], repo));
2142
+ const items = ids.map((id) => {
2143
+ const item = candidates.find((candidate) => candidate.id === id);
2144
+ if (!item) throw new Error(`workwork has no candidate ${id} in ${repo}`);
2145
+ return item;
559
2146
  });
560
- child.unref();
561
- writeFileSync(PID, `${child.pid}\n`);
562
- console.log(`factory: started (pid ${child.pid}); log: ${LOG}`);
2147
+ if (values.agent) agent(values.agent);
2148
+ if (values.after && !readJobs(STATE).some((job) => job.id === values.after)) throw new Error(`--after names no job ${values.after}; factory status lists them`);
2149
+ const pin = {
2150
+ agent: values.agent,
2151
+ model: values.model?.[0],
2152
+ effort: values.effort?.[0],
2153
+ after: values.after
2154
+ };
2155
+ const added = addJobs(STATE, items, "pick", pin);
2156
+ for (const job of added) console.log(`queued ${job.id}: ${job.item.label} ${job.item.id}`);
2157
+ for (const item of items.filter((item) => !added.some((job) => job.item === item))) console.log(`already queued: ${item.label} ${item.id}`);
2158
+ }
2159
+ function review(id, name) {
2160
+ if (!id || !name) throw new Error("factory review wants a job and --agent NAME");
2161
+ agent(name);
2162
+ const job = queueReview(STATE, id, name);
2163
+ console.log(job ? `queued ${job.id}: ${job.item.title}` : `a review of ${id} is already queued`);
2164
+ }
2165
+ const SETTLED = [
2166
+ "done",
2167
+ "failed",
2168
+ "blocked",
2169
+ "removed"
2170
+ ];
2171
+ async function wait(id, timeout) {
2172
+ if (!id) throw new Error("factory wait wants a job");
2173
+ const deadline = timeout ? Date.now() + count(timeout, "--timeout") * 6e4 : Infinity;
2174
+ for (;;) {
2175
+ const job = readJobs(STATE).find((job) => job.id === id);
2176
+ if (!job) throw new Error(`no job ${id}; factory status lists them`);
2177
+ if (SETTLED.includes(job.state)) {
2178
+ const said = job.notes.findLast((note) => note.kind === "result" || note.kind === "ask");
2179
+ return console.log([
2180
+ job.state,
2181
+ prUrl(job),
2182
+ said?.text
2183
+ ].filter(Boolean).join(" "));
2184
+ }
2185
+ if (Date.now() >= deadline) {
2186
+ console.log(`still ${job.state}`);
2187
+ process.exitCode = 1;
2188
+ return;
2189
+ }
2190
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
2191
+ }
2192
+ }
2193
+ /** Prints each new event in jobs.jsonl as a line, until interrupted. */
2194
+ async function tail() {
2195
+ const path = join(STATE, "jobs.jsonl");
2196
+ let read = existsSync(path) ? statSync(path).size : 0;
2197
+ for (;;) {
2198
+ const size = existsSync(path) ? statSync(path).size : 0;
2199
+ if (size > read) {
2200
+ const text = readFileSync(path).subarray(read, size).toString("utf8");
2201
+ const end = text.lastIndexOf("\n") + 1;
2202
+ read += Buffer.byteLength(text.slice(0, end));
2203
+ const jobs = new Map(readJobs(STATE).map((job) => [job.id, job]));
2204
+ for (const line of text.slice(0, end).split("\n").filter(Boolean)) console.log(eventLine(JSON.parse(line), jobs));
2205
+ }
2206
+ await new Promise((resolve) => setTimeout(resolve, 500));
2207
+ }
2208
+ }
2209
+ const PAST = {
2210
+ remove: "removed",
2211
+ requeue: "back in the queue",
2212
+ retry: "queued for a retry"
2213
+ };
2214
+ function eventLine(event, jobs) {
2215
+ const id = event.type === "add" ? event.job.id : event.id;
2216
+ const job = jobs.get(id);
2217
+ const what = event.type === "add" ? `queued ${event.job.item.title}${event.job.agent ? ` for ${event.job.agent}` : ""}` : event.type === "start" ? `started by ${event.agent}` : event.type === "attempt" ? `${event.attempt.agent} ${event.attempt.outcome} ${event.attempt.url ?? ""}` : event.type === "note" ? `${event.note.kind}: ${event.note.text}` : event.type === "move" ? `moved to ${event.index + 1}` : PAST[event.type];
2218
+ return `${clock(event.at)} ${id} ${job ? basename(job.item.repo) : ""} ${what}`.trimEnd();
2219
+ }
2220
+ /** The job an agent works, which factory hands it in the environment. */
2221
+ function ownJob(job = process.env.FACTORY_JOB) {
2222
+ if (!job) throw new Error("runs inside a job, which sets FACTORY_JOB; elsewhere pass --job ID");
2223
+ return job;
2224
+ }
2225
+ function text(value) {
2226
+ if (!value?.trim()) throw new Error("wants the text as one argument, in quotes: \"…\"");
2227
+ return value;
2228
+ }
2229
+ const CONFIDENCES = [
2230
+ "low",
2231
+ "medium",
2232
+ "high"
2233
+ ];
2234
+ function result(summary, values) {
2235
+ const { confidence, url, followup = [] } = values;
2236
+ if (confidence !== void 0 && !CONFIDENCES.includes(confidence)) throw new Error(`--confidence wants ${CONFIDENCES.join(", ")}, got ${confidence}`);
2237
+ addNote(STATE, ownJob(values.job), {
2238
+ kind: "result",
2239
+ text: text(summary),
2240
+ confidence,
2241
+ url,
2242
+ followups: followup
2243
+ });
2244
+ }
2245
+ function auto(onOrOff) {
2246
+ if (onOrOff !== "on" && onOrOff !== "off") throw new Error("factory auto wants on or off");
2247
+ const settings = readSettings(STATE);
2248
+ writeSettings(STATE, {
2249
+ ...settings,
2250
+ auto: {
2251
+ ...settings.auto,
2252
+ on: onOrOff === "on"
2253
+ }
2254
+ });
2255
+ console.log(`auto mode ${onOrOff}`);
563
2256
  }
564
2257
  function status() {
565
- const pid = runningPid();
2258
+ const pid = runningPid(STATE);
566
2259
  const path = join(STATE, "status.json");
567
- if (!existsSync(path)) return console.log(pid ? `running (pid ${pid}), starting up` : "not running, never ran");
568
- const state = JSON.parse(readFileSync(path, "utf8"));
569
- const until = state.until ? `, until ${clock(state.until)}` : "";
570
- console.log(`${pid ? `running (pid ${pid})` : "not running"}, run ${state.run}${until}`);
571
- for (const worker of state.workers) {
572
- const what = worker.item ?? (worker.until ? `until ${clock(worker.until)}` : worker.reason ?? "");
573
- console.log(` ${worker.agent.padEnd(7)} ${worker.state.padEnd(9)} ${what} (since ${clock(worker.since)}, limits ${worker.limits})`);
574
- }
575
- const { done, failed, limited, timeout } = state.counts;
576
- console.log(`done ${done}, failed ${failed}, timeout ${timeout}, limited ${limited}, queued ${state.queued}`);
577
- }
578
- async function stop() {
579
- const pid = runningPid();
580
- if (!pid) return console.log("not running");
581
- process.kill(pid, "SIGTERM");
582
- for (let waited = 0; alive(pid); waited++) {
583
- if (waited === 60) throw new Error(`pid ${pid} is still running after 30 seconds`);
584
- await new Promise((resolve) => setTimeout(resolve, 500));
2260
+ const settings = readSettings(STATE);
2261
+ console.log(`${pid ? `on (pid ${pid})` : "off"}, auto mode ${settings.auto.on ? "on" : "off"}`);
2262
+ if (pid && existsSync(path)) {
2263
+ const status = JSON.parse(readFileSync(path, "utf8"));
2264
+ const until = status.until ? `, until ${clock(status.until)}` : "";
2265
+ console.log(`run ${status.run}, limit ${status.limit ?? "none"}${until}`);
2266
+ for (const worker of status.workers) {
2267
+ const what = worker.job ?? (worker.until ? `until ${clock(worker.until)}` : worker.reason ?? "");
2268
+ console.log(` ${worker.agent.padEnd(7)} ${worker.state.padEnd(9)} ${what} (since ${clock(worker.since)}, limits hit ${worker.limits})`);
2269
+ }
585
2270
  }
586
- rmSync(PID, { force: true });
587
- console.log(`stopped (pid ${pid})`);
2271
+ const jobs = readJobs(STATE);
2272
+ const blocked = jobs.filter((job) => job.state === "blocked");
2273
+ if (blocked.length) console.log(`waiting for your answer: ${blocked.length}`);
2274
+ for (const job of blocked) console.log(` ${line(job)}\n ${job.notes.findLast((note) => note.kind === "ask").text}`);
2275
+ const queued = jobs.filter((job) => job.state === "queued");
2276
+ console.log(`queue: ${queued.length}`);
2277
+ for (const job of queued.slice(0, 10)) console.log(` ${line(job)}`);
2278
+ if (queued.length > 10) console.log(` … ${queued.length - 10} more`);
2279
+ }
2280
+ function line(job) {
2281
+ const agent = job.agent ? ` [${job.agent}]` : "";
2282
+ return `${job.id} ${job.source.padEnd(4)} ${basename(job.item.repo)} ${job.item.id}${agent}`;
588
2283
  }
589
2284
  function report(all, run) {
590
- const ledger = readLedger(STATE);
591
- const last = run ?? ledger.at(-1)?.run;
592
- const entries = all ? ledger : ledger.filter((entry) => entry.run === last);
593
- if (entries.length === 0) return "nothing done yet";
2285
+ const attempts = readJobs(STATE).flatMap((job) => job.attempts.map((attempt) => ({
2286
+ job,
2287
+ attempt
2288
+ }))).sort((a, b) => a.attempt.start.localeCompare(b.attempt.start));
2289
+ const last = run ?? attempts.at(-1)?.attempt.run;
2290
+ const shown = all ? attempts : attempts.filter(({ attempt }) => attempt.run === last);
2291
+ if (shown.length === 0) return "nothing done yet";
594
2292
  const lines = [];
595
- for (const [i, entry] of entries.entries()) {
596
- if (entry.run !== entries[i - 1]?.run) lines.push(`run ${entry.run}`);
597
- lines.push(` ${entry.outcome.padEnd(7)} ${entry.agent.padEnd(6)} ${basename(entry.repo)} ${entry.id}`);
598
- lines.push(` ${detail(entry)}`);
2293
+ for (const [i, { job, attempt }] of shown.entries()) {
2294
+ if (attempt.run !== shown[i - 1]?.attempt.run) lines.push(`run ${attempt.run}`);
2295
+ lines.push(` ${attempt.outcome.padEnd(7)} ${attempt.agent.padEnd(6)} ${line(job)}`);
2296
+ const details = [attempt.url ?? attempt.log];
2297
+ const number = job.attempts.indexOf(attempt) + 1;
2298
+ for (const note of job.notes) if (note.attempt === number && (note.kind === "result" || note.kind === "ask")) details.push(`${note.kind === "ask" ? "asks" : "result"}: ${note.text}`);
2299
+ if (attempt.error) details.push(attempt.error.split("\n")[0]);
2300
+ if (attempt.branch) details.push(`unpushed work kept on branch ${attempt.branch}`);
2301
+ lines.push(...details.map((detail) => ` ${detail}`));
599
2302
  }
600
2303
  return lines.join("\n");
601
2304
  }
602
- function detail(entry) {
603
- const parts = [entry.url ?? entry.log];
604
- if (entry.error) parts.push(entry.error.split("\n")[0]);
605
- if (entry.worktree) parts.push(`unpushed work kept in ${entry.worktree}`);
606
- return parts.join("\n ");
607
- }
608
- function runningPid() {
609
- if (!existsSync(PID)) return void 0;
610
- const pid = Number(readFileSync(PID, "utf8"));
611
- return alive(pid) ? pid : void 0;
612
- }
613
- function alive(pid) {
614
- try {
615
- process.kill(pid, 0);
616
- return true;
617
- } catch (error) {
618
- if (error.code === "ESRCH") return false;
619
- throw error;
620
- }
621
- }
622
2305
  /** The next time the local clock shows HH:MM. */
623
2306
  function nextTime(text) {
624
2307
  const match = /^(\d{1,2}):(\d{2})$/.exec(text);
@@ -639,9 +2322,6 @@ function clock(iso) {
639
2322
  minute: "2-digit"
640
2323
  });
641
2324
  }
642
- function version() {
643
- return JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
644
- }
645
2325
  main().catch((error) => {
646
2326
  console.error(`factory: ${error.message}`);
647
2327
  process.exitCode = 1;