@intentius/chant 0.124.76 → 0.124.78

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 (212) hide show
  1. package/dist/__fixtures__/agent-guard/plywood.d.ts +8 -0
  2. package/dist/__fixtures__/agent-guard/plywood.d.ts.map +1 -0
  3. package/dist/__fixtures__/agent-guard/plywood.js +19 -0
  4. package/dist/__fixtures__/agent-guard/terragucci.d.ts +8 -0
  5. package/dist/__fixtures__/agent-guard/terragucci.d.ts.map +1 -0
  6. package/dist/__fixtures__/agent-guard/terragucci.js +30 -0
  7. package/dist/__fixtures__/gated-ledger.d.ts +10 -0
  8. package/dist/__fixtures__/gated-ledger.d.ts.map +1 -0
  9. package/dist/__fixtures__/gated-ledger.js +51 -0
  10. package/dist/__fixtures__/notify-messages/events.d.ts +9 -0
  11. package/dist/__fixtures__/notify-messages/events.d.ts.map +1 -0
  12. package/dist/__fixtures__/notify-messages/events.js +21 -0
  13. package/dist/__fixtures__/product-words.d.ts +14 -0
  14. package/dist/__fixtures__/product-words.d.ts.map +1 -1
  15. package/dist/__fixtures__/product-words.js +11 -0
  16. package/dist/__fixtures__/terragucci-notify.d.ts +66 -0
  17. package/dist/__fixtures__/terragucci-notify.d.ts.map +1 -0
  18. package/dist/__fixtures__/terragucci-notify.js +133 -0
  19. package/dist/action-pins.d.ts +8 -0
  20. package/dist/action-pins.d.ts.map +1 -1
  21. package/dist/action-pins.js +9 -0
  22. package/dist/agent-guard.d.ts +143 -0
  23. package/dist/agent-guard.d.ts.map +1 -0
  24. package/dist/agent-guard.js +455 -0
  25. package/dist/ci-commit.d.ts +120 -5
  26. package/dist/ci-commit.d.ts.map +1 -1
  27. package/dist/ci-commit.js +214 -23
  28. package/dist/ci-own-jobs.d.ts +81 -0
  29. package/dist/ci-own-jobs.d.ts.map +1 -0
  30. package/dist/ci-own-jobs.js +233 -0
  31. package/dist/ci-product-words.d.ts +18 -4
  32. package/dist/ci-product-words.d.ts.map +1 -1
  33. package/dist/ci-product-words.js +26 -6
  34. package/dist/ci-product.d.ts +40 -1
  35. package/dist/ci-product.d.ts.map +1 -1
  36. package/dist/ci-product.js +40 -1
  37. package/dist/cli/handlers/approve.d.ts +5 -1
  38. package/dist/cli/handlers/approve.d.ts.map +1 -1
  39. package/dist/cli/handlers/approve.js +17 -11
  40. package/dist/cli/handlers/build.d.ts +1 -1
  41. package/dist/cli/handlers/build.d.ts.map +1 -1
  42. package/dist/cli/handlers/build.js +88 -2
  43. package/dist/cli/handlers/commit.d.ts.map +1 -1
  44. package/dist/cli/handlers/commit.js +3 -1
  45. package/dist/cli/handlers/notify-relay.d.ts +18 -1
  46. package/dist/cli/handlers/notify-relay.d.ts.map +1 -1
  47. package/dist/cli/handlers/notify-relay.js +90 -14
  48. package/dist/cli/handlers/pr.d.ts.map +1 -1
  49. package/dist/cli/handlers/pr.js +3 -1
  50. package/dist/cli/handlers/release.d.ts +5 -1
  51. package/dist/cli/handlers/release.d.ts.map +1 -1
  52. package/dist/cli/handlers/release.js +21 -9
  53. package/dist/cli/handlers/run-generate.d.ts.map +1 -1
  54. package/dist/cli/handlers/run-generate.js +2 -1
  55. package/dist/cli/main.d.ts.map +1 -1
  56. package/dist/cli/main.js +21 -1
  57. package/dist/cli/parse-args.d.ts.map +1 -1
  58. package/dist/cli/parse-args.js +60 -4
  59. package/dist/cli/registry.d.ts +16 -0
  60. package/dist/cli/registry.d.ts.map +1 -1
  61. package/dist/components/pr-env-components.d.ts +65 -0
  62. package/dist/components/pr-env-components.d.ts.map +1 -0
  63. package/dist/components/pr-env-components.js +162 -0
  64. package/dist/components/pr-policy.d.ts +15 -0
  65. package/dist/components/pr-policy.d.ts.map +1 -1
  66. package/dist/components/pr-policy.js +24 -1
  67. package/dist/components/release-compile.d.ts +15 -3
  68. package/dist/components/release-compile.d.ts.map +1 -1
  69. package/dist/components/release-compile.js +66 -15
  70. package/dist/config.d.ts +14 -8
  71. package/dist/config.d.ts.map +1 -1
  72. package/dist/config.js +16 -1
  73. package/dist/gate-policy.d.ts +14 -1
  74. package/dist/gate-policy.d.ts.map +1 -1
  75. package/dist/gate-policy.js +16 -6
  76. package/dist/lexicon.d.ts +25 -1
  77. package/dist/lexicon.d.ts.map +1 -1
  78. package/dist/lexicon.js +10 -0
  79. package/dist/lifecycle/gated-op.d.ts +95 -0
  80. package/dist/lifecycle/gated-op.d.ts.map +1 -0
  81. package/dist/lifecycle/gated-op.js +96 -0
  82. package/dist/lifecycle/git.d.ts.map +1 -1
  83. package/dist/lifecycle/git.js +83 -2
  84. package/dist/lifecycle/release-images.d.ts +77 -3
  85. package/dist/lifecycle/release-images.d.ts.map +1 -1
  86. package/dist/lifecycle/release-images.js +132 -6
  87. package/dist/notify-product.d.ts +11 -2
  88. package/dist/notify-product.d.ts.map +1 -1
  89. package/dist/notify-product.js +16 -4
  90. package/dist/notify-relay-repo.d.ts +131 -0
  91. package/dist/notify-relay-repo.d.ts.map +1 -0
  92. package/dist/notify-relay-repo.js +202 -0
  93. package/dist/notify-relay.d.ts +25 -1
  94. package/dist/notify-relay.d.ts.map +1 -1
  95. package/dist/notify-relay.js +27 -2
  96. package/dist/notify.d.ts +36 -4
  97. package/dist/notify.d.ts.map +1 -1
  98. package/dist/notify.js +31 -21
  99. package/dist/notify.schema.json +1 -0
  100. package/dist/op/activities/review-product.d.ts +111 -0
  101. package/dist/op/activities/review-product.d.ts.map +1 -0
  102. package/dist/op/activities/review-product.js +116 -0
  103. package/dist/op/op-waves-capability.js +2 -2
  104. package/dist/policy-engine.d.ts +95 -0
  105. package/dist/policy-engine.d.ts.map +1 -0
  106. package/dist/policy-engine.js +157 -0
  107. package/dist/pr-forge-reads.d.ts +124 -0
  108. package/dist/pr-forge-reads.d.ts.map +1 -0
  109. package/dist/pr-forge-reads.js +322 -0
  110. package/dist/pr-forge.d.ts +14 -0
  111. package/dist/pr-forge.d.ts.map +1 -1
  112. package/dist/pr-forge.js +21 -13
  113. package/dist/pr-plan-note.d.ts +293 -0
  114. package/dist/pr-plan-note.d.ts.map +1 -0
  115. package/dist/pr-plan-note.js +362 -0
  116. package/dist/release-floors.d.ts +9 -1
  117. package/dist/release-floors.d.ts.map +1 -1
  118. package/dist/release-floors.js +9 -1
  119. package/dist/state-export.d.ts +126 -0
  120. package/dist/state-export.d.ts.map +1 -0
  121. package/dist/state-export.js +156 -0
  122. package/dist/state-migration.d.ts +148 -0
  123. package/dist/state-migration.d.ts.map +1 -0
  124. package/dist/state-migration.js +146 -0
  125. package/dist/state-unlock.d.ts +167 -0
  126. package/dist/state-unlock.d.ts.map +1 -0
  127. package/dist/state-unlock.js +196 -0
  128. package/dist/wave-runtime.mjs +332 -332
  129. package/dist/workspace/declaration.schema.json +1 -1
  130. package/dist/workspace/release-workflow.d.ts +10 -0
  131. package/dist/workspace/release-workflow.d.ts.map +1 -1
  132. package/dist/workspace/release-workflow.js +10 -4
  133. package/package.json +1 -1
  134. package/src/__fixtures__/agent-guard/plywood.ts +27 -0
  135. package/src/__fixtures__/agent-guard/terragucci.ts +39 -0
  136. package/src/__fixtures__/gated-ledger.ts +58 -0
  137. package/src/__fixtures__/notify-messages/events.ts +23 -0
  138. package/src/__fixtures__/notify-messages/messages.json +50 -0
  139. package/src/__fixtures__/pr-loop/terragucci-plan.note.golden.md +53 -0
  140. package/src/__fixtures__/pr-loop/terragucci-plan.note.json +83 -0
  141. package/src/__fixtures__/product-words.ts +12 -0
  142. package/src/__fixtures__/review-agent/terragucci-review.json +94 -0
  143. package/src/__fixtures__/terragucci-notify.ts +170 -0
  144. package/src/action-pins.test.ts +12 -1
  145. package/src/action-pins.ts +11 -0
  146. package/src/agent-guard.test.ts +319 -0
  147. package/src/agent-guard.ts +547 -0
  148. package/src/ci-commit.test.ts +213 -2
  149. package/src/ci-commit.ts +258 -27
  150. package/src/ci-own-jobs.test.ts +108 -0
  151. package/src/ci-own-jobs.ts +252 -0
  152. package/src/ci-product-words.ts +35 -7
  153. package/src/ci-product.ts +81 -1
  154. package/src/cli/handlers/approve-cwd.test.ts +112 -0
  155. package/src/cli/handlers/approve.ts +22 -11
  156. package/src/cli/handlers/build-own-jobs.test.ts +80 -0
  157. package/src/cli/handlers/build-pr-loop-control.test.ts +87 -0
  158. package/src/cli/handlers/build-run-group.test.ts +59 -0
  159. package/src/cli/handlers/build.ts +83 -3
  160. package/src/cli/handlers/commit.ts +3 -0
  161. package/src/cli/handlers/notify-relay.ts +99 -17
  162. package/src/cli/handlers/pr.ts +3 -1
  163. package/src/cli/handlers/release.ts +20 -10
  164. package/src/cli/handlers/run-generate.ts +2 -1
  165. package/src/cli/main.ts +21 -1
  166. package/src/cli/parse-args.ts +45 -3
  167. package/src/cli/registry.ts +16 -0
  168. package/src/components/pr-env-components.test.ts +137 -0
  169. package/src/components/pr-env-components.ts +213 -0
  170. package/src/components/pr-policy.test.ts +41 -1
  171. package/src/components/pr-policy.ts +25 -1
  172. package/src/components/release-compile.test.ts +47 -0
  173. package/src/components/release-compile.ts +70 -13
  174. package/src/config.ts +23 -3
  175. package/src/gate-policy-bundle.test.ts +14 -0
  176. package/src/gate-policy.test.ts +7 -0
  177. package/src/gate-policy.ts +22 -7
  178. package/src/lexicon.ts +28 -1
  179. package/src/lifecycle/gated-op.ts +158 -0
  180. package/src/lifecycle/git.test.ts +92 -0
  181. package/src/lifecycle/git.ts +71 -2
  182. package/src/lifecycle/release-images-dockerfile.test.ts +221 -0
  183. package/src/lifecycle/release-images.ts +167 -8
  184. package/src/notify-message-words.test.ts +186 -0
  185. package/src/notify-product.ts +17 -4
  186. package/src/notify-relay-repo.test.ts +284 -0
  187. package/src/notify-relay-repo.ts +234 -0
  188. package/src/notify-relay.test.ts +12 -0
  189. package/src/notify-relay.ts +29 -3
  190. package/src/notify.schema.json +1 -0
  191. package/src/notify.ts +59 -19
  192. package/src/op/activities/review-product.test.ts +116 -0
  193. package/src/op/activities/review-product.ts +200 -0
  194. package/src/op/op-waves-capability.ts +2 -2
  195. package/src/op/schedule-overdue.test.ts +26 -0
  196. package/src/policy-engine.test.ts +162 -0
  197. package/src/policy-engine.ts +200 -0
  198. package/src/pr-forge-reads.test.ts +285 -0
  199. package/src/pr-forge-reads.ts +424 -0
  200. package/src/pr-forge.ts +30 -16
  201. package/src/pr-plan-note.test.ts +105 -0
  202. package/src/pr-plan-note.ts +521 -0
  203. package/src/release-floors.ts +13 -1
  204. package/src/state-export.test.ts +124 -0
  205. package/src/state-export.ts +227 -0
  206. package/src/state-migration.test.ts +133 -0
  207. package/src/state-migration.ts +236 -0
  208. package/src/state-unlock.test.ts +165 -0
  209. package/src/state-unlock.ts +293 -0
  210. package/src/workspace/declaration.schema.json +1 -1
  211. package/src/workspace/release-workflow.test.ts +34 -0
  212. package/src/workspace/release-workflow.ts +19 -4
@@ -0,0 +1,424 @@
1
+ /**
2
+ * Reads a product asks of a forge beside the ones `./pr-forge.ts` makes
3
+ * (#4809): the user the token acts as, a pull request with its author, URL,
4
+ * state and merge commit, the pull requests from a branch (or a branch
5
+ * prefix) in any state, every note on a pull request, GitHub's check runs on
6
+ * a commit, a pull request's commits, a collaborator's permission level, and
7
+ * every open pull request in the repository.
8
+ *
9
+ * They take the same options as the clients in `./pr-forge.ts` and live in
10
+ * their own module, imported only by the products that call them, so the
11
+ * pull-request loop's and the review agent's bundles do not grow for them
12
+ * (`./pr-forge-bundle.test.ts`, `./pr-loop-bundle.test.ts`,
13
+ * `./review-agent-bundle.test.ts`).
14
+ */
15
+
16
+ import {
17
+ ForgeApiError,
18
+ type ForgeFetch,
19
+ type ForgeKind,
20
+ type ForgeTarget,
21
+ type GithubForgeOptions,
22
+ type GitlabForgeOptions,
23
+ type OpenPullRequest,
24
+ } from "./pr-forge";
25
+
26
+ /** The user a token acts as: GitHub's and Forgejo's `login`, GitLab's `username`, and the forge's numeric id. */
27
+ export interface ForgeUser {
28
+ login: string;
29
+ id?: number;
30
+ }
31
+
32
+ /** A pull request (merge request) as {@link ForgeReads.pullRequest} reads it. */
33
+ export interface PullRequestDetail {
34
+ /** The pull request's number, or the merge request's iid. */
35
+ number: number;
36
+ url?: string;
37
+ title: string;
38
+ body: string;
39
+ state: "open" | "closed" | "merged";
40
+ /** Its head (source) branch. */
41
+ head: string;
42
+ /** The commit its head points at. */
43
+ headSha?: string;
44
+ /** Its base (target) branch. */
45
+ base?: string;
46
+ /** Who opened it. */
47
+ author?: string;
48
+ /** Its head branch lives in this repository, not a fork. */
49
+ sameRepo: boolean;
50
+ /**
51
+ * Once merged, the commit the merge made on the base branch: the merge or
52
+ * squash commit, or on GitLab the head itself after a fast-forward merge.
53
+ */
54
+ mergeCommit?: string;
55
+ /** When it last changed (ISO 8601). */
56
+ updated?: string;
57
+ }
58
+
59
+ /** A comment (note) on a pull request, as {@link ForgeReads.pullRequestNotes} reads it. */
60
+ export interface PullRequestNote {
61
+ id: number;
62
+ body: string;
63
+ author?: string;
64
+ /** The author's numeric id. */
65
+ authorId?: number;
66
+ /** GitLab's own note ("approved this merge request", "added 1 commit"). Always false on GitHub and Forgejo. */
67
+ system: boolean;
68
+ created?: string;
69
+ }
70
+
71
+ /** A GitHub check run on a commit. */
72
+ export interface CheckRun {
73
+ id: number;
74
+ name: string;
75
+ /** `queued`, `in_progress` or `completed`, and GitHub's other words for a run not done. */
76
+ status: string;
77
+ /** Once completed: `success`, `failure`, `neutral`, `cancelled`, `skipped`, `timed_out`, `action_required` or `stale`. */
78
+ conclusion?: string;
79
+ }
80
+
81
+ /** A person on a commit, as the forge records it. `login` only when the forge ties the address to an account (GitHub, Forgejo). */
82
+ export interface CommitPerson {
83
+ name?: string;
84
+ email?: string;
85
+ login?: string;
86
+ }
87
+
88
+ /** One of a pull request's commits. */
89
+ export interface PullRequestCommit {
90
+ sha: string;
91
+ message: string;
92
+ author: CommitPerson;
93
+ committer: CommitPerson;
94
+ }
95
+
96
+ /** What {@link ForgeReads.pullRequestsFrom} reads. */
97
+ export interface PullRequestsFromOptions {
98
+ /** Take every head branch that starts with the branch given, not only that branch. */
99
+ prefix?: boolean;
100
+ /** At most this many pull requests are read, newest update first. Default 500. */
101
+ limit?: number;
102
+ }
103
+
104
+ /** The reads, for GitHub, Forgejo and GitLab alike. */
105
+ export interface ForgeReads {
106
+ kind: ForgeKind;
107
+ /** The user the client's token acts as (`GET /user`). Undefined when the forge names none. */
108
+ tokenUser(): Promise<ForgeUser | undefined>;
109
+ /** A pull request in any state, or undefined when the forge has none by that number. */
110
+ pullRequest(pr: number): Promise<PullRequestDetail | undefined>;
111
+ /**
112
+ * The pull requests in any state whose head is `branch` (with `prefix`,
113
+ * whose head starts with it), from this repository, newest first by number.
114
+ */
115
+ pullRequestsFrom(branch: string, opts?: PullRequestsFromOptions): Promise<PullRequestDetail[]>;
116
+ /** Every comment on a pull request, GitLab's system notes among them, oldest first. */
117
+ pullRequestNotes(pr: number): Promise<PullRequestNote[]>;
118
+ /** GitHub's check runs on `sha`, the newest per name. Forgejo and GitLab have none and answer `[]`. */
119
+ checkRuns(sha: string): Promise<CheckRun[]>;
120
+ /** A pull request's commits, in the order the forge lists them. */
121
+ pullRequestCommits(pr: number): Promise<PullRequestCommit[]>;
122
+ /**
123
+ * The permission `login` holds on the repository: GitHub's `admin`,
124
+ * `maintain`, `write`, `triage`, `read` or `none`; Forgejo's `owner`,
125
+ * `admin`, `write`, `read` or `none`; GitLab's `guest`, `reporter`,
126
+ * `developer`, `maintainer` or `owner` (project or inherited). Undefined
127
+ * when the forge knows no such user or member.
128
+ */
129
+ permission(login: string): Promise<string | undefined>;
130
+ /** Every open pull request in the repository, into any base, ascending by number. */
131
+ openPullRequests(): Promise<OpenPullRequest[]>;
132
+ }
133
+
134
+ interface Get {
135
+ (path: string): Promise<unknown>;
136
+ /** Pages of a list until one comes back short, at most `max` items. */
137
+ list(path: string, max?: number): Promise<unknown[]>;
138
+ }
139
+
140
+ function getter(base: string, headers: Record<string, string>, fetchImpl: ForgeFetch, pageSize: number, pageParams: (page: number) => string): Get {
141
+ const root = base.replace(/\/+$/, "");
142
+ const get = (async (path: string) => {
143
+ const url = `${root}${path}`;
144
+ const res = await fetchImpl(url, { method: "GET", headers });
145
+ const text = await res.text();
146
+ if (!res.ok) throw new ForgeApiError("GET", url, res.status, text);
147
+ return text ? JSON.parse(text) : null;
148
+ }) as Get;
149
+ get.list = async (path, max = 50 * pageSize) => {
150
+ const out: unknown[] = [];
151
+ for (let page = 1; out.length < max; page++) {
152
+ const items = await get(`${path}${path.includes("?") ? "&" : "?"}${pageParams(page)}`);
153
+ if (!Array.isArray(items)) break;
154
+ out.push(...items);
155
+ if (items.length < pageSize) break;
156
+ }
157
+ return out.slice(0, max);
158
+ };
159
+ return get;
160
+ }
161
+
162
+ const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
163
+ const str = (v: unknown): string | undefined => (typeof v === "string" && v !== "" ? v : undefined);
164
+ const num = (v: unknown): number | undefined => (typeof v === "number" ? v : typeof v === "string" && /^\d+$/.test(v) ? Number(v) : undefined);
165
+ const notFound = (err: unknown): boolean => err instanceof ForgeApiError && err.status === 404;
166
+ const newestFirst = (a: { number: number }, b: { number: number }): number => b.number - a.number;
167
+ const defined = <T>(v: T | undefined): v is T => v !== undefined;
168
+ const person = (name: unknown, email: unknown, login?: unknown): CommitPerson => {
169
+ const n = str(name);
170
+ const e = str(email);
171
+ const l = str(login);
172
+ return { ...(n ? { name: n } : {}), ...(e ? { email: e } : {}), ...(l ? { login: l } : {}) };
173
+ };
174
+ const userOf = (v: unknown, field: "login" | "username"): ForgeUser | undefined => {
175
+ const login = isObject(v) ? str(v[field]) : undefined;
176
+ const id = isObject(v) ? num(v.id) : undefined;
177
+ return login ? { login, ...(id !== undefined ? { id } : {}) } : undefined;
178
+ };
179
+ const orUndefined = async <T>(read: Promise<T>): Promise<T | undefined> => {
180
+ try {
181
+ return await read;
182
+ } catch (err) {
183
+ if (notFound(err)) return undefined;
184
+ throw err;
185
+ }
186
+ };
187
+ const DEFAULT_LIMIT = 500;
188
+
189
+ function githubShapedReads(kind: "github" | "forgejo", opts: GithubForgeOptions): ForgeReads {
190
+ const headers =
191
+ kind === "github"
192
+ ? { ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}), Accept: "application/vnd.github+json" }
193
+ : { ...(opts.token ? { Authorization: `token ${opts.token}` } : {}), Accept: "application/json" };
194
+ // GitHub pages with per_page (up to 100); Forgejo with limit (capped at 50 by default).
195
+ const pageSize = kind === "github" ? 100 : 50;
196
+ const get = getter(opts.apiBase, headers, opts.fetch ?? (globalThis.fetch as unknown as ForgeFetch), pageSize, (page) => (kind === "github" ? `per_page=100&page=${page}` : `limit=50&page=${page}`));
197
+ const repo = `/repos/${opts.repo}`;
198
+ const sameRepo = (v: Record<string, unknown>): boolean => {
199
+ const full = isObject(v.head) && isObject(v.head.repo) ? str(v.head.repo.full_name) : undefined;
200
+ return full === undefined || full.toLowerCase() === opts.repo.toLowerCase();
201
+ };
202
+ const detail = (v: unknown): PullRequestDetail | undefined => {
203
+ if (!isObject(v)) return undefined;
204
+ const number = num(v.number);
205
+ if (number === undefined) return undefined;
206
+ const head = isObject(v.head) ? v.head : {};
207
+ const merged = v.merged === true || !!str(v.merged_at);
208
+ const mergeCommit = merged ? str(v.merge_commit_sha) : undefined;
209
+ const fields = {
210
+ url: str(v.html_url),
211
+ headSha: str(head.sha),
212
+ base: isObject(v.base) ? str(v.base.ref) : undefined,
213
+ author: isObject(v.user) ? str(v.user.login) : undefined,
214
+ mergeCommit,
215
+ updated: str(v.updated_at),
216
+ };
217
+ const out: PullRequestDetail = { number, title: str(v.title) ?? "", body: str(v.body) ?? "", state: merged ? "merged" : v.state === "open" ? "open" : "closed", head: str(head.ref) ?? "", sameRepo: sameRepo(v) };
218
+ for (const [k, val] of Object.entries(fields)) if (val !== undefined) (out as unknown as Record<string, unknown>)[k] = val;
219
+ return out;
220
+ };
221
+ /** Forgejo answers a pull request list with 404 while the repository is still empty; a missing repository 404s on its own read too. */
222
+ const pulls = async (query: string, max?: number): Promise<unknown[]> => {
223
+ try {
224
+ return await get.list(`${repo}/pulls?${query}`, max);
225
+ } catch (err) {
226
+ if (kind !== "forgejo" || !notFound(err)) throw err;
227
+ await get(repo);
228
+ return [];
229
+ }
230
+ };
231
+ return {
232
+ kind,
233
+ tokenUser: async () => userOf(await get("/user"), "login"),
234
+ pullRequest: async (pr) => detail(await orUndefined(get(`${repo}/pulls/${pr}`))),
235
+ async pullRequestsFrom(branch, o = {}) {
236
+ const limit = o.limit ?? DEFAULT_LIMIT;
237
+ // GitHub filters an exact head (`owner:branch`) server-side; Forgejo's list takes no head filter.
238
+ const exactOnGithub = kind === "github" && !o.prefix;
239
+ const query = exactOnGithub
240
+ ? `state=all&head=${encodeURIComponent(`${opts.repo.split("/")[0]}:${branch}`)}`
241
+ : kind === "github"
242
+ ? "state=all&sort=updated&direction=desc"
243
+ : "state=all&sort=recentupdate";
244
+ const listed = (await pulls(query, limit)).map(detail).filter(defined);
245
+ return listed.filter((p) => p.sameRepo && (o.prefix ? p.head.startsWith(branch) : p.head === branch)).sort(newestFirst);
246
+ },
247
+ async pullRequestNotes(pr) {
248
+ const out: PullRequestNote[] = [];
249
+ for (const c of await get.list(`${repo}/issues/${pr}/comments`)) {
250
+ const id = isObject(c) ? num(c.id) : undefined;
251
+ if (!isObject(c) || id === undefined) continue;
252
+ const author = isObject(c.user) ? str(c.user.login) : undefined;
253
+ const authorId = isObject(c.user) ? num(c.user.id) : undefined;
254
+ const created = str(c.created_at);
255
+ out.push({ id, body: str(c.body) ?? "", ...(author ? { author } : {}), ...(authorId !== undefined ? { authorId } : {}), system: false, ...(created ? { created } : {}) });
256
+ }
257
+ return out;
258
+ },
259
+ async checkRuns(sha) {
260
+ if (kind !== "github") return [];
261
+ // The check runs list is an object ({ total_count, check_runs }), not an array, so it is paged here.
262
+ const runs: Record<string, unknown>[] = [];
263
+ for (let page = 1; page <= 50; page++) {
264
+ const got = await get(`${repo}/commits/${sha}/check-runs?per_page=100&page=${page}`);
265
+ const items = isObject(got) && Array.isArray(got.check_runs) ? got.check_runs.filter(isObject) : [];
266
+ runs.push(...items);
267
+ if (items.length < 100) break;
268
+ }
269
+ const newest = new Map<string, CheckRun>();
270
+ for (const r of runs) {
271
+ const id = num(r.id);
272
+ const name = str(r.name);
273
+ if (id === undefined || !name) continue;
274
+ const conclusion = str(r.conclusion);
275
+ const had = newest.get(name);
276
+ if (!had || id > had.id) newest.set(name, { id, name, status: str(r.status) ?? "queued", ...(conclusion ? { conclusion } : {}) });
277
+ }
278
+ return [...newest.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
279
+ },
280
+ async pullRequestCommits(pr) {
281
+ const out: PullRequestCommit[] = [];
282
+ for (const c of await get.list(`${repo}/pulls/${pr}/commits`)) {
283
+ const sha = isObject(c) ? str(c.sha) : undefined;
284
+ if (!isObject(c) || !sha) continue;
285
+ const git = isObject(c.commit) ? c.commit : {};
286
+ const a = isObject(git.author) ? git.author : {};
287
+ const m = isObject(git.committer) ? git.committer : {};
288
+ out.push({ sha, message: str(git.message) ?? "", author: person(a.name, a.email, isObject(c.author) ? c.author.login : undefined), committer: person(m.name, m.email, isObject(c.committer) ? c.committer.login : undefined) });
289
+ }
290
+ return out;
291
+ },
292
+ async permission(login) {
293
+ let got: unknown;
294
+ try {
295
+ got = await get(`${repo}/collaborators/${encodeURIComponent(login)}/permission`);
296
+ } catch (err) {
297
+ // GitHub answers 404 for a user it does not know; Forgejo 403 or 404 for one who is no collaborator.
298
+ if (err instanceof ForgeApiError && (err.status === 404 || err.status === 403)) return undefined;
299
+ throw err;
300
+ }
301
+ return isObject(got) ? str(got.permission) : undefined;
302
+ },
303
+ async openPullRequests() {
304
+ const out: OpenPullRequest[] = [];
305
+ for (const v of await pulls("state=open")) {
306
+ if (!isObject(v) || !isObject(v.head) || !isObject(v.base)) continue;
307
+ const number = num(v.number);
308
+ const head = str(v.head.ref);
309
+ const headSha = str(v.head.sha);
310
+ const base = str(v.base.ref);
311
+ if (number === undefined || !head || !headSha || !base) continue;
312
+ const baseSha = str(v.base.sha);
313
+ const author = isObject(v.user) ? str(v.user.login) : undefined;
314
+ out.push({ number, head, headSha, base, ...(baseSha ? { baseSha } : {}), ...(author ? { author } : {}), fork: !sameRepo(v) });
315
+ }
316
+ return out.sort((a, b) => a.number - b.number);
317
+ },
318
+ };
319
+ }
320
+
321
+ /** GitLab's access levels, by the number its API answers. */
322
+ const GITLAB_ROLES: Record<number, string> = { 5: "minimal", 10: "guest", 15: "planner", 20: "reporter", 30: "developer", 40: "maintainer", 50: "owner" };
323
+
324
+ /** The reads for a GitHub client's options. */
325
+ export function githubReads(opts: GithubForgeOptions): ForgeReads {
326
+ return githubShapedReads("github", opts);
327
+ }
328
+
329
+ /** The reads for a Forgejo (or Gitea) client's options. */
330
+ export function forgejoReads(opts: GithubForgeOptions): ForgeReads {
331
+ return githubShapedReads("forgejo", opts);
332
+ }
333
+
334
+ /** The reads for a GitLab client's options. */
335
+ export function gitlabReads(opts: GitlabForgeOptions): ForgeReads {
336
+ const get = getter(opts.apiBase, opts.token ? { [opts.tokenHeader ?? "PRIVATE-TOKEN"]: opts.token } : {}, opts.fetch ?? (globalThis.fetch as unknown as ForgeFetch), 100, (page) => `per_page=100&page=${page}`);
337
+ const project = `/projects/${encodeURIComponent(decodeURIComponent(opts.project))}`;
338
+ const mrs = `${project}/merge_requests`;
339
+ const own = (v: Record<string, unknown>): boolean => num(v.source_project_id) === undefined || num(v.source_project_id) === num(v.target_project_id);
340
+ const detail = (v: unknown): PullRequestDetail | undefined => {
341
+ if (!isObject(v)) return undefined;
342
+ const number = num(v.iid);
343
+ if (number === undefined) return undefined;
344
+ const state = v.state === "merged" ? "merged" : v.state === "opened" ? "open" : "closed";
345
+ // A fast-forward merge makes no merge commit: the head is then what the base points at.
346
+ const mergeCommit = state === "merged" ? (str(v.merge_commit_sha) ?? str(v.squash_commit_sha) ?? str(v.sha)) : undefined;
347
+ const fields = {
348
+ url: str(v.web_url),
349
+ headSha: str(v.sha),
350
+ base: str(v.target_branch),
351
+ author: isObject(v.author) ? str(v.author.username) : undefined,
352
+ mergeCommit,
353
+ updated: str(v.updated_at),
354
+ };
355
+ const out: PullRequestDetail = { number, title: str(v.title) ?? "", body: str(v.description) ?? "", state, head: str(v.source_branch) ?? "", sameRepo: own(v) };
356
+ for (const [k, val] of Object.entries(fields)) if (val !== undefined) (out as unknown as Record<string, unknown>)[k] = val;
357
+ return out;
358
+ };
359
+ return {
360
+ kind: "gitlab",
361
+ tokenUser: async () => userOf(await get("/user"), "username"),
362
+ pullRequest: async (mr) => detail(await orUndefined(get(`${mrs}/${mr}`))),
363
+ async pullRequestsFrom(branch, o = {}) {
364
+ const query = o.prefix ? "state=all&order_by=updated_at&sort=desc" : `state=all&source_branch=${encodeURIComponent(branch)}&order_by=updated_at&sort=desc`;
365
+ const listed = (await get.list(`${mrs}?${query}`, o.limit ?? DEFAULT_LIMIT)).map(detail).filter(defined);
366
+ return listed.filter((m) => m.sameRepo && (o.prefix ? m.head.startsWith(branch) : m.head === branch)).sort(newestFirst);
367
+ },
368
+ async pullRequestNotes(mr) {
369
+ const out: PullRequestNote[] = [];
370
+ for (const n of await get.list(`${mrs}/${mr}/notes?sort=asc&order_by=created_at`)) {
371
+ const id = isObject(n) ? num(n.id) : undefined;
372
+ if (!isObject(n) || id === undefined) continue;
373
+ const author = isObject(n.author) ? str(n.author.username) : undefined;
374
+ const authorId = isObject(n.author) ? num(n.author.id) : undefined;
375
+ const created = str(n.created_at);
376
+ out.push({ id, body: str(n.body) ?? "", ...(author ? { author } : {}), ...(authorId !== undefined ? { authorId } : {}), system: n.system === true, ...(created ? { created } : {}) });
377
+ }
378
+ return out;
379
+ },
380
+ checkRuns: async () => [],
381
+ async pullRequestCommits(mr) {
382
+ const out: PullRequestCommit[] = [];
383
+ for (const c of await get.list(`${mrs}/${mr}/commits`)) {
384
+ const sha = isObject(c) ? str(c.id) : undefined;
385
+ if (!isObject(c) || !sha) continue;
386
+ out.push({ sha, message: str(c.message) ?? "", author: person(c.author_name, c.author_email), committer: person(c.committer_name, c.committer_email) });
387
+ }
388
+ return out;
389
+ },
390
+ async permission(login) {
391
+ const users = await get(`/users?username=${encodeURIComponent(login)}`);
392
+ const id = Array.isArray(users) ? users.map((u) => (isObject(u) && u.username === login ? num(u.id) : undefined)).find(defined) : undefined;
393
+ if (id === undefined) return undefined;
394
+ const member = await orUndefined(get(`${project}/members/all/${id}`));
395
+ const level = isObject(member) ? num(member.access_level) : undefined;
396
+ return level === undefined ? undefined : (GITLAB_ROLES[level] ?? String(level));
397
+ },
398
+ async openPullRequests() {
399
+ const out: OpenPullRequest[] = [];
400
+ for (const m of await get.list(`${mrs}?state=opened`)) {
401
+ if (!isObject(m)) continue;
402
+ const number = num(m.iid);
403
+ const head = str(m.source_branch);
404
+ const headSha = str(m.sha);
405
+ const base = str(m.target_branch);
406
+ if (number === undefined || !head || !headSha || !base) continue;
407
+ const baseSha = isObject(m.diff_refs) ? str(m.diff_refs.base_sha) : undefined;
408
+ const author = isObject(m.author) ? str(m.author.username) : undefined;
409
+ out.push({ number, head, headSha, base, ...(baseSha ? { baseSha } : {}), ...(author ? { author } : {}), fork: !own(m) });
410
+ }
411
+ return out.sort((a, b) => a.number - b.number);
412
+ },
413
+ };
414
+ }
415
+
416
+ /** The reads for a {@link ForgeTarget}, the way `forgeClient` builds its client. */
417
+ export function forgeReadsFor(target: ForgeTarget, fetchImpl?: ForgeFetch): ForgeReads {
418
+ const f = fetchImpl ? { fetch: fetchImpl } : {};
419
+ if (target.kind === "gitlab") {
420
+ return gitlabReads({ apiBase: target.apiBase, project: target.repo, token: target.token, host: target.host, ...(target.tokenHeader ? { tokenHeader: target.tokenHeader } : {}), ...f });
421
+ }
422
+ const opts = { apiBase: target.apiBase, repo: target.repo, token: target.token, host: target.host, ...f };
423
+ return target.kind === "forgejo" ? forgejoReads(opts) : githubReads(opts);
424
+ }
package/src/pr-forge.ts CHANGED
@@ -661,6 +661,16 @@ function checksVerdict(what: string, head: string, failing: string[], waiting: s
661
661
  export interface ScheduledRunsQuery {
662
662
  /** The Op's name, the value of GitLab's `CHANT_SCHEDULED_OP` selector. */
663
663
  op: string;
664
+ /**
665
+ * GitLab: pick the schedules the way the Op's `gitlab.scheduleRule` does,
666
+ * in place of `CHANT_SCHEDULED_OP` set to `op` (#4813). A schedule is
667
+ * picked when its `variable` is `value` (any value, or none, when `value`
668
+ * is left out) and is none of `not`. A schedule without the variable
669
+ * compares as unset, as a `rules: if:` reads it, so terragucci's drift
670
+ * rule, every schedule whose `TERRAGUCCI_SCHEDULE` is not one of its
671
+ * other schedules', is `{ variable: "TERRAGUCCI_SCHEDULE", not: ["comments", "resume", "rollouts", "ephemeral"] }`.
672
+ */
673
+ schedule?: { variable: string; value?: string; not?: readonly string[] };
664
674
  /** GitHub and Forgejo: the Op's workflow file name, such as `drift-watch.yml`. */
665
675
  workflow: string;
666
676
  }
@@ -964,12 +974,13 @@ function githubShaped(kind: "github" | "forgejo", opts: GithubForgeOptions): Git
964
974
  comments: async (pr) => threads(await api.list(`${repo}/issues/${pr}/comments`, pageParams, pageSize)),
965
975
  addComment: async (pr, body) => thread(await api.call("POST", `${repo}/issues/${pr}/comments`, { body })),
966
976
  editComment: async (_pr, id, body) => thread(await api.call("PATCH", `${repo}/issues/comments/${id}`, { body })),
967
- // Paged in full rather than searched: GitHub's search index lags a
968
- // write, so a run straight after another would miss the issue it just
969
- // opened, and Forgejo has no `/search/issues` at all. Both list pull
970
- // requests among issues; one of those is never ours.
971
- openIssues: async () =>
972
- threads((await api.list(`${repo}/issues?state=open`, pageParams, pageSize)).filter((i) => isObject(i) && !isObject(i.pull_request))),
977
+ async openIssues() {
978
+ // Paged in full rather than searched: GitHub's search index lags a
979
+ // write, so a run straight after another would miss the issue it just
980
+ // opened, and Forgejo has no `/search/issues` at all. Both list pull
981
+ // requests among issues; one of those is never ours.
982
+ return threads((await api.list(`${repo}/issues?state=open`, pageParams, pageSize)).filter((i) => isObject(i) && !isObject(i.pull_request)));
983
+ },
973
984
  openIssue: async (title, body) => thread(await api.call("POST", `${repo}/issues`, { title, body })),
974
985
  editIssue: async (n, title, body) => thread(await api.call("PATCH", `${repo}/issues/${n}`, { title, body })),
975
986
  async closeIssue(n, comment) {
@@ -1421,13 +1432,12 @@ export function gitlabForge(opts: GitlabForgeOptions): PrForge {
1421
1432
  .filter((n): n is Thread => n !== undefined),
1422
1433
  addComment: async (mr, body) => note(await api.call("POST", `${notes}/${mr}/notes`, { body })),
1423
1434
  editComment: async (mr, id, body) => note(await api.call("PUT", `${notes}/${mr}/notes/${id}`, { body })),
1424
- // `search` narrows the list server-side to issues whose description
1425
- // carries the marker, as `reconcilePr`'s GitLab issue does (#2292); the
1426
- // match itself is still decided here.
1427
- openIssues: async (marker) =>
1428
- (await api.list(`${project}/issues?state=opened&search=${encodeURIComponent(marker)}&in=description`, pageParams, 100))
1429
- .map(issue)
1430
- .filter((i): i is Thread => i !== undefined),
1435
+ async openIssues(marker) {
1436
+ // `search` narrows the list server-side to issues whose description
1437
+ // carries the marker, as `reconcilePr`'s GitLab issue does (#2292); the
1438
+ // match itself is still decided here.
1439
+ return (await api.list(`${project}/issues?state=opened&search=${encodeURIComponent(marker)}&in=description`, pageParams, 100)).map(issue).filter((i): i is Thread => i !== undefined);
1440
+ },
1431
1441
  openIssue: async (title, body) => issue(await api.call("POST", `${project}/issues`, { title, description: body })),
1432
1442
  editIssue: async (n, title, body) => issue(await api.call("PUT", `${project}/issues/${n}`, { title, description: body })),
1433
1443
  async closeIssue(n, comment) {
@@ -1612,9 +1622,13 @@ export function gitlabForge(opts: GitlabForgeOptions): PrForge {
1612
1622
  .sort(byNumber)[0];
1613
1623
  },
1614
1624
  async scheduledRuns(q) {
1615
- // The variable the gitlab lexicon's generated Op file selects a scheduled job by.
1616
- const selects = (d: unknown): boolean =>
1617
- isObject(d) && Array.isArray(d.variables) && d.variables.some((v) => isObject(v) && v.key === "CHANT_SCHEDULED_OP" && v.value === q.op);
1625
+ // The variable the gitlab lexicon's generated Op file selects a scheduled job by, or the Op's scheduleRule's.
1626
+ const { variable, value, not } = q.schedule ?? { variable: "CHANT_SCHEDULED_OP", value: q.op };
1627
+ const selects = (d: unknown): boolean => {
1628
+ if (!isObject(d)) return false;
1629
+ const got = (Array.isArray(d.variables) ? d.variables : []).find((v) => isObject(v) && v.key === variable)?.value;
1630
+ return (value === undefined || got === value) && !not?.includes(got);
1631
+ };
1618
1632
  const schedules = await api.list(`${project}/pipeline_schedules?scope=active`, pageParams, 100);
1619
1633
  // A schedule's variables are on each schedule, not the list.
1620
1634
  const details = await Promise.all(schedules.map((s) => api.call("GET", `${project}/pipeline_schedules/${isObject(s) ? num(s.id) : ""}`)));
@@ -0,0 +1,105 @@
1
+ /**
2
+ * A product's plan note (#4810): a report the product builds from its own
3
+ * plan run, rendered by chant in the product's words. The golden is
4
+ * terragucci's own (its test/__golden__/note.recurring.md), copied byte for
5
+ * byte, and the input is the report terragucci hands chant for that plan.
6
+ */
7
+ import { readFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { describe, expect, test } from "vitest";
10
+ import { renderPrNote as renderPrLoopNote, type PrReport } from "./pr-loop";
11
+ import { diffFence, diffLines, isPlanNote, planNoteMarker, renderPlanNote, renderPrNote, type PrPlanNote } from "./pr-plan-note";
12
+ import { assertProductWords } from "./ci-product-words";
13
+ import { PLYWOOD, TERRAGUCCI, TERRAGUCCI_NOTE, YODEL } from "./__fixtures__/product-words";
14
+
15
+ const DIR = join(import.meta.dirname, "__fixtures__", "pr-loop");
16
+ const read = (name: string): string => readFileSync(join(DIR, name), "utf-8");
17
+ const input = (): PrPlanNote => JSON.parse(read("terragucci-plan.note.json")) as PrPlanNote;
18
+ const words = assertProductWords(TERRAGUCCI);
19
+ const tg = { words, note: TERRAGUCCI_NOTE };
20
+
21
+ const PLAN = [
22
+ "OpenTofu will perform the following actions:",
23
+ "",
24
+ " # aws_sqs_queue.jobs will be updated in-place",
25
+ ' ~ resource "aws_sqs_queue" "jobs" {',
26
+ " ~ visibility_timeout_seconds = 60 -> 90",
27
+ " }",
28
+ "",
29
+ "Plan: 0 to add, 1 to change, 0 to destroy.",
30
+ ].join("\n");
31
+
32
+ describe("terragucci's plan note from chant (#4810)", () => {
33
+ test("is terragucci's golden, byte for byte", () => {
34
+ expect(renderPlanNote(input(), tg)).toBe(read("terragucci-plan.note.golden.md"));
35
+ expect(renderPrNote(input(), tg)).toBe(read("terragucci-plan.note.golden.md"));
36
+ });
37
+
38
+ test("a pull request loop report renders as the pr loop renders it, in every product's words", () => {
39
+ const report = JSON.parse(read("pr-plan.golden.json")) as PrReport;
40
+ expect(isPlanNote(report)).toBe(false);
41
+ expect(renderPrNote(report, { approver: "github:<your-login>" })).toBe(read("pr-plan.note.golden.md"));
42
+ for (const w of [PLYWOOD, YODEL, TERRAGUCCI]) {
43
+ const product = assertProductWords(w);
44
+ expect(renderPrNote(report, { words: product })).toBe(renderPrLoopNote(report, { words: product }));
45
+ }
46
+ });
47
+
48
+ test("a group shows its first unit's diff, and each unit's whole plan follows with its plan file", () => {
49
+ const note = renderPlanNote({ ...input(), unit: "member", groups: [{ id: "g1", units: ["app", "api"], changes: [{ line: "~ aws_sqs_queue.jobs", count: 2 }], diff: { unit: "app", lines: PLAN.split("\n").slice(2, 6) } }], sections: [], plans: [{ member: "app", text: PLAN, totals: "Plan: 0 to add, 1 to change, 0 to destroy.", file: "roots/app/plan.txt" }] }, tg);
50
+ expect(note).toContain("#### [Group g1](report.html#group-g1): 2 roots, identical change\n\nAs `app` plans it:\n\n```diff\n # aws_sqs_queue.jobs will be updated in-place\n~ resource \"aws_sqs_queue\" \"jobs\" {\n~ visibility_timeout_seconds = 60 -> 90\n }\n```\n\nRoots: `app`, `api`\n\n");
51
+ expect(note).toContain("**Each root's plan:**\n\n<details><summary><code>app</code>: Plan: 0 to add, 1 to change, 0 to destroy.</summary>");
52
+ expect(note).toContain("[plan.txt](roots/app/plan.txt)\n\n</details>");
53
+ });
54
+
55
+ test("over the limit the whole plans go first, then diffs shrink, and a Cut line names what went", () => {
56
+ const base = { ...input(), unit: "member" as const, sections: [], groups: [{ id: "g1", units: ["app"], changes: [{ line: "~ aws_sqs_queue.jobs", count: 1 }], diff: { unit: "app", lines: PLAN.split("\n").slice(2, 6) } }], plans: [{ member: "app", text: PLAN, file: "roots/app/plan.txt" }] };
57
+ const whole = renderPlanNote(base, tg);
58
+ const cut = renderPlanNote(base, { ...tg, limit: [...whole].length - 10 });
59
+ expect(cut).not.toContain("<details>");
60
+ expect(cut).toContain("```diff");
61
+ expect(cut).toContain(`**Cut:** this note leaves out the whole plans of 1 root ([\`app\`](roots/app/plan.txt)), to stay within ${[...whole].length - 10} characters. [The full report](report.html) has all of it, and each root's plan.txt the whole plan.\n`);
62
+ const tighter = renderPlanNote(base, { ...tg, limit: [...whole].length - 400 });
63
+ expect(tighter).toContain("shows one group by attribute name, without the diff");
64
+ expect(tighter).toContain("- [`app: aws_s3_bucket_acl.logs`](report.html#root-app) (replace, forced by `acl`)");
65
+ });
66
+
67
+ test("the report links three ways, and the run that keeps none", () => {
68
+ expect(renderPlanNote({ ...input(), links: { report: "https://ci/run/9", artifacts: true } }, tg)).toContain("The full report is `report.html` in the `terragucci-report` artifact of [this run](https://ci/run/9).");
69
+ expect(renderPlanNote({ ...input(), links: { report: "https://b/x/report.html?sig=1", expires: "2026-10-15T10:03:22.000Z" } }, tg)).toContain("[Full report](https://b/x/report.html?sig=1) The links to the bucket work until 2026-10-15 10:03 UTC.");
70
+ const none = renderPlanNote({ ...input(), links: { run: "https://ci/run/9" } }, tg);
71
+ expect(none).toContain("Planned in [this run](https://ci/run/9), which keeps no report artifact; with `reports` set, the note links the report in the bucket.");
72
+ expect(none).toContain("- `app: aws_s3_bucket_acl.logs` (replace, forced by `acl`)");
73
+ });
74
+
75
+ test("the wave table says why a wave waits, its approve line under sealed approval, and its approval rules", () => {
76
+ const note = renderPlanNote({ ...input(), sealed: true, waves: [{ number: 1, units: 2, digest: "d1", waits: true, unknownBy: ["app"], approvalRules: [{ units: ["app"], asks: "2 approvals" }] }, { number: 2, units: 1, digest: null, replansAfter: [1], waits: true }, { number: 3, units: 1, digest: "d3", policy: { outcome: "unattended", rules: ["ok"] } }] }, tg);
77
+ expect(note).toContain("| 1 | 2 | `d1` | waits for an approval: `terragucci approve wave-1 --plan d1 --sign` (since `app` reads a value unknown at plan time); approval_rules: `app` 2 approvals |");
78
+ expect(note).toContain("| 2 | 1 | after the re-plan | plans again once wave 1 applies, then waits for an approval of that plan |");
79
+ expect(note).toContain("| 3 | 1 | `d3` | applies without an approval: allowed unattended by `ok` |");
80
+ expect(note).toContain(planNoteMarker("terragucci:waves", { head: input().head, waves: [{ number: 1, digest: "d1", waits: true }, { number: 2, digest: null, waits: true }, { number: 3, digest: "d3", waits: false }] }));
81
+ });
82
+
83
+ test("policy overrides and warnings, deferred units and units planned on planned outputs", () => {
84
+ const note = renderPlanNote({
85
+ ...input(),
86
+ overrides: [
87
+ { member: "app", rules: ["no-public"], overriders: ["alice"] },
88
+ { member: "db", rules: ["size"], overriders: [], override: { by: "bob", at: "2026-10-01T00:00:00Z", plan: "p1", reason: "load\ntest" } },
89
+ { member: "net", rules: [], overriders: [] },
90
+ ],
91
+ warnings: [{ member: "app", text: "tags\nmissing" }],
92
+ deferred: [{ unit: "web", after: ["app"], why: "reads its outputs", previewed: true }],
93
+ linked: [{ member: "web", upstream: "app", unknown: ["url"] }],
94
+ }, { words: assertProductWords({ ...TERRAGUCCI, override: 'terragucci override {target} --rule {rule} --reason "<why>" {sign}' }), note: TERRAGUCCI_NOTE });
95
+ expect(note).toContain("**Policy overrides (1 of 3 denied):**\n\n- [`app`](report.html#root-app): denied by `no-public`. alice may override it once a tf-apply wave records the denial: `terragucci override app --rule no-public --reason \"<why>\"`\n- [`db`](report.html#root-db): `size` overridden by bob at 2026-10-01T00:00:00Z, for plan `p1`: load test. tf-apply applies this plan; this run still fails it\n- [`net`](report.html#root-net): denied by its rules. policy.override names nobody who may override it\n");
96
+ expect(note).toContain("**Policy warnings (1), which fail nothing:**\n\n- [`app`](report.html#root-app): tags missing\n");
97
+ expect(note).toContain("- `web` after `app`: reads its outputs (previewed)\n");
98
+ expect(note).toContain("- [`web`](report.html#root-web) reads `app`; `url` known once it applies\n");
99
+ });
100
+
101
+ test("diff lines move the change symbol to the first column, and the fence outgrows the text's backticks", () => {
102
+ expect(diffLines([" ~ a", " -/+ b", " c"])).toEqual(["~ a", "-/+ b", " c"]);
103
+ expect(diffFence(["x ``` y"])).toBe("````diff\nx ``` y\n````\n");
104
+ });
105
+ });