Public: anyone can read this; the crew can change it.

could we make building apps super fast?? #14

Closed opened this in answer to
Closed without merging

torque/forge:torque/8-could-we-make-building-apps-super-fast → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +701 −72
CLAUDE.md +4 −2
@@ -141,8 +141,10 @@ src/
141141 argv, stream-json, outcome), sandbox (what the agent's shell
142142 may reach and read), workdir (where clones live), runner (one
143143 run: token, clone, branch, Claude, push, open/update the pull,
144 report, reap leftovers), dispatch (outbox consumer + sweep +
145 worker tick), running (in-flight runs, for cancel)
144 report, reap leftovers), early (the pull that opens at the
145 agent's first push, and the run that is working a branch),
146 dispatch (outbox consumer + sweep + worker tick), running
147 (in-flight runs, for cancel)
146148 design/ themes, and activity (what an event is called, for both
147149 surfaces)
148150 ```
docs/APPS.md +8 −4
@@ -110,10 +110,14 @@ What a person sees, in order:
110110 makes it an app, and starts production. Seconds later there is a URL.
111111 If a sentence was given, it becomes the first issue, assigned to an agent
112112 on the crew, and the agent starts.
113 2. **A pull appears**, opened by the agent, with a preview. Open the preview
114 (a link, or a QR code from a phone), use it. Leave feedback as review
115 comments and a verdict. Request changes and the agent picks it up in the
116 background; the preview updates when it pushes.
113 2. **A pull appears at the agent's first push** — minutes in, not when the
114 whole run ends — with a preview and a description saying the work is in
115 progress; the agent's report replaces that description when it finishes.
116 Open the preview (a link, or a QR code from a phone), use it. Leave
117 feedback as review comments and a verdict. Request changes and the agent
118 picks it up in the background; the preview updates when it pushes. A
119 check that fails while the run is still working is the run's to fix, not
120 a new run's: it is handed over only if it still fails when the run ends.
117121 3. **Approve, merge.** Production redeploys from the default branch. The
118122 production data directory is untouched — the notes you took, the rows
119123 your app wrote, are all still there. The preview and its copied data are
src/actions/issues.ts +33
@@ -28,8 +28,10 @@ import {
2828 labelsFor,
2929 listComments,
3030 setAssignee,
31 setIssueBody as writeBody,
3132 setIssueLabels as writeLabels,
3233 setIssueState as writeState,
34 MAX_BODY,
3335 type Comment,
3436 type Issue,
3537 type IssueState,
@@ -195,6 +197,37 @@ export function setIssueState(
195197 return ok(changed);
196198 }
197199
200 /**
201 * Replace an issue's (or pull's) description. The author or a repo writer
202 * may; a mirror's body belongs to its origin. The forge itself uses this to
203 * finish a pull it opened at an agent's first push — the placeholder it
204 * wrote there becomes the agent's report when the run ends.
205 */
206 export function setIssueBody(
207 app: App,
208 actor: User | undefined,
209 repo: Repo,
210 issue: Issue,
211 body: string,
212 ): Result<Issue, AccessError | "body_too_long" | MirrorError> {
213 const user = requireParticipant(app, actor, repo);
214 if (!user.ok) return user;
215 if (issue.repoId !== repo.id) return err("not_found");
216 if (isMirror(app, repo)) return err("mirrored");
217 if (user.value.id !== issue.authorId && !canWrite(app.db, repo, user.value))
218 return err("forbidden");
219 if (body.length > MAX_BODY) return err("body_too_long");
220 const changed = writeBody(app.db, issue.id, body);
221 if (!changed) return ok(getIssueById(app.db, issue.id) ?? issue);
222 app.bus.append({
223 kind: `${issue.kind}.edited`,
224 repoId: repo.id,
225 actorId: user.value.id,
226 payload: { number: issue.number },
227 });
228 return ok(changed);
229 }
230
198231 /**
199232 * Replace an issue's (or pull's) label set. Writers only — labels are the
200233 * work queue. Labels may be named by id or by name; an unknown one rejects
src/core/issues.ts +13
@@ -378,6 +378,19 @@ export function setIssueState(
378378 return changed > 0 ? getIssueById(db, issueId) : undefined;
379379 }
380380
381 /** Replace the description. Returns the new issue, or undefined if it is gone. */
382 export function setIssueBody(
383 db: Database,
384 issueId: string,
385 body: string,
386 ): Issue | undefined {
387 if (body.length > MAX_BODY) return undefined;
388 const changed = db
389 .query("UPDATE issue SET body = ?1, updated_at = ?2 WHERE id = ?3")
390 .run(body, new Date().toISOString(), issueId).changes;
391 return changed > 0 ? getIssueById(db, issueId) : undefined;
392 }
393
381394 // ---- comments ----
382395
383396 export interface Comment {
src/core/pulls.ts +16 −1
@@ -95,7 +95,8 @@ export type CreatePullError =
9595 | "unknown_head"
9696 | "title_too_long"
9797 | "body_too_long"
98 | "nothing_to_merge";
98 | "nothing_to_merge"
99 | "already_open";
99100
100101 export interface CreatePullInput {
101102 /** The base (upstream) repo the PR is created in. */
@@ -125,6 +126,7 @@ export async function createPull(
125126 if (!crossRepo && input.baseBranch === input.headBranch)
126127 return err("same_branch");
127128
129
128130 const baseOid = await resolveOid(dir, `refs/heads/${input.baseBranch}`);
129131 if (!baseOid) return err("unknown_base");
130132
@@ -137,6 +139,19 @@ export async function createPull(
137139 if ((await aheadCount(dir, baseOid, headOid)) === 0)
138140 return err("nothing_to_merge");
139141
142 // One proposal per branch. A second open pull of the same head onto the
143 // same base is a duplicate, not a proposal — and two writers racing for
144 // it (the crew opening a pull at the agent's first push, the same run
145 // landing it a moment later) must leave one pull, not two. Asked here,
146 // after the last `await` and in the same turn as the insert, so no second
147 // caller can slip between the question and the answer.
148 const already = listOpenPullsFromHead(
149 db,
150 input.headRepoId ?? input.repoId,
151 input.headBranch,
152 ).some((p) => p.repoId === input.repoId && p.baseBranch === input.baseBranch);
153 if (already) return err("already_open");
154
140155 const issue = createIssue(db, {
141156 repoId: input.repoId,
142157 authorId: input.authorId,
src/crew/brief.ts +2 −2
@@ -39,9 +39,9 @@ export function systemPrompt(input: BriefInput): string {
3939 `You are working in a clone of the repository on the branch \`${input.branch}\`. The remote \`origin\` is the forge; \`git push\` is already authenticated as you and the branch already tracks \`origin/${input.branch}\`. Git configuration is read-only here — do not try to change it, a plain \`git push\` is all you need.`,
4040 "",
4141 "How to finish:",
42 "- Commit your work with clear messages and push: `git push`.",
42 "- Commit your work with clear messages and push: `git push`. Push a first working commit early and keep pushing as you go — the pull and its preview come up on that first push, so a person can watch the work instead of waiting for it.",
4343 "- If `forge.json` declares a `check`, the forge runs it against every push to your pull; a failing check comes back to you with its log. Run the same command yourself before you push.",
44 "- The forge opens the pull request for you, or updates the one that exists. Your last message is used verbatim as its description, so write it as one: what changed and what to look at, in a few sentences — no preamble, no status report, nothing addressed to a person.",
44 "- The forge opens the pull request for you at your first push, or updates the one that exists. Your last message is used verbatim as its description, so write it as one: what changed and what to look at, in a few sentences — no preamble, no status report, nothing addressed to a person.",
4545 "- Do not open the pull yourself, and do not merge anything.",
4646 "- Your run has a spend budget; when it runs out you get one short wrap-up turn to land what exists, so keep the app working as you go and commit as you go.",
4747 "",
src/crew/dispatch.ts +161 −46
@@ -27,16 +27,21 @@ import {
2727 hasQueuedRun,
2828 automaticRunsSince,
2929 cancelRun,
30 checkSummary,
3031 createRun,
3132 getRun,
3233 leaseLapsed,
3334 listActive,
3435 listQueued,
36 type CheckSummary,
3537 type Run,
3638 } from "../core/runs.ts";
3739 import { getUserById } from "../core/users.ts";
40 import { resolveOid } from "../git/merge.ts";
41 import { repoDir } from "../git/repos.ts";
3842 import { createLog } from "../kernel/log.ts";
3943 import { issueOfBranch, type RunReason } from "./brief.ts";
44 import { openEarlyPulls, pullOfRun, runWorkingOn } from "./early.ts";
4045 import { detectClaude } from "./claude.ts";
4146 import { sandboxAvailable } from "./sandbox.ts";
4247 import { AUTONOMY_TICK_MS, autonomyTick, landIfGreen } from "./autonomy.ts";
@@ -117,7 +122,7 @@ export async function startCrew(
117122 const inFlight = new Map<string, Promise<void>>();
118123 const unsubscribe = app.bus.subscribe((event) => {
119124 try {
120 route(app, event);
125 route(app, event, ready);
121126 } catch (error) {
122127 log.error("crew routing failed", {
123128 kind: event.kind,
@@ -138,6 +143,9 @@ export async function startCrew(
138143 );
139144 }
140145 pump(app, ready, inFlight);
146 // The sweep behind the push event: a wake-up missed while the forge was
147 // restarting costs a tick, not the preview.
148 void openEarlyPulls(app, ready.forgeUrl);
141149 }, TICK_MS);
142150 requeueInterrupted(app);
143151 sweep(app);
@@ -210,13 +218,20 @@ export function queueAgentRun(
210218 return run;
211219 }
212220
213 function route(app: App, event: ForgeEvent): void {
221 function route(app: App, event: ForgeEvent, options: CrewOptions): void {
214222 if (event.repoId === null) return;
215223 const number = event.payload["number"];
216224 const repo = getRepoById(app.db, event.repoId);
217225 if (!repo) return;
218226
219227 switch (event.kind) {
228 case "push": {
229 // An agent pushed: if that branch has something to propose and no
230 // pull yet, it gets one now — and with it a preview — rather than
231 // when the run ends, minutes or half an hour later.
232 void openEarlyPulls(app, options.forgeUrl);
233 return;
234 }
220235 case "issue.assigned":
221236 case "pull.assigned": {
222237 if (event.payload["agent"] !== true || typeof number !== "number") return;
@@ -272,6 +287,13 @@ function route(app: App, event: ForgeEvent): void {
272287 return;
273288 }
274289 case "run.finished": {
290 // An agent run that has just ended, on a pull whose head fails its
291 // check: the failure arrived while the run was working and was held
292 // back then (below), so it is handed over now.
293 if (event.payload["kind"] === "agent") {
294 handOverFailedCheck(app, repo, event);
295 return;
296 }
275297 if (
276298 event.payload["kind"] !== "deploy" &&
277299 event.payload["kind"] !== "check"
@@ -284,9 +306,9 @@ function route(app: App, event: ForgeEvent): void {
284306 // Green, in a repository that ships on green: land it.
285307 if (event.payload["state"] === "ok") {
286308 if (repo.autonomy !== "autonomous") return;
287 const pull = getPull(app.db, repo.id, issue.number);
288 if (!pull) return;
289 landIfGreen(app, repo, pull).catch((error) =>
309 const green = getPull(app.db, repo.id, issue.number);
310 if (!green) return;
311 landIfGreen(app, repo, green).catch((error) =>
290312 log.error("landing on green failed", {
291313 pull: issue.number,
292314 error: String(error),
@@ -297,50 +319,23 @@ function route(app: App, event: ForgeEvent): void {
297319 if (event.payload["state"] !== "failed") return;
298320 // A preview that failed to deploy, or a check that failed: either
299321 // is the agent's to look at.
300 const agent = agentFor(app, issue);
301 if (!agent) return;
302 // Bounded: after a few failed checks in a row the agent stops and a
303 // person must speak (docs/APPS.md, rule 7).
304 const since = lastHumanWord(app, issue, agent);
305 if (automaticRunsSince(app.db, issue.id, since) >= CHECK_FAILED_LIMIT) {
306 log.info("check failed again; waiting for a person", {
322 //
323 // Unless it is work in progress. The agent that is writing this
324 // branch right now knows more about it than the check does;
325 // interrupting it with a failure it is already fixing would spend a
326 // run and a slice of the `check_failed` budget for nothing. Whatever
327 // still fails when the run ends is handed to it then, above.
328 const pull = getPull(app.db, repo.id, issue.number);
329 if (
330 pull !== undefined &&
331 runWorkingOn(app, repo.id, pull.headBranch) !== undefined
332 ) {
333 log.info("check failed on work in progress; the run has it", {
307334 issue: issue.number,
308335 });
309336 return;
310337 }
311 // Whose fault: the change, or the environment the check ran in? A
312 // flaky runner or a broken base is not the agent's to rework; the
313 // check runs again instead, once, and the agent's tries are not spent.
314 const runId = event.payload["runId"];
315 // Without a decider the rule answers at once, and the rework queues
316 // in the same tick the event landed — nothing waits on a promise.
317 if (app.config.decider === undefined || typeof runId !== "string") {
318 queueAgentRun(app, repo, issue, agent, "check_failed");
319 return;
320 }
321 void whoseFault(app, runId).then((fault) => {
322 const checks = checksFor(app);
323 const kind = event.payload["kind"];
324 const commit = event.payload["commitOid"];
325 const env = event.payload["env"];
326 if (
327 fault === "environment" &&
328 kind === "check" &&
329 checks !== undefined &&
330 typeof commit === "string" &&
331 typeof env === "string" &&
332 !retriedChecks.has(`${issue.id}:${commit}`)
333 ) {
334 retriedChecks.add(`${issue.id}:${commit}`);
335 log.info(
336 "check looked like the environment's fault; running it again",
337 { issue: issue.number },
338 );
339 void checks.request(repo, env, commit, "retry", issue.id);
340 return;
341 }
342 queueAgentRun(app, repo, issue, agent, "check_failed");
343 });
338 followUpOnCheck(app, repo, issue, failedCheck(event.payload));
344339 return;
345340 }
346341 case "pull.closed":
@@ -356,7 +351,126 @@ function route(app: App, event: ForgeEvent): void {
356351 }
357352 }
358353
359 /** The agent an issue or pull belongs to: the assignee, or the pull's author. */
354 /** A red check that could be run again: which commit, in which environment. */
355 interface FailedCheck {
356 readonly runId: string;
357 readonly commitOid: string;
358 readonly env: string;
359 }
360
361 /** The failed check a `run.finished` payload describes, when it is one. */
362 function failedCheck(payload: ForgeEvent["payload"]): FailedCheck | undefined {
363 const runId = payload["runId"];
364 const commitOid = payload["commitOid"];
365 const env = payload["env"];
366 return payload["kind"] === "check" &&
367 typeof runId === "string" &&
368 typeof commitOid === "string" &&
369 typeof env === "string"
370 ? { runId, commitOid, env }
371 : undefined;
372 }
373
374 /**
375 * A failed check on an agent's pull becomes a bounded follow-up: after a
376 * few in a row the agent stops and a person must speak (docs/APPS.md,
377 * rule 7). When the check is one that can be run again, whose fault it was
378 * is asked first.
379 */
380 function followUpOnCheck(
381 app: App,
382 repo: Repo,
383 issue: Issue,
384 failed?: FailedCheck,
385 ): void {
386 const agent = agentFor(app, issue);
387 if (!agent) return;
388 const since = lastHumanWord(app, issue, agent);
389 if (automaticRunsSince(app.db, issue.id, since) >= CHECK_FAILED_LIMIT) {
390 log.info("check failed again; waiting for a person", {
391 issue: issue.number,
392 });
393 return;
394 }
395 // Whose fault: the change, or the environment the check ran in? A flaky
396 // runner or a broken base is not the agent's to rework; the check runs
397 // again instead, once, and the agent's tries are not spent.
398 //
399 // Without a decider the rule answers at once, and the rework queues in
400 // the same tick the event landed — nothing waits on a promise.
401 const checks = checksFor(app);
402 if (
403 app.config.decider === undefined ||
404 failed === undefined ||
405 checks === undefined
406 ) {
407 queueAgentRun(app, repo, issue, agent, "check_failed");
408 return;
409 }
410 void whoseFault(app, failed.runId).then((fault) => {
411 const seen = `${issue.id}:${failed.commitOid}`;
412 if (fault === "environment" && !retriedChecks.has(seen)) {
413 retriedChecks.add(seen);
414 log.info("check looked like the environment's fault; running it again", {
415 issue: issue.number,
416 });
417 void checks.request(repo, failed.env, failed.commitOid, "retry", issue.id);
418 return;
419 }
420 queueAgentRun(app, repo, issue, agent, "check_failed");
421 });
422 }
423
424 /**
425 * An agent run has ended. A check that failed on its pull while it was
426 * still working was held back — the run had the branch — so the failure is
427 * looked at once, now, if the head it failed on is still the head.
428 */
429 function handOverFailedCheck(app: App, repo: Repo, event: ForgeEvent): void {
430 const runId = event.payload["runId"];
431 if (typeof runId !== "string") return;
432 const run = getRun(app.db, runId);
433 if (!run || run.kind !== "agent") return;
434 const pull = pullOfRun(app, run);
435 if (pull === undefined || pull.state !== "open") return;
436 void headCheck(app, repo, pull)
437 .then((summary) => {
438 if (summary.state !== "failed" || summary.run === null) return;
439 const failed = summary.run;
440 followUpOnCheck(
441 app,
442 repo,
443 pull,
444 failed.kind === "check"
445 ? { runId: failed.id, commitOid: failed.commitOid, env: failed.env }
446 : undefined,
447 );
448 })
449 .catch((error) =>
450 log.error("could not read the check on a finished run's pull", {
451 run: runId,
452 error: String(error),
453 }),
454 );
455 }
456
457 /** The newest check at the pull's current head, and how it went. */
458 async function headCheck(
459 app: App,
460 repo: Repo,
461 pull: Pull,
462 ): Promise<CheckSummary> {
463 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
464 const head =
465 (await resolveOid(
466 dir,
467 pull.crossRepo
468 ? `refs/pull/${pull.number}/head`
469 : `refs/heads/${pull.headBranch}`,
470 )) ?? pull.headOid;
471 return checkSummary(app.db, pull.id, head);
472 }
473
360474 /** Checks already run again once for a head; a second red is real. */
361475 const retriedChecks = new Set<string>();
362476
@@ -400,6 +514,7 @@ async function whoseFault(
400514 : "change";
401515 }
402516
517 /** The agent an issue or pull belongs to: the assignee, or the pull's author. */
403518 export function agentFor(app: App, issue: Issue): Agent | undefined {
404519 if (issue.assigneeId !== null) {
405520 const assigned = getAgent(app.db, issue.assigneeId);
src/crew/early.ts added +209
@@ -0,0 +1,209 @@
1 /**
2 * The pull a run opens at its first push.
3 *
4 * A pull used to appear when the whole run ended, which is the slowest part
5 * of asking for an app: the seven finished agent runs on this forge took
6 * 527s, 688s, 738s, 1018s, 1435s, 1630s and 2268s, and there was nothing to
7 * look at until the last second of them. The branch exists long before that
8 * — the agent is told to push as it works — and a preview follows a pull,
9 * commit by commit, in about twelve seconds. So: as soon as an agent's
10 * branch carries a commit beyond the base, the forge opens the pull for it,
11 * with a placeholder description saying the work is in progress.
12 *
13 * `landWork` (`runner.ts`) adopts that pull when the run ends — the
14 * placeholder becomes the agent's report — and opens no second one.
15 *
16 * Nothing here is state. Running runs come from the `run` table and tips
17 * from git, read afresh every time, so this is safe to call on a push event,
18 * on a tick, or twice at once: a missed wake-up costs a tick, never a pull.
19 */
20
21 import type { App } from "../app.ts";
22 import { openPull } from "../actions/pulls.ts";
23 import { getAgent } from "../core/agents.ts";
24 import { getIssueById, type Issue } from "../core/issues.ts";
25 import { listOpenPullsFromHead, type Pull } from "../core/pulls.ts";
26 import { getForkOf, getRepoById } from "../core/repos.ts";
27 import { listActive, type Run } from "../core/runs.ts";
28 import { isSafeRef } from "../git/guard.ts";
29 import { aheadCount, resolveOid } from "../git/merge.ts";
30 import { repoDir } from "../git/repos.ts";
31 import { createLog } from "../kernel/log.ts";
32 import { appendRunLog } from "../runs/log.ts";
33
34 const log = createLog("crew");
35
36 /** The first words of a description the forge wrote for a run still going. */
37 const WIP = "**Work in progress**";
38
39 /** The trailer a pull carries: an issue is closed by it, a pull continued. */
40 export const trailerFor = (issue: Issue): string =>
41 issue.kind === "pull"
42 ? `Continues #${issue.number}`
43 : `Closes #${issue.number}`;
44
45 /**
46 * What an early pull says while the run is going. It carries the trailer
47 * from the start, so a pull merged before its run reports still closes the
48 * issue it was for.
49 */
50 export function placeholderBody(input: {
51 readonly agentName: string;
52 readonly issue: Issue;
53 readonly runUrl: string;
54 }): string {
55 return [
56 `${WIP} — @${input.agentName} is working on #${input.issue.number} now. The preview follows every push; this description becomes its report when the run ends.`,
57 "",
58 `[Watch the run](${input.runUrl})`,
59 "",
60 trailerFor(input.issue),
61 ].join("\n");
62 }
63
64 /** Whether a description is still the one the forge wrote at the first push. */
65 export const isPlaceholder = (body: string): boolean =>
66 body.startsWith(`${WIP} — @`);
67
68 /** The open pull proposing `branch` from `fork` to `repo`, if there is one. */
69 export function pullFromBranch(
70 app: App,
71 baseRepoId: string,
72 forkId: string,
73 branch: string,
74 ): Pull | undefined {
75 return listOpenPullsFromHead(app.db, forkId, branch).find(
76 (p) => p.repoId === baseRepoId,
77 );
78 }
79
80 /** The pull an agent run proposes, if one has been opened for its branch. */
81 export function pullOfRun(app: App, run: Run): Pull | undefined {
82 if (run.actorId === null || run.branch === "") return undefined;
83 const agent = getAgent(app.db, run.actorId);
84 if (agent === undefined) return undefined;
85 const fork = getForkOf(app.db, agent.user.id, run.repoId);
86 if (fork === undefined) return undefined;
87 return pullFromBranch(app, run.repoId, fork.id, run.branch);
88 }
89
90 /** Runs of an agent that are working right now, on a branch of their own. */
91 const workingRuns = (app: App): Run[] =>
92 listActive(app.db, "agent").filter(
93 (run) =>
94 run.state === "running" &&
95 run.branch !== "" &&
96 run.actorId !== null &&
97 run.issueId !== null,
98 );
99
100 /**
101 * Whether an agent run is working the branch this pull proposes. The run is
102 * on the issue, not on the pull, so this is the only way to ask — and it is
103 * what keeps an automatic follow-up from landing on an agent mid-sentence.
104 */
105 export function runWorkingOn(
106 app: App,
107 repoId: string,
108 branch: string,
109 ): Run | undefined {
110 return workingRuns(app).find(
111 (run) => run.repoId === repoId && run.branch === branch,
112 );
113 }
114
115 /** Runs whose early open is in flight, so two callers make one pull. */
116 const opening = new Set<string>();
117
118 /**
119 * Open the pull for every run whose branch already has something to
120 * propose. Never throws.
121 */
122 export async function openEarlyPulls(
123 app: App,
124 forgeUrl: string,
125 ): Promise<void> {
126 for (const run of workingRuns(app)) {
127 try {
128 await openEarlyPull(app, run, forgeUrl);
129 } catch (error) {
130 log.error("could not open a pull at the agent's push", {
131 run: run.id,
132 error: String(error),
133 });
134 }
135 }
136 }
137
138 async function openEarlyPull(
139 app: App,
140 run: Run,
141 forgeUrl: string,
142 ): Promise<void> {
143 // Single file, from the first line: a push event and a tick can land on
144 // the same run at the same moment, and everything below has an `await` in
145 // it — two of these interleaved would be two pulls.
146 if (opening.has(run.id)) return;
147 opening.add(run.id);
148 try {
149 await propose(app, run, forgeUrl);
150 } finally {
151 opening.delete(run.id);
152 }
153 }
154
155 async function propose(app: App, run: Run, forgeUrl: string): Promise<void> {
156 const repo = getRepoById(app.db, run.repoId);
157 const issue = run.issueId === null ? undefined : getIssueById(app.db, run.issueId);
158 const agent = run.actorId === null ? undefined : getAgent(app.db, run.actorId);
159 if (!repo || !issue || !agent) return;
160 // A mirror's pulls are its origin's, and the crew does not work one yet.
161 if (repo.origin !== null) return;
162 const branch = run.branch;
163 if (!isSafeRef(branch)) return;
164 const fork = getForkOf(app.db, agent.user.id, repo.id);
165 if (fork === undefined) return;
166 // Already proposed — by an earlier tick, or by a run before this one.
167 if (pullFromBranch(app, repo.id, fork.id, branch) !== undefined) return;
168
169 const forkBare = repoDir(app.reposRoot, fork.ownerName, fork.name);
170 const bare = repoDir(app.reposRoot, repo.ownerName, repo.name);
171 const [tip, base] = await Promise.all([
172 resolveOid(forkBare, `refs/heads/${branch}`),
173 resolveOid(bare, `refs/heads/${repo.defaultBranch}`),
174 ]);
175 // Nothing pushed yet, or a branch at the base tip: no proposal in it.
176 if (tip === undefined || base === undefined || tip === base) return;
177 if ((await aheadCount(forkBare, base, tip)) === 0) return;
178
179 const runUrl = `${forgeUrl}/${repo.ownerName}/${repo.name}/runs/${run.id}`;
180 const opened = await openPull(app, agent.user, repo, {
181 title: issue.title,
182 body: placeholderBody({ agentName: agent.user.username, issue, runUrl }),
183 baseBranch: repo.defaultBranch,
184 headBranch: branch,
185 headRepo: fork,
186 });
187 if (!opened.ok) {
188 // Two refusals are the run landing its own work in the same moment and
189 // are not news: `already_open` is its pull, `nothing_to_merge` is the
190 // branch as the base saw it a moment ago. Either way the next tick
191 // looks again, and the pull that exists is the one that matters.
192 if (opened.error !== "already_open" && opened.error !== "nothing_to_merge")
193 log.warn("the early pull was refused", {
194 run: run.id,
195 branch,
196 error: String(opened.error),
197 });
198 return;
199 }
200 log.info("opened a pull at the agent's push", {
201 run: run.id,
202 pull: opened.value.number,
203 });
204 appendRunLog(
205 app.config.dataDir,
206 run.id,
207 `opened pull #${opened.value.number} at ${tip.slice(0, 7)}; its preview follows every push`,
208 );
209 }
src/crew/runner.ts +95 −17
@@ -14,7 +14,11 @@
1414 import { existsSync, mkdirSync } from "node:fs";
1515 import { join } from "node:path";
1616 import type { App } from "../app.ts";
17 import { addComment } from "../actions/issues.ts";
17 import {
18 addComment,
19 setIssueBody,
20 setIssueState,
21 } from "../actions/issues.ts";
1822 import { openPull } from "../actions/pulls.ts";
1923 import { forkRepo } from "../actions/repos.ts";
2024 import { announceRun } from "../actions/runs.ts";
@@ -28,7 +32,7 @@ import {
2832 listComments,
2933 type Issue,
3034 } from "../core/issues.ts";
31 import { getPull, listPulls, type Pull } from "../core/pulls.ts";
35 import { getPull, type Pull } from "../core/pulls.ts";
3236 import { getForkOf, getRepoById, type Repo } from "../core/repos.ts";
3337 import { listReviewComments, listReviews } from "../core/reviews.ts";
3438 import {
@@ -58,6 +62,7 @@ import {
5862 type RunReason,
5963 } from "./brief.ts";
6064 import { BUDGET_REACHED, runClaude } from "./claude.ts";
65 import { isPlaceholder, pullFromBranch, trailerFor } from "./early.ts";
6166 import { isRateLimited, MAX_PAUSES, resumeAt, whenText } from "./limits.ts";
6267 import { trackAgentRun, untrackAgentRun } from "./running.ts";
6368 import { sandboxPolicy } from "./sandbox.ts";
@@ -586,6 +591,17 @@ async function work(
586591 target,
587592 `Declined: ${why || "no reason given"}`,
588593 );
594 // Nothing the agent touched becomes a proposal — including a pull the
595 // forge opened for it while it was still working.
596 closeEarlyPull(
597 app,
598 repo,
599 agent,
600 fork.value,
601 branch,
602 `Declined: ${why || "no reason given"}`,
603 write,
604 );
589605 return {
590606 state: "failed",
591607 summary: `declined: ${(why.split("\n")[0] ?? "").slice(0, 200)}`,
@@ -770,10 +786,41 @@ async function prepareClone(
770786 return { ok: true };
771787 }
772788
789 /** A pull's description: the agent's report, then the trailer. */
790 const bodyFor = (report: string, issue: Issue): string =>
791 `${report === "" ? "" : `${report}\n\n`}${trailerFor(issue)}`;
792
793 /**
794 * Close a pull the forge opened at the agent's first push, when the run
795 * ends with nothing to propose. Only a placeholder is closed: a description
796 * the agent or a person has written means the pull is theirs, not the
797 * forge's to withdraw.
798 */
799 function closeEarlyPull(
800 app: App,
801 repo: Repo,
802 agent: Agent,
803 fork: Repo,
804 branch: string,
805 why: string,
806 write: (line: string) => void,
807 ): void {
808 const early = pullFromBranch(app, repo.id, fork.id, branch);
809 if (early === undefined || !isPlaceholder(early.body)) return;
810 addComment(app, agent.user, repo, early, why);
811 const closed = setIssueState(app, agent.user, repo, early, "closed");
812 write(
813 closed.ok
814 ? `closed pull #${early.number}, opened while the run was working`
815 : `could not close pull #${early.number}: ${String(closed.error)}`,
816 );
817 }
818
773819 /**
774820 * After the agent stops: push what it committed if it did not, open the
775 * pull if there is none, and report on the conversation — the agent's
776 * last message, and the forge's note under it when there is one.
821 * pull if there is none — or finish the one the forge opened at the first
822 * push — and report on the conversation: the agent's last message, and the
823 * forge's note under it when there is one.
777824 */
778825 async function landWork(
779826 app: App,
@@ -863,6 +910,15 @@ async function landWork(
863910 write(
864911 "nothing to propose: the branch has no commits beyond the default branch",
865912 );
913 closeEarlyPull(
914 app,
915 repo,
916 agent,
917 fork,
918 branch,
919 "Closing this: the branch has nothing beyond the default branch, so there is nothing left to propose.",
920 write,
921 );
866922 if (report !== "" && pull === undefined)
867923 addComment(app, agent.user, repo, issue, report);
868924 else if (report !== "" && pull !== undefined)
@@ -877,25 +933,39 @@ async function landWork(
877933 };
878934 }
879935
880 const existing =
881 pull ??
882 listPulls(app.db, repo.id, { state: "open", limit: 200 }).find(
883 (p) => p.headRepoId === fork.id && p.headBranch === branch,
884 );
885 if (existing !== undefined) {
936 const leftover = committedForIt ? ", committing its leftover changes" : "";
937 /**
938 * A pull that already proposes this branch. The one the forge opened at
939 * this run's first push is the run's own: its placeholder becomes the
940 * report, in the description, where a pull says what it is — not a
941 * comment under a paragraph nobody wrote. A pull with a description
942 * somebody wrote gets the report as a comment, as it always has.
943 */
944 const adopt = (existing: Pull): { pushed: boolean; summary: string } => {
945 if (isPlaceholder(existing.body)) {
946 const written = setIssueBody(
947 app,
948 agent.user,
949 repo,
950 existing,
951 bodyFor(report, issue),
952 );
953 if (!written.ok)
954 write(`could not write the description: ${String(written.error)}`);
955 return { pushed: true, summary: `opened pull #${existing.number}${leftover}` };
956 }
886957 if (report !== "") addComment(app, agent.user, repo, existing, report);
887958 return {
888959 pushed: true,
889 summary: `updated pull #${existing.number} (${remote?.slice(0, 7)})${committedForIt ? ", committing its leftover changes" : ""}`,
960 summary: `updated pull #${existing.number} (${remote?.slice(0, 7)})${leftover}`,
890961 };
891 }
962 };
963
964 const existing = pull ?? pullFromBranch(app, repo.id, fork.id, branch);
965 if (existing !== undefined) return adopt(existing);
892966 // No pull to update and yet the task is one: the pull it continues was
893967 // merged, and this one follows it rather than closing it.
894 const trailer =
895 issue.kind === "pull"
896 ? `Continues #${issue.number}`
897 : `Closes #${issue.number}`;
898 const body = `${report === "" ? "" : `${report}\n\n`}${trailer}`;
968 const body = bodyFor(report, issue);
899969 const opened = await openPull(app, agent.user, repo, {
900970 title: issue.title,
901971 body,
@@ -904,6 +974,14 @@ async function landWork(
904974 headRepo: fork,
905975 });
906976 if (!opened.ok) {
977 // The early open, landing between the look-up above and this call: one
978 // pull exists and it is this run's, so adopt it rather than report a
979 // refusal for something that in fact worked.
980 const raced =
981 opened.error === "already_open"
982 ? pullFromBranch(app, repo.id, fork.id, branch)
983 : undefined;
984 if (raced !== undefined) return adopt(raced);
907985 write(`could not open the pull: ${JSON.stringify(opened.error)}`);
908986 return {
909987 pushed: true,
src/design/activity.ts +2
@@ -81,6 +81,7 @@ const WORDS: Record<string, string> = {
8181 "issue.reopened": "reopened an issue",
8282 "issue.commented": "commented on an issue",
8383 "issue.labeled": "labelled an issue",
84 "issue.edited": "edited an issue's description",
8485 "pull.opened": "opened a pull request",
8586 "pull.merged": "merged a pull request",
8687 "pull.closed": "closed a pull request",
@@ -88,6 +89,7 @@ const WORDS: Record<string, string> = {
8889 "pull.commented": "commented on a pull request",
8990 "pull.reviewed": "reviewed a pull request",
9091 "pull.labeled": "labelled a pull request",
92 "pull.edited": "edited a pull request's description",
9193 "pull.thread_resolved": "resolved a review thread",
9294 "repo.created": "created a repository",
9395 "repo.forked": "forked a repository",
src/tui/screens/common.ts +1
@@ -821,6 +821,7 @@ const MESSAGES: Record<string, string> = {
821821 unknown_head: "the head branch does not exist",
822822 same_branch: "the base and head branches are the same",
823823 nothing_to_merge: "there is nothing to merge",
824 already_open: "a pull for that branch is already open",
824825 invalid_branch: "that branch name is not allowed",
825826 conflict: "the branches conflict",
826827 closed: "this pull is closed",
src/web/pages/pulls.ts +1
@@ -451,6 +451,7 @@ const COMPOSE_ERRORS: Record<string, string> = {
451451 unknown_base: "That base branch does not exist.",
452452 unknown_head: "That compare branch does not exist.",
453453 nothing_to_merge: "The compare branch has no commits beyond base.",
454 already_open: "A pull request for that branch is already open.",
454455 invalid_branch: "That branch name is not valid.",
455456 };
456457
test/crew.test.ts +156
@@ -96,11 +96,27 @@ if grep -q "Carry on from where you stopped" "${promptFile}"; then
9696 if [ -f PAUSED.md ]; then kept=yes; else kept=no; fi
9797 echo '{"type":"assistant","message":{"content":[{"type":"text","text":"PAUSED.md present: '"$kept"'"}]}}'
9898 fi
99 if grep -q DECLINE-LATE "${promptFile}"; then
100 echo "second thoughts" >> CREW.md
101 git add -A && git commit -qm "crew work" && git push -q -u origin HEAD
102 n=0
103 while [ ! -f "${dataDir}/declined-go" ] && [ $n -lt 300 ]; do sleep 0.2; n=$((n+1)); done
104 echo '{"type":"result","subtype":"success","is_error":false,"result":"DECLINED: on reflection this is not mine to do.","total_cost_usd":0.01,"num_turns":2,"session_id":"fake-3","terminal_reason":"completed"}'
105 exit 0
106 fi
99107 if grep -q DECLINE-ME "${promptFile}"; then
100108 echo "half-done edit" > SHOULD-NOT-LAND.md
101109 echo '{"type":"result","subtype":"success","is_error":false,"result":"DECLINED: this is out of scope for me.","total_cost_usd":0.005,"num_turns":1,"session_id":"fake-2","terminal_reason":"completed"}'
102110 exit 0
103111 fi
112 if grep -q SLOW-ME "${promptFile}"; then
113 echo "work in progress" >> CREW.md
114 git add -A && git commit -qm "crew work in progress" && git push -q -u origin HEAD
115 n=0
116 while [ ! -f "${dataDir}/go-on" ] && [ $n -lt 300 ]; do sleep 0.2; n=$((n+1)); done
117 echo '{"type":"result","subtype":"success","is_error":false,"result":"Watered the lawn as asked.","total_cost_usd":0.01,"num_turns":2,"session_id":"fake-1","terminal_reason":"completed"}'
118 exit 0
119 fi
104120 if grep -q "The check on your pull" "${promptFile}"; then echo "daffodils" >> CREW.md; fi
105121 echo "work by the crew $(date +%s%N)" >> CREW.md
106122 git add -A && git commit -qm "crew work" && git push -q -u origin HEAD
@@ -574,4 +590,144 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Added CREW
574590 );
575591 expect(passed.summary).toMatch(/^check passed/);
576592 }, 120_000);
593
594 test("the pull opens at the agent's first push, and the run finishes into it", async () => {
595 const made = await createRepo(app, alice, {
596 name: "meadow",
597 visibility: "private",
598 });
599 if (!made.ok) throw new Error(String(made.error));
600 const meadow = made.value;
601 const seeded = await commitToBranch(app, alice, meadow, {
602 message: "Start",
603 files: [
604 { path: "README.md", content: "# meadow\n" },
605 {
606 path: "forge.json",
607 content:
608 '{"check": {"run": "grep -q daffodils CREW.md", "install": ""}}\n',
609 },
610 ],
611 });
612 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
613 expect(addToCrew(app, alice, meadow, "bot").ok).toBe(true);
614 const until = async <T>(
615 find: () => T | undefined,
616 timeoutMs = 30_000,
617 ): Promise<T> => {
618 const deadline = Date.now() + timeoutMs;
619 while (Date.now() < deadline) {
620 const found = find();
621 if (found !== undefined) return found;
622 await Bun.sleep(100);
623 }
624 throw new Error("did not happen in time");
625 };
626 const agentRuns = () => listRuns(app.db, meadow.id, { kind: "agent" });
627 const open = () => listPulls(app.db, meadow.id, { state: "open" });
628
629 const issue = openIssue(app, alice, meadow, {
630 title: "Water the lawn",
631 body: "SLOW-ME",
632 });
633 if (!issue.ok) throw new Error(String(issue.error));
634 expect(assignIssue(app, alice, meadow, issue.value, bot).ok).toBe(true);
635
636 // The agent pushes one commit and then keeps working. The pull is open
637 // long before the run ends, and it says so.
638 const early = await until(() => open()[0]);
639 const working = agentRuns().find((r) => r.reason === "assigned")!;
640 expect(working.state).toBe("running");
641 expect(early.authorName).toBe("bot");
642 expect(early.headBranch).toBe(`bot/${issue.value.number}-water-the-lawn`);
643 expect(early.body).toContain("Work in progress");
644 expect(early.body).toContain(`Closes #${issue.value.number}`);
645 // And the check the pull brings with it runs — and fails — while the
646 // agent is still working.
647 const failed = await until(() =>
648 listRuns(app.db, meadow.id, { kind: "check" }).find(
649 (r) => r.state === "failed" && r.issueId === early.id,
650 ),
651 );
652 expect(failed.summary).toBe("check failed: check exited with code 1");
653 // A check that fails on work in progress is the run's own to fix: no
654 // follow-up is queued behind it, and the `check_failed` budget for the
655 // runs that come after is untouched.
656 await Bun.sleep(500);
657 expect(agentRuns().filter((r) => r.reason === "check_failed")).toEqual([]);
658 expect(
659 agentRuns().find((r) => r.reason === "assigned")!.state,
660 ).toBe("running");
661
662 // Let the agent finish: its report replaces the placeholder in the same
663 // pull, and no second pull is opened.
664 writeFileSync(join(dataDir, "go-on"), "go\n");
665 const done = await until(() =>
666 agentRuns().find((r) => r.reason === "assigned" && r.state === "ok"),
667 );
668 expect(done.summary).toBe(`opened pull #${early.number}`);
669 expect(open().length).toBe(1);
670 const landed = getIssue(app.db, meadow.id, early.number)!;
671 expect(landed.body).toContain("Watered the lawn as asked.");
672 expect(landed.body).toContain(`Closes #${issue.value.number}`);
673 expect(landed.body).not.toContain("Work in progress");
674 // The failure held back while the run worked is handed to it now.
675 const followUp = await until(() =>
676 agentRuns().find((r) => r.reason === "check_failed"),
677 );
678 expect(followUp.issueId).toBe(early.id);
679 }, 120_000);
680
681 test("a run that pushes and then declines leaves no pull behind", async () => {
682 const made = await createRepo(app, alice, {
683 name: "hedge",
684 visibility: "private",
685 });
686 if (!made.ok) throw new Error(String(made.error));
687 const hedge = made.value;
688 const seeded = await commitToBranch(app, alice, hedge, {
689 message: "Start",
690 files: [{ path: "README.md", content: "# hedge\n" }],
691 });
692 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
693 expect(addToCrew(app, alice, hedge, "bot").ok).toBe(true);
694 const issue = openIssue(app, alice, hedge, {
695 title: "Trim the hedge",
696 body: "DECLINE-LATE",
697 });
698 if (!issue.ok) throw new Error(String(issue.error));
699 expect(assignIssue(app, alice, hedge, issue.value, bot).ok).toBe(true);
700
701 // The pull opens at the push, as always.
702 const deadline = Date.now() + 60_000;
703 let early = listPulls(app.db, hedge.id, { state: "open" })[0];
704 while (early === undefined && Date.now() < deadline) {
705 await Bun.sleep(100);
706 early = listPulls(app.db, hedge.id, { state: "open" })[0];
707 }
708 expect(early).toBeDefined();
709
710 // …and closes again when the run declines: nothing the agent touched
711 // becomes a proposal.
712 writeFileSync(join(dataDir, "declined-go"), "go\n");
713 const done = await (async () => {
714 const settleBy = Date.now() + 30_000;
715 while (Date.now() < settleBy) {
716 const run = listRuns(app.db, hedge.id, { kind: "agent" })[0];
717 if (run && (run.state === "failed" || run.state === "ok")) return run;
718 await Bun.sleep(100);
719 }
720 throw new Error("the run did not settle");
721 })();
722 expect(done.state).toBe("failed");
723 expect(done.summary).toBe(
724 "declined: on reflection this is not mine to do.",
725 );
726 expect(listPulls(app.db, hedge.id, { state: "open" })).toEqual([]);
727 const withdrawn = getIssue(app.db, hedge.id, early!.number)!;
728 expect(withdrawn.state).toBe("closed");
729 expect(listComments(app.db, withdrawn.id).map((c) => c.body)).toContain(
730 "Declined: on reflection this is not mine to do.",
731 );
732 }, 120_000);
577733 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs