@theholocron/cli 5.0.0-alpha.34 → 5.0.0-alpha.340

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