@theholocron/cli 5.0.0-alpha.33 → 5.0.0-alpha.330

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,14 +1,20 @@
1
- import { CARDINALITY, ProviderApiError, REQUIRED_CAPABILITIES, WebhookVerificationError, isMulti } from "./plugin/capabilities.mjs";
1
+ import { CARDINALITY, ElevationRequiredError, MissingTokenError, ProviderApiError, REQUIRED_CAPABILITIES, WebhookVerificationError, isMulti } from "./plugin/capabilities.mjs";
2
+ import { a as resolveEntry, i as resolveConfig, n as ConfigError, o as resolvePluginPackage, r as credentialsEnvironment, t as compose } from "./compose-DU_NeIR0.mjs";
2
3
  import { AuthError, createResolveToken as createResolveToken$1, createRestClient } from "@theholocron/http-client";
3
- import { createEnvLookup } from "@theholocron/env-utils";
4
+ import { createEnvLookup, withEnvPrefix } from "@theholocron/env-utils/lookup";
4
5
  import { Entry, findCredentials } from "@napi-rs/keyring";
5
- import { readFile } from "node:fs/promises";
6
+ import { errorMessage } from "@theholocron/misc-utils";
6
7
  import { basename, dirname, join } from "node:path";
7
- import { execFile } from "node:child_process";
8
- import { promisify } from "node:util";
8
+ import chalk from "chalk";
9
+ import { lookup } from "node:dns/promises";
10
+ import { readPackageJson } from "@theholocron/pkg-utils";
9
11
  import { loadTasksConfig } from "@theholocron/astromech/config";
10
12
  import { ConfigFileError, ConfigFileError as ConfigFileError$1, loadConfigFile } from "@theholocron/datapad";
11
- createEnvLookup();
13
+ import { readGitRemote } from "@theholocron/git-utils";
14
+ // src/env/env.ts
15
+ /** Singleton env for simple global lookups throughout the CLI. */
16
+ const env = createEnvLookup();
17
+ withEnvPrefix(env, "HOLOCRON");
12
18
  /**
13
19
  * Create an injectable env for commands that accept a fake env in tests.
14
20
  * Pass `input.env` when available, falls back to `process.env`.
@@ -16,8 +22,30 @@ createEnvLookup();
16
22
  function makeEnv(source) {
17
23
  return createEnvLookup(source);
18
24
  }
19
- //#endregion
20
- //#region src/auth/keyring.ts
25
+ // src/auth/credential-store/credential-store.ts
26
+ /**
27
+ * The variables the `credentials` providers returned, kept for the life of the process.
28
+ *
29
+ * The plugin loader reads each provider once (`setCredentials`), and the token resolvers look a token up here
30
+ * (`getCredential`) after the flag and the process environment and before the keyring. It is in memory only: the
31
+ * values were already in this process when the provider returned them, and nothing here writes them anywhere.
32
+ *
33
+ * A source is one provider's answer for one environment. They are kept in the order they were set, which is the
34
+ * order `holocron.config` lists the providers, and the first source that has a value wins.
35
+ */
36
+ const sources = /* @__PURE__ */ new Map();
37
+ /**
38
+ * The first non-empty value for any of `names`, from the first source that has one. Sources are tried in the order
39
+ * they were set; within a source the names are tried in the order given (the project's own variable name before the
40
+ * vendor's). `undefined` when no source has one.
41
+ */
42
+ function getCredential(...names) {
43
+ for (const variables of sources.values()) for (const name of names) {
44
+ const value = variables[name];
45
+ if (value) return value;
46
+ }
47
+ }
48
+ // src/auth/keyring/keyring.ts
21
49
  /**
22
50
  * Keyring-backed bootstrap credential store.
23
51
  *
@@ -38,27 +66,64 @@ function makeEnv(source) {
38
66
  */
39
67
  const SERVICE = "com.theholocron.cli";
40
68
  /**
69
+ * What `getToken` has already read, by provider, for the life of this process. A miss (`null`) is remembered too, so
70
+ * a token that is not stored, or a keyring that is unavailable, is asked about once, not on every lookup. The OS
71
+ * keyring can prompt on each read, and several resolvers ask for the same entry in one command.
72
+ *
73
+ * It lives in memory only. A cache that outlived the process would mean writing tokens somewhere else, which is
74
+ * what the keyring is there to avoid.
75
+ */
76
+ const cache = /* @__PURE__ */ new Map();
77
+ /**
78
+ * Forget every token `getToken` has remembered, so the next read asks the keyring again. `setToken` and
79
+ * `deleteToken` already keep the cache right for what they change; this is for a test, or after the keyring was
80
+ * changed from outside the process.
81
+ */
82
+ function clearTokenCache() {
83
+ cache.clear();
84
+ }
85
+ /**
41
86
  * Store or overwrite a bootstrap token for a provider. Returns true on
42
87
  * success, false when the underlying keyring is unsupported or errored.
43
88
  */
44
89
  function setToken(provider, token) {
45
90
  try {
46
91
  new Entry(SERVICE, provider).setPassword(token);
92
+ cache.set(provider, token);
47
93
  return true;
48
94
  } catch {
95
+ cache.delete(provider);
49
96
  return false;
50
97
  }
51
98
  }
52
99
  /**
53
100
  * Read the bootstrap token for a provider. Returns `null` for both
54
101
  * "not stored" and "keyring unavailable" — callers can treat them the
55
- * same way (fall through to env-var precedence).
102
+ * same way (fall through to env-var precedence). The answer is
103
+ * remembered for the rest of the process, so the keyring is asked once
104
+ * per provider.
56
105
  */
57
106
  function getToken(provider) {
107
+ if (cache.has(provider)) return cache.get(provider);
108
+ let token;
58
109
  try {
59
- return new Entry(SERVICE, provider).getPassword();
110
+ token = new Entry(SERVICE, provider).getPassword();
60
111
  } catch {
61
- return null;
112
+ token = null;
113
+ }
114
+ cache.set(provider, token);
115
+ return token;
116
+ }
117
+ /**
118
+ * Whether the OS keyring can be used at all. `getToken` answers `null` for a missing entry and for a keyring that
119
+ * cannot be reached alike; a caller that must tell an outage from an empty keyring asks this first.
120
+ */
121
+ function isKeyringAvailable() {
122
+ try {
123
+ findCredentials(SERVICE);
124
+ return true;
125
+ } catch {
126
+ return false;
62
127
  }
63
128
  }
64
129
  /**
@@ -69,8 +134,11 @@ function getToken(provider) {
69
134
  */
70
135
  function deleteToken(provider) {
71
136
  try {
72
- return new Entry(SERVICE, provider).deletePassword();
137
+ const removed = new Entry(SERVICE, provider).deletePassword();
138
+ cache.set(provider, null);
139
+ return removed;
73
140
  } catch {
141
+ cache.delete(provider);
74
142
  return false;
75
143
  }
76
144
  }
@@ -86,34 +154,447 @@ function listStoredProviders() {
86
154
  return [];
87
155
  }
88
156
  }
89
- //#endregion
90
- //#region src/auth/auth-resolver.ts
157
+ // src/auth/auth-resolver/auth-resolver.ts
91
158
  /** Wraps `createResolveToken` from `@theholocron/http` and injects the
92
159
  * system keyring so plugins stay at a one-liner call site. */
93
160
  function createResolveToken(config) {
94
- return createResolveToken$1({
161
+ const storedOrKeyring = (provider) => getCredential(config.envName, config.vendorEnvName) ?? getToken(provider);
162
+ return Object.assign(createResolveToken$1({
95
163
  ...config,
96
- getKeyringToken: getToken
97
- });
164
+ getKeyringToken: storedOrKeyring
165
+ }), { token: {
166
+ envName: config.envName,
167
+ vendorEnvName: config.vendorEnvName,
168
+ keyringKey: config.keyringService
169
+ } });
98
170
  }
99
171
  /**
100
172
  * Build a strict, single-feature token resolver.
101
173
  *
102
- * Resolution chain: `--token flag → envName env var → keyring(keyringKey)`.
174
+ * Resolution chain: `--token flag → envName env var → the `credentials` providers' envName → keyring(keyringKey)`.
103
175
  * No broad-token fallback — if the feature-specific token is absent the
104
176
  * operation fails with a message naming the exact env var to set.
105
177
  */
106
178
  function createFeatureResolver(config) {
107
- return function resolveFeatureToken(input = {}) {
179
+ const resolveFeatureToken = (input = {}) => {
108
180
  const env = makeEnv(input.env);
109
- const keyring = input.keyring ?? getToken;
181
+ const keyring = input.keyring ?? ((provider) => getCredential(config.envName) ?? getToken(provider));
110
182
  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>`);
183
+ if (!token) throw new AuthError(`no ${config.vendor ?? "GitHub"} token found for this operation. Pass --token <token>, set ${config.envName}, or run: holocron auth set ${config.keyringKey} <token>`);
112
184
  return token;
113
185
  };
186
+ return Object.assign(resolveFeatureToken, { token: {
187
+ envName: config.envName,
188
+ keyringKey: config.keyringKey
189
+ } });
190
+ }
191
+ // src/ui/style/style.ts
192
+ const style = {
193
+ success: (msg) => `${chalk.green("✓")} ${msg}`,
194
+ warn: (msg) => `${chalk.yellow("⚠")} ${msg}`,
195
+ fail: (msg) => `${chalk.red("✗")} ${msg}`,
196
+ step: (msg) => `${chalk.cyan("→")} ${msg}`,
197
+ /** A dim `·` marker for a row that's neither a pass nor a failure — loaded but inactive, or skipped. */
198
+ skip: (msg) => chalk.dim(`· ${msg}`),
199
+ hint: (msg) => chalk.dim(msg),
200
+ dim: (msg) => chalk.dim(msg),
201
+ header: (msg) => chalk.bold(msg)
202
+ };
203
+ // src/plugin/connection-probe/connection-probe.ts
204
+ const TLS_CODES = /* @__PURE__ */ new Set([
205
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
206
+ "SELF_SIGNED_CERT_IN_CHAIN",
207
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
208
+ "CERT_HAS_EXPIRED",
209
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
210
+ "ERR_TLS_CERT_ALTNAME_INVALID"
211
+ ]);
212
+ /** The code Node attaches to a network failure, with that error's message: on the error itself, or on its `cause` (where `fetch` puts it). */
213
+ function codeOf(err) {
214
+ for (let e = err, depth = 0; e && depth < 4; depth++) {
215
+ if (typeof e.code === "string") return {
216
+ code: e.code,
217
+ message: String(e.message ?? "")
218
+ };
219
+ e = e.cause;
220
+ }
221
+ }
222
+ /** A network failure in plain words, with what usually causes it. Never includes anything from a request. */
223
+ function describeNetworkError(err, timeoutMs) {
224
+ const found = codeOf(err);
225
+ const code = found?.code;
226
+ const name = err?.name;
227
+ if (name === "TimeoutError" || name === "AbortError" || code === "UND_ERR_CONNECT_TIMEOUT" || code === "ETIMEDOUT") return `no answer within ${timeoutMs / 1e3}s (${code ?? name}): a firewall, VPN or proxy may be dropping it`;
228
+ switch (code) {
229
+ case "ENOTFOUND":
230
+ case "EAI_AGAIN": return `${code}: the name did not resolve; check your network and DNS`;
231
+ case "ECONNREFUSED": return "ECONNREFUSED: the host refused the connection";
232
+ case "ECONNRESET":
233
+ case "UND_ERR_SOCKET": return `${code}: the connection was cut off; a proxy or firewall may be interfering`;
234
+ case "ENETUNREACH":
235
+ case "EHOSTUNREACH": return `${code}: no route to the host; check that you are online`;
236
+ default:
237
+ if (code && TLS_CODES.has(code)) return `${code}: the TLS certificate was not trusted; a corporate proxy that re-signs traffic needs NODE_EXTRA_CA_CERTS`;
238
+ return found ? `${found.code}: ${found.message}` : String(err?.message ?? err);
239
+ }
240
+ }
241
+ /**
242
+ * The `connection` probe every provider offers, for telling a network problem from a credential problem: does the name
243
+ * resolve, does the host answer, is there a token, and does the provider accept it. A step that cannot work because an
244
+ * earlier one failed is reported as not tried rather than failing a second time for the same reason.
245
+ */
246
+ function connectionProbe(input) {
247
+ const timeoutMs = input.timeoutMs ?? 1e4;
248
+ return {
249
+ summary: `Check the network path to ${input.provider} and that it accepts your token.`,
250
+ writes: false,
251
+ async run(probe) {
252
+ let reachable = true;
253
+ if (input.url) {
254
+ const host = new URL(input.url).hostname;
255
+ const lookup$1 = input.lookup ?? (input.fetch ? void 0 : (h) => lookup(h));
256
+ if (lookup$1) try {
257
+ const { address } = await lookup$1(host);
258
+ probe.say({
259
+ status: "ok",
260
+ label: `DNS ${host}`,
261
+ detail: address
262
+ });
263
+ } catch (err) {
264
+ reachable = false;
265
+ probe.say({
266
+ status: "fail",
267
+ label: `DNS ${host}`,
268
+ detail: describeNetworkError(err, timeoutMs)
269
+ });
270
+ }
271
+ if (reachable) {
272
+ const started = Date.now();
273
+ try {
274
+ const res = await (input.fetch ?? fetch)(input.url, {
275
+ method: "GET",
276
+ signal: AbortSignal.timeout(timeoutMs)
277
+ });
278
+ probe.say({
279
+ status: "ok",
280
+ label: `reach ${host}`,
281
+ detail: `HTTP ${res.status} in ${Date.now() - started} ms`
282
+ });
283
+ } catch (err) {
284
+ reachable = false;
285
+ probe.say({
286
+ status: "fail",
287
+ label: `reach ${host}`,
288
+ detail: describeNetworkError(err, timeoutMs)
289
+ });
290
+ }
291
+ } else probe.say({
292
+ status: "info",
293
+ label: `reach ${host}`,
294
+ detail: "not tried: the name did not resolve"
295
+ });
296
+ }
297
+ let token;
298
+ try {
299
+ token = await input.token();
300
+ } catch (err) {
301
+ probe.say({
302
+ status: "fail",
303
+ label: "token",
304
+ detail: err.message
305
+ });
306
+ probe.say({
307
+ status: "info",
308
+ label: "accepted",
309
+ detail: "not tried: there is no token"
310
+ });
311
+ return;
312
+ }
313
+ probe.secret(token);
314
+ probe.say({
315
+ status: "ok",
316
+ label: "token",
317
+ detail: "found"
318
+ });
319
+ if (!reachable) {
320
+ probe.say({
321
+ status: "info",
322
+ label: "accepted",
323
+ detail: "not tried: the host could not be reached"
324
+ });
325
+ return;
326
+ }
327
+ const result = await input.verify(token);
328
+ probe.say(result.ok ? {
329
+ status: "ok",
330
+ label: "accepted",
331
+ detail: result.subject
332
+ } : {
333
+ status: "fail",
334
+ label: "accepted",
335
+ detail: result.message
336
+ });
337
+ }
338
+ };
339
+ }
340
+ // src/ui/provider-error/provider-error.ts
341
+ /** Vendor response bodies land in the terminal — cap their length so one
342
+ * oversized error can't flood the report, and strip control characters
343
+ * (newlines and the C1 range, whose 0x9b is an 8-bit CSI) so a crafted body
344
+ * can't forge extra report lines or inject terminal escape sequences. */
345
+ const MAX_DETAIL_LENGTH = 200;
346
+ /** Control characters (newlines and the C1 range included) turned into spaces, whitespace collapsed, no length cap. */
347
+ function stripControl(text) {
348
+ return text.replace(/[\x00-\x1f\x7f-\x9f]/g, " ").replace(/\s+/g, " ").trim();
349
+ }
350
+ function sanitizeDetail(text) {
351
+ const stripped = stripControl(text);
352
+ return stripped.length > MAX_DETAIL_LENGTH ? `${stripped.slice(0, MAX_DETAIL_LENGTH)}…` : stripped;
353
+ }
354
+ /**
355
+ * `errorMessage(err)` alone is just `"<Vendor> <METHOD> <path> → <status>"` —
356
+ * the actual reason (what the vendor's response body said) lives in
357
+ * `ProviderApiError.details`, a raw response-body string (not parsed JSON —
358
+ * see AGENTS.md), and was being silently dropped. Appending it (sanitized
359
+ * and length-capped — see `sanitizeDetail`) turns e.g. a bare "→ 403" into
360
+ * something that actually explains itself, without the vendor text being
361
+ * able to overwhelm or manipulate the terminal.
362
+ */
363
+ function describeProviderError(err) {
364
+ const base = stripControl(errorMessage(err));
365
+ if (err instanceof ProviderApiError && err.details) {
366
+ const detail = sanitizeDetail(String(err.details));
367
+ if (detail) return `${base}: ${detail}`;
368
+ }
369
+ return base;
370
+ }
371
+ // src/commands/notifications-sync-roles/links.ts
372
+ const EMPTY_LINKS = {
373
+ version: 1,
374
+ links: []
375
+ };
376
+ const DIGITS = /^\d{1,20}$/;
377
+ /** 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. */
378
+ function parseLinks(text) {
379
+ let raw;
380
+ try {
381
+ raw = JSON.parse(text);
382
+ } catch {
383
+ throw new Error("the links file is not valid JSON");
384
+ }
385
+ const file = raw;
386
+ if (file.version !== 1) throw new Error(`the links file has version ${JSON.stringify(file.version)}; expected 1`);
387
+ if (!Array.isArray(file.links)) throw new Error("the links file has no `links` list");
388
+ const links = file.links.map((entry, i) => {
389
+ const e = entry;
390
+ if (typeof e.github !== "string" || !DIGITS.test(e.github)) throw new Error(`links[${i}]: \`github\` must be a numeric user id string`);
391
+ if (typeof e.member !== "string" || !DIGITS.test(e.member)) throw new Error(`links[${i}]: \`member\` must be a numeric id string`);
392
+ if (typeof e.login !== "string") throw new Error(`links[${i}]: \`login\` must be a string`);
393
+ return {
394
+ github: e.github,
395
+ login: e.login,
396
+ member: e.member
397
+ };
398
+ });
399
+ for (const key of ["github", "member"]) {
400
+ const seen = /* @__PURE__ */ new Set();
401
+ for (const [i, link] of links.entries()) {
402
+ if (seen.has(link[key])) throw new Error(`links[${i}]: \`${key}\` ${link[key]} appears more than once`);
403
+ seen.add(link[key]);
404
+ }
405
+ }
406
+ return {
407
+ version: 1,
408
+ links
409
+ };
410
+ }
411
+ /** Where the links file is: the layout's `links`, else `<org>/.github-private` and `notifications/<provider>-links.json`. */
412
+ function linksLocation(layout, org, provider) {
413
+ const repo = layout.links?.repo ?? (org ? `${org}/.github-private` : void 0);
414
+ if (!repo) throw new Error("no org to find the links file under — set `layout.links.repo` or `org` in holocron.config.ts");
415
+ return {
416
+ repo,
417
+ path: layout.links?.path ?? `notifications/${provider.toLowerCase()}-links.json`
418
+ };
419
+ }
420
+ // src/commands/notifications-sync-roles/plan.ts
421
+ /**
422
+ * What it takes to make a role's holders equal a team, given who is linked to whom. Pure: it decides, the
423
+ * caller acts. A holder is removed only when a link says they are a person who left the team; a holder
424
+ * nobody has linked is reported, never removed, so an empty or missing links file cannot strip the role from
425
+ * everyone.
426
+ */
427
+ function planRoleSync(input) {
428
+ const byGithub = new Map(input.links.map((l) => [l.github, l]));
429
+ const byMember = new Map(input.links.map((l) => [l.member, l]));
430
+ const onTeam = new Set(input.team.map((m) => m.id));
431
+ const holding = new Set(input.holders.map((h) => h.id));
432
+ const plan = {
433
+ add: [],
434
+ remove: [],
435
+ unlinked: [],
436
+ unknownHolders: [],
437
+ inSync: 0
438
+ };
439
+ for (const person of input.team) {
440
+ const link = byGithub.get(person.id);
441
+ if (!link) plan.unlinked.push(person);
442
+ else if (holding.has(link.member)) plan.inSync++;
443
+ else plan.add.push({
444
+ member: link.member,
445
+ login: person.login
446
+ });
447
+ }
448
+ for (const holder of input.holders) {
449
+ const link = byMember.get(holder.id);
450
+ if (!link) plan.unknownHolders.push({
451
+ member: holder.id,
452
+ ...holder.name ? { name: holder.name } : {}
453
+ });
454
+ else if (!onTeam.has(link.github)) plan.remove.push({
455
+ member: holder.id,
456
+ login: link.login
457
+ });
458
+ }
459
+ return plan;
460
+ }
461
+ /**
462
+ * The first role the layout declares for two different teams, or undefined. Names compare ignoring case, as
463
+ * the server does; the role would be synced against one team and then the other, so the last would win.
464
+ */
465
+ function roleTeamProblem(layout) {
466
+ const seen = /* @__PURE__ */ new Map();
467
+ for (const role of layout.roles ?? []) {
468
+ if (!role.team) continue;
469
+ const key = role.name.toLowerCase();
470
+ const earlier = seen.get(key);
471
+ 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`;
472
+ seen.set(key, role.team);
473
+ }
474
+ }
475
+ // src/commands/notifications-sync-roles/sync-roles.ts
476
+ /** Reads the team and the role's holders and works out what has to change. */
477
+ async function planForRole(args) {
478
+ const [team, holders] = await Promise.all([args.source.teamMembers(args.team, args.org), args.notifications.roleMembers(args.role)]);
479
+ return planRoleSync({
480
+ team,
481
+ links: args.links.links,
482
+ holders
483
+ });
484
+ }
485
+ /**
486
+ * Makes each role's holders equal its team, one role after another. This is the sync itself, with no setup in
487
+ * front of it: the caller has already picked the providers, read the links and checked the layout. `holocron
488
+ * notifications sync-roles` and Sentinel's role sync are two callers of it. A step that fails is recorded and the
489
+ * run goes on; nothing here throws for a provider error. Idempotent: a role that already matches changes nothing.
490
+ * Lines go to `input.print` when it is given, and nowhere otherwise.
491
+ */
492
+ async function syncRoles(input) {
493
+ const print = input.print ?? (() => {});
494
+ const { notifications, source, links, dryRun, keep } = input;
495
+ const result = {
496
+ roles: [],
497
+ failures: [],
498
+ ok: 0,
499
+ skipped: 0
500
+ };
501
+ for (const role of input.roles) {
502
+ print(`\n${style.header(`${role.name} ← team ${role.team}`)}`);
503
+ const step = `role ${role.name}`;
504
+ let plan;
505
+ try {
506
+ plan = await planForRole({
507
+ notifications,
508
+ source,
509
+ role: role.name,
510
+ team: role.team,
511
+ ...input.org ? { org: input.org } : {},
512
+ links
513
+ });
514
+ } catch (err) {
515
+ const message = describeProviderError(err);
516
+ print(` ${style.fail(`${step}: ${message}`)}`);
517
+ result.failures.push({
518
+ step,
519
+ message
520
+ });
521
+ continue;
522
+ }
523
+ const outcome = {
524
+ role: role.name,
525
+ team: role.team,
526
+ plan,
527
+ added: [],
528
+ removed: []
529
+ };
530
+ result.roles.push(outcome);
531
+ result.skipped += plan.inSync;
532
+ if (plan.inSync > 0) print(` ${style.skip(`${plan.inSync} already have it`)}`);
533
+ const act = async (verb, who) => {
534
+ const label = `${verb === "add" ? "gave" : "took"} ${role.name} ${verb === "add" ? "to" : "from"} ${who.login} (${who.member})`;
535
+ if (dryRun || verb === "remove" && keep) {
536
+ print(` ${style.skip(`would ${verb === "add" ? "give" : "take"} ${role.name} ${verb === "add" ? "to" : "from"} ${who.login} (${who.member})${keep && verb === "remove" ? " (kept: --keep)" : ""}`)}`);
537
+ result.skipped++;
538
+ return;
539
+ }
540
+ try {
541
+ if (verb === "add") await notifications.addRoleMember(role.name, who.member);
542
+ else await notifications.removeRoleMember(role.name, who.member);
543
+ (verb === "add" ? outcome.added : outcome.removed).push(who.member);
544
+ print(` ${style.success(label)}`);
545
+ result.ok++;
546
+ } catch (err) {
547
+ const message = describeProviderError(err);
548
+ print(` ${style.fail(`${step}: ${verb} ${who.login}: ${message}`)}`);
549
+ result.failures.push({
550
+ step: `${step} ${verb} ${who.login}`,
551
+ message
552
+ });
553
+ }
554
+ };
555
+ for (const who of plan.add) await act("add", who);
556
+ for (const who of plan.remove) await act("remove", who);
557
+ for (const person of plan.unlinked) {
558
+ print(` ${style.skip(`${person.login} is on the team but has not linked their account`)}`);
559
+ result.skipped++;
560
+ }
561
+ for (const holder of plan.unknownHolders) {
562
+ print(` ${style.skip(`${holder.name ?? holder.member} holds ${role.name} but is not linked to anyone: left alone`)}`);
563
+ result.skipped++;
564
+ }
565
+ }
566
+ return result;
114
567
  }
115
- //#endregion
116
- //#region src/commands/setup/derived-properties.ts
568
+ // src/commands/notifications-sync-roles/notifications-sync-roles.ts
569
+ /**
570
+ * `holocron notifications sync-roles` — make who holds a server role match a team.
571
+ *
572
+ * A role that declares `team` in the layout is kept equal to that team of the `source` provider (for GitHub,
573
+ * a team in the org). A team member is matched to a server member through the links file, so only people who
574
+ * have linked their account can be given the role; the rest are listed. The role is taken from a linked
575
+ * person who has left the team, but never from someone nobody has linked: an empty or missing links file
576
+ * cannot strip the role from everyone.
577
+ *
578
+ * Idempotent and safe to re-run. `--dry-run` previews it.
579
+ */
580
+ /** What a source provider needs to be able to do to feed a role sync, or the reason it cannot. */
581
+ function sourceProblem(source) {
582
+ if (!source) return "no `source` provider is available to read the team and the links file";
583
+ if (!source.teamMembers) return `the \`${source.providerName}\` provider cannot list team members`;
584
+ if (!source.readFile) return `the \`${source.providerName}\` provider cannot read the links file`;
585
+ }
586
+ /** Reads the links file; a file that does not exist yet is an empty one, a damaged one throws. */
587
+ async function readLinks(source, layout, org, provider) {
588
+ const { repo, path } = linksLocation(layout, org, provider);
589
+ const file = await source.readFile(path, repo);
590
+ if (!file) return EMPTY_LINKS;
591
+ try {
592
+ return parseLinks(file.content);
593
+ } catch (err) {
594
+ throw new Error(`${repo}/${path}: ${errorMessage(err)}`, { cause: err });
595
+ }
596
+ }
597
+ // src/commands/setup/derived-properties/derived-properties.ts
117
598
  /**
118
599
  * Repo archetype, in priority order:
119
600
  * 1. `*-template` repo name → `template` (independent of package shape).
@@ -184,7 +665,7 @@ function deriveCapabilities(providers) {
184
665
  return Object.keys(providers ?? {}).sort();
185
666
  }
186
667
  /**
187
- * `source` + `ci` are the minimal baseline every repo `holocron setup`
668
+ * `source` + `ci` are the minimal baseline every repo `holocron repo setup`
188
669
  * touches wires — every `holocron.config.ts` in this org already satisfies
189
670
  * this, so `non-compliant` here means drift (a provider manually removed
190
671
  * after setup), not an unmet aspirational policy. Deliberately not a richer
@@ -192,6 +673,7 @@ function deriveCapabilities(providers) {
192
673
  * a Phase B (GitHub App) refinement once it can post *why* on a check run.
193
674
  */
194
675
  const REQUIRED_BASELINE = ["source", "ci"];
676
+ /** Whether a repo's capabilities include the required baseline (`source` and `ci`); `non-compliant` means drift. */
195
677
  function deriveCompliance(capabilities) {
196
678
  return REQUIRED_BASELINE.every((key) => capabilities.includes(key)) ? "compliant" : "non-compliant";
197
679
  }
@@ -213,215 +695,18 @@ function missingCapabilities(capabilities) {
213
695
  */
214
696
  async function readWorkspacePackageJsons(repoRoot, workspacePackages) {
215
697
  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 {}
220
- return results;
221
- }
222
- //#endregion
223
- //#region src/config/config.ts
224
- var ConfigError = class extends Error {
225
- name = "ConfigError";
226
- };
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
- };
261
- }
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
- };
698
+ for (const { slug, dir = "packages", path } of workspacePackages) {
699
+ const pkg = await readPackageJson(join(repoRoot, path ?? join(dir, slug)));
700
+ if (pkg) results.push(pkg);
281
701
  }
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
- };
291
- }
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;
334
- }
335
- /**
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()];
398
- }
399
- }
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
- };
702
+ return results;
417
703
  }
418
- //#endregion
419
- //#region src/config/define-config.ts
704
+ // src/config/define-config/define-config.ts
705
+ /** Returns the config unchanged; it exists to type and autocomplete a `holocron.config.ts`. */
420
706
  function defineConfig(config) {
421
707
  return config;
422
708
  }
423
- //#endregion
424
- //#region src/config/load-config.ts
709
+ // src/config/load-config/load-config.ts
425
710
  /**
426
711
  * `holocron.config.{ts,js,mjs,cjs,json}` loader.
427
712
  *
@@ -433,34 +718,40 @@ function defineConfig(config) {
433
718
  * Probe order is TS-first (`.ts` → `.js` → `.mjs` → `.cjs` → `.json`) —
434
719
  * see ADR-0010 / issue #75 / #81.
435
720
  */
436
- const execFileAsync = promisify(execFile);
437
721
  /**
438
- * Read + parse + resolve `holocron.config.*` from the given directory.
722
+ * Read + parse + resolve `holocron.config.*` starting from the given
723
+ * directory, walking up through ancestors to the nearest `.git` boundary
724
+ * when `cwd` itself has no match — every command is usable from any
725
+ * subdirectory of a repo, not only its exact root (see
726
+ * `@theholocron/datapad`'s own doc comment for the stop conditions).
439
727
  * Throws {@link ConfigFileError} when nothing is found or a file cannot
440
- * be loaded, or `ConfigError` when the config is invalid.
728
+ * be loaded, or `ConfigError` when the config fails schema checks.
441
729
  */
442
730
  async function loadConfig(cwd) {
443
731
  const found = await loadConfigFile({
444
732
  cwd,
445
- name: "holocron"
733
+ name: "holocron",
734
+ walkUp: true
446
735
  });
447
736
  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.`);
737
+ const withDefaults = await deriveDefaults(found);
448
738
  return {
449
- resolved: resolveConfig(await deriveDefaults(dirname(found.filepath), found.config)),
739
+ resolved: resolveConfig(withDefaults),
450
740
  filepath: found.filepath
451
741
  };
452
742
  }
453
- async function deriveDefaults(configDir, raw) {
454
- const result = { ...raw };
743
+ async function deriveDefaults(found) {
744
+ const configDir = dirname(found.filepath);
745
+ const result = { ...found.config };
455
746
  if (!result.name) result.name = await readPackageJsonName(configDir) ?? basename(configDir);
456
747
  if (result.repo && !result.repo.name) {
457
- const repoName = await readGitRemote(configDir);
458
- if (repoName) result.repo = {
748
+ const remote = await readGitRemote(configDir);
749
+ if (remote?.host === "github.com") result.repo = {
459
750
  ...result.repo,
460
- name: repoName
751
+ name: remote.slug
461
752
  };
462
753
  }
463
- const manifest = await loadTasksConfig(configDir);
754
+ const manifest = await loadTasksConfig(configDir, { holocron: found });
464
755
  if (manifest.tasks) result.tasks = manifest.tasks;
465
756
  if (manifest.syncScripts !== void 0) result.syncScripts = manifest.syncScripts;
466
757
  if (manifest.holocronScript !== void 0) result.holocronScript = manifest.holocronScript;
@@ -469,31 +760,7 @@ async function deriveDefaults(configDir, raw) {
469
760
  return result;
470
761
  }
471
762
  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];
763
+ const name = (await readPackageJson(dir))?.name;
764
+ return name === void 0 ? void 0 : name.replace(/^@[^/]+\//, "");
497
765
  }
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 };
766
+ export { AuthError, CARDINALITY, ConfigError, ConfigFileError, ElevationRequiredError, MissingTokenError, ProviderApiError, REQUIRED_CAPABILITIES, WebhookVerificationError, clearTokenCache, compose, connectionProbe, createFeatureResolver, createResolveToken, createRestClient, credentialsEnvironment, defineConfig, deleteToken, deriveCapabilities, deriveCompliance, deriveProfile, deriveStack, describeNetworkError, getToken, isKeyringAvailable, isMulti, listStoredProviders, loadConfig, missingCapabilities, readLinks, readWorkspacePackageJsons, resolveConfig, resolveEntry, resolvePluginPackage, roleTeamProblem, setToken, sourceProblem, syncRoles };