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

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,421 @@
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 resolveConfig, i as credentialsEnvironment, n as system, o as resolveEntry, r as ConfigError, s as resolvePluginPackage, t as compose } from "./compose-BucaYv2k.mjs";
4
3
  import { Entry, findCredentials } from "@napi-rs/keyring";
5
- 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();
4
+ import { AuthError, createFeatureResolver as createFeatureResolver$1, createKeyring, createResolveToken as createResolveToken$1 } from "@theholocron/kyber/secrets";
5
+ import { describeError, style } from "@theholocron/kyber/ui";
6
+ import { errorMessage } from "@theholocron/misc-utils";
7
+ import { createRestClient } from "@theholocron/http-client";
8
+ import { lookup } from "node:dns/promises";
9
+ import { ConfigFileError } from "@theholocron/kyber/config";
10
+ import { join } from "node:path";
11
+ import { readPackageJson } from "@theholocron/pkg-utils";
12
+ // src/auth.ts
12
13
  /**
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`.
14
+ * The CLI's credentials: the OS keyring every plugin's bootstrap token lives in, and the two token resolvers built on
15
+ * it. Both are public, so a plugin's `src/auth.ts` is a one-line call.
16
+ *
17
+ * The keyring itself, with its best-effort failure model and its per-process cache, is `createKeyring` in
18
+ * `@theholocron/kyber/secrets`; this file only names the service. Managed via `holocron auth` subcommands and consulted
19
+ * last in every plugin's precedence chain (after --token / HOLOCRON_<X>_TOKEN / <native>_TOKEN). See
20
+ * `docs/wiki/specifications/tech-auth-bootstrap.spec.md`.
15
21
  */
16
- function makeEnv(source) {
17
- return createEnvLookup(source);
18
- }
19
- //#endregion
20
- //#region src/auth/keyring.ts
21
22
  /**
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.
31
- *
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.
23
+ * The holocron keyring: `get` answers `null` for "not stored" and for "keyring unavailable" alike, so callers fall
24
+ * through to env-var precedence, and remembers the answer for the process (`clearCache` forgets it); `set` and `delete`
25
+ * answer whether they did anything; `list` names the stored providers; `isAvailable` tells an outage from an empty keyring.
38
26
  */
39
- const SERVICE = "com.theholocron.cli";
27
+ const keyring = createKeyring({
28
+ service: "com.theholocron.cli",
29
+ binding: {
30
+ Entry,
31
+ findCredentials
32
+ }
33
+ });
40
34
  /**
41
- * Store or overwrite a bootstrap token for a provider. Returns true on
42
- * success, false when the underlying keyring is unsupported or errored.
35
+ * Kyber's `createResolveToken` with the keyring, the `HOLOCRON_ORG` variable and the `token` description
36
+ * `holocron doctor tokens` reads filled in, so a plugin stays at a one-liner call site. The chain is the flag, the
37
+ * plugin's variable, the vendor's variable, the `credentials` providers' variables, the keyring.
43
38
  */
44
- function setToken(provider, token) {
45
- try {
46
- new Entry(SERVICE, provider).setPassword(token);
47
- return true;
48
- } catch {
49
- return false;
39
+ function createResolveToken(config) {
40
+ return Object.assign(createResolveToken$1({
41
+ ...config,
42
+ keyring: keyring.get,
43
+ orgEnvName: "HOLOCRON_ORG"
44
+ }), { token: {
45
+ envName: config.envName,
46
+ vendorEnvName: config.vendorEnvName,
47
+ keyringKey: config.keyringService
48
+ } });
49
+ }
50
+ /**
51
+ * Kyber's `createFeatureResolver` for a strict, single-feature token: the flag, the feature's variable, the
52
+ * `credentials` providers' variable of that name, the keyring. No broad-token fallback; if the feature's token is absent
53
+ * the operation fails with a message naming the exact variable to set and `holocron auth set`.
54
+ */
55
+ function createFeatureResolver(config) {
56
+ return Object.assign(createFeatureResolver$1({
57
+ ...config,
58
+ vendor: config.vendor ?? "GitHub",
59
+ setCommand: (key) => `holocron auth set ${key} <token>`,
60
+ keyring: keyring.get
61
+ }), { token: {
62
+ envName: config.envName,
63
+ keyringKey: config.keyringKey
64
+ } });
65
+ }
66
+ // src/plugin/connection-probe/connection-probe.ts
67
+ const TLS_CODES = /* @__PURE__ */ new Set([
68
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
69
+ "SELF_SIGNED_CERT_IN_CHAIN",
70
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
71
+ "CERT_HAS_EXPIRED",
72
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
73
+ "ERR_TLS_CERT_ALTNAME_INVALID"
74
+ ]);
75
+ /** 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). */
76
+ function codeOf(err) {
77
+ for (let e = err, depth = 0; e && depth < 4; depth++) {
78
+ if (typeof e.code === "string") return {
79
+ code: e.code,
80
+ message: String(e.message ?? "")
81
+ };
82
+ e = e.cause;
83
+ }
84
+ }
85
+ /** A network failure in plain words, with what usually causes it. Never includes anything from a request. */
86
+ function describeNetworkError(err, timeoutMs) {
87
+ const found = codeOf(err);
88
+ const code = found?.code;
89
+ const name = err?.name;
90
+ 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`;
91
+ switch (code) {
92
+ case "ENOTFOUND":
93
+ case "EAI_AGAIN": return `${code}: the name did not resolve; check your network and DNS`;
94
+ case "ECONNREFUSED": return "ECONNREFUSED: the host refused the connection";
95
+ case "ECONNRESET":
96
+ case "UND_ERR_SOCKET": return `${code}: the connection was cut off; a proxy or firewall may be interfering`;
97
+ case "ENETUNREACH":
98
+ case "EHOSTUNREACH": return `${code}: no route to the host; check that you are online`;
99
+ default:
100
+ 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`;
101
+ return found ? `${found.code}: ${found.message}` : String(err?.message ?? err);
50
102
  }
51
103
  }
52
104
  /**
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).
105
+ * The `connection` probe every provider offers, for telling a network problem from a credential problem: does the name
106
+ * resolve, does the host answer, is there a token, and does the provider accept it. A step that cannot work because an
107
+ * earlier one failed is reported as not tried rather than failing a second time for the same reason.
56
108
  */
57
- function getToken(provider) {
109
+ function connectionProbe(input) {
110
+ const timeoutMs = input.timeoutMs ?? 1e4;
111
+ return {
112
+ summary: `Check the network path to ${input.provider} and that it accepts your token.`,
113
+ writes: false,
114
+ async run(probe) {
115
+ let reachable = true;
116
+ if (input.url) {
117
+ const host = new URL(input.url).hostname;
118
+ const lookup$1 = input.lookup ?? (input.fetch ? void 0 : (h) => lookup(h));
119
+ if (lookup$1) try {
120
+ const { address } = await lookup$1(host);
121
+ probe.say({
122
+ status: "ok",
123
+ label: `DNS ${host}`,
124
+ detail: address
125
+ });
126
+ } catch (err) {
127
+ reachable = false;
128
+ probe.say({
129
+ status: "fail",
130
+ label: `DNS ${host}`,
131
+ detail: describeNetworkError(err, timeoutMs)
132
+ });
133
+ }
134
+ if (reachable) {
135
+ const started = Date.now();
136
+ try {
137
+ const res = await (input.fetch ?? fetch)(input.url, {
138
+ method: "GET",
139
+ signal: AbortSignal.timeout(timeoutMs)
140
+ });
141
+ probe.say({
142
+ status: "ok",
143
+ label: `reach ${host}`,
144
+ detail: `HTTP ${res.status} in ${Date.now() - started} ms`
145
+ });
146
+ } catch (err) {
147
+ reachable = false;
148
+ probe.say({
149
+ status: "fail",
150
+ label: `reach ${host}`,
151
+ detail: describeNetworkError(err, timeoutMs)
152
+ });
153
+ }
154
+ } else probe.say({
155
+ status: "info",
156
+ label: `reach ${host}`,
157
+ detail: "not tried: the name did not resolve"
158
+ });
159
+ }
160
+ let token;
161
+ try {
162
+ token = await input.token();
163
+ } catch (err) {
164
+ probe.say({
165
+ status: "fail",
166
+ label: "token",
167
+ detail: err.message
168
+ });
169
+ probe.say({
170
+ status: "info",
171
+ label: "accepted",
172
+ detail: "not tried: there is no token"
173
+ });
174
+ return;
175
+ }
176
+ probe.secret(token);
177
+ probe.say({
178
+ status: "ok",
179
+ label: "token",
180
+ detail: "found"
181
+ });
182
+ if (!reachable) {
183
+ probe.say({
184
+ status: "info",
185
+ label: "accepted",
186
+ detail: "not tried: the host could not be reached"
187
+ });
188
+ return;
189
+ }
190
+ const result = await input.verify(token);
191
+ probe.say(result.ok ? {
192
+ status: "ok",
193
+ label: "accepted",
194
+ detail: result.subject
195
+ } : {
196
+ status: "fail",
197
+ label: "accepted",
198
+ detail: result.message
199
+ });
200
+ }
201
+ };
202
+ }
203
+ // src/commands/notifications-sync-roles/links.ts
204
+ const EMPTY_LINKS = {
205
+ version: 1,
206
+ links: []
207
+ };
208
+ const DIGITS = /^\d{1,20}$/;
209
+ /** 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. */
210
+ function parseLinks(text) {
211
+ let raw;
58
212
  try {
59
- return new Entry(SERVICE, provider).getPassword();
213
+ raw = JSON.parse(text);
60
214
  } catch {
61
- return null;
215
+ throw new Error("the links file is not valid JSON");
216
+ }
217
+ const file = raw;
218
+ if (file.version !== 1) throw new Error(`the links file has version ${JSON.stringify(file.version)}; expected 1`);
219
+ if (!Array.isArray(file.links)) throw new Error("the links file has no `links` list");
220
+ const links = file.links.map((entry, i) => {
221
+ const e = entry;
222
+ if (typeof e.github !== "string" || !DIGITS.test(e.github)) throw new Error(`links[${i}]: \`github\` must be a numeric user id string`);
223
+ if (typeof e.member !== "string" || !DIGITS.test(e.member)) throw new Error(`links[${i}]: \`member\` must be a numeric id string`);
224
+ if (typeof e.login !== "string") throw new Error(`links[${i}]: \`login\` must be a string`);
225
+ return {
226
+ github: e.github,
227
+ login: e.login,
228
+ member: e.member
229
+ };
230
+ });
231
+ for (const key of ["github", "member"]) {
232
+ const seen = /* @__PURE__ */ new Set();
233
+ for (const [i, link] of links.entries()) {
234
+ if (seen.has(link[key])) throw new Error(`links[${i}]: \`${key}\` ${link[key]} appears more than once`);
235
+ seen.add(link[key]);
236
+ }
62
237
  }
238
+ return {
239
+ version: 1,
240
+ links
241
+ };
242
+ }
243
+ /** Where the links file is: the layout's `links`, else `<org>/.github-private` and `notifications/<provider>-links.json`. */
244
+ function linksLocation(layout, org, provider) {
245
+ const repo = layout.links?.repo ?? (org ? `${org}/.github-private` : void 0);
246
+ if (!repo) throw new Error("no org to find the links file under — set `layout.links.repo` or `org` in holocron.config.ts");
247
+ return {
248
+ repo,
249
+ path: layout.links?.path ?? `notifications/${provider.toLowerCase()}-links.json`
250
+ };
63
251
  }
252
+ // src/commands/notifications-sync-roles/plan.ts
64
253
  /**
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.
254
+ * What it takes to make a role's holders equal a team, given who is linked to whom. Pure: it decides, the
255
+ * caller acts. A holder is removed only when a link says they are a person who left the team; a holder
256
+ * nobody has linked is reported, never removed, so an empty or missing links file cannot strip the role from
257
+ * everyone.
69
258
  */
70
- function deleteToken(provider) {
71
- try {
72
- return new Entry(SERVICE, provider).deletePassword();
73
- } catch {
74
- return false;
259
+ function planRoleSync(input) {
260
+ const byGithub = new Map(input.links.map((l) => [l.github, l]));
261
+ const byMember = new Map(input.links.map((l) => [l.member, l]));
262
+ const onTeam = new Set(input.team.map((m) => m.id));
263
+ const holding = new Set(input.holders.map((h) => h.id));
264
+ const plan = {
265
+ add: [],
266
+ remove: [],
267
+ unlinked: [],
268
+ unknownHolders: [],
269
+ inSync: 0
270
+ };
271
+ for (const person of input.team) {
272
+ const link = byGithub.get(person.id);
273
+ if (!link) plan.unlinked.push(person);
274
+ else if (holding.has(link.member)) plan.inSync++;
275
+ else plan.add.push({
276
+ member: link.member,
277
+ login: person.login
278
+ });
279
+ }
280
+ for (const holder of input.holders) {
281
+ const link = byMember.get(holder.id);
282
+ if (!link) plan.unknownHolders.push({
283
+ member: holder.id,
284
+ ...holder.name ? { name: holder.name } : {}
285
+ });
286
+ else if (!onTeam.has(link.github)) plan.remove.push({
287
+ member: holder.id,
288
+ login: link.login
289
+ });
75
290
  }
291
+ return plan;
76
292
  }
77
293
  /**
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.
294
+ * The first role the layout declares for two different teams, or undefined. Names compare ignoring case, as
295
+ * the server does; the role would be synced against one team and then the other, so the last would win.
81
296
  */
82
- function listStoredProviders() {
83
- try {
84
- return findCredentials(SERVICE).map((c) => c.account);
85
- } catch {
86
- return [];
297
+ function roleTeamProblem(layout) {
298
+ const seen = /* @__PURE__ */ new Map();
299
+ for (const role of layout.roles ?? []) {
300
+ if (!role.team) continue;
301
+ const key = role.name.toLowerCase();
302
+ const earlier = seen.get(key);
303
+ 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`;
304
+ seen.set(key, role.team);
87
305
  }
88
306
  }
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
307
+ // src/commands/notifications-sync-roles/sync-roles.ts
308
+ /** Reads the team and the role's holders and works out what has to change. */
309
+ async function planForRole(args) {
310
+ const [team, holders] = await Promise.all([args.source.teamMembers(args.team, args.org), args.notifications.roleMembers(args.role)]);
311
+ return planRoleSync({
312
+ team,
313
+ links: args.links.links,
314
+ holders
97
315
  });
98
316
  }
99
317
  /**
100
- * Build a strict, single-feature token resolver.
101
- *
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.
318
+ * Makes each role's holders equal its team, one role after another. This is the sync itself, with no setup in
319
+ * front of it: the caller has already picked the providers, read the links and checked the layout. `holocron
320
+ * notifications sync-roles` and Sentinel's role sync are two callers of it. A step that fails is recorded and the
321
+ * run goes on; nothing here throws for a provider error. Idempotent: a role that already matches changes nothing.
322
+ * Lines go to `input.print` when it is given, and nowhere otherwise.
105
323
  */
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;
324
+ async function syncRoles(input) {
325
+ const print = input.print ?? (() => {});
326
+ const { notifications, source, links, dryRun, keep } = input;
327
+ const result = {
328
+ roles: [],
329
+ failures: [],
330
+ ok: 0,
331
+ skipped: 0
113
332
  };
333
+ for (const role of input.roles) {
334
+ print(`\n${style.header(`${role.name} ← team ${role.team}`)}`);
335
+ const step = `role ${role.name}`;
336
+ let plan;
337
+ try {
338
+ plan = await planForRole({
339
+ notifications,
340
+ source,
341
+ role: role.name,
342
+ team: role.team,
343
+ ...input.org ? { org: input.org } : {},
344
+ links
345
+ });
346
+ } catch (err) {
347
+ const message = describeError(err);
348
+ print(` ${style.fail(`${step}: ${message}`)}`);
349
+ result.failures.push({
350
+ step,
351
+ message
352
+ });
353
+ continue;
354
+ }
355
+ const outcome = {
356
+ role: role.name,
357
+ team: role.team,
358
+ plan,
359
+ added: [],
360
+ removed: []
361
+ };
362
+ result.roles.push(outcome);
363
+ result.skipped += plan.inSync;
364
+ if (plan.inSync > 0) print(` ${style.skip(`${plan.inSync} already have it`)}`);
365
+ const act = async (verb, who) => {
366
+ const label = `${verb === "add" ? "gave" : "took"} ${role.name} ${verb === "add" ? "to" : "from"} ${who.login} (${who.member})`;
367
+ if (dryRun || verb === "remove" && keep) {
368
+ print(` ${style.skip(`would ${verb === "add" ? "give" : "take"} ${role.name} ${verb === "add" ? "to" : "from"} ${who.login} (${who.member})${keep && verb === "remove" ? " (kept: --keep)" : ""}`)}`);
369
+ result.skipped++;
370
+ return;
371
+ }
372
+ try {
373
+ if (verb === "add") await notifications.addRoleMember(role.name, who.member);
374
+ else await notifications.removeRoleMember(role.name, who.member);
375
+ (verb === "add" ? outcome.added : outcome.removed).push(who.member);
376
+ print(` ${style.success(label)}`);
377
+ result.ok++;
378
+ } catch (err) {
379
+ const message = describeError(err);
380
+ print(` ${style.fail(`${step}: ${verb} ${who.login}: ${message}`)}`);
381
+ result.failures.push({
382
+ step: `${step} ${verb} ${who.login}`,
383
+ message
384
+ });
385
+ }
386
+ };
387
+ for (const who of plan.add) await act("add", who);
388
+ for (const who of plan.remove) await act("remove", who);
389
+ for (const person of plan.unlinked) {
390
+ print(` ${style.skip(`${person.login} is on the team but has not linked their account`)}`);
391
+ result.skipped++;
392
+ }
393
+ for (const holder of plan.unknownHolders) {
394
+ print(` ${style.skip(`${holder.name ?? holder.member} holds ${role.name} but is not linked to anyone: left alone`)}`);
395
+ result.skipped++;
396
+ }
397
+ }
398
+ return result;
399
+ }
400
+ // src/commands/notifications-sync-roles/notifications-sync-roles.ts
401
+ /** What a source provider needs to be able to do to feed a role sync, or the reason it cannot. */
402
+ function sourceProblem(source) {
403
+ if (!source) return "no `source` provider is available to read the team and the links file";
404
+ if (!source.teamMembers) return `the \`${source.providerName}\` provider cannot list team members`;
405
+ if (!source.readFile) return `the \`${source.providerName}\` provider cannot read the links file`;
114
406
  }
115
- //#endregion
116
- //#region src/commands/setup/derived-properties.ts
407
+ /** Reads the links file; a file that does not exist yet is an empty one, a damaged one throws. */
408
+ async function readLinks(source, layout, org, provider) {
409
+ const { repo, path } = linksLocation(layout, org, provider);
410
+ const file = await source.readFile(path, repo);
411
+ if (!file) return EMPTY_LINKS;
412
+ try {
413
+ return parseLinks(file.content);
414
+ } catch (err) {
415
+ throw new Error(`${repo}/${path}: ${errorMessage(err)}`, { cause: err });
416
+ }
417
+ }
418
+ // src/commands/setup/derived-properties/derived-properties.ts
117
419
  /**
118
420
  * Repo archetype, in priority order:
119
421
  * 1. `*-template` repo name → `template` (independent of package shape).
@@ -184,7 +486,7 @@ function deriveCapabilities(providers) {
184
486
  return Object.keys(providers ?? {}).sort();
185
487
  }
186
488
  /**
187
- * `source` + `ci` are the minimal baseline every repo `holocron setup`
489
+ * `source` + `ci` are the minimal baseline every repo `holocron repo setup`
188
490
  * touches wires — every `holocron.config.ts` in this org already satisfies
189
491
  * this, so `non-compliant` here means drift (a provider manually removed
190
492
  * after setup), not an unmet aspirational policy. Deliberately not a richer
@@ -192,6 +494,7 @@ function deriveCapabilities(providers) {
192
494
  * a Phase B (GitHub App) refinement once it can post *why* on a check run.
193
495
  */
194
496
  const REQUIRED_BASELINE = ["source", "ci"];
497
+ /** Whether a repo's capabilities include the required baseline (`source` and `ci`); `non-compliant` means drift. */
195
498
  function deriveCompliance(capabilities) {
196
499
  return REQUIRED_BASELINE.every((key) => capabilities.includes(key)) ? "compliant" : "non-compliant";
197
500
  }
@@ -213,287 +516,38 @@ function missingCapabilities(capabilities) {
213
516
  */
214
517
  async function readWorkspacePackageJsons(repoRoot, workspacePackages) {
215
518
  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
- };
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
- };
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
- }
519
+ for (const { slug, dir = "packages", path } of workspacePackages) {
520
+ const pkg = await readPackageJson(join(repoRoot, path ?? join(dir, slug)));
521
+ if (pkg) results.push(pkg);
399
522
  }
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
- };
523
+ return results;
417
524
  }
418
- //#endregion
419
- //#region src/config/define-config.ts
525
+ // src/config/define-config/define-config.ts
526
+ /** Returns the config unchanged; it exists to type and autocomplete a `holocron.config.ts`. */
420
527
  function defineConfig(config) {
421
- return config;
528
+ return system.defineConfig(config);
422
529
  }
423
- //#endregion
424
- //#region src/config/load-config.ts
530
+ // src/config/load-config/load-config.ts
425
531
  /**
426
532
  * `holocron.config.{ts,js,mjs,cjs,json}` loader.
427
533
  *
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`.
534
+ * File discovery, the walk up to `.git`, module loading (typed configs via `tsx`) and the derive-then-resolve flow come
535
+ * from `@theholocron/kyber/config`. The holocron-specific parts are `deriveDefaults` (name, `repo.name`, the task
536
+ * manifest) and `resolveConfig`; see `../system`.
432
537
  *
433
538
  * Probe order is TS-first (`.ts` → `.js` → `.mjs` → `.cjs` → `.json`) —
434
539
  * see ADR-0010 / issue #75 / #81.
435
540
  */
436
- const execFileAsync = promisify(execFile);
437
541
  /**
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.
542
+ * Read + parse + resolve `holocron.config.*` starting from the given
543
+ * directory, walking up through ancestors to the nearest `.git` boundary
544
+ * when `cwd` itself has no match — every command is usable from any
545
+ * subdirectory of a repo, not only its exact root (see
546
+ * `@theholocron/datapad`'s own doc comment for the stop conditions).
547
+ * Throws `ConfigFileError` when nothing is found or a file cannot
548
+ * be loaded, or `ConfigError` when the config fails schema checks.
441
549
  */
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.`);
448
- return {
449
- resolved: resolveConfig(await deriveDefaults(dirname(found.filepath), found.config)),
450
- filepath: found.filepath
451
- };
452
- }
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];
550
+ function loadConfig(cwd) {
551
+ return system.loadConfig(cwd);
497
552
  }
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 };
553
+ export { AuthError, CARDINALITY, ConfigError, ConfigFileError, ElevationRequiredError, MissingTokenError, ProviderApiError, REQUIRED_CAPABILITIES, WebhookVerificationError, compose, connectionProbe, createFeatureResolver, createResolveToken, createRestClient, credentialsEnvironment, defineConfig, deriveCapabilities, deriveCompliance, deriveProfile, deriveStack, describeNetworkError, isMulti, keyring, loadConfig, missingCapabilities, readLinks, readWorkspacePackageJsons, resolveConfig, resolveEntry, resolvePluginPackage, roleTeamProblem, sourceProblem, syncRoles };