@soleone/factory 0.3.0 → 0.3.2

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/README.md CHANGED
@@ -33,11 +33,12 @@ Needs node 22+, git, [workwork](https://github.com/Soleone/workwork) with `--jso
33
33
  ### Goals
34
34
 
35
35
  ```sh
36
- factory goal new "GPUI client for Tasks" --repo ~/src/tasks --brief brief.md
36
+ factory goal new "GPUI client for Tasks" --repo ~/src/tasks --brief brief.md # or --project NAME
37
37
  factory goal show gpui-client # the graph before anything runs: tiers, critical path, estimate
38
38
  factory goal approve gpui-client
39
39
  ```
40
40
 
41
+ - **Starting one:** **New goal** on the Goals tab takes a title, a repo and a brief, or a plan to import. **New project...** in its repo list creates `$SRC/<name>` and a private GitHub repo of the same name (`goal new --project NAME` on the command line). The Live Agent can work out the brief with you and start the goal too; approving its plan stays with you.
41
42
  - **Planning:** `goal new` queues a communicator to decompose the goal into a plan, which factory validates and imports, then waits for your approval. `goal import plan.json` takes a plan you wrote, with someone or something else; [spec/plan-format.md](spec/plan-format.md) describes the format (JSON or YAML) and `goal check` validates one.
42
43
  - **Branches:** the goal gets `goal/<slug>` on origin. Each node works on `node/<slug>/<key>`, started from the integration branch's head; it commits and pushes but never opens a PR. Factory runs its gates, rebases it onto the integration branch, opens the PR and merges it, then runs the goal's own gates. A conflict queues a job to resolve it; a red integration branch pauses the goal and queues a fix.
43
44
  - **Memory:** `.factory/<slug>.md` on the integration branch holds the goal's summary and the decisions each node leaves for the next. Prompts carry the goal summary, what a node's dependencies delivered, and a pointer to the memory.
package/dist/cli.mjs CHANGED
@@ -202,6 +202,8 @@ const TIERS = [
202
202
  "builder",
203
203
  "grunt"
204
204
  ];
205
+ /** The plays of factory's own jobs that write a goal's plan. */
206
+ const PLANNING = ["decompose", "replan"];
205
207
  const presetId = (preset) => preset.id ?? [
206
208
  preset.agent,
207
209
  preset.model,
@@ -636,10 +638,12 @@ function replay(events) {
636
638
  if (event.type === "requeue" || event.type === "unblock") {
637
639
  job.state = "queued";
638
640
  job.blocked = void 0;
641
+ job.why = void 0;
639
642
  }
640
643
  if (event.type === "retry") {
641
644
  job.state = "queued";
642
645
  job.blocked = void 0;
646
+ job.why = void 0;
643
647
  failures.set(job.id, 0);
644
648
  }
645
649
  if (event.type === "move") {
@@ -660,10 +664,12 @@ function replay(events) {
660
664
  if (event.type === "block") {
661
665
  job.state = "blocked";
662
666
  job.blocked = event.reason;
667
+ job.why = event.why;
663
668
  }
664
669
  if (event.type === "merged") {
665
670
  job.state = "done";
666
671
  job.blocked = void 0;
672
+ job.why = void 0;
667
673
  }
668
674
  if (event.type === "update") Object.assign(job, event.change);
669
675
  if (event.type === "verify") job.unverified = event.need ? job.unverified.filter((need) => need !== event.need) : [];
@@ -688,7 +694,8 @@ function replay(events) {
688
694
  const said = job.notes.filter((note) => note.attempt === number);
689
695
  const asked = said.findLastIndex((note) => note.kind === "ask") > said.findLastIndex((note) => note.kind === "answer" && note.re === void 0);
690
696
  const lacking = [...job.notes.findLast((note) => note.kind === "result" && note.attempt === number)?.unverified ?? [], ...event.attempt.missing ?? []];
691
- if (outcome === "done" && lacking.length) job.unverified = [.../* @__PURE__ */ new Set([...job.unverified, ...lacking])];
697
+ const planning = PLANNING.includes(job.item.play);
698
+ if (outcome === "done" && lacking.length && !planning) job.unverified = [.../* @__PURE__ */ new Set([...job.unverified, ...lacking])];
692
699
  if (asked) {
693
700
  job.state = "blocked";
694
701
  job.blocked = "asked";
@@ -7802,8 +7809,7 @@ async function release(worktree) {
7802
7809
  //#region src/backend/goals.ts
7803
7810
  const PLAN_FORMAT = "factory-plan/1";
7804
7811
  /** Factory's own jobs inside a goal, told apart by their play. */
7805
- const DECOMPOSE = "decompose";
7806
- const REPLAN = "replan";
7812
+ const [DECOMPOSE, REPLAN] = PLANNING;
7807
7813
  const REVIEW = "review";
7808
7814
  const FIX = "fix";
7809
7815
  const CONFLICTS = "conflicts";
@@ -7834,18 +7840,20 @@ function checkPlan(raw) {
7834
7840
  }
7835
7841
  if (!Array.isArray(plan.nodes) || plan.nodes.length === 0) return [...problems, "nodes is empty"];
7836
7842
  const keys = /* @__PURE__ */ new Set();
7843
+ const milestones = new Set(plan.nodes.map((node) => node?.parent));
7837
7844
  for (const [index, node] of plan.nodes.entries()) {
7845
+ const runs = !milestones.has(node?.key);
7838
7846
  const at = `nodes[${index}]${typeof node?.key === "string" ? ` (${node.key})` : ""}`;
7839
7847
  if (typeof node?.key !== "string" || !KEY.test(node.key)) problems.push(`${at}: key must be lowercase letters, digits, . _ -`);
7840
7848
  else if (keys.has(node.key)) problems.push(`${at}: key is used twice`);
7841
7849
  else keys.add(node.key);
7842
7850
  if (typeof node?.title !== "string" || !node.title.trim()) problems.push(`${at}: title is empty`);
7843
- if (typeof node?.prompt !== "string" || !node.prompt.trim()) problems.push(`${at}: prompt is empty`);
7844
- if (!isTier(node?.tier)) problems.push(`${at}: tier must be one of ${TIERS.join(", ")}`);
7851
+ if (runs && (typeof node?.prompt !== "string" || !node.prompt.trim())) problems.push(`${at}: prompt is empty`);
7852
+ if ((runs || node?.tier !== void 0) && !isTier(node?.tier)) problems.push(`${at}: tier must be one of ${TIERS.join(", ")}`);
7845
7853
  if (node?.review !== void 0 && !isTier(node.review)) problems.push(`${at}: review must be a tier`);
7846
7854
  if (!strings(node?.after)) problems.push(`${at}: after must be a list of keys`);
7847
- if (!strings(node?.touches)) problems.push(`${at}: touches must be a list of globs (empty: anything)`);
7848
- if (!strings(node?.gates)) problems.push(`${at}: gates must be a list of commands`);
7855
+ if ((runs || node?.touches !== void 0) && !strings(node?.touches)) problems.push(`${at}: touches must be a list of globs (empty: anything)`);
7856
+ if ((runs || node?.gates !== void 0) && !strings(node?.gates)) problems.push(`${at}: gates must be a list of commands`);
7849
7857
  if (node?.needs !== void 0 && !strings(node.needs)) problems.push(`${at}: needs must be a list`);
7850
7858
  }
7851
7859
  for (const node of plan.nodes) {
@@ -7920,11 +7928,7 @@ async function importPlan(state, plan, into) {
7920
7928
  goal
7921
7929
  });
7922
7930
  if (!into) {
7923
- record(state, {
7924
- type: "block",
7925
- id: job.id,
7926
- reason: "checkpoint"
7927
- });
7931
+ checkpoint(state, job.id, `the plan has ${plan.nodes.length} nodes; approve it to start`);
7928
7932
  await createBranch(goal);
7929
7933
  }
7930
7934
  await commitFiles(goal, `factory: plan for ${plan.goal.title}`, {
@@ -7950,11 +7954,11 @@ function nodeFields(goal, node, ids) {
7950
7954
  of: goal.id,
7951
7955
  key: node.key,
7952
7956
  tier: node.tier,
7953
- prompt: node.prompt,
7957
+ prompt: node.prompt ?? "",
7954
7958
  after: node.after.map((key) => ids.get(key)),
7955
7959
  parent: node.parent ? ids.get(node.parent) : void 0,
7956
- gates: node.gates,
7957
- touches: node.touches,
7960
+ gates: node.gates ?? [],
7961
+ touches: node.touches ?? [],
7958
7962
  needs: node.needs ?? [],
7959
7963
  checkpoint: node.checkpoint || void 0,
7960
7964
  review: node.review
@@ -8007,7 +8011,7 @@ async function commitFiles(goal, message, files) {
8007
8011
  });
8008
8012
  }
8009
8013
  }
8010
- /** `factory goal new`: a goal at a checkpoint with one job for the communicator, to decompose it. */
8014
+ /** `factory goal new`: a goal with one job for the communicator, to decompose it; it waits for approval once the plan is in. */
8011
8015
  async function newGoal(state, title, repo, brief) {
8012
8016
  if (!existsSync(join(repo, ".git"))) throw new Error(`${repo} is not a git repository`);
8013
8017
  const summary = brief.trim() || title;
@@ -8035,11 +8039,6 @@ async function newGoal(state, title, repo, brief) {
8035
8039
  source: "goal",
8036
8040
  goal
8037
8041
  });
8038
- record(state, {
8039
- type: "block",
8040
- id: job.id,
8041
- reason: "checkpoint"
8042
- });
8043
8042
  await createBranch(goal);
8044
8043
  await commitFiles(goal, `factory: goal ${title}`, { [memoryPath(slug)]: `# ${title}\n\n${summary}\n\n## Decisions\n` });
8045
8044
  addJob(state, {
@@ -8067,10 +8066,11 @@ const PLAN_SPEC = `A plan is JSON:
8067
8066
  "after": [keys it depends on], "touches": [globs of files it changes; empty means anything, so it runs alone],
8068
8067
  "gates": [commands run in its worktree before it merges], "needs"?: ["display" | "gpu" | ...],
8069
8068
  "checkpoint"?: true to pause the goal for the user's approval once it's done,
8070
- "parent"?: a key, which makes milestones (a milestone's nodes wait for what it comes after; never list your own milestone in after), "review"?: a tier that reviews it before it merges
8069
+ "parent"?: a key, which makes that node a milestone (a milestone's nodes wait for what it comes after; never list your own milestone in after), "review"?: a tier that reviews it before it merges
8071
8070
  }]
8072
8071
  }
8073
- Rules: keys unique, no cycles, every reference resolves, every node has touches and gates (may be empty lists), non-empty prompts. Nodes whose touches overlap never run at the same time, so precise touches buy parallelism. Each node should fit comfortably in one session of its tier (under about 200k tokens of context).`;
8072
+ A milestone never runs: give it only "key", "title" and "after".
8073
+ Rules: keys unique, no cycles, every reference resolves; every node that runs has a tier, a non-empty prompt, and touches and gates (may be empty lists). Nodes whose touches overlap never run at the same time, so precise touches buy parallelism. Each node should fit comfortably in one session of its tier (under about 200k tokens of context).`;
8074
8074
  function decomposePrompt(title, repo, slug, brief) {
8075
8075
  return `Decompose this goal into a plan of nodes for factory, which runs them with coding agents of three tiers, in parallel where the dependencies allow.
8076
8076
 
@@ -8090,7 +8090,7 @@ ${TIER_RUBRIC}
8090
8090
 
8091
8091
  ## What to do
8092
8092
 
8093
- Read the repo enough to plan well. Write the plan to \`${planPath(slug)}\` in this folder, with goal.repo "${repo}" and goal.branch "goal/${slug}". Don't commit it: factory validates it, imports it and shows it to the user for approval. Prefer more, smaller nodes with precise touches over a few big ones, put the foundations first, and give each node gates that prove it works (build, tests, lint).`;
8093
+ Read the repo enough to plan well. Write the plan to \`${planPath(slug)}\` in this folder, with goal.repo "${repo}" and goal.branch "goal/${slug}". Don't commit it: factory validates it, imports it and shows it to the user for approval. Prefer more, smaller nodes with precise touches over a few big ones, put the foundations first, and give each node gates that prove it works (build, tests, lint). A plan has nothing for the user to check by hand, so don't pass \`--unverified\`; say what you're unsure of in your result.`;
8094
8094
  }
8095
8095
  /** Checks factory itself runs after the agent says it's done, before the job's gates: the plan files. */
8096
8096
  function builtinCheck(job, jobs, worktree) {
@@ -8161,7 +8161,7 @@ ${job.prompt}
8161
8161
 
8162
8162
  ${goal.summary}
8163
8163
 
8164
- Read \`${memoryPath(goal.slug)}\` first: the goal's memory, with the decisions, conventions and traps earlier nodes left. When you commit, append to it what the next node needs to know. The whole plan is in \`${planPath(goal.slug)}\`.
8164
+ Read \`${memoryPath(goal.slug)}\` first: the goal's memory, with the decisions, conventions and traps earlier nodes left. When you commit, append to it what the next node needs to know. The whole plan is in \`${planPath(goal.slug)}\`; read it, but leave it to factory.
8165
8165
  ${deps.length ? `\n## What this builds on\n\n${deps.join("\n")}\n` : ""}
8166
8166
  ## How to deliver
8167
8167
 
@@ -8213,19 +8213,12 @@ async function delivered$1(state, job, jobs, goalJob, worktree, log) {
8213
8213
  replanTier
8214
8214
  } }
8215
8215
  });
8216
+ checkpoint(state, goalJob.id, `the plan has ${plan.nodes.length} nodes; approve it to start`);
8216
8217
  await importPlan(state, plan, goalJob);
8217
8218
  record(state, {
8218
8219
  type: "merged",
8219
8220
  id: job.id
8220
8221
  });
8221
- record(state, {
8222
- type: "note",
8223
- id: goalJob.id,
8224
- note: {
8225
- kind: "factory",
8226
- text: `the plan has ${plan.nodes.length} nodes; approve it to start`
8227
- }
8228
- });
8229
8222
  return;
8230
8223
  }
8231
8224
  if (play === REPLAN) return applyReplan(state, job, jobs, goalJob, worktree);
@@ -8251,7 +8244,7 @@ async function delivered$1(state, job, jobs, goalJob, worktree, log) {
8251
8244
  id: job.id
8252
8245
  });
8253
8246
  if (findings.length === 0) return merge(state, served, goalJob, worktree, log);
8254
- 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.\n\nThe original task:\n\n${served.prompt}`));
8247
+ 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}`));
8255
8248
  return;
8256
8249
  }
8257
8250
  if (served === job && job.review && !jobs.some((each) => each.branchOf === job.id && each.item.play === REVIEW)) {
@@ -8288,7 +8281,7 @@ function reviewPrompt(job, goal) {
8288
8281
  return `Review the work on branch \`${nodeBranch(goal, job.key)}\` (checked out here) against its task below, before factory merges it into \`${integration(goal)}\`. See the change with \`git diff origin/${integration(goal)}...HEAD\`.
8289
8282
 
8290
8283
  1. Run its checks${job.gates.length ? ` (${job.gates.map((gate) => `\`${gate}\``).join(", ")})` : ""} and read the change against the task.
8291
- 2. Look for bugs, missed cases and changes nobody asked for. Skip style the linters already cover.
8284
+ 2. Look for bugs, missed cases and changes nobody asked for. Skip style the linters already cover. Additions to the goal memory, \`${memoryPath(goal.slug)}\`, are expected: every node records its decisions there. A change to the plan, \`${planPath(goal.slug)}\`, is a finding.
8292
8285
  3. Report with \`factory result "<summary>"\`, adding \`--followup "<finding: file, line, why it matters>"\` for each finding worth fixing. No findings: no --followup. Don't change or push anything.
8293
8286
 
8294
8287
  ## The task
@@ -8411,21 +8404,7 @@ async function afterMerge(state, node, goalId, worktree, log) {
8411
8404
  type: "unblock",
8412
8405
  id: goalId
8413
8406
  });
8414
- if (node.checkpoint) {
8415
- record(state, {
8416
- type: "block",
8417
- id: goalId,
8418
- reason: "checkpoint"
8419
- });
8420
- record(state, {
8421
- type: "note",
8422
- id: goalId,
8423
- note: {
8424
- kind: "factory",
8425
- text: `checkpoint after ${node.item.title}; approve to go on`
8426
- }
8427
- });
8428
- }
8407
+ if (node.checkpoint) checkpoint(state, goalId, `checkpoint after ${node.item.title}; approve to go on`);
8429
8408
  const parent = node.parent && readJobs(state).find((each) => each.id === node.parent);
8430
8409
  if (parent && parent.state === "done") {
8431
8410
  await rebaseOntoMain(state, goalJob, worktree, log);
@@ -8538,7 +8517,7 @@ Nodes marked heavy compacted their context more than twice: split similar work s
8538
8517
 
8539
8518
  ## What to do
8540
8519
 
8541
- Write the whole plan, as it should be from now on, to \`${replanPath(goal.slug)}\` in this folder (don't commit it). Keep every node that is done, running, or waiting to merge exactly as it is now. You may add nodes and change or drop those that haven't started. Changing or dropping more than a quarter of the unstarted ones stops the goal for the user's approval.
8520
+ Write the whole plan, as it should be from now on, to \`${replanPath(goal.slug)}\` in this folder (don't commit it). Keep every node that is done, running, or waiting to merge exactly as it is now. You may add nodes and change or drop those that haven't started. Changing or dropping more than a quarter of the unstarted ones stops the goal for the user's approval. A plan has nothing for the user to check by hand, so don't pass \`--unverified\`; say what you're unsure of in your result.
8542
8521
 
8543
8522
  ${PLAN_SPEC}
8544
8523
 
@@ -8553,7 +8532,7 @@ function replanProblems(plan, job, jobs) {
8553
8532
  if (!started$1(node)) return [];
8554
8533
  const now = planned.get(node.key);
8555
8534
  if (!now) return [`${node.key} is ${node.state} and has to stay in the plan`];
8556
- return now.prompt === node.prompt && now.tier === node.tier && JSON.stringify([...now.after].sort()) === JSON.stringify(node.after.map(keyOf).sort()) ? [] : [`${node.key} is ${node.state}; its prompt, tier and after have to stay as they are`];
8535
+ return (now.prompt ?? "") === node.prompt && now.tier === node.tier && JSON.stringify([...now.after].sort()) === JSON.stringify(node.after.map(keyOf).sort()) ? [] : [`${node.key} is ${node.state}; its prompt, tier and after have to stay as they are`];
8557
8536
  });
8558
8537
  }
8559
8538
  const started$1 = (node) => node.state !== "queued" && !(node.state === "blocked" && node.blocked === "held");
@@ -8614,45 +8593,36 @@ function applyReplan(state, job, jobs, goalJob, worktree) {
8614
8593
  text: note
8615
8594
  }
8616
8595
  });
8617
- if (changed > unstarted.length / 4) {
8618
- record(state, {
8619
- type: "block",
8620
- id: goalJob.id,
8621
- reason: "checkpoint"
8622
- });
8623
- record(state, {
8624
- type: "note",
8625
- id: goalJob.id,
8626
- note: {
8627
- kind: "factory",
8628
- text: "the replan changed more than a quarter of what's left; approve it to go on"
8629
- }
8630
- });
8631
- }
8596
+ if (changed > unstarted.length / 4) checkpoint(state, goalJob.id, "the replan changed more than a quarter of what's left; approve it to go on");
8632
8597
  }
8633
- /** At its attempt budget a goal waits at a checkpoint; approving gives it the same budget again. */
8634
- function checkBudget(state, goalId) {
8635
- const jobs = readJobs(state);
8636
- const goalJob = jobs.find((each) => each.id === goalId);
8637
- const budget = goalJob.goal.budget?.attempts;
8638
- if (!budget || goalJob.state === "blocked" || goalJob.state === "done") return;
8639
- const used = attemptsUsed(jobs, goalId);
8640
- const allowed = budget * (1 + goalJob.notes.filter((note) => note.kind === "factory" && note.text.startsWith("budget raised")).length);
8641
- if (used < allowed) return;
8598
+ /** Stops the goal for the user's approval, saying why on the goal and in its notes. */
8599
+ function checkpoint(state, id, why) {
8642
8600
  record(state, {
8643
8601
  type: "block",
8644
- id: goalId,
8645
- reason: "checkpoint"
8602
+ id,
8603
+ reason: "checkpoint",
8604
+ why
8646
8605
  });
8647
8606
  record(state, {
8648
8607
  type: "note",
8649
- id: goalId,
8608
+ id,
8650
8609
  note: {
8651
8610
  kind: "factory",
8652
- text: `budget used: ${used} of ${allowed} attempts; approving adds ${budget} more`
8611
+ text: why
8653
8612
  }
8654
8613
  });
8655
8614
  }
8615
+ /** At its attempt budget a goal waits at a checkpoint; approving gives it the same budget again. */
8616
+ function checkBudget(state, goalId) {
8617
+ const jobs = readJobs(state);
8618
+ const goalJob = jobs.find((each) => each.id === goalId);
8619
+ const budget = goalJob.goal.budget?.attempts;
8620
+ if (!budget || goalJob.state === "blocked" || goalJob.state === "done") return;
8621
+ const used = attemptsUsed(jobs, goalId);
8622
+ const allowed = budget * (1 + goalJob.notes.filter((note) => note.kind === "factory" && note.text.startsWith("budget raised")).length);
8623
+ if (used < allowed) return;
8624
+ checkpoint(state, goalId, `budget used: ${used} of ${allowed} attempts; approving adds ${budget} more`);
8625
+ }
8656
8626
  const attemptsUsed = (jobs, goalId) => jobs.filter((each) => each.of === goalId).reduce((sum, each) => sum + each.attempts.length, 0);
8657
8627
  /** The user's go: after the plan, a checkpoint or a used budget. */
8658
8628
  function approveGoal(state, goalId) {
@@ -8735,6 +8705,13 @@ function readPlan(file) {
8735
8705
  if (!existsSync(file) || !statSync(file).isFile()) throw new Error(`no plan file ${file}`);
8736
8706
  return parsePlan(readFileSync(file, "utf8"), file);
8737
8707
  }
8708
+ /** A pasted plan, JSON or YAML (YAML reads both), imported once it's valid. */
8709
+ async function importPlanText(state, text) {
8710
+ const plan = (0, import_dist.parse)(text);
8711
+ const problems = checkPlan(plan);
8712
+ if (problems.length) throw new Error(`the plan has problems:\n${problems.map((each) => `- ${each}`).join("\n")}`);
8713
+ return importPlan(state, plan);
8714
+ }
8738
8715
  //#endregion
8739
8716
  //#region src/backend/models.ts
8740
8717
  /** Every model each agent offers, its short list first. */
@@ -9992,6 +9969,102 @@ function log(message) {
9992
9969
  console.log(`${(/* @__PURE__ */ new Date()).toISOString()} ${message}`);
9993
9970
  }
9994
9971
  //#endregion
9972
+ //#region src/backend/repos.ts
9973
+ /** Where workwork --all looks for repos, with the same fallback. */
9974
+ const sourceRoot = () => resolve(process.env.SRC ?? process.cwd());
9975
+ /** Local repos are available as filters even when workwork finds no candidates in them. */
9976
+ function localRepos() {
9977
+ const root = sourceRoot();
9978
+ return existsSync(root) ? findRepos(root, 4) : [];
9979
+ }
9980
+ /**
9981
+ * The GitHub user's own repos (not forked or archived) that aren't cloned anywhere under $SRC
9982
+ * yet, newest first.
9983
+ */
9984
+ async function clonableRepos() {
9985
+ const root = sourceRoot();
9986
+ const listed = JSON.parse(await output("gh", [
9987
+ "repo",
9988
+ "list",
9989
+ "--source",
9990
+ "--no-archived",
9991
+ "--limit",
9992
+ "5000",
9993
+ "--json",
9994
+ "nameWithOwner,description,createdAt"
9995
+ ], root));
9996
+ const cloned = new Set(await Promise.all(localRepos().map(originName)));
9997
+ return {
9998
+ root,
9999
+ repos: listed.filter((repo) => !cloned.has(repo.nameWithOwner.toLowerCase())).map((repo) => ({
10000
+ name: repo.nameWithOwner,
10001
+ description: repo.description,
10002
+ createdAt: repo.createdAt
10003
+ })).sort((a, b) => b.createdAt.localeCompare(a.createdAt))
10004
+ };
10005
+ }
10006
+ /** Clones `name` (owner/repo) to $SRC/<repo> and returns that path. */
10007
+ async function cloneRepo(name) {
10008
+ if (!/^[\w.-]+\/[\w.-]+$/.test(name)) throw new Error(`${name} isn't a GitHub owner/repo`);
10009
+ const root = sourceRoot();
10010
+ const path = join(root, name.split("/")[1]);
10011
+ if (existsSync(path)) throw new Error(`${path} already exists`);
10012
+ await output("gh", [
10013
+ "repo",
10014
+ "clone",
10015
+ name,
10016
+ path
10017
+ ], root);
10018
+ return path;
10019
+ }
10020
+ /**
10021
+ * A new project: $SRC/<name> with a first commit, pushed to a new private GitHub repo of the same
10022
+ * name, since a goal's integration branch lives on origin. Returns its path.
10023
+ */
10024
+ async function createRepo(name) {
10025
+ if (!/^[\w.-]+$/.test(name)) throw new Error(`${name} isn't a repo name: letters, digits, . _ -`);
10026
+ const path = join(sourceRoot(), name);
10027
+ if (existsSync(path)) throw new Error(`${path} already exists`);
10028
+ mkdirSync(path, { recursive: true });
10029
+ writeFileSync(join(path, "README.md"), `# ${name}\n`);
10030
+ await output("git", [
10031
+ "init",
10032
+ "-b",
10033
+ "main"
10034
+ ], path);
10035
+ await output("git", ["add", "README.md"], path);
10036
+ await output("git", [
10037
+ "commit",
10038
+ "-m",
10039
+ "init"
10040
+ ], path);
10041
+ await output("gh", [
10042
+ "repo",
10043
+ "create",
10044
+ name,
10045
+ "--private",
10046
+ "--source",
10047
+ ".",
10048
+ "--push"
10049
+ ], path);
10050
+ return path;
10051
+ }
10052
+ /** Repos under `dir`, searched the way workwork --all does. */
10053
+ function findRepos(dir, depth) {
10054
+ if (existsSync(join(dir, ".git"))) return [dir];
10055
+ if (depth === 0) return [];
10056
+ 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));
10057
+ }
10058
+ /** owner/repo of the GitHub origin, lowercased; empty when there is none. */
10059
+ async function originName(repo) {
10060
+ const url = await output("git", [
10061
+ "remote",
10062
+ "get-url",
10063
+ "origin"
10064
+ ], repo).catch(() => "");
10065
+ return /github\.com[:/](.+?)(?:\.git)?\/?$/.exec(url.trim())?.[1].toLowerCase() ?? "";
10066
+ }
10067
+ //#endregion
9995
10068
  //#region src/backend/power.ts
9996
10069
  const logPath = (state) => join(state, "factory.log");
9997
10070
  /** `factory run <args>` in the background, outliving this process and whoever started it. */
@@ -10370,71 +10443,9 @@ function context() {
10370
10443
  - \`--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.
10371
10444
  - 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.
10372
10445
 
10373
- 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.`;
10374
- }
10375
- //#endregion
10376
- //#region src/backend/repos.ts
10377
- /** Where workwork --all looks for repos, with the same fallback. */
10378
- const sourceRoot = () => resolve(process.env.SRC ?? process.cwd());
10379
- /** Local repos are available as filters even when workwork finds no candidates in them. */
10380
- function localRepos() {
10381
- const root = sourceRoot();
10382
- return existsSync(root) ? findRepos(root, 4) : [];
10383
- }
10384
- /**
10385
- * The GitHub user's own repos (not forked or archived) that aren't cloned anywhere under $SRC
10386
- * yet, newest first.
10387
- */
10388
- async function clonableRepos() {
10389
- const root = sourceRoot();
10390
- const listed = JSON.parse(await output("gh", [
10391
- "repo",
10392
- "list",
10393
- "--source",
10394
- "--no-archived",
10395
- "--limit",
10396
- "5000",
10397
- "--json",
10398
- "nameWithOwner,description,createdAt"
10399
- ], root));
10400
- const cloned = new Set(await Promise.all(localRepos().map(originName)));
10401
- return {
10402
- root,
10403
- repos: listed.filter((repo) => !cloned.has(repo.nameWithOwner.toLowerCase())).map((repo) => ({
10404
- name: repo.nameWithOwner,
10405
- description: repo.description,
10406
- createdAt: repo.createdAt
10407
- })).sort((a, b) => b.createdAt.localeCompare(a.createdAt))
10408
- };
10409
- }
10410
- /** Clones `name` (owner/repo) to $SRC/<repo> and returns that path. */
10411
- async function cloneRepo(name) {
10412
- if (!/^[\w.-]+\/[\w.-]+$/.test(name)) throw new Error(`${name} isn't a GitHub owner/repo`);
10413
- const root = sourceRoot();
10414
- const path = join(root, name.split("/")[1]);
10415
- if (existsSync(path)) throw new Error(`${path} already exists`);
10416
- await output("gh", [
10417
- "repo",
10418
- "clone",
10419
- name,
10420
- path
10421
- ], root);
10422
- return path;
10423
- }
10424
- /** Repos under `dir`, searched the way workwork --all does. */
10425
- function findRepos(dir, depth) {
10426
- if (existsSync(join(dir, ".git"))) return [dir];
10427
- if (depth === 0) return [];
10428
- 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));
10429
- }
10430
- /** owner/repo of the GitHub origin, lowercased; empty when there is none. */
10431
- async function originName(repo) {
10432
- const url = await output("git", [
10433
- "remote",
10434
- "get-url",
10435
- "origin"
10436
- ], repo).catch(() => "");
10437
- return /github\.com[:/](.+?)(?:\.git)?\/?$/.exec(url.trim())?.[1].toLowerCase() ?? "";
10446
+ - 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.
10447
+
10448
+ Propose what to queue and why, briefly, and add jobs or goals only once the user agrees. Never start, stop or run the factory, never change files or git state other than through those commands, and never merge or close PRs: the user does those from the page.`;
10438
10449
  }
10439
10450
  //#endregion
10440
10451
  //#region src/backend/train.ts
@@ -10593,7 +10604,8 @@ function serve(state, port, host) {
10593
10604
  return {
10594
10605
  at: cached?.at ?? null,
10595
10606
  items,
10596
- repos
10607
+ repos,
10608
+ root: sourceRoot()
10597
10609
  };
10598
10610
  },
10599
10611
  "POST /api/candidates/refresh": () => {
@@ -10604,6 +10616,13 @@ function serve(state, port, host) {
10604
10616
  await cloneRepo(body.name);
10605
10617
  refreshCandidates(state, "workwork").catch((error) => console.error(`factory: workwork failed: ${error.message}`));
10606
10618
  },
10619
+ /** A goal from a brief, in a repo under $SRC or, with `project`, a new one. */
10620
+ "POST /api/goals": async (body) => {
10621
+ const repo = body.project ? await createRepo(body.project) : body.repo;
10622
+ if (!body.title?.trim() || !repo) throw new Error("a goal wants a title and a repo");
10623
+ return newGoal(state, body.title.trim(), repo, body.brief ?? "");
10624
+ },
10625
+ "POST /api/goals/import": (body) => importPlanText(state, body.plan),
10607
10626
  "GET /api/plays": async () => JSON.parse(await output("workwork", ["plays", "--json"], process.cwd())),
10608
10627
  "POST /api/candidates/prompt": (body) => {
10609
10628
  const [item] = candidates([body]);
@@ -10757,7 +10776,7 @@ function send(response, type, body) {
10757
10776
  }
10758
10777
  //#endregion
10759
10778
  //#region package.json
10760
- var version = "0.3.0";
10779
+ var version = "0.3.2";
10761
10780
  //#endregion
10762
10781
  //#region src/backend/cli.ts
10763
10782
  const USAGE = `factory: works workwork candidates and long goals with headless coding agents
@@ -10788,8 +10807,9 @@ const USAGE = `factory: works workwork candidates and long goals with headless c
10788
10807
  a web page to watch, browse candidates, queue them and turn it on or off
10789
10808
 
10790
10809
  Goals: one large task as a graph of jobs on its own integration branch
10791
- factory goal new "<title>" --repo DIR [--brief FILE]
10792
- queue a decomposer; the goal waits at a checkpoint for its plan
10810
+ factory goal new "<title>" --repo DIR|--project NAME [--brief FILE]
10811
+ queue a decomposer; the goal waits for approval once its plan is in;
10812
+ --project creates $SRC/NAME and a private GitHub repo for it
10793
10813
  factory goal import PLAN validate and import a plan (JSON or YAML); waits for approval
10794
10814
  factory goal check PLAN validate only, listing every problem
10795
10815
  factory goal show [GOAL] [--json]
@@ -10836,6 +10856,7 @@ async function main() {
10836
10856
  timeout: { type: "string" },
10837
10857
  idle: { type: "string" },
10838
10858
  repo: { type: "string" },
10859
+ project: { type: "string" },
10839
10860
  prompt: { type: "string" },
10840
10861
  tier: { type: "string" },
10841
10862
  title: { type: "string" },
@@ -11026,9 +11047,10 @@ function step(what, values) {
11026
11047
  async function goal(args, values) {
11027
11048
  const [sub, target, why] = args;
11028
11049
  if (sub === "new") {
11029
- if (!target || !values.repo) throw new Error("factory goal new wants \"<title>\" --repo DIR");
11050
+ if (!target || !(values.repo || values.project)) throw new Error("factory goal new wants \"<title>\" --repo DIR or --project NAME");
11030
11051
  const brief = values.brief ? readFileSync(values.brief, "utf8") : "";
11031
- const job = await newGoal(STATE, target, resolve(values.repo), brief);
11052
+ const repo = values.project ? await createRepo(values.project) : resolve(values.repo);
11053
+ const job = await newGoal(STATE, target, repo, brief);
11032
11054
  return console.log(`goal ${job.goal.slug} (${job.id}): the decomposer is queued; approve its plan with factory goal approve ${job.goal.slug}`);
11033
11055
  }
11034
11056
  if (sub === "check" || sub === "import") {