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

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

Closed opened this
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
8 files changed +479 −137
docs/APPS.md +5 −4
@@ -110,10 +110,11 @@ 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**, not at the end of its run,
114 with a preview that follows every push after. Open the preview (a link,
115 or a QR code from a phone), use it. Leave feedback as review comments and
116 a verdict. Request changes and the agent picks it up in the background;
117 the preview updates when it pushes.
117118 3. **Approve, merge.** Production redeploys from the default branch. The
118119 production data directory is untouched — the notes you took, the rows
119120 your app wrote, are all still there. The preview and its copied data are
src/core/issues.ts +17
@@ -113,6 +113,23 @@ export function setAssignee(
113113 return changed > 0 ? getIssueById(db, issueId) : undefined;
114114 }
115115
116 /**
117 * Replace an issue's (or pull's) body outright. Used once, to turn an early
118 * pull's "still working" placeholder into the agent's own report when the
119 * run that opened it lands — every other edit is a comment, not a rewrite.
120 */
121 export function setBody(
122 db: Database,
123 issueId: string,
124 body: string,
125 ): Issue | undefined {
126 db.query(
127 `UPDATE issue SET body = ?2, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
128 WHERE id = ?1`,
129 ).run(issueId, body);
130 return getIssueById(db, issueId);
131 }
132
116133 /**
117134 * Several conversations by id, in one query per chunk — what a run list
118135 * needs to name the pull each run is about without a read per row.
src/core/runs.ts +21
@@ -396,6 +396,27 @@ export function hasQueuedRun(
396396 );
397397 }
398398
399 /**
400 * The unfinished run pushing to one branch, if any. A pull opened on its
401 * first push (runner.ts) shares no issue id with the run authoring it — that
402 * run began against the task issue, before the pull existed — so `branch`
403 * is how a check on the pull finds its still-running author.
404 */
405 export function activeRunForBranch(
406 db: Database,
407 kind: RunKind,
408 repoId: string,
409 branch: string,
410 ): Run | undefined {
411 const row = db
412 .query<
413 RunRow,
414 [RunKind, string, string]
415 >("SELECT * FROM run WHERE state IN ('queued','running') AND kind = ?1 AND repo_id = ?2 AND branch = ?3 ORDER BY id LIMIT 1")
416 .get(kind, repoId, branch);
417 return row ? toRun(row) : undefined;
418 }
419
399420 /**
400421 * The checks on a pull: the deploy runs at its current head, newest first.
401422 * Older heads are history — a push makes new runs — so a caller that wants
src/crew/brief.ts +4 −3
@@ -39,9 +39,10 @@ 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 "- 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.",
4243 "- Commit your work with clear messages and push: `git push`.",
43 "- 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 "- 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, but not while you are still working — only once you have stopped. Run the same command yourself before you push.",
45 "- 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.",
4546 "- Do not open the pull yourself, and do not merge anything.",
4647 "- 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.",
4748 "",
@@ -155,7 +156,7 @@ function taskBody(input: TaskInput): string {
155156 }
156157 out.push(
157158 "",
158 `Work it on the branch \`${input.branch}\` and push when done.`,
159 `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.`,
159160 );
160161 return out.join("\n");
161162 }
src/crew/dispatch.ts +26
@@ -24,6 +24,7 @@ import { getRepoById, type Repo } from "../core/repos.ts";
2424 import { listReviews } from "../core/reviews.ts";
2525 import {
2626 activeRunFor,
27 activeRunForBranch,
2728 hasQueuedRun,
2829 automaticRunsSince,
2930 cancelRun,
@@ -295,6 +296,31 @@ function route(app: App, event: ForgeEvent): void {
295296 return;
296297 }
297298 if (event.payload["state"] !== "failed") return;
299 // A push mid-run — the pull opened on its first commit (runner.ts) —
300 // failing its check is not feedback: the run that made it is still
301 // going and will push again. Engaging the agent now would answer a
302 // draft, and spend a try from the bounded few it gets (rule 7,
303 // docs/APPS.md) on nothing it asked to be judged on yet.
304 // An early pull shares no issue id with the run authoring it — that
305 // run began against the task issue, before the pull existed — so its
306 // branch, not its issue id, is what finds a still-running author.
307 const authoringPull = getPull(app.db, repo.id, issue.number);
308 const authoring =
309 activeRunFor(app.db, "agent", issue.id) ??
310 (authoringPull
311 ? activeRunForBranch(
312 app.db,
313 "agent",
314 repo.id,
315 authoringPull.headBranch,
316 )
317 : undefined);
318 if (authoring !== undefined && authoring.state === "running") {
319 log.info("check failed on a work-in-progress push; still running", {
320 issue: issue.number,
321 });
322 return;
323 }
298324 // A preview that failed to deploy, or a check that failed: either
299325 // is the agent's to look at.
300326 const agent = agentFor(app, issue);
src/crew/runner.ts +295 −130
@@ -14,7 +14,7 @@
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 { addComment, setIssueState } from "../actions/issues.ts";
1818 import { openPull } from "../actions/pulls.ts";
1919 import { forkRepo } from "../actions/repos.ts";
2020 import { announceRun } from "../actions/runs.ts";
@@ -26,6 +26,7 @@ import {
2626 getIssue,
2727 getIssueById,
2828 listComments,
29 setBody,
2930 type Issue,
3031 } from "../core/issues.ts";
3132 import { getPull, listPulls, type Pull } from "../core/pulls.ts";
@@ -113,6 +114,23 @@ const RESERVE = 0.15;
113114 /** ...and never less than this: a wrap-up that cannot run a test is none. */
114115 const RESERVE_FLOOR_USD = 0.5;
115116
117 /** How often the run's clone is polled for a branch worth a pull, while the agent works. */
118 const WATCH_MS = 2_000;
119
120 /**
121 * The first line of a pull opened before the run that will fill it in has
122 * finished. Its presence, and nothing else, is what tells `landWork` this
123 * pull is still a placeholder rather than a person's or an earlier run's.
124 */
125 const IN_PROGRESS_MARKER =
126 "_Work in progress — the agent is still on it; this pull will update as it pushes._";
127
128 const earlyPullBody = (forgeUrl: string, repo: Repo, runId: string): string =>
129 `${IN_PROGRESS_MARKER}\n\n[Follow the run](${forgeUrl}/${repo.ownerName}/${repo.name}/runs/${runId}).`;
130
131 const isEarlyPull = (pull: Pull): boolean =>
132 pull.body.trim().startsWith(IN_PROGRESS_MARKER);
133
116134 /**
117135 * What a run keeps for its wrap-up: fifteen percent of the budget, at
118136 * least fifty cents, never more than half — a budget too small to split
@@ -496,132 +514,160 @@ async function work(
496514 `sandbox: off here${options.sandboxNote === undefined ? "" : ` — ${options.sandboxNote}`}; the shell runs unrestricted`,
497515 );
498516 const working = budget - reserve;
499 let result = await invoke(
500 prompt,
501 working,
502 brief.resuming ? previous?.sessionId : undefined,
503 );
504 if (
505 !result.ok &&
506 brief.resuming &&
507 result.turns === 0 &&
508 !signal.aborted &&
509 !isRateLimited(result)
510 ) {
511 write("the session could not be resumed; starting fresh");
512 result = await invoke(prompt, working, undefined);
513 }
514 noteRunProgress(app.db, run.id, {
515 sessionId: result.sessionId,
516 costUsd: result.costUsd,
517 });
518 write(
519 `claude: ${result.reason}, ${result.turns} turns, $${result.costUsd.toFixed(2)}`,
520 );
521
522 // The provider's refusal, not the agent's failure: the run pauses with
523 // its clone and session as they are, and goes on when the limit lifts.
524 // A limit that never lifts is not waited on forever.
525 if (isRateLimited(result) && !signal.aborted) {
526 const said = (
527 result.result.split("\n").find((l) => l.trim() !== "") ?? result.reason
528 ).slice(0, 160);
529 if (run.attempt < MAX_PAUSES) {
530 const at = resumeAt(result.result, new Date());
531 return {
532 state: "paused",
533 summary: `paused: ${said}; resumes ${whenText(at)}`,
534 resumeAt: at.toISOString(),
535 sessionId: result.sessionId,
536 costUsd: result.costUsd,
537 };
538 }
539 write(`paused ${MAX_PAUSES} times already; not waiting again`);
540 }
541
542 // The reserve: the same session gets one more turn, to land what exists
543 // rather than to keep working. Its ending is the run's ending, with the
544 // whole spend; the pull says where the work stopped.
545 let stoppedAt: number | undefined;
546 if (
547 result.reason === BUDGET_REACHED &&
548 result.sessionId !== "" &&
549 !signal.aborted &&
550 Date.now() < deadline
551 ) {
552 stoppedAt = result.costUsd;
553 write(`claude: wrapping up with the reserve, $${reserve.toFixed(2)}`);
554 const wrapped = await invoke(wrapUpPrompt(), reserve, result.sessionId);
555 write(
556 `claude: ${wrapped.reason}, ${wrapped.turns} turns, $${wrapped.costUsd.toFixed(2)}`,
557 );
558 result = {
559 ...wrapped,
560 sessionId: wrapped.sessionId || result.sessionId,
561 costUsd: result.costUsd + wrapped.costUsd,
562 turns: result.turns + wrapped.turns,
563 };
564 noteRunProgress(app.db, run.id, { costUsd: result.costUsd });
565 }
566 if (signal.aborted)
567 return {
568 state: "failed",
569 summary: "cancelled",
570 sessionId: result.sessionId,
571 costUsd: result.costUsd,
572 turns: result.turns,
573 };
574
575 // The decline contract: an agent that should not do the task says so
576 // instead of guessing, and nothing it touched becomes a proposal.
577 const declined = /^\s*DECLINED\b/i.test(result.result);
578 if (declined) {
579 const why = result.result.replace(/^\s*DECLINED:?\s*/i, "").trim();
580 write(`declined: ${why.split("\n")[0] ?? ""}`);
581 const target = pull ?? issue;
582 addComment(
583 app,
584 agent.user,
585 repo,
586 target,
587 `Declined: ${why || "no reason given"}`,
588 );
589 return {
590 state: "failed",
591 summary: `declined: ${(why.split("\n")[0] ?? "").slice(0, 200)}`,
592 sessionId: result.sessionId,
593 costUsd: result.costUsd,
594 turns: result.turns,
595 };
596 }
597
598 // Bookkeeping the agent does not have to get right.
599 const landed = await landWork(
517 // The branch, in the fork, is polled while the agent works: the moment
518 // it is first ahead of the base is the moment a person could look at
519 // something, so the pull opens then rather than at the end of the run.
520 const stopWatch = watchForFirstPush(
600521 app,
601522 options,
602523 repo,
603524 agent,
604525 issue,
605 continuing ? undefined : pull,
606526 fork.value,
607527 branch,
608 dir,
609528 forkBare,
610529 bare,
611 { ...gitAuth, ...identity },
612 result.result,
613 stoppedAt === undefined
614 ? undefined
615 : `Budget reached at $${stoppedAt.toFixed(2)}; this is where it stopped.`,
530 run.id,
616531 write,
617532 );
618 return {
619 state: result.ok || landed.pushed ? "ok" : "failed",
620 summary: landed.summary + (result.ok ? "" : ` (${result.reason})`),
621 sessionId: result.sessionId,
622 costUsd: result.costUsd,
623 turns: result.turns,
624 };
533 try {
534 let result = await invoke(
535 prompt,
536 working,
537 brief.resuming ? previous?.sessionId : undefined,
538 );
539 if (
540 !result.ok &&
541 brief.resuming &&
542 result.turns === 0 &&
543 !signal.aborted &&
544 !isRateLimited(result)
545 ) {
546 write("the session could not be resumed; starting fresh");
547 result = await invoke(prompt, working, undefined);
548 }
549 noteRunProgress(app.db, run.id, {
550 sessionId: result.sessionId,
551 costUsd: result.costUsd,
552 });
553 write(
554 `claude: ${result.reason}, ${result.turns} turns, $${result.costUsd.toFixed(2)}`,
555 );
556
557 // The provider's refusal, not the agent's failure: the run pauses with
558 // its clone and session as they are, and goes on when the limit lifts.
559 // A limit that never lifts is not waited on forever.
560 if (isRateLimited(result) && !signal.aborted) {
561 const said = (
562 result.result.split("\n").find((l) => l.trim() !== "") ??
563 result.reason
564 ).slice(0, 160);
565 if (run.attempt < MAX_PAUSES) {
566 const at = resumeAt(result.result, new Date());
567 return {
568 state: "paused",
569 summary: `paused: ${said}; resumes ${whenText(at)}`,
570 resumeAt: at.toISOString(),
571 sessionId: result.sessionId,
572 costUsd: result.costUsd,
573 };
574 }
575 write(`paused ${MAX_PAUSES} times already; not waiting again`);
576 }
577
578 // The reserve: the same session gets one more turn, to land what exists
579 // rather than to keep working. Its ending is the run's ending, with the
580 // whole spend; the pull says where the work stopped.
581 let stoppedAt: number | undefined;
582 if (
583 result.reason === BUDGET_REACHED &&
584 result.sessionId !== "" &&
585 !signal.aborted &&
586 Date.now() < deadline
587 ) {
588 stoppedAt = result.costUsd;
589 write(`claude: wrapping up with the reserve, $${reserve.toFixed(2)}`);
590 const wrapped = await invoke(wrapUpPrompt(), reserve, result.sessionId);
591 write(
592 `claude: ${wrapped.reason}, ${wrapped.turns} turns, $${wrapped.costUsd.toFixed(2)}`,
593 );
594 result = {
595 ...wrapped,
596 sessionId: wrapped.sessionId || result.sessionId,
597 costUsd: result.costUsd + wrapped.costUsd,
598 turns: result.turns + wrapped.turns,
599 };
600 noteRunProgress(app.db, run.id, { costUsd: result.costUsd });
601 }
602 if (signal.aborted)
603 return {
604 state: "failed",
605 summary: "cancelled",
606 sessionId: result.sessionId,
607 costUsd: result.costUsd,
608 turns: result.turns,
609 };
610
611 // Stopped here, and only here: whatever the agent's own commits did
612 // to the branch is already in, so the watcher's job is done, and what
613 // comes next — closing the early pull, or landWork opening or filling
614 // it in — is bookkeeping the watcher must not race to do first.
615 await stopWatch();
616
617 // The decline contract: an agent that should not do the task says so
618 // instead of guessing, and nothing it touched becomes a proposal.
619 const declined = /^\s*DECLINED\b/i.test(result.result);
620 if (declined) {
621 const why = result.result.replace(/^\s*DECLINED:?\s*/i, "").trim();
622 write(`declined: ${why.split("\n")[0] ?? ""}`);
623 const target = pull ?? issue;
624 addComment(
625 app,
626 agent.user,
627 repo,
628 target,
629 `Declined: ${why || "no reason given"}`,
630 );
631 closeEarlyPull(app, agent, repo, fork.value, branch, why, write);
632 return {
633 state: "failed",
634 summary: `declined: ${(why.split("\n")[0] ?? "").slice(0, 200)}`,
635 sessionId: result.sessionId,
636 costUsd: result.costUsd,
637 turns: result.turns,
638 };
639 }
640
641 // Bookkeeping the agent does not have to get right.
642 const landed = await landWork(
643 app,
644 options,
645 repo,
646 agent,
647 issue,
648 continuing ? undefined : pull,
649 fork.value,
650 branch,
651 dir,
652 forkBare,
653 bare,
654 { ...gitAuth, ...identity },
655 result.result,
656 stoppedAt === undefined
657 ? undefined
658 : `Budget reached at $${stoppedAt.toFixed(2)}; this is where it stopped.`,
659 write,
660 );
661 return {
662 state: result.ok || landed.pushed ? "ok" : "failed",
663 summary: landed.summary + (result.ok ? "" : ` (${result.reason})`),
664 sessionId: result.sessionId,
665 costUsd: result.costUsd,
666 turns: result.turns,
667 };
668 } finally {
669 await stopWatch();
670 }
625671 } finally {
626672 deleteToken(app.db, agent.user.id, token.id);
627673 }
@@ -770,6 +816,104 @@ async function prepareClone(
770816 return { ok: true };
771817 }
772818
819 /**
820 * Poll the fork's branch while the agent works, and open the pull the
821 * moment it is first ahead of the base — a placeholder that says so and
822 * links the run's own log. `landWork` finds it by branch when the run ends
823 * and fills it in; nothing here ever opens a second one, since every tick
824 * checks for an open pull on this branch before proposing one.
825 *
826 * Returns a stop function: clearing the timer is not enough on its own, a
827 * tick already in flight when the run ends could otherwise open the pull
828 * after `landWork` has already looked for it, so the stop function is
829 * awaited too.
830 */
831 function watchForFirstPush(
832 app: App,
833 options: CrewOptions,
834 repo: Repo,
835 agent: Agent,
836 issue: Issue,
837 fork: Repo,
838 branch: string,
839 forkBare: string,
840 bare: string,
841 runId: string,
842 write: (line: string) => void,
843 ): () => Promise<void> {
844 let opened = false;
845 let inflight: Promise<void> = Promise.resolve();
846 const tick = async (): Promise<void> => {
847 if (opened) return;
848 const already = listPulls(app.db, repo.id, {
849 state: "open",
850 limit: 200,
851 }).some((p) => p.headRepoId === fork.id && p.headBranch === branch);
852 if (already) {
853 opened = true;
854 return;
855 }
856 const remote = await resolveOid(forkBare, `refs/heads/${branch}`);
857 if (remote === undefined) return;
858 const base = await resolveOid(bare, `refs/heads/${repo.defaultBranch}`);
859 const ahead =
860 base === undefined ? 1 : await aheadCount(forkBare, base, remote);
861 if (ahead <= 0) return;
862 const result = await openPull(app, agent.user, repo, {
863 title: issue.title,
864 body: earlyPullBody(options.forgeUrl, repo, runId),
865 baseBranch: repo.defaultBranch,
866 headBranch: branch,
867 headRepo: fork,
868 });
869 if (result.ok) {
870 opened = true;
871 write(
872 `opened pull #${result.value.number} on the first push; the preview follows from here`,
873 );
874 }
875 };
876 const timer = setInterval(() => {
877 inflight = tick().catch((error) =>
878 log.error("could not open the pull on the first push", {
879 run: runId,
880 error: String(error),
881 }),
882 );
883 }, WATCH_MS);
884 inflight = tick().catch(() => {});
885 return async () => {
886 clearInterval(timer);
887 await inflight;
888 };
889 }
890
891 /**
892 * An early pull that turns out to lead nowhere — the run declined, or ended
893 * with nothing to propose — is closed rather than left open with only its
894 * placeholder in it. A pull with real content from a previous run is left
895 * exactly alone.
896 */
897 function closeEarlyPull(
898 app: App,
899 agent: Agent,
900 repo: Repo,
901 fork: Repo,
902 branch: string,
903 why: string,
904 write: (line: string) => void,
905 ): void {
906 const existing = listPulls(app.db, repo.id, {
907 state: "open",
908 limit: 200,
909 }).find((p) => p.headRepoId === fork.id && p.headBranch === branch);
910 if (existing === undefined || !isEarlyPull(existing)) return;
911 const said = why.trim() || "nothing to propose";
912 addComment(app, agent.user, repo, existing, said);
913 setIssueState(app, agent.user, repo, existing, "closed");
914 write(`closed pull #${existing.number}: ${said}`);
915 }
916
773917 /**
774918 * After the agent stops: push what it committed if it did not, open the
775919 * pull if there is none, and report on the conversation — the agent's
@@ -858,15 +1002,29 @@ async function landWork(
8581002 const report = [message.trim(), note]
8591003 .filter((part): part is string => part !== undefined && part !== "")
8601004 .join("\n\n");
1005 const existing =
1006 pull ??
1007 listPulls(app.db, repo.id, { state: "open", limit: 200 }).find(
1008 (p) => p.headRepoId === fork.id && p.headBranch === branch,
1009 );
8611010
8621011 if (proposed === 0) {
8631012 write(
8641013 "nothing to propose: the branch has no commits beyond the default branch",
8651014 );
866 if (report !== "" && pull === undefined)
1015 // An early pull opened on a push that turned out to lead nowhere: it is
1016 // debris, not a proposal, so it is closed rather than left with only
1017 // its placeholder in it.
1018 if (existing !== undefined && isEarlyPull(existing)) {
1019 const said = report || "nothing to propose";
1020 addComment(app, agent.user, repo, existing, said);
1021 setIssueState(app, agent.user, repo, existing, "closed");
1022 write(`closed pull #${existing.number}: ${said.split("\n")[0]}`);
1023 } else if (report !== "" && pull === undefined) {
8671024 addComment(app, agent.user, repo, issue, report);
868 else if (report !== "" && pull !== undefined)
1025 } else if (report !== "" && pull !== undefined) {
8691026 addComment(app, agent.user, repo, pull, report);
1027 }
8701028 const first = report.split("\n").find((l) => l.trim() !== "") ?? "";
8711029 return {
8721030 pushed: false,
@@ -877,24 +1035,31 @@ async function landWork(
8771035 };
8781036 }
8791037
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) {
886 if (report !== "") addComment(app, agent.user, repo, existing, report);
887 return {
888 pushed: true,
889 summary: `updated pull #${existing.number} (${remote?.slice(0, 7)})${committedForIt ? ", committing its leftover changes" : ""}`,
890 };
891 }
8921038 // No pull to update and yet the task is one: the pull it continues was
8931039 // merged, and this one follows it rather than closing it.
8941040 const trailer =
8951041 issue.kind === "pull"
8961042 ? `Continues #${issue.number}`
8971043 : `Closes #${issue.number}`;
1044 if (existing !== undefined) {
1045 // The pull opened while the agent was still working carried only a
1046 // placeholder; this is the run that gives it real content, so the
1047 // placeholder is replaced rather than commented under.
1048 if (isEarlyPull(existing)) {
1049 const body = `${report === "" ? "" : `${report}\n\n`}${trailer}`;
1050 setBody(app.db, existing.id, body);
1051 write(`filled in pull #${existing.number}, opened on its first push`);
1052 return {
1053 pushed: true,
1054 summary: `opened pull #${existing.number}${committedForIt ? ", committing its leftover changes" : ""}`,
1055 };
1056 }
1057 if (report !== "") addComment(app, agent.user, repo, existing, report);
1058 return {
1059 pushed: true,
1060 summary: `updated pull #${existing.number} (${remote?.slice(0, 7)})${committedForIt ? ", committing its leftover changes" : ""}`,
1061 };
1062 }
8981063 const body = `${report === "" ? "" : `${report}\n\n`}${trailer}`;
8991064 const opened = await openPull(app, agent.user, repo, {
9001065 title: issue.title,
test/apps.test.ts +8
@@ -496,6 +496,14 @@ describe("apps: production, previews, data, gates, crew", () => {
496496 r.commitOid === committed.value.commitOid,
497497 );
498498 expect(done.state).toBe("ok");
499 const merged = await mergePull(
500 app,
501 alice,
502 repo,
503 getPull(app.db, repo.id, opened.value.number)!,
504 "merge",
505 );
506 expect(merged.ok).toBe(true);
499507 }, 30_000);
500508
501509 test("the crew: an agent reads and writes its repo, never the default branch, never a merge", async () => {
test/crew.test.ts +103
@@ -104,6 +104,7 @@ fi
104104 if grep -q "The check on your pull" "${promptFile}"; then echo "daffodils" >> CREW.md; fi
105105 echo "work by the crew $(date +%s%N)" >> CREW.md
106106 git add -A && git commit -qm "crew work" && git push -q -u origin HEAD
107 if grep -q PUSH-SLOW "${promptFile}"; then sleep 4; fi
107108 echo '{"type":"assistant","message":{"content":[{"type":"text","text":"Added CREW.md."},{"type":"tool_use","name":"Bash","input":{"command":"git push"}}]}}'
108109 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"}'
109110 `,
@@ -574,4 +575,106 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Added CREW
574575 );
575576 expect(passed.summary).toMatch(/^check passed/);
576577 }, 120_000);
578
579 test("a mid-run push opens the pull and its check before the run ends, with exactly one pull once it does", async () => {
580 const made = await createRepo(app, alice, {
581 name: "meadow",
582 visibility: "private",
583 });
584 if (!made.ok) throw new Error(String(made.error));
585 const meadow = made.value;
586 const seeded = await commitToBranch(app, alice, meadow, {
587 message: "Start",
588 files: [
589 { path: "README.md", content: "# meadow\n" },
590 {
591 path: "forge.json",
592 content:
593 '{"check": {"run": "grep -q daffodils CREW.md", "install": ""}}\n',
594 },
595 ],
596 });
597 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
598 expect(addToCrew(app, alice, meadow, "bot").ok).toBe(true);
599 const issue = openIssue(app, alice, meadow, {
600 title: "Sow clover",
601 body: "PUSH-SLOW: take your time before you say you are done.",
602 });
603 if (!issue.ok) throw new Error(String(issue.error));
604 expect(assignIssue(app, alice, meadow, issue.value, bot).ok).toBe(true);
605
606 const until = async <T>(
607 find: () => T | undefined,
608 timeoutMs = 20_000,
609 ): Promise<T> => {
610 const deadline = Date.now() + timeoutMs;
611 while (Date.now() < deadline) {
612 const found = find();
613 if (found !== undefined) return found;
614 await Bun.sleep(100);
615 }
616 throw new Error("did not happen in time");
617 };
618
619 const branch = `bot/${issue.value.number}-sow-clover`;
620 // The pull opens on the first push — well before the fake agent's
621 // deliberate sleep ends and the run settles.
622 const early = await until(() =>
623 listPulls(app.db, meadow.id, { state: "open" }).find(
624 (p) => p.headBranch === branch,
625 ),
626 );
627 expect(early.body).toContain("Work in progress");
628 const authoring = listRuns(app.db, meadow.id, { kind: "agent" }).find(
629 (r) => r.issueId === issue.value.id,
630 );
631 expect(authoring?.state).toBe("running");
632
633 // The check follows the early pull like any other, and fails (no
634 // daffodils yet) — but that must not engage the agent a second time
635 // while the run that will fix it is still going.
636 const checked = await until(() =>
637 listRuns(app.db, meadow.id, { kind: "check" }).find(
638 (r) => r.issueId === early.id && r.state === "failed",
639 ),
640 );
641 expect(checked).toBeDefined();
642 await Bun.sleep(300);
643 // No follow-up at all: not on the task issue, and not on the early
644 // pull either, whose own issue id differs from the run authoring it.
645 expect(
646 listRuns(app.db, meadow.id, { kind: "agent" }).filter(
647 (r) => r.reason === "check_failed",
648 ).length,
649 ).toBe(0);
650
651 const run = await until(() => {
652 const found = listRuns(app.db, meadow.id, { kind: "agent" }).find(
653 (r) => r.issueId === issue.value.id,
654 );
655 return found &&
656 (found.state === "ok" ||
657 found.state === "failed" ||
658 found.state === "cancelled")
659 ? found
660 : undefined;
661 }, 30_000);
662 expect(run.state).toBe("ok");
663 expect(run.summary).toMatch(/^opened pull #\d+/);
664
665 const openPulls = listPulls(app.db, meadow.id, { state: "open" }).filter(
666 (p) => p.headBranch === branch,
667 );
668 expect(openPulls.length).toBe(1);
669 expect(openPulls[0]!.id).toBe(early.id);
670 expect(openPulls[0]!.body).not.toContain("Work in progress");
671 expect(openPulls[0]!.body).toContain(`Closes #${issue.value.number}`);
672 // Nothing was spent on the suppressed follow-up: the budget the real
673 // one (once the check runs again on a real push) would use is intact.
674 expect(
675 listRuns(app.db, meadow.id, { kind: "agent" }).filter(
676 (r) => r.reason === "check_failed",
677 ).length,
678 ).toBe(0);
679 }, 90_000);
577680 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs