@theholocron/cli 5.0.0-alpha.49 → 5.0.0-alpha.491

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,119 +1,784 @@
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-BqX0yRVh.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 { DOCUMENTATION_FLAG, codecovFlagNames, readWorkspacePackages } 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 { execFile } from "node:child_process";
8
- import { promisify } from "node:util";
9
- import { loadTasksConfig } from "@theholocron/astromech/config";
10
- import { ConfigFileError, ConfigFileError as ConfigFileError$1, loadConfigFile } from "@theholocron/datapad";
11
- 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 { connectionProbe as connectionProbe$1 } from "@theholocron/kyber/checks";
12
+ import { readPackageJson } from "@theholocron/pkg-utils";
13
+ import { fstatSync, mkdirSync } from "node:fs";
14
+ // src/auth/auth.ts
12
15
  /**
13
- * Create an injectable env for commands that accept a fake env in tests.
14
- * Pass `input.env` when available, falls back to `process.env`.
16
+ * The CLI's credentials: the OS keyring every plugin's bootstrap token lives in, and the two token resolvers built on
17
+ * it. Both are public, so a plugin's `src/auth.ts` is a one-line call.
18
+ *
19
+ * The keyring itself, with its best-effort failure model and its per-process cache, is `createKeyring` in
20
+ * `@theholocron/kyber/secrets`; this file only names the service. Managed via `holocron check token` subcommands and consulted
21
+ * last in every plugin's precedence chain (after --token / HOLOCRON_<X>_TOKEN / <native>_TOKEN). See
22
+ * `docs/wiki/specifications/tech-auth-bootstrap.spec.md`.
23
+ */
24
+ /**
25
+ * The holocron keyring: `get` answers `null` for "not stored" and for "keyring unavailable" alike, so callers fall
26
+ * through to env-var precedence, and remembers the answer for the process (`clearCache` forgets it); `set` and `delete`
27
+ * answer whether they did anything; `list` names the stored providers; `isAvailable` tells an outage from an empty keyring.
28
+ */
29
+ const keyring = createKeyring({
30
+ service: "com.theholocron.cli",
31
+ binding: {
32
+ Entry,
33
+ findCredentials
34
+ }
35
+ });
36
+ /**
37
+ * Kyber's `createResolveToken` with the keyring, the `HOLOCRON_ORG` variable and the `token` description
38
+ * `holocron doctor secrets --verify` reads filled in, so a plugin stays at a one-liner call site. The chain is the flag, the
39
+ * plugin's variable, the vendor's variable, the `credentials` providers' variables, the keyring.
15
40
  */
16
- function makeEnv(source) {
17
- return createEnvLookup(source);
41
+ function createResolveToken(config) {
42
+ return Object.assign(createResolveToken$1({
43
+ ...config,
44
+ keyring: keyring.get,
45
+ orgEnvName: "HOLOCRON_ORG"
46
+ }), { token: {
47
+ envName: config.envName,
48
+ vendorEnvName: config.vendorEnvName,
49
+ keyringKey: config.keyringService
50
+ } });
18
51
  }
19
- //#endregion
20
- //#region src/auth/keyring.ts
21
52
  /**
22
- * Keyring-backed bootstrap credential store.
23
- *
24
- * Every holocron plugin's bootstrap token (the one it needs before it
25
- * can talk to its vendor's API) can be stored in the OS keyring under
26
- * a single reverse-DNS service scope. Managed via `holocron auth`
27
- * subcommands; consulted at position 4 in every plugin's auth
28
- * precedence chain (after --token / HOLOCRON_<X>_TOKEN / <native>_TOKEN).
29
- *
30
- * See `docs/wiki/specifications/tech-auth-bootstrap.spec.md` for the design rationale.
53
+ * Kyber's `createFeatureResolver` for a strict, single-feature token: the flag, the feature's variable, the
54
+ * `credentials` providers' variable of that name, the keyring. No broad-token fallback; if the feature's token is absent
55
+ * the operation fails with a message naming the exact variable to set and `holocron new token`.
56
+ */
57
+ function createFeatureResolver(config) {
58
+ return Object.assign(createFeatureResolver$1({
59
+ ...config,
60
+ vendor: config.vendor ?? "GitHub",
61
+ setCommand: (key) => `holocron new token ${key} <token>`,
62
+ keyring: keyring.get
63
+ }), { token: {
64
+ envName: config.envName,
65
+ keyringKey: config.keyringKey
66
+ } });
67
+ }
68
+ // src/commands/coverage-expectations/coverage-expectations.ts
69
+ /**
70
+ * The flags and components `holocron sync` writes to `codecov.yml` for the workspace at `repoRoot`: the same
71
+ * functions the generator uses, so a coverage provider's `checkRepo()` compares with exactly what is written. A flag per
72
+ * package (none for `docs`), plus `documentation` when `docsCoverage` is `warn` or `required`; a component per package.
73
+ * Both lists are sorted. Plugins call this instead of importing the task runner.
74
+ */
75
+ function coverageExpectations(repoRoot, docsCoverage = "off") {
76
+ const packages = readWorkspacePackages(repoRoot);
77
+ const flags = codecovFlagNames(packages);
78
+ if (docsCoverage !== "off") flags.push(DOCUMENTATION_FLAG);
79
+ return {
80
+ flags: [...new Set(flags)].sort(),
81
+ components: packages.map((pkg) => pkg.slug).sort()
82
+ };
83
+ }
84
+ // src/commands/notifications-reaction/parse-reaction/parse-reaction.ts
85
+ /** A server emoji written as Discord shows it: `:name:`, the name 2 to 32 letters, digits and underscores. */
86
+ const CUSTOM_EMOJI = /^:([A-Za-z0-9_]{2,32}):$/;
87
+ /**
88
+ * Reads a layout reaction. `":git_merge:"` (or `{ emoji: ":git_merge:", image }`) is a server emoji named `git_merge`;
89
+ * any other string is a Unicode emoji and kept as written. It does not judge a value: `reactionProblem()` does, before
90
+ * anything is applied, so an invalid `emoji` here is kept as the name it was given.
91
+ */
92
+ function parseReaction(reaction) {
93
+ if (typeof reaction === "string") {
94
+ const name = CUSTOM_EMOJI.exec(reaction)?.[1];
95
+ return name === void 0 ? {
96
+ kind: "unicode",
97
+ value: reaction
98
+ } : {
99
+ kind: "custom",
100
+ name
101
+ };
102
+ }
103
+ return {
104
+ kind: "custom",
105
+ name: CUSTOM_EMOJI.exec(reaction.emoji)?.[1] ?? reaction.emoji,
106
+ ...reaction.image ? { image: reaction.image } : {}
107
+ };
108
+ }
109
+ // src/commands/notifications-reaction/emoji-conflict-problem/emoji-conflict-problem.ts
110
+ /**
111
+ * The first server emoji a layout gives two different pictures, or undefined. One name is one emoji, so it can be made
112
+ * from one file only; the same file written twice is fine.
113
+ */
114
+ function emojiConflictProblem(layout) {
115
+ const images = /* @__PURE__ */ new Map();
116
+ for (const channel of (layout.categories ?? []).flatMap((c) => c.channels ?? [])) {
117
+ const reactions = [...channel.defaultReaction === void 0 ? [] : [channel.defaultReaction], ...channel.starterReactions ?? []];
118
+ for (const reaction of reactions) {
119
+ const parsed = parseReaction(reaction);
120
+ if (parsed.kind !== "custom" || !parsed.image) continue;
121
+ const image = posix.normalize(parsed.image);
122
+ const have = images.get(parsed.name);
123
+ if (have !== void 0 && have !== image) return `emoji \`:${parsed.name}:\` is given two different images, \`${have}\` and \`${image}\``;
124
+ images.set(parsed.name, image);
125
+ }
126
+ }
127
+ }
128
+ // src/commands/notifications-reaction/layout-emojis/layout-emojis.ts
129
+ /**
130
+ * The server emoji a layout's forum reactions name (default and starter), once each, in the order the layout first
131
+ * names them. A name that is given an `image` anywhere keeps it, so the picture can sit on any one of its uses.
132
+ */
133
+ function layoutEmojis(layout) {
134
+ const found = /* @__PURE__ */ new Map();
135
+ for (const channel of (layout?.categories ?? []).flatMap((c) => c.channels ?? [])) {
136
+ const reactions = [...channel.defaultReaction === void 0 ? [] : [channel.defaultReaction], ...channel.starterReactions ?? []];
137
+ for (const reaction of reactions) {
138
+ const parsed = parseReaction(reaction);
139
+ if (parsed.kind !== "custom") continue;
140
+ const have = found.get(parsed.name);
141
+ if (!have) found.set(parsed.name, {
142
+ name: parsed.name,
143
+ ...parsed.image ? { image: parsed.image } : {}
144
+ });
145
+ else if (!have.image && parsed.image) have.image = parsed.image;
146
+ }
147
+ }
148
+ return [...found.values()];
149
+ }
150
+ // src/commands/notifications-reaction/load-emoji-image/load-emoji-image.ts
151
+ /** Discord's limit for an emoji file ("256 KiB", its Emoji resource docs). */
152
+ const MAX_EMOJI_BYTES = 262144;
153
+ const ascii = (bytes, from, to) => Buffer.from(bytes.subarray(from, to)).toString("latin1");
154
+ /** The image type the first bytes show, among the ones Discord takes for an emoji (JPEG, PNG, GIF, WebP, AVIF). */
155
+ function typeOf(bytes) {
156
+ if (bytes.length >= 8 && [
157
+ 137,
158
+ 80,
159
+ 78,
160
+ 71,
161
+ 13,
162
+ 10,
163
+ 26,
164
+ 10
165
+ ].every((b, i) => bytes[i] === b)) return "image/png";
166
+ if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg";
167
+ if (ascii(bytes, 0, 4) === "GIF8") return "image/gif";
168
+ if (ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 12) === "WEBP") return "image/webp";
169
+ if (ascii(bytes, 4, 8) === "ftyp" && ["avif", "avis"].includes(ascii(bytes, 8, 12))) return "image/avif";
170
+ }
171
+ /**
172
+ * 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
173
+ * first bytes, not the name, and a file Discord would refuse (larger than 256 KiB, or not a JPEG, PNG, GIF, WebP or
174
+ * AVIF image) is refused here, before anything is written. `read` is injected by tests.
175
+ */
176
+ async function loadEmojiImage(source, baseDir = process.cwd(), read = readFile) {
177
+ const bytes = await read(resolve(baseDir, source));
178
+ if (bytes.length > 262144) throw new Error(`it is ${Math.ceil(bytes.length / 1024)} KiB, and Discord takes an emoji up to 256 KiB`);
179
+ const type = typeOf(bytes);
180
+ if (!type) throw new Error("it is not a JPEG, PNG, GIF, WebP or AVIF image, which are the formats Discord takes");
181
+ return `data:${type};base64,${Buffer.from(bytes).toString("base64")}`;
182
+ }
183
+ // src/commands/notifications-reaction/reaction-problem/reaction-problem.ts
184
+ /** The folder a layout's emoji pictures live in, as the webhook avatar's files do. */
185
+ const EMOJI_MEDIA_DIR = ".holocron/media/";
186
+ /**
187
+ * The first reason a reaction cannot work, or undefined; `noun` names it in the message (`` `defaultReaction` ``, "a
188
+ * starter reaction"). A Unicode emoji must be a character, not a word (`git_merge` without colons would be sent to
189
+ * Discord as text), a server emoji `:name:` with a name Discord allows, and an `image` a file under `.holocron/media/`
190
+ * (a path, not a URL, with no `..` out of it). A `null` a config wrote is refused, not read as absent.
191
+ */
192
+ function reactionProblem(noun, reaction) {
193
+ if (reaction === null || typeof reaction !== "string" && typeof reaction !== "object") return `${noun} must be an emoji, \`:name:\` for a server emoji, or \`{ emoji, image }\``;
194
+ const text = typeof reaction === "string" ? reaction : reaction.emoji;
195
+ if (typeof text !== "string" || text.trim() === "") return `${noun} is empty`;
196
+ const isCustom = CUSTOM_EMOJI.test(text);
197
+ if (typeof reaction === "object" && !isCustom) return `${noun}: \`emoji\` must be a server emoji written \`:name:\` (2 to 32 letters, digits and underscores), not \`${text}\``;
198
+ 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)`;
199
+ if (typeof reaction === "object" && reaction.image !== void 0) {
200
+ const image = reaction.image;
201
+ if (typeof image !== "string" || image.trim() === "") return `${noun}: \`image\` is empty`;
202
+ if (/^[a-z][a-z0-9+.-]+:/i.test(image)) return `${noun}: \`image\` must be a file under \`${EMOJI_MEDIA_DIR}\`, not a URL`;
203
+ const path = posix.normalize(image);
204
+ if (!path.startsWith(".holocron/media/") || path === ".holocron/media/") return `${noun}: \`image\` must be a file under \`${EMOJI_MEDIA_DIR}\`, not \`${image}\``;
205
+ }
206
+ }
207
+ // src/commands/notifications-reaction/reaction-spelling/reaction-spelling.ts
208
+ /** How a reaction is written in a layout and shown in a row: `:name:` for a server emoji, the character otherwise. */
209
+ function reactionSpelling(reaction) {
210
+ const parsed = parseReaction(reaction);
211
+ return parsed.kind === "custom" ? `:${parsed.name}:` : parsed.value;
212
+ }
213
+ // src/plugin/issues-provider/order-keys/order-keys.ts
214
+ /**
215
+ * Puts issue keys in creation order without asking the tracker: issue numbers (`#12`, `ENG-12`) rise with creation inside
216
+ * one repository or team, so the trailing number is the order. `oldest` is ascending, `newest` descending; keys with the
217
+ * same number keep their place. A key with no trailing number is an error, because nothing can be said of its age.
218
+ */
219
+ function orderKeys(keys, order) {
220
+ const numbered = keys.map((key, index) => {
221
+ const match = /(\d+)\s*$/.exec(key);
222
+ if (!match) throw new Error(`Cannot order "${key}" by creation: it has no issue number.`);
223
+ return {
224
+ key,
225
+ index,
226
+ n: Number(match[1])
227
+ };
228
+ });
229
+ const sign = order === "newest" ? -1 : 1;
230
+ return numbered.sort((a, b) => sign * (a.n - b.n) || a.index - b.index).map((e) => e.key);
231
+ }
232
+ // src/plugin/issues-provider/pick-by-creation/pick-by-creation.ts
233
+ /**
234
+ * Keeps the first or last `limit` of a listing by creation time, returned oldest first. `createdAt` reads an item's
235
+ * ISO timestamp; items created in the same instant keep their listed order. The cut happens on what the listing already
236
+ * holds, so no request is spent on an item that is dropped.
237
+ */
238
+ function pickByCreation(items, createdAt, order, limit) {
239
+ const ascending = items.map((item, index) => ({
240
+ item,
241
+ index,
242
+ at: Date.parse(createdAt(item))
243
+ })).sort((a, b) => a.at - b.at || a.index - b.index).map((e) => e.item);
244
+ return order === "newest" ? ascending.slice(Math.max(ascending.length - limit, 0)) : ascending.slice(0, limit);
245
+ }
246
+ // src/plugin/issues-provider/read-keys-limited/read-keys-limited.ts
247
+ /**
248
+ * Reads an explicit list of issues in creation order until `limit` of them are kept. The keys are sorted by number first
249
+ * (see {@link orderKeys}), then fetched in small steps of at most `concurrency`, each step no bigger than the places
250
+ * still open, so an issue that is later skipped (a pull request, a closed one) is replaced by the next key and nothing
251
+ * beyond the budget is fetched unless a skip made room. Within a step the fetches run together; the results keep the key
252
+ * order. The kept items come back oldest first, whichever end was chosen.
253
+ */
254
+ async function readKeysLimited(input) {
255
+ const { keys, order, limit, concurrency, fetch, keep } = input;
256
+ const ordered = orderKeys(keys, order);
257
+ const kept = [];
258
+ let next = 0;
259
+ while (kept.length < limit && next < ordered.length) {
260
+ const step = ordered.slice(next, next + Math.min(concurrency, limit - kept.length));
261
+ next += step.length;
262
+ const fetched = await Promise.all(step.map((key) => fetch(key)));
263
+ for (const item of fetched) if (keep(item)) kept.push(item);
264
+ }
265
+ return order === "newest" ? kept.reverse() : kept;
266
+ }
267
+ // src/plugin/issues-provider/report-progress/report-progress.ts
268
+ /**
269
+ * Calls a provider's optional `onProgress` hook with how many items are done of how many. A hook that throws is
270
+ * ignored, because a progress counter must never change or stop the read or write it reports on.
31
271
  *
32
- * Failure model: keyring access is best-effort. Platforms without a
33
- * supported credential store (some Linux CI images, sandboxed
34
- * environments) will throw from the underlying library. Every export
35
- * here catches and returns a null/empty result rather than propagating
36
- * — the plugin's precedence chain then falls through to
37
- * env-var-only paths, which is exactly how CI is meant to work.
272
+ * @param onProgress - The hook from `ExportInfo` or `ImportOptions`; nothing happens when it is not given.
273
+ * @param done - How many items are finished.
274
+ * @param total - How many items there are.
38
275
  */
39
- const SERVICE = "com.theholocron.cli";
276
+ function reportProgress(onProgress, done, total) {
277
+ try {
278
+ onProgress?.(done, total);
279
+ } catch {}
280
+ }
281
+ // src/plugin/probes/connection-probe/connection-probe.ts
40
282
  /**
41
- * Store or overwrite a bootstrap token for a provider. Returns true on
42
- * success, false when the underlying keyring is unsupported or errored.
283
+ * The `connection` probe every provider offers, for telling a network problem from a credential problem. The checks are
284
+ * kyber's `connectionProbe`; this types the result as the plugin system's {@link Probe} and `verify` as `VerifyTokenResult`.
43
285
  */
44
- function setToken(provider, token) {
286
+ function connectionProbe(input) {
287
+ return connectionProbe$1(input);
288
+ }
289
+ // src/commands/notifications-sync-roles/links.ts
290
+ const EMPTY_LINKS = {
291
+ version: 1,
292
+ links: []
293
+ };
294
+ const DIGITS = /^\d{1,20}$/;
295
+ /** 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. */
296
+ function parseLinks(text) {
297
+ let raw;
45
298
  try {
46
- new Entry(SERVICE, provider).setPassword(token);
47
- return true;
299
+ raw = JSON.parse(text);
48
300
  } catch {
49
- return false;
301
+ throw new Error("the links file is not valid JSON");
302
+ }
303
+ const file = raw;
304
+ if (file.version !== 1) throw new Error(`the links file has version ${JSON.stringify(file.version)}; expected 1`);
305
+ if (!Array.isArray(file.links)) throw new Error("the links file has no `links` list");
306
+ const links = file.links.map((entry, i) => {
307
+ const e = entry;
308
+ if (typeof e.github !== "string" || !DIGITS.test(e.github)) throw new Error(`links[${i}]: \`github\` must be a numeric user id string`);
309
+ if (typeof e.member !== "string" || !DIGITS.test(e.member)) throw new Error(`links[${i}]: \`member\` must be a numeric id string`);
310
+ if (typeof e.login !== "string") throw new Error(`links[${i}]: \`login\` must be a string`);
311
+ return {
312
+ github: e.github,
313
+ login: e.login,
314
+ member: e.member
315
+ };
316
+ });
317
+ for (const key of ["github", "member"]) {
318
+ const seen = /* @__PURE__ */ new Set();
319
+ for (const [i, link] of links.entries()) {
320
+ if (seen.has(link[key])) throw new Error(`links[${i}]: \`${key}\` ${link[key]} appears more than once`);
321
+ seen.add(link[key]);
322
+ }
50
323
  }
324
+ return {
325
+ version: 1,
326
+ links
327
+ };
51
328
  }
329
+ /** Where the links file is: the layout's `links`, else `<org>/.github-private` and `notifications/<provider>-links.json`. */
330
+ function linksLocation(layout, org, provider) {
331
+ const repo = layout.links?.repo ?? (org ? `${org}/.github-private` : void 0);
332
+ if (!repo) throw new Error("no org to find the links file under — set `layout.links.repo` or `org` in holocron.config.ts");
333
+ return {
334
+ repo,
335
+ path: layout.links?.path ?? `notifications/${provider.toLowerCase()}-links.json`
336
+ };
337
+ }
338
+ // src/commands/notifications-sync-roles/plan.ts
52
339
  /**
53
- * Read the bootstrap token for a provider. Returns `null` for both
54
- * "not stored" and "keyring unavailable" — callers can treat them the
55
- * same way (fall through to env-var precedence).
340
+ * What it takes to make a role's holders equal a team, given who is linked to whom. Pure: it decides, the
341
+ * caller acts. A holder is removed only when a link says they are a person who left the team; a holder
342
+ * nobody has linked is reported, never removed, so an empty or missing links file cannot strip the role from
343
+ * everyone.
56
344
  */
57
- function getToken(provider) {
58
- try {
59
- return new Entry(SERVICE, provider).getPassword();
60
- } catch {
61
- return null;
345
+ function planRoleSync(input) {
346
+ const byGithub = new Map(input.links.map((l) => [l.github, l]));
347
+ const byMember = new Map(input.links.map((l) => [l.member, l]));
348
+ const onTeam = new Set(input.team.map((m) => m.id));
349
+ const holding = new Set(input.holders.map((h) => h.id));
350
+ const plan = {
351
+ add: [],
352
+ remove: [],
353
+ unlinked: [],
354
+ unknownHolders: [],
355
+ inSync: 0
356
+ };
357
+ for (const person of input.team) {
358
+ const link = byGithub.get(person.id);
359
+ if (!link) plan.unlinked.push(person);
360
+ else if (holding.has(link.member)) plan.inSync++;
361
+ else plan.add.push({
362
+ member: link.member,
363
+ login: person.login
364
+ });
365
+ }
366
+ for (const holder of input.holders) {
367
+ const link = byMember.get(holder.id);
368
+ if (!link) plan.unknownHolders.push({
369
+ member: holder.id,
370
+ ...holder.name ? { name: holder.name } : {}
371
+ });
372
+ else if (!onTeam.has(link.github)) plan.remove.push({
373
+ member: holder.id,
374
+ login: link.login
375
+ });
62
376
  }
377
+ return plan;
63
378
  }
64
379
  /**
65
- * Delete a stored token. Returns true when a token was removed, false
66
- * when there was nothing to delete or the keyring is unavailable.
67
- * Distinguishing the two cases isn't worth the surface area — the
68
- * command output makes the situation clear either way.
380
+ * The first role the layout declares for two different teams, or undefined. Names compare ignoring case, as
381
+ * the server does; the role would be synced against one team and then the other, so the last would win.
69
382
  */
70
- function deleteToken(provider) {
71
- try {
72
- return new Entry(SERVICE, provider).deletePassword();
73
- } catch {
74
- return false;
383
+ function roleTeamProblem(layout) {
384
+ const seen = /* @__PURE__ */ new Map();
385
+ for (const role of layout.roles ?? []) {
386
+ if (!role.team) continue;
387
+ const key = role.name.toLowerCase();
388
+ const earlier = seen.get(key);
389
+ 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`;
390
+ seen.set(key, role.team);
75
391
  }
76
392
  }
393
+ // src/commands/notifications-sync-roles/sync-roles.ts
394
+ /** Reads the team and the role's holders and works out what has to change. */
395
+ async function planForRole(args) {
396
+ const [team, holders] = await Promise.all([args.source.teamMembers(args.team, args.org), args.notifications.roleMembers(args.role)]);
397
+ return planRoleSync({
398
+ team,
399
+ links: args.links.links,
400
+ holders
401
+ });
402
+ }
77
403
  /**
78
- * List provider slugs with a stored token in this service scope.
79
- * Uses the library's `findCredentials(service)` — supported on all
80
- * platforms the underlying credential store supports.
404
+ * Makes each role's holders equal its team, one role after another. This is the sync itself, with no setup in
405
+ * front of it: the caller has already picked the providers, read the links and checked the layout. `holocron
406
+ * sync roles` and Sentinel's role sync are two callers of it. A step that fails is recorded and the
407
+ * run goes on; nothing here throws for a provider error. Idempotent: a role that already matches changes nothing.
408
+ * Lines go to `input.print` when it is given, and nowhere otherwise.
81
409
  */
82
- function listStoredProviders() {
410
+ async function syncRoles(input) {
411
+ const print = input.print ?? (() => {});
412
+ const { notifications, source, links, dryRun, keep } = input;
413
+ const result = {
414
+ roles: [],
415
+ failures: [],
416
+ ok: 0,
417
+ skipped: 0
418
+ };
419
+ for (const role of input.roles) {
420
+ print(`\n${style.header(`${role.name} ← team ${role.team}`)}`);
421
+ const step = `role ${role.name}`;
422
+ let plan;
423
+ try {
424
+ plan = await planForRole({
425
+ notifications,
426
+ source,
427
+ role: role.name,
428
+ team: role.team,
429
+ ...input.org ? { org: input.org } : {},
430
+ links
431
+ });
432
+ } catch (err) {
433
+ const message = describeError(err);
434
+ print(` ${style.fail(`${step}: ${message}`)}`);
435
+ result.failures.push({
436
+ step,
437
+ message
438
+ });
439
+ continue;
440
+ }
441
+ const outcome = {
442
+ role: role.name,
443
+ team: role.team,
444
+ plan,
445
+ added: [],
446
+ removed: []
447
+ };
448
+ result.roles.push(outcome);
449
+ result.skipped += plan.inSync;
450
+ if (plan.inSync > 0) print(` ${style.skip(`${plan.inSync} already have it`)}`);
451
+ const act = async (verb, who) => {
452
+ const label = `${verb === "add" ? "gave" : "took"} ${role.name} ${verb === "add" ? "to" : "from"} ${who.login} (${who.member})`;
453
+ if (dryRun || verb === "remove" && keep) {
454
+ print(` ${style.skip(`would ${verb === "add" ? "give" : "take"} ${role.name} ${verb === "add" ? "to" : "from"} ${who.login} (${who.member})${keep && verb === "remove" ? " (kept: --keep)" : ""}`)}`);
455
+ result.skipped++;
456
+ return;
457
+ }
458
+ try {
459
+ if (verb === "add") await notifications.addRoleMember(role.name, who.member);
460
+ else await notifications.removeRoleMember(role.name, who.member);
461
+ (verb === "add" ? outcome.added : outcome.removed).push(who.member);
462
+ print(` ${style.success(label)}`);
463
+ result.ok++;
464
+ } catch (err) {
465
+ const message = describeError(err);
466
+ print(` ${style.fail(`${step}: ${verb} ${who.login}: ${message}`)}`);
467
+ result.failures.push({
468
+ step: `${step} ${verb} ${who.login}`,
469
+ message
470
+ });
471
+ }
472
+ };
473
+ for (const who of plan.add) await act("add", who);
474
+ for (const who of plan.remove) await act("remove", who);
475
+ for (const person of plan.unlinked) {
476
+ print(` ${style.skip(`${person.login} is on the team but has not linked their account`)}`);
477
+ result.skipped++;
478
+ }
479
+ for (const holder of plan.unknownHolders) {
480
+ print(` ${style.skip(`${holder.name ?? holder.member} holds ${role.name} but is not linked to anyone: left alone`)}`);
481
+ result.skipped++;
482
+ }
483
+ }
484
+ return result;
485
+ }
486
+ // src/commands/notifications-sync-roles/notifications-sync-roles.ts
487
+ /** What a source provider needs to be able to do to feed a role sync, or the reason it cannot. */
488
+ function sourceProblem(source) {
489
+ if (!source) return "no `source` provider is available to read the team and the links file";
490
+ if (!source.teamMembers) return `the \`${source.providerName}\` provider cannot list team members`;
491
+ if (!source.readFile) return `the \`${source.providerName}\` provider cannot read the links file`;
492
+ }
493
+ /** Reads the links file; a file that does not exist yet is an empty one, a damaged one throws. */
494
+ async function readLinks(source, layout, org, provider) {
495
+ const { repo, path } = linksLocation(layout, org, provider);
496
+ const file = await source.readFile(path, repo);
497
+ if (!file) return EMPTY_LINKS;
83
498
  try {
84
- return findCredentials(SERVICE).map((c) => c.account);
85
- } catch {
86
- return [];
499
+ return parseLinks(file.content);
500
+ } catch (err) {
501
+ throw new Error(`${repo}/${path}: ${errorMessage(err)}`, { cause: err });
87
502
  }
88
503
  }
89
- //#endregion
90
- //#region src/auth/auth-resolver.ts
91
- /** Wraps `createResolveToken` from `@theholocron/http` and injects the
92
- * system keyring so plugins stay at a one-liner call site. */
93
- function createResolveToken(config) {
94
- return createResolveToken$1({
95
- ...config,
96
- getKeyringToken: getToken
97
- });
504
+ // src/commands/project/plan-pull-request-status/plan-pull-request-status.ts
505
+ /**
506
+ * Decide the status an item's linked pull requests ask for (spec `tech-board-status-automation`, #2388). Pure: it reads
507
+ * one item and the template and touches nothing; status only, never priority or any other field.
508
+ *
509
+ * - an open linked pull request (a draft counts) puts the item in `active`;
510
+ * - an open one whose aggregate check is `success` puts it in `review`;
511
+ * - when the item is in `review` and no open pull request is green, a `failure` moves it back to `active`, while
512
+ * `pending` and `none` leave it, so a re-run after a push does not flicker the board;
513
+ * - no open pull request: no change (closed and merged ones are `planReconcile()`'s, through the closed issue).
514
+ *
515
+ * Left to `planReconcile()`, which runs first: a closed item, an item with an open blocker or in `blocked`, and an
516
+ * item with no status (reported there, not set). An item in `done` is left alone. Where the template has no status of
517
+ * the wanted category the rule comes back as `unresolved` and nothing is guessed; where a category has several statuses
518
+ * the first in template order is used. Applying the change and planning again gives no change.
519
+ */
520
+ function planPullRequestStatus(item, template) {
521
+ if (!item.open || item.status === void 0 || item.blockedBy.length > 0) return void 0;
522
+ const category = template.statuses.find((s) => s.name === item.status)?.category ?? item.category;
523
+ if (category === "blocked" || category === "done") return void 0;
524
+ const open = (item.pullRequests ?? []).filter((pr) => pr.state === "open");
525
+ if (open.length === 0) return void 0;
526
+ let want;
527
+ let reason;
528
+ if (open.some((pr) => pr.checks === "success")) {
529
+ if (category !== "review") [want, reason] = ["review", "checks-green"];
530
+ } else if (category === "review") {
531
+ if (open.some((pr) => pr.checks === "failure")) [want, reason] = ["active", "checks-failed"];
532
+ } else if (category !== "active") [want, reason] = ["active", "pull-request-open"];
533
+ if (want === void 0 || reason === void 0) return void 0;
534
+ const to = template.statuses.find((s) => s.category === want)?.name;
535
+ if (to === void 0) return {
536
+ kind: "unresolved",
537
+ unresolved: {
538
+ key: item.key,
539
+ title: item.title,
540
+ category: want,
541
+ reason
542
+ }
543
+ };
544
+ return {
545
+ kind: "change",
546
+ change: {
547
+ key: item.key,
548
+ title: item.title,
549
+ from: item.status,
550
+ to,
551
+ category: want,
552
+ reason
553
+ }
554
+ };
98
555
  }
556
+ // src/commands/project/plan-reconcile/plan-reconcile.ts
99
557
  /**
100
- * Build a strict, single-feature token resolver.
558
+ * Decide the status changes that keep a board true (spec `command-project`, "Keeping a board true"). Pure: it reads
559
+ * the items and the template and touches nothing. Status only, never priority or any other field.
101
560
  *
102
- * Resolution chain: `--token flag → envName env var → keyring(keyringKey)`.
103
- * No broad-token fallback — if the feature-specific token is absent the
104
- * operation fails with a message naming the exact env var to set.
561
+ * - closed or merged, not in a `done` status: set to `done` (whatever the blockers say);
562
+ * - open with no status: not changed, listed in `unset` (it needs a decision, not a rule; this holds even when it has a
563
+ * blocker);
564
+ * - open with an open blocker, not in a `blocked` status: set to `blocked`;
565
+ * - open, in a `blocked` status, with no open blocker: set to `planned` (the status it held before is unknown).
566
+ *
567
+ * Where a category has several statuses the first in template order is used; where it has none the item is listed in
568
+ * `unresolved` and nothing is guessed. An item's category is read from the template by its status name, falling back
569
+ * to the one the provider reports. Applying the changes and planning again gives no change.
105
570
  */
106
- function createFeatureResolver(config) {
107
- return function resolveFeatureToken(input = {}) {
108
- const env = makeEnv(input.env);
109
- const keyring = input.keyring ?? getToken;
110
- const token = input.cliToken || env.get(config.envName) || keyring(config.keyringKey);
111
- 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>`);
112
- return token;
571
+ function planReconcile(items, template) {
572
+ const target = (category) => template.statuses.find((s) => s.category === category)?.name;
573
+ const plan = {
574
+ changes: [],
575
+ unset: [],
576
+ unresolved: []
113
577
  };
578
+ for (const item of items) {
579
+ const category = item.status === void 0 ? void 0 : template.statuses.find((s) => s.name === item.status)?.category ?? item.category;
580
+ let want;
581
+ let reason;
582
+ if (!item.open) {
583
+ if (category !== "done") [want, reason] = ["done", "closed"];
584
+ } else if (item.status === void 0) {
585
+ plan.unset.push(item);
586
+ continue;
587
+ } else if (item.blockedBy.length > 0) {
588
+ if (category !== "blocked") [want, reason] = ["blocked", "blocked"];
589
+ } else if (category === "blocked") [want, reason] = ["planned", "unblocked"];
590
+ if (want === void 0 || reason === void 0) continue;
591
+ const to = target(want);
592
+ if (to === void 0) {
593
+ plan.unresolved.push({
594
+ key: item.key,
595
+ title: item.title,
596
+ category: want,
597
+ reason
598
+ });
599
+ continue;
600
+ }
601
+ plan.changes.push({
602
+ key: item.key,
603
+ title: item.title,
604
+ ...item.status !== void 0 ? { from: item.status } : {},
605
+ to,
606
+ category: want,
607
+ reason
608
+ });
609
+ }
610
+ return plan;
114
611
  }
115
- //#endregion
116
- //#region src/commands/setup/derived-properties.ts
612
+ // src/commands/project/project-options/project-options.ts
613
+ /** Where a repo's own template files live unless the `templates` option says otherwise. */
614
+ const DEFAULT_TEMPLATES_DIR = ".holocron/projects";
615
+ /**
616
+ * Read the options of `providers.projects`: `org` (the owner, defaulting to `fallbackOwner`, the config's org), `boards`
617
+ * (a list of `{ template, name }`, nothing else about a board is written in the config) and `templates` (the directory
618
+ * of template files). Every problem is listed at once, and two boards with the same name are one.
619
+ */
620
+ function resolveProjectOptions(options, fallbackOwner) {
621
+ const problems = [];
622
+ const org = options.org;
623
+ if (org !== void 0 && (typeof org !== "string" || org.trim() === "")) problems.push("org must be text");
624
+ const owner = typeof org === "string" && org.trim() !== "" ? org : fallbackOwner;
625
+ const dir = options.templates;
626
+ if (dir !== void 0 && (typeof dir !== "string" || dir.trim() === "")) problems.push("templates must be the path of a directory");
627
+ const boards = [];
628
+ if (options.boards !== void 0) {
629
+ if (!Array.isArray(options.boards)) problems.push("boards must be a list of { template, name }");
630
+ else {
631
+ const seen = /* @__PURE__ */ new Set();
632
+ options.boards.forEach((entry, i) => {
633
+ const where = `boards[${i}]`;
634
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
635
+ problems.push(`${where} must be { template, name }`);
636
+ return;
637
+ }
638
+ const { template, name } = entry;
639
+ if (typeof template !== "string" || template.trim() === "") problems.push(`${where} needs a template`);
640
+ if (typeof name !== "string" || name.trim() === "") problems.push(`${where} needs a name`);
641
+ if (typeof template !== "string" || typeof name !== "string" || !template.trim() || !name.trim()) return;
642
+ if (seen.has(name)) problems.push(`${where}: the board name "${name}" is used twice`);
643
+ seen.add(name);
644
+ boards.push({
645
+ template,
646
+ name
647
+ });
648
+ });
649
+ }
650
+ }
651
+ if (problems.length > 0) return {
652
+ ok: false,
653
+ problems
654
+ };
655
+ return {
656
+ ok: true,
657
+ options: {
658
+ owner,
659
+ boards,
660
+ templatesDir: typeof dir === "string" ? dir : DEFAULT_TEMPLATES_DIR
661
+ }
662
+ };
663
+ }
664
+ // src/commands/project/templates/builtin-templates/builtin-templates.ts
665
+ /** The templates that ship in `@theholocron/cli`, by name. A repo's own template with the same name replaces one. */
666
+ const BUILTIN_TEMPLATES = {
667
+ roadmap: {
668
+ name: "roadmap",
669
+ statuses: [
670
+ {
671
+ name: "Someday",
672
+ category: "backlog",
673
+ color: "GRAY",
674
+ description: "Idea or future consideration, not yet planned"
675
+ },
676
+ {
677
+ name: "Todo",
678
+ category: "planned",
679
+ color: "BLUE",
680
+ description: "Planned and ready to be worked on"
681
+ },
682
+ {
683
+ name: "In Progress",
684
+ category: "active",
685
+ color: "YELLOW",
686
+ description: "Currently being worked on"
687
+ },
688
+ {
689
+ name: "In Review",
690
+ category: "review",
691
+ color: "ORANGE",
692
+ description: "Pull request is green and waiting on review"
693
+ },
694
+ {
695
+ name: "Blocked",
696
+ category: "blocked",
697
+ color: "RED",
698
+ description: "Waiting on another issue or an outside change"
699
+ },
700
+ {
701
+ name: "Done",
702
+ category: "done",
703
+ color: "GREEN",
704
+ description: "Completed"
705
+ }
706
+ ],
707
+ fields: [{
708
+ name: "Priority",
709
+ type: "single_select",
710
+ options: [
711
+ "1 · Now",
712
+ "2 · Next",
713
+ "3 · Process"
714
+ ]
715
+ }],
716
+ views: [
717
+ {
718
+ name: "Active",
719
+ layout: "board",
720
+ filter: "-status:Someday -status:Done",
721
+ default: true
722
+ },
723
+ {
724
+ name: "Backlog",
725
+ layout: "board",
726
+ filter: "status:Someday"
727
+ },
728
+ {
729
+ name: "Done",
730
+ layout: "table",
731
+ filter: "status:Done"
732
+ }
733
+ ],
734
+ rules: ["Auto-add sub-issues to project"]
735
+ },
736
+ sprint: {
737
+ name: "sprint",
738
+ statuses: [
739
+ {
740
+ name: "Todo",
741
+ category: "planned",
742
+ color: "BLUE"
743
+ },
744
+ {
745
+ name: "In Progress",
746
+ category: "active",
747
+ color: "YELLOW"
748
+ },
749
+ {
750
+ name: "In Review",
751
+ category: "review",
752
+ color: "ORANGE"
753
+ },
754
+ {
755
+ name: "Blocked",
756
+ category: "blocked",
757
+ color: "RED"
758
+ },
759
+ {
760
+ name: "Done",
761
+ category: "done",
762
+ color: "GREEN"
763
+ }
764
+ ],
765
+ fields: [{
766
+ name: "Sprint",
767
+ type: "text"
768
+ }],
769
+ views: [{
770
+ name: "Active",
771
+ layout: "table",
772
+ filter: "-status:Done",
773
+ default: true
774
+ }, {
775
+ name: "Done",
776
+ layout: "table",
777
+ filter: "status:Done"
778
+ }]
779
+ }
780
+ };
781
+ // src/commands/setup/derived-properties/derived-properties.ts
117
782
  /**
118
783
  * Repo archetype, in priority order:
119
784
  * 1. `*-template` repo name → `template` (independent of package shape).
@@ -153,6 +818,7 @@ function deriveProfile(input) {
153
818
  if (pkg?.private) return "app";
154
819
  return "library";
155
820
  }
821
+ /** The framework and build-tool names `deriveStack()` can detect, in the order it lists them; `StackName` is derived from it. */
156
822
  const KNOWN_STACK_DEPS = [
157
823
  "next",
158
824
  "vite",
@@ -192,6 +858,7 @@ function deriveCapabilities(providers) {
192
858
  * a Phase B (GitHub App) refinement once it can post *why* on a check run.
193
859
  */
194
860
  const REQUIRED_BASELINE = ["source", "ci"];
861
+ /** Whether a repo's capabilities include the required baseline (`source` and `ci`); `non-compliant` means drift. */
195
862
  function deriveCompliance(capabilities) {
196
863
  return REQUIRED_BASELINE.every((key) => capabilities.includes(key)) ? "compliant" : "non-compliant";
197
864
  }
@@ -213,287 +880,273 @@ function missingCapabilities(capabilities) {
213
880
  */
214
881
  async function readWorkspacePackageJsons(repoRoot, workspacePackages) {
215
882
  const results = [];
216
- for (const { slug, dir = "packages" } of workspacePackages) try {
217
- const raw = await readFile(join(repoRoot, dir, slug, "package.json"), "utf8");
218
- results.push(JSON.parse(raw));
219
- } catch {}
883
+ for (const { slug, dir = "packages", path } of workspacePackages) {
884
+ const pkg = await readPackageJson(join(repoRoot, path ?? join(dir, slug)));
885
+ if (pkg) results.push(pkg);
886
+ }
220
887
  return results;
221
888
  }
222
- //#endregion
223
- //#region src/config/config.ts
224
- var ConfigError = class extends Error {
225
- name = "ConfigError";
889
+ // src/commands/setup/labels.ts
890
+ /**
891
+ * The labels every repository gets from `setup`, with their GitHub colours (hex, no `#`) and descriptions. A
892
+ * plugin that makes labels of its own, such as Linear's setup, takes the colour of the one with the same name.
893
+ */
894
+ const CANONICAL_LABELS = [
895
+ {
896
+ name: "bug",
897
+ color: "d73a4a",
898
+ description: "Something isn't working"
899
+ },
900
+ {
901
+ name: "chore",
902
+ color: "ededed",
903
+ description: "Maintenance, no user-facing change"
904
+ },
905
+ {
906
+ name: "ci",
907
+ color: "0075ca",
908
+ description: "CI/CD pipeline changes"
909
+ },
910
+ {
911
+ name: "dependencies",
912
+ color: "0366d6",
913
+ description: "Dependency update"
914
+ },
915
+ {
916
+ name: "documentation",
917
+ color: "0075ca",
918
+ description: "Documentation only"
919
+ },
920
+ {
921
+ name: "duplicate",
922
+ color: "cfd3d7",
923
+ description: "Already reported"
924
+ },
925
+ {
926
+ name: "enhancement",
927
+ color: "a2eeef",
928
+ description: "New feature or request"
929
+ },
930
+ {
931
+ name: "good first issue",
932
+ color: "7057ff",
933
+ description: "Good for newcomers"
934
+ },
935
+ {
936
+ name: "help wanted",
937
+ color: "008672",
938
+ description: "Extra attention needed"
939
+ },
940
+ {
941
+ name: "invalid",
942
+ color: "e4e669",
943
+ description: "Doesn't seem right"
944
+ },
945
+ {
946
+ name: "performance",
947
+ color: "fbca04",
948
+ description: "Performance improvement"
949
+ },
950
+ {
951
+ name: "question",
952
+ color: "d876e3",
953
+ description: "Further information requested"
954
+ },
955
+ {
956
+ name: "refactor",
957
+ color: "cfd3d7",
958
+ description: "Code restructuring"
959
+ },
960
+ {
961
+ name: "released",
962
+ color: "ededed",
963
+ description: "Included in a release"
964
+ },
965
+ {
966
+ name: "test",
967
+ color: "bfd4f2",
968
+ description: "Test-related changes"
969
+ },
970
+ {
971
+ name: "triage",
972
+ color: "e4e669",
973
+ description: "Needs investigation"
974
+ },
975
+ {
976
+ name: "wontfix",
977
+ color: "ffffff",
978
+ description: "Won't be addressed"
979
+ }
980
+ ];
981
+ // src/commands/token-rotation/token-rotation.ts
982
+ /** The rotation policy of a token that declares none: a token is due after 90 days, and an expiry is flagged 14 days ahead. */
983
+ const DEFAULT_TOKEN_ROTATION = {
984
+ maxAgeDays: 90,
985
+ warnDays: 14
226
986
  };
227
- const PLUGIN_PREFIX = "@theholocron/holocron-plugin-";
228
- const COMMUNITY_PREFIX = "holocron-plugin-";
229
- /**
230
- * Resolve `"github"` → `"@theholocron/holocron-plugin-github"`.
231
- * Fully-qualified names (scoped or not) are honored verbatim, which
232
- * is how third-party plugins published outside the org work.
233
- */
234
- function resolvePluginPackage(provider) {
235
- if (!provider) throw new ConfigError("provider name is empty");
236
- if (provider.startsWith("@")) return provider;
237
- if (provider.startsWith(COMMUNITY_PREFIX)) return provider;
238
- if (provider.includes("/")) return provider;
239
- return PLUGIN_PREFIX + provider;
240
- }
241
- /** A bare `[provider, options]` tuple, with both elements present? */
242
- function isOptionsTuple(value) {
243
- if (!Array.isArray(value)) return false;
244
- if (value.length !== 2) return false;
245
- if (typeof value[0] !== "string") return false;
246
- const opt = value[1];
247
- return typeof opt === "object" && opt !== null && !Array.isArray(opt);
248
- }
249
- function normalizeEntry(entry) {
250
- if (typeof entry === "string") return {
251
- provider: entry,
252
- packageName: resolvePluginPackage(entry),
253
- options: {}
254
- };
255
- const [provider, options] = entry;
256
- return {
257
- provider,
258
- packageName: resolvePluginPackage(provider),
259
- options
260
- };
987
+ const DAY_MS = 864e5;
988
+ /** The whole days from `from` to `to`, rounded down (negative once `to` is past). */
989
+ function daysBetween(from, to) {
990
+ return Math.floor((to.getTime() - from.getTime()) / DAY_MS);
261
991
  }
262
- function resolveEntry(key, raw) {
263
- const cardinality = CARDINALITY[key];
264
- if (typeof raw === "string") {
265
- if (cardinality === "many") throw new ConfigError(`\`${key}\` accepts multiple providers; wrap a single one in an array: ["${raw}"]`);
266
- return {
267
- cardinality: "single",
268
- tuple: normalizeEntry(raw)
269
- };
270
- }
271
- if (!Array.isArray(raw)) throw new ConfigError(`\`${key}\` entry must be a string or array, got ${typeof raw}`);
272
- if (isOptionsTuple(raw)) {
273
- if (cardinality === "many") return {
274
- cardinality: "many",
275
- tuples: [normalizeEntry(raw)]
276
- };
277
- return {
278
- cardinality: "single",
279
- tuple: normalizeEntry(raw)
280
- };
281
- }
282
- if (cardinality === "single") throw new ConfigError(`\`${key}\` accepts exactly one provider; got a multi-provider list with ${raw.length} entries`);
283
- return {
284
- cardinality: "many",
285
- tuples: raw.map((entry, idx) => {
286
- if (typeof entry === "string") return normalizeEntry(entry);
287
- if (isOptionsTuple(entry)) return normalizeEntry(entry);
288
- throw new ConfigError(`\`${key}[${idx}]\` must be a provider string or [provider, options] tuple`);
289
- })
290
- };
992
+ /** `2026-11-13` of a valid date. */
993
+ const day = (d) => d.toISOString().slice(0, 10);
994
+ /** A valid `Date` of an ISO string, or `undefined` when there is none or it does not parse. */
995
+ function parse(value) {
996
+ if (value === void 0) return void 0;
997
+ const date = new Date(value);
998
+ return Number.isNaN(date.getTime()) ? void 0 : date;
291
999
  }
292
- function resolveConfig(raw) {
293
- if (!raw.name) throw new ConfigError("`name` is required");
294
- if (!raw.providers || typeof raw.providers !== "object") throw new ConfigError("`providers` block is required");
295
- const providers = {};
296
- for (const [key, entry] of Object.entries(raw.providers)) {
297
- if (entry === void 0) continue;
298
- providers[key] = resolveEntry(key, entry);
299
- }
300
- for (const required of REQUIRED_CAPABILITIES) if (!providers[required]) throw new ConfigError(`required capability \`${required}\` is missing from providers`);
301
- let docs;
302
- if (raw.docs !== void 0) {
303
- if (!raw.docs.build) throw new ConfigError("`docs.build` is required when `docs` is set");
304
- docs = raw.docs;
305
- }
306
- const homepage = raw.homepage ?? (docs?.domain ? `https://${docs.domain}/` : void 0);
307
- return {
308
- name: raw.name,
309
- description: raw.description,
310
- homepage,
311
- org: raw.org,
312
- domain: raw.domain,
313
- repo: raw.repo,
314
- tasks: raw.tasks,
315
- syncScripts: raw.syncScripts,
316
- holocronScript: raw.holocronScript,
317
- extraRequiredChecks: raw.extraRequiredChecks,
318
- hooks: raw.hooks,
319
- providers,
320
- apps: raw.apps ?? [],
321
- doctor: raw.doctor ?? {},
322
- agent: raw.agent,
323
- skills: raw.skills,
324
- docs,
325
- env: raw.env,
326
- log: raw.log,
327
- telemetry: raw.telemetry
328
- };
329
- }
330
- //#endregion
331
- //#region src/config/compose.ts
332
- function taskName(e) {
333
- return typeof e === "string" ? e : e.name;
1000
+ /**
1001
+ * Rows saying whether a token is due for rotation, from what its provider exposes. Provider-neutral: a token probe reads
1002
+ * the lifetime however its provider offers it and hands it here, with the layer's `rotation` from `tokenExpectations()`.
1003
+ * `lifetime` is `undefined` when the provider exposes nothing (the row says so rather than passing), and a date the
1004
+ * provider gave that does not parse is an `info` row, never a pass. An expired or near-expiry token fails, and so does
1005
+ * one older than `maxAgeDays`. Only dates are printed, never the token.
1006
+ */
1007
+ function tokenRotationRows(lifetime, rotation, now) {
1008
+ if (!lifetime) return [{
1009
+ status: "info",
1010
+ label: "rotation",
1011
+ detail: `the provider does not expose this token's age or expiry; rotate it by hand every ${rotation.maxAgeDays} days`
1012
+ }];
1013
+ const rows = [];
1014
+ const expires = parse(lifetime.expiresAt);
1015
+ if (lifetime.expiresAt !== void 0 && !expires) rows.push({
1016
+ status: "info",
1017
+ label: "expiry",
1018
+ detail: "the provider's expiry date could not be read"
1019
+ });
1020
+ else if (expires) {
1021
+ const left = daysBetween(now, expires);
1022
+ if (expires.getTime() <= now.getTime()) rows.push({
1023
+ status: "fail",
1024
+ label: "expiry",
1025
+ detail: `expired on ${day(expires)}`
1026
+ });
1027
+ else if (left < rotation.warnDays) rows.push({
1028
+ status: "fail",
1029
+ label: "expiry",
1030
+ detail: `expires on ${day(expires)} (${left} days left, warns under ${rotation.warnDays}); rotate it`
1031
+ });
1032
+ else rows.push({
1033
+ status: "ok",
1034
+ label: "expiry",
1035
+ detail: `expires on ${day(expires)} (${left} days left)`
1036
+ });
1037
+ } else rows.push({
1038
+ status: "info",
1039
+ label: "expiry",
1040
+ detail: "the token has no expiry"
1041
+ });
1042
+ const created = parse(lifetime.createdAt);
1043
+ if (lifetime.createdAt !== void 0 && !created) rows.push({
1044
+ status: "info",
1045
+ label: "age",
1046
+ detail: "the provider's creation date could not be read"
1047
+ });
1048
+ else if (created) {
1049
+ const age = daysBetween(created, now);
1050
+ const due = age > rotation.maxAgeDays;
1051
+ rows.push({
1052
+ status: due ? "fail" : "ok",
1053
+ label: "age",
1054
+ 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})`
1055
+ });
1056
+ } else rows.push({
1057
+ status: "info",
1058
+ label: "age",
1059
+ detail: "the provider does not say when the token was made"
1060
+ });
1061
+ return rows;
334
1062
  }
1063
+ // src/commands/token-expectations/token-expectations.ts
335
1064
  /**
336
- * Merge any number of capability fragments into a single preset object that
337
- * spreads directly into `defineConfig()`.
338
- *
339
- * - Accepts individual capabilities or nested arrays (for bundle presets).
340
- * - Deduplicates by `id` — when the same ID appears more than once, the last
341
- * occurrence wins. This lets callers override bundle defaults by listing an
342
- * explicit capability after the bundle.
343
- * - Validates all `requires` at call time and throws `ConfigError` if any are
344
- * unmet, listing every missing dependency in a single message.
345
- *
346
- * @example
347
- * // docs-only site — no typecheck
348
- * const preset = compose(node(), docs());
349
- *
350
- * // library with docs
351
- * const preset = compose(node(), typecheck(), docs());
352
- *
353
- * // nextjs() is a bundle that returns Capability[]
354
- * const preset = compose(node(), nextjs());
355
- */
356
- function compose(...args) {
357
- const flat = args.flat();
358
- const byId = /* @__PURE__ */ new Map();
359
- for (const cap of flat) byId.set(cap.id, cap);
360
- const caps = [...byId.values()];
361
- const available = new Set(caps.map((c) => c.id));
362
- const errors = [];
363
- for (const cap of caps) for (const req of cap.requires ?? []) if (!available.has(req)) errors.push(`"${cap.id}" requires "${req}"`);
364
- if (errors.length > 0) throw new ConfigError(`compose(): unmet dependencies — ${errors.join(", ")}`);
365
- const taskMap = /* @__PURE__ */ new Map();
366
- for (const cap of caps) for (const entry of cap.tasks ?? []) taskMap.set(taskName(entry), entry);
367
- let providers = {};
368
- for (const cap of caps) if (cap.providers) providers = {
369
- ...providers,
370
- ...cap.providers
371
- };
372
- const checksSeen = /* @__PURE__ */ new Set();
373
- const extraRequiredChecks = [];
374
- for (const cap of caps) for (const check of cap.extraRequiredChecks ?? []) if (!checksSeen.has(check)) {
375
- checksSeen.add(check);
376
- extraRequiredChecks.push(check);
377
- }
378
- let repo = {};
379
- for (const cap of caps) {
380
- if (!cap.repo) continue;
381
- const { properties, topics, teams, ...scalars } = cap.repo;
382
- repo = {
383
- ...repo,
384
- ...scalars
385
- };
386
- if (properties) repo.properties = {
387
- ...repo.properties,
388
- ...properties
389
- };
390
- if (topics) {
391
- const merged = /* @__PURE__ */ new Set([...repo.topics ?? [], ...topics]);
392
- repo.topics = [...merged];
393
- }
394
- if (teams) {
395
- const teamMap = new Map((repo.teams ?? []).map((t) => [typeof t === "string" ? t : t.slug, t]));
396
- for (const t of teams) teamMap.set(typeof t === "string" ? t : t.slug, t);
397
- repo.teams = [...teamMap.values()];
1065
+ * Reads what a plugin's tokens declare (`PluginToken.expect`) as one entry per token and layer that holds it, in the
1066
+ * order of `ENVIRONMENT_LAYERS`. The one reader the token probes, the doctor and the docs check share, so none of them
1067
+ * walks the declaration itself. A token with no `expect` yields nothing; a layer no token holds is never listed.
1068
+ */
1069
+ function tokenExpectations(tokens, filter = {}) {
1070
+ const found = [];
1071
+ for (const token of tokens) {
1072
+ if (!token.expect || filter.envName !== void 0 && token.envName !== filter.envName) continue;
1073
+ const { layers = [], permissions = {} } = token.expect;
1074
+ for (const layer of ENVIRONMENT_LAYERS) {
1075
+ if (filter.layer !== void 0 && filter.layer !== layer) continue;
1076
+ const rules = permissions[layer];
1077
+ if (!rules && !layers.includes(layer)) continue;
1078
+ const entries = Object.entries(rules ?? {});
1079
+ found.push({
1080
+ envName: token.envName,
1081
+ layer,
1082
+ rules: rules ?? {},
1083
+ required: entries.filter(([, rule]) => rule === "required").map(([name]) => name),
1084
+ absent: entries.filter(([, rule]) => rule === "absent").map(([name]) => name),
1085
+ rotation: {
1086
+ ...DEFAULT_TOKEN_ROTATION,
1087
+ ...token.expect.rotation
1088
+ }
1089
+ });
398
1090
  }
399
1091
  }
400
- let org;
401
- let domain;
402
- let docs;
403
- for (const cap of caps) {
404
- if (cap.org !== void 0) org = cap.org;
405
- if (cap.domain !== void 0) domain = cap.domain;
406
- if (cap.docs !== void 0) docs = cap.docs;
407
- }
408
- return {
409
- tasks: [...taskMap.values()],
410
- providers,
411
- repo,
412
- extraRequiredChecks,
413
- ...org !== void 0 ? { org } : {},
414
- ...domain !== void 0 ? { domain } : {},
415
- ...docs !== void 0 ? { docs } : {}
416
- };
1092
+ return found;
417
1093
  }
418
- //#endregion
419
- //#region src/config/define-config.ts
420
- function defineConfig(config) {
421
- return config;
1094
+ // src/commands/auth-export/stdout-kind/stdout-kind.ts
1095
+ /**
1096
+ * What file descriptor `fd` (stdout) is, for deciding where tokens may go: a `terminal`, a `pipe` (a FIFO, or the
1097
+ * socket some shells and runners use for one), or `other` (a regular file, a device, or anything that cannot be
1098
+ * inspected). Only a pipe is safe to write the lines to, so anything unknown is `other`.
1099
+ */
1100
+ function stdoutKind(isTerminal, fd = 1, stat = fstatSync) {
1101
+ if (isTerminal) return "terminal";
1102
+ try {
1103
+ const s = stat(fd);
1104
+ return s.isFIFO() || s.isSocket() ? "pipe" : "other";
1105
+ } catch {
1106
+ return "other";
1107
+ }
422
1108
  }
423
- //#endregion
424
- //#region src/config/load-config.ts
1109
+ // src/commands/secrets-sync/resolve-environment-id/resolve-environment-id.ts
425
1110
  /**
426
- * `holocron.config.{ts,js,mjs,cjs,json}` loader.
427
- *
428
- * File discovery + module loading (typed configs via `tsx`, no build
429
- * step) is delegated to `@theholocron/datapad`. This module keeps the
430
- * holocron-specific parts: filling `name` / `repo.name` defaults and
431
- * running the config through `resolveConfig`.
1111
+ * The vault Environment `holocron sync secrets --env <environment>` reads. A layer word (`local`, `dev`, `ci`, `prod`) is the
1112
+ * Environment of that layer of this repository, `<org/repo> - <layer>`; any other text is a literal Environment name.
1113
+ * A literal name wins only when it is not exactly a layer word, so an Environment that is itself called `prod` cannot be
1114
+ * addressed by that name (spec `tech-environment-layers`, #2069).
432
1115
  *
433
- * Probe order is TS-first (`.ts` → `.js` → `.mjs` → `.cjs` → `.json`) —
434
- * see ADR-0010 / issue #75 / #81.
1116
+ * @param id - The `--env` value the user gave.
1117
+ * @param input - Where the repository is (its `origin` remote is read there), and optionally how to read it.
1118
+ * @throws {ConfigError} For a layer word when the remote cannot be read (the message names the `environment` option).
435
1119
  */
436
- const execFileAsync = promisify(execFile);
1120
+ async function resolveEnvironmentId(id, input) {
1121
+ if (!isEnvironmentLayer(id)) return id;
1122
+ return layerEnvironment(await repoSlug(input.repoRoot, input.gitExec), id);
1123
+ }
1124
+ // src/private-dir/ignore-advice/ignore-advice.ts
1125
+ /** The line that says how to fix a credentials path the version control ignore rules do not cover. */
1126
+ function ignoreAdvice(isDefault, choose) {
1127
+ return isDefault ? "the private directory's ignore rule is missing: run `holocron sync` to add it" : `add it to .gitignore, or ${choose}`;
1128
+ }
1129
+ /** The file `export tokens` and `new github-app` write by default, relative to the repository root. */
1130
+ const PRIVATE_CREDENTIALS_FILE = `.holocron/.private/.credentials`;
1131
+ // src/private-dir/resolve-credentials-file/resolve-credentials-file.ts
437
1132
  /**
438
- * Read + parse + resolve `holocron.config.*` from the given directory.
439
- * Throws {@link ConfigFileError} when nothing is found or a file cannot
440
- * be loaded, or `ConfigError` when the config is invalid.
1133
+ * The credentials file for a command: `file` (relative to `base`) when given, else `.holocron/.private/.credentials`
1134
+ * under `base`. The default's directory is created when missing (owner-only), because the ignore check can only ask
1135
+ * about a path whose directory exists and the file cannot be written without it.
441
1136
  */
442
- async function loadConfig(cwd) {
443
- const found = await loadConfigFile({
444
- cwd,
445
- name: "holocron"
446
- });
447
- 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.`);
1137
+ function resolveCredentialsFile(base, file, makeDir = (dir) => void mkdirSync(dir, {
1138
+ recursive: true,
1139
+ mode: 448
1140
+ })) {
1141
+ if (file) return {
1142
+ path: resolve(base, file),
1143
+ isDefault: false
1144
+ };
1145
+ const path = resolve(base, PRIVATE_CREDENTIALS_FILE);
1146
+ makeDir(dirname(path));
448
1147
  return {
449
- resolved: resolveConfig(await deriveDefaults(dirname(found.filepath), found.config)),
450
- filepath: found.filepath
1148
+ path,
1149
+ isDefault: true
451
1150
  };
452
1151
  }
453
- async function deriveDefaults(configDir, raw) {
454
- const result = { ...raw };
455
- if (!result.name) result.name = await readPackageJsonName(configDir) ?? basename(configDir);
456
- if (result.repo && !result.repo.name) {
457
- const repoName = await readGitRemote(configDir);
458
- if (repoName) result.repo = {
459
- ...result.repo,
460
- name: repoName
461
- };
462
- }
463
- const manifest = await loadTasksConfig(configDir);
464
- if (manifest.tasks) result.tasks = manifest.tasks;
465
- if (manifest.syncScripts !== void 0) result.syncScripts = manifest.syncScripts;
466
- if (manifest.holocronScript !== void 0) result.holocronScript = manifest.holocronScript;
467
- if (manifest.hooks !== void 0) result.hooks = manifest.hooks;
468
- if (manifest.extraRequiredChecks) result.extraRequiredChecks = [...result.extraRequiredChecks ?? [], ...manifest.extraRequiredChecks];
469
- return result;
470
- }
471
- async function readPackageJsonName(dir) {
472
- try {
473
- const content = await readFile(join(dir, "package.json"), "utf8");
474
- const pkg = JSON.parse(content);
475
- return typeof pkg.name === "string" ? pkg.name.replace(/^@[^/]+\//, "") : void 0;
476
- } catch {
477
- return;
478
- }
479
- }
480
- async function readGitRemote(dir) {
481
- try {
482
- const { stdout } = await execFileAsync("git", [
483
- "remote",
484
- "get-url",
485
- "origin"
486
- ], { cwd: dir });
487
- return parseGitRemoteUrl(stdout.trim());
488
- } catch {
489
- return;
490
- }
491
- }
492
- function parseGitRemoteUrl(url) {
493
- const httpsMatch = url.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/);
494
- if (httpsMatch) return httpsMatch[1];
495
- const sshMatch = url.match(/github\.com:([^/]+\/[^/]+?)(?:\.git)?$/);
496
- if (sshMatch) return sshMatch[1];
497
- }
498
- //#endregion
499
- export { AuthError, CARDINALITY, ConfigError, ConfigFileError, ProviderApiError, REQUIRED_CAPABILITIES, WebhookVerificationError, compose, createFeatureResolver, createResolveToken, createRestClient, defineConfig, deleteToken, deriveCapabilities, deriveCompliance, deriveProfile, deriveStack, getToken, isMulti, listStoredProviders, loadConfig, missingCapabilities, readWorkspacePackageJsons, resolveConfig, resolveEntry, resolvePluginPackage, setToken };
1152
+ export { 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, SHARED_AREAS, WebhookVerificationError, compose, connectionProbe, coverageExpectations, createFeatureResolver, createResolveToken, createRestClient, credentialsEnvironment, defineConfig, deriveCapabilities, deriveCompliance, deriveProfile, deriveStack, emojiConflictProblem, ignoreAdvice, isMulti, keyring, layoutEmojis, loadConfig, loadEmojiImage, missingCapabilities, orderKeys, parseReaction, pickByCreation, placeAreas, planPullRequestStatus, planReconcile, reactionProblem, reactionSpelling, readKeysLimited, readLinks, readWorkspacePackageJsons, reportProgress, resolveConfig, resolveCredentialsFile, resolveEntry, resolveEnvironmentId, resolvePluginPackage, resolveProjectOptions, resolveValue, roleTeamProblem, sourceProblem, stdoutKind, syncRoles, tokenExpectations, tokenRotationRows };