@theholocron/cli 5.0.0-alpha.59 → 5.0.0-alpha.591

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-kv3gASRw.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.
17
29
  */
18
- function makeEnv(source) {
19
- return createEnvLookup(source);
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
+ } });
20
52
  }
21
- //#endregion
22
- //#region src/auth/keyring.ts
23
53
  /**
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.
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`.
57
+ */
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
+ } });
68
+ }
69
+ // src/commands/coverage-expectations/coverage-expectations.ts
70
+ /**
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");
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
+ }
52
352
  }
353
+ return {
354
+ version: 1,
355
+ links
356
+ };
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
+ };
53
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,344 +960,553 @@ 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
- };
1180
+ return labels;
1181
+ }
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 !== "");
388
1192
  }
389
- //#endregion
390
- //#region src/config/compose.ts
391
- function taskName(e) {
392
- return typeof e === "string" ? e : e.name;
1193
+ // src/area-labels/area-labels-for-title/area-labels-for-title.ts
1194
+ /**
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);
1207
+ }
1208
+ return labels;
393
1209
  }
1210
+ // src/commands/forbidden-token-layers/forbidden-token-layers.ts
394
1211
  /**
395
- * Merge any number of capability fragments into a single preset object that
396
- * spreads directly into `defineConfig()`.
397
- *
398
- * - Accepts individual capabilities or nested arrays (for bundle presets).
399
- * - Deduplicates by `id` — when the same ID appears more than once, the last
400
- * occurrence wins. This lets callers override bundle defaults by listing an
401
- * explicit capability after the bundle.
402
- * - Validates all `requires` at call time and throws `ConfigError` if any are
403
- * unmet, listing every missing dependency in a single message.
404
- *
405
- * @example
406
- * // docs-only site — no typecheck
407
- * const preset = compose(node(), docs());
408
- *
409
- * // library with docs
410
- * const preset = compose(node(), typecheck(), docs());
1212
+ * Reads the layers a plugin's tokens forbid (`TokenExpectation.forbiddenLayers`, #2825) as one entry per token and
1213
+ * layer, in the order of `ENVIRONMENT_LAYERS`: the Environments that must not hold the token at all. A separate reader
1214
+ * from `tokenExpectations()`, which lists only the layers that hold a token, so the probes, the rotation readers and the
1215
+ * docs check never see a forbidden layer. A token with no `forbiddenLayers` yields nothing.
411
1216
  *
412
- * // nextjs() is a bundle that returns Capability[]
413
- * const preset = compose(node(), nextjs());
414
- */
415
- function compose(...args) {
416
- const flat = args.flat();
417
- const byId = /* @__PURE__ */ new Map();
418
- for (const cap of flat) byId.set(cap.id, cap);
419
- const caps = [...byId.values()];
420
- const available = new Set(caps.map((c) => c.id));
421
- const errors = [];
422
- for (const cap of caps) for (const req of cap.requires ?? []) if (!available.has(req)) errors.push(`"${cap.id}" requires "${req}"`);
423
- if (errors.length > 0) throw new ConfigError(`compose(): unmet dependencies — ${errors.join(", ")}`);
424
- const taskMap = /* @__PURE__ */ new Map();
425
- for (const cap of caps) for (const entry of cap.tasks ?? []) taskMap.set(taskName(entry), entry);
426
- let providers = {};
427
- for (const cap of caps) if (cap.providers) providers = {
428
- ...providers,
429
- ...cap.providers
430
- };
431
- const checksSeen = /* @__PURE__ */ new Set();
432
- const extraRequiredChecks = [];
433
- for (const cap of caps) for (const check of cap.extraRequiredChecks ?? []) if (!checksSeen.has(check)) {
434
- checksSeen.add(check);
435
- extraRequiredChecks.push(check);
436
- }
437
- let repo = {};
438
- for (const cap of caps) {
439
- if (!cap.repo) continue;
440
- const { properties, topics, teams, ...scalars } = cap.repo;
441
- repo = {
442
- ...repo,
443
- ...scalars
444
- };
445
- if (properties) repo.properties = {
446
- ...repo.properties,
447
- ...properties
448
- };
449
- if (topics) {
450
- const merged = /* @__PURE__ */ new Set([...repo.topics ?? [], ...topics]);
451
- repo.topics = [...merged];
452
- }
453
- if (teams) {
454
- const teamMap = new Map((repo.teams ?? []).map((t) => [typeof t === "string" ? t : t.slug, t]));
455
- for (const t of teams) teamMap.set(typeof t === "string" ? t : t.slug, t);
456
- repo.teams = [...teamMap.values()];
1217
+ * @throws {ConfigError} For a layer that is not one of `ENVIRONMENT_LAYERS` (every layer word reads a vault
1218
+ * Environment, so none is left out), and for a layer a token is both declared for (`layers`, or a key of
1219
+ * `permissions`) and forbids: the declaration contradicts itself.
1220
+ */
1221
+ function forbiddenTokenLayers(tokens, filter = {}) {
1222
+ const found = [];
1223
+ for (const token of tokens) {
1224
+ const { forbiddenLayers: forbidden, layers = [], permissions = {} } = token.expect ?? {};
1225
+ if (!forbidden || filter.envName !== void 0 && token.envName !== filter.envName) continue;
1226
+ const unknown = forbidden.find((layer) => !isEnvironmentLayer(layer));
1227
+ if (unknown !== void 0) throw new ConfigError$1(`${token.envName} forbids the layer ${JSON.stringify(unknown)}: use one of ${ENVIRONMENT_LAYERS.join(", ")}`);
1228
+ const declaredFor = ENVIRONMENT_LAYERS.filter((layer) => layers.includes(layer) || permissions[layer]);
1229
+ const both = declaredFor.find((layer) => forbidden.includes(layer));
1230
+ if (both !== void 0) throw new ConfigError$1(`${token.envName} is both declared for and forbidden in the ${both} layer`);
1231
+ for (const layer of ENVIRONMENT_LAYERS) {
1232
+ if (!forbidden.includes(layer) || filter.layer !== void 0 && filter.layer !== layer) continue;
1233
+ found.push({
1234
+ envName: token.envName,
1235
+ layer,
1236
+ declaredFor
1237
+ });
457
1238
  }
458
1239
  }
459
- let org;
460
- let domain;
461
- let docs;
462
- for (const cap of caps) {
463
- if (cap.org !== void 0) org = cap.org;
464
- if (cap.domain !== void 0) domain = cap.domain;
465
- if (cap.docs !== void 0) docs = cap.docs;
466
- }
467
- return {
468
- tasks: [...taskMap.values()],
469
- providers,
470
- repo,
471
- extraRequiredChecks,
472
- ...org !== void 0 ? { org } : {},
473
- ...domain !== void 0 ? { domain } : {},
474
- ...docs !== void 0 ? { docs } : {}
475
- };
476
- }
477
- //#endregion
478
- //#region src/config/define-config.ts
479
- function defineConfig(config) {
480
- return config;
1240
+ return found;
481
1241
  }
482
- //#endregion
483
- //#region src/config/load-config.ts
1242
+ // src/commands/token-rotation/token-rotation.ts
1243
+ /** The rotation policy of a token that declares none: a token is due after 90 days, and an expiry is flagged 14 days ahead. */
1244
+ const DEFAULT_TOKEN_ROTATION = {
1245
+ maxAgeDays: 90,
1246
+ warnDays: 14
1247
+ };
484
1248
  /**
485
- * `holocron.config.{ts,js,mjs,cjs,json}` loader.
486
- *
487
- * File discovery + module loading (typed configs via `tsx`, no build
488
- * step) is delegated to `@theholocron/datapad`. This module keeps the
489
- * holocron-specific parts: filling `name` / `repo.name` defaults and
490
- * running the config through `resolveConfig`.
491
- *
492
- * Probe order is TS-first (`.ts` → `.js` → `.mjs` → `.cjs` → `.json`) —
493
- * see ADR-0010 / issue #75 / #81.
1249
+ * The labels of the rows that fail for a token that is due (`expired on ...`, `expires on ... (N days left)` inside the
1250
+ * warning window, `N days old`): what `rotate tokens` looks for in a `doctor tokens` problem to tell a token that is due
1251
+ * from one that only lacks a permission.
494
1252
  */
495
- const execFileAsync = promisify(execFile);
1253
+ const ROTATION_LABELS = ["expiry", "age"];
1254
+ const DAY_MS = 864e5;
1255
+ /** The whole days from `from` to `to`, rounded down (negative once `to` is past). */
1256
+ function daysBetween(from, to) {
1257
+ return Math.floor((to.getTime() - from.getTime()) / DAY_MS);
1258
+ }
1259
+ /** `2026-11-13` of a valid date. */
1260
+ const day = (d) => d.toISOString().slice(0, 10);
1261
+ /** A valid `Date` of an ISO string, or `undefined` when there is none or it does not parse. */
1262
+ function parse(value) {
1263
+ if (value === void 0) return void 0;
1264
+ const date = new Date(value);
1265
+ return Number.isNaN(date.getTime()) ? void 0 : date;
1266
+ }
496
1267
  /**
497
- * Read + parse + resolve `holocron.config.*` from the given directory.
498
- * Throws {@link ConfigFileError} when nothing is found or a file cannot
499
- * be loaded, or `ConfigError` when the config is invalid.
1268
+ * Rows saying whether a token is due for rotation, from what its provider exposes. Provider-neutral: a token probe reads
1269
+ * the lifetime however its provider offers it and hands it here, with the layer's `rotation` from `tokenExpectations()`.
1270
+ * `lifetime` is `undefined` when the provider exposes nothing (the row says so rather than passing), and a date the
1271
+ * provider gave that does not parse is an `info` row, never a pass. An expired or near-expiry token fails, and so does
1272
+ * one older than `maxAgeDays`. Only dates are printed, never the token.
500
1273
  */
501
- async function loadConfig(cwd) {
502
- const found = await loadConfigFile({
503
- cwd,
504
- name: "holocron"
1274
+ function tokenRotationRows(lifetime, rotation, now) {
1275
+ if (!lifetime) return [{
1276
+ status: "info",
1277
+ label: "rotation",
1278
+ detail: `the provider does not expose this token's age or expiry; rotate it by hand every ${rotation.maxAgeDays} days`
1279
+ }];
1280
+ const rows = [];
1281
+ const expires = parse(lifetime.expiresAt);
1282
+ if (lifetime.expiresAt !== void 0 && !expires) rows.push({
1283
+ status: "info",
1284
+ label: "expiry",
1285
+ detail: "the provider's expiry date could not be read"
505
1286
  });
506
- 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.`);
507
- return {
508
- resolved: resolveConfig(await deriveDefaults(dirname(found.filepath), found.config)),
509
- filepath: found.filepath
510
- };
1287
+ else if (expires) {
1288
+ const left = daysBetween(now, expires);
1289
+ if (expires.getTime() <= now.getTime()) rows.push({
1290
+ status: "fail",
1291
+ label: "expiry",
1292
+ detail: `expired on ${day(expires)}`
1293
+ });
1294
+ else if (left < rotation.warnDays) rows.push({
1295
+ status: "fail",
1296
+ label: "expiry",
1297
+ detail: `expires on ${day(expires)} (${left} days left, warns under ${rotation.warnDays}); rotate it`
1298
+ });
1299
+ else rows.push({
1300
+ status: "ok",
1301
+ label: "expiry",
1302
+ detail: `expires on ${day(expires)} (${left} days left)`
1303
+ });
1304
+ } else rows.push({
1305
+ status: "info",
1306
+ label: "expiry",
1307
+ detail: "the token has no expiry"
1308
+ });
1309
+ const created = parse(lifetime.createdAt);
1310
+ if (lifetime.createdAt !== void 0 && !created) rows.push({
1311
+ status: "info",
1312
+ label: "age",
1313
+ detail: "the provider's creation date could not be read"
1314
+ });
1315
+ else if (created) {
1316
+ const age = daysBetween(created, now);
1317
+ const due = age > rotation.maxAgeDays;
1318
+ rows.push({
1319
+ status: due ? "fail" : "ok",
1320
+ label: "age",
1321
+ 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})`
1322
+ });
1323
+ } else rows.push({
1324
+ status: "info",
1325
+ label: "age",
1326
+ detail: "the provider does not say when the token was made"
1327
+ });
1328
+ return rows;
511
1329
  }
512
- async function deriveDefaults(configDir, raw) {
513
- const result = { ...raw };
514
- if (!result.name) result.name = await readPackageJsonName(configDir) ?? basename(configDir);
515
- if (result.repo && !result.repo.name) {
516
- const repoName = await readGitRemote(configDir);
517
- if (repoName) result.repo = {
518
- ...result.repo,
519
- name: repoName
520
- };
1330
+ // src/commands/token-expectations/token-expectations.ts
1331
+ /**
1332
+ * Reads what a plugin's tokens declare (`PluginToken.expect`) as one entry per token and layer that holds it, in the
1333
+ * order of `ENVIRONMENT_LAYERS`. The one reader the token probes, the doctor and the docs check share, so none of them
1334
+ * walks the declaration itself. A token with no `expect` yields nothing; a layer no token holds is never listed.
1335
+ */
1336
+ function tokenExpectations(tokens, filter = {}) {
1337
+ const found = [];
1338
+ for (const token of tokens) {
1339
+ if (!token.expect || filter.envName !== void 0 && token.envName !== filter.envName) continue;
1340
+ const { layers = [], permissions = {} } = token.expect;
1341
+ for (const layer of ENVIRONMENT_LAYERS) {
1342
+ if (filter.layer !== void 0 && filter.layer !== layer) continue;
1343
+ const rules = permissions[layer];
1344
+ if (!rules && !layers.includes(layer)) continue;
1345
+ const entries = Object.entries(rules ?? {});
1346
+ found.push({
1347
+ envName: token.envName,
1348
+ layer,
1349
+ rules: rules ?? {},
1350
+ required: entries.filter(([, rule]) => rule === "required").map(([name]) => name),
1351
+ absent: entries.filter(([, rule]) => rule === "absent").map(([name]) => name),
1352
+ rotation: {
1353
+ ...DEFAULT_TOKEN_ROTATION,
1354
+ ...token.expect.rotation
1355
+ }
1356
+ });
1357
+ }
521
1358
  }
522
- const manifest = await loadTasksConfig(configDir);
523
- if (manifest.tasks) result.tasks = manifest.tasks;
524
- if (manifest.syncScripts !== void 0) result.syncScripts = manifest.syncScripts;
525
- if (manifest.holocronScript !== void 0) result.holocronScript = manifest.holocronScript;
526
- if (manifest.hooks !== void 0) result.hooks = manifest.hooks;
527
- if (manifest.extraRequiredChecks) result.extraRequiredChecks = [...result.extraRequiredChecks ?? [], ...manifest.extraRequiredChecks];
528
- return result;
1359
+ return found;
529
1360
  }
530
- async function readPackageJsonName(dir) {
531
- try {
532
- const content = await readFile(join(dir, "package.json"), "utf8");
533
- const pkg = JSON.parse(content);
534
- return typeof pkg.name === "string" ? pkg.name.replace(/^@[^/]+\//, "") : void 0;
535
- } catch {
536
- return;
537
- }
1361
+ // src/commands/whoami-action/whoami-action.ts
1362
+ /**
1363
+ * A provider's `whoami` (`holocron provider <name> whoami`): who its token belongs to, when it stops working and what
1364
+ * 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
1365
+ * token and its value are never printed: only the vendor's own description of it (`verifyToken`'s subject), dates and
1366
+ * permission names.
1367
+ *
1368
+ * The permission row lists what each layer's declaration (`PluginToken.expect`) says the token needs and must not
1369
+ * have, and names the probe that proves it against the vendor: a vendor's API rarely says what a token may do, so
1370
+ * `whoami` reports the declaration and does not claim more than it has read.
1371
+ */
1372
+ function whoamiAction(input) {
1373
+ return async () => {
1374
+ const id = (suffix) => `${input.provider}:whoami:${suffix}`;
1375
+ let token;
1376
+ try {
1377
+ token = input.token();
1378
+ } catch (err) {
1379
+ return [{
1380
+ id: id("token"),
1381
+ title: `${input.provider} token`,
1382
+ status: "fail",
1383
+ detail: describeError(err),
1384
+ problems: []
1385
+ }];
1386
+ }
1387
+ const rows = [];
1388
+ const verified = await input.verify(token).catch((err) => ({
1389
+ ok: false,
1390
+ message: describeError(err)
1391
+ }));
1392
+ rows.push(verified.ok ? {
1393
+ id: id("identity"),
1394
+ title: "identity",
1395
+ status: "ok",
1396
+ detail: verified.subject,
1397
+ problems: []
1398
+ } : {
1399
+ id: id("identity"),
1400
+ title: "identity",
1401
+ status: "fail",
1402
+ detail: "the provider did not accept the token",
1403
+ problems: [verified.message]
1404
+ });
1405
+ if (!verified.ok) return rows;
1406
+ let lifetime = verified.expiresAt ? { expiresAt: verified.expiresAt } : void 0;
1407
+ let lifetimeProblem;
1408
+ if (input.lifetime) try {
1409
+ lifetime = await input.lifetime(token) ?? lifetime;
1410
+ } catch (err) {
1411
+ lifetimeProblem = describeError(err);
1412
+ }
1413
+ const policy = tokenExpectations(input.tokens)[0]?.rotation ?? DEFAULT_TOKEN_ROTATION;
1414
+ if (lifetimeProblem) rows.push({
1415
+ id: id("rotation"),
1416
+ title: "rotation",
1417
+ status: "skip",
1418
+ detail: `the provider's expiry could not be read: ${lifetimeProblem}`,
1419
+ problems: []
1420
+ });
1421
+ else for (const row of tokenRotationRows(lifetime, policy, (input.now ?? (() => /* @__PURE__ */ new Date()))())) {
1422
+ const detail = String(row.detail);
1423
+ rows.push({
1424
+ id: id(row.label),
1425
+ title: row.label,
1426
+ status: row.status === "ok" || row.status === "fail" ? row.status : "skip",
1427
+ detail,
1428
+ problems: row.status === "fail" ? [detail] : []
1429
+ });
1430
+ }
1431
+ const declared = tokenExpectations(input.tokens);
1432
+ const prove = input.proveWith ?? `holocron probe ${input.provider} token --environment <layer>`;
1433
+ rows.push(declared.length === 0 ? {
1434
+ id: id("permissions"),
1435
+ title: "permissions",
1436
+ status: "skip",
1437
+ detail: `the plugin declares none for this token; ${input.provider} does not say what a token may do`,
1438
+ problems: []
1439
+ } : {
1440
+ id: id("permissions"),
1441
+ title: "permissions",
1442
+ status: "skip",
1443
+ detail: `declared, not read from ${input.provider}: ${declared.map((e) => `${e.layer} ${describeRules(e.required, e.absent)}`).join("; ")}. Prove it with \`${prove}\``,
1444
+ problems: []
1445
+ });
1446
+ return rows;
1447
+ };
1448
+ }
1449
+ /** `needs pages; must not have dns, routes`, or `no permission rules` for a layer that only holds the token. */
1450
+ function describeRules(required, absent) {
1451
+ if (required.length === 0 && absent.length === 0) return "holds it, no permission rules";
1452
+ return [required.length > 0 ? `needs ${required.join(", ")}` : "", absent.length > 0 ? `must not have ${absent.join(", ")}` : ""].filter(Boolean).join("; ");
538
1453
  }
539
- async function readGitRemote(dir) {
1454
+ // src/commands/auth-export/stdout-kind/stdout-kind.ts
1455
+ /**
1456
+ * What file descriptor `fd` (stdout) is, for deciding where tokens may go: a `terminal`, a `pipe` (a FIFO, or the
1457
+ * socket some shells and runners use for one), or `other` (a regular file, a device, or anything that cannot be
1458
+ * inspected). Only a pipe is safe to write the lines to, so anything unknown is `other`.
1459
+ */
1460
+ function stdoutKind(isTerminal, fd = 1, stat = fstatSync) {
1461
+ if (isTerminal) return "terminal";
540
1462
  try {
541
- const { stdout } = await execFileAsync("git", [
542
- "remote",
543
- "get-url",
544
- "origin"
545
- ], { cwd: dir });
546
- return parseGitRemoteUrl(stdout.trim());
1463
+ const s = stat(fd);
1464
+ return s.isFIFO() || s.isSocket() ? "pipe" : "other";
547
1465
  } catch {
548
- return;
1466
+ return "other";
549
1467
  }
550
1468
  }
551
- function parseGitRemoteUrl(url) {
552
- const httpsMatch = url.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/);
553
- if (httpsMatch) return httpsMatch[1];
554
- const sshMatch = url.match(/github\.com:([^/]+\/[^/]+?)(?:\.git)?$/);
555
- if (sshMatch) return sshMatch[1];
1469
+ // src/commands/secrets-sync/resolve-environment-id/resolve-environment-id.ts
1470
+ /**
1471
+ * The vault Environment `holocron sync secrets --env <environment>` reads. A layer word (`local`, `dev`, `ci`, `prod`) is the
1472
+ * Environment of that layer of this repository, `<org/repo> - <layer>`; any other text is a literal Environment name.
1473
+ * A literal name wins only when it is not exactly a layer word, so an Environment that is itself called `prod` cannot be
1474
+ * addressed by that name (spec `tech-environment-layers`, #2069).
1475
+ *
1476
+ * @param id - The `--env` value the user gave.
1477
+ * @param input - Where the repository is (its `origin` remote is read there), and optionally how to read it.
1478
+ * @throws {ConfigError} For a layer word when the remote cannot be read (the message names the `environment` option).
1479
+ */
1480
+ async function resolveEnvironmentId(id, input) {
1481
+ if (!isEnvironmentLayer(id)) return id;
1482
+ return layerEnvironment(await repoSlug(input.repoRoot, input.gitExec), id);
1483
+ }
1484
+ // src/private-dir/ignore-advice/ignore-advice.ts
1485
+ /** The line that says how to fix a credentials path the version control ignore rules do not cover. */
1486
+ function ignoreAdvice(isDefault, choose) {
1487
+ return isDefault ? "the private directory's ignore rule is missing: run `holocron sync` to add it" : `add it to .gitignore, or ${choose}`;
1488
+ }
1489
+ /** The file `export tokens` and `new github-app` write by default, relative to the repository root. */
1490
+ const PRIVATE_CREDENTIALS_FILE = `.holocron/.private/.credentials`;
1491
+ // src/private-dir/resolve-credentials-file/resolve-credentials-file.ts
1492
+ /**
1493
+ * The credentials file for a command: `file` (relative to `base`) when given, else `.holocron/.private/.credentials`
1494
+ * under `base`. The default's directory is created when missing (owner-only), because the ignore check can only ask
1495
+ * about a path whose directory exists and the file cannot be written without it.
1496
+ */
1497
+ function resolveCredentialsFile(base, file, makeDir = (dir) => void mkdirSync(dir, {
1498
+ recursive: true,
1499
+ mode: 448
1500
+ })) {
1501
+ if (file) return {
1502
+ path: resolve(base, file),
1503
+ isDefault: false
1504
+ };
1505
+ const path = resolve(base, PRIVATE_CREDENTIALS_FILE);
1506
+ makeDir(dirname(path));
1507
+ return {
1508
+ path,
1509
+ isDefault: true
1510
+ };
556
1511
  }
557
- //#endregion
558
- export { AuthError, CARDINALITY, ConfigError, ConfigFileError, 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 };
1512
+ 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, parseReaction, pathMatches, pickByCreation, placeAreas, planPullRequestStatus, planReconcile, reactionProblem, reactionSpelling, readKeysLimited, readLinks, readWorkspacePackageJsons, reportProgress, requiredChecksVerdict, requiredFromContexts, resolveConfig, resolveCredentialsFile, resolveEntry, resolveEnvironmentId, resolvePluginPackage, resolveProjectOptions, resolveValue, roleTeamProblem, sourceProblem, stdoutKind, syncRoles, tagEmojiProblem, titleScopes, tokenExpectations, tokenRotationRows, whoamiAction };