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

Open the pull at the agent's first push, not when the run ends #993

Closed opened this
Closed without merging

scout/forge:scout/10-open-the-pull-at-the-agent-s-first-push → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +361 −23
docs/APPS.md +5 −4
@@ -183,10 +183,11 @@ What a person sees, in order:
183183 with a small working app in it, makes it an app, and starts production.
184184 Seconds later there is a URL. The sentence becomes the first issue,
185185 assigned to an agent on the crew, and the agent starts.
186 2. **A pull appears**, opened by the agent, with a preview. Open the preview
187 (a link, or a QR code from a phone), use it. Leave feedback as review
188 comments and a verdict. Request changes and the agent picks it up in the
189 background; the preview updates when it pushes.
186 2. **A pull appears at the agent's first push**, not at the end of its run,
187 with a preview that follows every push after. Open the preview (a link,
188 or a QR code from a phone), use it. Leave feedback as review comments and
189 a verdict. Request changes and the agent picks it up in the background;
190 the preview updates when it pushes.
190191 3. **Approve, merge.** Production redeploys from the default branch. The
191192 production data directory is untouched — the notes you took, the rows
192193 your app wrote, are all still there. The preview and its copied data are
src/core/issues.ts +17
@@ -136,6 +136,23 @@ export function setAssignee(
136136 return changed > 0 ? getIssueById(db, issueId) : undefined;
137137 }
138138
139 /**
140 * Replace an issue's (or pull's) body outright. Used once, to turn an early
141 * pull's "still working" placeholder into the agent's own report when the
142 * run that opened it lands — every other edit is a comment, not a rewrite.
143 */
144 export function setBody(
145 db: Database,
146 issueId: string,
147 body: string,
148 ): Issue | undefined {
149 db.query(
150 `UPDATE issue SET body = ?2, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
151 WHERE id = ?1`,
152 ).run(issueId, body);
153 return getIssueById(db, issueId);
154 }
155
139156 /**
140157 * Several conversations by id, in one query per chunk — what a run list
141158 * needs to name the pull each run is about without a read per row.
src/core/runs.ts +21
@@ -608,6 +608,27 @@ export function hasQueuedRun(
608608 );
609609 }
610610
611 /**
612 * The unfinished run pushing to one branch, if any. A pull opened on its
613 * first push (runner.ts) shares no issue id with the run authoring it — that
614 * run began against the task issue, before the pull existed — so `branch`
615 * is how a check on the pull finds its still-running author.
616 */
617 export function activeRunForBranch(
618 db: Database,
619 kind: RunKind,
620 repoId: string,
621 branch: string,
622 ): Run | undefined {
623 const row = db
624 .query<
625 RunRow,
626 [RunKind, string, string]
627 >("SELECT * FROM run WHERE state IN ('queued','running') AND kind = ?1 AND repo_id = ?2 AND branch = ?3 ORDER BY id LIMIT 1")
628 .get(kind, repoId, branch);
629 return row ? toRun(row) : undefined;
630 }
631
611632 /**
612633 * The checks on a pull: the deploy runs at its current head, newest first.
613634 * Older heads are history — a push makes new runs — so a caller that wants
src/crew/brief.ts +4 −3
@@ -67,9 +67,10 @@ export function systemPrompt(input: BriefInput): string {
6767 `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.`,
6868 "",
6969 "How to finish:",
70 "- Push a first working commit early, then keep committing and pushing as you go. The forge opens the pull — and its preview — on that first push, not when you are done, so push something real as soon as you have it rather than saving it all for the end.",
7071 "- Commit your work with clear messages and push: `git push`.",
71 "- If `forge.json` declares a `check`, the forge runs it against every push to your pull, and that verdict is what lands it; a failing check comes back to you with its log. Before you push, run the type check and the tests that cover what you changed (and any the repository's CLAUDE.md or AGENTS.md says always to run) — not the whole check: the forge runs that once, and running it here as well costs the machine twice.",
72 "- 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.",
72 "- If `forge.json` declares a `check`, the forge runs it against every push to your pull, and that verdict is what lands it; a failing check comes back to you with its log, but not while you are still working — only once you have stopped. Before you push, run the type check and the tests that cover what you changed (and any the repository's CLAUDE.md or AGENTS.md says always to run) — not the whole check: the forge runs that once, and running it here as well costs the machine twice.",
73 "- The forge opens the pull request for you on 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.",
7374 "- Do not open the pull yourself, and do not merge anything.",
7475 "- 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.",
7576 "",
@@ -248,7 +249,7 @@ function taskBody(input: TaskInput): string {
248249 if (handed.length > 0) out.push("", ...handed);
249250 out.push(
250251 "",
251 `Work it on the branch \`${input.branch}\` and push when done.`,
252 `Work it on the branch \`${input.branch}\`. Push a first working commit as soon as you have one — that is what opens the pull and its preview — and keep pushing as you go.`,
252253 );
253254 return out.join("\n");
254255 }
src/crew/dispatch.ts +26
@@ -34,6 +34,7 @@ import { listReviews } from "../core/reviews.ts";
3434 import { greenHead, sendToReview } from "./review.ts";
3535 import {
3636 activeRunFor,
37 activeRunForBranch,
3738 hasQueuedRun,
3839 automaticRunsSince,
3940 cancelRun,
@@ -511,6 +512,31 @@ function route(app: App, event: ForgeEvent): void {
511512 return;
512513 }
513514 if (event.payload["state"] !== "failed") return;
515 // A push mid-run — the pull opened on its first commit (runner.ts) —
516 // failing its check is not feedback: the run that made it is still
517 // going and will push again. Engaging the agent now would answer a
518 // draft, and spend a try from the bounded few it gets (rule 7,
519 // docs/APPS.md) on nothing it asked to be judged on yet.
520 // An early pull shares no issue id with the run authoring it — that
521 // run began against the task issue, before the pull existed — so its
522 // branch, not its issue id, is what finds a still-running author.
523 const authoringPull = getPull(app.db, repo.id, issue.number);
524 const authoring =
525 activeRunFor(app.db, "agent", issue.id) ??
526 (authoringPull
527 ? activeRunForBranch(
528 app.db,
529 "agent",
530 repo.id,
531 authoringPull.headBranch,
532 )
533 : undefined);
534 if (authoring !== undefined && authoring.state === "running") {
535 log.info("check failed on a work-in-progress push; still running", {
536 issue: issue.number,
537 });
538 return;
539 }
514540 // A preview that failed to deploy, or a check that failed: either
515541 // is the agent's to look at.
516542 const agent = agentFor(app, issue);
src/crew/runner.ts +185 −16
@@ -15,7 +15,7 @@ import { capacityEnv } from "../core/capacity.ts";
1515 import { existsSync, mkdirSync, rmSync } from "node:fs";
1616 import { join } from "node:path";
1717 import type { App } from "../app.ts";
18 import { addComment } from "../actions/issues.ts";
18 import { addComment, setIssueState } from "../actions/issues.ts";
1919 import { openPull } from "../actions/pulls.ts";
2020 import { forkRepo, sealedForkFor } from "../actions/repos.ts";
2121 import { announceRun } from "../actions/runs.ts";
@@ -28,6 +28,7 @@ import {
2828 getIssueById,
2929 labelsForIssues,
3030 listComments,
31 setBody,
3132 type Issue,
3233 } from "../core/issues.ts";
3334 import { getPull, listPulls, type Pull } from "../core/pulls.ts";
@@ -199,6 +200,23 @@ const RESERVE = 0.15;
199200 /** ...and never less than this: a wrap-up that cannot run a test is none. */
200201 const RESERVE_FLOOR_USD = 0.5;
201202
203 /** How often the run's clone is polled for a branch worth a pull, while the agent works. */
204 const WATCH_MS = 2_000;
205
206 /**
207 * The first line of a pull opened before the run that will fill it in has
208 * finished. Its presence, and nothing else, is what tells `landWork` this
209 * pull is still a placeholder rather than a person's or an earlier run's.
210 */
211 const IN_PROGRESS_MARKER =
212 "_Work in progress — the agent is still on it; this pull will update as it pushes._";
213
214 const earlyPullBody = (forgeUrl: string, repo: Repo, runId: string): string =>
215 `${IN_PROGRESS_MARKER}\n\n[Follow the run](${forgeUrl}/${repo.ownerName}/${repo.name}/runs/${runId}).`;
216
217 const isEarlyPull = (pull: Pull): boolean =>
218 pull.body.trim().startsWith(IN_PROGRESS_MARKER);
219
202220 /**
203221 * What a run keeps for its wrap-up: fifteen percent of the budget, at
204222 * least fifty cents, never more than half — a budget too small to split
@@ -650,6 +668,7 @@ async function work(
650668 };
651669
652670 let grant: Grant | undefined;
671 let stopWatch: () => Promise<void> = async () => {};
653672 let runTmp: string | undefined;
654673 try {
655674 // The secrets this run declared, for this run only: opened now, held for
@@ -970,6 +989,23 @@ async function work(
970989 `sandbox: off here${options.sandboxNote === undefined ? "" : ` — ${options.sandboxNote}`}; the shell runs unrestricted`,
971990 );
972991 const working = budget - reserve;
992 // The branch, in the fork, is polled while the agent works: the moment
993 // it is first ahead of the base is the moment a person could look at
994 // something, so the pull opens then rather than at the end of the run.
995 if (!reviewing)
996 stopWatch = watchForFirstPush(
997 app,
998 options,
999 repo,
1000 agent,
1001 issue,
1002 fork.value,
1003 branch,
1004 forkBare,
1005 bare,
1006 run.id,
1007 write,
1008 );
9731009 let result = await invoke(
9741010 prompt,
9751011 working,
@@ -1105,6 +1141,11 @@ async function work(
11051141 turns: result.turns,
11061142 };
11071143
1144 // Stopped here, and before anything below: what comes next — closing
1145 // the early pull, or landWork filling it in — is bookkeeping the watcher
1146 // must not race to do first.
1147 await stopWatch();
1148
11081149 // The decline contract: an agent that should not do the task says so
11091150 // instead of guessing, and nothing it touched becomes a proposal.
11101151 const declined = /^\s*DECLINED\b/i.test(result.result);
@@ -1113,7 +1154,9 @@ async function work(
11131154 write(`declined: ${why.split("\n")[0] ?? ""}`);
11141155 // The reason lives on the run record (its summary) and the ledger
11151156 // line, never as a comment: a comment on an assigned issue is the
1116 // thing that starts the next run.
1157 // thing that starts the next run. An early pull is the exception: it
1158 // is the agent's own, and it is closed, so nothing waits on it.
1159 closeEarlyPull(app, agent, repo, fork.value, branch, why, write);
11171160 return {
11181161 state: "failed",
11191162 summary: `declined: ${(why.split("\n")[0] ?? "").slice(0, 200)}`,
@@ -1172,6 +1215,7 @@ async function work(
11721215 turns: result.turns,
11731216 };
11741217 } finally {
1218 await stopWatch();
11751219 grant?.release();
11761220 deleteToken(app.db, agent.user.id, token.id);
11771221 if (runTmp !== undefined) rmSync(runTmp, { recursive: true, force: true });
@@ -1331,6 +1375,106 @@ async function prepareClone(
13311375 return { ok: true };
13321376 }
13331377
1378 /**
1379 * Poll the fork's branch while the agent works, and open the pull the
1380 * moment it is first ahead of the base — a placeholder that says so and
1381 * links the run's own log. `landWork` finds it by branch when the run ends
1382 * and fills it in; nothing here ever opens a second one, since every tick
1383 * checks for an open pull on this branch before proposing one.
1384 *
1385 * Returns a stop function: clearing the timer is not enough on its own, a
1386 * tick already in flight when the run ends could otherwise open the pull
1387 * after `landWork` has already looked for it, so the stop function is
1388 * awaited too.
1389 */
1390 function watchForFirstPush(
1391 app: App,
1392 options: CrewOptions,
1393 repo: Repo,
1394 agent: Agent,
1395 issue: Issue,
1396 fork: Repo,
1397 branch: string,
1398 forkBare: string,
1399 bare: string,
1400 runId: string,
1401 write: (line: string) => void,
1402 ): () => Promise<void> {
1403 let opened = false;
1404 let inflight: Promise<void> = Promise.resolve();
1405 const tick = async (): Promise<void> => {
1406 if (opened) return;
1407 const already = listPulls(app.db, repo.id, {
1408 sealed: true,
1409 state: "open",
1410 limit: 200,
1411 }).some((p) => p.headRepoId === fork.id && p.headBranch === branch);
1412 if (already) {
1413 opened = true;
1414 return;
1415 }
1416 const remote = await resolveOid(forkBare, `refs/heads/${branch}`);
1417 if (remote === undefined) return;
1418 const base = await resolveOid(bare, `refs/heads/${repo.defaultBranch}`);
1419 const ahead =
1420 base === undefined ? 1 : await aheadCount(forkBare, base, remote);
1421 if (ahead <= 0) return;
1422 const result = await openPull(app, agent.user, repo, {
1423 title: issue.title,
1424 body: earlyPullBody(options.forgeUrl, repo, runId),
1425 baseBranch: repo.defaultBranch,
1426 headBranch: branch,
1427 headRepo: fork,
1428 });
1429 if (result.ok) {
1430 opened = true;
1431 write(
1432 `opened pull #${result.value.number} on the first push; the preview follows from here`,
1433 );
1434 }
1435 };
1436 const timer = setInterval(() => {
1437 inflight = tick().catch((error) =>
1438 log.error("could not open the pull on the first push", {
1439 run: runId,
1440 error: String(error),
1441 }),
1442 );
1443 }, WATCH_MS);
1444 inflight = tick().catch(() => {});
1445 return async () => {
1446 clearInterval(timer);
1447 await inflight;
1448 };
1449 }
1450
1451 /**
1452 * An early pull that turns out to lead nowhere — the run declined, or ended
1453 * with nothing to propose — is closed rather than left open with only its
1454 * placeholder in it. A pull with real content from a previous run is left
1455 * exactly alone.
1456 */
1457 function closeEarlyPull(
1458 app: App,
1459 agent: Agent,
1460 repo: Repo,
1461 fork: Repo,
1462 branch: string,
1463 why: string,
1464 write: (line: string) => void,
1465 ): void {
1466 const existing = listPulls(app.db, repo.id, {
1467 sealed: true,
1468 state: "open",
1469 limit: 200,
1470 }).find((p) => p.headRepoId === fork.id && p.headBranch === branch);
1471 if (existing === undefined || !isEarlyPull(existing)) return;
1472 const said = why.trim() || "nothing to propose";
1473 addComment(app, agent.user, repo, existing, said);
1474 setIssueState(app, agent.user, repo, existing, "closed");
1475 write(`closed pull #${existing.number}: ${said}`);
1476 }
1477
13341478 /**
13351479 * After the agent stops: push what it committed if it did not, open the
13361480 * pull if there is none, and report on the conversation — the agent's
@@ -1443,14 +1587,29 @@ async function landWork(
14431587 .filter((part): part is string => part !== undefined && part !== "")
14441588 .join("\n\n");
14451589
1590 const existing =
1591 pull ??
1592 listPulls(app.db, repo.id, { sealed: true, state: "open", limit: 200 }).find(
1593 (p) => p.headRepoId === fork.id && p.headBranch === branch,
1594 );
1595
14461596 if (proposed === 0) {
14471597 write(
14481598 "nothing to propose: the branch has no commits beyond the default branch",
14491599 );
1450 if (report !== "" && pull === undefined)
1600 // An early pull opened on a push that turned out to lead nowhere: it is
1601 // debris, not a proposal, so it is closed rather than left with only
1602 // its placeholder in it.
1603 if (existing !== undefined && isEarlyPull(existing)) {
1604 const said = report || "nothing to propose";
1605 addComment(app, agent.user, repo, existing, said);
1606 setIssueState(app, agent.user, repo, existing, "closed");
1607 write(`closed pull #${existing.number}: ${said.split("\n")[0]}`);
1608 } else if (report !== "" && pull === undefined) {
14511609 addComment(app, agent.user, repo, issue, report);
1452 else if (report !== "" && pull !== undefined)
1610 } else if (report !== "" && pull !== undefined) {
14531611 addComment(app, agent.user, repo, pull, report);
1612 }
14541613 const first = report.split("\n").find((l) => l.trim() !== "") ?? "";
14551614 return {
14561615 pushed: false,
@@ -1461,24 +1620,34 @@ async function landWork(
14611620 };
14621621 }
14631622
1464 const existing =
1465 pull ??
1466 listPulls(app.db, repo.id, { sealed: true, state: "open", limit: 200 }).find(
1467 (p) => p.headRepoId === fork.id && p.headBranch === branch,
1468 );
1469 if (existing !== undefined) {
1470 if (report !== "") addComment(app, agent.user, repo, existing, report);
1471 return {
1472 pushed: true,
1473 summary: `updated pull #${existing.number} (${remote?.slice(0, 7)})${committedForIt ? ", committing its leftover changes" : ""}`,
1474 };
1475 }
14761623 // No pull to update and yet the task is one: the pull it continues was
14771624 // merged, and this one follows it rather than closing it.
14781625 const trailer =
14791626 issue.kind === "pull"
14801627 ? `Continues #${issue.number}`
14811628 : `Closes #${issue.number}`;
1629 if (existing !== undefined) {
1630 // The pull opened while the agent was still working carried only a
1631 // placeholder; this is the run that gives it real content, so the
1632 // placeholder is replaced rather than commented under.
1633 if (isEarlyPull(existing)) {
1634 setBody(
1635 app.db,
1636 existing.id,
1637 `${report === "" ? "" : `${report}\n\n`}${trailer}`,
1638 );
1639 write(`filled in pull #${existing.number}, opened on its first push`);
1640 return {
1641 pushed: true,
1642 summary: `opened pull #${existing.number}${committedForIt ? ", committing its leftover changes" : ""}`,
1643 };
1644 }
1645 if (report !== "") addComment(app, agent.user, repo, existing, report);
1646 return {
1647 pushed: true,
1648 summary: `updated pull #${existing.number} (${remote?.slice(0, 7)})${committedForIt ? ", committing its leftover changes" : ""}`,
1649 };
1650 }
14821651 const body = `${report === "" ? "" : `${report}\n\n`}${trailer}`;
14831652 const opened = await openPull(app, agent.user, repo, {
14841653 title: issue.title,
test/crew.test.ts +103
@@ -205,6 +205,7 @@ fi
205205 if grep -q "The check on your pull" "${promptFile}"; then echo "daffodils" >> CREW.md; fi
206206 echo "work by the crew $(date +%s%N)" >> CREW.md
207207 git add -A && git commit -qm "crew work" && git push -q -u origin HEAD
208 if grep -q PUSH-SLOW "${promptFile}"; then sleep 4; fi
208209 echo '{"type":"assistant","message":{"content":[{"type":"text","text":"Added CREW.md."},{"type":"tool_use","name":"Read","input":{"file_path":"'"$(pwd)"'/CREW.md"}},{"type":"tool_use","name":"Bash","input":{"command":"cat /etc/hosts"}},{"type":"tool_use","name":"Bash","input":{"command":"git push"}}]}}'
209210 echo '{"type":"result","subtype":"success","is_error":false,"result":"Added CREW.md as asked.","total_cost_usd":0.01,"num_turns":3,"session_id":"fake-1","terminal_reason":"completed"}'
210211 `,
@@ -686,6 +687,108 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Added CREW
686687 expect(passed.summary).toMatch(/^check passed/);
687688 }, 120_000);
688689
690 test("a mid-run push opens the pull and its check before the run ends, with exactly one pull once it does", async () => {
691 const made = await createRepo(app, alice, {
692 name: "meadow",
693 visibility: "private",
694 });
695 if (!made.ok) throw new Error(String(made.error));
696 const meadow = made.value;
697 const seeded = await commitToBranch(app, alice, meadow, {
698 message: "Start",
699 files: [
700 { path: "README.md", content: "# meadow\n" },
701 {
702 path: "forge.json",
703 content:
704 '{"check": {"run": "grep -q daffodils CREW.md", "install": ""}}\n',
705 },
706 ],
707 });
708 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
709 expect(addToCrew(app, alice, meadow, "bot").ok).toBe(true);
710 const issue = openIssue(app, alice, meadow, {
711 title: "Sow clover",
712 body: "PUSH-SLOW: take your time before you say you are done.",
713 });
714 if (!issue.ok) throw new Error(String(issue.error));
715 expect(assignIssue(app, alice, meadow, issue.value, bot).ok).toBe(true);
716
717 const until = async <T>(
718 find: () => T | undefined,
719 timeoutMs = 20_000,
720 ): Promise<T> => {
721 const deadline = Date.now() + timeoutMs;
722 while (Date.now() < deadline) {
723 const found = find();
724 if (found !== undefined) return found;
725 await Bun.sleep(100);
726 }
727 throw new Error("did not happen in time");
728 };
729
730 const branch = `bot/${issue.value.number}-sow-clover`;
731 // The pull opens on the first push — well before the fake agent's
732 // deliberate sleep ends and the run settles.
733 const early = await until(() =>
734 listPulls(app.db, meadow.id, { state: "open" }).find(
735 (p) => p.headBranch === branch,
736 ),
737 );
738 expect(early.body).toContain("Work in progress");
739 const authoring = listRuns(app.db, meadow.id, { kind: "agent" }).find(
740 (r) => r.issueId === issue.value.id,
741 );
742 expect(authoring?.state).toBe("running");
743
744 // The check follows the early pull like any other, and fails (no
745 // daffodils yet) — but that must not engage the agent a second time
746 // while the run that will fix it is still going.
747 const checked = await until(() =>
748 listRuns(app.db, meadow.id, { kind: "check" }).find(
749 (r) => r.issueId === early.id && r.state === "failed",
750 ),
751 );
752 expect(checked).toBeDefined();
753 await Bun.sleep(300);
754 // No follow-up at all: not on the task issue, and not on the early
755 // pull either, whose own issue id differs from the run authoring it.
756 expect(
757 listRuns(app.db, meadow.id, { kind: "agent" }).filter(
758 (r) => r.reason === "check_failed",
759 ).length,
760 ).toBe(0);
761
762 const run = await until(() => {
763 const found = listRuns(app.db, meadow.id, { kind: "agent" }).find(
764 (r) => r.issueId === issue.value.id,
765 );
766 return found &&
767 (found.state === "ok" ||
768 found.state === "failed" ||
769 found.state === "cancelled")
770 ? found
771 : undefined;
772 }, 30_000);
773 expect(run.state).toBe("ok");
774 expect(run.summary).toMatch(/^opened pull #\d+/);
775
776 const openPulls = listPulls(app.db, meadow.id, { state: "open" }).filter(
777 (p) => p.headBranch === branch,
778 );
779 expect(openPulls.length).toBe(1);
780 expect(openPulls[0]!.id).toBe(early.id);
781 expect(openPulls[0]!.body).not.toContain("Work in progress");
782 expect(openPulls[0]!.body).toContain(`Closes #${issue.value.number}`);
783 // Nothing was spent on the suppressed follow-up: the budget the real
784 // one (once the check runs again on a real push) would use is intact.
785 expect(
786 listRuns(app.db, meadow.id, { kind: "agent" }).filter(
787 (r) => r.reason === "check_failed",
788 ).length,
789 ).toBe(0);
790 }, 90_000);
791
689792 test("a reviewer's run that posts its verdict is ok, though it pushes nothing", async () => {
690793 const made = await createAgent(app, alice, { username: "rev" });
691794 if (!made.ok) throw new Error(String(made.error));

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs