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

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

Closed opened this
Closed without merging

scout/forge:scout/1049-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.
6 files changed +345 −33
docs/APPS.md +6 −2
@@ -183,8 +183,12 @@ 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
186 2. **A pull appears** at the agent's first push — minutes in, not when its run
187 ends — marked as work in progress, with a preview that follows each push
188 after it. When the run ends, the agent's report replaces the placeholder;
189 a run that proposes nothing closes the pull again. A failed check on a
190 push the agent is still working on does not send it back to work (rule 7).
191 Open the preview (a link, or a QR code from a phone), use it. Leave feedback as review
188192 comments and a verdict. Request changes and the agent picks it up in the
189193 background; the preview updates when it pushes.
190194 3. **Approve, merge.** Production redeploys from the default branch. The
src/crew/brief.ts +1 −1
@@ -67,7 +67,7 @@ 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 "- Commit your work with clear messages and push: `git push`.",
70 "- Commit your work with clear messages and push: `git push`. Push a first working commit early and keep pushing as it grows: the pull and its preview come up on your first push, marked as work in progress, and follow every push after it, so a person can look at the app while you are still working.",
7171 "- 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.",
7272 "- 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.",
7373 "- Do not open the pull yourself, and do not merge anything.",
src/crew/dispatch.ts +18
@@ -515,6 +515,24 @@ function route(app: App, event: ForgeEvent): void {
515515 // is the agent's to look at.
516516 const agent = agentFor(app, issue);
517517 if (!agent) return;
518 // A push the author is still working on: its own run sees the
519 // failure when it runs the tests itself, and a second run on the same
520 // branch would only race it. Not counted against the budget below.
521 const authoring = getPull(app.db, repo.id, issue.number);
522 if (
523 authoring &&
524 listActive(app.db, "agent").some(
525 (r) =>
526 r.repoId === repo.id &&
527 r.state === "running" &&
528 r.branch === authoring.headBranch,
529 )
530 ) {
531 log.info("check failed while its author is still working", {
532 issue: issue.number,
533 });
534 return;
535 }
518536 // Bounded: after a few failed checks in a row the agent stops and a
519537 // person must speak (docs/APPS.md, rule 7).
520538 const since = lastHumanWord(app, issue, agent);
src/crew/early.ts added +143
@@ -0,0 +1,143 @@
1 /**
2 * The pull at the first push. An agent's work becomes a pull when its
3 * branch first lands in the agent's fork with a commit beyond the base, not
4 * when the run ends: the pull's preview is the first look at what was asked
5 * for. The pull says it is in progress until `landWork` (`runner.ts`) puts
6 * the agent's report in its place, and it is closed again if the run ends
7 * with nothing to propose.
8 */
9
10 import type { App } from "../app.ts";
11 import { addComment, editIssue, setIssueState } from "../actions/issues.ts";
12 import { openPull } from "../actions/pulls.ts";
13 import type { Agent } from "../core/agents.ts";
14 import type { Issue } from "../core/issues.ts";
15 import { listPulls, type Pull } from "../core/pulls.ts";
16 import type { Repo } from "../core/repos.ts";
17 import { aheadCount, resolveOid } from "../git/merge.ts";
18 import { createLog } from "../kernel/log.ts";
19
20 const log = createLog("crew");
21
22 /** First line of a pull's body while its run is still going. */
23 export const IN_PROGRESS = "<!-- forge:in-progress -->";
24
25 /** Whether a pull's body is still the placeholder. */
26 export const isInProgress = (body: string): boolean =>
27 body.startsWith(IN_PROGRESS);
28
29 /** The body of a pull opened mid-run. */
30 export function placeholderBody(
31 agent: Agent,
32 runLog: string,
33 ): string {
34 return `${IN_PROGRESS}\n**Work in progress.** @${agent.user.username} is still working on this; the pull and its preview follow each push. [The run's log](${runLog}).`;
35 }
36
37 /** The open pull whose head is this branch of this fork, if any. */
38 export function openPullOnBranch(
39 app: App,
40 repo: Repo,
41 fork: Repo,
42 branch: string,
43 ): Pull | undefined {
44 return listPulls(app.db, repo.id, {
45 sealed: true,
46 state: "open",
47 limit: 200,
48 }).find((p) => p.headRepoId === fork.id && p.headBranch === branch);
49 }
50
51 export interface Watch {
52 readonly app: App;
53 readonly repo: Repo;
54 readonly fork: Repo;
55 readonly agent: Agent;
56 readonly issue: Issue;
57 readonly branch: string;
58 readonly forkBare: string;
59 readonly bare: string;
60 /** Where the run's log can be read. */
61 readonly runLog: string;
62 readonly pollMs: number;
63 readonly write: (line: string) => void;
64 }
65
66 /**
67 * Look at the agent's fork every `pollMs` until the branch has a commit
68 * beyond the base, and open the pull for it then. `stop` ends the looking
69 * and waits for a look in flight, so the run's ending never races it.
70 */
71 export function watchFirstPush(w: Watch): () => Promise<void> {
72 let stopped = false;
73 let done = false;
74 let busy: Promise<void> = Promise.resolve();
75 const look = async (): Promise<void> => {
76 if (stopped || done) return;
77 try {
78 const head = await resolveOid(w.forkBare, `refs/heads/${w.branch}`);
79 const base = await resolveOid(w.bare, `refs/heads/${w.repo.defaultBranch}`);
80 if (head === undefined || base === undefined) return;
81 if ((await aheadCount(w.forkBare, base, head)) === 0) return;
82 if (stopped) return;
83 done = true;
84 if (openPullOnBranch(w.app, w.repo, w.fork, w.branch) !== undefined)
85 return;
86 const opened = await openPull(w.app, w.agent.user, w.repo, {
87 title: w.issue.title,
88 body: placeholderBody(w.agent, w.runLog),
89 baseBranch: w.repo.defaultBranch,
90 headBranch: w.branch,
91 headRepo: w.fork,
92 });
93 if (opened.ok) w.write(`opened pull #${opened.value.number} at the first push`);
94 else w.write(`could not open the pull early: ${JSON.stringify(opened.error)}`);
95 } catch (error) {
96 log.warn("looking for the first push failed", { error: String(error) });
97 }
98 };
99 const timer = setInterval(() => {
100 busy = busy.then(look);
101 }, w.pollMs);
102 return async () => {
103 stopped = true;
104 clearInterval(timer);
105 await busy;
106 };
107 }
108
109 /**
110 * The run ended with nothing to propose: a pull opened early for it is
111 * closed, with the reason, rather than left saying "in progress".
112 */
113 export function retireEarlyPull(
114 app: App,
115 agent: Agent,
116 repo: Repo,
117 fork: Repo,
118 branch: string,
119 why: string,
120 ): void {
121 const pull = openPullOnBranch(app, repo, fork, branch);
122 if (pull === undefined || !isInProgress(pull.body)) return;
123 addComment(
124 app,
125 agent.user,
126 repo,
127 pull,
128 `Closing this: the run ended with ${why}.`,
129 );
130 setIssueState(app, agent.user, repo, pull, "closed", { reason: "dropped" });
131 }
132
133 /** An early pull's placeholder, replaced by what the run came to. */
134 export function fillEarlyPull(
135 app: App,
136 agent: Agent,
137 repo: Repo,
138 pull: Pull,
139 body: string,
140 ): boolean {
141 if (!isInProgress(pull.body)) return false;
142 return editIssue(app, agent.user, repo, pull, { body }).ok;
143 }
src/crew/runner.ts +79 −30
@@ -106,6 +106,12 @@ import { historyHolds, scrubTree } from "./leak.ts";
106106 import { workdirFor } from "./workdir.ts";
107107 import { readersAmong, voiceOf } from "./direct.ts";
108108 import { feedbackSince } from "./news.ts";
109 import {
110 fillEarlyPull,
111 openPullOnBranch,
112 retireEarlyPull,
113 watchFirstPush,
114 } from "./early.ts";
109115 import { SKIP_SUMMARY, skipsFeedback } from "./guard.ts";
110116
111117 const log = createLog("crew");
@@ -120,6 +126,8 @@ export interface CrewOptions {
120126 /** Spend per run when the agent's own budget is 0. */
121127 readonly budgetUsd: number;
122128 readonly runTimeoutMs: number;
129 /** How often a run's fork is looked at for its first push; 2s when unset. */
130 readonly earlyPollMs?: number | undefined;
123131 /** A `CLAUDE_CONFIG_DIR` for runs, when the operator wants one. */
124132 readonly configDir?: string | undefined;
125133 /** Hosts an agent's shell may reach beyond the forge and the registry. */
@@ -983,20 +991,42 @@ async function work(
983991 `sandbox: off here${options.sandboxNote === undefined ? "" : ` — ${options.sandboxNote}`}; the shell runs unrestricted`,
984992 );
985993 const working = budget - reserve;
986 let result = await invoke(
987 prompt,
988 working,
989 brief.resuming ? previous?.sessionId : undefined,
990 );
991 if (
992 !result.ok &&
993 brief.resuming &&
994 result.turns === 0 &&
995 !signal.aborted &&
996 !isRateLimited(result)
997 ) {
998 write("the session could not be resumed; starting fresh");
999 result = await invoke(prompt, working, undefined);
994 // The pull opens at the agent's first push, not at the run's end.
995 const stopWatching =
996 reviewing || (pull !== undefined && !continuing)
997 ? async () => {}
998 : watchFirstPush({
999 app,
1000 repo,
1001 fork: fork.value,
1002 agent,
1003 issue,
1004 branch,
1005 forkBare,
1006 bare,
1007 runLog: `${options.forgeUrl.replace(/\/+$/, "")}/${repo.ownerName}/${repo.name}/runs/${run.id}`,
1008 pollMs: options.earlyPollMs ?? 2000,
1009 write,
1010 });
1011 let result: ClaudeOutcome;
1012 try {
1013 result = await invoke(
1014 prompt,
1015 working,
1016 brief.resuming ? previous?.sessionId : undefined,
1017 );
1018 if (
1019 !result.ok &&
1020 brief.resuming &&
1021 result.turns === 0 &&
1022 !signal.aborted &&
1023 !isRateLimited(result)
1024 ) {
1025 write("the session could not be resumed; starting fresh");
1026 result = await invoke(prompt, working, undefined);
1027 }
1028 } finally {
1029 await stopWatching();
10001030 }
10011031 noteRunProgress(app.db, run.id, {
10021032 sessionId: result.sessionId,
@@ -1124,6 +1154,14 @@ async function work(
11241154 if (declined) {
11251155 const why = result.result.replace(/^\s*DECLINED:?\s*/i, "").trim();
11261156 write(`declined: ${why.split("\n")[0] ?? ""}`);
1157 retireEarlyPull(
1158 app,
1159 agent,
1160 repo,
1161 fork.value,
1162 branch,
1163 "a decline, so nothing is proposed",
1164 );
11271165 // The reason lives on the run record (its summary) and the ledger
11281166 // line, never as a comment: a comment on an assigned issue is the
11291167 // thing that starts the next run.
@@ -1511,6 +1549,14 @@ async function landWork(
15111549 write(
15121550 "nothing to propose: the branch has no commits beyond the default branch",
15131551 );
1552 retireEarlyPull(
1553 app,
1554 agent,
1555 repo,
1556 fork,
1557 branch,
1558 "no commits beyond the default branch",
1559 );
15141560 if (report !== "" && pull === undefined)
15151561 addComment(app, agent.user, repo, issue, report);
15161562 else if (report !== "" && pull !== undefined)
@@ -1525,26 +1571,29 @@ async function landWork(
15251571 };
15261572 }
15271573
1528 const existing =
1529 pull ??
1530 listPulls(app.db, repo.id, {
1531 sealed: true,
1532 state: "open",
1533 limit: 200,
1534 }).find((p) => p.headRepoId === fork.id && p.headBranch === branch);
1535 if (existing !== undefined) {
1536 if (report !== "") addComment(app, agent.user, repo, existing, report);
1537 return {
1538 pushed: true,
1539 summary: `updated pull #${existing.number} (${remote?.slice(0, 7)})${committedForIt ? ", committing its leftover changes" : ""}`,
1540 };
1541 }
1542 // No pull to update and yet the task is one: the pull it continues was
1543 // merged, and this one follows it rather than closing it.
1574 const existing = pull ?? openPullOnBranch(app, repo, fork, branch);
15441575 const trailer =
15451576 issue.kind === "pull"
15461577 ? `Continues #${issue.number}`
15471578 : `Closes #${issue.number}`;
1579 if (existing !== undefined) {
1580 // An early pull's placeholder gives way to the report and the trailer.
1581 const filled = fillEarlyPull(
1582 app,
1583 agent,
1584 repo,
1585 existing,
1586 `${report === "" ? "" : `${report}\n\n`}${trailer}`,
1587 );
1588 if (!filled && report !== "")
1589 addComment(app, agent.user, repo, existing, report);
1590 return {
1591 pushed: true,
1592 summary: `${filled ? "opened" : "updated"} pull #${existing.number} (${remote?.slice(0, 7)})${committedForIt ? ", committing its leftover changes" : ""}`,
1593 };
1594 }
1595 // No pull to update and yet the task is one: the pull it continues was
1596 // merged, and this one follows it rather than closing it.
15481597 const body = `${report === "" ? "" : `${report}\n\n`}${trailer}`;
15491598 const opened = await openPull(app, agent.user, repo, {
15501599 title: issue.title,
test/crew.test.ts +98
@@ -203,6 +203,22 @@ if grep -q "You are the reviewer on this crew" "${promptFile}"; then
203203 echo '{"type":"result","subtype":"success","is_error":false,"result":"Reviewed.","total_cost_usd":0.004,"num_turns":1,"session_id":"fake-3","terminal_reason":"completed"}'
204204 exit 0
205205 fi
206 if grep -q PUSH-AND-WAIT "${promptFile}"; then
207 echo "first" >> WAIT.md
208 git add -A && git commit -qm "first working commit" && git push -q -u origin HEAD
209 while [ ! -f "${dataDir}/release" ]; do sleep 0.1; done
210 echo "second" >> WAIT.md
211 git add -A && git commit -qm "more" && git push -q origin HEAD
212 echo '{"type":"result","subtype":"success","is_error":false,"result":"Watered the beds.","total_cost_usd":0.01,"num_turns":3,"session_id":"fake-4","terminal_reason":"completed"}'
213 exit 0
214 fi
215 if grep -q PUSH-THEN-DECLINE "${promptFile}"; then
216 echo "first" >> ROSE.md
217 git add -A && git commit -qm "first working commit" && git push -q -u origin HEAD
218 while [ ! -f "${dataDir}/release2" ]; do sleep 0.1; done
219 echo '{"type":"result","subtype":"success","is_error":false,"result":"DECLINED: not after all.","total_cost_usd":0.005,"num_turns":1,"session_id":"fake-5","terminal_reason":"completed"}'
220 exit 0
221 fi
206222 if grep -q "The check on your pull" "${promptFile}"; then echo "daffodils" >> CREW.md; fi
207223 echo "work by the crew $(date +%s%N)" >> CREW.md
208224 # What a sandboxed shell leaves beside the code: a temp directory with a
@@ -222,6 +238,7 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Added CREW
222238 concurrency: 1,
223239 budgetUsd: 1,
224240 runTimeoutMs: 60_000,
241 earlyPollMs: 100,
225242 });
226243 const a = await createUser(app.db, {
227244 trusted: true,
@@ -745,4 +762,85 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Added CREW
745762 expect(readFileSync(argsFile, "utf8")).not.toContain("--resume");
746763 expect(listReviews(app.db, issue.id)).toHaveLength(1);
747764 }, 60_000);
765
766 test("the pull opens at the first push, in progress, and the run's end fills it in", async () => {
767 const issue = openIssue(app, alice, repo, {
768 title: "Water the beds",
769 body: "PUSH-AND-WAIT",
770 });
771 if (!issue.ok) throw new Error(String(issue.error));
772 expect(assignIssue(app, alice, repo, issue.value, bot).ok).toBe(true);
773 const branch = "bot/" + issue.value.number + "-water-the-beds";
774 const early = () =>
775 listPulls(app.db, repo.id, { state: "open", limit: 200 }).filter(
776 (p) => p.headBranch === branch,
777 );
778 const deadline = Date.now() + 30_000;
779 while (early().length === 0 && Date.now() < deadline) await Bun.sleep(50);
780 const [pull] = early();
781 if (pull === undefined) throw new Error("no pull at the first push");
782 // The run is still going, and the pull says so and links its log.
783 const during = listRuns(app.db, repo.id, { kind: "agent" }).find(
784 (r) => r.issueId === issue.value.id,
785 )!;
786 expect(during.state).toBe("running");
787 expect(pull.title).toBe("Water the beds");
788 expect(pull.body).toContain("Work in progress");
789 expect(pull.body).toContain(`/runs/${during.id}`);
790 expect(pull.body).not.toContain("Closes");
791
792 // A failed check on this push does not send the agent back to work
793 // while it is still on it, and spends none of the automatic tries.
794 const pullIssue = getIssue(app.db, repo.id, pull.number)!;
795 app.bus.append({
796 kind: "run.finished",
797 repoId: repo.id,
798 actorId: alice.id,
799 payload: {
800 kind: "check",
801 state: "failed",
802 issueId: pullIssue.id,
803 runId: "not-a-run",
804 },
805 });
806 await Bun.sleep(700);
807 expect(
808 listRuns(app.db, repo.id, { kind: "agent" }).filter(
809 (r) => r.reason === "check_failed" && r.issueId === pullIssue.id,
810 ),
811 ).toHaveLength(0);
812
813 writeFileSync(join(dataDir, "release"), "");
814 const done = await settled((r) => r.issueId === issue.value.id);
815 expect(done.state).toBe("ok");
816 expect(done.summary).toBe(`opened pull #${pull.number} (${done.summary.match(/\((\w+)\)/)![1]})`);
817 // One pull, with the report and the trailer where the placeholder was.
818 const after = early();
819 expect(after).toHaveLength(1);
820 expect(after[0]!.number).toBe(pull.number);
821 expect(after[0]!.body).not.toContain("Work in progress");
822 expect(after[0]!.body).toContain("Watered the beds.");
823 expect(after[0]!.body).toContain(`Closes #${issue.value.number}`);
824 }, 60_000);
825
826 test("a decline after an early pull closes it with a reason", async () => {
827 const issue = openIssue(app, alice, repo, {
828 title: "Tame the roses",
829 body: "PUSH-THEN-DECLINE",
830 });
831 if (!issue.ok) throw new Error(String(issue.error));
832 expect(assignIssue(app, alice, repo, issue.value, bot).ok).toBe(true);
833 const branch = "bot/" + issue.value.number + "-tame-the-roses";
834 const pulls = () =>
835 listPulls(app.db, repo.id, { state: "open", limit: 200 }).filter(
836 (p) => p.headBranch === branch,
837 );
838 const deadline = Date.now() + 30_000;
839 while (pulls().length === 0 && Date.now() < deadline) await Bun.sleep(50);
840 expect(pulls()).toHaveLength(1);
841 writeFileSync(join(dataDir, "release2"), "");
842 const done = await settled((r) => r.issueId === issue.value.id);
843 expect(done.summary).toStartWith("declined");
844 expect(pulls()).toHaveLength(0);
845 }, 60_000);
748846 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs