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

An agent's pull opens at its first push, marked in progress, and the run's end fills it in #1526

Parked opened this
Closed without merging

scout/forge:scout/1461-an-agent-s-pull-opens-at-its-first-push → main 10 commits fork 8 threads · 8 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +452 −33
README.md +13
@@ -443,6 +443,19 @@ off: no autonomy tick, no dispatch, no spend; checks still run and everything
443443 can still be read. The boot log and the studio's crew card say so. Set
444444 `FORGE_CREW_IN_PREVIEW=1` to run it anyway.
445445
446 **An agent's pull opens at its first push.** `src/crew/early.ts` watches the
447 agent's fork while the run works; once its branch has a commit beyond the
448 default branch (and the same history check `landWork` runs, for granted secret
449 values, passes) the pull opens with a body that starts "Work in progress" and
450 links the run's log, and its preview follows each push. Review waits while that
451 body stands: the run's end puts the report and the `Closes #N` line in the same
452 pull, and only then is it sent to a reviewer. A run that ends without landing
453 (a failure, a timeout, a cancel, a refused push) leaves the pull open with
454 "ended without finishing" and the reason in its body, unreviewed, until a later
455 run on the branch fills it in or a person closes it. A run that declines closes
456 its early pull instead: nothing it touched becomes a proposal. If the early
457 open fails, the run's end opens the pull as before.
458
446459 **Tell the crew from any page.** In a repository you may direct, the web palette
447460 (`:` in the browser) has a *Tell the crew* row. With the script it opens the thread's own
448461 comment box over the page you are on, without leaving it: `enter` sends (shift+
src/crew/early.ts added +184
@@ -0,0 +1,184 @@
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.
7 */
8
9 import type { App } from "../app.ts";
10 import { editIssue } from "../actions/issues.ts";
11 import { openPull } from "../actions/pulls.ts";
12 import { getAgent, type Agent } from "../core/agents.ts";
13 import type { Issue } from "../core/issues.ts";
14 import { setIssueState } from "../core/issues.ts";
15 import { listPulls, type Pull } from "../core/pulls.ts";
16 import { getForkOf, getRepoById, type Repo } from "../core/repos.ts";
17 import type { Run } from "../core/runs.ts";
18 import { aheadCount, resolveOid } from "../git/merge.ts";
19 import { createLog } from "../kernel/log.ts";
20
21 const log = createLog("crew");
22
outdated

This marker is only read inside this file. Review dispatch, checks and merge need to honour isInProgress, or a half-done pull gets reviewed and can land.

23 /** First line of a pull's body while its run has not put a report there. */
24 export const IN_PROGRESS = "<!-- forge:in-progress -->";
25
26 /** Whether a pull's body is still a placeholder. */
27 export const isInProgress = (body: string): boolean =>
28 body.startsWith(IN_PROGRESS);
29
30 /** The body of a pull opened mid-run. */
31 export function placeholderBody(agent: Agent, runLog: string): string {
32 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}).`;
33 }
34
35 /** The body of an early pull whose run ended without proposing it. */
outdated

A decline also ends up here, so the pushed work stays open as a proposal, against the decline contract. Close the pull when the run declined, and keep this open-and-marked body for failed and interrupted runs.

36 export function failedBody(agent: Agent, runLog: string, why: string): string {
37 return `${IN_PROGRESS}\n**This run ended without finishing:** ${why}. @${agent.user.username}'s pushes so far are here, unreviewed. [The run's log](${runLog}).`;
38 }
39
40 /** The open pull whose head is this branch of this fork, if any. */
41 export function openPullOnBranch(
42 app: App,
43 repo: Repo,
44 fork: Repo,
45 branch: string,
46 ): Pull | undefined {
47 return listPulls(app.db, repo.id, {
48 sealed: true,
49 state: "open",
50 limit: 200,
51 }).find((p) => p.headRepoId === fork.id && p.headBranch === branch);
52 }
53
54 export interface Watch {
55 readonly app: App;
56 readonly repo: Repo;
57 readonly fork: Repo;
58 readonly agent: Agent;
59 readonly issue: Issue;
60 readonly branch: string;
61 readonly forkBare: string;
62 readonly bare: string;
63 /** Where the run's log can be read. */
64 readonly runLog: string;
65 readonly pollMs: number;
66 /** Whether the commits between `base` and `head` may be shown; the run's own history check. */
67 readonly clears: (base: string, head: string) => Promise<boolean>;
68 readonly write: (line: string) => void;
69 }
70
71 /**
72 * Look at the agent's fork every `pollMs` until the branch has a commit
73 * beyond the base, and open the pull for it then. `stop` ends the looking
74 * and waits for a look in flight, so the run's ending never races it.
75 */
76 export function watchFirstPush(w: Watch): () => Promise<void> {
77 let stopped = false;
78 let done = false;
79 let refused: string | undefined;
80 let busy: Promise<void> = Promise.resolve();
81 const look = async (): Promise<void> => {
82 if (stopped || done) return;
83 try {
84 const head = await resolveOid(w.forkBare, `refs/heads/${w.branch}`);
85 const base = await resolveOid(
86 w.bare,
87 `refs/heads/${w.repo.defaultBranch}`,
88 );
89 if (head === undefined || base === undefined) return;
90 if ((await aheadCount(w.forkBare, base, head)) === 0) return;
91 if (stopped || head === refused) return;
92 // The agent's clone may not hold a head pushed by hand elsewhere; a
93 // check that cannot read the range is a refusal, not a pass.
94 const clear = await w.clears(base, head).catch(() => false);
95 if (!clear) {
96 refused = head;
97 w.write("not opening the pull early: the history check refused it");
98 return;
99 }
100 if (stopped) return;
101 done = true;
102 if (openPullOnBranch(w.app, w.repo, w.fork, w.branch) !== undefined)
103 return;
104 const opened = await openPull(w.app, w.agent.user, w.repo, {
105 title: w.issue.title,
106 body: placeholderBody(w.agent, w.runLog),
107 baseBranch: w.repo.defaultBranch,
108 headBranch: w.branch,
109 headRepo: w.fork,
outdated

This log line should say the pull will be opened at the run's end instead, since done is already set and nothing retries.

110 });
111 if (opened.ok)
112 w.write(`opened pull #${opened.value.number} at the first push`);
113 else
outdated

Nothing retries this because done is already set. Say in the line that the run's end will open the pull, so the log does not read as a lost pull.

114 w.write(
115 `could not open the pull early: ${JSON.stringify(opened.error)}; the run's end will open it`,
116 );
117 } catch (error) {
118 log.warn("looking for the first push failed", { error: String(error) });
119 }
outdated

This queues one more look every pollMs, even while one is still running. Skip the tick when a look is in flight, for example with an inFlight flag, so a slow history check cannot pile up looks.

120 };
121 // One look at a time: a slow history check never queues another behind it.
122 let looking = false;
123 const timer = setInterval(() => {
124 if (looking) return;
125 looking = true;
126 busy = busy.then(look).finally(() => {
127 looking = false;
128 });
129 }, w.pollMs);
130 return async () => {
131 stopped = true;
132 clearInterval(timer);
outdated

Skip this tick if a look is already in flight. Otherwise a slow history check lets the chain of looks grow without bound.

133 await busy;
134 };
135 }
136
137 /** An early pull's placeholder, replaced by what the run came to. */
138 export function fillEarlyPull(
outdated

The failed body keeps the marker, so the pull stays "in progress" and open. Decide explicitly whether it is held or closed, and test the choice.

139 app: App,
140 agent: Agent,
141 repo: Repo,
142 pull: Pull,
143 body: string,
144 ): boolean {
145 if (!isInProgress(pull.body)) return false;
146 return editIssue(app, agent.user, repo, pull, { body }).ok;
147 }
148
149 /**
150 * The run ended and its work did not land: an early pull still holding its
151 * placeholder says why instead of "in progress". The pull stays open and
152 * marked, its pushes unreviewed (`sendReview` waits while the marker is
153 * there), until a later run on the branch fills it in or a person closes it.
154 * Every ending passes through here once (`runOne`), so no reason is missed.
155 *
156 * A decline is the exception: nothing the agent touched becomes a proposal,
157 * so the pull is closed, with the same words as its body.
158 */
159 export function settleEarlyPull(
160 app: App,
outdated

A declined run should close the pull here, not leave it open with a live preview. Keep this text as a closing comment, and keep open-and-marked only for resumable endings.

161 run: Run,
162 forgeUrl: string,
163 why: string,
164 declined = false,
165 ): void {
166 if (run.reason === "review" || run.branch === "") return;
167 const repo = getRepoById(app.db, run.repoId);
168 const agent = run.actorId === null ? undefined : getAgent(app.db, run.actorId);
169 if (repo === undefined || agent === undefined) return;
170 const fork = getForkOf(app.db, agent.user.id, repo.id);
171 if (fork === undefined) return;
172 const pull = openPullOnBranch(app, repo, fork, run.branch);
173 if (pull === undefined || !isInProgress(pull.body)) return;
174 const runLog = `${forgeUrl.replace(/\/+$/, "")}/${repo.ownerName}/${repo.name}/runs/${run.id}`;
175 fillEarlyPull(app, agent, repo, pull, failedBody(agent, runLog, why));
176 if (!declined) return;
177 if (setIssueState(app.db, pull.id, "closed") !== undefined)
178 app.bus.append({
179 kind: "pull.closed",
180 repoId: repo.id,
181 actorId: agent.user.id,
182 payload: { number: pull.number },
183 });
184 }
src/crew/review.ts +3
@@ -29,6 +29,7 @@ import { checksForHead } from "../core/runs.ts";
2929 import { repoDir } from "../git/repos.ts";
3030 import { createLog } from "../kernel/log.ts";
3131 import { queueAgentRun } from "./dispatch.ts";
32 import { isInProgress } from "./early.ts";
3233 import { type Handover, handoverOf } from "./guard.ts";
3334
3435 const log = createLog("crew");
@@ -293,6 +294,8 @@ export async function sendToReview(
293294 now = new Date(),
294295 ): Promise<"none" | "done" | "sent" | "wait" | "lapsed" | "held"> {
295296 if (getHold(app.db, pull.id) !== undefined) return "held";
297 // An early pull whose run has not put its report there is not for review.
298 if (isInProgress(pull.body)) return "wait";
296299 const reviewers = reviewersOf(app.db, repo.id);
297300 if (reviewers.length === 0) return "none";
298301 const seen = reviewSummary(app.db, pull.id, pull.headOid);
src/crew/runner.ts +85 −31
@@ -49,6 +49,7 @@ import {
4949 checkSummary,
5050 claimRun,
5151 finishRun,
52 getRun,
5253 lastAgentRun,
5354 noteRunProgress,
5455 overranBefore,
@@ -115,6 +116,12 @@ import { historyHolds, scrubTree } from "./leak.ts";
115116 import { workdirFor } from "./workdir.ts";
116117 import { readersAmong, voiceOf } from "./direct.ts";
117118 import { feedbackSince } from "./news.ts";
119 import {
120 fillEarlyPull,
121 settleEarlyPull,
122 openPullOnBranch,
123 watchFirstPush,
124 } from "./early.ts";
118125 import { SKIP_SUMMARY, skipsFeedback } from "./guard.ts";
119126 import { passportEnv } from "./passport_env.ts";
120127
@@ -130,6 +137,8 @@ export interface CrewOptions {
130137 /** Spend per run when the agent's own budget is 0. */
131138 readonly budgetUsd: number;
132139 readonly runTimeoutMs: number;
140 /** How often a run's fork is looked at for its first push; 2s when unset. */
141 readonly earlyPollMs?: number | undefined;
133142 /** Scales the wait before a network retry; tests pass 0. @default 1 */
134143 readonly networkRetryScale?: number | undefined;
135144 /** How long a review run may take. @default BUDGETS.review */
@@ -371,6 +380,15 @@ export async function executeAgentRun(
371380 turns: outcome.turns,
372381 });
373382 if (done) announceRun(app, done);
383 // After the run is recorded: closing a pull stops a run still working on it.
384 // Whatever ended the run, an early pull still saying "in progress" says why.
385 settleEarlyPull(
386 app,
387 getRun(app.db, run.id) ?? claimed,
388 options.forgeUrl,
389 summary,
390 outcome.declined === true,
391 );
374392 return undefined;
375393 }
376394
@@ -467,6 +485,8 @@ type Outcome =
467485 | {
468486 readonly state: "ok" | "failed";
469487 readonly summary: string;
488 /** The agent declined: what it pushed is not proposed (`early.ts`). */
489 readonly declined?: true | undefined;
470490 /** When a run the provider cut short can go on (`interrupted.ts`). */
471491 readonly resumesAt?: Date | undefined;
472492 readonly sessionId?: string | undefined;
@@ -1042,20 +1062,52 @@ async function work(
10421062 `sandbox: off here${options.sandboxNote === undefined ? "" : ` — ${options.sandboxNote}`}; the shell runs unrestricted`,
10431063 );
10441064 const working = budget - reserve;
1045 let result = await invoke(
1046 prompt,
1047 working,
1048 brief.resuming ? previous?.sessionId : undefined,
1049 );
1050 if (
1051 !result.ok &&
1052 brief.resuming &&
1053 result.turns === 0 &&
1054 !signal.aborted &&
1055 !isRateLimited(result)
1056 ) {
1057 write("the session could not be resumed; starting fresh");
1058 result = await invoke(prompt, working, undefined);
1065 // The pull opens at the agent's first push, not at the run's end.
1066 const runLog = `${options.forgeUrl.replace(/\/+$/, "")}/${repo.ownerName}/${repo.name}/runs/${run.id}`;
1067 const stopWatching =
1068 reviewing || (pull !== undefined && !continuing)
1069 ? async () => {}
1070 : watchFirstPush({
1071 app,
1072 repo,
1073 fork: fork.value,
1074 agent,
1075 issue,
1076 branch,
1077 forkBare,
1078 bare,
1079 runLog,
1080 pollMs: options.earlyPollMs ?? 2000,
1081 // The same history check `landWork` runs, before a preview
1082 // can show what it would have refused to push.
1083 clears: async (base, head) =>
1084 !(await historyHolds(
1085 dir,
1086 `${base}..${head}`,
1087 Object.values(grant?.env ?? {}),
1088 env,
1089 )),
1090 write,
1091 });
1092 let result: ClaudeOutcome;
1093 try {
1094 result = await invoke(
1095 prompt,
1096 working,
1097 brief.resuming ? previous?.sessionId : undefined,
1098 );
1099 if (
1100 !result.ok &&
1101 brief.resuming &&
1102 result.turns === 0 &&
1103 !signal.aborted &&
1104 !isRateLimited(result)
1105 ) {
1106 write("the session could not be resumed; starting fresh");
1107 result = await invoke(prompt, working, undefined);
1108 }
1109 } finally {
1110 await stopWatching();
10591111 }
10601112 // A dropped connection says nothing about the work: ask again, in the
10611113 // same session when there is one, before the run is judged.
@@ -1187,7 +1239,7 @@ async function work(
11871239 };
11881240 noteRunProgress(app.db, run.id, { costUsd: result.costUsd });
11891241 }
1190 if (signal.aborted)
1242 if (signal.aborted) {
11911243 return {
11921244 state: "failed",
11931245 summary: "cancelled",
@@ -1195,6 +1247,7 @@ async function work(
11951247 costUsd: result.costUsd,
11961248 turns: result.turns,
11971249 };
1250 }
11981251
11991252 // The decline contract: an agent that should not do the task says so
12001253 // instead of guessing, and nothing it touched becomes a proposal.
@@ -1213,6 +1266,7 @@ async function work(
12131266 if (done.length > 0)
12141267 return {
12151268 state: "ok",
1269 declined: true,
12161270 summary: alreadyDoneSummary(done),
12171271 sessionId: result.sessionId,
12181272 costUsd: result.costUsd,
@@ -1223,6 +1277,7 @@ async function work(
12231277 // thing that starts the next run.
12241278 return {
12251279 state: "failed",
1280 declined: true,
12261281 summary: `declined: ${(why.split("\n")[0] ?? "").slice(0, 200)}`,
12271282 sessionId: result.sessionId,
12281283 costUsd: result.costUsd,
@@ -1656,27 +1711,26 @@ async function landWork(
16561711 };
16571712 }
16581713
1659 const existing =
1660 pull ??
1661 listPulls(app.db, repo.id, {
1662 sealed: true,
1663 state: "open",
1664 limit: 200,
1665 }).find((p) => p.headRepoId === fork.id && p.headBranch === branch);
1666 if (existing !== undefined) {
1667 if (report !== "") addComment(app, agent.user, repo, existing, report);
1668 return {
1669 pushed: true,
1670 summary: `updated pull #${existing.number} (${remote?.slice(0, 7)})${committedForIt ? ", committing its leftover changes" : ""}`,
1671 };
1672 }
1673 // No pull to update and yet the task is one: the pull it continues was
1674 // merged, and this one follows it rather than closing it.
16751714 const trailer =
16761715 issue.kind === "pull"
16771716 ? `Continues #${issue.number}`
16781717 : `Closes #${issue.number}`;
16791718 const body = `${report === "" ? "" : `${report}\n\n`}${trailer}`;
1719 const existing = pull ?? openPullOnBranch(app, repo, fork, branch);
1720 if (existing !== undefined) {
1721 // A pull opened at the first push has its placeholder replaced by the
1722 // report: that is the run's opening of it, so it reports `opened`. A
1723 // pull that was already the work's (a continuation) is `updated`.
1724 const filled = fillEarlyPull(app, agent, repo, existing, body);
1725 if (!filled && report !== "")
1726 addComment(app, agent.user, repo, existing, report);
1727 return {
1728 pushed: true,
1729 summary: `${filled ? "opened" : "updated"} pull #${existing.number} (${remote?.slice(0, 7)})${committedForIt ? ", committing its leftover changes" : ""}`,
1730 };
1731 }
1732 // No pull to update and yet the task is one: the pull it continues was
1733 // merged, and this one follows it rather than closing it.
16801734 const opened = await openPull(app, agent.user, repo, {
16811735 title: issue.title,
16821736 body,
test/crew.test.ts +122
@@ -12,6 +12,7 @@ import {
1212 readFileSync,
1313 realpathSync,
1414 symlinkSync,
15 writeFileSync,
1516 } from "node:fs";
1617 import { mkdtemp, rm } from "node:fs/promises";
1718 import { tmpdir } from "node:os";
@@ -26,6 +27,8 @@ import {
2627 import { sandboxAvailable } from "../src/crew/sandbox.ts";
2728 import { queueAgentRun, type CrewHandle } from "../src/crew/dispatch.ts";
2829 import { workdirFor } from "../src/crew/runner.ts";
30 import { isInProgress } from "../src/crew/early.ts";
31 import { abortAgentRun } from "../src/crew/running.ts";
2932 import { getAgentByName } from "../src/core/agents.ts";
3033 import { getIssue, listComments } from "../src/core/issues.ts";
3134 import { listPulls } from "../src/core/pulls.ts";
@@ -367,4 +370,123 @@ describe("the crew, with a stand-in Claude Code", () => {
367370 `pull #${closed.number} was closed before the run began`,
368371 );
369372 }, 30_000);
373
374 test("the pull opens at the first push, in progress, and the run's end fills in that same pull", async () => {
375 const issue = openIssue(app, alice, repo, {
376 title: "Water the beds",
377 body: "PUSH-AND-WAIT",
378 });
379 if (!issue.ok) throw new Error(String(issue.error));
380 expect(assignIssue(app, alice, repo, issue.value, bot).ok).toBe(true);
381 const branch = "bot/" + issue.value.number + "-water-the-beds";
382 const mine = () =>
383 listPulls(app.db, repo.id, { state: "open", limit: 200 }).filter(
384 (p) => p.headBranch === branch,
385 );
386 const deadline = Date.now() + 30_000;
387 while (mine().length === 0 && Date.now() < deadline) await Bun.sleep(50);
388 const [pull] = mine();
389 if (pull === undefined) throw new Error("no pull at the first push");
390 // The run is still going; the pull says so and links its log.
391 const during = listRuns(app.db, repo.id, { kind: "agent" }).find(
392 (r) => r.issueId === issue.value.id,
393 )!;
394 expect(during.state).toBe("running");
395 expect(pull.title).toBe("Water the beds");
396 expect(pull.baseBranch).toBe(repo.defaultBranch);
397 expect(pull.body).toContain("Work in progress");
398 expect(pull.body).toContain(`/runs/${during.id}`);
399 expect(pull.body).not.toContain("Closes");
400
401 writeFileSync(join(dataDir, "release"), "");
402 const done = await settled((r) => r.issueId === issue.value.id);
403 expect(done.state).toBe("ok");
404 // The summary says `opened`: the run's end is what opens the pull for review.
405 expect(done.summary).toStartWith(`opened pull #${pull.number} (`);
406 const after = mine();
407 expect(after).toHaveLength(1);
408 expect(after[0]!.number).toBe(pull.number);
409 expect(after[0]!.body).not.toContain("Work in progress");
410 expect(after[0]!.body).toContain("Watered the beds.");
411 expect(after[0]!.body).toContain(`Closes #${issue.value.number}`);
412 }, 60_000);
413
414 test("a run that declines after its first push marks the early pull as not finished", async () => {
415 const issue = openIssue(app, alice, repo, {
416 title: "Tame the roses",
417 body: "PUSH-THEN-DECLINE",
418 });
419 if (!issue.ok) throw new Error(String(issue.error));
420 expect(assignIssue(app, alice, repo, issue.value, bot).ok).toBe(true);
421 const branch = "bot/" + issue.value.number + "-tame-the-roses";
422 const mine = () =>
423 listPulls(app.db, repo.id, { state: "open", limit: 200 }).filter(
424 (p) => p.headBranch === branch,
425 );
426 const deadline = Date.now() + 30_000;
427 while (mine().length === 0 && Date.now() < deadline) await Bun.sleep(50);
428 expect(mine()).toHaveLength(1);
429 expect(mine()[0]!.body).toContain("Work in progress");
430 writeFileSync(join(dataDir, "release2"), "");
431 const done = await settled((r) => r.issueId === issue.value.id);
432 expect(done.summary).toStartWith("declined");
433 // Nothing a declined run touched stays a proposal: the pull is closed,
434 // and says why.
435 expect(mine()).toHaveLength(0);
436 const closed = listPulls(app.db, repo.id, { state: "closed", limit: 200 })
437 .filter((p) => p.headBranch === branch);
438 expect(closed).toHaveLength(1);
439 expect(closed[0]!.body).not.toContain("Work in progress");
440 expect(closed[0]!.body).toContain("ended without finishing");
441 }, 60_000);
442
443 test("a failed result whose pushed work lands fills the early pull in", async () => {
444 const issue = openIssue(app, alice, repo, {
445 title: "Trim the ferns",
446 body: "PUSH-THEN-FAIL",
447 });
448 if (!issue.ok) throw new Error(String(issue.error));
449 expect(assignIssue(app, alice, repo, issue.value, bot).ok).toBe(true);
450 const branch = "bot/" + issue.value.number + "-trim-the-ferns";
451 const mine = () =>
452 listPulls(app.db, repo.id, { state: "open", limit: 200 }).filter(
453 (p) => p.headBranch === branch,
454 );
455 const deadline = Date.now() + 30_000;
456 while (mine().length === 0 && Date.now() < deadline) await Bun.sleep(50);
457 expect(mine()[0]?.body).toContain("Work in progress");
458 writeFileSync(join(dataDir, "release3"), "");
459 await settled((r) => r.issueId === issue.value.id);
460 expect(mine()).toHaveLength(1);
461 expect(mine()[0]!.body).not.toContain("Work in progress");
462 expect(isInProgress(mine()[0]!.body)).toBe(false);
463 }, 60_000);
464
465 test("a cancelled run marks the early pull", async () => {
466 const issue = openIssue(app, alice, repo, {
467 title: "Cover the moss",
468 body: "PUSH-THEN-CANCEL",
469 });
470 if (!issue.ok) throw new Error(String(issue.error));
471 expect(assignIssue(app, alice, repo, issue.value, bot).ok).toBe(true);
472 const branch = "bot/" + issue.value.number + "-cover-the-moss";
473 const mine = () =>
474 listPulls(app.db, repo.id, { state: "open", limit: 200 }).filter(
475 (p) => p.headBranch === branch,
476 );
477 const deadline = Date.now() + 30_000;
478 while (mine().length === 0 && Date.now() < deadline) await Bun.sleep(50);
479 expect(mine()[0]?.body).toContain("Work in progress");
480 const run = listRuns(app.db, repo.id, { kind: "agent" }).find(
481 (r) => r.issueId === issue.value.id,
482 )!;
483 abortAgentRun(run.id);
484 const done = await settled((r) => r.issueId === issue.value.id);
485 expect(done.summary).toContain("cancelled");
486 expect(mine()).toHaveLength(1);
487 expect(mine()[0]!.body).not.toContain("Work in progress");
488 expect(mine()[0]!.body).toContain("cancelled");
489 // Left open and still marked, so no review is started on it.
490 expect(isInProgress(mine()[0]!.body)).toBe(true);
491 }, 60_000);
370492 });
test/helpers/crew-standin.ts +30
@@ -76,6 +76,35 @@ echo "half-done edit" > SHOULD-NOT-LAND.md
7676 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"}'
7777 exit 0
7878 fi
79 if grep -q PUSH-AND-WAIT "${promptFile}"; then
80 echo "first" >> WAIT.md
81 git add -A && git commit -qm "first working commit" && git push -q -u origin HEAD
82 while [ ! -f "${dataDir}/release" ]; do sleep 0.1; done
83 echo "second" >> WAIT.md
84 git add -A && git commit -qm "more" && git push -q origin HEAD
85 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"}'
86 exit 0
87 fi
88 if grep -q PUSH-THEN-DECLINE "${promptFile}"; then
89 echo "first" >> ROSE.md
90 git add -A && git commit -qm "first working commit" && git push -q -u origin HEAD
91 while [ ! -f "${dataDir}/release2" ]; do sleep 0.1; done
92 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"}'
93 exit 0
94 fi
95 if grep -q PUSH-THEN-FAIL "${promptFile}"; then
96 echo "first" >> FERN.md
97 git add -A && git commit -qm "first working commit" && git push -q -u origin HEAD
98 while [ ! -f "${dataDir}/release3" ]; do sleep 0.1; done
99 echo '{"type":"result","subtype":"error_max_turns","is_error":true,"result":"it broke","total_cost_usd":0.005,"num_turns":1,"session_id":"fake-6","terminal_reason":"max_turns"}'
100 exit 0
101 fi
102 if grep -q PUSH-THEN-CANCEL "${promptFile}"; then
103 echo "first" >> MOSS.md
104 git add -A && git commit -qm "first working commit" && git push -q -u origin HEAD
105 sleep 60
106 exit 0
107 fi
79108 if grep -q DONE-ON-MAIN "${promptFile}"; then
80109 tip=$(git rev-parse HEAD)
81110 if grep -q NAMED "${promptFile}"; then said="already done on main in $tip"
@@ -110,6 +139,7 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Added CREW
110139 concurrency: 1,
111140 budgetUsd: 1,
112141 runTimeoutMs: 60_000,
142 earlyPollMs: 100,
113143 networkRetryScale: 0,
114144 reviewBudgetMs: 4_000,
115145 });
test/review-wait.test.ts +15 −2
@@ -11,6 +11,9 @@ import { createApp, type App } from "../src/app.ts";
1111 import { addToCrew, createAgent } from "../src/actions/crew.ts";
1212 import { openPull } from "../src/actions/pulls.ts";
1313 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
14 import { IN_PROGRESS } from "../src/crew/early.ts";
15 import { sendToReview } from "../src/crew/review.ts";
16 import { listRuns } from "../src/core/runs.ts";
1417 import { setCrewRole } from "../src/core/agents.ts";
1518 import type { Pull } from "../src/core/pulls.ts";
1619 import type { Repo } from "../src/core/repos.ts";
@@ -38,7 +41,7 @@ describe("a green agent pull and its reviewer", () => {
3841 const wordCtx = (): WordCtx => ({ db: app.db }) as unknown as WordCtx;
3942
4043 /** An agent's open pull on branch `n`, its check green. */
41 const greenPull = async (n: number): Promise<Pull> => {
44 const greenPull = async (n: number, body = ""): Promise<Pull> => {
4245 await commitToBranch(app, getUserByName(app.db, "alice")!, repo, {
4346 branch: `bot/${n}-thing`,
4447 base: "main",
@@ -47,7 +50,7 @@ describe("a green agent pull and its reviewer", () => {
4750 });
4851 const opened = await openPull(app, getUserByName(app.db, "bot")!, repo, {
4952 title: `Bot did thing ${n}`,
50 body: "",
53 body,
5154 baseBranch: "main",
5255 headBranch: `bot/${n}-thing`,
5356 });
@@ -133,4 +136,14 @@ describe("a green agent pull and its reviewer", () => {
133136 });
134137 expect(await home()).toContain(`id="ask-look:${other.id}"`);
135138 });
139
140 test("an early pull still marked in progress is not sent to review", async () => {
141 const early = await greenPull(3, `${IN_PROGRESS}\n**Work in progress.**`);
142 expect(await sendToReview(app, repo, early)).toBe("wait");
143 expect(
144 listRuns(app.db, repo.id, { kind: "agent" }).filter(
145 (r) => r.issueId === early.id,
146 ),
147 ).toHaveLength(0);
148 });
136149 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs