@intentius/chant 0.124.60 → 0.124.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/cli/main.d.ts.map +1 -1
  2. package/dist/cli/main.js +16 -2
  3. package/dist/cli/parse-args.d.ts.map +1 -1
  4. package/dist/cli/parse-args.js +12 -0
  5. package/dist/cli/registry.d.ts +6 -0
  6. package/dist/cli/registry.d.ts.map +1 -1
  7. package/dist/notify.d.ts +24 -2
  8. package/dist/notify.d.ts.map +1 -1
  9. package/dist/notify.js +16 -2
  10. package/dist/notify.schema.json +17 -1
  11. package/dist/release-floors.d.ts +1 -1
  12. package/dist/release-floors.js +1 -1
  13. package/dist/wave-runtime.mjs +310 -309
  14. package/dist/workspace/ci-builds.d.ts +16 -4
  15. package/dist/workspace/ci-builds.d.ts.map +1 -1
  16. package/dist/workspace/ci-builds.js +10 -7
  17. package/dist/workspace/ci-green-cli.d.ts +12 -0
  18. package/dist/workspace/ci-green-cli.d.ts.map +1 -1
  19. package/dist/workspace/ci-green-cli.js +80 -6
  20. package/dist/workspace/ci-green-workflow.d.ts +11 -0
  21. package/dist/workspace/ci-green-workflow.d.ts.map +1 -1
  22. package/dist/workspace/ci-green-workflow.js +63 -1
  23. package/dist/workspace/ci-green.d.ts +130 -6
  24. package/dist/workspace/ci-green.d.ts.map +1 -1
  25. package/dist/workspace/ci-green.js +251 -24
  26. package/dist/workspace/declaration.d.ts +37 -0
  27. package/dist/workspace/declaration.d.ts.map +1 -1
  28. package/dist/workspace/declaration.js +29 -1
  29. package/dist/workspace/declaration.schema.json +44 -0
  30. package/dist/workspace/trust/ci-tag-statement.d.ts +1 -0
  31. package/dist/workspace/trust/ci-tag-statement.d.ts.map +1 -1
  32. package/dist/workspace/trust/ci-tag-statement.js +5 -1
  33. package/package.json +1 -1
  34. package/src/cli/main.ts +16 -2
  35. package/src/cli/parse-args.ts +9 -0
  36. package/src/cli/registry.ts +6 -0
  37. package/src/notify.schema.json +17 -1
  38. package/src/notify.ts +30 -2
  39. package/src/release-floors.ts +1 -1
  40. package/src/workspace/ci-builds.ts +16 -7
  41. package/src/workspace/ci-green-builds.test.ts +83 -1
  42. package/src/workspace/ci-green-cli.ts +80 -6
  43. package/src/workspace/ci-green-lanes.test.ts +121 -0
  44. package/src/workspace/ci-green-merge-queue.test.ts +66 -0
  45. package/src/workspace/ci-green-notify.test.ts +166 -0
  46. package/src/workspace/ci-green-signed.test.ts +20 -0
  47. package/src/workspace/ci-green-workflow.test.ts +47 -1
  48. package/src/workspace/ci-green-workflow.ts +62 -1
  49. package/src/workspace/ci-green.ts +290 -26
  50. package/src/workspace/declaration.schema.json +44 -0
  51. package/src/workspace/declaration.ts +64 -2
  52. package/src/workspace/trust/ci-tag-statement.ts +5 -2
@@ -0,0 +1,121 @@
1
+ /**
2
+ * #4662 — green lanes: named subsets of ci.green's phases, each tagged
3
+ * ci/green-<lane>/<sha> by the same tick from the same runs, and read back
4
+ * by `ci last-green --lane` and `ci base --lane`.
5
+ */
6
+
7
+ import { execFileSync } from "node:child_process";
8
+ import { afterAll, describe, expect, test } from "vitest";
9
+ import { cleanScratch, declaration, git, scratchDir, writeFiles } from "./__fixtures__/contract-repo";
10
+ import { ciBase, ciTick, formatTick, lastGreen } from "./ci-green";
11
+ import type { CheckRun, CiForge } from "./ci-green-forge";
12
+ import { parseDeclaration } from "./declaration";
13
+
14
+ afterAll(cleanScratch);
15
+
16
+ const NOW = new Date("2026-10-20T12:00:00Z");
17
+ const hoursAgo = (h: number) => new Date(NOW.getTime() - h * 3_600_000).toISOString();
18
+
19
+ const GREEN = {
20
+ branch: "main",
21
+ phases: { lint: ["lint"], test: ["test"], windows: ["windows"] },
22
+ require: ["lint", "test", "windows"],
23
+ lanes: { server: { require: ["lint", "test"] } },
24
+ };
25
+
26
+ function commitAt(root: string, hours: number, file: string): string {
27
+ writeFiles(root, { [file]: `${file} ${hours}\n` });
28
+ const env = { ...process.env, GIT_AUTHOR_DATE: hoursAgo(hours), GIT_COMMITTER_DATE: hoursAgo(hours) };
29
+ const g = (...args: string[]) => execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "commit.gpgsign=false", ...args], { cwd: root, env, stdio: ["ignore", "pipe", "pipe"] });
30
+ g("add", "-A");
31
+ g("commit", "-q", "-m", file);
32
+ return git(root, "rev-parse", "HEAD");
33
+ }
34
+
35
+ function workspace(green: unknown = GREEN): { root: string; origin: string } {
36
+ const origin = scratchDir("chant-lanes-origin-");
37
+ git(origin, "init", "-q", "--bare");
38
+ const root = scratchDir("chant-lanes-work-");
39
+ git(root, "init", "-q");
40
+ git(root, "symbolic-ref", "HEAD", "refs/heads/main");
41
+ writeFiles(root, { "chant.workspace.json": declaration([{ name: "app", dir: "app", kind: "other", because: "the app" }], { ci: { green } }), "app/a.txt": "a\n" });
42
+ git(root, "remote", "add", "origin", origin);
43
+ return { root, origin };
44
+ }
45
+
46
+ let id = 1;
47
+ const run = (name: string, conclusion: string): CheckRun => ({ id: id++, name, status: "completed", conclusion, completedAt: null, url: null });
48
+ const forgeOf = (runs: Map<string, CheckRun[]>): CiForge => ({ kind: "github", checkRuns: async (sha) => runs.get(sha) ?? [] });
49
+ const remoteTags = (origin: string) => git(origin, "for-each-ref", "--format=%(refname:lstrip=2)", "refs/tags/").split("\n").filter(Boolean).sort();
50
+
51
+ describe("green lanes (#4662)", () => {
52
+ test("a commit that passes a lane's phases and fails another gets the lane's tag and no ci/green", async () => {
53
+ const { root, origin } = workspace();
54
+ const a = commitAt(root, 3, "app/a.txt");
55
+ const b = commitAt(root, 2, "app/b.txt");
56
+ git(root, "push", "-q", "origin", "main");
57
+ const runs = new Map([
58
+ [a, [run("lint", "success"), run("test", "success"), run("windows", "success")]],
59
+ [b, [run("lint", "success"), run("test", "success"), run("windows", "failure")]],
60
+ ]);
61
+
62
+ const tick = await ciTick({ cwd: root, forge: forgeOf(runs), now: NOW });
63
+ expect(tick.made.sort()).toEqual([`ci/green-server/${a}`, `ci/green-server/${b}`, `ci/green/${a}`].sort());
64
+ expect(remoteTags(origin)).toEqual([`ci/green-server/${a}`, `ci/green-server/${b}`, `ci/green/${a}`].sort());
65
+ expect(formatTick(tick)).toContain(`${b.slice(0, 12)} lane server: made ci/green-server`);
66
+ const annotation = git(root, "tag", "-l", "--format=%(contents)", `ci/green-server/${b}`);
67
+ expect(annotation.split("\n")[0]).toBe("ci: every phase of lane server passed (lint, test)");
68
+ expect(JSON.parse(annotation.slice(annotation.indexOf("{")))).toMatchObject({ tag: "green", lane: "server", commit: b });
69
+
70
+ // The lane's newest green commit is b, the branch's is a.
71
+ expect(lastGreen({ cwd: root, lane: "server" })).toMatchObject({ commit: { sha: b, tag: `ci/green-server/${b}` } });
72
+ expect(lastGreen({ cwd: root })).toMatchObject({ commit: { sha: a, tag: `ci/green/${a}` } });
73
+
74
+ // A second tick makes nothing again.
75
+ expect((await ciTick({ cwd: root, forge: forgeOf(runs), now: NOW })).made).toEqual([]);
76
+ });
77
+
78
+ test("a lane-green commit that later fails the lane's phases gets the lane's revoked tag", async () => {
79
+ const { root, origin } = workspace();
80
+ const a = commitAt(root, 2, "app/a.txt");
81
+ git(root, "push", "-q", "origin", "main");
82
+ const runs = new Map([[a, [run("lint", "success"), run("test", "success"), run("windows", "failure")]]]);
83
+ await ciTick({ cwd: root, forge: forgeOf(runs), now: NOW });
84
+ runs.set(a, [run("lint", "success"), run("test", "failure"), run("windows", "failure")]);
85
+ const tick = await ciTick({ cwd: root, forge: forgeOf(runs), now: NOW });
86
+ expect(tick.made).toEqual([`ci/revoked-server/${a}`]);
87
+ expect(remoteTags(origin)).toContain(`ci/revoked-server/${a}`);
88
+ expect(lastGreen({ cwd: root, lane: "server" })).toMatchObject({ commit: null });
89
+ });
90
+
91
+ test("ci base --lane checks the lane's phases and falls back to the lane's tags", async () => {
92
+ const { root } = workspace();
93
+ const a = commitAt(root, 3, "app/a.txt");
94
+ git(root, "push", "-q", "origin", "main");
95
+ await ciTick({ cwd: root, forge: forgeOf(new Map([[a, [run("lint", "success"), run("test", "success"), run("windows", "failure")]]])), now: NOW });
96
+ const docs = commitAt(root, 2, "docs/readme.md");
97
+ // a's record passed the lane's phases; it failed windows, which every required phase includes.
98
+ expect(ciBase({ cwd: root, from: docs, lane: "server" })).toMatchObject({ commit: { sha: a, via: "record", tag: `ci/green-server/${a}` } });
99
+ expect(ciBase({ cwd: root, from: docs })).toMatchObject({ commit: null });
100
+ expect(() => ciBase({ cwd: root, from: docs, lane: "server", phase: "lint" })).toThrow(/give one/);
101
+ });
102
+
103
+ test("an unknown lane is declaration-invalid, and a lane must name declared phases", () => {
104
+ const { root } = workspace();
105
+ commitAt(root, 2, "app/a.txt");
106
+ expect(lastGreen({ cwd: root, lane: "app" })).toMatchObject({ error: { code: "declaration-invalid", message: expect.stringContaining('no lane "app"; it declares server') } });
107
+ const bad = JSON.stringify({ name: "w", schema: 1, members: [], ci: { green: { ...GREEN, lanes: { server: { require: ["lint", "deploy"] } } } } });
108
+ expect(() => parseDeclaration(bad, "chant.workspace.json")).toThrow(/ci\.green\.lanes\.server\.require names the phase "deploy"/);
109
+ const named = JSON.stringify({ name: "w", schema: 1, members: [], ci: { green: { ...GREEN, lanes: { Server: { require: ["lint"] } } } } });
110
+ expect(() => parseDeclaration(named, "chant.workspace.json")).toThrow();
111
+ });
112
+
113
+ test("a declaration with no lanes ticks as before", async () => {
114
+ const { root } = workspace({ ...GREEN, lanes: undefined });
115
+ const a = commitAt(root, 2, "app/a.txt");
116
+ git(root, "push", "-q", "origin", "main");
117
+ const tick = await ciTick({ cwd: root, forge: forgeOf(new Map([[a, [run("lint", "success"), run("test", "success"), run("windows", "success")]]])), now: NOW });
118
+ expect(tick.made).toEqual([`ci/green/${a}`]);
119
+ expect(tick.lanes).toBeUndefined();
120
+ });
121
+ });
@@ -0,0 +1,66 @@
1
+ /**
2
+ * #4644 — a merge queue: a decided attempt of a job is never replaced by a
3
+ * later skipped or cancelled one (the push run on the commit the queue
4
+ * landed), and `chant ci verdict` judges a group's commit as the tick would.
5
+ */
6
+
7
+ import { afterAll, describe, expect, test } from "vitest";
8
+ import { cleanScratch, declaration, git, scratchDir, writeFiles } from "./__fixtures__/contract-repo";
9
+ import { ciVerdict, evaluateCommit, latestAttempts } from "./ci-green";
10
+ import type { CheckRun, CiForge } from "./ci-green-forge";
11
+ import { parseDeclaration } from "./declaration";
12
+
13
+ afterAll(cleanScratch);
14
+
15
+ const run = (id: number, name: string, conclusion: string | null, status = "completed"): CheckRun => ({ id, name, status, conclusion: status === "completed" ? conclusion : null, completedAt: null, url: null });
16
+
17
+ describe("a job's attempts on one commit (#4644)", () => {
18
+ test("a later skipped or cancelled attempt doesn't replace a decided one, and a later decided one does", () => {
19
+ expect(latestAttempts([run(1, "test", "success"), run(2, "test", "skipped")]).map((r) => r.id)).toEqual([1]);
20
+ expect(latestAttempts([run(1, "test", "failure"), run(2, "test", "cancelled")]).map((r) => r.id)).toEqual([1]);
21
+ expect(latestAttempts([run(2, "test", "cancelled"), run(1, "test", "success")]).map((r) => r.id)).toEqual([1]);
22
+ expect(latestAttempts([run(1, "test", "success"), run(2, "test", "failure")]).map((r) => r.id)).toEqual([2]);
23
+ expect(latestAttempts([run(1, "test", "skipped"), run(2, "test", "success")]).map((r) => r.id)).toEqual([2]);
24
+ // With nothing decided the latest still wins, and a run in progress replaces a decided one, as a re-run does.
25
+ expect(latestAttempts([run(1, "test", "skipped"), run(2, "test", "cancelled")]).map((r) => r.id)).toEqual([2]);
26
+ expect(latestAttempts([run(1, "test", "failure"), run(2, "test", null, "in_progress")]).map((r) => r.id)).toEqual([2]);
27
+ });
28
+
29
+ test("the group's run decides the commit the queue landed, whatever the push run did after", () => {
30
+ const green = parseDeclaration(JSON.stringify({ name: "w", schema: 1, members: [], ci: { green: { branch: "main", phases: { test: { runs: ["test"], build: "newest" } }, require: ["test"] } } }), "chant.workspace.json").ci!.green!;
31
+ // The group's test passed; main's push run on the same commit was cancelled by a newer push.
32
+ expect(evaluateCommit(green, [run(1, "test", "success"), run(2, "test", "cancelled")]).verdict).toBe("pass");
33
+ });
34
+ });
35
+
36
+ describe("chant ci verdict (#4644)", () => {
37
+ function workspace(): string {
38
+ const root = scratchDir("chant-verdict-");
39
+ git(root, "init", "-q");
40
+ writeFiles(root, { "chant.workspace.json": declaration([], { ci: { green: { branch: "main", phases: { lint: ["lint"], test: ["test"] }, require: ["lint", "test"], mergeQueue: true } } }) });
41
+ return root;
42
+ }
43
+ const forgeOf = (answers: CheckRun[][]): CiForge & { reads: number } => {
44
+ const f = { kind: "github" as const, reads: 0, checkRuns: async () => answers[Math.min(f.reads++, answers.length - 1)]! };
45
+ return f;
46
+ };
47
+
48
+ test("waits while a phase is pending, then passes; its own check run doesn't count", async () => {
49
+ const root = workspace();
50
+ const forge = forgeOf([
51
+ [run(1, "lint", "success"), run(2, "test", null, "in_progress"), run(9, "chant-verdict", null, "in_progress")],
52
+ [run(1, "lint", "success"), run(2, "test", "success"), run(9, "chant-verdict", null, "in_progress")],
53
+ ]);
54
+ const pending: string[][] = [];
55
+ const out = await ciVerdict({ cwd: root, sha: "a".repeat(40), forge, wait: true, sleep: async () => {}, onPending: (v) => pending.push(v.phases.filter((p) => p.verdict === "pending").map((p) => p.phase)) });
56
+ expect(out.verdict.verdict).toBe("pass");
57
+ expect(pending).toEqual([["test"]]);
58
+ expect(forge.reads).toBe(2);
59
+ });
60
+
61
+ test("fails on a failed phase, and without --wait answers pending at once", async () => {
62
+ const root = workspace();
63
+ expect((await ciVerdict({ cwd: root, sha: "b".repeat(40), forge: forgeOf([[run(1, "lint", "success"), run(2, "test", "failure")]]), wait: true, sleep: async () => {} })).verdict).toMatchObject({ verdict: "fail", failure: { phase: "test" } });
64
+ expect((await ciVerdict({ cwd: root, sha: "c".repeat(40), forge: forgeOf([[run(1, "lint", "success")]]) })).verdict.verdict).toBe("pending");
65
+ });
66
+ });
@@ -0,0 +1,166 @@
1
+ /**
2
+ * #4645 — the tick tells people through ci.green.notify: ci.red when the
3
+ * branch's newest decided commit is red after its retry, ci.culprit when a
4
+ * bisect names the first red commit, ci.green when the branch is green again.
5
+ * Each once, remembered in the commit's _ci record.
6
+ */
7
+
8
+ import { execFileSync } from "node:child_process";
9
+ import { afterAll, describe, expect, test } from "vitest";
10
+ import { cleanScratch, declaration, git, scratchDir, writeFiles } from "./__fixtures__/contract-repo";
11
+ import { ciTick, formatTick } from "./ci-green";
12
+ import type { CheckRun, CiForge } from "./ci-green-forge";
13
+ import { readCiRecord } from "./ci-builds";
14
+ import type { NotifyConfig, NotifyDelivery, NotifyEvent } from "../notify";
15
+
16
+ afterAll(cleanScratch);
17
+
18
+ const NOW = new Date("2026-10-20T12:00:00Z");
19
+ const hoursAgo = (h: number) => new Date(NOW.getTime() - h * 3_600_000).toISOString();
20
+ const NOTIFY = { webhook: "HOOK_URL", key: "HOOK_KEY" };
21
+ const GREEN = { branch: "main", phases: { lint: ["lint"], test: ["test"] }, require: ["lint", "test"], notify: NOTIFY };
22
+
23
+ function commitAt(root: string, hours: number, file: string): string {
24
+ writeFiles(root, { [file]: `${file} ${hours}\n` });
25
+ const env = { ...process.env, GIT_AUTHOR_DATE: hoursAgo(hours), GIT_COMMITTER_DATE: hoursAgo(hours) };
26
+ const g = (...args: string[]) => execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "commit.gpgsign=false", ...args], { cwd: root, env, stdio: ["ignore", "pipe", "pipe"] });
27
+ g("add", "-A");
28
+ g("commit", "-q", "-m", file);
29
+ return git(root, "rev-parse", "HEAD");
30
+ }
31
+
32
+ function workspace(green: unknown = GREEN): { root: string } {
33
+ const origin = scratchDir("chant-notify-origin-");
34
+ git(origin, "init", "-q", "--bare");
35
+ const root = scratchDir("chant-notify-work-");
36
+ git(root, "init", "-q");
37
+ git(root, "symbolic-ref", "HEAD", "refs/heads/main");
38
+ writeFiles(root, { "chant.workspace.json": declaration([{ name: "app", dir: "app", kind: "other", because: "the app" }], { ci: { green } }), "app/a.txt": "a\n" });
39
+ git(root, "remote", "add", "origin", origin);
40
+ return { root };
41
+ }
42
+
43
+ let id = 1;
44
+ const run = (name: string, conclusion: string): CheckRun => ({ id: id++, name, status: "completed", conclusion, completedAt: null, url: `https://ci.example/runs/${id}` });
45
+ const pass = () => [run("lint", "success"), run("test", "success")];
46
+ const fail = () => [run("lint", "success"), run("test", "failure")];
47
+ /** A forge with no re-run: a red commit is red at once, with nothing to retry. */
48
+ const forgeOf = (runs: Map<string, CheckRun[]>): CiForge => ({ kind: "github", checkRuns: async (sha) => runs.get(sha) ?? [] });
49
+
50
+ /** A notify that records each event and answers as `answer` says. */
51
+ function sink(answer: (e: NotifyEvent) => NotifyDelivery[] = () => [{ target: "webhook", ok: true, detail: "delivered" }]) {
52
+ const sent: NotifyEvent[] = [];
53
+ const send = async (config: NotifyConfig | undefined, e: NotifyEvent | undefined) => {
54
+ if (!config || !e) return [];
55
+ sent.push(e);
56
+ return answer(e);
57
+ };
58
+ return { sent, send };
59
+ }
60
+
61
+ const tick = (root: string, runs: Map<string, CheckRun[]>, s: ReturnType<typeof sink>, more: { dryRun?: boolean } = {}) =>
62
+ ciTick({ cwd: root, forge: forgeOf(runs), now: NOW, env: { GITHUB_REPOSITORY: "acme/app", GITHUB_RUN_ID: "9" }, sendNotify: s.send, ...more });
63
+
64
+ describe("the tick's notify events (#4645)", () => {
65
+ test("ci.red once for a red tip", async () => {
66
+ const { root } = workspace();
67
+ const a = commitAt(root, 3, "app/a.txt");
68
+ const b = commitAt(root, 2, "app/b.txt");
69
+ git(root, "push", "-q", "origin", "main");
70
+ const runs = new Map([
71
+ [a, pass()],
72
+ [b, fail()],
73
+ ]);
74
+ const s = sink();
75
+
76
+ const first = await tick(root, runs, s);
77
+ expect(s.sent.map((e) => [e.event, e.ci?.commit])).toEqual([["ci.red", b]]);
78
+ const red = s.sent[0]!;
79
+ expect(red).toMatchObject({ source: "chant", project: "acme/app", summary: expect.stringMatching(/^main is red at [0-9a-f]{12}: phase test, test failure$/), ci: { branch: "main", phase: "test", failedRun: { name: "test", conclusion: "failure" } }, run: { commit: b } });
80
+ // The tick's own run link says nothing about the commit, so it isn't in the event.
81
+ expect(red.run?.url).toBeUndefined();
82
+ expect(first.notified).toEqual([{ event: "ci.red", commit: b, sent: true }]);
83
+ expect(formatTick(first)).toContain(`${b.slice(0, 12)} told ci.red`);
84
+ expect(readCiRecord(root, b)?.notified?.red).toBe(NOW.toISOString().replace(/\.\d{3}Z$/, "Z"));
85
+
86
+ // The next tick tells nothing again.
87
+ await tick(root, runs, s);
88
+ expect(s.sent).toHaveLength(1);
89
+ });
90
+
91
+ test("ci.green once when the branch is green again, naming the red commit", async () => {
92
+ const { root } = workspace();
93
+ const b = commitAt(root, 2, "app/b.txt");
94
+ git(root, "push", "-q", "origin", "main");
95
+ const runs = new Map([[b, fail()]]);
96
+ const s = sink();
97
+ await tick(root, runs, s);
98
+ // A fix lands and passes.
99
+ const c = commitAt(root, 1, "app/c.txt");
100
+ git(root, "push", "-q", "origin", "main");
101
+ runs.set(c, pass());
102
+ await tick(root, runs, s);
103
+ expect(s.sent.map((e) => [e.event, e.ci?.commit, e.ci?.red])).toEqual([
104
+ ["ci.red", b, undefined],
105
+ ["ci.green", c, b],
106
+ ]);
107
+ expect(readCiRecord(root, b)?.notified).toMatchObject({ green: c });
108
+ await tick(root, runs, s);
109
+ expect(s.sent).toHaveLength(2);
110
+ });
111
+
112
+ test("ci.culprit names the first red commit below a red tip, once", async () => {
113
+ const { root } = workspace({ ...GREEN, phases: { lint: ["lint"], test: { runs: ["test"], build: "newest" } } });
114
+ const base = commitAt(root, 4, "app/a.txt");
115
+ const a = commitAt(root, 3, "app/b.txt");
116
+ const b = commitAt(root, 2, "app/c.txt");
117
+ git(root, "push", "-q", "origin", "main");
118
+ // a's test was superseded and never ran; b's failed. The bisect asks for a.
119
+ const runs = new Map([
120
+ [base, pass()],
121
+ [a, [run("lint", "success")]],
122
+ [b, fail()],
123
+ ]);
124
+ const s = sink();
125
+ await tick(root, runs, s);
126
+ expect(s.sent.map((e) => e.event)).toEqual(["ci.red"]);
127
+ // a's build fails too, so a is the culprit.
128
+ runs.set(a, fail());
129
+ await tick(root, runs, s);
130
+ expect(s.sent.map((e) => [e.event, e.ci?.commit, e.ci?.culprit])).toEqual([
131
+ ["ci.red", b, undefined],
132
+ ["ci.culprit", b, a],
133
+ ]);
134
+ await tick(root, runs, s);
135
+ expect(s.sent).toHaveLength(2);
136
+ });
137
+
138
+ test("a dry run tells and marks nothing, and a failed delivery is tried again next tick", async () => {
139
+ const { root } = workspace();
140
+ const a = commitAt(root, 2, "app/a.txt");
141
+ git(root, "push", "-q", "origin", "main");
142
+ const runs = new Map([[a, fail()]]);
143
+ const dry = sink();
144
+ const would = await tick(root, runs, dry, { dryRun: true });
145
+ expect(dry.sent).toEqual([]);
146
+ expect(would.notified).toEqual([{ event: "ci.red", commit: a, sent: false }]);
147
+
148
+ const down = sink(() => [{ target: "webhook", ok: false, detail: "503" }]);
149
+ const failed = await tick(root, runs, down);
150
+ expect(failed.warnings.some((w) => w.includes("could not send ci.red") && w.includes("webhook 503"))).toBe(true);
151
+ expect(readCiRecord(root, a)?.notified).toBeUndefined();
152
+ const up = sink();
153
+ await tick(root, runs, up);
154
+ expect(up.sent.map((e) => e.event)).toEqual(["ci.red"]);
155
+ });
156
+
157
+ test("no ci.green.notify, no events and no notified field", async () => {
158
+ const { root } = workspace({ ...GREEN, notify: undefined });
159
+ const a = commitAt(root, 2, "app/a.txt");
160
+ git(root, "push", "-q", "origin", "main");
161
+ const s = sink();
162
+ const result = await tick(root, new Map([[a, fail()]]), s);
163
+ expect(s.sent).toEqual([]);
164
+ expect(result.notified).toBeUndefined();
165
+ });
166
+ });
@@ -300,3 +300,23 @@ describe("signed ci tags (#4031)", () => {
300
300
  expect(lastGreen({ cwd: root, from: "nope" })).toMatchObject({ error: { code: "revision-unknown" } });
301
301
  });
302
302
  });
303
+
304
+ describe("a lane's signed tag (#4662)", () => {
305
+ test("counts only as its own lane's tag, never as ci/green or another lane's", () => {
306
+ const sha = "a".repeat(40);
307
+ const signed = greenAnnotation(GREEN_DECL, sha, evaluateCommit(GREEN_DECL, PASSING), NOW, { principal: "ci-bot", key: createPrivateKey(BOT.pem), publicKey: BOT.ssh }, "server");
308
+ const record = JSON.parse(signed.slice(signed.indexOf("{"))) as Record<string, unknown>;
309
+ expect(signed.split("\n")[0]).toBe("ci: every phase of lane server passed (lint, test)");
310
+ expect(record.lane).toBe("server");
311
+ const runners = [{ principal: "ci-bot", class: "runner" as const, key: BOT.ssh }];
312
+ const roles = { runner: ["ci-bot"] };
313
+ expect(verifyCiTagStatement(record, { sha, kind: "green", branch: "main", lane: "server" }, runners, roles)).toMatchObject({ status: "signed", signer: "ci-bot" });
314
+ // Copied onto ci/green/<sha>, or onto another lane's tag, the statement doesn't match.
315
+ expect(verifyCiTagStatement(record, { sha, kind: "green", branch: "main" }, runners, roles)).toMatchObject({ status: "mismatch", reason: expect.stringContaining("it signs lane server's tag, not ci/green") });
316
+ expect(verifyCiTagStatement(record, { sha, kind: "green", branch: "main", lane: "app" }, runners, roles)).toMatchObject({ status: "mismatch", reason: expect.stringContaining("not lane app's") });
317
+ // And a ci/green statement doesn't count as a lane's.
318
+ const plain = greenAnnotation(GREEN_DECL, sha, evaluateCommit(GREEN_DECL, PASSING), NOW, { principal: "ci-bot", key: createPrivateKey(BOT.pem), publicKey: BOT.ssh });
319
+ const plainRecord = JSON.parse(plain.slice(plain.indexOf("{"))) as Record<string, unknown>;
320
+ expect(verifyCiTagStatement(plainRecord, { sha, kind: "green", branch: "main", lane: "server" }, runners, roles)).toMatchObject({ status: "mismatch", reason: expect.stringContaining("not lane server's") });
321
+ });
322
+ });
@@ -11,7 +11,7 @@ import { GENERATED_MARKER } from "../discovery/files";
11
11
  import type { CommandContext } from "../cli/registry";
12
12
  import { parseYAMLDocument } from "../yaml";
13
13
  import { runCiWorkflow } from "./ci-green-cli";
14
- import { BUILD_BLOCK_MARKER, buildTriggerEdits, CI_GREEN_WORKFLOW_FILE, dispatchableWorkflows, jobCheckRuns, renderCiGreenWorkflow, workflowsHolding, writeTopLevel } from "./ci-green-workflow";
14
+ import { BUILD_BLOCK_MARKER, buildTriggerEdits, CI_GREEN_WORKFLOW_FILE, dispatchableWorkflows, jobCheckRuns, MERGE_QUEUE_VERDICT_JOB, MERGE_QUEUE_WORKFLOW_FILE, MERGE_QUEUE_WORKFLOW_NAME, renderCiGreenWorkflow, workflowsHolding, writeTopLevel } from "./ci-green-workflow";
15
15
  import { parseDeclaration } from "./declaration";
16
16
  import { cleanScratch, declaration, git, scratchDir, writeFiles } from "./__fixtures__/contract-repo";
17
17
  import { ACTION_PINS, usesRef } from "../action-pins";
@@ -220,6 +220,40 @@ describe("chant ci workflow (#3573)", () => {
220
220
  }
221
221
  });
222
222
 
223
+ test("mergeQueue writes the verdict workflow and adds merge_group to the phases' workflows, byte-identically again (#4644)", async () => {
224
+ const root = scratchDir("chant-ci-workflow-");
225
+ git(root, "init", "-q");
226
+ const queued = { ...GREEN, phases: { ...GREEN.phases, lint: { runs: ["lint"], build: "every" }, test: { runs: ["test", "e2e (*)"], build: "newest" } }, mergeQueue: true };
227
+ const SPLIT = `name: lint\non: push\njobs:\n lint:\n runs-on: ubuntu-latest\n`;
228
+ const TESTS = `name: tests\non: push\njobs:\n test:\n runs-on: ubuntu-latest\n`;
229
+ writeFiles(root, { "chant.workspace.json": declaration([], { ci: { green: queued } }), ".github/workflows/lint.yml": SPLIT, ".github/workflows/tests.yml": TESTS, ".github/workflows/macos.yml": MACOS });
230
+ const cwd = vi.spyOn(process, "cwd").mockReturnValue(root);
231
+ const log = vi.spyOn(console, "log").mockImplementation(() => {});
232
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
233
+ try {
234
+ expect(await runCiWorkflow({ args: {} } as unknown as CommandContext)).toBe(0);
235
+ const queue = readFileSync(join(root, MERGE_QUEUE_WORKFLOW_FILE), "utf-8");
236
+ expect(queue.split("\n")[0]).toBe(`# ${GENERATED_MARKER}. Regenerate with: chant ci workflow (in the workspace root)`);
237
+ const q = parseYAMLDocument(queue) as Yaml;
238
+ expect(q.on).toEqual({ merge_group: { types: ["checks_requested"] } });
239
+ expect(q.permissions).toEqual({ contents: "read", checks: "read" });
240
+ expect(q.jobs[MERGE_QUEUE_VERDICT_JOB].steps.at(-1).run).toMatch(/^npx --yes @intentius\/chant@\S+ ci verdict --wait$/);
241
+ for (const f of ["lint.yml", "tests.yml"]) {
242
+ expect((parseYAMLDocument(readFileSync(join(root, ".github/workflows", f), "utf-8")) as Yaml).on.merge_group).toEqual({ types: ["checks_requested"] });
243
+ }
244
+ // The verdict's workflow holds no phase, so the tick doesn't listen to it.
245
+ expect((parseYAMLDocument(readFileSync(join(root, CI_GREEN_WORKFLOW_FILE), "utf-8")) as Yaml).on.workflow_run.workflows).not.toContain(MERGE_QUEUE_WORKFLOW_NAME);
246
+ const before = ["lint.yml", "tests.yml"].map((f) => readFileSync(join(root, ".github/workflows", f), "utf-8"));
247
+ expect(await runCiWorkflow({ args: {} } as unknown as CommandContext)).toBe(0);
248
+ expect(readFileSync(join(root, MERGE_QUEUE_WORKFLOW_FILE), "utf-8")).toBe(queue);
249
+ expect(["lint.yml", "tests.yml"].map((f) => readFileSync(join(root, ".github/workflows", f), "utf-8"))).toEqual(before);
250
+ } finally {
251
+ cwd.mockRestore();
252
+ log.mockRestore();
253
+ error.mockRestore();
254
+ }
255
+ });
256
+
223
257
  test("--token-secret goes into the file and its header, and without it the bytes are what they were", async () => {
224
258
  const root = scratchDir("chant-ci-workflow-");
225
259
  git(root, "init", "-q");
@@ -360,6 +394,18 @@ describe("the triggers of a phase that sets build (#4169)", () => {
360
394
  expect(again.map((e) => e.changed)).toEqual([false, false]);
361
395
  });
362
396
 
397
+ test("newest with skipped: pass says where a path filter gets its base, once (#4643)", () => {
398
+ const filtered = parseDeclaration(JSON.stringify({ name: "w", schema: 1, members: [], ci: { green: { ...BUILD_GREEN, phases: { ...BUILD_GREEN.phases, suites: { runs: ["suites"], build: "newest", skipped: "pass" } } } } }), "chant.workspace.json").ci!.green!;
399
+ const [edit] = buildTriggerEdits(filtered, [{ path: ".github/workflows/suites.yml", text: SUITES_WF }]);
400
+ expect(edit.text).toContain(`${BUILD_BLOCK_MARKER}\nconcurrency:\n # A job skipped by changed paths diffs against \`chant ci base --phase suites\``);
401
+ expect((parseYAMLDocument(edit.text) as Yaml).concurrency).toEqual({ group: "chant-build-suites-${{ github.ref }}", "cancel-in-progress": false });
402
+ const [again] = buildTriggerEdits(filtered, [{ path: edit.path, text: edit.text }]);
403
+ expect(again.changed).toBe(false);
404
+ // Without skipped: pass there is no filter to point at.
405
+ const [plain] = buildTriggerEdits(green(), [{ path: ".github/workflows/suites.yml", text: SUITES_WF }]);
406
+ expect(plain.text).not.toContain("chant ci base");
407
+ });
408
+
363
409
  test("a phase without build leaves its workflow alone, and one workflow holding both builds is refused", () => {
364
410
  const plain = parseDeclaration(JSON.stringify({ name: "w", schema: 1, members: [], ci: { green: { branch: "main", phases: { lint: ["lint"] }, require: ["lint"] } } }), "chant.workspace.json").ci!.green!;
365
411
  expect(buildTriggerEdits(plain, [{ path: ".github/workflows/ci.yml", text: LINT_WF }])).toEqual([]);
@@ -58,6 +58,10 @@ import { COMPOSE_BRANCH_PREFIX } from "../lifecycle/compose-refs";
58
58
  /** Where the workflow goes, relative to the repository root. */
59
59
  export const CI_GREEN_WORKFLOW_FILE = ".github/workflows/chant-ci-green.yml";
60
60
  export const CI_GREEN_WORKFLOW_NAME = "chant-ci-green";
61
+ /** The merge queue's verdict workflow (#4644), and the job its ruleset requires. */
62
+ export const MERGE_QUEUE_WORKFLOW_FILE = ".github/workflows/chant-merge-queue.yml";
63
+ export const MERGE_QUEUE_WORKFLOW_NAME = "chant-merge-queue";
64
+ export const MERGE_QUEUE_VERDICT_JOB = "chant-verdict";
61
65
 
62
66
  /** One workflow file as the scan reads it. */
63
67
  export interface WorkflowSource {
@@ -296,6 +300,51 @@ export function renderCiGreenWorkflow(input: WorkflowInput): string {
296
300
  return tagComments(lines.join("\n") + "\n");
297
301
  }
298
302
 
303
+ /**
304
+ * The merge queue's verdict workflow (#4644): on each group, `chant ci
305
+ * verdict --wait` judges the group's commit by `ci.green`'s required phases
306
+ * as the tick would, and its job, `chant-verdict`, is the one check the
307
+ * queue's ruleset requires. It reads check runs and writes nothing.
308
+ */
309
+ export function renderMergeQueueWorkflow(input: Omit<WorkflowInput, "workflows" | "push" | "runnerKeySecret" | "compose">): string {
310
+ const where = input.workspaceRoot === "." ? [] : [` working-directory: ${q(input.workspaceRoot)}`];
311
+ const cache = input.install && input.npmLock ? [" cache: npm", ...(input.npmLock === "package-lock.json" ? [] : [` cache-dependency-path: ${q(input.npmLock)}`])] : [];
312
+ const verdict = input.chant ? q(`${input.chant} ci verdict --wait`) : `npx --yes @intentius/chant@${input.chantVersion} ci verdict --wait`;
313
+ const lines = [
314
+ `name: ${MERGE_QUEUE_WORKFLOW_NAME}`,
315
+ "",
316
+ "# The merge queue's verdict: passes when every phase ci.green requires passed",
317
+ "# on the group's commit, judged as chant ci tick judges. Require its job,",
318
+ `# ${MERGE_QUEUE_VERDICT_JOB}, in the branch's ruleset.`,
319
+ "on:",
320
+ " merge_group:",
321
+ " types:",
322
+ " - checks_requested",
323
+ "",
324
+ "permissions:",
325
+ " contents: read",
326
+ " checks: read",
327
+ "",
328
+ "jobs:",
329
+ ` ${MERGE_QUEUE_VERDICT_JOB}:`,
330
+ " runs-on: ubuntu-latest",
331
+ " timeout-minutes: 120",
332
+ " steps:",
333
+ ` - uses: ${usesRef(ACTION_PINS.checkout6)}`,
334
+ ` - uses: ${usesRef(ACTION_PINS.setupNode6)}`,
335
+ " with:",
336
+ " node-version: \"24\"",
337
+ ...cache,
338
+ ...(input.install ? [" - name: Install what the verdict runs", ...where, ` run: ${q(input.install)}`] : []),
339
+ " - name: Wait for the required phases on the group's commit",
340
+ ...where,
341
+ " env:",
342
+ " GITHUB_TOKEN: ${{ github.token }}",
343
+ ` run: ${verdict}`,
344
+ ];
345
+ return tagComments(lines.join("\n") + "\n");
346
+ }
347
+
299
348
  /** Whether any phase sets `build` (#4169): then the tick may re-run jobs and start workflows. */
300
349
  export const declaresBuild = (green: CiGreen) => green.phases.some((p) => p.build !== undefined);
301
350
  /** Whether a required phase builds only the newest commit (#4169). */
@@ -374,8 +423,18 @@ export function buildTriggerEdits(green: CiGreen, sources: readonly WorkflowSour
374
423
  const withBranch = [...branches, ...greenBranches(green).filter((b) => !branches.includes(b))];
375
424
  push.branches = compose && !withBranch.includes(COMPOSE_BRANCHES) ? [...withBranch, COMPOSE_BRANCHES] : withBranch;
376
425
  const { push: _push, workflow_dispatch: dispatch, ...rest } = on;
426
+ // #4644: a merge queue's groups run the phases too.
427
+ if (green.mergeQueue && !("merge_group" in rest)) rest.merge_group = { types: ["checks_requested"] };
377
428
  text = writeTopLevel(text, "on", { push, workflow_dispatch: dispatch ?? {}, ...rest });
378
- text = writeTopLevel(text, "concurrency", { group: `chant-build-${tag}-\${{ github.ref }}`, "cancel-in-progress": false });
429
+ // #4643: a phase whose skipped jobs pass is one a path filter skips, and under newest the push's
430
+ // previous commit may never have been built, so the block says where such a filter gets its base.
431
+ const filtered = held.filter((p) => p.skipped === "pass").map((p) => p.name);
432
+ text = writeTopLevel(text, "concurrency", [
433
+ "concurrency:",
434
+ ...(filtered.length > 0 ? [` # A job skipped by changed paths diffs against \`chant ci base --phase ${filtered[0]}\`, not github.event.before, which a newer push may have kept from being built (#4643).`] : []),
435
+ ` group: chant-build-${tag}-\${{ github.ref }}`,
436
+ " cancel-in-progress: false",
437
+ ]);
379
438
  } else {
380
439
  const main = `refs/heads/${green.branch}`;
381
440
  const on = triggersOf(isObject(doc) ? doc.on : undefined);
@@ -387,6 +446,8 @@ export function buildTriggerEdits(green: CiGreen, sources: readonly WorkflowSour
387
446
  }
388
447
  // #4216: the tick starts the workflow by hand at a ci/build/<sha> tag when the forge ran nothing on a commit.
389
448
  if (!("workflow_dispatch" in next)) next = { ...next, workflow_dispatch: {} };
449
+ // #4644: a merge queue's groups run the phases too.
450
+ if (green.mergeQueue && !("merge_group" in next)) next = { ...next, merge_group: { types: ["checks_requested"] } };
390
451
  if (next !== on) text = writeTopLevel(text, "on", next);
391
452
  // #4220: a compose branch's commits each get a verdict, so its runs are keyed by commit, as the trunk branch's are.
392
453
  // #4325: each branch ci.green judges is keyed by commit.