Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

464 lines · 23.2 KBRaw History
1import { describe, expect, it, vi } from "vitest";
2import { DatabaseSync } from "node:sqlite";
3import { parseWorkflow, type Workflow } from "@diffinery/workflow-yaml";
4import { Actions, canonicalJson } from "../../src/repo/actions.js";
5import { REPO_SCHEMA, migrateRepoSchema } from "../../src/repo/schema.js";
6import { logKeys } from "../../src/lib/storage-keys.js";
7import { uuidNumber, uuidPattern, workflowNumber } from "../../src/http/gh.js";
8import { Runtime } from "../../src/repo/runtime.js";
9import { testD1 } from "./stubs/d1.js";
10import type { RepoDO } from "../../src/repo/RepoDO.js";
11import type { Env } from "../../src/env.js";
12import type { Caller } from "../../src/repo/types.js";
13
14/** The Durable Object's SqlStorage over node:sqlite: exec(query, ...bindings) with toArray() and one(). */
15function sqlStorage() {
16 const db = new DatabaseSync(":memory:");
17 return {
18 exec(query: string, ...args: unknown[]) {
19 const params = args.map((a) => (a === undefined ? null : a)) as Array<string | number | null>;
20 let rows: unknown[] = [];
21 if (!params.length && query.trim().replace(/;\s*$/, "").includes(";")) db.exec(query);
22 else rows = db.prepare(query).all(...params);
23 return {
24 toArray: () => rows as never[],
25 one: () => {
26 if (rows.length !== 1) throw new Error(`expected one row, got ${rows.length}`);
27 return rows[0] as never;
28 },
29 };
30 },
31 };
32}
33
34const parse = (yaml: string, path: string): Workflow => {
35 const { workflow, errors } = parseWorkflow(yaml, path);
36 if (!workflow) throw new Error(errors.map((e) => e.message).join("; "));
37 return workflow;
38};
39
40const WORKFLOW = `name: w
41on: push
42jobs:
43 lint:
44 runs-on: ubuntu-latest
45 steps: [{ run: echo lint }]
46 test:
47 runs-on: ubuntu-latest
48 strategy:
49 matrix:
50 os: [a, b, c]
51 steps: [{ run: echo test }]
52 deploy:
53 needs: test
54 runs-on: ubuntu-latest
55 steps: [{ run: echo deploy }]
56 report:
57 needs: lint
58 runs-on: ubuntu-latest
59 steps: [{ run: echo report }]
60`;
61
62type Row = { id: string; run_id: string; job_key: string; name: string; status: string; conclusion: string | null; matrix: string; carried_from: string | null; container: string | null };
63type Outcome = (job: Row) => "success" | "failure";
64
65const ADA: Caller = { id: "u1", login: "ada", kind: "user", role: "write" };
66
67/**
68 * Actions over an in-memory repository and D1, with the workflow files given, and a stand-in for
69 * RunWorkflow (`drive`) that walks the job graph and finishes each started job as `outcome` says.
70 */
71function fixture(files: Record<string, string>) {
72 const sql = sqlStorage();
73 sql.exec(REPO_SCHEMA);
74 migrateRepoSchema(sql as unknown as SqlStorage);
75 const DB = testD1();
76 DB.sqlite.prepare("INSERT INTO accounts (id, login, kind, status, created_at) VALUES ('acme', 'acme', 'org', 'active', ?)").run(new Date().toISOString());
77 const objects = new Map<string, string>();
78 const started: string[] = [];
79 const checks: Array<{ name: string; status: string; conclusion?: string | null; runId?: string; jobId?: string }> = [];
80 const repo = {
81 sql,
82 meta: { repoId: "r", owner: "acme", ownerId: "acme", ownerKind: "org", name: "app", defaultBranch: "main" },
83 headRef: "refs/heads/main",
84 getRef: () => null,
85 // Like Collab.upsertCheck: one check run per commit and name.
86 upsertCheck: (c: (typeof checks)[number] & { sha: string }) => {
87 checks.push(c);
88 sql.exec("DELETE FROM checks WHERE sha = ? AND name = ?", c.sha, c.name);
89 sql.exec("INSERT INTO checks (id, sha, name, status, conclusion, run_id, job_id) VALUES (?, ?, ?, ?, ?, ?, ?)", `${c.sha}/${c.name}`, c.sha, c.name, c.status, c.conclusion ?? null, c.runId ?? null, c.jobId ?? null);
90 },
91 broadcast: () => {},
92 emit: () => {},
93 deploys: { jobCompleted: () => {}, protection: () => null },
94 protectionFor: (branch: string) => (branch === "release" ? {} : null),
95 runtime: { sweepJob: async () => {} },
96 policy: { agentOrigin: () => false },
97 alarmBy: () => {},
98 } as unknown as RepoDO;
99 const env = {
100 DB,
101 PUBLIC_URL: "https://d.test",
102 BUCKET: {
103 put: async (k: string, v: string) => void objects.set(k, v),
104 get: async (k: string) => (objects.has(k) ? { json: async () => JSON.parse(objects.get(k)!) } : null),
105 delete: async (keys: string | string[]) => void [keys].flat().forEach((k) => objects.delete(k)),
106 },
107 RUNNER: { idFromName: (n: string) => n, get: (n: string) => ({ startJob: async () => void started.push(n), stopJob: async () => {} }) },
108 RUN_WORKFLOW: { create: async () => {}, get: async () => ({ sendEvent: async () => {} }) },
109 } as unknown as Env;
110 const actions = new Actions(repo, env);
111 const workflows = Object.entries(files).map(([path, text]) => ({ path, workflow: parse(text, path), errors: [] as string[] }));
112 Object.defineProperty(actions, "loadWorkflows", { value: async () => workflows });
113 Object.defineProperty(actions, "loadCalled", { value: async (uses: string) => ({ workflow: workflows.find((w) => w.path === uses.replace(/^\.\//, ""))!.workflow, source: { repoId: null, sha: "abc" } }) });
114 const internal = actions as unknown as { completeJob(id: string, c: unknown): Promise<void> };
115 const jobs = (runId: string) => sql.exec("SELECT * FROM jobs WHERE run_id = ? ORDER BY rowid", runId).toArray() as Row[];
116 const leg = (j: Row) => `${j.job_key}${j.matrix === "{}" ? "" : ` ${Object.values(JSON.parse(j.matrix)).join(",")}`}`;
117 /** Each job (by `leg`) with its conclusion, and whether it was kept from an earlier attempt. */
118 const summary = (runId: string) => Object.fromEntries(jobs(runId).map((j) => [leg(j), `${j.conclusion}${j.carried_from ? " (kept)" : ""}`]));
119
120 async function drive(runId: string, outcome: Outcome) {
121 const plan = await actions.plan(runId);
122 expect(plan.error).toBeUndefined();
123 const done = new Set<string>();
124 while (done.size < plan.jobs.length) {
125 const next = plan.jobs.find((n) => !done.has(n.key) && n.needs.every((k) => done.has(k)))!;
126 await actions.startJobKey(runId, next.key);
127 // Finish the key's started legs one at a time, in order, as their runners would.
128 for (;;) {
129 const running = jobs(runId).find((j) => j.job_key === next.key && j.status === "waiting");
130 if (!running) break;
131 await internal.completeJob(running.id, { conclusion: outcome(running), outputs: {} });
132 }
133 expect(jobs(runId).filter((j) => j.job_key === next.key && j.status !== "completed")).toEqual([]);
134 done.add(next.key);
135 }
136 return actions.finishRun(runId);
137 }
138
139 async function firstRun(outcome: Outcome, ref = "refs/heads/main") {
140 const run = (await actions.createRun(workflows[0]!.workflow, { event: "push", ref, sha: "abc", payload: {}, caller: ADA, title: "first" }))!;
141 await drive(run.id, outcome);
142 return run.id;
143 }
144 return { sql, actions, started, checks, objects, jobs, leg, summary, drive, firstRun };
145}
146
147const failB: Outcome = (j) => (j.job_key === "test" && JSON.parse(j.matrix).os === "b" ? "failure" : "success");
148const allPass: Outcome = () => "success";
149
150describe("re-running failed jobs", () => {
151 it("keeps the legs that passed and re-runs the failed and cancelled ones, with what depends on them", async () => {
152 const f = fixture({ ".github/workflows/w.yml": WORKFLOW });
153 const first = await f.firstRun(failB);
154 // fail-fast: b's failure cancelled c, and deploy (needs test) was skipped.
155 expect(f.summary(first)).toEqual({ lint: "success", "test a": "success", "test b": "failure", "test c": "cancelled", deploy: "skipped", report: "success" });
156 expect(f.actions.getRun(first).conclusion).toBe("failure");
157
158 const before = f.started.length;
159 const second = await f.actions.rerun(first, ADA, "failed");
160 expect(second).toMatchObject({ attempt: 2, number: f.actions.getRun(first).number });
161 const done = await f.drive(second.id, allPass);
162 expect(done.conclusion).toBe("success");
163 expect(f.summary(second.id)).toEqual({ lint: "success (kept)", report: "success (kept)", "test a": "success (kept)", "test b": "success", "test c": "success", deploy: "success" });
164 // Only the re-run legs started a container.
165 const ran = f.jobs(second.id).filter((j) => !j.carried_from);
166 expect(f.started.slice(before).sort()).toEqual(ran.map((j) => `job-${j.id}`).sort());
167 // A kept job is a copy of the one that ran, pointing at it.
168 const old = Object.fromEntries(f.jobs(first).map((j) => [f.leg(j), j]));
169 for (const j of f.jobs(second.id).filter((x) => x.carried_from)) {
170 expect(j.carried_from).toBe(old[f.leg(j)]!.id);
171 expect(j.name).toBe(old[f.leg(j)]!.name);
172 }
173 // Kept jobs use no minutes.
174 const usage = (await (f.actions as unknown as { env: Env }).env.DB.prepare("SELECT id FROM compute_usage").all<{ id: string }>()).results.map((r) => r.id);
175 for (const j of f.jobs(second.id)) expect(usage.includes(j.id)).toBe(!j.carried_from);
176 // The kept jobs' check runs now point at the new attempt, completed with their conclusion.
177 const lintCheck = f.checks.filter((c) => c.name === "w / lint").at(-1)!;
178 expect(lintCheck).toMatchObject({ status: "completed", conclusion: "success", runId: second.id });
179 });
180
181 it("refuses a run without failed jobs, and one that hasn't finished", async () => {
182 const f = fixture({ ".github/workflows/w.yml": WORKFLOW });
183 const first = await f.firstRun(allPass);
184 await expect(f.actions.rerun(first, ADA, "failed")).rejects.toMatchObject({ status: 409, detail: "this run has no failed jobs to re-run" });
185 const second = await f.actions.rerun(first, ADA);
186 await expect(f.actions.rerun(second.id, ADA, "failed")).rejects.toMatchObject({ status: 409 });
187 await expect(f.actions.rerunJob(f.jobs(first)[0]!.id, ADA)).resolves.toMatchObject({ attempt: 2 });
188 });
189
190 it("checks permissions like a full re-run", async () => {
191 const f = fixture({ ".github/workflows/w.yml": WORKFLOW });
192 const first = await f.firstRun(failB);
193 await expect(f.actions.rerun(first, { ...ADA, role: "read" }, "failed")).rejects.toMatchObject({ status: 403 });
194 await expect(f.actions.rerun(first, { ...ADA, id: "job:x" }, "failed")).rejects.toMatchObject({ status: 403, detail: "a workflow's GITHUB_TOKEN cannot re-run workflows" });
195 await expect(f.actions.rerunJob(f.jobs(first)[0]!.id, { ...ADA, role: "read" })).rejects.toMatchObject({ status: 403 });
196 });
197
198 it("re-runs a full run as before", async () => {
199 const f = fixture({ ".github/workflows/w.yml": WORKFLOW });
200 const first = await f.firstRun(failB);
201 const second = await f.actions.rerun(first, ADA);
202 await f.drive(second.id, allPass);
203 expect(Object.values(f.summary(second.id))).toEqual(Array(6).fill("success"));
204 expect((f.sql.exec("SELECT rerun_carry FROM runs WHERE id = ?", second.id).one() as { rerun_carry: string | null }).rerun_carry).toBeNull();
205 });
206
207 it("starts up to max-parallel re-run legs; kept legs don't count", async () => {
208 const f = fixture({
209 ".github/workflows/w.yml": `name: w
210on: push
211jobs:
212 test:
213 runs-on: ubuntu-latest
214 strategy:
215 fail-fast: false
216 max-parallel: 1
217 matrix:
218 n: [1, 2, 3, 4]
219 steps: [{ run: echo }]
220`,
221 });
222 const first = await f.firstRun((j) => (JSON.parse(j.matrix).n <= 2 ? "failure" : "success"));
223 const second = await f.actions.rerun(first, ADA, "failed");
224 await f.actions.plan(second.id);
225 await f.actions.startJobKey(second.id, "test");
226 expect(f.jobs(second.id).map((j) => [f.leg(j), j.status, !!j.carried_from])).toEqual([
227 ["test 1", "waiting", false],
228 ["test 2", "queued", false],
229 ["test 3", "completed", true],
230 ["test 4", "completed", true],
231 ]);
232 });
233});
234
235describe("re-running one job", () => {
236 it("re-runs that job and its dependents and keeps the rest, failures included", async () => {
237 const f = fixture({ ".github/workflows/w.yml": WORKFLOW });
238 const first = await f.firstRun(failB);
239 const lint = f.jobs(first).find((j) => j.job_key === "lint")!;
240 const second = await f.actions.rerunJob(lint.id, ADA);
241 await f.drive(second.id, allPass);
242 expect(f.summary(second.id)).toEqual({ lint: "success", report: "success", "test a": "success (kept)", "test b": "failure (kept)", "test c": "cancelled (kept)", deploy: "skipped (kept)" });
243 expect(f.actions.getRun(second.id).conclusion).toBe("failure");
244
245 // One matrix leg: the other legs are kept. deploy needs test, so it runs again, and is skipped: test c is still cancelled.
246 const b = f.jobs(second.id).find((j) => f.leg(j) === "test b")!;
247 const third = await f.actions.rerunJob(b.id, ADA);
248 expect(third.attempt).toBe(3);
249 await f.drive(third.id, allPass);
250 expect(f.summary(third.id)).toEqual({ lint: "success (kept)", report: "success (kept)", "test a": "success (kept)", "test b": "success", "test c": "cancelled (kept)", deploy: "skipped" });
251 // A job kept twice points at the job that actually ran, in the first attempt.
252 const a1 = f.jobs(first).find((j) => f.leg(j) === "test a")!;
253 expect(f.jobs(third.id).find((j) => f.leg(j) === "test a")!.carried_from).toBe(a1.id);
254 });
255
256 it("serves a kept job's log from the job that ran", async () => {
257 const f = fixture({ ".github/workflows/w.yml": WORKFLOW });
258 const first = await f.firstRun((j) => {
259 if (j.job_key === "lint") f.sql.exec("INSERT INTO logs (job_id, seq, t, step, text) VALUES (?, 0, 't', 0, 'linted')", j.id);
260 return failB(j);
261 });
262 const lint = f.jobs(first).find((j) => j.job_key === "lint")!;
263 expect(f.objects.has(logKeys("r", lint.id)[0]!)).toBe(true);
264 const second = await f.actions.rerun(first, ADA, "failed");
265 await f.drive(second.id, allPass);
266 const kept = f.jobs(second.id).find((j) => j.job_key === "lint")!;
267 expect(kept.carried_from).toBe(lint.id);
268 const logs = await f.actions.logs(kept.id);
269 expect(logs).toMatchObject({ complete: true, lines: [{ text: "linted" }] });
270 expect(f.actions.getJob(kept.id).carriedFrom).toBe(lint.id);
271 // gh asks by the REST API's numeric ids (http/gh.ts uuidNumber).
272 expect(await f.actions.logs(String(uuidNumber(kept.id)))).toEqual(logs);
273 });
274
275 it("lists the kept jobs' artifacts with the new attempt's", async () => {
276 const f = fixture({ ".github/workflows/w.yml": WORKFLOW });
277 const first = await f.firstRun(failB);
278 const byLeg = Object.fromEntries(f.jobs(first).map((j) => [f.leg(j), j.id]));
279 const t = new Date().toISOString();
280 const later = new Date(Date.now() + 86400_000).toISOString();
281 const add = (runId: string, jobId: string, name: string) =>
282 f.sql.exec("INSERT INTO rt_artifacts (run_id, job_id, name, size, status, created_at, updated_at, expires_at) VALUES (?, ?, ?, 1, 'ready', ?, ?, ?)", runId, jobId, name, t, t, later);
283 add(first, byLeg.lint!, "lint-report");
284 add(first, byLeg["test b"]!, "failed-b");
285 const second = await f.actions.rerun(first, ADA, "failed");
286 await f.drive(second.id, allPass);
287 add(second.id, f.jobs(second.id).find((j) => f.leg(j) === "test b")!.id, "passed-b");
288 const rt = new Runtime({ sql: f.sql } as unknown as RepoDO, {} as Env);
289 // The failed leg ran again, so its first attempt's artifact isn't the new attempt's.
290 expect(rt.runArtifacts(second.id).map((a) => a.name).sort()).toEqual(["lint-report", "passed-b"]);
291 expect(rt.runArtifacts(first).map((a) => a.name).sort()).toEqual(["failed-b", "lint-report"]);
292 expect(rt.runArtifacts(String(uuidNumber(second.id))).map((a) => a.name).sort()).toEqual(["lint-report", "passed-b"]);
293 });
294});
295
296describe("the REST API's numeric run and job ids", () => {
297 it("are 16 digits that find the run or job again, while shorter numbers stay run numbers", async () => {
298 const f = fixture({ ".github/workflows/w.yml": WORKFLOW });
299 const first = await f.firstRun(failB);
300 const second = await f.actions.rerun(first, ADA, "failed");
301 const n = uuidNumber(first);
302 expect(String(n)).toMatch(/^\d{16}$/);
303 expect(uuidPattern(String(n))).not.toBeNull();
304 expect(f.actions.getRun(String(n)).id).toBe(first);
305 expect(f.actions.getRun(String(uuidNumber(second.id))).id).toBe(second.id);
306 // A run number is the latest attempt, as before.
307 expect(f.actions.getRun(String(second.number)).id).toBe(second.id);
308 expect(f.actions.jobs(String(n)).map((j) => j.id)).toEqual(f.jobs(first).map((j) => j.id));
309 const job = f.jobs(first)[0]!;
310 expect(f.actions.getJob(String(uuidNumber(job.id))).id).toBe(job.id);
311 expect(() => f.actions.getJob(String(uuidNumber(job.id) + 1))).toThrow(/job not found/);
312 expect(() => f.actions.getRun("9999999999999999")).toThrow(/run not found/);
313 expect(uuidPattern("123")).toBeNull();
314 expect(uuidPattern("abc")).toBeNull();
315 });
316
317 it("give workflows a stable number of their own", () => {
318 expect(workflowNumber(".github/workflows/ci.yml")).toBe(workflowNumber(".github/workflows/ci.yml"));
319 expect(workflowNumber(".github/workflows/ci.yml")).not.toBe(workflowNumber(".github/workflows/cd.yml"));
320 expect(Number.isSafeInteger(workflowNumber(".github/workflows/ci.yml"))).toBe(true);
321 });
322});
323
324describe("re-running failed jobs of a reusable workflow call", () => {
325 it("treats the call's jobs like any other and re-runs what needs the call", async () => {
326 const f = fixture({
327 ".github/workflows/w.yml": `name: w
328on: push
329jobs:
330 build:
331 uses: ./.github/workflows/lib.yml
332 ship:
333 needs: build
334 runs-on: ubuntu-latest
335 steps: [{ run: echo ship }]
336 docs:
337 runs-on: ubuntu-latest
338 steps: [{ run: echo docs }]
339`,
340 ".github/workflows/lib.yml": `on: workflow_call
341jobs:
342 compile:
343 runs-on: ubuntu-latest
344 steps: [{ run: echo compile }]
345 check:
346 needs: compile
347 runs-on: ubuntu-latest
348 steps: [{ run: echo check }]
349`,
350 });
351 const first = await f.firstRun((j) => (j.job_key === "build/check" ? "failure" : "success"));
352 expect(f.summary(first)).toEqual({ "build/compile": "success", "build/check": "failure", ship: "skipped", docs: "success" });
353 const second = await f.actions.rerun(first, ADA, "failed");
354 await f.drive(second.id, allPass);
355 expect(f.summary(second.id)).toEqual({ "build/compile": "success (kept)", "build/check": "success", ship: "success", docs: "success (kept)" });
356 });
357});
358
359describe("canonicalJson", () => {
360 it("doesn't depend on key order", () => {
361 expect(canonicalJson({ b: 1, a: { d: [1, { y: 2, x: 1 }], c: null } })).toBe(canonicalJson({ a: { c: null, d: [1, { x: 1, y: 2 }] }, b: 1 }));
362 expect(canonicalJson({ a: 1 })).not.toBe(canonicalJson({ a: "1" }));
363 });
364});
365
366describe("starting a run's workflow", () => {
367 const start = async (create: () => Promise<void>, exists: () => boolean) => {
368 const f = fixture({ ".github/workflows/w.yml": WORKFLOW });
369 let calls = 0;
370 (f.actions as unknown as { env: Env }).env.RUN_WORKFLOW = {
371 create: async () => {
372 calls++;
373 await create();
374 },
375 get: async () => ({
376 status: async () => {
377 if (!exists()) throw new Error("instance not found");
378 return { status: "running" };
379 },
380 sendEvent: async () => {},
381 }),
382 } as unknown as Env["RUN_WORKFLOW"];
383 vi.useFakeTimers();
384 try {
385 const pending = f.actions.createRun(parse(WORKFLOW, ".github/workflows/w.yml"), { event: "push", ref: "refs/heads/main", sha: "abc", payload: {}, caller: ADA, title: "t" });
386 await vi.runAllTimersAsync();
387 return { f, run: (await pending)!, calls: () => calls };
388 } finally {
389 vi.useRealTimers();
390 }
391 };
392
393 it("tries again when the platform fails the call, and counts a call that failed after creating it", async () => {
394 let fails = 1;
395 const a = await start(async () => {
396 if (fails-- > 0) throw new Error("internal error; reference = abc");
397 }, () => false);
398 expect(a.calls()).toBe(2);
399 expect(a.run.status).toBe("queued");
400 let created = false;
401 const b = await start(async () => {
402 created = true;
403 throw new Error("internal error; reference = def");
404 }, () => created);
405 expect(b.calls()).toBe(1);
406 expect(b.run.status).toBe("queued");
407 });
408
409 it("fails the run, saying why, rather than leave it queued for good", async () => {
410 const { f, run, calls } = await start(async () => {
411 throw new Error("internal error; reference = ghi");
412 }, () => false);
413 expect(calls()).toBe(3);
414 expect(run).toMatchObject({ status: "completed", conclusion: "failure" });
415 expect(f.jobs(run.id).map((j) => [j.name, j.conclusion])).toEqual([["Set up workflow", "failure"]]);
416 const failure = f.sql.exec<{ failure: string }>("SELECT failure FROM jobs WHERE run_id = ?", run.id).one().failure;
417 expect(JSON.parse(failure).message).toBe("Diffinery couldn't start this run (internal error; reference = ghi). Re-run the workflow.");
418 });
419});
420
421describe("deleting a run's logs", () => {
422 const logged = (f: ReturnType<typeof fixture>) => (j: Row) => {
423 f.sql.exec("INSERT INTO logs (job_id, seq, t, step, text) VALUES (?, 0, 't', 0, ?)", j.id, `log of ${j.job_key}`);
424 f.sql.exec("UPDATE jobs SET summary = 'a summary' WHERE id = ?", j.id);
425 return "success" as const;
426 };
427
428 it("deletes every job's lines, archived copy and summary, and keeps the run and its jobs", async () => {
429 const f = fixture({ ".github/workflows/w.yml": WORKFLOW });
430 const first = await f.firstRun(logged(f));
431 const jobs = f.jobs(first);
432 expect(jobs.every((j) => f.objects.has(logKeys("r", j.id)[0]!))).toBe(true);
433 expect(await f.actions.deleteLogs(first, ADA)).toEqual(jobs.map((j) => j.id));
434 for (const j of jobs) {
435 expect(f.objects.has(logKeys("r", j.id)[0]!)).toBe(false);
436 expect(await f.actions.logs(j.id)).toEqual({ lines: [], complete: true });
437 }
438 expect(f.sql.exec("SELECT count(*) AS n FROM logs").one()).toEqual({ n: 0 });
439 expect(f.sql.exec("SELECT count(*) AS n FROM jobs WHERE run_id = ? AND summary IS NOT NULL", first).one()).toEqual({ n: 0 });
440 expect(f.actions.getRun(first)).toMatchObject({ conclusion: "success", jobs: expect.arrayContaining([expect.objectContaining({ conclusion: "success" })]) });
441 });
442
443 it("needs write access, refuses job tokens and runs that haven't finished", async () => {
444 const f = fixture({ ".github/workflows/w.yml": WORKFLOW });
445 const first = await f.firstRun(allPass);
446 await expect(f.actions.deleteLogs(first, { ...ADA, role: "read" })).rejects.toMatchObject({ status: 403 });
447 await expect(f.actions.deleteLogs(first, { ...ADA, id: "job:x" })).rejects.toMatchObject({ status: 403 });
448 const second = await f.actions.rerun(first, ADA);
449 await expect(f.actions.deleteLogs(second.id, ADA)).rejects.toMatchObject({ status: 409 });
450 });
451
452 it("lets agents delete logs only of runs off the default and protected branches", async () => {
453 const BOT: Caller = { id: "a1", login: "bot", kind: "agent", role: "write" };
454 for (const [ref, ok] of [["refs/heads/main", false], ["refs/heads/release", false], ["refs/heads/feature", true], ["refs/pull/3/merge", true]] as const) {
455 const f = fixture({ ".github/workflows/w.yml": WORKFLOW });
456 const run = await f.firstRun(logged(f), ref);
457 if (ok) await expect(f.actions.deleteLogs(run, BOT)).resolves.toHaveLength(6);
458 else await expect(f.actions.deleteLogs(run, BOT)).rejects.toMatchObject({ status: 403 });
459 }
460 // People may delete logs of any branch's runs.
461 const f = fixture({ ".github/workflows/w.yml": WORKFLOW });
462 await expect(f.actions.deleteLogs(await f.firstRun(logged(f)), ADA)).resolves.toHaveLength(6);
463 });
464});