@antelopejs/tooling-configs 0.2.7 → 0.2.9

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.
@@ -0,0 +1,1480 @@
1
+ #!/usr/bin/env node
2
+ import { n as runCliAsync } from "../cli-4Tv71vYk.mjs";
3
+ import { c as ciNodeCallers, n as CI_NODE_REF, r as CI_PATH, t as CI_CONTEXT } from "../ci-workflow-BDy6hQJ6.mjs";
4
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
+ import { execFileSync, spawnSync } from "node:child_process";
7
+ import { parseArgs } from "node:util";
8
+ import { homedir, tmpdir } from "node:os";
9
+ import { inflateRawSync } from "node:zlib";
10
+ //#region src/garden/json.ts
11
+ /** Raised when an API payload lacks a field the Gardener relies on. */
12
+ var DecodeError = class extends Error {};
13
+ function isString(value) {
14
+ return String(value) === value;
15
+ }
16
+ function isNumber(value) {
17
+ return Number.isFinite(value);
18
+ }
19
+ function isObject(value) {
20
+ return Object(value) === value && !Array.isArray(value);
21
+ }
22
+ function parseJson(text) {
23
+ return JSON.parse(text);
24
+ }
25
+ function object(value, path) {
26
+ if (!isObject(value)) throw new DecodeError(`${path}: expected an object`);
27
+ return value;
28
+ }
29
+ function list(value, path) {
30
+ if (!Array.isArray(value)) throw new DecodeError(`${path}: expected a list`);
31
+ return value;
32
+ }
33
+ function str(source, key) {
34
+ const value = source[key];
35
+ if (value === void 0 || !isString(value)) throw new DecodeError(`${key}: expected a string`);
36
+ return value;
37
+ }
38
+ function optStr(source, key) {
39
+ const value = source[key];
40
+ return value !== void 0 && isString(value) ? value : void 0;
41
+ }
42
+ function num(source, key) {
43
+ const value = source[key];
44
+ if (value === void 0 || !isNumber(value)) throw new DecodeError(`${key}: expected a number`);
45
+ return value;
46
+ }
47
+ function optNum(source, key) {
48
+ const value = source[key];
49
+ return value !== void 0 && isNumber(value) ? value : void 0;
50
+ }
51
+ function flag(source, key) {
52
+ return source[key] === true;
53
+ }
54
+ function child(source, key) {
55
+ const value = source[key];
56
+ return value === void 0 ? {} : object(value, key);
57
+ }
58
+ function children(source, key) {
59
+ const value = source[key];
60
+ return value === void 0 ? [] : list(value, key).map((entry) => object(entry, key));
61
+ }
62
+ function strings(source, key) {
63
+ const value = source[key];
64
+ return value === void 0 ? [] : list(value, key).filter((entry) => isString(entry));
65
+ }
66
+ function time(source, key) {
67
+ const value = Date.parse(str(source, key));
68
+ if (Number.isNaN(value)) throw new DecodeError(`${key}: expected a date`);
69
+ return value;
70
+ }
71
+ function optTime(source, key) {
72
+ const value = optStr(source, key);
73
+ return value === void 0 ? void 0 : Date.parse(value);
74
+ }
75
+ //#endregion
76
+ //#region src/garden/api.ts
77
+ /** A GitHub or npm answer that is not a success. */
78
+ var ApiError = class extends Error {
79
+ status;
80
+ constructor(status, message) {
81
+ super(message);
82
+ this.status = status;
83
+ }
84
+ };
85
+ const GITHUB = "https://api.github.com";
86
+ const NPM = "https://registry.npmjs.org";
87
+ const CREDENTIAL_NAME = /TOKEN|SECRET|PASSW|CREDENTIAL|API_?KEY|PRIVATE_?KEY|ACCESS_?KEY/i;
88
+ const MINTED_TOKENS = /* @__PURE__ */ new Set(["GH_TOKEN", "GITHUB_TOKEN"]);
89
+ const CREDENTIAL_FILES = [
90
+ ".aws/credentials",
91
+ ".netrc",
92
+ ".pypirc",
93
+ ".config/gcloud/application_default_credentials.json",
94
+ ".kube/config",
95
+ ".ssh/id_rsa",
96
+ ".ssh/id_ed25519",
97
+ ".ssh/id_ecdsa"
98
+ ];
99
+ const MAX_ATTEMPTS = 4;
100
+ function ghToken() {
101
+ return execFileSync("gh", ["auth", "token"], { encoding: "utf8" }).trim();
102
+ }
103
+ function pause(milliseconds) {
104
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
105
+ }
106
+ function nextLink(header) {
107
+ return header?.match(/<([^>]+)>;\s*rel="next"/)?.[1];
108
+ }
109
+ function withPaging(path) {
110
+ return path.includes("per_page=") ? path : `${path}${path.includes("?") ? "&" : "?"}per_page=100`;
111
+ }
112
+ function npmrcCarriesToken(home) {
113
+ const path = join(home, ".npmrc");
114
+ return existsSync(path) && /_auth(?:Token)?\s*=/.test(readFileSync(path, "utf8"));
115
+ }
116
+ /** Reads variable names only, never values. */
117
+ function readSecretSurface(names, home) {
118
+ const files = CREDENTIAL_FILES.filter((file) => existsSync(join(home, file)));
119
+ if (npmrcCarriesToken(home)) files.push(".npmrc");
120
+ return {
121
+ variables: names.filter((name) => CREDENTIAL_NAME.test(name) && !MINTED_TOKENS.has(name)).sort(),
122
+ files: files.sort()
123
+ };
124
+ }
125
+ /** Runs the released `antelopejs-registry --check` against committed manifests copied to a temporary directory. */
126
+ function registryCheck(files) {
127
+ const directory = mkdtempSync(join(tmpdir(), "garden-registry-"));
128
+ try {
129
+ for (const file of files) {
130
+ mkdirSync(dirname(join(directory, file.path)), { recursive: true });
131
+ writeFileSync(join(directory, file.path), file.content);
132
+ }
133
+ const result = spawnSync("npx", [
134
+ "--yes",
135
+ "--package",
136
+ "@antelopejs/tooling-configs@latest",
137
+ "antelopejs-registry",
138
+ "--check",
139
+ directory
140
+ ], { encoding: "utf8" });
141
+ if (result.error) throw result.error;
142
+ return result.status !== 0;
143
+ } finally {
144
+ rmSync(directory, {
145
+ recursive: true,
146
+ force: true
147
+ });
148
+ }
149
+ }
150
+ /** Authenticates with the token `gh` is logged in with and with no other credential. */
151
+ function createApi(token) {
152
+ const headers = {
153
+ Authorization: `Bearer ${token}`,
154
+ Accept: "application/vnd.github+json",
155
+ "X-GitHub-Api-Version": "2022-11-28",
156
+ "User-Agent": "antelopejs-garden"
157
+ };
158
+ async function request(url, init) {
159
+ for (let attempt = 1;; attempt++) {
160
+ const response = await fetch(url, {
161
+ ...init,
162
+ headers: {
163
+ ...headers,
164
+ ...init.headers
165
+ }
166
+ });
167
+ const retryAfter = Number(response.headers.get("retry-after") ?? 0);
168
+ if (!(response.status === 429 || response.status === 403 && retryAfter > 0 || response.status >= 502) || attempt === MAX_ATTEMPTS) return response;
169
+ await pause(Math.max(retryAfter, attempt) * 1e3);
170
+ }
171
+ }
172
+ async function get(path, accept) {
173
+ const response = await request(path.startsWith("http") ? path : `${GITHUB}${path}`, { headers: accept ? { Accept: accept } : {} });
174
+ if (!response.ok) throw new ApiError(response.status, `GET ${path}: HTTP ${response.status} ${(await response.text()).slice(0, 200)}`);
175
+ return response;
176
+ }
177
+ return {
178
+ async json(path) {
179
+ return parseJson(await (await get(path)).text());
180
+ },
181
+ async pages(path, key) {
182
+ const items = [];
183
+ for (let url = `${GITHUB}${withPaging(path)}`; url;) {
184
+ const response = await get(url);
185
+ const body = parseJson(await response.text());
186
+ const page = key === void 0 || !isObject(body) ? body : body[key];
187
+ if (Array.isArray(page)) items.push(...page);
188
+ url = nextLink(response.headers.get("link"));
189
+ }
190
+ return items;
191
+ },
192
+ async text(path) {
193
+ return (await get(path, "application/vnd.github.raw+json")).text();
194
+ },
195
+ async bytes(path) {
196
+ return new Uint8Array(await (await get(path)).arrayBuffer());
197
+ },
198
+ async send(method, path, body) {
199
+ const response = await request(`${GITHUB}${path}`, {
200
+ method,
201
+ body: JSON.stringify(body),
202
+ headers: { "Content-Type": "application/json" }
203
+ });
204
+ if (!response.ok) throw new ApiError(response.status, `${method} ${path}: HTTP ${response.status}`);
205
+ },
206
+ async npm(name) {
207
+ const response = await fetch(`${NPM}/${name.replace("/", "%2F")}`);
208
+ if (response.status === 404) return void 0;
209
+ if (!response.ok) throw new ApiError(response.status, `npm ${name}: HTTP ${response.status}`);
210
+ return parseJson(await response.text());
211
+ },
212
+ async contentLength(url) {
213
+ const response = await fetch(url, { method: "HEAD" });
214
+ const length = response.headers.get("content-length");
215
+ return response.ok && length !== null && isString(length) ? Number(length) : void 0;
216
+ },
217
+ async registryDiffers(files) {
218
+ return registryCheck(files);
219
+ },
220
+ secrets() {
221
+ return readSecretSurface(Object.keys(process.env), homedir());
222
+ },
223
+ now() {
224
+ return /* @__PURE__ */ new Date();
225
+ }
226
+ };
227
+ }
228
+ //#endregion
229
+ //#region src/garden/decode.ts
230
+ function orgRepo(value) {
231
+ const source = object(value, "repository");
232
+ return {
233
+ name: str(source, "name"),
234
+ archived: flag(source, "archived"),
235
+ isPrivate: flag(source, "private"),
236
+ language: optStr(source, "language"),
237
+ defaultBranch: optStr(source, "default_branch") ?? "main"
238
+ };
239
+ }
240
+ function workflowRun(value) {
241
+ const source = object(value, "workflow run");
242
+ const created = time(source, "created_at");
243
+ return {
244
+ id: num(source, "id"),
245
+ conclusion: optStr(source, "conclusion"),
246
+ createdAt: created,
247
+ startedAt: optTime(source, "run_started_at") ?? created,
248
+ updatedAt: time(source, "updated_at"),
249
+ url: str(source, "html_url"),
250
+ headSha: optStr(source, "head_sha") ?? ""
251
+ };
252
+ }
253
+ function checkRuns(value) {
254
+ return children(object(value, "check runs"), "check_runs").map((source) => ({
255
+ id: num(source, "id"),
256
+ name: str(source, "name"),
257
+ conclusion: optStr(source, "conclusion"),
258
+ url: optStr(source, "html_url") ?? "",
259
+ summary: optStr(child(source, "output"), "summary") ?? ""
260
+ }));
261
+ }
262
+ function pullRequest(value) {
263
+ const source = object(value, "pull request");
264
+ return {
265
+ number: num(source, "number"),
266
+ title: str(source, "title"),
267
+ author: optStr(child(source, "user"), "login") ?? "",
268
+ createdAt: time(source, "created_at"),
269
+ url: str(source, "html_url")
270
+ };
271
+ }
272
+ function alert(value) {
273
+ const source = object(value, "alert");
274
+ const advisory = child(source, "security_advisory");
275
+ const dependency = child(source, "dependency");
276
+ return {
277
+ number: num(source, "number"),
278
+ advisory: optStr(advisory, "ghsa_id") ?? String(num(source, "number")),
279
+ severity: optStr(advisory, "severity") ?? "unknown",
280
+ runtime: optStr(dependency, "scope") === "runtime",
281
+ createdAt: time(source, "created_at"),
282
+ url: str(source, "html_url"),
283
+ package: optStr(child(dependency, "package"), "name") ?? "unknown"
284
+ };
285
+ }
286
+ function packageJson(path, text) {
287
+ const source = object(JSON.parse(text), path);
288
+ const antelope = child(source, "antelopeJs");
289
+ const tooling = [source.dependencies, source.devDependencies].map((group) => group === void 0 ? void 0 : optStr(object(group, path), "@antelopejs/tooling-configs")).find((range) => range !== void 0);
290
+ return {
291
+ path,
292
+ name: optStr(source, "name"),
293
+ private: flag(source, "private"),
294
+ tooling,
295
+ hasTemplate: antelope.template !== void 0
296
+ };
297
+ }
298
+ function artifacts(value) {
299
+ return children(object(value, "artifacts"), "artifacts").map((source) => ({
300
+ id: num(source, "id"),
301
+ name: str(source, "name"),
302
+ createdAt: time(source, "created_at"),
303
+ expired: flag(source, "expired"),
304
+ runId: num(child(source, "workflow_run"), "id")
305
+ }));
306
+ }
307
+ function logins(value) {
308
+ return list(value, "members").map((entry) => str(object(entry, "member"), "login"));
309
+ }
310
+ //#endregion
311
+ //#region src/garden/context.ts
312
+ const ORG = "AntelopeJS";
313
+ const PACKS = [
314
+ "full",
315
+ "template",
316
+ "none"
317
+ ];
318
+ const TIERS = [
319
+ "N1",
320
+ "N2",
321
+ "N3",
322
+ "N4"
323
+ ];
324
+ /** `dms-cicd` and every `cms*` repository are being archived and are never read. */
325
+ function isUntouchable(name) {
326
+ return name === "dms-cicd" || name.startsWith("cms");
327
+ }
328
+ function isInScope(repo) {
329
+ return (repo.pack === "full" || repo.pack === "template") && (repo.tier === "N1" || repo.tier === "N2" || repo.tier === "N3");
330
+ }
331
+ function isMissing(error) {
332
+ return error instanceof ApiError && error.status === 404;
333
+ }
334
+ var Memo = class {
335
+ values = /* @__PURE__ */ new Map();
336
+ get(key, make) {
337
+ let value = this.values.get(key);
338
+ if (value === void 0) {
339
+ value = make();
340
+ this.values.set(key, value);
341
+ }
342
+ return value;
343
+ }
344
+ };
345
+ async function mapLimit(items, limit, run) {
346
+ const results = [];
347
+ let next = 0;
348
+ const worker = async () => {
349
+ while (next < items.length) {
350
+ const index = next++;
351
+ results[index] = await run(items[index]);
352
+ }
353
+ };
354
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
355
+ return results;
356
+ }
357
+ function pack(value) {
358
+ return PACKS.find((candidate) => candidate === value);
359
+ }
360
+ function tier(value) {
361
+ return TIERS.find((candidate) => candidate === value);
362
+ }
363
+ function propertyValues(entries) {
364
+ const byRepo = /* @__PURE__ */ new Map();
365
+ for (const entry of entries) {
366
+ const source = object(entry, "property values");
367
+ const values = {};
368
+ for (const property of children(source, "properties")) values[str(property, "property_name")] = property.value ?? null;
369
+ byRepo.set(str(source, "repository_name"), values);
370
+ }
371
+ return byRepo;
372
+ }
373
+ /** Reads GitHub and npm through one memoised seam, so every check shares each answer. */
374
+ var GardenContext = class {
375
+ api;
376
+ listing = new Memo();
377
+ branches = new Memo();
378
+ trees = new Memo();
379
+ files = new Memo();
380
+ manifests = new Memo();
381
+ runs = new Memo();
382
+ checks = new Memo();
383
+ pulls = new Memo();
384
+ alertLists = new Memo();
385
+ variables = new Memo();
386
+ packuments = new Memo();
387
+ removals = new Memo();
388
+ searches = new Memo();
389
+ constructor(api) {
390
+ this.api = api;
391
+ }
392
+ /** Non-archived repositories, untouchable ones removed, joined with their `pack` and `tier` properties. */
393
+ async repos() {
394
+ return (await this.listed()).filter((repo) => !repo.archived);
395
+ }
396
+ /** Names of archived repositories, which the Registry must not list. */
397
+ async archived() {
398
+ return new Set((await this.listed()).filter((repo) => repo.archived).map((repo) => repo.name));
399
+ }
400
+ listed() {
401
+ return this.listing.get(ORG, async () => {
402
+ const [repos, values] = await Promise.all([this.api.pages(`/orgs/${ORG}/repos?type=all`), this.api.pages(`/orgs/${ORG}/properties/values`)]);
403
+ const properties = propertyValues(values);
404
+ return repos.map(orgRepo).filter((repo) => !isUntouchable(repo.name)).map((repo) => {
405
+ const own = properties.get(repo.name) ?? {};
406
+ return {
407
+ ...repo,
408
+ pack: pack(optStr(own, "pack")),
409
+ tier: tier(optStr(own, "tier"))
410
+ };
411
+ }).sort((a, b) => a.name < b.name ? -1 : 1);
412
+ });
413
+ }
414
+ async scope() {
415
+ return (await this.repos()).filter(isInScope);
416
+ }
417
+ async targetBranch(repo) {
418
+ return this.branches.get(repo.name, async () => {
419
+ try {
420
+ await this.api.json(`/repos/${ORG}/${repo.name}/branches/next`);
421
+ return "next";
422
+ } catch (error) {
423
+ if (error instanceof Error && isMissing(error)) return repo.defaultBranch;
424
+ throw error;
425
+ }
426
+ });
427
+ }
428
+ tree(repo) {
429
+ return this.trees.get(repo.name, async () => {
430
+ return children(object(await this.api.json(`/repos/${ORG}/${repo.name}/git/trees/${repo.defaultBranch}?recursive=1`), "tree"), "tree").map((entry) => str(entry, "path"));
431
+ });
432
+ }
433
+ file(repo, path, ref = repo.defaultBranch) {
434
+ return this.files.get(`${repo.name}:${ref}:${path}`, async () => {
435
+ try {
436
+ return await this.api.text(`/repos/${ORG}/${repo.name}/contents/${path}?ref=${encodeURIComponent(ref)}`);
437
+ } catch (error) {
438
+ if (error instanceof Error && isMissing(error)) return void 0;
439
+ throw error;
440
+ }
441
+ });
442
+ }
443
+ /** Every `package.json` within three levels, `node_modules` excluded. */
444
+ packages(repo) {
445
+ return this.manifests.get(repo.name, async () => {
446
+ const paths = (await this.tree(repo)).filter((path) => /(?:^|\/)package\.json$/.test(path) && !path.includes("node_modules/") && path.split("/").length <= 3);
447
+ const manifests = [];
448
+ for (const path of paths) {
449
+ const text = await this.file(repo, path);
450
+ if (text !== void 0) manifests.push(packageJson(path, text));
451
+ }
452
+ return manifests;
453
+ });
454
+ }
455
+ /** Completed runs of a workflow file on a branch, newest first; undefined when the workflow does not exist. */
456
+ workflowRuns(repo, workflow, branch, event = "push") {
457
+ return this.runs.get(`${repo.name}:${workflow}:${branch}:${event}`, async () => {
458
+ try {
459
+ const filter = event === "" ? "" : `&event=${event}`;
460
+ return children(object(await this.api.json(`/repos/${ORG}/${repo.name}/actions/workflows/${workflow}/runs?branch=${branch}${filter}&status=completed&per_page=100`), "runs"), "workflow_runs").map((run) => workflowRun(run));
461
+ } catch (error) {
462
+ if (error instanceof Error && isMissing(error)) return void 0;
463
+ throw error;
464
+ }
465
+ });
466
+ }
467
+ checkRuns(repo, branch) {
468
+ return this.checks.get(`${repo.name}:${branch}`, async () => checkRuns(await this.api.json(`/repos/${ORG}/${repo.name}/commits/${branch}/check-runs?per_page=100`)));
469
+ }
470
+ openPulls(repo) {
471
+ return this.pulls.get(repo.name, async () => (await this.api.pages(`/repos/${ORG}/${repo.name}/pulls?state=open`)).map(pullRequest));
472
+ }
473
+ /** Open alerts, or undefined when Dependabot alerts are disabled for the repository. */
474
+ alerts(repo) {
475
+ return this.alertLists.get(repo.name, async () => {
476
+ try {
477
+ return (await this.api.pages(`/repos/${ORG}/${repo.name}/dependabot/alerts?state=open`)).map(alert);
478
+ } catch (error) {
479
+ if (error instanceof ApiError && error.status === 403 && /disabled/i.test(error.message)) return void 0;
480
+ throw error;
481
+ }
482
+ });
483
+ }
484
+ async exists(repo, path, ref) {
485
+ try {
486
+ await this.api.json(`/repos/${ORG}/${repo}/contents/${path}${ref === void 0 ? "" : `?ref=${ref}`}`);
487
+ return true;
488
+ } catch (error) {
489
+ if (error instanceof Error && isMissing(error)) return false;
490
+ throw error;
491
+ }
492
+ }
493
+ /** A repository Actions variable, or undefined when it does not exist. */
494
+ variable(repo, name) {
495
+ return this.variables.get(`${repo.name}:${name}`, async () => {
496
+ try {
497
+ return str(object(await this.api.json(`/repos/${ORG}/${repo.name}/actions/variables/${name}`), "variable"), "value");
498
+ } catch (error) {
499
+ if (error instanceof Error && isMissing(error)) return void 0;
500
+ throw error;
501
+ }
502
+ });
503
+ }
504
+ /** Whether a commit of the default branch history removed the file; looks at the 30 newest commits that touched it. */
505
+ removedInHistory(repo, path) {
506
+ return this.removals.get(`${repo.name}:${path}`, async () => {
507
+ const commits = list(await this.api.json(`/repos/${ORG}/${repo.name}/commits?path=${path}&sha=${repo.defaultBranch}&per_page=30`), "commits");
508
+ for (const commit of commits) if (children(object(await this.api.json(`/repos/${ORG}/${repo.name}/commits/${str(object(commit, "commit"), "sha")}`), "commit"), "files").some((file) => str(file, "filename") === path && optStr(file, "status") === "removed")) return true;
509
+ return false;
510
+ });
511
+ }
512
+ packument(name) {
513
+ return this.packuments.get(name, () => this.api.npm(name));
514
+ }
515
+ /** Names of repositories holding an issue or pull request authored by the Renovate app. */
516
+ renovateRepos() {
517
+ return this.searches.get("renovate", async () => {
518
+ const hits = await this.api.pages(`/search/issues?q=${encodeURIComponent(`org:${ORG} author:app/renovate`)}`, "items");
519
+ return new Set(hits.map((hit) => str(object(hit, "issue"), "repository_url").split("/").pop() ?? ""));
520
+ });
521
+ }
522
+ async artifactsNamed(repo, name) {
523
+ return artifacts(await this.api.json(`/repos/${ORG}/${repo}/actions/artifacts?name=${name}&per_page=100`)).filter((artifact) => !artifact.expired).sort((a, b) => b.createdAt - a.createdAt);
524
+ }
525
+ organizationOwners() {
526
+ return this.api.pages(`/orgs/${ORG}/members?role=admin`).then(logins);
527
+ }
528
+ };
529
+ //#endregion
530
+ //#region src/garden/types.ts
531
+ function finding(id, evidence, doneMeans, severity = "normal") {
532
+ return {
533
+ key: [
534
+ id.repo,
535
+ id.check,
536
+ id.subject
537
+ ].join("|"),
538
+ ...id,
539
+ severity,
540
+ evidence,
541
+ doneMeans
542
+ };
543
+ }
544
+ function found(findings) {
545
+ return {
546
+ kind: "findings",
547
+ findings
548
+ };
549
+ }
550
+ function skip(reason) {
551
+ return {
552
+ kind: "skipped",
553
+ reason
554
+ };
555
+ }
556
+ //#endregion
557
+ //#region src/garden/checks/apps.ts
558
+ const ALTAB = "Altab-S-R-L";
559
+ const ORG_BASELINE = {
560
+ all: [
561
+ "amp-for-github",
562
+ "claude",
563
+ "chatgpt-codex-connector"
564
+ ],
565
+ selectedOnly: []
566
+ };
567
+ const ALTAB_BASELINE = {
568
+ all: ["claude", "chatgpt-codex-connector"],
569
+ selectedOnly: ["amp-for-github"]
570
+ };
571
+ async function installations(api, org) {
572
+ return (await api.pages(`/orgs/${org}/installations`, "installations")).map((entry) => {
573
+ const source = object(entry, "installation");
574
+ return {
575
+ slug: str(source, "app_slug"),
576
+ selection: str(source, "repository_selection")
577
+ };
578
+ });
579
+ }
580
+ function drift(org, apps) {
581
+ const baseline = org === ALTAB ? ALTAB_BASELINE : ORG_BASELINE;
582
+ const findings = [];
583
+ for (const app of apps) {
584
+ if (/cursor/i.test(app.slug)) findings.push(finding({
585
+ repo: org,
586
+ check: "ai-apps",
587
+ subject: `cursor:${app.slug}`
588
+ }, `Cursor's app ${app.slug} is installed on ${org}.`, `The app is uninstalled from ${org}.`));
589
+ const pinned = baseline.selectedOnly.includes(app.slug);
590
+ if (app.selection === "all" && !pinned && !baseline.all.includes(app.slug)) findings.push(finding({
591
+ repo: org,
592
+ check: "ai-apps",
593
+ subject: `app:${app.slug}`
594
+ }, `${app.slug} is installed on all repositories of ${org} and is not in the baseline.`, `${app.slug} is limited to selected repositories, or Antony adds it to the baseline.`));
595
+ if (app.selection === "all" && pinned) findings.push(finding({
596
+ repo: org,
597
+ check: "ai-apps",
598
+ subject: `selected:${app.slug}`
599
+ }, `${app.slug} is installed on all repositories of ${org}; the baseline limits it to selected ones.`, `${app.slug} is limited to selected repositories on ${org}.`));
600
+ }
601
+ return findings;
602
+ }
603
+ const aiApps = {
604
+ id: "ai-apps",
605
+ async run(context) {
606
+ const findings = [];
607
+ for (const org of [ORG, ALTAB]) findings.push(...drift(org, await installations(context.api, org)));
608
+ return found(findings);
609
+ }
610
+ };
611
+ const orbSecrets = {
612
+ id: "orb-secrets",
613
+ async run(context) {
614
+ const surface = context.api.secrets();
615
+ return found([...surface.variables.map((name) => finding({
616
+ repo: ORG,
617
+ check: "orb-secrets",
618
+ subject: `env:${name}`
619
+ }, `The environment variable ${name} is set in the scanning process.`, `${name} is removed from the scanner's environment.`)), ...surface.files.map((file) => finding({
620
+ repo: ORG,
621
+ check: "orb-secrets",
622
+ subject: `file:${file}`
623
+ }, `The credential file ~/${file} is readable by the scanning process.`, `~/${file} is removed from the scanner's machine.`))]);
624
+ }
625
+ };
626
+ //#endregion
627
+ //#region src/garden/zip.ts
628
+ const END_OF_CENTRAL_DIRECTORY = 101010256;
629
+ const CENTRAL_ENTRY = 33639248;
630
+ /** Reads the first file of a stored or deflated ZIP archive, as produced for an Actions artifact. */
631
+ function firstZipEntry(archive) {
632
+ const view = new DataView(archive.buffer, archive.byteOffset, archive.byteLength);
633
+ let end = archive.byteLength - 22;
634
+ while (end >= 0 && view.getUint32(end, true) !== END_OF_CENTRAL_DIRECTORY) end--;
635
+ if (end < 0) throw new Error("Not a ZIP archive.");
636
+ const entry = view.getUint32(end + 16, true);
637
+ if (view.getUint32(entry, true) !== CENTRAL_ENTRY) throw new Error("Empty ZIP archive.");
638
+ const method = view.getUint16(entry + 10, true);
639
+ const size = view.getUint32(entry + 20, true);
640
+ const local = view.getUint32(entry + 42, true);
641
+ const start = local + 30 + view.getUint16(local + 26, true) + view.getUint16(local + 28, true);
642
+ const data = archive.subarray(start, start + size);
643
+ if (method === 0) return Buffer.from(data).toString("utf8");
644
+ if (method === 8) return inflateRawSync(data).toString("utf8");
645
+ throw new Error(`Unsupported ZIP method ${method}.`);
646
+ }
647
+ //#endregion
648
+ //#region src/garden/checks/artifacts.ts
649
+ const WORKFLOWS_REPO = ".github";
650
+ async function latestReport(context, repo, name) {
651
+ const [latest] = await context.artifactsNamed(repo, name);
652
+ if (latest === void 0) return void 0;
653
+ return object(parseJson(firstZipEntry(await context.api.bytes(`/repos/${ORG}/${repo}/actions/artifacts/${latest.id}/zip`))), name);
654
+ }
655
+ function survivors(report) {
656
+ const files = object(report.files ?? {}, "files");
657
+ return Object.keys(files).map((file) => {
658
+ const mutants = children(object(files[file], file), "mutants");
659
+ return {
660
+ file,
661
+ survived: mutants.filter((mutant) => optStr(mutant, "status") === "Survived").length,
662
+ total: mutants.length
663
+ };
664
+ });
665
+ }
666
+ const mutation = {
667
+ id: "mutation",
668
+ async run(context) {
669
+ if (!await context.exists(WORKFLOWS_REPO, ".github/workflows/mutation.yml")) return skip("AntelopeJS/.github has no mutation.yml yet");
670
+ const repos = (await context.scope()).filter((repo) => repo.tier === "N1" || repo.tier === "N2");
671
+ const findings = [];
672
+ let reports = 0;
673
+ for (const repo of repos) {
674
+ const report = await latestReport(context, repo.name, "mutation-report");
675
+ if (report === void 0) continue;
676
+ reports++;
677
+ for (const { file, survived, total } of survivors(report)) if (survived > 0) findings.push(finding({
678
+ repo: repo.name,
679
+ check: "mutation",
680
+ subject: file
681
+ }, `${survived} of ${total} mutants survive in ${file}.`, `Tests kill the surviving mutants of ${file}, or Stryker ignores them with a reason.`));
682
+ }
683
+ return reports ? found(findings) : skip("no mutation-report artifact exists in any N1 or N2 repository yet");
684
+ }
685
+ };
686
+ const linkRot = {
687
+ id: "link-rot",
688
+ async run(context) {
689
+ if (!await context.exists(WORKFLOWS_REPO, ".github/workflows/link-rot.yml")) return skip("AntelopeJS/.github has no link-rot.yml yet");
690
+ const report = await latestReport(context, WORKFLOWS_REPO, "link-rot");
691
+ if (report === void 0) return skip("no link-rot artifact exists yet");
692
+ const repos = object(report.repos ?? {}, "repos");
693
+ const findings = [];
694
+ for (const repo of Object.keys(repos)) {
695
+ const files = object(repos[repo], repo);
696
+ for (const file of Object.keys(files)) {
697
+ const links = list(files[file], file).map((link) => object(link, file));
698
+ if (links.length) findings.push(finding({
699
+ repo,
700
+ check: "link-rot",
701
+ subject: file
702
+ }, `${links.length} dead external links in ${file}: ${links.map((link) => str(link, "url")).join(", ")}`, `Every external link in ${file} resolves.`));
703
+ }
704
+ }
705
+ return found(findings);
706
+ }
707
+ };
708
+ //#endregion
709
+ //#region src/garden/check.ts
710
+ /** A check that read some repositories and failed on others keeps what it found. */
711
+ var PartialFailure = class extends Error {
712
+ findings;
713
+ constructor(findings, failures) {
714
+ super(failures.join("; "));
715
+ this.findings = findings;
716
+ }
717
+ };
718
+ const CONCURRENCY = 6;
719
+ /** Runs a scan on each repository; a failing repository is reported once, not allowed to hide the rest. */
720
+ async function perRepo(repos, scan) {
721
+ const failures = [];
722
+ const findings = (await mapLimit(repos, CONCURRENCY, async (repo) => {
723
+ try {
724
+ return await scan(repo);
725
+ } catch (error) {
726
+ failures.push(`${repo.name}: ${error instanceof Error ? error.message : String(error)}`);
727
+ return [];
728
+ }
729
+ })).flat();
730
+ if (failures.length) throw new PartialFailure(findings, failures.sort());
731
+ return found(findings);
732
+ }
733
+ //#endregion
734
+ //#region src/garden/checks/ci-health.ts
735
+ const DAY$3 = 864e5;
736
+ const WORKFLOW = "ci.yml";
737
+ const RECENT_RUNS = 10;
738
+ const MIN_BASELINE = 5;
739
+ const RELATIVE_LIMIT = 1.2;
740
+ const ABSOLUTE_LIMIT_SECONDS = 60;
741
+ const RED = /* @__PURE__ */ new Set([
742
+ "failure",
743
+ "timed_out",
744
+ "startup_failure"
745
+ ]);
746
+ function duration(run) {
747
+ return (run.updatedAt - run.startedAt) / 1e3;
748
+ }
749
+ function median(values) {
750
+ const sorted = [...values].sort((a, b) => a - b);
751
+ const middle = Math.floor(sorted.length / 2);
752
+ return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
753
+ }
754
+ /** The creation time of the oldest run of the unbroken red streak ending at the newest judged run. */
755
+ function redSince(runs) {
756
+ const judged = runs.filter(({ conclusion }) => conclusion === "success" || RED.has(conclusion ?? ""));
757
+ let oldest;
758
+ for (const run of judged) {
759
+ if (!RED.has(run.conclusion ?? "")) break;
760
+ oldest = run;
761
+ }
762
+ return oldest;
763
+ }
764
+ async function red(context, repo) {
765
+ const branch = await context.targetBranch(repo);
766
+ const runs = await context.workflowRuns(repo, WORKFLOW, branch);
767
+ const since = runs === void 0 ? void 0 : redSince(runs);
768
+ if (since === void 0 || context.api.now().getTime() - since.createdAt <= DAY$3) return [];
769
+ return [finding({
770
+ repo: repo.name,
771
+ check: "red-branch",
772
+ subject: branch
773
+ }, `${WORKFLOW} has been red on ${branch} since ${new Date(since.createdAt).toISOString()}: ${since.url}`, `${WORKFLOW} is green on ${branch}.`)];
774
+ }
775
+ async function slow(context, repo) {
776
+ const branch = await context.targetBranch(repo);
777
+ const runs = await context.workflowRuns(repo, WORKFLOW, branch);
778
+ const horizon = context.api.now().getTime() - 30 * DAY$3;
779
+ const passed = (runs ?? []).filter((run) => run.conclusion === "success" && run.createdAt >= horizon);
780
+ const baseline = passed.slice(RECENT_RUNS).map(duration);
781
+ if (passed.length <= RECENT_RUNS || baseline.length < MIN_BASELINE) return [];
782
+ const recent = median(passed.slice(0, RECENT_RUNS).map(duration));
783
+ const usual = median(baseline);
784
+ if (recent <= usual * RELATIVE_LIMIT && recent <= usual + ABSOLUTE_LIMIT_SECONDS) return [];
785
+ return [finding({
786
+ repo: repo.name,
787
+ check: "ci-duration",
788
+ subject: branch
789
+ }, `The median of the last ${RECENT_RUNS} ${WORKFLOW} runs on ${branch} is ${Math.round(recent)} s against ${Math.round(usual)} s over the previous 30 days.`, `The median is within 20% and 60 s of the 30-day baseline.`)];
790
+ }
791
+ const redBranch = {
792
+ id: "red-branch",
793
+ async run(context) {
794
+ return perRepo(await context.scope(), (repo) => red(context, repo));
795
+ }
796
+ };
797
+ const ciDuration = {
798
+ id: "ci-duration",
799
+ async run(context) {
800
+ return perRepo(await context.scope(), (repo) => slow(context, repo));
801
+ }
802
+ };
803
+ //#endregion
804
+ //#region src/garden/npm.ts
805
+ const TOOLING_PACKAGE = "@antelopejs/tooling-configs";
806
+ function distTags(packument) {
807
+ return child(object(packument, "packument"), "dist-tags");
808
+ }
809
+ function tagVersion(packument, tag) {
810
+ return optStr(distTags(packument), tag);
811
+ }
812
+ /** The `latest` dist-tag of tooling-configs. */
813
+ async function tooling(context) {
814
+ const packument = await context.packument(TOOLING_PACKAGE);
815
+ const latest = packument === void 0 ? void 0 : tagVersion(packument, "latest");
816
+ if (latest === void 0) throw new Error(`${TOOLING_PACKAGE} has no latest version on npm.`);
817
+ return latest;
818
+ }
819
+ //#endregion
820
+ //#region src/garden/checks/conformance.ts
821
+ const CHECK$1 = "conformance";
822
+ const DAY$2 = 864e5;
823
+ const RENOVATE_CONFIGS = [
824
+ "renovate.json",
825
+ "renovate.json5",
826
+ ".github/renovate.json",
827
+ ".github/renovate.json5",
828
+ ".renovaterc",
829
+ ".renovaterc.json"
830
+ ];
831
+ const RENOVATE_PRESET = /github>AntelopeJS\/\.github(?::|\/)/;
832
+ const MEND_EXEMPT = /* @__PURE__ */ new Set(["k8s-gitops-infra"]);
833
+ function problem(repo, subject, evidence, doneMeans) {
834
+ return finding({
835
+ repo: repo.name,
836
+ check: CHECK$1,
837
+ subject
838
+ }, evidence, doneMeans);
839
+ }
840
+ async function ciCaller(context, repo) {
841
+ const text = await context.file(repo, CI_PATH);
842
+ if (text === void 0) return [problem(repo, "ci-caller", `${CI_PATH} does not exist.`, `${CI_PATH} has a job calling ${CI_NODE_REF}.`)];
843
+ const callers = ciNodeCallers(text);
844
+ if (!callers.length) return [problem(repo, "ci-caller", `${CI_PATH} has no job calling ci-node.yml.`, `${CI_PATH} has a job calling ${CI_NODE_REF}.`)];
845
+ const findings = [];
846
+ const unpinned = callers.filter(({ uses }) => uses !== CI_NODE_REF);
847
+ if (unpinned.length === callers.length) findings.push(problem(repo, "ci-caller", `${CI_PATH} calls ${unpinned[0].uses}.`, `The caller uses ${CI_NODE_REF}.`));
848
+ if (!callers.some(({ id, named }) => id === "ci" && !named)) findings.push(problem(repo, "ci-job-id", `The caller job is ${callers[0].id}${callers[0].named ? " with a name" : ""}, so the check is not reported as ${CI_CONTEXT}.`, `antelopejs-sync has renamed the caller job to ci and removed its name.`));
849
+ return findings;
850
+ }
851
+ async function renovateConfig(context, repo) {
852
+ const tree = await context.tree(repo);
853
+ const path = RENOVATE_CONFIGS.find((candidate) => tree.includes(candidate));
854
+ const text = path === void 0 ? void 0 : await context.file(repo, path);
855
+ if (text !== void 0 && RENOVATE_PRESET.test(text)) return [];
856
+ return [problem(repo, "renovate-config", path === void 0 ? "No Renovate configuration file." : `${path} does not extend the AntelopeJS preset.`, "renovate.json extends github>AntelopeJS/.github:renovate.json5.")];
857
+ }
858
+ const LOCK_ENTRY = /'?@antelopejs\/tooling-configs'?:\s*\n\s+specifier:[^\n]*\n\s+version:\s*'?(\d[^\s'(]*)/;
859
+ /** The version the lockfile resolves, or the declared version when there is no pnpm lockfile. */
860
+ async function installed(context, repo, range) {
861
+ return (await context.file(repo, "pnpm-lock.yaml"))?.match(LOCK_ENTRY)?.[1] ?? range.replace(/^[^\d]*/, "");
862
+ }
863
+ async function toolingVersion(context, repo) {
864
+ const range = (await context.packages(repo)).map(({ tooling: declared }) => declared).find((declared) => declared !== void 0);
865
+ const latest = await tooling(context);
866
+ const done = `@antelopejs/tooling-configs is ${latest} or a Renovate PR bumping it is under 7 days old.`;
867
+ if (range === void 0) return [problem(repo, "tooling-configs", "@antelopejs/tooling-configs is not a dependency.", done)];
868
+ if (await installed(context, repo, range) === latest) return [];
869
+ const now = context.api.now().getTime();
870
+ return (await context.openPulls(repo)).some((pull) => pull.author === "renovate[bot]" && /tooling-configs/.test(pull.title) && now - pull.createdAt < 7 * DAY$2) ? [] : [problem(repo, "tooling-configs", `Declared ${range}, latest is ${latest}, and no Renovate PR under 7 days old bumps it.`, done)];
871
+ }
872
+ async function checksStatus(context, repo) {
873
+ const branch = await context.targetBranch(repo);
874
+ const [latest] = await context.workflowRuns(repo, "ci.yml", branch) ?? [];
875
+ const runs = (await context.checkRuns(repo, latest?.headSha || branch)).filter(({ name }) => name === CI_CONTEXT || name === "checks");
876
+ const reported = runs.find(({ name }) => name === CI_CONTEXT);
877
+ if (reported === void 0) return [problem(repo, "checks-context", `${branch} reports ${runs.length ? runs.map(({ name }) => name).join(", ") : "no checks"} instead of ${CI_CONTEXT}.`, `The latest run on ${branch} reports ${CI_CONTEXT}.`)];
878
+ return reported.conclusion === "success" ? [] : [problem(repo, "checks-red", `${CI_CONTEXT} on ${branch} is ${reported.conclusion ?? "pending"}: ${reported.url}`, `${CI_CONTEXT} is green on ${branch}.`)];
879
+ }
880
+ const GUARDRAILS_RATCHET = "guardrails.ratchet.json";
881
+ async function cleanRatchet(context, repo) {
882
+ if (!(await context.tree(repo)).includes(GUARDRAILS_RATCHET) || !await context.removedInHistory(repo, GUARDRAILS_RATCHET)) return [];
883
+ return [problem(repo, "ratchet", `${GUARDRAILS_RATCHET} is back after the history deleted it.`, `${GUARDRAILS_RATCHET} is deleted again.`)];
884
+ }
885
+ async function scan(context, repo) {
886
+ return [
887
+ ...await ciCaller(context, repo),
888
+ ...await renovateConfig(context, repo),
889
+ ...await toolingVersion(context, repo),
890
+ ...await checksStatus(context, repo),
891
+ ...await cleanRatchet(context, repo)
892
+ ];
893
+ }
894
+ async function newRepos(context) {
895
+ return (await context.repos()).filter((repo) => repo.pack === "none" && repo.language === "TypeScript" && (repo.tier === "N1" || repo.tier === "N2" || repo.tier === "N3")).map((repo) => problem(repo, "new", "A TypeScript repository in N1-N3 without the guardrail pack.", "The repository runs antelopejs-sync and its pack property is full or template."));
896
+ }
897
+ async function mendSelection(context) {
898
+ const active = await context.renovateRepos();
899
+ return (await context.repos()).filter((repo) => repo.tier !== "N4" && !MEND_EXEMPT.has(repo.name) && !active.has(repo.name)).map((repo) => problem(repo, "renovate-app", "No issue or pull request from the Renovate app: the repository is not in the app's selection.", "Antony adds the repository to the Mend Renovate app's selected repositories."));
900
+ }
901
+ const conformance = {
902
+ id: CHECK$1,
903
+ async run(context) {
904
+ const scanned = await perRepo(await context.scope(), (repo) => scan(context, repo));
905
+ const extra = [...await newRepos(context), ...await mendSelection(context)];
906
+ return scanned.kind === "findings" ? found([...scanned.findings, ...extra]) : scanned;
907
+ }
908
+ };
909
+ //#endregion
910
+ //#region src/garden/checks/governance.ts
911
+ const ALLOWED_ADMINS = [
912
+ "Upd4ting",
913
+ "mwesto",
914
+ "dada-sudo"
915
+ ];
916
+ const AUTOMERGE = "NEXT_AUTOMERGE";
917
+ const CHECK = "next-governance";
918
+ const ACTIONS_APP = 15368;
919
+ const ADMIN_ROLE = 5;
920
+ const MAINTAIN_BLOCKED = "altabmachine";
921
+ const REQUIRED_CONTEXTS = [[CI_CONTEXT, "checks"], ["verify-gate"]];
922
+ const VERIFICATION_SKILL = /(?:^|\/)(?:\.agents\/skills|\.claude\/skills|skills)\/[^/]*verif[^/]*\/SKILL\.md$/i;
923
+ function branchTargets(ruleset, branch) {
924
+ return ruleset.includes.some((ref) => ref === `refs/heads/${branch}` || ref === "~DEFAULT_BRANCH" && branch !== "next");
925
+ }
926
+ async function rulesets(context, repo) {
927
+ const summaries = await context.api.pages(`/repos/${ORG}/${repo.name}/rulesets?includes_parents=true`);
928
+ const result = [];
929
+ for (const summary of summaries) {
930
+ const source = object(summary, "ruleset");
931
+ if (optStr(source, "enforcement") !== "active" || optStr(source, "target") !== "branch") continue;
932
+ const path = optStr(source, "source_type") === "Organization" ? `/orgs/${ORG}/rulesets/${num(source, "id")}` : `/repos/${ORG}/${repo.name}/rulesets/${num(source, "id")}`;
933
+ const detail = object(await context.api.json(path), "ruleset");
934
+ result.push({
935
+ name: str(detail, "name"),
936
+ includes: strings(child(child(detail, "conditions"), "ref_name"), "include"),
937
+ rules: children(detail, "rules"),
938
+ bypass: children(detail, "bypass_actors")
939
+ });
940
+ }
941
+ return result;
942
+ }
943
+ function bypassWidened(set) {
944
+ return set.bypass.some((actor) => {
945
+ const kind = optStr(actor, "actor_type");
946
+ return !(kind === "OrganizationAdmin" || kind === "RepositoryRole" && optNum(actor, "actor_id") === ADMIN_ROLE) || optStr(actor, "bypass_mode") !== "pull_request";
947
+ });
948
+ }
949
+ function requiredContexts(sets) {
950
+ return sets.flatMap((set) => set.rules.filter((rule) => optStr(rule, "type") === "required_status_checks").flatMap((rule) => children(child(rule, "parameters"), "required_status_checks").filter((entry) => optNum(entry, "integration_id") === ACTIONS_APP).map((entry) => str(entry, "context"))));
951
+ }
952
+ function pullRules(sets) {
953
+ return sets.flatMap((set) => set.rules.filter((rule) => optStr(rule, "type") === "pull_request").map((rule) => child(rule, "parameters")));
954
+ }
955
+ function branchFindings(repo, branch, sets) {
956
+ const hit = sets.filter((set) => branchTargets(set, branch));
957
+ const findings = [];
958
+ const report = (subject, evidence, urgent) => findings.push(finding({
959
+ repo: repo.name,
960
+ check: CHECK,
961
+ subject: `${branch}:${subject}`
962
+ }, evidence, `The ${branch} rulesets match the Next channel merge policy.`, urgent ? "urgent" : "normal"));
963
+ const contexts = requiredContexts(hit);
964
+ if (!contexts.includes("verify-gate")) report("verify-gate", `No ruleset on ${branch} requires verify-gate from GitHub Actions.`, true);
965
+ if (!REQUIRED_CONTEXTS[0].some((name) => contexts.includes(name))) report("checks", `No ruleset on ${branch} requires ${CI_CONTEXT} from GitHub Actions.`, false);
966
+ const reviews = pullRules(hit);
967
+ if (reviews.some((rule) => (optNum(rule, "required_approving_review_count") ?? 0) > 0 || flag(rule, "require_code_owner_review") || flag(rule, "require_last_push_approval"))) report("review-rule", `A ruleset on ${branch} requires a review.`, true);
968
+ if (!reviews.length || !reviews.every((rule) => strings(rule, "allowed_merge_methods").join() === "squash")) report("squash-only", `${branch} does not allow squash merges only.`, false);
969
+ if (hit.some(bypassWidened)) report("bypass", `The bypass list of ${hit.filter(bypassWidened).map((set) => set.name).join(", ")} holds more than the pull-request-only administrators.`, true);
970
+ return findings;
971
+ }
972
+ async function people(context, repo) {
973
+ const members = await context.api.pages(`/repos/${ORG}/${repo.name}/collaborators?affiliation=all`);
974
+ const findings = [];
975
+ for (const member of members.map((entry) => object(entry, "collaborator"))) {
976
+ const login = str(member, "login");
977
+ const role = optStr(member, "role_name");
978
+ if (role === "admin" && !ALLOWED_ADMINS.includes(login)) findings.push(finding({
979
+ repo: repo.name,
980
+ check: CHECK,
981
+ subject: `admin:${login}`
982
+ }, `${login} holds admin.`, `${login} holds write or lower.`));
983
+ if (login === MAINTAIN_BLOCKED && (role === "maintain" || role === "admin")) findings.push(finding({
984
+ repo: repo.name,
985
+ check: CHECK,
986
+ subject: `maintain:${login}`
987
+ }, `${login} holds ${role}.`, `${login} holds no maintain.`));
988
+ }
989
+ return findings;
990
+ }
991
+ async function scope(context, repo, value) {
992
+ if (value !== "on") return [];
993
+ const skill = (await context.tree(repo)).some((path) => VERIFICATION_SKILL.test(path));
994
+ return repo.tier === "N1" || repo.tier === "N2" ? skill ? [] : [finding({
995
+ repo: repo.name,
996
+ check: CHECK,
997
+ subject: "automerge-scope"
998
+ }, `${AUTOMERGE}=on without a Verification skill on ${repo.defaultBranch}.`, `${AUTOMERGE} is shadow or off, or the repository has a Verification skill.`)] : [finding({
999
+ repo: repo.name,
1000
+ check: CHECK,
1001
+ subject: "automerge-scope"
1002
+ }, `${AUTOMERGE}=on on a ${repo.tier ?? "untiered"} repository.`, `${AUTOMERGE} is on only in N1 and N2.`)];
1003
+ }
1004
+ async function governed(context, repo, value) {
1005
+ const sets = await rulesets(context, repo);
1006
+ return [
1007
+ ...(await context.targetBranch(repo) === "next" ? ["next", repo.defaultBranch] : [repo.defaultBranch]).flatMap((branch) => branchFindings(repo, branch, sets)),
1008
+ ...await people(context, repo),
1009
+ ...await scope(context, repo, value)
1010
+ ];
1011
+ }
1012
+ const nextGovernance = {
1013
+ id: CHECK,
1014
+ async run(context) {
1015
+ const values = /* @__PURE__ */ new Map();
1016
+ const repos = await context.scope();
1017
+ await perRepo(repos, async (repo) => {
1018
+ const value = await context.variable(repo, AUTOMERGE);
1019
+ if (value !== void 0) values.set(repo.name, value);
1020
+ return [];
1021
+ });
1022
+ if (!values.size) return skip(`${AUTOMERGE} exists on no repository yet (the verify-gate task has not landed).`);
1023
+ return perRepo(repos.filter((repo) => values.has(repo.name)), (repo) => governed(context, repo, values.get(repo.name) ?? ""));
1024
+ }
1025
+ };
1026
+ const governanceDrift = {
1027
+ id: "governance-drift",
1028
+ async run(context) {
1029
+ return found((await context.organizationOwners()).filter((login) => !ALLOWED_ADMINS.includes(login)).map((login) => finding({
1030
+ repo: ORG,
1031
+ check: "governance-drift",
1032
+ subject: `org-admin:${login}`
1033
+ }, `${login} is an organization owner.`, `${login} is a member, or the allowed administrators change.`)));
1034
+ }
1035
+ };
1036
+ const orgChecksRuleset = {
1037
+ id: "org-checks-ruleset",
1038
+ async run() {
1039
+ return skip("ruleset postponed until the sync fan-out");
1040
+ }
1041
+ };
1042
+ //#endregion
1043
+ //#region src/garden/checks/pipelines.ts
1044
+ const DAY$1 = 864e5;
1045
+ const SCENE = /scene[\s:=]+["']?([A-Za-z0-9._-]+)/gi;
1046
+ async function sceneIds(context, repo, runId) {
1047
+ const jobs = children(object(await context.api.json(`/repos/${ORG}/${repo.name}/actions/runs/${runId}/jobs`), "jobs"), "jobs");
1048
+ const ids = /* @__PURE__ */ new Set();
1049
+ for (const job of jobs) {
1050
+ const notes = await context.api.pages(`/repos/${ORG}/${repo.name}/check-runs/${num(job, "id")}/annotations`);
1051
+ for (const note of notes) for (const match of optStr(object(note, "annotation"), "message")?.matchAll(SCENE) ?? []) ids.add(match[1]);
1052
+ }
1053
+ return [...ids].sort();
1054
+ }
1055
+ const captureScenes = {
1056
+ id: "capture-scenes",
1057
+ async run(context) {
1058
+ let wired = 0;
1059
+ const result = await perRepo(await context.scope(), async (repo) => {
1060
+ const runs = await context.workflowRuns(repo, "docs-captures.yml", repo.defaultBranch, "");
1061
+ if (runs === void 0) return [];
1062
+ wired++;
1063
+ const latest = runs[0];
1064
+ if (latest === void 0 || latest.conclusion !== "failure") return [];
1065
+ const ids = await sceneIds(context, repo, latest.id);
1066
+ return (ids.length ? ids : ["run"]).map((id) => finding({
1067
+ repo: repo.name,
1068
+ check: "capture-scenes",
1069
+ subject: id
1070
+ }, `The latest docs-captures.yml run failed${id === "run" ? "" : ` on scene ${id}`}: ${latest.url}`, `Every capture scene renders in docs-captures.yml.`));
1071
+ });
1072
+ return wired ? result : skip("no repository runs docs-captures.yml yet");
1073
+ }
1074
+ };
1075
+ const WEB = "antelope-web";
1076
+ const webBuild = {
1077
+ id: "antelope-web-build",
1078
+ async run(context) {
1079
+ const repo = (await context.repos()).find(({ name }) => name === WEB);
1080
+ if (repo === void 0) return skip("antelope-web is not in the organization");
1081
+ const workflows = (await context.tree(repo)).filter((path) => /^\.github\/workflows\/[^/]+\.ya?ml$/.test(path));
1082
+ for (const path of workflows) {
1083
+ const text = await context.file(repo, path) ?? "";
1084
+ if (!/^\s*schedule:/m.test(text)) continue;
1085
+ const since = redSince(await context.workflowRuns(repo, path.split("/").pop() ?? "", repo.defaultBranch, "schedule") ?? []);
1086
+ return found(since === void 0 || context.api.now().getTime() - since.createdAt <= DAY$1 ? [] : [finding({
1087
+ repo: WEB,
1088
+ check: "antelope-web-build",
1089
+ subject: path
1090
+ }, `${path} has been red since ${new Date(since.createdAt).toISOString()}: ${since.url}`, `${path} is green.`)]);
1091
+ }
1092
+ return skip("antelope-web has no scheduled workflow yet");
1093
+ }
1094
+ };
1095
+ //#endregion
1096
+ //#region src/garden/checks/supply.ts
1097
+ const HOUR = 36e5;
1098
+ const STUCK_AFTER = 168 * HOUR;
1099
+ const ADVISORY_AFTER = 168 * HOUR;
1100
+ const CRITICAL_AFTER = 48 * HOUR;
1101
+ const GROWTH_LIMIT = 1.2;
1102
+ async function published(context, repo) {
1103
+ return (await context.packages(repo)).filter(({ name, private: hidden }) => name !== void 0 && !hidden);
1104
+ }
1105
+ async function alerts(context, repo) {
1106
+ const open = await context.alerts(repo);
1107
+ if (open === void 0) return [];
1108
+ const now = context.api.now().getTime();
1109
+ const shipped = (await published(context, repo)).length > 0;
1110
+ const findings = [];
1111
+ for (const alert of open) {
1112
+ const critical = alert.severity === "critical";
1113
+ if (!alert.runtime || now - alert.createdAt <= (critical ? CRITICAL_AFTER : ADVISORY_AFTER)) continue;
1114
+ findings.push(finding({
1115
+ repo: repo.name,
1116
+ check: "advisories",
1117
+ subject: alert.advisory
1118
+ }, `${alert.severity} advisory in the runtime dependency ${alert.package}, open since ${new Date(alert.createdAt).toISOString()}: ${alert.url}`, `The Dependabot alert ${alert.number} is fixed or dismissed with a reason.`, critical && shipped ? "urgent" : "normal"));
1119
+ }
1120
+ return findings;
1121
+ }
1122
+ function isStuck(pull) {
1123
+ return pull.author === "renovate[bot]" || /docs captures/i.test(pull.title) || /registry/i.test(pull.title) && /regenerat/i.test(pull.title);
1124
+ }
1125
+ async function stuck(context, repo) {
1126
+ const now = context.api.now().getTime();
1127
+ return (await context.openPulls(repo)).filter((pull) => isStuck(pull) && now - pull.createdAt > STUCK_AFTER).map((pull) => finding({
1128
+ repo: repo.name,
1129
+ check: "stuck-renovate",
1130
+ subject: `pr-${pull.number}`
1131
+ }, `${pull.title} has been open since ${new Date(pull.createdAt).toISOString()}: ${pull.url}`, `Pull request ${pull.number} is merged or closed.`));
1132
+ }
1133
+ function versions(packument) {
1134
+ return Object.keys(object(object(packument, "packument").versions ?? {}, "versions"));
1135
+ }
1136
+ function tarball(packument, version) {
1137
+ const entry = object(object(packument, "packument").versions ?? {}, "versions")[version];
1138
+ return entry === void 0 ? void 0 : optStr(object(object(entry, version).dist ?? {}, "dist"), "tarball");
1139
+ }
1140
+ async function size(context, name) {
1141
+ const packument = await context.packument(name);
1142
+ const latest = packument === void 0 ? void 0 : tagVersion(packument, "latest");
1143
+ if (packument === void 0 || latest === void 0) return void 0;
1144
+ const all = versions(packument);
1145
+ const prerelease = tagVersion(packument, "next");
1146
+ const [base, newest] = prerelease === void 0 ? [all.at(-2), all.at(-1)] : [latest, prerelease];
1147
+ const left = newest === void 0 ? void 0 : tarball(packument, newest);
1148
+ const right = base === void 0 ? void 0 : tarball(packument, base);
1149
+ if (base === void 0 || newest === void 0 || newest === base || left === void 0 || right === void 0) return void 0;
1150
+ const [next, current] = await Promise.all([context.api.contentLength(left), context.api.contentLength(right)]);
1151
+ return next === void 0 || current === void 0 || current === 0 ? void 0 : {
1152
+ current: base,
1153
+ newest,
1154
+ ratio: next / current
1155
+ };
1156
+ }
1157
+ async function grown(context, repo) {
1158
+ const findings = [];
1159
+ for (const manifest of await published(context, repo)) {
1160
+ const measured = manifest.name === void 0 ? void 0 : await size(context, manifest.name);
1161
+ if (manifest.name === void 0 || measured === void 0 || measured.ratio <= GROWTH_LIMIT) continue;
1162
+ findings.push(finding({
1163
+ repo: repo.name,
1164
+ check: "package-size",
1165
+ subject: manifest.name
1166
+ }, `${manifest.name}@${measured.newest} is ${Math.round((measured.ratio - 1) * 100)}% larger than ${measured.current}.`, `The newest tarball is within 20% of latest.`));
1167
+ }
1168
+ return findings;
1169
+ }
1170
+ const advisories = {
1171
+ id: "advisories",
1172
+ async run(context) {
1173
+ return perRepo(await context.scope(), (repo) => alerts(context, repo));
1174
+ }
1175
+ };
1176
+ const stuckRenovate = {
1177
+ id: "stuck-renovate",
1178
+ async run(context) {
1179
+ return perRepo(await context.scope(), (repo) => stuck(context, repo));
1180
+ }
1181
+ };
1182
+ const packageSize = {
1183
+ id: "package-size",
1184
+ async run(context) {
1185
+ return perRepo(await context.scope(), (repo) => grown(context, repo));
1186
+ }
1187
+ };
1188
+ //#endregion
1189
+ //#region src/garden/semver.ts
1190
+ const VERSION = /^v?(\d+)\.(\d+)\.(\d+)/;
1191
+ function parse(text) {
1192
+ const match = VERSION.exec(text.trim());
1193
+ return match ? [
1194
+ Number(match[1]),
1195
+ Number(match[2]),
1196
+ Number(match[3])
1197
+ ] : void 0;
1198
+ }
1199
+ function compare$1(a, b) {
1200
+ return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
1201
+ }
1202
+ function caret(floor) {
1203
+ if (floor[0] > 0) return [
1204
+ floor[0] + 1,
1205
+ 0,
1206
+ 0
1207
+ ];
1208
+ return floor[1] > 0 ? [
1209
+ 0,
1210
+ floor[1] + 1,
1211
+ 0
1212
+ ] : [
1213
+ 0,
1214
+ 0,
1215
+ floor[2] + 1
1216
+ ];
1217
+ }
1218
+ function comparator(term, version) {
1219
+ const operator = /^(>=|<=|>|<|=|\^|~)?\s*(.*)$/.exec(term.trim());
1220
+ const bound = parse(operator?.[2] ?? "");
1221
+ if (!operator || !bound) return true;
1222
+ switch (operator[1]) {
1223
+ case ">=": return compare$1(version, bound) >= 0;
1224
+ case ">": return compare$1(version, bound) > 0;
1225
+ case "<=": return compare$1(version, bound) <= 0;
1226
+ case "<": return compare$1(version, bound) < 0;
1227
+ case "^": return compare$1(version, bound) >= 0 && compare$1(version, caret(bound)) < 0;
1228
+ case "~": return compare$1(version, bound) >= 0 && compare$1(version, [
1229
+ bound[0],
1230
+ bound[1] + 1,
1231
+ 0
1232
+ ]) < 0;
1233
+ default: return compare$1(version, bound) === 0;
1234
+ }
1235
+ }
1236
+ /** Whether a plain npm range (`^`, `~`, comparators, `||`, `*`) admits a release; wildcards and tags admit everything. */
1237
+ function admits(range, release) {
1238
+ const version = parse(release);
1239
+ if (!version) return true;
1240
+ return range.split("||").some((alternative) => {
1241
+ return alternative.replace(/(>=|<=|>|<|=|\^|~)\s+/g, "$1").trim().split(/\s+/).every((term) => comparator(term, version));
1242
+ });
1243
+ }
1244
+ //#endregion
1245
+ //#region src/garden/checks/templates.ts
1246
+ const DAY = 864e5;
1247
+ const INTERFACES = "interfaces";
1248
+ const REGISTRY_BIN = "antelopejs-registry";
1249
+ const SCOPE = "@antelopejs/";
1250
+ const DEPENDENCY_FIELDS = [
1251
+ "dependencies",
1252
+ "devDependencies",
1253
+ "peerDependencies",
1254
+ "optionalDependencies"
1255
+ ];
1256
+ async function templates(context) {
1257
+ return (await context.repos()).filter((repo) => repo.pack === "template");
1258
+ }
1259
+ async function registryShipped(context) {
1260
+ const packument = await context.packument(TOOLING_PACKAGE);
1261
+ const latest = packument === void 0 ? void 0 : tagVersion(packument, "latest");
1262
+ if (packument === void 0 || latest === void 0) return false;
1263
+ const bin = child(object(object(packument, "packument").versions ?? {}, "versions"), latest);
1264
+ return Object.keys(child(bin, "bin")).includes(REGISTRY_BIN);
1265
+ }
1266
+ function listedTemplates(manifest) {
1267
+ return [...children(manifest, "templates"), ...children(manifest, "projectTemplates")].map((entry) => /([^/]+?)(?:\.git)?$/.exec(str(entry, "repository"))?.[1] ?? "");
1268
+ }
1269
+ async function declaredRanges(context, repo) {
1270
+ const ranges = [];
1271
+ for (const manifest of await context.packages(repo)) {
1272
+ const source = object(parseJson(await context.file(repo, manifest.path) ?? "{}"), manifest.path);
1273
+ for (const field of DEPENDENCY_FIELDS) {
1274
+ const group = child(source, field);
1275
+ for (const name of Object.keys(group).filter((key) => key.startsWith(SCOPE))) ranges.push({
1276
+ name,
1277
+ range: optStr(group, name) ?? ""
1278
+ });
1279
+ }
1280
+ }
1281
+ return ranges;
1282
+ }
1283
+ function publishedAt(packument, version) {
1284
+ const moment = child(object(packument, "packument"), "time")[version];
1285
+ return moment === void 0 ? void 0 : Date.parse(String(moment));
1286
+ }
1287
+ async function behind(context, repo) {
1288
+ const findings = [];
1289
+ const now = context.api.now().getTime();
1290
+ for (const { name, range } of await declaredRanges(context, repo)) {
1291
+ const packument = await context.packument(name);
1292
+ const latest = packument === void 0 ? void 0 : tagVersion(packument, "latest");
1293
+ const released = packument === void 0 || latest === void 0 ? void 0 : publishedAt(packument, latest);
1294
+ if (latest === void 0 || released === void 0 || admits(range, latest) || now - released <= 7 * DAY) continue;
1295
+ findings.push(finding({
1296
+ repo: repo.name,
1297
+ check: "template-behind-latest",
1298
+ subject: name
1299
+ }, `${name} ${range} excludes ${latest}, published ${new Date(released).toISOString()}.`, `The range of ${name} admits ${latest}.`));
1300
+ }
1301
+ return findings;
1302
+ }
1303
+ const templateBehindLatest = {
1304
+ id: "template-behind-latest",
1305
+ async run(context) {
1306
+ const repos = await templates(context);
1307
+ let described = false;
1308
+ for (const repo of repos) described ||= (await context.packages(repo)).some(({ hasTemplate }) => hasTemplate);
1309
+ return described ? perRepo(repos, (repo) => behind(context, repo)) : skip("no template declares antelopeJs.template yet");
1310
+ }
1311
+ };
1312
+ const templateMembership = {
1313
+ id: "template-membership",
1314
+ async run(context) {
1315
+ if (!await registryShipped(context)) return skip(`${REGISTRY_BIN} is not released yet`);
1316
+ const listed = listedTemplates(object(parseJson(await context.api.text(`/repos/${ORG}/${INTERFACES}/contents/manifest.json`)), "manifest"));
1317
+ const archived = await context.archived();
1318
+ return found([...(await templates(context)).filter((repo) => !listed.includes(repo.name)).map((repo) => finding({
1319
+ repo: repo.name,
1320
+ check: "template-membership",
1321
+ subject: "missing"
1322
+ }, `${repo.name} has pack=template and is not in the Registry.`, `${repo.name} is listed under templates or projectTemplates.`)), ...listed.filter((name) => archived.has(name)).map((name) => finding({
1323
+ repo: INTERFACES,
1324
+ check: "template-membership",
1325
+ subject: `archived:${name}`
1326
+ }, `The Registry lists the archived repository ${name}.`, `The entry for ${name} is removed.`))]);
1327
+ }
1328
+ };
1329
+ const staleRegistry = {
1330
+ id: "stale-registry",
1331
+ async run(context) {
1332
+ if (!await registryShipped(context)) return skip(`${REGISTRY_BIN} is not released yet`);
1333
+ const interfaces = (await context.repos()).find(({ name }) => name === INTERFACES);
1334
+ if (interfaces === void 0) return skip("AntelopeJS/interfaces is not in the organization");
1335
+ const files = await context.tree(interfaces);
1336
+ const contents = await Promise.all(files.filter((path) => path.endsWith(".json")).map(async (path) => ({
1337
+ path,
1338
+ content: await context.file(interfaces, path) ?? ""
1339
+ })));
1340
+ if (!await context.api.registryDiffers(contents)) return found([]);
1341
+ const now = context.api.now().getTime();
1342
+ const open = (await context.openPulls(interfaces)).find((pull) => /regenerat/i.test(pull.title));
1343
+ if (open !== void 0 && now - open.createdAt <= DAY) return found([]);
1344
+ const evidence = open === void 0 ? "The Registry output differs from the committed manifests and no regeneration PR is open." : `The regeneration PR has been open since ${new Date(open.createdAt).toISOString()}: ${open.url}`;
1345
+ return found([finding({
1346
+ repo: INTERFACES,
1347
+ check: "stale-registry",
1348
+ subject: "manifests"
1349
+ }, evidence, "The committed manifests match antelopejs-registry output.")]);
1350
+ }
1351
+ };
1352
+ const CANARY = "template-canary.yml";
1353
+ const templateCanary = {
1354
+ id: "template-canary",
1355
+ async run(context) {
1356
+ let wired = 0;
1357
+ const result = await perRepo(await templates(context), async (repo) => {
1358
+ const runs = await context.workflowRuns(repo, CANARY, repo.defaultBranch, "");
1359
+ if (runs === void 0) return [];
1360
+ wired++;
1361
+ const latest = runs[0];
1362
+ return latest?.conclusion === "failure" ? [finding({
1363
+ repo: repo.name,
1364
+ check: "template-canary",
1365
+ subject: "canary"
1366
+ }, `The latest ${CANARY} run is red: ${latest.url}`, `${CANARY} is green with every @antelopejs/* dependency on next.`)] : [];
1367
+ });
1368
+ return wired ? result : skip(`no template runs ${CANARY} yet`);
1369
+ }
1370
+ };
1371
+ //#endregion
1372
+ //#region src/garden/pauses.ts
1373
+ const PAUSED = "shadow";
1374
+ function reasons(repo, findings) {
1375
+ const own = findings.filter((entry) => entry.repo === repo);
1376
+ return [...own.some((entry) => entry.check === "conformance" && entry.subject === "ratchet") ? ["the ratchet file is back on a Clean repository"] : [], ...own.some((entry) => entry.check === "next-governance") ? ["governance drift"] : []];
1377
+ }
1378
+ /** Repositories where `NEXT_AUTOMERGE` is `on` and a stop-the-line trigger fired. */
1379
+ async function plannedPauses(context, findings) {
1380
+ const pauses = [];
1381
+ for (const repo of await context.scope()) {
1382
+ if (await context.variable(repo, "NEXT_AUTOMERGE") !== "on") continue;
1383
+ const triggers = reasons(repo.name, findings);
1384
+ const runs = await context.targetBranch(repo) === "next" ? await context.workflowRuns(repo, "ci.yml", "next") : void 0;
1385
+ if (runs !== void 0 && redSince(runs) !== void 0) triggers.unshift("checks is red on next after a merge");
1386
+ if (triggers.length) pauses.push({
1387
+ repo: repo.name,
1388
+ from: "on",
1389
+ to: PAUSED,
1390
+ reason: triggers.join("; ")
1391
+ });
1392
+ }
1393
+ return pauses;
1394
+ }
1395
+ /** Writes the one repository variable and nothing else. */
1396
+ async function applyPauses(api, pauses) {
1397
+ for (const pause of pauses) await api.send("PATCH", `/repos/${ORG}/${pause.repo}/actions/variables/${AUTOMERGE}`, {
1398
+ name: AUTOMERGE,
1399
+ value: pause.to
1400
+ });
1401
+ }
1402
+ //#endregion
1403
+ //#region src/garden/run.ts
1404
+ const CHECKS = [
1405
+ conformance,
1406
+ redBranch,
1407
+ ciDuration,
1408
+ advisories,
1409
+ stuckRenovate,
1410
+ governanceDrift,
1411
+ nextGovernance,
1412
+ orgChecksRuleset,
1413
+ aiApps,
1414
+ orbSecrets,
1415
+ packageSize,
1416
+ mutation,
1417
+ templateBehindLatest,
1418
+ templateMembership,
1419
+ staleRegistry,
1420
+ templateCanary,
1421
+ webBuild,
1422
+ linkRot,
1423
+ captureScenes
1424
+ ];
1425
+ function compare(a, b) {
1426
+ return a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
1427
+ }
1428
+ /** Runs every check, plans the pauses and applies them only when asked. */
1429
+ async function garden(api, options) {
1430
+ const context = new GardenContext(api);
1431
+ const found = [];
1432
+ const skipped = [];
1433
+ const failures = [];
1434
+ for (const check of options.checks ?? CHECKS) try {
1435
+ const result = await check.run(context);
1436
+ if (result.kind === "findings") found.push(...result.findings);
1437
+ else skipped.push({
1438
+ check: check.id,
1439
+ reason: result.reason
1440
+ });
1441
+ } catch (error) {
1442
+ const failure = {
1443
+ check: check.id,
1444
+ reason: error instanceof Error ? error.message : String(error)
1445
+ };
1446
+ if (error instanceof PartialFailure) found.push(...error.findings);
1447
+ skipped.push(failure);
1448
+ failures.push(failure);
1449
+ }
1450
+ const findings = [...new Map(found.map((entry) => [entry.key, entry])).values()].sort(compare);
1451
+ const pauses = (await plannedPauses(context, findings)).sort((a, b) => a.repo < b.repo ? -1 : 1);
1452
+ if (options.applyPauses) await applyPauses(api, pauses);
1453
+ return {
1454
+ report: {
1455
+ generatedAt: api.now().toISOString(),
1456
+ findings,
1457
+ pauses,
1458
+ skipped: skipped.sort((a, b) => a.check < b.check ? -1 : 1)
1459
+ },
1460
+ failures
1461
+ };
1462
+ }
1463
+ /** One line per finding and per check that could not run; nothing when the org is clean. */
1464
+ function failureLines(outcome) {
1465
+ return [...outcome.report.findings.map((entry) => `${entry.severity === "urgent" ? "URGENT " : ""}${entry.repo} ${entry.check} ${entry.subject}: ${entry.evidence}`), ...outcome.failures.map((entry) => `${entry.check} could not run: ${entry.reason}`)];
1466
+ }
1467
+ //#endregion
1468
+ //#region src/bin/garden.ts
1469
+ await runCliAsync(async () => {
1470
+ const { values } = parseArgs({ options: {
1471
+ json: { type: "boolean" },
1472
+ "apply-pauses": { type: "boolean" }
1473
+ } });
1474
+ const outcome = await garden(createApi(ghToken()), { applyPauses: values["apply-pauses"] === true });
1475
+ if (values.json) process.stdout.write(`${JSON.stringify(outcome.report, null, 2)}\n`);
1476
+ else for (const line of failureLines(outcome)) process.stdout.write(`${line}\n`);
1477
+ return outcome.failures.length ? 1 : 0;
1478
+ });
1479
+ //#endregion
1480
+ export {};