@theholocron/cli 5.0.0-alpha.99 → 5.0.0

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.
package/dist/index.mjs CHANGED
@@ -1,121 +1,864 @@
1
- import { CARDINALITY, ProviderApiError, REQUIRED_CAPABILITIES, WebhookVerificationError, isMulti } from "./plugin/capabilities.mjs";
2
- import { AuthError, createResolveToken as createResolveToken$1, createRestClient } from "@theholocron/http-client";
3
- import { createEnvLookup } from "@theholocron/env-utils";
1
+ import { CARDINALITY, ElevationRequiredError, MissingTokenError, ProviderApiError, REQUIRED_CAPABILITIES, WebhookVerificationError, isMulti } from "./plugin/capabilities.mjs";
2
+ import { a as placeAreas, c as ConfigError, d as resolveEntry, f as resolvePluginPackage, g as layerEnvironment, h as isEnvironmentLayer, i as loadConfig, l as credentialsEnvironment, m as ENVIRONMENT_LAYERS, n as compose, o as HOLOCRON_AREAS, p as repoSlug, r as defineConfig, s as SHARED_AREAS, t as ConfigFileError, u as resolveConfig } from "./config-system-CZ9zgh3-.mjs";
4
3
  import { Entry, findCredentials } from "@napi-rs/keyring";
4
+ import { AuthError, createFeatureResolver as createFeatureResolver$1, createKeyring, createResolveToken as createResolveToken$1, resolveValue } from "@theholocron/kyber/secrets";
5
+ import { AGGREGATE_CHECK_NAME, AGGREGATE_SHADOW_CHECK_NAME, DOCUMENTATION_FLAG, codecovFlagNames, readWorkspacePackages, requiredChecks, requiredChecksVerdict } from "@theholocron/astromech";
6
+ import { dirname, join, posix, resolve } from "node:path";
5
7
  import { readFile } from "node:fs/promises";
6
- import { basename, dirname, join } from "node:path";
7
- import load from "@commitlint/load";
8
- import lint from "@commitlint/lint";
9
- import { execFile } from "node:child_process";
10
- import { promisify } from "node:util";
11
- import { loadTasksConfig } from "@theholocron/astromech/config";
12
- import { ConfigFileError, ConfigFileError as ConfigFileError$1, loadConfigFile } from "@theholocron/datapad";
13
- createEnvLookup();
8
+ import { describeError, style } from "@theholocron/kyber/ui";
9
+ import { errorMessage } from "@theholocron/misc-utils";
10
+ import { createRestClient } from "@theholocron/http-client";
11
+ import { ConfigError as ConfigError$1 } from "@theholocron/kyber/config";
12
+ import { connectionProbe as connectionProbe$1 } from "@theholocron/kyber/checks";
13
+ import { readPackageJson } from "@theholocron/pkg-utils";
14
+ import { fstatSync, mkdirSync } from "node:fs";
15
+ // src/auth/auth.ts
14
16
  /**
15
- * Create an injectable env for commands that accept a fake env in tests.
16
- * Pass `input.env` when available, falls back to `process.env`.
17
+ * The CLI's credentials: the OS keyring every plugin's bootstrap token lives in, and the two token resolvers built on
18
+ * it. Both are public, so a plugin's `src/auth.ts` is a one-line call.
19
+ *
20
+ * The keyring itself, with its best-effort failure model and its per-process cache, is `createKeyring` in
21
+ * `@theholocron/kyber/secrets`; this file only names the service. Managed via `holocron check token` subcommands and consulted
22
+ * last in every plugin's precedence chain (after --token / HOLOCRON_<X>_TOKEN / <native>_TOKEN). See
23
+ * `docs/wiki/specifications/tech-auth-bootstrap.spec.md`.
24
+ */
25
+ /**
26
+ * The holocron keyring: `get` answers `null` for "not stored" and for "keyring unavailable" alike, so callers fall
27
+ * through to env-var precedence, and remembers the answer for the process (`clearCache` forgets it); `set` and `delete`
28
+ * answer whether they did anything; `list` names the stored providers; `isAvailable` tells an outage from an empty keyring.
29
+ */
30
+ const keyring = createKeyring({
31
+ service: "com.theholocron.cli",
32
+ binding: {
33
+ Entry,
34
+ findCredentials
35
+ }
36
+ });
37
+ /**
38
+ * Kyber's `createResolveToken` with the keyring, the `HOLOCRON_ORG` variable and the `token` description
39
+ * `holocron doctor secrets --verify` reads filled in, so a plugin stays at a one-liner call site. The chain is the flag, the
40
+ * plugin's variable, the vendor's variable, the `credentials` providers' variables, the keyring.
41
+ */
42
+ function createResolveToken(config) {
43
+ return Object.assign(createResolveToken$1({
44
+ ...config,
45
+ keyring: keyring.get,
46
+ orgEnvName: "HOLOCRON_ORG"
47
+ }), { token: {
48
+ envName: config.envName,
49
+ vendorEnvName: config.vendorEnvName,
50
+ keyringKey: config.keyringService
51
+ } });
52
+ }
53
+ /**
54
+ * Kyber's `createFeatureResolver` for a strict, single-feature token: the flag, the feature's variable, the
55
+ * `credentials` providers' variable of that name, the keyring. No broad-token fallback; if the feature's token is absent
56
+ * the operation fails with a message naming the exact variable to set and `holocron new token`.
17
57
  */
18
- function makeEnv(source) {
19
- return createEnvLookup(source);
58
+ function createFeatureResolver(config) {
59
+ return Object.assign(createFeatureResolver$1({
60
+ ...config,
61
+ vendor: config.vendor ?? "GitHub",
62
+ setCommand: (key) => `holocron new token ${key} <token>`,
63
+ keyring: keyring.get
64
+ }), { token: {
65
+ envName: config.envName,
66
+ keyringKey: config.keyringKey
67
+ } });
20
68
  }
21
- //#endregion
22
- //#region src/auth/keyring.ts
69
+ // src/commands/coverage-expectations/coverage-expectations.ts
23
70
  /**
24
- * Keyring-backed bootstrap credential store.
25
- *
26
- * Every holocron plugin's bootstrap token (the one it needs before it
27
- * can talk to its vendor's API) can be stored in the OS keyring under
28
- * a single reverse-DNS service scope. Managed via `holocron auth`
29
- * subcommands; consulted at position 4 in every plugin's auth
30
- * precedence chain (after --token / HOLOCRON_<X>_TOKEN / <native>_TOKEN).
31
- *
32
- * See `docs/wiki/specifications/tech-auth-bootstrap.spec.md` for the design rationale.
71
+ * The flags and components `holocron sync` writes to `codecov.yml` for the workspace at `repoRoot`: the same
72
+ * functions the generator uses, so a coverage provider's `checkRepo()` compares with exactly what is written. A flag per
73
+ * package (none for `docs`), plus `documentation` when `docsCoverage` is `warn` or `required`; a component per package.
74
+ * Both lists are sorted. Plugins call this instead of importing the task runner.
75
+ */
76
+ function coverageExpectations(repoRoot, docsCoverage = "off") {
77
+ const packages = readWorkspacePackages(repoRoot);
78
+ const flags = codecovFlagNames(packages);
79
+ if (docsCoverage !== "off") flags.push(DOCUMENTATION_FLAG);
80
+ return {
81
+ flags: [...new Set(flags)].sort(),
82
+ components: packages.map((pkg) => pkg.slug).sort()
83
+ };
84
+ }
85
+ // src/commands/notifications-reaction/layout-reactions/layout-reactions.ts
86
+ /**
87
+ * Every reaction a layout writes that can name a server emoji: each forum's default and starter reactions and its tags'
88
+ * `emoji` (a tag's is a string, Unicode or `:name:`), then the layout's own `emojis` (server emoji made with no reaction
89
+ * naming them), in that order.
90
+ */
91
+ function layoutReactions(layout) {
92
+ const reactions = [];
93
+ for (const channel of (layout?.categories ?? []).flatMap((c) => c.channels ?? [])) {
94
+ if (channel.defaultReaction !== void 0) reactions.push(channel.defaultReaction);
95
+ reactions.push(...channel.starterReactions ?? []);
96
+ for (const tag of channel.tags ?? []) if (tag.emoji) reactions.push(tag.emoji);
97
+ }
98
+ reactions.push(...layout?.emojis ?? []);
99
+ return reactions;
100
+ }
101
+ // src/commands/notifications-reaction/parse-reaction/parse-reaction.ts
102
+ /** A server emoji written as Discord shows it: `:name:`, the name 2 to 32 letters, digits and underscores. */
103
+ const CUSTOM_EMOJI = /^:([A-Za-z0-9_]{2,32}):$/;
104
+ /**
105
+ * Reads a layout reaction. `":git_merge:"` (or `{ emoji: ":git_merge:", image }`) is a server emoji named `git_merge`;
106
+ * any other string is a Unicode emoji and kept as written. It does not judge a value: `reactionProblem()` does, before
107
+ * anything is applied, so an invalid `emoji` here is kept as the name it was given.
108
+ */
109
+ function parseReaction(reaction) {
110
+ if (typeof reaction === "string") {
111
+ const name = CUSTOM_EMOJI.exec(reaction)?.[1];
112
+ return name === void 0 ? {
113
+ kind: "unicode",
114
+ value: reaction
115
+ } : {
116
+ kind: "custom",
117
+ name
118
+ };
119
+ }
120
+ return {
121
+ kind: "custom",
122
+ name: CUSTOM_EMOJI.exec(reaction.emoji)?.[1] ?? reaction.emoji,
123
+ ...reaction.image ? { image: reaction.image } : {}
124
+ };
125
+ }
126
+ // src/commands/notifications-reaction/emoji-conflict-problem/emoji-conflict-problem.ts
127
+ /**
128
+ * The first server emoji a layout gives two different pictures, or undefined. One name is one emoji, so it can be made
129
+ * from one file only; the same file written twice is fine.
130
+ */
131
+ function emojiConflictProblem(layout) {
132
+ const images = /* @__PURE__ */ new Map();
133
+ for (const reaction of layoutReactions(layout)) {
134
+ const parsed = parseReaction(reaction);
135
+ if (parsed.kind !== "custom" || !parsed.image) continue;
136
+ const image = posix.normalize(parsed.image);
137
+ const have = images.get(parsed.name);
138
+ if (have !== void 0 && have !== image) return `emoji \`:${parsed.name}:\` is given two different images, \`${have}\` and \`${image}\``;
139
+ images.set(parsed.name, image);
140
+ }
141
+ }
142
+ // src/commands/notifications-reaction/layout-emojis/layout-emojis.ts
143
+ /**
144
+ * The server emoji a layout's forum reactions name (default and starter) and its `emojis` list, once each, in the order the layout first
145
+ * names them. A name that is given an `image` anywhere keeps it, so the picture can sit on any one of its uses.
146
+ */
147
+ function layoutEmojis(layout) {
148
+ const found = /* @__PURE__ */ new Map();
149
+ for (const reaction of layoutReactions(layout)) {
150
+ const parsed = parseReaction(reaction);
151
+ if (parsed.kind !== "custom") continue;
152
+ const have = found.get(parsed.name);
153
+ if (!have) found.set(parsed.name, {
154
+ name: parsed.name,
155
+ ...parsed.image ? { image: parsed.image } : {}
156
+ });
157
+ else if (!have.image && parsed.image) have.image = parsed.image;
158
+ }
159
+ return [...found.values()];
160
+ }
161
+ // src/commands/notifications-reaction/load-emoji-image/load-emoji-image.ts
162
+ /** Discord's limit for an emoji file ("256 KiB", its Emoji resource docs). */
163
+ const MAX_EMOJI_BYTES = 262144;
164
+ const ascii = (bytes, from, to) => Buffer.from(bytes.subarray(from, to)).toString("latin1");
165
+ /** The image type the first bytes show, among the ones Discord takes for an emoji (JPEG, PNG, GIF, WebP, AVIF). */
166
+ function typeOf(bytes) {
167
+ if (bytes.length >= 8 && [
168
+ 137,
169
+ 80,
170
+ 78,
171
+ 71,
172
+ 13,
173
+ 10,
174
+ 26,
175
+ 10
176
+ ].every((b, i) => bytes[i] === b)) return "image/png";
177
+ if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg";
178
+ if (ascii(bytes, 0, 4) === "GIF8") return "image/gif";
179
+ if (ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 12) === "WEBP") return "image/webp";
180
+ if (ascii(bytes, 4, 8) === "ftyp" && ["avif", "avis"].includes(ascii(bytes, 8, 12))) return "image/avif";
181
+ }
182
+ /**
183
+ * Reads the picture an emoji is made from, a file in the repo, and returns it as a `data:` URI. The type comes from the
184
+ * first bytes, not the name, and a file Discord would refuse (larger than 256 KiB, or not a JPEG, PNG, GIF, WebP or
185
+ * AVIF image) is refused here, before anything is written. `read` is injected by tests.
186
+ */
187
+ async function loadEmojiImage(source, baseDir = process.cwd(), read = readFile) {
188
+ const bytes = await read(resolve(baseDir, source));
189
+ if (bytes.length > 262144) throw new Error(`it is ${Math.ceil(bytes.length / 1024)} KiB, and Discord takes an emoji up to 256 KiB`);
190
+ const type = typeOf(bytes);
191
+ if (!type) throw new Error("it is not a JPEG, PNG, GIF, WebP or AVIF image, which are the formats Discord takes");
192
+ return `data:${type};base64,${Buffer.from(bytes).toString("base64")}`;
193
+ }
194
+ // src/commands/notifications-reaction/reaction-problem/reaction-problem.ts
195
+ /** The folder a layout's emoji pictures live in, as the webhook avatar's files do. */
196
+ const EMOJI_MEDIA_DIR = ".holocron/media/";
197
+ /**
198
+ * The first reason a reaction cannot work, or undefined; `noun` names it in the message (`` `defaultReaction` ``, "a
199
+ * starter reaction"). A Unicode emoji must be a character, not a word (`git_merge` without colons would be sent to
200
+ * Discord as text), a server emoji `:name:` with a name Discord allows, and an `image` a file under `.holocron/media/`
201
+ * (a path, not a URL, with no `..` out of it). A `null` a config wrote is refused, not read as absent.
202
+ */
203
+ function reactionProblem(noun, reaction) {
204
+ if (reaction === null || typeof reaction !== "string" && typeof reaction !== "object") return `${noun} must be an emoji, \`:name:\` for a server emoji, or \`{ emoji, image }\``;
205
+ const text = typeof reaction === "string" ? reaction : reaction.emoji;
206
+ if (typeof text !== "string" || text.trim() === "") return `${noun} is empty`;
207
+ const isCustom = CUSTOM_EMOJI.test(text);
208
+ if (typeof reaction === "object" && !isCustom) return `${noun}: \`emoji\` must be a server emoji written \`:name:\` (2 to 32 letters, digits and underscores), not \`${text}\``;
209
+ if (!isCustom && /^:|:$|^[A-Za-z0-9_ ]+$/.test(text)) return `${noun}: \`${text}\` is not an emoji; write a server emoji as \`:name:\` (2 to 32 letters, digits and underscores)`;
210
+ if (typeof reaction === "object" && reaction.image !== void 0) {
211
+ const image = reaction.image;
212
+ if (typeof image !== "string" || image.trim() === "") return `${noun}: \`image\` is empty`;
213
+ if (/^[a-z][a-z0-9+.-]+:/i.test(image)) return `${noun}: \`image\` must be a file under \`${EMOJI_MEDIA_DIR}\`, not a URL`;
214
+ const path = posix.normalize(image);
215
+ if (!path.startsWith(".holocron/media/") || path === ".holocron/media/") return `${noun}: \`image\` must be a file under \`${EMOJI_MEDIA_DIR}\`, not \`${image}\``;
216
+ }
217
+ }
218
+ // src/commands/notifications-reaction/reaction-spelling/reaction-spelling.ts
219
+ /** How a reaction is written in a layout and shown in a row: `:name:` for a server emoji, the character otherwise. */
220
+ function reactionSpelling(reaction) {
221
+ const parsed = parseReaction(reaction);
222
+ return parsed.kind === "custom" ? `:${parsed.name}:` : parsed.value;
223
+ }
224
+ // src/commands/notifications-reaction/tag-emoji-problem/tag-emoji-problem.ts
225
+ /**
226
+ * The first reason a forum tag's `emoji` cannot work, or undefined. A string with no colon at either end is a Unicode
227
+ * emoji and kept as written (it is not judged). One that starts or ends with a colon is meant as a server emoji, so it
228
+ * must be `:name:` (2 to 32 letters, digits and underscores), and the layout must give that emoji a picture somewhere
229
+ * (`pictured`: the names an `image` is declared for, from `layoutEmojis()`), because a tag's `emoji` is only a name and
230
+ * `setup` makes the emoji before any channel.
231
+ */
232
+ function tagEmojiProblem(tagName, emoji, pictured) {
233
+ if (emoji === void 0 || !/^:|:$/.test(emoji)) return void 0;
234
+ const noun = `tag \`${tagName}\` emoji`;
235
+ const problem = reactionProblem(noun, emoji);
236
+ if (problem) return problem;
237
+ if (pictured.has(emoji.slice(1, -1))) return void 0;
238
+ return `${noun} \`${emoji}\` has no picture: give the emoji an \`image\` in \`emojis\` or a reaction so \`setup\` can make it`;
239
+ }
240
+ // src/plugin/issues-provider/order-keys/order-keys.ts
241
+ /**
242
+ * Puts issue keys in creation order without asking the tracker: issue numbers (`#12`, `ENG-12`) rise with creation inside
243
+ * one repository or team, so the trailing number is the order. `oldest` is ascending, `newest` descending; keys with the
244
+ * same number keep their place. A key with no trailing number is an error, because nothing can be said of its age.
245
+ */
246
+ function orderKeys(keys, order) {
247
+ const numbered = keys.map((key, index) => {
248
+ const trimmed = key.trimEnd();
249
+ let start = trimmed.length;
250
+ while (start > 0 && trimmed[start - 1] >= "0" && trimmed[start - 1] <= "9") start -= 1;
251
+ if (start === trimmed.length) throw new Error(`Cannot order "${key}" by creation: it has no issue number.`);
252
+ return {
253
+ key,
254
+ index,
255
+ n: Number(trimmed.slice(start))
256
+ };
257
+ });
258
+ const sign = order === "newest" ? -1 : 1;
259
+ return numbered.sort((a, b) => sign * (a.n - b.n) || a.index - b.index).map((e) => e.key);
260
+ }
261
+ // src/plugin/issues-provider/pick-by-creation/pick-by-creation.ts
262
+ /**
263
+ * Keeps the first or last `limit` of a listing by creation time, returned oldest first. `createdAt` reads an item's
264
+ * ISO timestamp; items created in the same instant keep their listed order. The cut happens on what the listing already
265
+ * holds, so no request is spent on an item that is dropped.
266
+ */
267
+ function pickByCreation(items, createdAt, order, limit) {
268
+ const ascending = items.map((item, index) => ({
269
+ item,
270
+ index,
271
+ at: Date.parse(createdAt(item))
272
+ })).sort((a, b) => a.at - b.at || a.index - b.index).map((e) => e.item);
273
+ return order === "newest" ? ascending.slice(Math.max(ascending.length - limit, 0)) : ascending.slice(0, limit);
274
+ }
275
+ // src/plugin/issues-provider/read-keys-limited/read-keys-limited.ts
276
+ /**
277
+ * Reads an explicit list of issues in creation order until `limit` of them are kept. The keys are sorted by number first
278
+ * (see {@link orderKeys}), then fetched in small steps of at most `concurrency`, each step no bigger than the places
279
+ * still open, so an issue that is later skipped (a pull request, a closed one) is replaced by the next key and nothing
280
+ * beyond the budget is fetched unless a skip made room. Within a step the fetches run together; the results keep the key
281
+ * order. The kept items come back oldest first, whichever end was chosen.
282
+ */
283
+ async function readKeysLimited(input) {
284
+ const { keys, order, limit, concurrency, fetch, keep } = input;
285
+ const ordered = orderKeys(keys, order);
286
+ const kept = [];
287
+ let next = 0;
288
+ while (kept.length < limit && next < ordered.length) {
289
+ const step = ordered.slice(next, next + Math.min(concurrency, limit - kept.length));
290
+ next += step.length;
291
+ const fetched = await Promise.all(step.map((key) => fetch(key)));
292
+ for (const item of fetched) if (keep(item)) kept.push(item);
293
+ }
294
+ return order === "newest" ? kept.reverse() : kept;
295
+ }
296
+ // src/plugin/issues-provider/report-progress/report-progress.ts
297
+ /**
298
+ * Calls a provider's optional `onProgress` hook with how many items are done of how many. A hook that throws is
299
+ * ignored, because a progress counter must never change or stop the read or write it reports on.
33
300
  *
34
- * Failure model: keyring access is best-effort. Platforms without a
35
- * supported credential store (some Linux CI images, sandboxed
36
- * environments) will throw from the underlying library. Every export
37
- * here catches and returns a null/empty result rather than propagating
38
- * — the plugin's precedence chain then falls through to
39
- * env-var-only paths, which is exactly how CI is meant to work.
301
+ * @param onProgress - The hook from `ExportInfo` or `ImportOptions`; nothing happens when it is not given.
302
+ * @param done - How many items are finished.
303
+ * @param total - How many items there are.
40
304
  */
41
- const SERVICE = "com.theholocron.cli";
305
+ function reportProgress(onProgress, done, total) {
306
+ try {
307
+ onProgress?.(done, total);
308
+ } catch {}
309
+ }
310
+ // src/plugin/probes/connection-probe/connection-probe.ts
42
311
  /**
43
- * Store or overwrite a bootstrap token for a provider. Returns true on
44
- * success, false when the underlying keyring is unsupported or errored.
312
+ * The `connection` probe every provider offers, for telling a network problem from a credential problem. The checks are
313
+ * kyber's `connectionProbe`; this types the result as the plugin system's {@link Probe} and `verify` as `VerifyTokenResult`.
45
314
  */
46
- function setToken(provider, token) {
315
+ function connectionProbe(input) {
316
+ return connectionProbe$1(input);
317
+ }
318
+ // src/commands/notifications-sync-roles/links.ts
319
+ const EMPTY_LINKS = {
320
+ version: 1,
321
+ links: []
322
+ };
323
+ const DIGITS = /^\d{1,20}$/;
324
+ /** Reads the file's text. Throws with a plain reason on anything that is not a links file, so a damaged one is never treated as empty. */
325
+ function parseLinks(text) {
326
+ let raw;
47
327
  try {
48
- new Entry(SERVICE, provider).setPassword(token);
49
- return true;
328
+ raw = JSON.parse(text);
50
329
  } catch {
51
- return false;
330
+ throw new Error("the links file is not valid JSON");
52
331
  }
332
+ const file = raw;
333
+ if (file.version !== 1) throw new Error(`the links file has version ${JSON.stringify(file.version)}; expected 1`);
334
+ if (!Array.isArray(file.links)) throw new Error("the links file has no `links` list");
335
+ const links = file.links.map((entry, i) => {
336
+ const e = entry;
337
+ if (typeof e.github !== "string" || !DIGITS.test(e.github)) throw new Error(`links[${i}]: \`github\` must be a numeric user id string`);
338
+ if (typeof e.member !== "string" || !DIGITS.test(e.member)) throw new Error(`links[${i}]: \`member\` must be a numeric id string`);
339
+ if (typeof e.login !== "string") throw new Error(`links[${i}]: \`login\` must be a string`);
340
+ return {
341
+ github: e.github,
342
+ login: e.login,
343
+ member: e.member
344
+ };
345
+ });
346
+ for (const key of ["github", "member"]) {
347
+ const seen = /* @__PURE__ */ new Set();
348
+ for (const [i, link] of links.entries()) {
349
+ if (seen.has(link[key])) throw new Error(`links[${i}]: \`${key}\` ${link[key]} appears more than once`);
350
+ seen.add(link[key]);
351
+ }
352
+ }
353
+ return {
354
+ version: 1,
355
+ links
356
+ };
53
357
  }
358
+ /** Where the links file is: the layout's `links`, else `<org>/.github-private` and `notifications/<provider>-links.json`. */
359
+ function linksLocation(layout, org, provider) {
360
+ const repo = layout.links?.repo ?? (org ? `${org}/.github-private` : void 0);
361
+ if (!repo) throw new Error("no org to find the links file under — set `layout.links.repo` or `org` in holocron.config.ts");
362
+ return {
363
+ repo,
364
+ path: layout.links?.path ?? `notifications/${provider.toLowerCase()}-links.json`
365
+ };
366
+ }
367
+ // src/commands/notifications-sync-roles/plan.ts
54
368
  /**
55
- * Read the bootstrap token for a provider. Returns `null` for both
56
- * "not stored" and "keyring unavailable" — callers can treat them the
57
- * same way (fall through to env-var precedence).
369
+ * What it takes to make a role's holders equal a team, given who is linked to whom. Pure: it decides, the
370
+ * caller acts. A holder is removed only when a link says they are a person who left the team; a holder
371
+ * nobody has linked is reported, never removed, so an empty or missing links file cannot strip the role from
372
+ * everyone.
58
373
  */
59
- function getToken(provider) {
60
- try {
61
- return new Entry(SERVICE, provider).getPassword();
62
- } catch {
63
- return null;
374
+ function planRoleSync(input) {
375
+ const byGithub = new Map(input.links.map((l) => [l.github, l]));
376
+ const byMember = new Map(input.links.map((l) => [l.member, l]));
377
+ const onTeam = new Set(input.team.map((m) => m.id));
378
+ const holding = new Set(input.holders.map((h) => h.id));
379
+ const plan = {
380
+ add: [],
381
+ remove: [],
382
+ unlinked: [],
383
+ unknownHolders: [],
384
+ inSync: 0
385
+ };
386
+ for (const person of input.team) {
387
+ const link = byGithub.get(person.id);
388
+ if (!link) plan.unlinked.push(person);
389
+ else if (holding.has(link.member)) plan.inSync++;
390
+ else plan.add.push({
391
+ member: link.member,
392
+ login: person.login
393
+ });
394
+ }
395
+ for (const holder of input.holders) {
396
+ const link = byMember.get(holder.id);
397
+ if (!link) plan.unknownHolders.push({
398
+ member: holder.id,
399
+ ...holder.name ? { name: holder.name } : {}
400
+ });
401
+ else if (!onTeam.has(link.github)) plan.remove.push({
402
+ member: holder.id,
403
+ login: link.login
404
+ });
64
405
  }
406
+ return plan;
65
407
  }
66
408
  /**
67
- * Delete a stored token. Returns true when a token was removed, false
68
- * when there was nothing to delete or the keyring is unavailable.
69
- * Distinguishing the two cases isn't worth the surface area — the
70
- * command output makes the situation clear either way.
409
+ * The first role the layout declares for two different teams, or undefined. Names compare ignoring case, as
410
+ * the server does; the role would be synced against one team and then the other, so the last would win.
71
411
  */
72
- function deleteToken(provider) {
73
- try {
74
- return new Entry(SERVICE, provider).deletePassword();
75
- } catch {
76
- return false;
412
+ function roleTeamProblem(layout) {
413
+ const seen = /* @__PURE__ */ new Map();
414
+ for (const role of layout.roles ?? []) {
415
+ if (!role.team) continue;
416
+ const key = role.name.toLowerCase();
417
+ const earlier = seen.get(key);
418
+ if (earlier !== void 0 && earlier.toLowerCase() !== role.team.toLowerCase()) return `role \`${role.name}\` is declared for two teams (\`${earlier}\` and \`${role.team}\`); a role follows one team`;
419
+ seen.set(key, role.team);
77
420
  }
78
421
  }
422
+ // src/commands/notifications-sync-roles/sync-roles.ts
423
+ /** Reads the team and the role's holders and works out what has to change. */
424
+ async function planForRole(args) {
425
+ const [team, holders] = await Promise.all([args.source.teamMembers(args.team, args.org), args.notifications.roleMembers(args.role)]);
426
+ return planRoleSync({
427
+ team,
428
+ links: args.links.links,
429
+ holders
430
+ });
431
+ }
79
432
  /**
80
- * List provider slugs with a stored token in this service scope.
81
- * Uses the library's `findCredentials(service)` — supported on all
82
- * platforms the underlying credential store supports.
433
+ * Makes each role's holders equal its team, one role after another. This is the sync itself, with no setup in
434
+ * front of it: the caller has already picked the providers, read the links and checked the layout. `holocron
435
+ * sync roles` and Sentinel's role sync are two callers of it. A step that fails is recorded and the
436
+ * run goes on; nothing here throws for a provider error. Idempotent: a role that already matches changes nothing.
437
+ * Lines go to `input.print` when it is given, and nowhere otherwise.
83
438
  */
84
- function listStoredProviders() {
439
+ async function syncRoles(input) {
440
+ const print = input.print ?? (() => {});
441
+ const { notifications, source, links, dryRun, keep } = input;
442
+ const result = {
443
+ roles: [],
444
+ failures: [],
445
+ ok: 0,
446
+ skipped: 0
447
+ };
448
+ for (const role of input.roles) {
449
+ print(`\n${style.header(`${role.name} ← team ${role.team}`)}`);
450
+ const step = `role ${role.name}`;
451
+ let plan;
452
+ try {
453
+ plan = await planForRole({
454
+ notifications,
455
+ source,
456
+ role: role.name,
457
+ team: role.team,
458
+ ...input.org ? { org: input.org } : {},
459
+ links
460
+ });
461
+ } catch (err) {
462
+ const message = describeError(err);
463
+ print(` ${style.fail(`${step}: ${message}`)}`);
464
+ result.failures.push({
465
+ step,
466
+ message
467
+ });
468
+ continue;
469
+ }
470
+ const outcome = {
471
+ role: role.name,
472
+ team: role.team,
473
+ plan,
474
+ added: [],
475
+ removed: []
476
+ };
477
+ result.roles.push(outcome);
478
+ result.skipped += plan.inSync;
479
+ if (plan.inSync > 0) print(` ${style.skip(`${plan.inSync} already have it`)}`);
480
+ const act = async (verb, who) => {
481
+ const label = `${verb === "add" ? "gave" : "took"} ${role.name} ${verb === "add" ? "to" : "from"} ${who.login} (${who.member})`;
482
+ if (dryRun || verb === "remove" && keep) {
483
+ print(` ${style.skip(`would ${verb === "add" ? "give" : "take"} ${role.name} ${verb === "add" ? "to" : "from"} ${who.login} (${who.member})${keep && verb === "remove" ? " (kept: --keep)" : ""}`)}`);
484
+ result.skipped++;
485
+ return;
486
+ }
487
+ try {
488
+ if (verb === "add") await notifications.addRoleMember(role.name, who.member);
489
+ else await notifications.removeRoleMember(role.name, who.member);
490
+ (verb === "add" ? outcome.added : outcome.removed).push(who.member);
491
+ print(` ${style.success(label)}`);
492
+ result.ok++;
493
+ } catch (err) {
494
+ const message = describeError(err);
495
+ print(` ${style.fail(`${step}: ${verb} ${who.login}: ${message}`)}`);
496
+ result.failures.push({
497
+ step: `${step} ${verb} ${who.login}`,
498
+ message
499
+ });
500
+ }
501
+ };
502
+ for (const who of plan.add) await act("add", who);
503
+ for (const who of plan.remove) await act("remove", who);
504
+ for (const person of plan.unlinked) {
505
+ print(` ${style.skip(`${person.login} is on the team but has not linked their account`)}`);
506
+ result.skipped++;
507
+ }
508
+ for (const holder of plan.unknownHolders) {
509
+ print(` ${style.skip(`${holder.name ?? holder.member} holds ${role.name} but is not linked to anyone: left alone`)}`);
510
+ result.skipped++;
511
+ }
512
+ }
513
+ return result;
514
+ }
515
+ // src/commands/notifications-sync-roles/notifications-sync-roles.ts
516
+ /** What a source provider needs to be able to do to feed a role sync, or the reason it cannot. */
517
+ function sourceProblem(source) {
518
+ if (!source) return "no `source` provider is available to read the team and the links file";
519
+ if (!source.teamMembers) return `the \`${source.providerName}\` provider cannot list team members`;
520
+ if (!source.readFile) return `the \`${source.providerName}\` provider cannot read the links file`;
521
+ }
522
+ /** Reads the links file; a file that does not exist yet is an empty one, a damaged one throws. */
523
+ async function readLinks(source, layout, org, provider) {
524
+ const { repo, path } = linksLocation(layout, org, provider);
525
+ const file = await source.readFile(path, repo);
526
+ if (!file) return EMPTY_LINKS;
85
527
  try {
86
- return findCredentials(SERVICE).map((c) => c.account);
87
- } catch {
88
- return [];
528
+ return parseLinks(file.content);
529
+ } catch (err) {
530
+ throw new Error(`${repo}/${path}: ${errorMessage(err)}`, { cause: err });
89
531
  }
90
532
  }
91
- //#endregion
92
- //#region src/auth/auth-resolver.ts
93
- /** Wraps `createResolveToken` from `@theholocron/http` and injects the
94
- * system keyring so plugins stay at a one-liner call site. */
95
- function createResolveToken(config) {
96
- return createResolveToken$1({
97
- ...config,
98
- getKeyringToken: getToken
99
- });
533
+ // src/commands/project/plan-pull-request-status/plan-pull-request-status.ts
534
+ /**
535
+ * Decide the status an item's linked pull requests ask for (spec `tech-board-status-automation`, #2388). Pure: it reads
536
+ * one item and the template and touches nothing; status only, never priority or any other field.
537
+ *
538
+ * - an open linked pull request (a draft counts) puts the item in `active`;
539
+ * - an open one whose aggregate check is `success` puts it in `review`;
540
+ * - when the item is in `review` and no open pull request is green, a `failure` moves it back to `active`, while
541
+ * `pending` and `none` leave it, so a re-run after a push does not flicker the board;
542
+ * - no open pull request: no change (closed and merged ones are `planReconcile()`'s, through the closed issue).
543
+ *
544
+ * Left to `planReconcile()`, which runs first: a closed item, an item with an open blocker or in `blocked`, and an
545
+ * item with no status (reported there, not set). An item in `done` is left alone. Where the template has no status of
546
+ * the wanted category the rule comes back as `unresolved` and nothing is guessed; where a category has several statuses
547
+ * the first in template order is used. Applying the change and planning again gives no change.
548
+ */
549
+ function planPullRequestStatus(item, template) {
550
+ if (!item.open || item.status === void 0 || item.blockedBy.length > 0) return void 0;
551
+ const category = template.statuses.find((s) => s.name === item.status)?.category ?? item.category;
552
+ if (category === "blocked" || category === "done") return void 0;
553
+ const open = (item.pullRequests ?? []).filter((pr) => pr.state === "open");
554
+ if (open.length === 0) return void 0;
555
+ let want;
556
+ let reason;
557
+ if (open.some((pr) => pr.checks === "success")) {
558
+ if (category !== "review") [want, reason] = ["review", "checks-green"];
559
+ } else if (category === "review") {
560
+ if (open.some((pr) => pr.checks === "failure")) [want, reason] = ["active", "checks-failed"];
561
+ } else if (category !== "active") [want, reason] = ["active", "pull-request-open"];
562
+ if (want === void 0 || reason === void 0) return void 0;
563
+ const to = template.statuses.find((s) => s.category === want)?.name;
564
+ if (to === void 0) return {
565
+ kind: "unresolved",
566
+ unresolved: {
567
+ key: item.key,
568
+ title: item.title,
569
+ category: want,
570
+ reason
571
+ }
572
+ };
573
+ return {
574
+ kind: "change",
575
+ change: {
576
+ key: item.key,
577
+ title: item.title,
578
+ from: item.status,
579
+ to,
580
+ category: want,
581
+ reason
582
+ }
583
+ };
100
584
  }
585
+ // src/commands/project/plan-reconcile/plan-reconcile.ts
101
586
  /**
102
- * Build a strict, single-feature token resolver.
587
+ * Decide the status changes that keep a board true (spec `command-project`, "Keeping a board true"). Pure: it reads
588
+ * the items and the template and touches nothing. Status only, never priority or any other field.
589
+ *
590
+ * - closed or merged, not in a `done` status: set to `done` (whatever the blockers say);
591
+ * - open with no status: not changed, listed in `unset` (it needs a decision, not a rule; this holds even when it has a
592
+ * blocker);
593
+ * - open with an open blocker, not in a `blocked` status: set to `blocked`;
594
+ * - open, in a `blocked` status, with no open blocker: set to `planned` (the status it held before is unknown).
103
595
  *
104
- * Resolution chain: `--token flag → envName env var → keyring(keyringKey)`.
105
- * No broad-token fallback — if the feature-specific token is absent the
106
- * operation fails with a message naming the exact env var to set.
596
+ * Where a category has several statuses the first in template order is used; where it has none the item is listed in
597
+ * `unresolved` and nothing is guessed. An item's category is read from the template by its status name, falling back
598
+ * to the one the provider reports. Applying the changes and planning again gives no change.
107
599
  */
108
- function createFeatureResolver(config) {
109
- return function resolveFeatureToken(input = {}) {
110
- const env = makeEnv(input.env);
111
- const keyring = input.keyring ?? getToken;
112
- const token = input.cliToken || env.get(config.envName) || keyring(config.keyringKey);
113
- if (!token) throw new AuthError(`no GitHub token found for this operation. Pass --token <PAT>, set ${config.envName}, or run: holocron auth set ${config.keyringKey} <PAT>`);
114
- return token;
600
+ function planReconcile(items, template) {
601
+ const target = (category) => template.statuses.find((s) => s.category === category)?.name;
602
+ const plan = {
603
+ changes: [],
604
+ unset: [],
605
+ unresolved: []
606
+ };
607
+ for (const item of items) {
608
+ const category = item.status === void 0 ? void 0 : template.statuses.find((s) => s.name === item.status)?.category ?? item.category;
609
+ let want;
610
+ let reason;
611
+ if (!item.open) {
612
+ if (category !== "done") [want, reason] = ["done", "closed"];
613
+ } else if (item.status === void 0) {
614
+ plan.unset.push(item);
615
+ continue;
616
+ } else if (item.blockedBy.length > 0) {
617
+ if (category !== "blocked") [want, reason] = ["blocked", "blocked"];
618
+ } else if (category === "blocked") [want, reason] = ["planned", "unblocked"];
619
+ if (want === void 0 || reason === void 0) continue;
620
+ const to = target(want);
621
+ if (to === void 0) {
622
+ plan.unresolved.push({
623
+ key: item.key,
624
+ title: item.title,
625
+ category: want,
626
+ reason
627
+ });
628
+ continue;
629
+ }
630
+ plan.changes.push({
631
+ key: item.key,
632
+ title: item.title,
633
+ ...item.status !== void 0 ? { from: item.status } : {},
634
+ to,
635
+ category: want,
636
+ reason
637
+ });
638
+ }
639
+ return plan;
640
+ }
641
+ // src/commands/project/project-options/project-options.ts
642
+ /** Where a repo's own template files live unless the `templates` option says otherwise. */
643
+ const DEFAULT_TEMPLATES_DIR = ".holocron/projects";
644
+ /**
645
+ * Read the options of `providers.projects`: `org` (the owner, defaulting to `fallbackOwner`, the config's org), `boards`
646
+ * (a list of `{ template, name }`, nothing else about a board is written in the config) and `templates` (the directory
647
+ * of template files). Every problem is listed at once, and two boards with the same name are one.
648
+ */
649
+ function resolveProjectOptions(options, fallbackOwner) {
650
+ const problems = [];
651
+ const org = options.org;
652
+ if (org !== void 0 && (typeof org !== "string" || org.trim() === "")) problems.push("org must be text");
653
+ const owner = typeof org === "string" && org.trim() !== "" ? org : fallbackOwner;
654
+ const dir = options.templates;
655
+ if (dir !== void 0 && (typeof dir !== "string" || dir.trim() === "")) problems.push("templates must be the path of a directory");
656
+ const boards = [];
657
+ if (options.boards !== void 0) {
658
+ if (!Array.isArray(options.boards)) problems.push("boards must be a list of { template, name }");
659
+ else {
660
+ const seen = /* @__PURE__ */ new Set();
661
+ options.boards.forEach((entry, i) => {
662
+ const where = `boards[${i}]`;
663
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
664
+ problems.push(`${where} must be { template, name }`);
665
+ return;
666
+ }
667
+ const { template, name } = entry;
668
+ if (typeof template !== "string" || template.trim() === "") problems.push(`${where} needs a template`);
669
+ if (typeof name !== "string" || name.trim() === "") problems.push(`${where} needs a name`);
670
+ if (typeof template !== "string" || typeof name !== "string" || !template.trim() || !name.trim()) return;
671
+ if (seen.has(name)) problems.push(`${where}: the board name "${name}" is used twice`);
672
+ seen.add(name);
673
+ boards.push({
674
+ template,
675
+ name
676
+ });
677
+ });
678
+ }
679
+ }
680
+ if (problems.length > 0) return {
681
+ ok: false,
682
+ problems
683
+ };
684
+ return {
685
+ ok: true,
686
+ options: {
687
+ owner,
688
+ boards,
689
+ templatesDir: typeof dir === "string" ? dir : DEFAULT_TEMPLATES_DIR
690
+ }
115
691
  };
116
692
  }
117
- //#endregion
118
- //#region src/commands/setup/derived-properties.ts
693
+ // src/commands/project/templates/board-issue-views/board-issue-views.ts
694
+ /**
695
+ * The issue-list views of `repo.views` (spec `tech-issue-views`, #2743) that mean the same on a board, written in a
696
+ * board's filter syntax. Every qualifier is one GitHub documents for a project view (`is:`, `type:`, `assignee:@me`,
697
+ * `no:<field>`, `field:value`); `no:parent-issue` reads "Parent issue" as a field, which the docs imply but do not
698
+ * list. Left out on purpose: Backlog (a template already has a view of that name), Blocking (a board has no qualifier
699
+ * for it) and anything that needs `linked:pr` (not documented for a board). Blocked, Ready to start and In flight use
700
+ * the status, which is how a board says the same thing. Both built-in templates use the same list, after their own views.
701
+ */
702
+ const BOARD_ISSUE_VIEWS = [
703
+ {
704
+ name: "Blocked",
705
+ layout: "table",
706
+ filter: "is:open status:Blocked"
707
+ },
708
+ {
709
+ name: "Epics",
710
+ layout: "table",
711
+ filter: "is:open type:Epic"
712
+ },
713
+ {
714
+ name: "No Epic",
715
+ layout: "table",
716
+ filter: "is:open is:issue no:parent-issue -type:Epic"
717
+ },
718
+ {
719
+ name: "Ready to start",
720
+ layout: "table",
721
+ filter: "is:open status:Todo -type:Epic"
722
+ },
723
+ {
724
+ name: "In flight",
725
+ layout: "table",
726
+ filter: "is:open status:\"In Progress\""
727
+ },
728
+ {
729
+ name: "Mine",
730
+ layout: "table",
731
+ filter: "is:open assignee:@me"
732
+ },
733
+ {
734
+ name: "Spikes",
735
+ layout: "table",
736
+ filter: "is:open type:Spike"
737
+ }
738
+ ];
739
+ // src/commands/project/templates/builtin-templates/builtin-templates.ts
740
+ /** The templates that ship in `@theholocron/cli`, by name. A repo's own template with the same name replaces one. */
741
+ const BUILTIN_TEMPLATES = {
742
+ roadmap: {
743
+ name: "roadmap",
744
+ statuses: [
745
+ {
746
+ name: "Someday",
747
+ category: "backlog",
748
+ color: "GRAY",
749
+ description: "Idea or future consideration, not yet planned"
750
+ },
751
+ {
752
+ name: "Todo",
753
+ category: "planned",
754
+ color: "BLUE",
755
+ description: "Planned and ready to be worked on"
756
+ },
757
+ {
758
+ name: "In Progress",
759
+ category: "active",
760
+ color: "YELLOW",
761
+ description: "Currently being worked on"
762
+ },
763
+ {
764
+ name: "In Review",
765
+ category: "review",
766
+ color: "ORANGE",
767
+ description: "Pull request is green and waiting on review"
768
+ },
769
+ {
770
+ name: "Blocked",
771
+ category: "blocked",
772
+ color: "RED",
773
+ description: "Waiting on another issue or an outside change"
774
+ },
775
+ {
776
+ name: "Done",
777
+ category: "done",
778
+ color: "GREEN",
779
+ description: "Completed"
780
+ }
781
+ ],
782
+ fields: [{
783
+ name: "Priority",
784
+ type: "single_select",
785
+ options: [
786
+ "1 · Now",
787
+ "2 · Next",
788
+ "3 · Process"
789
+ ]
790
+ }],
791
+ views: [
792
+ {
793
+ name: "Active",
794
+ layout: "board",
795
+ filter: "-status:Someday -status:Done",
796
+ default: true
797
+ },
798
+ {
799
+ name: "Backlog",
800
+ layout: "board",
801
+ filter: "status:Someday"
802
+ },
803
+ {
804
+ name: "Done",
805
+ layout: "table",
806
+ filter: "status:Done"
807
+ },
808
+ ...BOARD_ISSUE_VIEWS
809
+ ],
810
+ rules: ["Auto-add sub-issues to project"]
811
+ },
812
+ sprint: {
813
+ name: "sprint",
814
+ statuses: [
815
+ {
816
+ name: "Todo",
817
+ category: "planned",
818
+ color: "BLUE"
819
+ },
820
+ {
821
+ name: "In Progress",
822
+ category: "active",
823
+ color: "YELLOW"
824
+ },
825
+ {
826
+ name: "In Review",
827
+ category: "review",
828
+ color: "ORANGE"
829
+ },
830
+ {
831
+ name: "Blocked",
832
+ category: "blocked",
833
+ color: "RED"
834
+ },
835
+ {
836
+ name: "Done",
837
+ category: "done",
838
+ color: "GREEN"
839
+ }
840
+ ],
841
+ fields: [{
842
+ name: "Sprint",
843
+ type: "text"
844
+ }],
845
+ views: [
846
+ {
847
+ name: "Active",
848
+ layout: "table",
849
+ filter: "-status:Done",
850
+ default: true
851
+ },
852
+ {
853
+ name: "Done",
854
+ layout: "table",
855
+ filter: "status:Done"
856
+ },
857
+ ...BOARD_ISSUE_VIEWS
858
+ ]
859
+ }
860
+ };
861
+ // src/commands/setup/derived-properties/derived-properties.ts
119
862
  /**
120
863
  * Repo archetype, in priority order:
121
864
  * 1. `*-template` repo name → `template` (independent of package shape).
@@ -155,6 +898,7 @@ function deriveProfile(input) {
155
898
  if (pkg?.private) return "app";
156
899
  return "library";
157
900
  }
901
+ /** The framework and build-tool names `deriveStack()` can detect, in the order it lists them; `StackName` is derived from it. */
158
902
  const KNOWN_STACK_DEPS = [
159
903
  "next",
160
904
  "vite",
@@ -194,6 +938,7 @@ function deriveCapabilities(providers) {
194
938
  * a Phase B (GitHub App) refinement once it can post *why* on a check run.
195
939
  */
196
940
  const REQUIRED_BASELINE = ["source", "ci"];
941
+ /** Whether a repo's capabilities include the required baseline (`source` and `ci`); `non-compliant` means drift. */
197
942
  function deriveCompliance(capabilities) {
198
943
  return REQUIRED_BASELINE.every((key) => capabilities.includes(key)) ? "compliant" : "non-compliant";
199
944
  }
@@ -215,410 +960,683 @@ function missingCapabilities(capabilities) {
215
960
  */
216
961
  async function readWorkspacePackageJsons(repoRoot, workspacePackages) {
217
962
  const results = [];
218
- for (const { slug, dir = "packages" } of workspacePackages) try {
219
- const raw = await readFile(join(repoRoot, dir, slug, "package.json"), "utf8");
220
- results.push(JSON.parse(raw));
221
- } catch {}
963
+ for (const { slug, dir = "packages", path } of workspacePackages) {
964
+ const pkg = await readPackageJson(join(repoRoot, path ?? join(dir, slug)));
965
+ if (pkg) results.push(pkg);
966
+ }
222
967
  return results;
223
968
  }
224
- //#endregion
225
- //#region src/commit-lint/lint-message.ts
226
- /**
227
- * Lints one commit message string against an already-loaded commitlint
228
- * config. The genuinely environment-independent half of commit-message
229
- * linting (holocron#789) — *obtaining* a `QualifiedConfig` differs by
230
- * caller (Sentinel isolates itself from any ambient config since it runs
231
- * standalone, away from a real repo checkout; `lintCommitMsgFile` below
232
- * just lets cosmiconfig discover the invoking repo's own
233
- * `commitlint.config.*`, matching `commitlint --edit`'s own contract) —
234
- * but linting one message against a loaded config is identical either way.
235
- *
236
- * Real `@commitlint/lint` — the same programmatic API `@commitlint/cli`
237
- * itself uses internally — never a reimplementation of commitlint's rules.
238
- */
239
- /** `parserPreset.parserOpts`, if the loaded config sets one — same lookup `@commitlint/cli`'s own `selectParserOpts()` does. */
240
- function selectParserOpts(parserPreset) {
241
- return parserPreset?.parserOpts;
242
- }
243
- async function lintCommitMessage(message, loaded) {
244
- const opts = {
245
- /* istanbul ignore next -- see comment above */
246
- parserOpts: selectParserOpts(loaded.parserPreset) ?? {},
247
- plugins: loaded.plugins,
248
- /* istanbul ignore next -- see comment above */
249
- ignores: loaded.ignores ?? [],
250
- defaultIgnores: loaded.defaultIgnores !== false
251
- };
252
- const outcome = await lint(message, loaded.rules, opts);
253
- if (outcome.valid) return [];
254
- return outcome.errors.map((error) => ({
255
- rule: error.name,
256
- message: error.message
257
- }));
258
- }
259
- //#endregion
260
- //#region src/commit-lint/lint-commit-msg-file.ts
261
- /**
262
- * `holocron lint commit-msg <file>` — a real programmatic replacement for
263
- * shelling out to `commitlint --edit "$1"` from `.husky/commit-msg`
264
- * (holocron#789). Matches that CLI's own contract exactly: `file` is a
265
- * path to the commit message being written (the arg git's `commit-msg`
266
- * hook passes as `$1`), no `--config` override needed — `@commitlint/load`
267
- * runs from `cwd` with no seed, so cosmiconfig's own normal upward search
268
- * discovers the invoking repo's real `commitlint.config.*` file, exactly
269
- * as `commitlint --edit` (no `--config` flag) already does today. Unlike
270
- * Sentinel's `loadIsolatedConfig()`, no isolation is needed here — this
271
- * runs inside a real repo checkout with a real `node_modules`, not
272
- * standalone on a server.
273
- */
274
- async function lintCommitMsgFile(filePath, cwd = process.cwd()) {
275
- const violations = await lintCommitMessage(await readFile(filePath, "utf8"), await load({}, { cwd }));
276
- return {
277
- valid: violations.length === 0,
278
- violations
279
- };
969
+ // src/commands/setup/labels.ts
970
+ /**
971
+ * The labels every repository gets from `setup`, with their GitHub colours (hex, no `#`) and descriptions. A
972
+ * plugin that makes labels of its own, such as Linear's setup, takes the colour of the one with the same name.
973
+ */
974
+ const CANONICAL_LABELS = [
975
+ {
976
+ name: "bug",
977
+ color: "d73a4a",
978
+ description: "Something isn't working"
979
+ },
980
+ {
981
+ name: "chore",
982
+ color: "ededed",
983
+ description: "Maintenance, no user-facing change"
984
+ },
985
+ {
986
+ name: "ci",
987
+ color: "0075ca",
988
+ description: "CI/CD pipeline changes"
989
+ },
990
+ {
991
+ name: "dependencies",
992
+ color: "0366d6",
993
+ description: "Dependency update"
994
+ },
995
+ {
996
+ name: "documentation",
997
+ color: "0075ca",
998
+ description: "Documentation only"
999
+ },
1000
+ {
1001
+ name: "duplicate",
1002
+ color: "cfd3d7",
1003
+ description: "Already reported"
1004
+ },
1005
+ {
1006
+ name: "enhancement",
1007
+ color: "a2eeef",
1008
+ description: "New feature or request"
1009
+ },
1010
+ {
1011
+ name: "good first issue",
1012
+ color: "7057ff",
1013
+ description: "Good for newcomers"
1014
+ },
1015
+ {
1016
+ name: "help wanted",
1017
+ color: "008672",
1018
+ description: "Extra attention needed"
1019
+ },
1020
+ {
1021
+ name: "invalid",
1022
+ color: "e4e669",
1023
+ description: "Doesn't seem right"
1024
+ },
1025
+ {
1026
+ name: "performance",
1027
+ color: "fbca04",
1028
+ description: "Performance improvement"
1029
+ },
1030
+ {
1031
+ name: "question",
1032
+ color: "d876e3",
1033
+ description: "Further information requested"
1034
+ },
1035
+ {
1036
+ name: "refactor",
1037
+ color: "cfd3d7",
1038
+ description: "Code restructuring"
1039
+ },
1040
+ {
1041
+ name: "released",
1042
+ color: "ededed",
1043
+ description: "Included in a release"
1044
+ },
1045
+ {
1046
+ name: "test",
1047
+ color: "bfd4f2",
1048
+ description: "Test-related changes"
1049
+ },
1050
+ {
1051
+ name: "triage",
1052
+ color: "e4e669",
1053
+ description: "Needs investigation"
1054
+ },
1055
+ {
1056
+ name: "wontfix",
1057
+ color: "ffffff",
1058
+ description: "Won't be addressed"
1059
+ }
1060
+ ];
1061
+ // src/commands/setup/branch-protection.ts
1062
+ /** The name of the ruleset `holocron setup` makes for the default branch. */
1063
+ const RULESET_NAME = "holocron-default-branch";
1064
+ // src/commands/declared-required-checks/declared-required-checks.ts
1065
+ /** `repo.requiredChecks` de-duplicated, whole (nothing is added to it), or `undefined` when `setup` derives the list. */
1066
+ function declaredRequiredChecks(repo) {
1067
+ const declared = repo?.requiredChecks;
1068
+ return declared === void 0 ? void 0 : [...new Set(declared)];
280
1069
  }
281
- //#endregion
282
- //#region src/config/config.ts
283
- var ConfigError = class extends Error {
284
- name = "ConfigError";
285
- };
286
- const PLUGIN_PREFIX = "@theholocron/holocron-plugin-";
287
- const COMMUNITY_PREFIX = "holocron-plugin-";
288
- /**
289
- * Resolve `"github"` → `"@theholocron/holocron-plugin-github"`.
290
- * Fully-qualified names (scoped or not) are honored verbatim, which
291
- * is how third-party plugins published outside the org work.
292
- */
293
- function resolvePluginPackage(provider) {
294
- if (!provider) throw new ConfigError("provider name is empty");
295
- if (provider.startsWith("@")) return provider;
296
- if (provider.startsWith(COMMUNITY_PREFIX)) return provider;
297
- if (provider.includes("/")) return provider;
298
- return PLUGIN_PREFIX + provider;
299
- }
300
- /** A bare `[provider, options]` tuple, with both elements present? */
301
- function isOptionsTuple(value) {
302
- if (!Array.isArray(value)) return false;
303
- if (value.length !== 2) return false;
304
- if (typeof value[0] !== "string") return false;
305
- const opt = value[1];
306
- return typeof opt === "object" && opt !== null && !Array.isArray(opt);
307
- }
308
- function normalizeEntry(entry) {
309
- if (typeof entry === "string") return {
310
- provider: entry,
311
- packageName: resolvePluginPackage(entry),
312
- options: {}
313
- };
314
- const [provider, options] = entry;
1070
+ // src/required-checks/config-required-contexts/config-required-contexts.ts
1071
+ /** A config's required contexts: `repo.requiredChecks` when declared, else what `setup` writes to the ruleset. */
1072
+ function configRequiredContexts(config) {
1073
+ const declared = declaredRequiredChecks(config.repo);
1074
+ if (declared !== void 0) return declared;
1075
+ const tasks = { tasks: config.tasks };
1076
+ if (config.extraRequiredChecks) tasks.extraRequiredChecks = config.extraRequiredChecks;
1077
+ if (config.ci) tasks.ci = config.ci;
1078
+ return requiredChecks(tasks, false);
1079
+ }
1080
+ // src/required-checks/required-from-contexts/required-from-contexts.ts
1081
+ /** What GitHub puts between a caller job's name and the called job's name in a check run's name. */
1082
+ const SEPARATOR = " / ";
1083
+ /** Contexts to `{ expected, statuses }`: the part before ` / ` is a check id, a context without one is a status. */
1084
+ function requiredFromContexts(contexts) {
1085
+ const expected = /* @__PURE__ */ new Set();
1086
+ const statuses = /* @__PURE__ */ new Set();
1087
+ for (const context of contexts) {
1088
+ const at = context.indexOf(SEPARATOR);
1089
+ if (at === -1) statuses.add(context);
1090
+ else expected.add(context.slice(0, at));
1091
+ }
315
1092
  return {
316
- provider,
317
- packageName: resolvePluginPackage(provider),
318
- options
1093
+ expected: [...expected],
1094
+ statuses: [...statuses]
319
1095
  };
320
1096
  }
321
- function resolveEntry(key, raw) {
322
- const cardinality = CARDINALITY[key];
323
- if (typeof raw === "string") {
324
- if (cardinality === "many") throw new ConfigError(`\`${key}\` accepts multiple providers; wrap a single one in an array: ["${raw}"]`);
325
- return {
326
- cardinality: "single",
327
- tuple: normalizeEntry(raw)
328
- };
329
- }
330
- if (!Array.isArray(raw)) throw new ConfigError(`\`${key}\` entry must be a string or array, got ${typeof raw}`);
331
- if (isOptionsTuple(raw)) {
332
- if (cardinality === "many") return {
333
- cardinality: "many",
334
- tuples: [normalizeEntry(raw)]
335
- };
1097
+ // src/area-labels/area-for-scope/area-for-scope.ts
1098
+ /**
1099
+ * The area a title scope means, by `repo.labels.scopes` (spec `tech-github-area-labels`): `sentinel` gives the area it is
1100
+ * mapped to. The scope is matched without regard to case; a scope the map does not name, or a repo with no map, gives
1101
+ * `undefined`. It is the area's name, not its label: `areaLabelsForTitle()` adds the prefix.
1102
+ */
1103
+ function areaForScope(scope, scopes) {
1104
+ const wanted = scope.trim().toLowerCase();
1105
+ for (const [name, area] of Object.entries(scopes ?? {})) if (name.toLowerCase() === wanted) return area;
1106
+ }
1107
+ // src/area-labels/area-prefix/area-prefix.ts
1108
+ /** The prefix of an area label (spec `tech-github-area-labels`): `area:cli`. */
1109
+ const AREA_PREFIX = "area:";
1110
+ // src/area-labels/area-label-defs/area-label-defs.ts
1111
+ /** The colour of every area label: one family, one colour (spec `tech-github-area-labels`). */
1112
+ const AREA_LABEL_COLOR = "c5def5";
1113
+ /** GitHub refuses a label description longer than this. */
1114
+ const MAX_DESCRIPTION = 100;
1115
+ /**
1116
+ * The labels `holocron setup` makes for the areas a repo declares: `area:<name>`, the one family colour and the
1117
+ * description `Changes under <paths>` from the area's own (not excluded) patterns, cut to GitHub's 100 characters. They
1118
+ * are never part of `CANONICAL_LABELS`: an area names this repo's folders, so another repo has none of them.
1119
+ */
1120
+ function areaLabelDefs(areas) {
1121
+ return Object.entries(areas ?? {}).map(([name, patterns]) => {
1122
+ const text = `Changes under ${patterns.filter((p) => !p.startsWith("!")).join(", ")}`;
1123
+ const description = text.length > MAX_DESCRIPTION ? `${text.slice(0, 99)}…` : text;
336
1124
  return {
337
- cardinality: "single",
338
- tuple: normalizeEntry(raw)
1125
+ name: `${AREA_PREFIX}${name}`,
1126
+ color: AREA_LABEL_COLOR,
1127
+ description
339
1128
  };
340
- }
341
- if (cardinality === "single") throw new ConfigError(`\`${key}\` accepts exactly one provider; got a multi-provider list with ${raw.length} entries`);
342
- return {
343
- cardinality: "many",
344
- tuples: raw.map((entry, idx) => {
345
- if (typeof entry === "string") return normalizeEntry(entry);
346
- if (isOptionsTuple(entry)) return normalizeEntry(entry);
347
- throw new ConfigError(`\`${key}[${idx}]\` must be a provider string or [provider, options] tuple`);
348
- })
349
- };
1129
+ });
1130
+ }
1131
+ // src/area-labels/path-matches/path-matches.ts
1132
+ /** `value` without the slashes at its end. A scan from the end, not a pattern, so a long run of slashes costs one pass. */
1133
+ function withoutTrailingSlashes(value) {
1134
+ let end = value.length;
1135
+ while (end > 0 && value[end - 1] === "/") end -= 1;
1136
+ return value.slice(0, end);
350
1137
  }
351
- function resolveConfig(raw) {
352
- if (!raw.name) throw new ConfigError("`name` is required");
353
- if (!raw.providers || typeof raw.providers !== "object") throw new ConfigError("`providers` block is required");
354
- const providers = {};
355
- for (const [key, entry] of Object.entries(raw.providers)) {
356
- if (entry === void 0) continue;
357
- providers[key] = resolveEntry(key, entry);
1138
+ /** Turns one glob into the expression a whole path must match: `**` crosses folders, `*` and `?` stay in one. */
1139
+ function globToRegExp(glob) {
1140
+ let out = "";
1141
+ for (let i = 0; i < glob.length; i++) {
1142
+ const c = glob.charAt(i);
1143
+ if (c === "*") {
1144
+ if (glob.charAt(i + 1) === "*") {
1145
+ const slash = glob.charAt(i + 2) === "/";
1146
+ out += slash ? "(?:.*/)?" : ".*";
1147
+ i += slash ? 2 : 1;
1148
+ } else out += "[^/]*";
1149
+ } else if (c === "?") out += "[^/]";
1150
+ else out += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
358
1151
  }
359
- for (const required of REQUIRED_CAPABILITIES) if (!providers[required]) throw new ConfigError(`required capability \`${required}\` is missing from providers`);
360
- let docs;
361
- if (raw.docs !== void 0) {
362
- if (!raw.docs.build) throw new ConfigError("`docs.build` is required when `docs` is set");
363
- docs = raw.docs;
1152
+ return new RegExp(`^${out}$`);
1153
+ }
1154
+ /**
1155
+ * Whether a repository path (forward slashes, from the root) matches one pattern of `repo.labels.areas`. A pattern with
1156
+ * a `*` or `?` is a glob (`cli/**`, `docs/**` then `/*.md`); one without is a file (`turbo.json`) or a folder and
1157
+ * everything under it (`.holocron`, `.holocron/`).
1158
+ */
1159
+ function pathMatches(path, pattern) {
1160
+ const clean = path.replace(/^\.?\//, "");
1161
+ if (/[*?]/.test(pattern)) return globToRegExp(pattern.replace(/^\.?\//, "")).test(clean);
1162
+ const plain = withoutTrailingSlashes(pattern.replace(/^\.?\//, ""));
1163
+ return clean === plain || clean.startsWith(`${plain}/`);
1164
+ }
1165
+ // src/area-labels/area-labels-for-files/area-labels-for-files.ts
1166
+ /**
1167
+ * The `area:<name>` labels a set of changed paths earns, in the order the areas are declared (spec
1168
+ * `tech-github-area-labels`). An area's patterns are the ones in `repo.labels.areas`; one starting with `!` takes a path
1169
+ * out of the area (`docs/**` with `!docs/wiki/**`), so a path is in an area when some pattern includes it and none
1170
+ * excludes it. A path in no area earns nothing, which is right, not a failure. This is the one mapping from changed
1171
+ * folders to labels in the CLI; Sentinel's `planAreaLabels()` is meant to agree with it.
1172
+ */
1173
+ function areaLabelsForFiles(files, areas) {
1174
+ const labels = [];
1175
+ for (const [name, patterns] of Object.entries(areas ?? {})) {
1176
+ const include = patterns.filter((p) => !p.startsWith("!"));
1177
+ const exclude = patterns.filter((p) => p.startsWith("!")).map((p) => p.slice(1));
1178
+ if (files.some((file) => include.some((p) => pathMatches(file, p)) && !exclude.some((p) => pathMatches(file, p)))) labels.push(`${AREA_PREFIX}${name}`);
364
1179
  }
365
- const homepage = raw.homepage ?? (docs?.domain ? `https://${docs.domain}/` : void 0);
366
- return {
367
- name: raw.name,
368
- description: raw.description,
369
- homepage,
370
- org: raw.org,
371
- domain: raw.domain,
372
- repo: raw.repo,
373
- tasks: raw.tasks,
374
- syncScripts: raw.syncScripts,
375
- holocronScript: raw.holocronScript,
376
- extraRequiredChecks: raw.extraRequiredChecks,
377
- hooks: raw.hooks,
378
- providers,
379
- apps: raw.apps ?? [],
380
- doctor: raw.doctor ?? {},
381
- agent: raw.agent,
382
- skills: raw.skills,
383
- docs,
384
- env: raw.env,
385
- log: raw.log,
386
- telemetry: raw.telemetry,
387
- eslint: raw.eslint
388
- };
1180
+ return labels;
389
1181
  }
390
- //#endregion
391
- //#region src/config/compose.ts
392
- function taskName(e) {
393
- return typeof e === "string" ? e : e.name;
1182
+ // src/area-labels/title-scopes/title-scopes.ts
1183
+ const TITLE = /^\s*[A-Za-z]+(?:\(([^)]*)\))?!?:/;
1184
+ /**
1185
+ * The scopes of a Conventional Commit title: `feat(sentinel): ...` gives `["sentinel"]`, `fix(cli, docs)!: ...` gives
1186
+ * `["cli", "docs"]`. A title with no scope, or that is not in the `type(scope): subject` form, gives none.
1187
+ */
1188
+ function titleScopes(title) {
1189
+ const scope = TITLE.exec(title)?.[1];
1190
+ if (scope === void 0) return [];
1191
+ return scope.split(",").map((s) => s.trim()).filter((s) => s !== "");
394
1192
  }
1193
+ // src/area-labels/area-labels-for-title/area-labels-for-title.ts
395
1194
  /**
396
- * Merge any number of capability fragments into a single preset object that
397
- * spreads directly into `defineConfig()`.
398
- *
399
- * - Accepts individual capabilities or nested arrays (for bundle presets).
400
- * - Deduplicates by `id` — when the same ID appears more than once, the last
401
- * occurrence wins. This lets callers override bundle defaults by listing an
402
- * explicit capability after the bundle.
403
- * - Validates all `requires` at call time and throws `ConfigError` if any are
404
- * unmet, listing every missing dependency in a single message.
405
- *
406
- * @example
407
- * // docs-only site — no typecheck
408
- * const preset = compose(node(), docs());
409
- *
410
- * // library with docs
411
- * const preset = compose(node(), typecheck(), docs());
412
- *
413
- * // nextjs() is a bundle that returns Capability[]
414
- * const preset = compose(node(), nextjs());
415
- */
416
- function compose(...args) {
417
- const flat = args.flat();
418
- const byId = /* @__PURE__ */ new Map();
419
- for (const cap of flat) byId.set(cap.id, cap);
420
- const caps = [...byId.values()];
421
- const available = new Set(caps.map((c) => c.id));
422
- const errors = [];
423
- for (const cap of caps) for (const req of cap.requires ?? []) if (!available.has(req)) errors.push(`"${cap.id}" requires "${req}"`);
424
- if (errors.length > 0) throw new ConfigError(`compose(): unmet dependencies — ${errors.join(", ")}`);
425
- const taskMap = /* @__PURE__ */ new Map();
426
- for (const cap of caps) for (const entry of cap.tasks ?? []) taskMap.set(taskName(entry), entry);
427
- let providers = {};
428
- for (const cap of caps) if (cap.providers) providers = {
429
- ...providers,
430
- ...cap.providers
431
- };
432
- const checksSeen = /* @__PURE__ */ new Set();
433
- const extraRequiredChecks = [];
434
- for (const cap of caps) for (const check of cap.extraRequiredChecks ?? []) if (!checksSeen.has(check)) {
435
- checksSeen.add(check);
436
- extraRequiredChecks.push(check);
1195
+ * The `area:<name>` labels the scopes of an issue's title earn, through `repo.labels.scopes` (spec
1196
+ * `tech-github-area-labels`): `feat(sentinel): ...` gives `["area:sentinel"]`. An issue has no changed files, so this is
1197
+ * its only source of an area. A title with no scope, or a scope the map does not name, earns nothing; the same area
1198
+ * from two scopes is given once, in the order of the title.
1199
+ */
1200
+ function areaLabelsForTitle(title, scopes) {
1201
+ const labels = [];
1202
+ for (const scope of titleScopes(title)) {
1203
+ const area = areaForScope(scope, scopes);
1204
+ if (area === void 0) continue;
1205
+ const label = `${AREA_PREFIX}${area}`;
1206
+ if (!labels.includes(label)) labels.push(label);
437
1207
  }
438
- let repo = {};
439
- for (const cap of caps) {
440
- if (!cap.repo) continue;
441
- const { properties, topics, teams, ...scalars } = cap.repo;
442
- repo = {
443
- ...repo,
444
- ...scalars
445
- };
446
- if (properties) repo.properties = {
447
- ...repo.properties,
448
- ...properties
449
- };
450
- if (topics) {
451
- const merged = /* @__PURE__ */ new Set([...repo.topics ?? [], ...topics]);
452
- repo.topics = [...merged];
453
- }
454
- if (teams) {
455
- const teamMap = new Map((repo.teams ?? []).map((t) => [typeof t === "string" ? t : t.slug, t]));
456
- for (const t of teams) teamMap.set(typeof t === "string" ? t : t.slug, t);
457
- repo.teams = [...teamMap.values()];
1208
+ return labels;
1209
+ }
1210
+ // src/pull-request-post/parse-pr-key/parse-pr-key.ts
1211
+ /**
1212
+ * The repository and number a post's key names, the inverse of `prKey()`: `owner/repo#123` gives
1213
+ * `{ repo: "owner/repo", number: 123 }`; any other text gives `undefined`.
1214
+ */
1215
+ function parsePrKey(key) {
1216
+ const match = /^([^/#\s]+\/[^/#\s]+)#(\d+)$/.exec(key ?? "");
1217
+ return match ? {
1218
+ repo: match[1],
1219
+ number: Number(match[2])
1220
+ } : void 0;
1221
+ }
1222
+ // src/pull-request-post/pr-key/pr-key.ts
1223
+ /** The key a pull request's post is found by: `owner/repo#123`. */
1224
+ function prKey(repo, number) {
1225
+ return `${repo}#${number}`;
1226
+ }
1227
+ // src/pull-request-post/pull-request-tag/pull-request-tag.ts
1228
+ /** The tag of a pull request: the first that applies of merged, closed, draft, conflicts, failing, changes requested, ready, in review. */
1229
+ function pullRequestTag(state) {
1230
+ if (state.merged) return "merged";
1231
+ if (state.closed) return "closed";
1232
+ if (state.draft) return "draft";
1233
+ if (state.mergeable === "conflicting") return "conflicts";
1234
+ if (state.ci === "failing") return "failing";
1235
+ if (state.review === "changes_requested") return "changes requested";
1236
+ if (state.review === "approved" && state.ci === "passing") return "ready";
1237
+ return "in review";
1238
+ }
1239
+ // src/pull-request-post/age-text/age-text.ts
1240
+ const MINUTE = 6e4;
1241
+ const HOUR = 60 * MINUTE;
1242
+ const DAY = 24 * HOUR;
1243
+ /** How long ago something happened, in the largest whole unit: `just now`, `5 minutes ago`, `1 hour ago`, `3 days ago`. */
1244
+ function ageText(createdAt, now) {
1245
+ const elapsed = Math.max(0, now.getTime() - new Date(createdAt).getTime());
1246
+ if (elapsed < MINUTE) return "just now";
1247
+ const [value, unit] = elapsed >= DAY ? [Math.floor(elapsed / DAY), "day"] : elapsed >= HOUR ? [Math.floor(elapsed / HOUR), "hour"] : [Math.floor(elapsed / MINUTE), "minute"];
1248
+ return `${value} ${unit}${value === 1 ? "" : "s"} ago`;
1249
+ }
1250
+ /** What Sourcery writes between its start and end markers, e.g. the reviewer's guide. */
1251
+ const SOURCERY_BLOCK = /<!--\s*Generated by sourcery-ai[^>]*?start\s+(\w+)\s*-->[\s\S]*?<!--\s*Generated by sourcery-ai[^>]*?end\s+\1\s*-->/gi;
1252
+ /** Sourcery's auto-generated summary starts at this marker and runs to the end of the description. */
1253
+ const SOURCERY_SUMMARY = /<!--\s*This is an auto-generated description by sourcery-ai\.?\s*-->[\s\S]*$/i;
1254
+ /** A command someone typed to Sourcery (`@sourcery-ai summary`). */
1255
+ const SOURCERY_COMMAND = /^.*@sourcery-ai\b.*$/gim;
1256
+ /** Drops each heading that names Sourcery with its section, up to the next heading of the same or a higher level. */
1257
+ function withoutSourcerySections(text) {
1258
+ const kept = [];
1259
+ let skipping = 0;
1260
+ for (const line of text.split("\n")) {
1261
+ const heading = /^(#{1,6})\s/.exec(line);
1262
+ if (heading) {
1263
+ const level = heading[1].length;
1264
+ if (/sourcery/i.test(line)) {
1265
+ skipping = level;
1266
+ continue;
1267
+ }
1268
+ if (skipping > 0 && level <= skipping) skipping = 0;
458
1269
  }
1270
+ if (skipping === 0) kept.push(line);
459
1271
  }
460
- let org;
461
- let domain;
462
- let docs;
463
- for (const cap of caps) {
464
- if (cap.org !== void 0) org = cap.org;
465
- if (cap.domain !== void 0) domain = cap.domain;
466
- if (cap.docs !== void 0) docs = cap.docs;
1272
+ return kept.join("\n");
1273
+ }
1274
+ /**
1275
+ * `text` without its HTML comments, repeated until none is left: taking one out can join the pieces around it into a new
1276
+ * one (`<!<!-- x -->-- y -->`), which a single pass would leave in the post.
1277
+ */
1278
+ function withoutHtmlComments(text) {
1279
+ let current = text;
1280
+ for (;;) {
1281
+ const next = current.replace(/<!--[\s\S]*?-->/g, "");
1282
+ if (next === current) return next;
1283
+ current = next;
467
1284
  }
1285
+ }
1286
+ /**
1287
+ * The part of a pull request's description worth showing in its post: the text the author wrote. Sourcery's summary,
1288
+ * reviewer's guide and commands are removed, and so is every HTML comment (a template's hints), the blank runs they
1289
+ * leave are closed up, and what is left is cut to {@link DESCRIPTION_LIMIT} characters with an ellipsis. A description
1290
+ * with nothing left, or none, is an empty string.
1291
+ */
1292
+ function prDescription(body) {
1293
+ if (!body) return "";
1294
+ const text = withoutHtmlComments(withoutSourcerySections(body.replace(/\r\n?/g, "\n").replace(SOURCERY_BLOCK, "").replace(SOURCERY_SUMMARY, "")).replace(SOURCERY_COMMAND, "")).replace(/\n{3,}/g, "\n\n").trim();
1295
+ return text.length <= 1500 ? text : `${text.slice(0, 1499).trimEnd()}…`;
1296
+ }
1297
+ // src/pull-request-post/render-pull-request/render-pull-request.ts
1298
+ /** Discord's limit on a post's title. */
1299
+ const TITLE_LIMIT = 100;
1300
+ const CI_TEXT = {
1301
+ passing: "passing",
1302
+ failing: "failing",
1303
+ pending: "running",
1304
+ none: "no result yet"
1305
+ };
1306
+ function cut(text) {
1307
+ return text.length <= TITLE_LIMIT ? text : `${text.slice(0, 99)}…`;
1308
+ }
1309
+ function reviewText(state) {
1310
+ if (state.review === "approved") return "approved";
1311
+ if (state.review === "changes_requested") return "changes requested";
1312
+ if (state.requestedReviewers.length > 0) return `waiting on review from ${state.requestedReviewers.join(", ")}`;
1313
+ return "waiting on review";
1314
+ }
1315
+ /**
1316
+ * The post for a pull request: its title (`repo#123: title`, plain text, because a forum post's title is not
1317
+ * markdown), the summary that is the first message (edited in place, no footer: a link to the pull request without
1318
+ * repeating the title, the status lines and the author's description with Sourcery's parts removed) and its tag. A pure function of the current state; the caller fetches it, and the provider adds the sync footer.
1319
+ */
1320
+ function renderPullRequest(state, now) {
1321
+ const tag = pullRequestTag(state);
1322
+ const name = state.repo.slice(state.repo.indexOf("/") + 1);
1323
+ const author = state.authorIsBot ? `${state.author} (bot)` : state.author;
1324
+ const status = state.merged ? "merged" : state.closed ? "closed" : state.draft ? "draft" : reviewText(state);
1325
+ const lines = [
1326
+ `**[${state.repo}#${state.number}](${state.url})**`,
1327
+ `by ${author} into \`${state.base}\`, opened ${ageText(state.createdAt, now)}`,
1328
+ `Status: ${status}`,
1329
+ `CI: ${CI_TEXT[state.ci]}`
1330
+ ];
1331
+ if (state.mergeable === "conflicting") lines.push(`Conflicts with \`${state.base}\``);
1332
+ const description = prDescription(state.body);
1333
+ const body = description ? `${lines.join("\n")}\n\n${description}` : lines.join("\n");
468
1334
  return {
469
- tasks: [...taskMap.values()],
470
- providers,
471
- repo,
472
- extraRequiredChecks,
473
- ...org !== void 0 ? { org } : {},
474
- ...domain !== void 0 ? { domain } : {},
475
- ...docs !== void 0 ? { docs } : {}
1335
+ title: cut(`${name}#${state.number}: ${state.title}`),
1336
+ body,
1337
+ tag
476
1338
  };
477
1339
  }
478
- //#endregion
479
- //#region src/config/define-config.ts
480
- function defineConfig(config) {
481
- return config;
482
- }
483
- //#endregion
484
- //#region src/config/load-config.ts
1340
+ // src/commands/forbidden-token-layers/forbidden-token-layers.ts
485
1341
  /**
486
- * `holocron.config.{ts,js,mjs,cjs,json}` loader.
487
- *
488
- * File discovery + module loading (typed configs via `tsx`, no build
489
- * step) is delegated to `@theholocron/datapad`. This module keeps the
490
- * holocron-specific parts: filling `name` / `repo.name` defaults and
491
- * running the config through `resolveConfig`.
1342
+ * Reads the layers a plugin's tokens forbid (`TokenExpectation.forbiddenLayers`, #2825) as one entry per token and
1343
+ * layer, in the order of `ENVIRONMENT_LAYERS`: the Environments that must not hold the token at all. A separate reader
1344
+ * from `tokenExpectations()`, which lists only the layers that hold a token, so the probes, the rotation readers and the
1345
+ * docs check never see a forbidden layer. A token with no `forbiddenLayers` yields nothing.
492
1346
  *
493
- * Probe order is TS-first (`.ts` → `.js` → `.mjs` → `.cjs` → `.json`) —
494
- * see ADR-0010 / issue #75 / #81.
1347
+ * @throws {ConfigError} For a layer that is not one of `ENVIRONMENT_LAYERS` (every layer word reads a vault
1348
+ * Environment, so none is left out), and for a layer a token is both declared for (`layers`, or a key of
1349
+ * `permissions`) and forbids: the declaration contradicts itself.
495
1350
  */
496
- const execFileAsync = promisify(execFile);
1351
+ function forbiddenTokenLayers(tokens, filter = {}) {
1352
+ const found = [];
1353
+ for (const token of tokens) {
1354
+ const { forbiddenLayers: forbidden, layers = [], permissions = {} } = token.expect ?? {};
1355
+ if (!forbidden || filter.envName !== void 0 && token.envName !== filter.envName) continue;
1356
+ const unknown = forbidden.find((layer) => !isEnvironmentLayer(layer));
1357
+ if (unknown !== void 0) throw new ConfigError$1(`${token.envName} forbids the layer ${JSON.stringify(unknown)}: use one of ${ENVIRONMENT_LAYERS.join(", ")}`);
1358
+ const declaredFor = ENVIRONMENT_LAYERS.filter((layer) => layers.includes(layer) || permissions[layer]);
1359
+ const both = declaredFor.find((layer) => forbidden.includes(layer));
1360
+ if (both !== void 0) throw new ConfigError$1(`${token.envName} is both declared for and forbidden in the ${both} layer`);
1361
+ for (const layer of ENVIRONMENT_LAYERS) {
1362
+ if (!forbidden.includes(layer) || filter.layer !== void 0 && filter.layer !== layer) continue;
1363
+ found.push({
1364
+ envName: token.envName,
1365
+ layer,
1366
+ declaredFor
1367
+ });
1368
+ }
1369
+ }
1370
+ return found;
1371
+ }
1372
+ // src/commands/token-rotation/token-rotation.ts
1373
+ /** The rotation policy of a token that declares none: a token is due after 90 days, and an expiry is flagged 14 days ahead. */
1374
+ const DEFAULT_TOKEN_ROTATION = {
1375
+ maxAgeDays: 90,
1376
+ warnDays: 14
1377
+ };
497
1378
  /**
498
- * Read + parse + resolve `holocron.config.*` from the given directory.
499
- * Throws {@link ConfigFileError} when nothing is found or a file cannot
500
- * be loaded, or `ConfigError` when the config is invalid.
1379
+ * The labels of the rows that fail for a token that is due (`expired on ...`, `expires on ... (N days left)` inside the
1380
+ * warning window, `N days old`): what `rotate tokens` looks for in a `doctor tokens` problem to tell a token that is due
1381
+ * from one that only lacks a permission.
501
1382
  */
502
- async function loadConfig(cwd) {
503
- const found = await loadConfigFile({
504
- cwd,
505
- name: "holocron"
1383
+ const ROTATION_LABELS = ["expiry", "age"];
1384
+ const DAY_MS = 864e5;
1385
+ /** The whole days from `from` to `to`, rounded down (negative once `to` is past). */
1386
+ function daysBetween(from, to) {
1387
+ return Math.floor((to.getTime() - from.getTime()) / DAY_MS);
1388
+ }
1389
+ /** `2026-11-13` of a valid date. */
1390
+ const day = (d) => d.toISOString().slice(0, 10);
1391
+ /** A valid `Date` of an ISO string, or `undefined` when there is none or it does not parse. */
1392
+ function parse(value) {
1393
+ if (value === void 0) return void 0;
1394
+ const date = new Date(value);
1395
+ return Number.isNaN(date.getTime()) ? void 0 : date;
1396
+ }
1397
+ /**
1398
+ * Rows saying whether a token is due for rotation, from what its provider exposes. Provider-neutral: a token probe reads
1399
+ * the lifetime however its provider offers it and hands it here, with the layer's `rotation` from `tokenExpectations()`.
1400
+ * `lifetime` is `undefined` when the provider exposes nothing (the row says so rather than passing), and a date the
1401
+ * provider gave that does not parse is an `info` row, never a pass. An expired or near-expiry token fails, and so does
1402
+ * one older than `maxAgeDays`. Only dates are printed, never the token.
1403
+ */
1404
+ function tokenRotationRows(lifetime, rotation, now) {
1405
+ if (!lifetime) return [{
1406
+ status: "info",
1407
+ label: "rotation",
1408
+ detail: `the provider does not expose this token's age or expiry; rotate it by hand every ${rotation.maxAgeDays} days`
1409
+ }];
1410
+ const rows = [];
1411
+ const expires = parse(lifetime.expiresAt);
1412
+ if (lifetime.expiresAt !== void 0 && !expires) rows.push({
1413
+ status: "info",
1414
+ label: "expiry",
1415
+ detail: "the provider's expiry date could not be read"
506
1416
  });
507
- if (!found) throw new ConfigFileError$1(`no holocron.config.{ts,js,mjs,cjs,json} found in ${cwd}. Create one — see the README for the schema.`);
508
- return {
509
- resolved: resolveConfig(await deriveDefaults(dirname(found.filepath), found.config)),
510
- filepath: found.filepath
511
- };
1417
+ else if (expires) {
1418
+ const left = daysBetween(now, expires);
1419
+ if (expires.getTime() <= now.getTime()) rows.push({
1420
+ status: "fail",
1421
+ label: "expiry",
1422
+ detail: `expired on ${day(expires)}`
1423
+ });
1424
+ else if (left < rotation.warnDays) rows.push({
1425
+ status: "fail",
1426
+ label: "expiry",
1427
+ detail: `expires on ${day(expires)} (${left} days left, warns under ${rotation.warnDays}); rotate it`
1428
+ });
1429
+ else rows.push({
1430
+ status: "ok",
1431
+ label: "expiry",
1432
+ detail: `expires on ${day(expires)} (${left} days left)`
1433
+ });
1434
+ } else rows.push({
1435
+ status: "info",
1436
+ label: "expiry",
1437
+ detail: "the token has no expiry"
1438
+ });
1439
+ const created = parse(lifetime.createdAt);
1440
+ if (lifetime.createdAt !== void 0 && !created) rows.push({
1441
+ status: "info",
1442
+ label: "age",
1443
+ detail: "the provider's creation date could not be read"
1444
+ });
1445
+ else if (created) {
1446
+ const age = daysBetween(created, now);
1447
+ const due = age > rotation.maxAgeDays;
1448
+ rows.push({
1449
+ status: due ? "fail" : "ok",
1450
+ label: "age",
1451
+ detail: due ? `${age} days old since ${day(created)}, over the ${rotation.maxAgeDays} days allowed; rotate it` : `${age} days old since ${day(created)} (rotate after ${rotation.maxAgeDays})`
1452
+ });
1453
+ } else rows.push({
1454
+ status: "info",
1455
+ label: "age",
1456
+ detail: "the provider does not say when the token was made"
1457
+ });
1458
+ return rows;
512
1459
  }
513
- async function deriveDefaults(configDir, raw) {
514
- const result = { ...raw };
515
- if (!result.name) result.name = await readPackageJsonName(configDir) ?? basename(configDir);
516
- if (result.repo && !result.repo.name) {
517
- const repoName = await readGitRemote(configDir);
518
- if (repoName) result.repo = {
519
- ...result.repo,
520
- name: repoName
521
- };
1460
+ // src/commands/token-expectations/token-expectations.ts
1461
+ /**
1462
+ * Reads what a plugin's tokens declare (`PluginToken.expect`) as one entry per token and layer that holds it, in the
1463
+ * order of `ENVIRONMENT_LAYERS`. The one reader the token probes, the doctor and the docs check share, so none of them
1464
+ * walks the declaration itself. A token with no `expect` yields nothing; a layer no token holds is never listed.
1465
+ */
1466
+ function tokenExpectations(tokens, filter = {}) {
1467
+ const found = [];
1468
+ for (const token of tokens) {
1469
+ if (!token.expect || filter.envName !== void 0 && token.envName !== filter.envName) continue;
1470
+ const { layers = [], permissions = {} } = token.expect;
1471
+ for (const layer of ENVIRONMENT_LAYERS) {
1472
+ if (filter.layer !== void 0 && filter.layer !== layer) continue;
1473
+ const rules = permissions[layer];
1474
+ if (!rules && !layers.includes(layer)) continue;
1475
+ const entries = Object.entries(rules ?? {});
1476
+ found.push({
1477
+ envName: token.envName,
1478
+ layer,
1479
+ rules: rules ?? {},
1480
+ required: entries.filter(([, rule]) => rule === "required").map(([name]) => name),
1481
+ absent: entries.filter(([, rule]) => rule === "absent").map(([name]) => name),
1482
+ rotation: {
1483
+ ...DEFAULT_TOKEN_ROTATION,
1484
+ ...token.expect.rotation
1485
+ }
1486
+ });
1487
+ }
522
1488
  }
523
- const manifest = await loadTasksConfig(configDir);
524
- if (manifest.tasks) result.tasks = manifest.tasks;
525
- if (manifest.syncScripts !== void 0) result.syncScripts = manifest.syncScripts;
526
- if (manifest.holocronScript !== void 0) result.holocronScript = manifest.holocronScript;
527
- if (manifest.hooks !== void 0) result.hooks = manifest.hooks;
528
- if (manifest.extraRequiredChecks) result.extraRequiredChecks = [...result.extraRequiredChecks ?? [], ...manifest.extraRequiredChecks];
529
- return result;
1489
+ return found;
530
1490
  }
531
- async function readPackageJsonName(dir) {
532
- try {
533
- const content = await readFile(join(dir, "package.json"), "utf8");
534
- const pkg = JSON.parse(content);
535
- return typeof pkg.name === "string" ? pkg.name.replace(/^@[^/]+\//, "") : void 0;
536
- } catch {
537
- return;
538
- }
1491
+ // src/commands/whoami-action/whoami-action.ts
1492
+ /**
1493
+ * A provider's `whoami` (`holocron provider <name> whoami`): who its token belongs to, when it stops working and what
1494
+ * the plugin declares it may do. Read-only, one row per fact, and a failing step is a row, not the end of the run. The
1495
+ * token and its value are never printed: only the vendor's own description of it (`verifyToken`'s subject), dates and
1496
+ * permission names.
1497
+ *
1498
+ * The permission row lists what each layer's declaration (`PluginToken.expect`) says the token needs and must not
1499
+ * have, and names the probe that proves it against the vendor: a vendor's API rarely says what a token may do, so
1500
+ * `whoami` reports the declaration and does not claim more than it has read.
1501
+ */
1502
+ function whoamiAction(input) {
1503
+ return async () => {
1504
+ const id = (suffix) => `${input.provider}:whoami:${suffix}`;
1505
+ let token;
1506
+ try {
1507
+ token = input.token();
1508
+ } catch (err) {
1509
+ return [{
1510
+ id: id("token"),
1511
+ title: `${input.provider} token`,
1512
+ status: "fail",
1513
+ detail: describeError(err),
1514
+ problems: []
1515
+ }];
1516
+ }
1517
+ const rows = [];
1518
+ const verified = await input.verify(token).catch((err) => ({
1519
+ ok: false,
1520
+ message: describeError(err)
1521
+ }));
1522
+ rows.push(verified.ok ? {
1523
+ id: id("identity"),
1524
+ title: "identity",
1525
+ status: "ok",
1526
+ detail: verified.subject,
1527
+ problems: []
1528
+ } : {
1529
+ id: id("identity"),
1530
+ title: "identity",
1531
+ status: "fail",
1532
+ detail: "the provider did not accept the token",
1533
+ problems: [verified.message]
1534
+ });
1535
+ if (!verified.ok) return rows;
1536
+ let lifetime = verified.expiresAt ? { expiresAt: verified.expiresAt } : void 0;
1537
+ let lifetimeProblem;
1538
+ if (input.lifetime) try {
1539
+ lifetime = await input.lifetime(token) ?? lifetime;
1540
+ } catch (err) {
1541
+ lifetimeProblem = describeError(err);
1542
+ }
1543
+ const policy = tokenExpectations(input.tokens)[0]?.rotation ?? DEFAULT_TOKEN_ROTATION;
1544
+ if (lifetimeProblem) rows.push({
1545
+ id: id("rotation"),
1546
+ title: "rotation",
1547
+ status: "skip",
1548
+ detail: `the provider's expiry could not be read: ${lifetimeProblem}`,
1549
+ problems: []
1550
+ });
1551
+ else for (const row of tokenRotationRows(lifetime, policy, (input.now ?? (() => /* @__PURE__ */ new Date()))())) {
1552
+ const detail = String(row.detail);
1553
+ rows.push({
1554
+ id: id(row.label),
1555
+ title: row.label,
1556
+ status: row.status === "ok" || row.status === "fail" ? row.status : "skip",
1557
+ detail,
1558
+ problems: row.status === "fail" ? [detail] : []
1559
+ });
1560
+ }
1561
+ const declared = tokenExpectations(input.tokens);
1562
+ const prove = input.proveWith ?? `holocron probe ${input.provider} token --environment <layer>`;
1563
+ rows.push(declared.length === 0 ? {
1564
+ id: id("permissions"),
1565
+ title: "permissions",
1566
+ status: "skip",
1567
+ detail: `the plugin declares none for this token; ${input.provider} does not say what a token may do`,
1568
+ problems: []
1569
+ } : {
1570
+ id: id("permissions"),
1571
+ title: "permissions",
1572
+ status: "skip",
1573
+ detail: `declared, not read from ${input.provider}: ${declared.map((e) => `${e.layer} ${describeRules(e.required, e.absent)}`).join("; ")}. Prove it with \`${prove}\``,
1574
+ problems: []
1575
+ });
1576
+ return rows;
1577
+ };
539
1578
  }
540
- async function readGitRemote(dir) {
1579
+ /** `needs pages; must not have dns, routes`, or `no permission rules` for a layer that only holds the token. */
1580
+ function describeRules(required, absent) {
1581
+ if (required.length === 0 && absent.length === 0) return "holds it, no permission rules";
1582
+ return [required.length > 0 ? `needs ${required.join(", ")}` : "", absent.length > 0 ? `must not have ${absent.join(", ")}` : ""].filter(Boolean).join("; ");
1583
+ }
1584
+ // src/commands/auth-export/stdout-kind/stdout-kind.ts
1585
+ /**
1586
+ * What file descriptor `fd` (stdout) is, for deciding where tokens may go: a `terminal`, a `pipe` (a FIFO, or the
1587
+ * socket some shells and runners use for one), or `other` (a regular file, a device, or anything that cannot be
1588
+ * inspected). Only a pipe is safe to write the lines to, so anything unknown is `other`.
1589
+ */
1590
+ function stdoutKind(isTerminal, fd = 1, stat = fstatSync) {
1591
+ if (isTerminal) return "terminal";
541
1592
  try {
542
- const { stdout } = await execFileAsync("git", [
543
- "remote",
544
- "get-url",
545
- "origin"
546
- ], { cwd: dir });
547
- return parseGitRemoteUrl(stdout.trim());
1593
+ const s = stat(fd);
1594
+ return s.isFIFO() || s.isSocket() ? "pipe" : "other";
548
1595
  } catch {
549
- return;
1596
+ return "other";
550
1597
  }
551
1598
  }
552
- function parseGitRemoteUrl(url) {
553
- const httpsMatch = url.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/);
554
- if (httpsMatch) return httpsMatch[1];
555
- const sshMatch = url.match(/github\.com:([^/]+\/[^/]+?)(?:\.git)?$/);
556
- if (sshMatch) return sshMatch[1];
557
- }
558
- //#endregion
559
- //#region src/inclusive-language/config.ts
1599
+ // src/commands/secrets-sync/resolve-environment-id/resolve-environment-id.ts
560
1600
  /**
561
- * The org's canonical `alex` (inclusive-language) config, as raw parsed
562
- * data rather than the pre-rendered file strings `createRcConfig()`/
563
- * `createIgnoreConfig()` produce for `holocron setup` to write into a
564
- * repo's own `.alexrc.json`/`.alexignore`.
1601
+ * The vault Environment `holocron sync secrets --env <environment>` reads. A layer word (`local`, `dev`, `ci`, `prod`) is the
1602
+ * Environment of that layer of this repository, `<org/repo> - <layer>`; any other text is a literal Environment name.
1603
+ * A literal name wins only when it is not exactly a layer word, so an Environment that is itself called `prod` cannot be
1604
+ * addressed by that name (spec `tech-environment-layers`, #2069).
565
1605
  *
566
- * `.alexrc.json` is explicitly "generated by `holocron setup` — do not
567
- * edit manually" (this repo's own `AGENTS.md`) — the real source of truth
568
- * is this JSON file, one canonical copy, not each repo's synced one. A
569
- * central Sentinel check (holocron#769/#793) reads it directly rather
570
- * than fetching each repo's own copy via the Contents API — the same "one
571
- * config, not N copies" reasoning `@theholocron/commitlint-config` already
572
- * established for commit-message linting.
573
- */
574
- const ALEX_CONFIG = { allow: [
575
- "dead",
576
- "execute",
577
- "execution",
578
- "executes",
579
- "failure",
580
- "failures",
581
- "hook",
582
- "hooks",
583
- "husky",
584
- "period"
585
- ] };
586
- /**
587
- * Glob-ish path patterns `alex` skips. Kept as a literal here rather than
588
- * importing `../templates/configs/alexjs/alexignore` directly — that file
589
- * (like `commit-msg`/`pre-push`) is deliberately extensionless, matching
590
- * the real filename `holocron setup` writes, which ECMAScript's own
591
- * module resolution (`moduleResolution: "nodenext"`) can't import across
592
- * a package boundary without an extension. Keep in sync with that file by
593
- * hand; it changes rarely.
594
- */
595
- const ALEX_IGNORE_PATTERNS = [
596
- ".github/*",
597
- "CHANGELOG.md",
598
- "LICENSE"
599
- ];
600
- //#endregion
601
- //#region src/formatting/config.ts
602
- /**
603
- * The org's canonical prettier ignore-pattern list for a central Sentinel
604
- * check (holocron#769/#819) — the `PRETTIER_CONFIG` object itself doesn't
605
- * need a home here, since `@theholocron/prettier-config`'s default export
606
- * already *is* one canonical, importable config (the same "one config,
607
- * not N copies" reasoning `@theholocron/commitlint-config` established for
608
- * commit-message linting, and `ALEX_CONFIG` established for inclusive
609
- * language) — only the ignore list is a Sentinel-specific decision that
610
- * belongs alongside `ALEX_IGNORE_PATTERNS`, not inside the config package.
611
- *
612
- * Reuses `ALEX_IGNORE_PATTERNS`' own entries (`.github/*`, `CHANGELOG.md`,
613
- * `LICENSE` all independently confirmed to fail a real `prettier.check()`
614
- * today — machine-generated or unparseable content, same reasoning that
615
- * excluded them from alex), plus `pnpm-lock.yaml` — prettier-specific
616
- * (alex never reads a lockfile, but prettier would try to reformat it):
617
- * machine-written by pnpm's own writer, and not gitignored (lockfiles are
618
- * tracked), so prettier picks it up by default. Reformatting it just
619
- * fights every subsequent `pnpm install` (this repo's own `.prettierignore`
620
- * already excludes it for that exact reason).
621
- */
622
- const PRETTIER_IGNORE_PATTERNS = [...ALEX_IGNORE_PATTERNS, "pnpm-lock.yaml"];
623
- //#endregion
624
- export { ALEX_CONFIG, ALEX_IGNORE_PATTERNS, AuthError, CARDINALITY, ConfigError, ConfigFileError, PRETTIER_IGNORE_PATTERNS, ProviderApiError, REQUIRED_CAPABILITIES, WebhookVerificationError, compose, createFeatureResolver, createResolveToken, createRestClient, defineConfig, deleteToken, deriveCapabilities, deriveCompliance, deriveProfile, deriveStack, getToken, isMulti, lintCommitMessage, lintCommitMsgFile, listStoredProviders, loadConfig, missingCapabilities, readWorkspacePackageJsons, resolveConfig, resolveEntry, resolvePluginPackage, setToken };
1606
+ * @param id - The `--env` value the user gave.
1607
+ * @param input - Where the repository is (its `origin` remote is read there), and optionally how to read it.
1608
+ * @throws {ConfigError} For a layer word when the remote cannot be read (the message names the `environment` option).
1609
+ */
1610
+ async function resolveEnvironmentId(id, input) {
1611
+ if (!isEnvironmentLayer(id)) return id;
1612
+ return layerEnvironment(await repoSlug(input.repoRoot, input.gitExec), id);
1613
+ }
1614
+ // src/private-dir/ignore-advice/ignore-advice.ts
1615
+ /** The line that says how to fix a credentials path the version control ignore rules do not cover. */
1616
+ function ignoreAdvice(isDefault, choose) {
1617
+ return isDefault ? "the private directory's ignore rule is missing: run `holocron sync` to add it" : `add it to .gitignore, or ${choose}`;
1618
+ }
1619
+ /** The file `export tokens` and `new github-app` write by default, relative to the repository root. */
1620
+ const PRIVATE_CREDENTIALS_FILE = `.holocron/.private/.credentials`;
1621
+ // src/private-dir/resolve-credentials-file/resolve-credentials-file.ts
1622
+ /**
1623
+ * The credentials file for a command: `file` (relative to `base`) when given, else `.holocron/.private/.credentials`
1624
+ * under `base`. The default's directory is created when missing (owner-only), because the ignore check can only ask
1625
+ * about a path whose directory exists and the file cannot be written without it.
1626
+ */
1627
+ function resolveCredentialsFile(base, file, makeDir = (dir) => void mkdirSync(dir, {
1628
+ recursive: true,
1629
+ mode: 448
1630
+ })) {
1631
+ if (file) return {
1632
+ path: resolve(base, file),
1633
+ isDefault: false
1634
+ };
1635
+ const path = resolve(base, PRIVATE_CREDENTIALS_FILE);
1636
+ makeDir(dirname(path));
1637
+ return {
1638
+ path,
1639
+ isDefault: true
1640
+ };
1641
+ }
1642
+ export { AGGREGATE_CHECK_NAME, AGGREGATE_SHADOW_CHECK_NAME, AREA_LABEL_COLOR, AREA_PREFIX, AuthError, BUILTIN_TEMPLATES, CANONICAL_LABELS, CARDINALITY, CUSTOM_EMOJI, ConfigError, ConfigFileError, DEFAULT_TEMPLATES_DIR, DEFAULT_TOKEN_ROTATION, EMOJI_MEDIA_DIR, ElevationRequiredError, HOLOCRON_AREAS, KNOWN_STACK_DEPS, MAX_EMOJI_BYTES, MissingTokenError, PRIVATE_CREDENTIALS_FILE, ProviderApiError, REQUIRED_CAPABILITIES, ROTATION_LABELS, RULESET_NAME, SHARED_AREAS, WebhookVerificationError, areaForScope, areaLabelDefs, areaLabelsForFiles, areaLabelsForTitle, compose, configRequiredContexts, connectionProbe, coverageExpectations, createFeatureResolver, createResolveToken, createRestClient, credentialsEnvironment, defineConfig, deriveCapabilities, deriveCompliance, deriveProfile, deriveStack, emojiConflictProblem, forbiddenTokenLayers, ignoreAdvice, isMulti, keyring, layoutEmojis, layoutReactions, loadConfig, loadEmojiImage, missingCapabilities, orderKeys, parsePrKey, parseReaction, pathMatches, pickByCreation, placeAreas, planPullRequestStatus, planReconcile, prKey, pullRequestTag, reactionProblem, reactionSpelling, readKeysLimited, readLinks, readWorkspacePackageJsons, renderPullRequest, reportProgress, requiredChecksVerdict, requiredFromContexts, resolveConfig, resolveCredentialsFile, resolveEntry, resolveEnvironmentId, resolvePluginPackage, resolveProjectOptions, resolveValue, roleTeamProblem, sourceProblem, stdoutKind, syncRoles, tagEmojiProblem, titleScopes, tokenExpectations, tokenRotationRows, whoamiAction };