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

An agent run's log says where its time went: one timing line at the first push and one at the end #3776

Parked opened this
Closed without merging

scout/forge:scout/3665-an-agent-run-s-log-says-where-its-time-w → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +120 −4
docs/CREW.md +4
@@ -50,3 +50,7 @@ strip shows the last hunt and the count of open findings.
5050 Left to a person on purpose: ingress routes at the edge are not in the
5151 database, and the sentinel opens no pull itself — a finding with a mechanical
5252 fix says what it is, and a run of the crew picks the issue up.
53
54 ## Where a run's time went (#3665)
55
56 A run's log carries two `timing:` lines, in the words the deploy log uses (`src/apps/timing.ts`): one when the pull opens at the first push (`first push Xs after the run started — clone … · brief … · harness to first push …`) and one when the run ends, with the laps so far plus `harness to the end` and, when the reserve was used, `wrap-up`.
src/apps/timing.ts +4 −3
@@ -37,10 +37,11 @@ export class Stopwatch {
3737
3838 /**
3939 * `timing: <what> 0.4s after the deploy started — turn 0.0s · checkout
40 * 0.3s · …`, every lap so far in the order it was taken.
40 * 0.3s · …`, every lap so far in the order it was taken. `since` names
41 * what the first number counts from; a crew run says "the run started".
4142 */
42 line(what: string): string {
43 line(what: string, since = "the deploy started"): string {
4344 const steps = this.laps.map((l) => `${l.name} ${seconds(l.ms)}`).join(" · ");
44 return `timing: ${what} ${seconds(this.elapsed())} after the deploy started${steps === "" ? "" : ` — ${steps}`}`;
45 return `timing: ${what} ${seconds(this.elapsed())} after ${since}${steps === "" ? "" : ` — ${steps}`}`;
4546 }
4647 }
src/crew/early.ts +3
@@ -73,6 +73,8 @@ export interface EarlyInput {
7373 /** A pull already stands for this work: nothing to open. */
7474 continuing: boolean;
7575 intervalMs?: number;
76 /** Called once, after the pull opened at the first push. */
77 onOpened?: () => void;
7678 }
7779
7880 /**
@@ -135,6 +137,7 @@ export function watchForPull(input: EarlyInput): EarlyPull {
135137 ? `opened pull #${opened.value.number} at the first push, in progress`
136138 : `could not open the pull early: ${JSON.stringify(opened.error)}`,
137139 );
140 if (opened.ok) input.onOpened?.();
138141 };
139142 const every = input.intervalMs ?? WATCH_MS;
140143 let looks = 0;
src/crew/runner.ts +16
@@ -31,7 +31,11 @@ import { forkRepo, sealedForkFor } from "../actions/repos.ts";
3131 import { announceRun } from "../actions/runs.ts";
3232 import { previewEnv } from "../apps/data.ts";
3333 import { appsRuntime } from "../apps/runtime.ts";
34 <<<<<<< HEAD
35 import { Stopwatch } from "../apps/timing.ts";
36 =======
3437 import { ownApp, ownAppUrls } from "./app_hosts.ts";
38 >>>>>>> origin/main
3539 import { crewRole, getAgent, type Agent } from "../core/agents.ts";
3640 import { getAppByRepo, type AppRecord } from "../core/apps.ts";
3741 import {
@@ -171,6 +175,8 @@ export interface CrewOptions {
171175 readonly sandboxNote?: string | undefined;
172176 /** Milliseconds between the crew's ticks; tests pass a small one. @default 5000 */
173177 readonly tickMs?: number | undefined;
178 /** The clock a run's `timing:` lines read; tests pass a fake. @default Date.now */
179 readonly now?: (() => number) | undefined;
174180 }
175181
176182 export { crewRoot, workdirFor } from "./workdir.ts";
@@ -745,6 +751,7 @@ async function work(
745751 meter: Meter,
746752 ): Promise<Outcome> {
747753 const began = new Date().toISOString();
754 const clock = new Stopwatch(options.now);
748755 const repo = getRepoById(app.db, run.repoId);
749756 const issue =
750757 run.issueId === null ? undefined : getIssueById(app.db, run.issueId);
@@ -901,6 +908,7 @@ async function work(
901908 run.attempt > 0,
902909 );
903910 if (!prepared.ok) return { state: "failed", summary: prepared.error };
911 clock.lap("clone");
904912
905913 // What the agent is told.
906914 // The session belongs to the task, which spans the issue and the pull
@@ -1256,6 +1264,7 @@ async function work(
12561264 `sandbox: off here${options.sandboxNote === undefined ? "" : ` — ${options.sandboxNote}`}; the shell runs unrestricted`,
12571265 );
12581266 const working = budget - reserve;
1267 clock.lap("brief");
12591268 if (!reviewing)
12601269 early = watchForPull({
12611270 app,
@@ -1271,6 +1280,10 @@ async function work(
12711280 write,
12721281 variantGroup: run.variantGroup,
12731282 continuing: pullStands,
1283 onOpened: () => {
1284 clock.lap("harness to first push");
1285 write(clock.line("first push", "the run started"));
1286 },
12741287 });
12751288 let result = await invoke(
12761289 prompt,
@@ -1347,6 +1360,7 @@ async function work(
13471360 : { prompt: "Continue where you stopped.", sessionId: last.sessionId },
13481361 );
13491362 await early?.stop();
1363 clock.lap("harness to the end");
13501364 const down = outagePause(result, result.costUsd);
13511365 if (down !== undefined) return down;
13521366 noteRunProgress(app.db, run.id, {
@@ -1473,7 +1487,9 @@ async function work(
14731487 turns: result.turns + wrapped.turns,
14741488 };
14751489 noteRunProgress(app.db, run.id, { costUsd: result.costUsd });
1490 clock.lap("wrap-up");
14761491 }
1492 write(clock.line("run ended", "the run started"));
14771493 if (signal.aborted)
14781494 return {
14791495 state: "failed",
test/crew-run-timing.test.ts added +87
@@ -0,0 +1,87 @@
1 /**
2 * A crew run's log says where its time went (#3665): one `timing:` line when
3 * the pull opens at the first push, one when the run ends, laps in order.
4 */
5
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { existsSync, rmSync, writeFileSync } from "node:fs";
8 import { join } from "node:path";
9 import { addComment, assignIssue, openIssue } from "../src/actions/issues.ts";
10 import { listPulls } from "../src/core/pulls.ts";
11 import { listRuns } from "../src/core/runs.ts";
12 import { readRunLog } from "../src/runs/log.ts";
13 import {
14 agentRunSettled,
15 startStandInCrew,
16 stopStandInCrew,
17 type StandInCrew,
18 } from "./helpers/crew-standin.ts";
19
20 describe("the crew run's timing lines", () => {
21 let standIn: StandInCrew;
22
23 beforeAll(async () => {
24 // Every reading of the clock is one second later than the last.
25 let t = 0;
26 standIn = await startStandInCrew({ now: () => (t += 1000) });
27 }, 30_000);
28
29 afterAll(() => stopStandInCrew(standIn));
30
31 test("the first push and the end each get a line with their laps in order", async () => {
32 const { app, alice, bot, repo, dataDir } = standIn;
33 rmSync(join(dataDir, "release"), { force: true });
34 const issue = openIssue(app, alice, repo, {
35 title: "Plant tulips",
36 body: "LINGER-ME by the shed.",
37 });
38 if (!issue.ok) throw new Error("issue");
39 expect(assignIssue(app, alice, repo, issue.value, bot).ok).toBe(true);
40 const branch = `bot/${issue.value.number}-plant-tulips`;
41 let runId = "";
42 const lines = (): string[] =>
43 runId === ""
44 ? []
45 : readRunLog(dataDir, runId).lines.filter((l) => l.includes("timing:"));
46 const deadline = Date.now() + 20_000;
47 while (runId === "" && Date.now() < deadline) {
48 runId =
49 listRuns(app.db, repo.id, { issueId: issue.value.id }).find((r) => r.branch === branch)?.id ?? "";
50 await Bun.sleep(100);
51 }
52 while (lines().length === 0 && Date.now() < deadline) await Bun.sleep(100);
53 expect(lines()[0]).toMatch(
54 /^timing: first push \d+\.\ds after the run started — clone 1\.0s · brief 1\.0s · harness to first push \d+\.\ds$/,
55 );
56 expect(existsSync(join(dataDir, "release"))).toBe(false);
57
58 writeFileSync(join(dataDir, "release"), "");
59 await agentRunSettled(app, repo, (r) => r.branch === branch);
60 const all = lines();
61 expect(all.length).toBe(2);
62 expect(all[1]).toMatch(
63 /^timing: run ended \d+\.\ds after the run started — clone 1\.0s · brief 1\.0s · harness to first push \d+\.\ds · harness to the end \d+\.\ds$/,
64 );
65
66 // A follow-up on the pull that stands opens no pull: its log has the end
67 // line and no first-push line.
68 const pull = listPulls(app.db, repo.id, { state: "open", limit: 200 }).find(
69 (p) => p.headBranch === branch,
70 );
71 if (pull === undefined) throw new Error("pull");
72 expect(addComment(app, alice, repo, pull, "Please add more.").ok).toBe(true);
73 const idle = Date.now() + 30_000;
74 let follow = "";
75 while (follow === "" && Date.now() < idle) {
76 follow =
77 listRuns(app.db, repo.id, { kind: "agent" }).find(
78 (r) => r.id !== runId && (r.state === "ok" || r.state === "failed"),
79 )?.id ?? "";
80 await Bun.sleep(100);
81 }
82 expect(follow).not.toBe("");
83 const second = readRunLog(dataDir, follow).lines.filter((l) => l.includes("timing:"));
84 expect(second.length).toBe(1);
85 expect(second[0]).toMatch(/^timing: run ended /);
86 }, 60_000);
87 });
test/helpers/crew-standin.ts +6 −1
@@ -43,7 +43,11 @@ export interface StandInCrew {
4343
4444 /** A forge with checks and a crew whose Claude Code is the stand-in. */
4545 export async function startStandInCrew(
46 options: { readonly reviewBudgetMs?: number; readonly tickMs?: number } = {},
46 options: {
47 readonly reviewBudgetMs?: number;
48 readonly tickMs?: number;
49 readonly now?: () => number;
50 } = {},
4751 ): Promise<StandInCrew> {
4852 const dataDir = await mkdtemp(join(tmpdir(), "forge-crew-"));
4953 const app = createApp({ dataDir, port: 0 });
@@ -179,6 +183,7 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Added CREW
179183 networkRetryScale: 0,
180184 reviewBudgetMs: options.reviewBudgetMs ?? 4_000,
181185 ...(options.tickMs === undefined ? {} : { tickMs: options.tickMs }),
186 ...(options.now === undefined ? {} : { now: options.now }),
182187 });
183188 const a = await createUser(app.db, {
184189 origin: "seed",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs