@soleone/factory 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -202,15 +202,30 @@ const TIERS = [
202
202
  "builder",
203
203
  "grunt"
204
204
  ];
205
- /** The plays of factory's own jobs that write a goal's plan. */
205
+ /** The blueprints of factory's own jobs that write a goal's plan. */
206
206
  const PLANNING = ["decompose", "replan"];
207
207
  const presetId = (preset) => preset.id ?? [
208
208
  preset.agent,
209
209
  preset.model,
210
210
  preset.effort
211
211
  ].filter(Boolean).join("/");
212
+ function upgradeItem(item) {
213
+ if (!("play" in item)) return item;
214
+ const { play, level, ...rest } = item;
215
+ return {
216
+ ...rest,
217
+ blueprint: play,
218
+ attention: level === "auto" ? "none" : level
219
+ };
220
+ }
212
221
  /** A candidate's identity across workwork runs. */
213
222
  const itemKey = (item) => `${item.repo} ${item.id}`;
223
+ /** The pools whose 5-hour usage factory can read, so a reserve can be kept on them. */
224
+ const USAGE_POOLS = [
225
+ "claude",
226
+ "anthropic",
227
+ "openai-codex"
228
+ ];
214
229
  const onTrain = (car) => car !== void 0 && car.step !== "merged" && car.step !== "skipped";
215
230
  /** The PR factory opened for a goal node, or else the PR of the job's latest attempt that linked one. */
216
231
  const prUrl = (job) => job.notes.findLast((note) => note.kind === "factory" && note.url?.includes("/pull/"))?.url ?? job.attempts.findLast((attempt) => attempt.url?.includes("/pull/"))?.url;
@@ -287,8 +302,8 @@ function alive(pid) {
287
302
  throw error;
288
303
  }
289
304
  }
290
- const LEVELS = [
291
- "auto",
305
+ const ATTENTION = [
306
+ "none",
292
307
  "skim",
293
308
  "decide"
294
309
  ];
@@ -300,6 +315,7 @@ const DEFAULTS = {
300
315
  chat: { agent: "pi" },
301
316
  presets: [],
302
317
  limit: 1,
318
+ reserves: {},
303
319
  idle: 10,
304
320
  tiers: {
305
321
  communicator: [],
@@ -311,8 +327,8 @@ const DEFAULTS = {
311
327
  env: {},
312
328
  auto: {
313
329
  on: false,
314
- levels: LEVELS,
315
- plays: [],
330
+ attention: ATTENTION,
331
+ blueprints: [],
316
332
  repos: []
317
333
  }
318
334
  };
@@ -336,7 +352,7 @@ function checkSettings(raw) {
336
352
  },
337
353
  auto: {
338
354
  ...DEFAULTS.auto,
339
- ...rest.auto
355
+ ...upgradeAuto(rest.auto)
340
356
  }
341
357
  };
342
358
  for (const name of Object.keys(settings.agents)) if (!AGENT_NAMES.includes(name)) throw new Error(`unknown agent ${name} (known: ${AGENT_NAMES.join(", ")})`);
@@ -344,6 +360,10 @@ function checkSettings(raw) {
344
360
  for (const preset of settings.presets) if (!AGENT_NAMES.includes(preset.agent)) throw new Error(`unknown preset agent ${preset.agent} (known: ${AGENT_NAMES.join(", ")})`);
345
361
  if (Object.keys(settings.agents).length === 0) throw new Error("settings need at least one agent");
346
362
  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}`);
363
+ for (const [pool, reserve] of Object.entries(settings.reserves)) {
364
+ if (!USAGE_POOLS.includes(pool)) throw new Error(`can't read ${pool}'s usage to keep a reserve (can: ${USAGE_POOLS.join(", ")})`);
365
+ if (!(Number.isInteger(reserve) && reserve >= 0 && reserve < 100)) throw new Error(`reserve for ${pool} wants a whole percent from 0 to 99, got ${reserve}`);
366
+ }
347
367
  if (settings.until !== void 0 && !/^\d{1,2}:\d{2}$/.test(settings.until)) throw new Error(`until wants HH:MM, got ${settings.until}`);
348
368
  if (!(Number.isInteger(settings.idle) && settings.idle > 0)) throw new Error(`idle wants whole minutes above 0, got ${settings.idle}`);
349
369
  const ids = settings.presets.map(presetId);
@@ -354,14 +374,27 @@ function checkSettings(raw) {
354
374
  }
355
375
  if (settings.store !== "local" && settings.store !== "tasks") throw new Error(`store wants local or tasks, got ${String(settings.store)}`);
356
376
  if (settings.store === "tasks" && !settings.tasks?.home) throw new Error("store tasks wants tasks.home, the Tasks home to mirror goals into");
357
- for (const level of settings.auto.levels) if (!LEVELS.includes(level)) throw new Error(`unknown level ${level}`);
377
+ for (const attention of settings.auto.attention) if (!ATTENTION.includes(attention)) throw new Error(`unknown attention ${attention}`);
358
378
  return settings;
359
379
  }
380
+ /** Before workwork 0.3 auto mode filtered on levels and plays, with auto for none. */
381
+ function upgradeAuto(auto = {}) {
382
+ const { levels, plays, ...rest } = auto;
383
+ return {
384
+ ...rest,
385
+ ...levels && { attention: levels.map((level) => level === "auto" ? "none" : level) },
386
+ ...plays && { blueprints: plays }
387
+ };
388
+ }
360
389
  const candidatesPath = (state) => join(state, "candidates.json");
361
390
  const refreshLock = (state) => join(state, "candidates.lock");
362
391
  function readCandidates(state) {
363
392
  if (!existsSync(candidatesPath(state))) return void 0;
364
- return JSON.parse(readFileSync(candidatesPath(state), "utf8"));
393
+ const { at, items } = JSON.parse(readFileSync(candidatesPath(state), "utf8"));
394
+ return {
395
+ at,
396
+ items: items.map(upgradeItem)
397
+ };
365
398
  }
366
399
  function refreshingCandidates(state) {
367
400
  if (!existsSync(refreshLock(state))) return false;
@@ -389,11 +422,13 @@ async function refreshCandidates(state, workwork) {
389
422
  rmSync(refreshLock(state), { force: true });
390
423
  }
391
424
  }
392
- async function output(command, args, cwd) {
393
- const { stdout, stderr } = await promisify(execFile)(command, args, {
425
+ async function output(command, args, cwd, input) {
426
+ const run = promisify(execFile)(command, args, {
394
427
  cwd,
395
428
  maxBuffer: 67108864
396
429
  });
430
+ run.child.stdin.end(input);
431
+ const { stdout, stderr } = await run;
397
432
  process.stderr.write(stderr);
398
433
  return stdout;
399
434
  }
@@ -434,7 +469,7 @@ async function readPr(url) {
434
469
  state: raw.state,
435
470
  draft: raw.isDraft,
436
471
  title: raw.title,
437
- level: /^Level: (\w+)\s*$/m.exec(raw.body)?.[1],
472
+ attention: /^(?:Attention|Level): (\w+)\s*$/m.exec(raw.body)?.[1].replace(/^auto$/, "none"),
438
473
  additions: raw.additions,
439
474
  deletions: raw.deletions,
440
475
  files: raw.files.map((file) => file.path),
@@ -602,6 +637,7 @@ function record(state, event) {
602
637
  }
603
638
  const fresh = (job, at) => ({
604
639
  ...job,
640
+ item: upgradeItem(job.item),
605
641
  after: typeof job.after === "string" ? [job.after] : job.after ?? [],
606
642
  gates: job.gates ?? [],
607
643
  needs: job.needs ?? [],
@@ -671,7 +707,7 @@ function replay(events) {
671
707
  job.blocked = void 0;
672
708
  job.why = void 0;
673
709
  }
674
- if (event.type === "update") Object.assign(job, event.change);
710
+ if (event.type === "update") Object.assign(job, event.change, event.change.item && { item: upgradeItem(event.change.item) });
675
711
  if (event.type === "verify") job.unverified = event.need ? job.unverified.filter((need) => need !== event.need) : [];
676
712
  if (event.type === "note") {
677
713
  const { kind } = event.note;
@@ -694,7 +730,7 @@ function replay(events) {
694
730
  const said = job.notes.filter((note) => note.attempt === number);
695
731
  const asked = said.findLastIndex((note) => note.kind === "ask") > said.findLastIndex((note) => note.kind === "answer" && note.re === void 0);
696
732
  const lacking = [...job.notes.findLast((note) => note.kind === "result" && note.attempt === number)?.unverified ?? [], ...event.attempt.missing ?? []];
697
- const planning = PLANNING.includes(job.item.play);
733
+ const planning = PLANNING.includes(job.item.blueprint);
698
734
  if (outcome === "done" && lacking.length && !planning) job.unverified = [.../* @__PURE__ */ new Set([...job.unverified, ...lacking])];
699
735
  if (asked) {
700
736
  job.state = "blocked";
@@ -811,7 +847,7 @@ const ACTIVE = [
811
847
  "running",
812
848
  "blocked"
813
849
  ];
814
- const sameWork = (item) => `${itemKey(item)} ${item.play} ${item.title}`;
850
+ const sameWork = (item) => `${itemKey(item)} ${item.blueprint} ${item.title}`;
815
851
  /** Queues the items, skipping those already in the queue; returns the jobs it added. */
816
852
  function addJobs(state, items, source, pin = {}) {
817
853
  const at = (/* @__PURE__ */ new Date()).toISOString();
@@ -845,8 +881,8 @@ function addOwnJob(state, own) {
845
881
  repo: own.repo,
846
882
  label: basename(own.repo),
847
883
  id: `own-${Date.now()}`,
848
- play: "own",
849
- level: "decide",
884
+ blueprint: "own",
885
+ attention: "decide",
850
886
  title
851
887
  },
852
888
  source: "pick",
@@ -863,7 +899,7 @@ function queueConflicts(state, id, url, files) {
863
899
  const job = readJobs(state).find((job) => job.id === id);
864
900
  addJobs(state, [{
865
901
  ...job.item,
866
- play: "conflicts",
902
+ blueprint: "conflicts",
867
903
  title: `Resolve conflicts: ${job.item.title}`
868
904
  }], "pick", { prompt: conflictsPrompt(url, files) });
869
905
  }
@@ -889,7 +925,7 @@ function queueReview(state, id, agent) {
889
925
  const branch = workworkBranch(job.item);
890
926
  const item = {
891
927
  ...job.item,
892
- play: "review",
928
+ blueprint: "review",
893
929
  title: `Review: ${job.item.title}`
894
930
  };
895
931
  const prompt = reviewPrompt$1(branch, job.agent);
@@ -919,7 +955,7 @@ function queueFollowup(state, id, task) {
919
955
  const item = {
920
956
  ...job.item,
921
957
  id: `${job.item.id}+followup`,
922
- play: "followup",
958
+ blueprint: "followup",
923
959
  title: task
924
960
  };
925
961
  const url = prUrl(job);
@@ -1046,7 +1082,7 @@ Change the work to follow the answer. ${prUrl(job) ? `Its pull request is ${prUr
1046
1082
  item: {
1047
1083
  ...job.item,
1048
1084
  id: `${job.item.id}+answer`,
1049
- play: "answer",
1085
+ blueprint: "answer",
1050
1086
  title: `Follow the answer: ${job.item.title}`
1051
1087
  },
1052
1088
  source: job.of ? "goal" : "pick",
@@ -1078,11 +1114,11 @@ function endJob(state, id, attempt) {
1078
1114
  attempt
1079
1115
  });
1080
1116
  }
1081
- /** Cheapest attention first, and within a level one item per repo in turn so no repo takes the night. */
1082
- function order(items, levels) {
1083
- return LEVELS.filter((level) => levels.includes(level)).flatMap((level) => {
1117
+ /** Cheapest attention first, and within each one item per repo in turn so no repo takes the night. */
1118
+ function order(items, wanted) {
1119
+ return ATTENTION.filter((attention) => wanted.includes(attention)).flatMap((attention) => {
1084
1120
  const byRepo = /* @__PURE__ */ new Map();
1085
- for (const item of items.filter((item) => item.level === level)) byRepo.set(item.repo, [...byRepo.get(item.repo) ?? [], item]);
1121
+ for (const item of items.filter((item) => item.attention === attention)) byRepo.set(item.repo, [...byRepo.get(item.repo) ?? [], item]);
1086
1122
  const queues = [...byRepo.values()];
1087
1123
  const turns = [];
1088
1124
  for (let round = 0; queues.some((queue) => queue.length > round); round++) for (const queue of queues) if (queue[round]) turns.push(queue[round]);
@@ -1092,7 +1128,7 @@ function order(items, levels) {
1092
1128
  /** What auto mode would add next: wanted candidates that never had a job. */
1093
1129
  function autoPicks(candidates, jobs, auto, count) {
1094
1130
  const seen = new Set(jobs.map((job) => itemKey(job.item)));
1095
- 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);
1131
+ return order(candidates.filter((item) => !seen.has(itemKey(item)) && (auto.blueprints.length === 0 || auto.blueprints.includes(item.blueprint)) && (auto.repos.length === 0 || auto.repos.includes(item.repo))), auto.attention).slice(0, count);
1096
1132
  }
1097
1133
  //#endregion
1098
1134
  //#region node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/dist/nodes/identity.js
@@ -7830,7 +7866,7 @@ async function release(worktree) {
7830
7866
  //#endregion
7831
7867
  //#region src/backend/goals.ts
7832
7868
  const PLAN_FORMAT = "factory-plan/1";
7833
- /** Factory's own jobs inside a goal, told apart by their play. */
7869
+ /** Factory's own jobs inside a goal, told apart by their blueprint. */
7834
7870
  const [DECOMPOSE, REPLAN] = PLANNING;
7835
7871
  const REVIEW = "review";
7836
7872
  const FIX = "fix";
@@ -7919,12 +7955,12 @@ const planPath = (slug) => `.factory/${slug}.plan.json`;
7919
7955
  const replanPath = (slug) => `.factory/${slug}.replan.json`;
7920
7956
  const integration = (goal) => `goal/${goal.slug}`;
7921
7957
  const nodeBranch = (goal, key) => `node/${goal.slug}/${key}`;
7922
- const goalItem = (repo, id, play, title) => ({
7958
+ const goalItem = (repo, id, blueprint, title) => ({
7923
7959
  repo,
7924
7960
  label: basename(repo),
7925
7961
  id,
7926
- play,
7927
- level: "decide",
7962
+ blueprint,
7963
+ attention: "decide",
7928
7964
  title
7929
7965
  });
7930
7966
  /**
@@ -8051,6 +8087,7 @@ async function newGoal(state, title, repo, brief) {
8051
8087
  const goal = {
8052
8088
  repo,
8053
8089
  slug,
8090
+ brief: brief.trim() || void 0,
8054
8091
  summary,
8055
8092
  gates: [],
8056
8093
  allowUp: false
@@ -8117,8 +8154,8 @@ Read the repo enough to plan well. Write the plan to \`${planPath(slug)}\` in th
8117
8154
  /** Checks factory itself runs after the agent says it's done, before the job's gates: the plan files. */
8118
8155
  function builtinCheck(job, jobs, worktree) {
8119
8156
  const goal = jobs.find((each) => each.id === job.of)?.goal;
8120
- if (!goal || job.item.play !== DECOMPOSE && job.item.play !== REPLAN) return void 0;
8121
- const path = join(worktree, job.item.play === DECOMPOSE ? planPath(goal.slug) : replanPath(goal.slug));
8157
+ if (!goal || job.item.blueprint !== DECOMPOSE && job.item.blueprint !== REPLAN) return void 0;
8158
+ const path = join(worktree, job.item.blueprint === DECOMPOSE ? planPath(goal.slug) : replanPath(goal.slug));
8122
8159
  if (!existsSync(path)) return `There's no plan at ${path}. Write it there.`;
8123
8160
  let plan;
8124
8161
  try {
@@ -8126,7 +8163,7 @@ function builtinCheck(job, jobs, worktree) {
8126
8163
  } catch (error) {
8127
8164
  return `${path} isn't valid JSON: ${error.message}`;
8128
8165
  }
8129
- const problems = [...checkPlan(plan), ...job.item.play === REPLAN ? replanProblems(plan, job, jobs) : []];
8166
+ const problems = [...checkPlan(plan), ...job.item.blueprint === REPLAN ? replanProblems(plan, job, jobs) : []];
8130
8167
  if (problems.length) return `The plan at ${path} has problems; fix them all:\n${problems.map((each) => `- ${each}`).join("\n")}`;
8131
8168
  }
8132
8169
  /** The prompt for a job: workwork's, or a goal node's with its goal, memory and dependencies; checks out its worktree. */
@@ -8157,15 +8194,15 @@ async function prepare(state, job, jobs, worktree, workwork) {
8157
8194
  "-B",
8158
8195
  branch
8159
8196
  ], worktree);
8160
- if (job.item.play === DECOMPOSE || job.item.play === REVIEW) return job.prompt;
8161
- if (job.item.play === REPLAN) return job.prompt;
8197
+ if (job.item.blueprint === DECOMPOSE || job.item.blueprint === REVIEW) return job.prompt;
8198
+ if (job.item.blueprint === REPLAN) return job.prompt;
8162
8199
  return nodePrompt(job, jobs, goalJob, branch);
8163
8200
  }
8164
8201
  /** The branch a goal job works on: its own, or for factory's helpers the one they serve. */
8165
8202
  function branchFor(job, jobs, goal) {
8166
8203
  const served = job.branchOf && jobs.find((each) => each.id === job.branchOf);
8167
8204
  if (served) return nodeBranch(goal, served.key);
8168
- return nodeBranch(goal, job.key ?? `${job.item.play}-${job.id}`);
8205
+ return nodeBranch(goal, job.key ?? `${job.item.blueprint}-${job.id}`);
8169
8206
  }
8170
8207
  function nodePrompt(job, jobs, goalJob, branch) {
8171
8208
  const goal = goalJob.goal;
@@ -8204,6 +8241,7 @@ async function afterAttempt(state, id, worktree, log) {
8204
8241
  if (job.state === "failed") queueReplan(state, goalJob, `${job.item.title} failed for good: ${job.attempts.at(-1)?.error ?? "see its notes"}`);
8205
8242
  else if (job.attempts.at(-1)?.outcome === "done") await delivered$1(state, job, jobs, goalJob, worktree, log);
8206
8243
  checkBudget(state, goalJob.id);
8244
+ await finishGoals(state, log);
8207
8245
  } catch (error) {
8208
8246
  const message = error.message.trim().split("\n").slice(0, 5).join("\n");
8209
8247
  log(`goal ${goalJob.goal.slug}: ${job.id} didn't deliver: ${message}`);
@@ -8219,8 +8257,8 @@ async function afterAttempt(state, id, worktree, log) {
8219
8257
  }
8220
8258
  async function delivered$1(state, job, jobs, goalJob, worktree, log) {
8221
8259
  const goal = goalJob.goal;
8222
- const play = job.item.play;
8223
- if (play === DECOMPOSE) {
8260
+ const blueprint = job.item.blueprint;
8261
+ if (blueprint === DECOMPOSE) {
8224
8262
  const plan = JSON.parse(readFileSync(join(worktree, planPath(goal.slug)), "utf8"));
8225
8263
  const { summary, gates, budget, allowUp, replanTier } = plan.goal;
8226
8264
  record(state, {
@@ -8243,8 +8281,8 @@ async function delivered$1(state, job, jobs, goalJob, worktree, log) {
8243
8281
  });
8244
8282
  return;
8245
8283
  }
8246
- if (play === REPLAN) return applyReplan(state, job, jobs, goalJob, worktree);
8247
- if (play === MAIN) {
8284
+ if (blueprint === REPLAN) return applyReplan(state, job, jobs, goalJob, worktree);
8285
+ if (blueprint === MAIN) {
8248
8286
  await output("git", [
8249
8287
  "push",
8250
8288
  "--quiet",
@@ -8259,7 +8297,7 @@ async function delivered$1(state, job, jobs, goalJob, worktree, log) {
8259
8297
  return afterMerge(state, job, goalJob.id, worktree, log);
8260
8298
  }
8261
8299
  const served = job.branchOf ? jobs.find((each) => each.id === job.branchOf) : job;
8262
- if (play === REVIEW) {
8300
+ if (blueprint === REVIEW) {
8263
8301
  const findings = job.notes.findLast((note) => note.kind === "result")?.followups ?? [];
8264
8302
  record(state, {
8265
8303
  type: "merged",
@@ -8269,7 +8307,7 @@ async function delivered$1(state, job, jobs, goalJob, worktree, log) {
8269
8307
  addJob(state, helper(served, goalJob, FIX, `Fix review findings: ${served.item.title}`, served.tier, `A review of branch \`${nodeBranch(goal, served.key)}\` found:\n\n${findings.map((each) => `- ${each}`).join("\n")}\n\nFix each one on that branch (it's checked out here), run the checks, commit and push. Don't open a pull request, and keep what the branch added to the goal memory, \`${memoryPath(goal.slug)}\`.\n\nThe original task:\n\n${served.prompt}`));
8270
8308
  return;
8271
8309
  }
8272
- if (served === job && job.review && !jobs.some((each) => each.branchOf === job.id && each.item.play === REVIEW)) {
8310
+ if (served === job && job.review && !jobs.some((each) => each.branchOf === job.id && each.item.blueprint === REVIEW)) {
8273
8311
  await output("git", [
8274
8312
  "push",
8275
8313
  "--quiet",
@@ -8283,10 +8321,10 @@ async function delivered$1(state, job, jobs, goalJob, worktree, log) {
8283
8321
  return merge(state, served, goalJob, worktree, log, job === served ? void 0 : job);
8284
8322
  }
8285
8323
  /** One of factory's jobs for a node's branch, at the front of the goal. */
8286
- function helper(node, goalJob, play, title, tier, prompt) {
8324
+ function helper(node, goalJob, blueprint, title, tier, prompt) {
8287
8325
  return {
8288
8326
  id: newId(),
8289
- item: goalItem(goalJob.goal.repo, `${node.key ?? node.item.id}+${play}`, play, title),
8327
+ item: goalItem(goalJob.goal.repo, `${node.key ?? node.item.id}+${blueprint}`, blueprint, title),
8290
8328
  source: "goal",
8291
8329
  of: goalJob.id,
8292
8330
  parent: node.parent,
@@ -8294,7 +8332,7 @@ function helper(node, goalJob, play, title, tier, prompt) {
8294
8332
  tier,
8295
8333
  front: true,
8296
8334
  prompt,
8297
- gates: play === REVIEW ? [] : node.gates,
8335
+ gates: blueprint === REVIEW ? [] : node.gates,
8298
8336
  touches: node.touches,
8299
8337
  needs: node.needs
8300
8338
  };
@@ -8318,7 +8356,7 @@ ${job.prompt}`;
8318
8356
  async function merge(state, node, goalJob, worktree, log, by) {
8319
8357
  const goal = goalJob.goal;
8320
8358
  const git = (...args) => output("git", args, worktree);
8321
- const branch = nodeBranch(goal, node.key ?? `${node.item.play}-${node.id}`);
8359
+ const branch = nodeBranch(goal, node.key ?? `${node.item.blueprint}-${node.id}`);
8322
8360
  const base = integration(goal);
8323
8361
  for (let tries = 0;; tries++) {
8324
8362
  await git("fetch", "--quiet", "origin");
@@ -8345,7 +8383,7 @@ async function merge(state, node, goalJob, worktree, log, by) {
8345
8383
  }
8346
8384
  }
8347
8385
  const said = (by ?? node).notes.findLast((note) => note.kind === "result");
8348
- const url = node.item.play === MAIN ? void 0 : await createPr(goal.repo, base, branch, `${node.item.title}`, `${said?.text ?? node.item.title}\n\nPart of goal ${goalJob.item.title}; factory merged it into ${base}.`).catch(() => void 0);
8386
+ const url = node.item.blueprint === MAIN ? void 0 : await createPr(goal.repo, base, branch, `${node.item.title}`, `${said?.text ?? node.item.title}\n\nPart of goal ${goalJob.item.title}; factory merged it into ${base}.`).catch(() => void 0);
8349
8387
  record(state, {
8350
8388
  type: "note",
8351
8389
  id: node.id,
@@ -8389,7 +8427,7 @@ async function remember(goal, node, worktree) {
8389
8427
  `HEAD:${integration(goal)}`
8390
8428
  ], worktree);
8391
8429
  }
8392
- /** After a merge: the goal's gates, checkpoints, milestones, a red goal turning green, the final PR. */
8430
+ /** After a merge: the goal's gates, checkpoints, milestones and a red goal turning green. */
8393
8431
  async function afterMerge(state, node, goalId, worktree, log) {
8394
8432
  const goalJob = readJobs(state).find((each) => each.id === goalId);
8395
8433
  const goal = goalJob.goal;
@@ -8432,14 +8470,24 @@ async function afterMerge(state, node, goalId, worktree, log) {
8432
8470
  await rebaseOntoMain(state, goalJob, worktree, log);
8433
8471
  queueReplan(state, goalJob, `milestone ${parent.item.title} is done`);
8434
8472
  }
8435
- const rest = readJobs(state).filter((each) => each.of === goalId && each.state !== "removed");
8436
- if (rest.length > 0 && rest.every((each) => each.state === "done")) {
8473
+ }
8474
+ /**
8475
+ * Opens the final PR of every goal whose nodes are all done. Runs after each goal attempt, not only
8476
+ * a merge: a replan can be the last to finish, and a run's start picks up any goal left waiting.
8477
+ */
8478
+ async function finishGoals(state, log) {
8479
+ const jobs = readJobs(state);
8480
+ for (const goalJob of jobs) {
8481
+ if (!goalJob.goal || goalJob.state !== "queued") continue;
8482
+ const rest = jobs.filter((each) => each.of === goalJob.id && each.state !== "removed");
8483
+ if (rest.length === 0 || rest.some((each) => each.state !== "done")) continue;
8484
+ const goal = goalJob.goal;
8437
8485
  const main = await originHead(goal.repo);
8438
8486
  const unverified = rest.flatMap((each) => each.unverified.map((need) => `- [ ] ${each.item.title}: ${need}`));
8439
8487
  const url = await createPr(goal.repo, main, integration(goal), goalJob.item.title, `${goal.summary}\n${unverified.length ? `\n## Unverified\n\n${unverified.join("\n")}\n` : ""}\nFactory worked this goal; merging it is yours.`);
8440
8488
  record(state, {
8441
8489
  type: "note",
8442
- id: goalId,
8490
+ id: goalJob.id,
8443
8491
  note: {
8444
8492
  kind: "factory",
8445
8493
  text: `every node is done; the final PR is open`,
@@ -8448,7 +8496,7 @@ async function afterMerge(state, node, goalId, worktree, log) {
8448
8496
  });
8449
8497
  record(state, {
8450
8498
  type: "merged",
8451
- id: goalId
8499
+ id: goalJob.id
8452
8500
  });
8453
8501
  log(`goal ${goal.slug} is done: ${url}`);
8454
8502
  }
@@ -8491,7 +8539,7 @@ async function gatesFail(gates, cwd) {
8491
8539
  /** Queues a replan of the goal, unless one waits already. */
8492
8540
  function queueReplan(state, goalJob, why) {
8493
8541
  const jobs = readJobs(state);
8494
- if (jobs.some((each) => each.of === goalJob.id && each.item.play === REPLAN && ["queued", "running"].includes(each.state))) return void 0;
8542
+ if (jobs.some((each) => each.of === goalJob.id && each.item.blueprint === REPLAN && ["queued", "running"].includes(each.state))) return void 0;
8495
8543
  const goal = goalJob.goal;
8496
8544
  return addJob(state, {
8497
8545
  id: newId(),
@@ -8981,8 +9029,8 @@ function pull(state, tasks) {
8981
9029
  repo: goal.goal.repo,
8982
9030
  label: goal.item.label,
8983
9031
  id: key,
8984
- play: "goal",
8985
- level: "decide",
9032
+ blueprint: "goal",
9033
+ attention: "decide",
8986
9034
  title: task.title
8987
9035
  },
8988
9036
  source: "goal",
@@ -9279,6 +9327,49 @@ function describe(tool, input) {
9279
9327
  return tool;
9280
9328
  }
9281
9329
  //#endregion
9330
+ //#region src/backend/usage.ts
9331
+ const CLAUDE = "https://api.anthropic.com/api/oauth/usage";
9332
+ const CODEX = "https://chatgpt.com/backend-api/wham/usage";
9333
+ const readJson = (...path) => JSON.parse(readFileSync(join(homedir(), ...path), "utf8"));
9334
+ const piAuth = () => readJson(".pi", "agent", "auth.json");
9335
+ const READERS = {
9336
+ claude: () => claudeWindow(readJson(".claude", ".credentials.json").claudeAiOauth.accessToken),
9337
+ anthropic: () => claudeWindow(piAuth().anthropic.access),
9338
+ "openai-codex": async () => {
9339
+ const { access, accountId } = piAuth()["openai-codex"];
9340
+ const window = (await get(CODEX, {
9341
+ Authorization: `Bearer ${access}`,
9342
+ "ChatGPT-Account-Id": accountId
9343
+ })).rate_limit.primary_window;
9344
+ return {
9345
+ used: window.used_percent,
9346
+ resets: window.reset_at * 1e3
9347
+ };
9348
+ }
9349
+ };
9350
+ const fiveHour = (pool) => READERS[pool]();
9351
+ async function claudeWindow(token) {
9352
+ const window = (await get(CLAUDE, {
9353
+ Authorization: `Bearer ${token}`,
9354
+ "anthropic-beta": "oauth-2025-04-20"
9355
+ })).five_hour ?? {
9356
+ utilization: 0,
9357
+ resets_at: ""
9358
+ };
9359
+ return {
9360
+ used: window.utilization,
9361
+ resets: Date.parse(window.resets_at)
9362
+ };
9363
+ }
9364
+ async function get(url, headers) {
9365
+ const response = await fetch(url, {
9366
+ headers,
9367
+ signal: AbortSignal.timeout(1e4)
9368
+ });
9369
+ if (!response.ok) throw new Error(`${url} answered ${response.status}`);
9370
+ return await response.json();
9371
+ }
9372
+ //#endregion
9282
9373
  //#region src/backend/loop.ts
9283
9374
  const MINUTE = 6e4;
9284
9375
  /** Auto mode keeps this many of its jobs queued per worker, so picks never drown in them. */
@@ -9310,6 +9401,8 @@ async function run(options) {
9310
9401
  let killing = false;
9311
9402
  let topping;
9312
9403
  const borrowed = /* @__PURE__ */ new Set();
9404
+ /** Each pool's last usage read, shared by its workers so one read serves them all. */
9405
+ const reads = /* @__PURE__ */ new Map();
9313
9406
  const piPresets = slots.map((slot) => slot.preset).filter((preset) => preset.agent === "pi" && preset.model);
9314
9407
  if (piPresets.length) piWindows().then((windows) => piSettingsWarnings(piPresets, windows).forEach(log)).catch((error) => log(`can't check pi's compaction settings: ${error.message}`));
9315
9408
  function writeStatus() {
@@ -9361,6 +9454,34 @@ async function run(options) {
9361
9454
  wakers.add(wake);
9362
9455
  });
9363
9456
  }
9457
+ /**
9458
+ * Holds a pool until its 5-hour window resets once the window reaches the pool's reserve, so
9459
+ * other apps on the account keep some. Reads at most once a minute; a failed read holds nothing.
9460
+ * Reads the settings each time, so a changed reserve applies at once.
9461
+ */
9462
+ function keepReserve(pool) {
9463
+ const reserve = readSettings(state).reserves[pool.name];
9464
+ const last = reads.get(pool.name);
9465
+ if (reserve === void 0 || pool.until) return Promise.resolve();
9466
+ if (last && Date.now() - last.at < MINUTE) return last.done;
9467
+ const done = (options.usage ?? fiveHour)(pool.name).then(({ used, resets }) => {
9468
+ pool.used = used;
9469
+ if (used >= 100 - reserve && resets > Date.now()) {
9470
+ const wake = Math.min(resets + 2 * MINUTE, options.until ?? Infinity);
9471
+ Object.assign(pool, {
9472
+ until: new Date(wake).toISOString(),
9473
+ reserved: true
9474
+ });
9475
+ log(`${pool.name} used ${used}% of its 5 hours, keeps ${reserve}% until ${pool.until}`);
9476
+ }
9477
+ writeStatus();
9478
+ }, (error) => log(`can't read ${pool.name}'s usage: ${error.message}`));
9479
+ reads.set(pool.name, {
9480
+ at: Date.now(),
9481
+ done
9482
+ });
9483
+ return done;
9484
+ }
9364
9485
  /** Auto mode's part: keep a few of its jobs queued. Reads settings each time, so the toggle applies at once. */
9365
9486
  function topUp() {
9366
9487
  topping ??= fillFromAuto().catch((error) => log(`auto mode could not ask workwork: ${error.message}`)).finally(() => topping = void 0);
@@ -9411,6 +9532,7 @@ async function run(options) {
9411
9532
  if (chosen === worker.preset) return job;
9412
9533
  if (chosen !== null) continue;
9413
9534
  }
9535
+ if (!(worker.preset in options.agents)) continue;
9414
9536
  if ((job.agent ?? worker.agent) === worker.agent) return job;
9415
9537
  }
9416
9538
  }
@@ -9423,13 +9545,17 @@ async function run(options) {
9423
9545
  state: "stopped",
9424
9546
  reason: pool.stopped
9425
9547
  });
9548
+ if (!handed) await keepReserve(pool);
9426
9549
  if (pool.until) {
9427
9550
  set(worker, {
9428
9551
  state: "sleeping",
9429
9552
  until: pool.until
9430
9553
  });
9431
9554
  await (options.sleep ?? nap)(Math.max(0, Date.parse(pool.until) - Date.now()));
9432
- pool.until = void 0;
9555
+ Object.assign(pool, {
9556
+ until: void 0,
9557
+ reserved: void 0
9558
+ });
9433
9559
  continue;
9434
9560
  }
9435
9561
  let job;
@@ -9787,6 +9913,7 @@ async function run(options) {
9787
9913
  const stopMirror = mirrorTasks(state, settings, log);
9788
9914
  writeStatus();
9789
9915
  try {
9916
+ await finishGoals(state, log);
9790
9917
  await Promise.all(slots.map((slot) => work(slot, handed.get(slot))));
9791
9918
  } catch (error) {
9792
9919
  kill();
@@ -10460,11 +10587,12 @@ function context() {
10460
10587
  const factory = `"${process.execPath}" "${process.argv[1]}"`;
10461
10588
  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.
10462
10589
 
10463
- - 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.
10590
+ - The current folder is factory's state. candidates.json holds every repo's candidates from workwork ({ at, items: [{ repo, label, id, blueprint, attention, title }] }); jobs.jsonl is the queue and results, one event per line. runs/ holds each attempt's prompt.md and agent.log.
10464
10591
  - \`${factory} status\` shows the queue and \`${factory} report --all\` past results. \`workwork prompt <id>\`, run in the candidate's repo, shows the full task.
10465
10592
  - To queue candidates: \`${factory} add <id>... --repo <repo>\`, optionally with \`--agent ${AGENT_NAMES.join("|")}\`. Picked jobs go ahead of auto ones.
10593
+ - A blueprint is the reusable prompt behind candidates; \`workwork blueprints\` lists them, and on-request ones never show up in candidates.json. \`${factory} add --blueprint <name> --repo <repo>\` queues what one finds in a repo.
10466
10594
  - \`--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.
10467
- - 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.
10595
+ - Attention: none 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.
10468
10596
 
10469
10597
  - Goals are one large task, planned into a graph of jobs. When the user wants one, work out a brief with them: what done looks like, constraints, links to specs, and how to verify it (the commands that prove it works). Write it to a file in this folder, then \`${factory} goal new "<title>" --repo <repo> --brief <file>\`, or \`--project <name>\` instead of \`--repo\` for a new project, which creates the repo under the source folder and on GitHub. A decomposer plans it, and the user approves the plan on the Goals tab: never approve one yourself.
10470
10598
 
@@ -10583,6 +10711,9 @@ function serve(state, port, host) {
10583
10711
  }));
10584
10712
  return models.get(name);
10585
10713
  }
10714
+ function refresh() {
10715
+ refreshCandidates(state, "workwork").catch((error) => console.error(`factory: workwork failed: ${error.message}`));
10716
+ }
10586
10717
  /** Only cached candidates, so the page can't queue or run workwork for anything it names. */
10587
10718
  function candidates(wanted) {
10588
10719
  const cached = new Map(readCandidates(state)?.items.map((item) => [itemKey(item), item]));
@@ -10632,12 +10763,12 @@ function serve(state, port, host) {
10632
10763
  };
10633
10764
  },
10634
10765
  "POST /api/candidates/refresh": () => {
10635
- refreshCandidates(state, "workwork").catch((error) => console.error(`factory: workwork failed: ${error.message}`));
10766
+ refresh();
10636
10767
  },
10637
10768
  "GET /api/repos": () => clonableRepos(),
10638
10769
  "POST /api/repos/clone": async (body) => {
10639
10770
  await cloneRepo(body.name);
10640
- refreshCandidates(state, "workwork").catch((error) => console.error(`factory: workwork failed: ${error.message}`));
10771
+ refresh();
10641
10772
  },
10642
10773
  /** A goal from a brief, in a repo under $SRC or, with `project`, a new one. */
10643
10774
  "POST /api/goals": async (body) => {
@@ -10646,7 +10777,28 @@ function serve(state, port, host) {
10646
10777
  return newGoal(state, body.title.trim(), repo, body.brief ?? "");
10647
10778
  },
10648
10779
  "POST /api/goals/import": (body) => importPlanText(state, body.plan),
10649
- "GET /api/plays": async () => JSON.parse(await output("workwork", ["plays", "--json"], process.cwd())),
10780
+ "GET /api/blueprints": async () => JSON.parse(await output("workwork", ["blueprints", "--json"], process.cwd())),
10781
+ "PUT /api/blueprints": async (body) => {
10782
+ await output("workwork", ["blueprints", "save"], process.cwd(), JSON.stringify(body));
10783
+ refresh();
10784
+ },
10785
+ "POST /api/blueprints/delete": async (body) => {
10786
+ await output("workwork", [
10787
+ "blueprints",
10788
+ "delete",
10789
+ body.name
10790
+ ], process.cwd());
10791
+ refresh();
10792
+ },
10793
+ "POST /api/blueprints/run": async (body) => {
10794
+ const found = JSON.parse(await output("workwork", [
10795
+ "--blueprint",
10796
+ body.name,
10797
+ "--json"
10798
+ ], body.repo));
10799
+ if (found.length === 0) throw new Error(`${body.name} finds nothing to do in ${body.repo}`);
10800
+ return addJobs(state, found, "pick");
10801
+ },
10650
10802
  "POST /api/candidates/prompt": (body) => {
10651
10803
  const [item] = candidates([body]);
10652
10804
  return output("workwork", ["prompt", item.id], item.repo);
@@ -10800,7 +10952,7 @@ function send(response, type, body) {
10800
10952
  }
10801
10953
  //#endregion
10802
10954
  //#region package.json
10803
- var version = "0.3.3";
10955
+ var version = "0.4.0";
10804
10956
  //#endregion
10805
10957
  //#region src/backend/cli.ts
10806
10958
  const USAGE = `factory: works workwork candidates and long goals with headless coding agents
@@ -10813,6 +10965,8 @@ const USAGE = `factory: works workwork candidates and long goals with headless c
10813
10965
  factory add <id>... [--repo DIR] [--agent NAME] [--model M] [--effort E] [--after JOB]...
10814
10966
  queue workwork candidates from DIR (default: here), ahead of auto jobs;
10815
10967
  --after: start once that job is done
10968
+ factory add --blueprint NAME [--repo DIR] [<id>...]
10969
+ queue what a blueprint finds in DIR, on-request ones too; ids pick some
10816
10970
  factory add --prompt FILE --tier T [--repo DIR] [--title TEXT]
10817
10971
  one job of your own, without workwork, for a tier
10818
10972
  factory review <job> --agent NAME
@@ -10882,6 +11036,7 @@ async function main() {
10882
11036
  repo: { type: "string" },
10883
11037
  project: { type: "string" },
10884
11038
  prompt: { type: "string" },
11039
+ blueprint: { type: "string" },
10885
11040
  tier: { type: "string" },
10886
11041
  title: { type: "string" },
10887
11042
  brief: { type: "string" },
@@ -11013,10 +11168,16 @@ function runOptions(values) {
11013
11168
  }
11014
11169
  async function add(ids, values) {
11015
11170
  if (values.prompt) return addOwn(values);
11016
- if (ids.length === 0) throw new Error("factory add wants at least one workwork id, or --prompt FILE");
11171
+ if (ids.length === 0 && !values.blueprint) throw new Error("factory add wants workwork ids, --blueprint NAME or --prompt FILE");
11017
11172
  const repo = resolve(values.repo ?? ".");
11018
- const candidates = JSON.parse(await output("workwork", ["--json"], repo));
11019
- const items = ids.map((id) => {
11173
+ const listing = values.blueprint ? [
11174
+ "--blueprint",
11175
+ values.blueprint,
11176
+ "--json"
11177
+ ] : ["--json"];
11178
+ const candidates = JSON.parse(await output("workwork", listing, repo));
11179
+ if (values.blueprint && candidates.length === 0) throw new Error(`${values.blueprint} finds nothing to do in ${repo}`);
11180
+ const items = (ids.length ? ids : candidates.map((each) => each.id)).map((id) => {
11020
11181
  const item = candidates.find((candidate) => candidate.id === id);
11021
11182
  if (!item) throw new Error(`workwork has no candidate ${id} in ${repo}`);
11022
11183
  return item;
@@ -11211,8 +11372,9 @@ function status() {
11211
11372
  const until = status.until ? `, until ${clock(status.until)}` : "";
11212
11373
  console.log(`run ${status.run}, limit ${status.limit ?? "none"}${until}`);
11213
11374
  for (const pool of status.pools) {
11214
- const pause = pool.stopped ?? (pool.until ? `sleeps until ${clock(pool.until)}` : "");
11215
- console.log(` pool ${pool.name}: limits hit ${pool.limits}${pause ? `, ${pause}` : ""}`);
11375
+ const pause = pool.stopped ?? (pool.until ? `${pool.reserved ? "keeps its reserve" : "sleeps"} until ${clock(pool.until)}` : "");
11376
+ const used = pool.used === void 0 ? "" : `, ${pool.used}% of 5h used`;
11377
+ console.log(` pool ${pool.name}: limits hit ${pool.limits}${used}${pause ? `, ${pause}` : ""}`);
11216
11378
  for (const worker of status.workers.filter((each) => each.pool === pool.name)) {
11217
11379
  const what = worker.job ?? (worker.until ? `until ${clock(worker.until)}` : worker.reason ?? "");
11218
11380
  const doing = worker.activity ? ` ${worker.activity}` : "";