@theholocron/cli 5.3.0 → 5.5.0

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/cli.mjs CHANGED
@@ -148,6 +148,7 @@ const COMMAND_CONTEXTS = {
148
148
  "sync incidents": "workspace",
149
149
  "sync prs": "workspace",
150
150
  "sync releases": "workspace",
151
+ "sync templates": "workspace",
151
152
  "sync ideas": "workspace",
152
153
  "sync tooling": "workspace",
153
154
  "sync requests": "workspace",
@@ -508,17 +509,26 @@ const doctorCiEntry = {
508
509
  name: "doctor ci",
509
510
  description: "Check the repo against the flat task vocabulary: aliases, caller names, the ci aggregate, home (read-only)",
510
511
  positionals: [],
511
- options: [{
512
- key: "shadow",
513
- flag: "--shadow",
514
- type: "confirm",
515
- message: "Also compare Sentinel's shadow aggregate with the Actions one?"
516
- }, {
517
- key: "remote",
518
- flag: "--remote",
519
- type: "confirm",
520
- message: "Also check the hosted files over the network (the ci-v1 tag, what callers name at it, the frozen copies)?"
521
- }],
512
+ options: [
513
+ {
514
+ key: "shadow",
515
+ flag: "--shadow",
516
+ type: "confirm",
517
+ message: "Also compare Sentinel's shadow aggregate with the Actions one?"
518
+ },
519
+ {
520
+ key: "remote",
521
+ flag: "--remote",
522
+ type: "confirm",
523
+ message: "Also check the hosted files over the network (the ci-v1 tag, what callers name at it, the frozen copies)?"
524
+ },
525
+ {
526
+ key: "scan",
527
+ flag: "--scan",
528
+ type: "confirm",
529
+ message: "Also list the org's repositories still calling the frozen .github files (clones every repo)?"
530
+ }
531
+ ],
522
532
  skipOptions: [
523
533
  "all",
524
534
  "repo",
@@ -2294,6 +2304,15 @@ const syncRequestsEntry = {
2294
2304
  ],
2295
2305
  supportsDryRun: true
2296
2306
  };
2307
+ // src/commands/sync-templates/sync-templates.entry.ts
2308
+ const syncTemplatesEntry = {
2309
+ name: "sync templates",
2310
+ description: "Publish each templates/<type>/ folder to its template repo and tag it with the templates version",
2311
+ positionals: [],
2312
+ options: [],
2313
+ skipOptions: ["yes"],
2314
+ supportsDryRun: true
2315
+ };
2297
2316
  // src/commands/sync-tooling/sync-tooling.entry.ts
2298
2317
  const syncToolingEntry = {
2299
2318
  name: "sync tooling",
@@ -2516,6 +2535,7 @@ const registry = createCommandRegistry([
2516
2535
  syncIncidentsEntry,
2517
2536
  syncPrsEntry,
2518
2537
  syncReleasesEntry,
2538
+ syncTemplatesEntry,
2519
2539
  ideasSyncEntry,
2520
2540
  syncToolingEntry,
2521
2541
  syncRequestsEntry,
@@ -14458,7 +14478,7 @@ const FROZEN_NOTICE = "DEPRECATED — frozen copy";
14458
14478
  const API = "https://api.github.com";
14459
14479
  const RAW = "https://raw.githubusercontent.com";
14460
14480
  // src/commands/doctor-ci/frozen-row.ts
14461
- const ID$10 = "frozen";
14481
+ const ID$11 = "frozen";
14462
14482
  const TITLE$11 = `the workflows left in ${DOT_GITHUB_REPO} say they are frozen`;
14463
14483
  /**
14464
14484
  * The `frozen` row: every workflow still in `theholocron/.github` carries the deprecation notice, so nobody mistakes a
@@ -14468,7 +14488,7 @@ const TITLE$11 = `the workflows left in ${DOT_GITHUB_REPO} say they are frozen`;
14468
14488
  async function frozenRow(read) {
14469
14489
  const listing = await read(`${API}/repos/${DOT_GITHUB_REPO}/contents/.github/workflows`);
14470
14490
  if (listing.status !== 200) return {
14471
- id: ID$10,
14491
+ id: ID$11,
14472
14492
  title: TITLE$11,
14473
14493
  status: "skip",
14474
14494
  detail: `could not list them (HTTP ${listing.status || "no answer"})`,
@@ -14479,7 +14499,7 @@ async function frozenRow(read) {
14479
14499
  names = JSON.parse(listing.text).map((entry) => entry.name).filter((name) => typeof name === "string" && /\.ya?ml$/.test(name)).sort();
14480
14500
  } catch {
14481
14501
  return {
14482
- id: ID$10,
14502
+ id: ID$11,
14483
14503
  title: TITLE$11,
14484
14504
  status: "skip",
14485
14505
  detail: "the listing was not JSON",
@@ -14492,7 +14512,7 @@ async function frozenRow(read) {
14492
14512
  })));
14493
14513
  const unread = files.find(({ res }) => res.status !== 200);
14494
14514
  if (unread) return {
14495
- id: ID$10,
14515
+ id: ID$11,
14496
14516
  title: TITLE$11,
14497
14517
  status: "skip",
14498
14518
  detail: `could not read ${unread.name} (HTTP ${unread.res.status || "no answer"})`,
@@ -14500,14 +14520,14 @@ async function frozenRow(read) {
14500
14520
  };
14501
14521
  const unmarked = files.filter(({ res }) => !res.text.split("\n", 15).some((line) => line.includes(FROZEN_NOTICE)));
14502
14522
  if (unmarked.length > 0) return {
14503
- id: ID$10,
14523
+ id: ID$11,
14504
14524
  title: TITLE$11,
14505
14525
  status: "fail",
14506
14526
  detail: `${unmarked.length} of ${files.length} carry no notice`,
14507
14527
  problems: unmarked.map(({ name }) => `${name}: no "${FROZEN_NOTICE}" notice`)
14508
14528
  };
14509
14529
  return {
14510
- id: ID$10,
14530
+ id: ID$11,
14511
14531
  title: TITLE$11,
14512
14532
  status: "ok",
14513
14533
  detail: `${files.length} of ${files.length} carry the notice`,
@@ -14532,7 +14552,7 @@ function hostedPaths(workflows) {
14532
14552
  })).sort((a, b) => a.path.localeCompare(b.path));
14533
14553
  }
14534
14554
  // src/commands/doctor-ci/refs-row.ts
14535
- const ID$9 = "refs";
14555
+ const ID$10 = "refs";
14536
14556
  const TITLE$10 = `every ${CI_TAG} reference resolves`;
14537
14557
  /** A workflow file holds itself at its path; an action is a folder with an `action.yml` (or `.yaml`) in it. */
14538
14558
  async function resolves(read, path) {
@@ -14549,7 +14569,7 @@ async function resolves(read, path) {
14549
14569
  async function refsRow(workflows, read) {
14550
14570
  const paths = hostedPaths(workflows);
14551
14571
  if (paths.length === 0) return {
14552
- id: ID$9,
14572
+ id: ID$10,
14553
14573
  title: TITLE$10,
14554
14574
  status: "skip",
14555
14575
  detail: `no workflow names a file at ${CI_TAG}`,
@@ -14563,7 +14583,7 @@ async function refsRow(workflows, read) {
14563
14583
  if (unread.length > 0) {
14564
14584
  const first = unread[0];
14565
14585
  return {
14566
- id: ID$9,
14586
+ id: ID$10,
14567
14587
  title: TITLE$10,
14568
14588
  status: "skip",
14569
14589
  detail: `could not read ${first.hosted.path} (HTTP ${first.status || "no answer"})`,
@@ -14572,14 +14592,14 @@ async function refsRow(workflows, read) {
14572
14592
  }
14573
14593
  const missing = answers.filter(({ status }) => status === 404);
14574
14594
  if (missing.length > 0) return {
14575
- id: ID$9,
14595
+ id: ID$10,
14576
14596
  title: TITLE$10,
14577
14597
  status: "fail",
14578
14598
  detail: `${missing.length} of ${paths.length} missing at ${CI_TAG}`,
14579
14599
  problems: missing.map(({ hosted }) => `${hosted.path}: not at ${CI_TAG} (named by ${hosted.files.join(", ")})`)
14580
14600
  };
14581
14601
  return {
14582
- id: ID$9,
14602
+ id: ID$10,
14583
14603
  title: TITLE$10,
14584
14604
  status: "ok",
14585
14605
  detail: `${paths.length} found at ${CI_TAG}`,
@@ -14587,7 +14607,7 @@ async function refsRow(workflows, read) {
14587
14607
  };
14588
14608
  }
14589
14609
  // src/commands/doctor-ci/tag-row.ts
14590
- const ID$8 = "tag";
14610
+ const ID$9 = "tag";
14591
14611
  const TITLE$9 = `${CI_TAG} exists in ${HOLOCRON_REPO}`;
14592
14612
  /** The `tag` row: the tag every caller pins the hosted files to exists. A read that fails or is rate limited is a skip, not a fail. */
14593
14613
  async function tagRow(read) {
@@ -14595,7 +14615,7 @@ async function tagRow(read) {
14595
14615
  if (res.status === 200) {
14596
14616
  const sha = /"sha"\s*:\s*"([0-9a-f]{7,40})"/.exec(res.text)?.[1];
14597
14617
  return {
14598
- id: ID$8,
14618
+ id: ID$9,
14599
14619
  title: TITLE$9,
14600
14620
  status: "ok",
14601
14621
  detail: sha ? `at ${sha.slice(0, 9)}` : "found",
@@ -14603,14 +14623,14 @@ async function tagRow(read) {
14603
14623
  };
14604
14624
  }
14605
14625
  if (res.status === 404) return {
14606
- id: ID$8,
14626
+ id: ID$9,
14607
14627
  title: TITLE$9,
14608
14628
  status: "fail",
14609
14629
  detail: "no such tag",
14610
14630
  problems: [`${HOLOCRON_REPO} has no ${CI_TAG} tag, so every caller that pins it fails to resolve`]
14611
14631
  };
14612
14632
  return {
14613
- id: ID$8,
14633
+ id: ID$9,
14614
14634
  title: TITLE$9,
14615
14635
  status: "skip",
14616
14636
  detail: `could not read the tag (HTTP ${res.status || "no answer"})`,
@@ -14626,6 +14646,273 @@ async function remoteRows(workflows, read) {
14626
14646
  await frozenRow(read)
14627
14647
  ];
14628
14648
  }
14649
+ // src/commands/probe/references/clone-org.ts
14650
+ const SKIP_DIRS$1 = /* @__PURE__ */ new Set([".git", "node_modules"]);
14651
+ const MAX_FILE_BYTES = 5242880;
14652
+ /** How often, and how long apart, removing a clone is tried again when something is still writing into it. */
14653
+ const REMOVE_RETRIES = 10;
14654
+ const REMOVE_RETRY_DELAY_MS = 200;
14655
+ /**
14656
+ * The arguments of `gh repo clone` for `org/name` into `dest`: a shallow, quiet clone that runs none of the user's git
14657
+ * hooks. The probe only reads, and a global hook (`core.hooksPath`, `init.templateDir`) such as a `post-checkout` that
14658
+ * starts `ctags` in the background writes `.git/tags` after the clone has returned, which made removing the clone fail
14659
+ * with `ENOTEMPTY` (#2913). `-c` takes effect before the files are checked out.
14660
+ */
14661
+ function cloneArgs(org, name, dest) {
14662
+ return [
14663
+ "repo",
14664
+ "clone",
14665
+ `${org}/${name}`,
14666
+ dest,
14667
+ "--",
14668
+ "--depth",
14669
+ "1",
14670
+ "--quiet",
14671
+ "-c",
14672
+ "core.hooksPath=/dev/null"
14673
+ ];
14674
+ }
14675
+ /**
14676
+ * Removes a scratch directory, trying again when something still writes into it. A process the clone left running can
14677
+ * recreate a file while the directory is being deleted; `rmSync` retries `ENOTEMPTY` (and `EBUSY`, `EPERM`) itself.
14678
+ */
14679
+ function removeScratch(path, remove = rmSync) {
14680
+ remove(path, {
14681
+ recursive: true,
14682
+ force: true,
14683
+ maxRetries: REMOVE_RETRIES,
14684
+ retryDelay: REMOVE_RETRY_DELAY_MS
14685
+ });
14686
+ }
14687
+ /** Every text file under `dir`: not in `.git` or `node_modules`, under 5 MiB, and without a NUL in its first KiB. */
14688
+ function* textFiles(dir, root = dir) {
14689
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
14690
+ if (SKIP_DIRS$1.has(entry.name)) continue;
14691
+ const path = join(dir, entry.name);
14692
+ if (entry.isDirectory()) yield* textFiles(path, root);
14693
+ else if (entry.isFile() && statSync(path).size < MAX_FILE_BYTES) {
14694
+ const buffer = readFileSync(path);
14695
+ if (!buffer.subarray(0, 1024).includes(0)) yield {
14696
+ path: relative(root, path),
14697
+ text: buffer.toString("utf8")
14698
+ };
14699
+ }
14700
+ }
14701
+ }
14702
+ /**
14703
+ * Shallow-clones the default branch of each active (not archived) repository of `org` with `gh`, one at a time, and
14704
+ * removes every clone when the scan ends. Cloning, rather than GitHub code search, because search skips repositories
14705
+ * that are not indexed and gives no guarantee of completeness.
14706
+ */
14707
+ function cloneOrg(org) {
14708
+ return JSON.parse(execFileSync("gh", [
14709
+ "repo",
14710
+ "list",
14711
+ org,
14712
+ "--limit",
14713
+ "200",
14714
+ "--json",
14715
+ "name,isArchived,isTemplate"
14716
+ ], { encoding: "utf8" })).filter((repo) => !repo.isArchived).sort((a, b) => a.name.localeCompare(b.name)).map((repo) => ({
14717
+ name: repo.name,
14718
+ isTemplate: repo.isTemplate,
14719
+ files() {
14720
+ const scratch = mkdtempSync(join(tmpdir(), "refs-"));
14721
+ const dest = join(scratch, repo.name);
14722
+ execFileSync("gh", cloneArgs(org, repo.name, dest), { stdio: "pipe" });
14723
+ try {
14724
+ return [...textFiles(dest)];
14725
+ } finally {
14726
+ removeScratch(scratch);
14727
+ }
14728
+ }
14729
+ }));
14730
+ /* v8 ignore stop */
14731
+ }
14732
+ // src/commands/probe/references/find-references.ts
14733
+ const CALL = /^-?\s*uses:\s/;
14734
+ /** The repository that hosts the files; its own references are the starters and shims, not callers. */
14735
+ const HOST_REPO = ".github";
14736
+ /** What a reference points at, from the text after the needle. */
14737
+ function kindOf$1(line, needle) {
14738
+ const rest = line.slice(line.indexOf(needle) + needle.length);
14739
+ if (rest.startsWith("workflows/")) return "workflow";
14740
+ if (rest.startsWith("actions/")) return "action";
14741
+ return "other";
14742
+ }
14743
+ /** Every line of every file of `repo` that contains `needle`. */
14744
+ function findReferences(repo, needle) {
14745
+ const found = [];
14746
+ for (const file of repo.files()) file.text.split("\n").forEach((line, index) => {
14747
+ if (!line.includes(needle)) return;
14748
+ found.push({
14749
+ repo: repo.name,
14750
+ file: file.path,
14751
+ line: index + 1,
14752
+ kind: kindOf$1(line, needle),
14753
+ text: line.trim()
14754
+ });
14755
+ });
14756
+ return found;
14757
+ }
14758
+ /**
14759
+ * Whether a reference is a live call: a `uses:` line in a YAML file, which is what GitHub reads. Tests, docs and specs
14760
+ * name the path on purpose (the legacy-path detection, a test that nothing spells it, a record of the move), so they are
14761
+ * references to list but not calls to wait on.
14762
+ */
14763
+ function isCall(ref) {
14764
+ return /\.ya?ml$/.test(ref.file) && CALL.test(ref.text);
14765
+ }
14766
+ // src/commands/probe/references/references-probes.ts
14767
+ function scan(repos, needle) {
14768
+ return {
14769
+ repos,
14770
+ found: repos.flatMap((repo) => findReferences(repo, needle))
14771
+ };
14772
+ }
14773
+ function summarise$2(ctx, repos, found, needle, max) {
14774
+ ctx.say({
14775
+ status: "heading",
14776
+ label: `References to ${needle}`
14777
+ });
14778
+ for (const repo of repos) {
14779
+ const own = found.filter((ref) => ref.repo === repo.name);
14780
+ const files = new Set(own.map((ref) => ref.file)).size;
14781
+ const count = (kind) => own.filter((ref) => ref.kind === kind).length;
14782
+ ctx.say({
14783
+ status: "info",
14784
+ label: repo.name === ".github" ? `${repo.name} (host)` : repo.name,
14785
+ detail: `${files} files: ${count("workflow")} workflow, ${count("action")} action, ${count("other")} other; ${own.filter(isCall).length} live calls`
14786
+ });
14787
+ }
14788
+ const outside = found.filter((ref) => ref.repo !== HOST_REPO);
14789
+ const calls = outside.filter(isCall).length;
14790
+ const inside = found.length - outside.length;
14791
+ const detail = `${outside.length} references in all (tests, docs and specs may name the path on purpose), ${inside} more inside ${HOST_REPO}`;
14792
+ if (calls > max) ctx.say({
14793
+ status: "fail",
14794
+ label: `${calls} live calls outside ${HOST_REPO}`,
14795
+ detail: `more than the ${max} allowed; ${detail}`
14796
+ });
14797
+ else ctx.say({
14798
+ status: "ok",
14799
+ label: `${calls} live calls outside ${HOST_REPO}`,
14800
+ detail
14801
+ });
14802
+ }
14803
+ /**
14804
+ * `ci refs` counts the references to the reusable workflows and composite actions hosted in `<org>/.github` across
14805
+ * every active repository of the org. It is the exit test for removing the forwarding shims there: they can go when
14806
+ * no live call outside `.github` is left (a `uses:` line in a YAML file; see {@link isCall}). It fails above `<max>`,
14807
+ * which defaults to 0, so the exit code is the test (#2915). `ci ref-list` prints each reference with its file and line.
14808
+ */
14809
+ function ciProbes(org, clone = cloneOrg) {
14810
+ const needle = (name) => `${name}/.github/.github/`;
14811
+ const read = (ctx) => {
14812
+ if (!org) {
14813
+ ctx.say({
14814
+ status: "fail",
14815
+ label: "no org",
14816
+ detail: "the config has no org to scan"
14817
+ });
14818
+ return null;
14819
+ }
14820
+ return {
14821
+ org,
14822
+ ...scan(clone(org), needle(org))
14823
+ };
14824
+ };
14825
+ return {
14826
+ refs: {
14827
+ summary: "Count references to the reusable workflows and actions hosted in the org's .github repo; fails on a live call outside it (arg: max, default 0).",
14828
+ writes: false,
14829
+ async run(ctx) {
14830
+ const result = read(ctx);
14831
+ if (!result) return;
14832
+ const max = ctx.args?.[0] === void 0 ? 0 : Number(ctx.args[0]);
14833
+ if (!Number.isInteger(max) || max < 0) {
14834
+ ctx.say({
14835
+ status: "fail",
14836
+ label: `\`${ctx.args[0]}\` is not a number`,
14837
+ detail: "usage: ci refs [max]"
14838
+ });
14839
+ return;
14840
+ }
14841
+ summarise$2(ctx, result.repos, result.found, needle(result.org), max);
14842
+ }
14843
+ },
14844
+ "ref-list": {
14845
+ summary: "List every reference to the org's .github workflows and actions, with file and line.",
14846
+ writes: false,
14847
+ async run(ctx) {
14848
+ const result = read(ctx);
14849
+ if (!result) return;
14850
+ for (const ref of result.found) ctx.say({
14851
+ status: "info",
14852
+ label: `${ref.repo}:${ref.file}:${ref.line}`,
14853
+ detail: `${ref.kind}: ${ref.text}`
14854
+ });
14855
+ ctx.say({
14856
+ status: "ok",
14857
+ label: `${result.found.length} references`
14858
+ });
14859
+ }
14860
+ }
14861
+ };
14862
+ }
14863
+ // src/commands/doctor-ci/repos-row.ts
14864
+ const ID$8 = "repos";
14865
+ /**
14866
+ * The `repos` row (`doctor ci --scan`): which repositories of the org still call the frozen workflows and actions in
14867
+ * `<org>/.github` (a live `uses:` line, the same count `holocron probe ci refs` makes). Each is named with how many
14868
+ * calls it has. It clones every active repository, so it is never part of `doctor --all`. With no org, or a scan that
14869
+ * cannot run (no `gh`, no network), the row is a skip, never a failure.
14870
+ */
14871
+ function reposRow(org, clone = cloneOrg) {
14872
+ const title = `no repository of ${org ?? "the org"} still calls the frozen ${HOST_REPO} files`;
14873
+ if (!org) return {
14874
+ id: ID$8,
14875
+ title,
14876
+ status: "skip",
14877
+ detail: "the config has no org to scan",
14878
+ problems: []
14879
+ };
14880
+ let repos;
14881
+ let calls;
14882
+ try {
14883
+ repos = clone(org);
14884
+ const needle = `${org}/${HOST_REPO}/.github/`;
14885
+ calls = /* @__PURE__ */ new Map();
14886
+ for (const repo of repos) {
14887
+ if (repo.name === ".github") continue;
14888
+ const live = findReferences(repo, needle).filter(isCall).length;
14889
+ if (live > 0) calls.set(repo.name, live);
14890
+ }
14891
+ } catch (err) {
14892
+ const reason = err instanceof Error ? err.message.split("\n")[0] : "unknown error";
14893
+ return {
14894
+ id: ID$8,
14895
+ title,
14896
+ status: "skip",
14897
+ detail: `could not scan the org (${reason})`,
14898
+ problems: []
14899
+ };
14900
+ }
14901
+ if (calls.size === 0) return {
14902
+ id: ID$8,
14903
+ title,
14904
+ status: "ok",
14905
+ detail: `${repos.length} repositories scanned`,
14906
+ problems: []
14907
+ };
14908
+ return {
14909
+ id: ID$8,
14910
+ title,
14911
+ status: "fail",
14912
+ detail: `${calls.size} of ${repos.length} repositories`,
14913
+ problems: [...calls].map(([name, count]) => `${name}: ${count} live call${count === 1 ? "" : "s"}`)
14914
+ };
14915
+ }
14629
14916
  // src/commands/doctor-ci/shadow-verdict.ts
14630
14917
  /**
14631
14918
  * The verdict of the newest run named `name` among a commit's check runs: still running is `pending`, a completed
@@ -14787,6 +15074,7 @@ async function runDoctorCi(input) {
14787
15074
  aggregateRow(callers, aggregateChecks(tasksConfig).expected, aggregatePoster(tasksConfig)),
14788
15075
  homeRow(callers),
14789
15076
  ...input.remote ? await remoteRows(io.workflows(), input.fetchText ?? fetchText) : [],
15077
+ ...input.scan ? [reposRow(input.context.org ?? config.org, input.scanRepos)] : [],
14790
15078
  ...input.shadow ? await shadowRows(input) : []
14791
15079
  ];
14792
15080
  printCheckRows(rows, print);
@@ -14813,6 +15101,9 @@ const doctorCiCommand = {
14813
15101
  }).option("remote", {
14814
15102
  type: "boolean",
14815
15103
  describe: "Also check the hosted files over the network: the ci-v1 tag, every file and action the workflows name at it, and the frozen copies in theholocron/.github (public URLs, no token)"
15104
+ }).option("scan", {
15105
+ type: "boolean",
15106
+ describe: "Also list the org's repositories that still call the frozen theholocron/.github files (clones every repository with gh; not part of doctor --all)"
14816
15107
  }).option("limit", {
14817
15108
  type: "number",
14818
15109
  describe: "With --shadow: how many of the newest pull requests to read (default 40)"
@@ -14827,10 +15118,11 @@ const doctorCiCommand = {
14827
15118
  context: {
14828
15119
  repoRoot: argv.cwd,
14829
15120
  ...tokens,
14830
- ...argv.shadow ? { org: resolveOrg(argv, loaded.resolved) } : {}
15121
+ ...argv.shadow || argv.scan ? { org: resolveOrg(argv, loaded.resolved) } : {}
14831
15122
  },
14832
15123
  ...argv.shadow ? { shadow: true } : {},
14833
15124
  ...argv.remote ? { remote: true } : {},
15125
+ ...argv.scan ? { scan: true } : {},
14834
15126
  ...argv.limit !== void 0 ? { shadowLimit: Number(argv.limit) } : {}
14835
15127
  })).status === "fail") process.exitCode = 1;
14836
15128
  }
@@ -24061,7 +24353,10 @@ const DEEP_CHECKS = [
24061
24353
  capability: "source",
24062
24354
  command: doctorCiCommand,
24063
24355
  async run(input) {
24064
- const report = await runDoctorCi(input);
24356
+ const report = await runDoctorCi({
24357
+ ...input,
24358
+ remote: true
24359
+ });
24065
24360
  return {
24066
24361
  status: report.status,
24067
24362
  summary: report.summary
@@ -30402,7 +30697,7 @@ async function runSecretsSync(input) {
30402
30697
  environment: input.environmentId,
30403
30698
  reason: logReason(err)
30404
30699
  }, "sync secrets: vault read failed");
30405
- return summarise$2([{
30700
+ return summarise$1([{
30406
30701
  destination: `vault:${vault.providerName}`,
30407
30702
  scope: `environment=${input.environmentId}`,
30408
30703
  key: "(all)",
@@ -30519,7 +30814,7 @@ async function runSecretsSync(input) {
30519
30814
  }
30520
30815
  }
30521
30816
  }
30522
- return summarise$2(rows, logger, print, dryRun);
30817
+ return summarise$1(rows, logger, print, dryRun);
30523
30818
  }
30524
30819
  /**
30525
30820
  * Record the vault keys a deployment or Worker filter left out: one skipped row each (names only; the value is never
@@ -30557,7 +30852,7 @@ async function readAccess(secrets, scope, print) {
30557
30852
  }
30558
30853
  }
30559
30854
  /** Log every row, then print and log the summary. Shared by a finished run and one that stopped at the vault. */
30560
- function summarise$2(rows, logger, print, dryRun) {
30855
+ function summarise$1(rows, logger, print, dryRun) {
30561
30856
  for (const r of rows) logger[r.status === "fail" ? "warn" : "info"]({
30562
30857
  destination: r.destination,
30563
30858
  scope: r.scope,
@@ -34284,13 +34579,13 @@ function generateHolocronConfig(opts) {
34284
34579
  lines.push(``);
34285
34580
  return lines.join("\n");
34286
34581
  }
34287
- const SKIP_DIRS$1 = [
34582
+ const SKIP_DIRS = [
34288
34583
  ".git",
34289
34584
  "node_modules",
34290
34585
  "dist",
34291
34586
  ".turbo"
34292
34587
  ];
34293
- const defaultWalkFiles = (dir) => walkFilesSync(dir, { skip: SKIP_DIRS$1 });
34588
+ const defaultWalkFiles = (dir) => walkFilesSync(dir, { skip: SKIP_DIRS });
34294
34589
  function isBinary(content) {
34295
34590
  for (let i = 0; i < Math.min(content.length, 8e3); i++) if (content.charCodeAt(i) === 0) return true;
34296
34591
  return false;
@@ -34363,6 +34658,7 @@ async function runNew(input) {
34363
34658
  const readFn = input.readFile ?? defaultReadFile;
34364
34659
  const writeFn = input.writeFile ?? defaultWriteFile;
34365
34660
  const walkFn = input.walkFiles ?? defaultWalkFiles;
34661
+ const self = input.selfCommand ?? [process.execPath, process.argv[1]];
34366
34662
  preflight();
34367
34663
  const templateRepo = `${org}/${input.type}-template`;
34368
34664
  const newRepo = `${org}/${input.name}`;
@@ -34380,6 +34676,7 @@ async function runNew(input) {
34380
34676
  if (input.homepage) print(` Would replace <homepage> → "${input.homepage}"`);
34381
34677
  if (input.runtimeEnvironment) print(` Would replace <runtime_environment> → "${input.runtimeEnvironment}"`);
34382
34678
  print(` Would generate holocron.config.ts`);
34679
+ if (!input.noVerify) print(` Would run holocron sync in ${repoDir}`);
34383
34680
  logger.info({
34384
34681
  repo: newRepo,
34385
34682
  status: "dry-run"
@@ -34507,25 +34804,45 @@ async function runNew(input) {
34507
34804
  message: "pnpm install failed; inspect output above"
34508
34805
  };
34509
34806
  }
34807
+ const adminToken = input.token ?? keychainLookup("github.admin");
34808
+ const tokenEnv = {};
34809
+ if (!env$4.get("HOLOCRON_ORG_TOKEN")) {
34810
+ const orgToken = keychainLookup("github.org");
34811
+ if (orgToken) tokenEnv["HOLOCRON_ORG_TOKEN"] = orgToken;
34812
+ }
34813
+ if (!env$4.get("HOLOCRON_DEPLOY_TOKEN")) {
34814
+ const deployToken = keychainLookup("github.deploy");
34815
+ if (deployToken) tokenEnv["HOLOCRON_DEPLOY_TOKEN"] = deployToken;
34816
+ }
34817
+ const manualSync = `cd ${repoDir} && holocron sync`;
34818
+ print("");
34819
+ if (!adminToken) print(` ✗ holocron sync skipped — no GitHub admin token found. Run it by hand: ${manualSync}`);
34820
+ else {
34821
+ print(" Running holocron sync…");
34822
+ try {
34823
+ execFn(self[0], [
34824
+ ...self.slice(1),
34825
+ "sync",
34826
+ "--token",
34827
+ adminToken
34828
+ ], {
34829
+ cwd: repoDir,
34830
+ stdio: "inherit",
34831
+ env: tokenEnv
34832
+ });
34833
+ } catch (err) {
34834
+ print(` ✗ holocron sync failed (${errorMessage(err)}) — run it by hand: ${manualSync}`);
34835
+ }
34836
+ }
34510
34837
  print("");
34511
34838
  print(" Running holocron setup…");
34512
34839
  try {
34513
34840
  const setupArgs = ["setup"];
34514
- const setupEnv = {};
34515
- const adminToken = input.token ?? keychainLookup("github.admin");
34516
34841
  if (adminToken) setupArgs.push("--token", adminToken);
34517
- if (!env$4.get("HOLOCRON_ORG_TOKEN")) {
34518
- const orgToken = keychainLookup("github.org");
34519
- if (orgToken) setupEnv["HOLOCRON_ORG_TOKEN"] = orgToken;
34520
- }
34521
- if (!env$4.get("HOLOCRON_DEPLOY_TOKEN")) {
34522
- const deployToken = keychainLookup("github.deploy");
34523
- if (deployToken) setupEnv["HOLOCRON_DEPLOY_TOKEN"] = deployToken;
34524
- }
34525
34842
  execFn("holocron", setupArgs, {
34526
34843
  cwd: repoDir,
34527
34844
  stdio: "inherit",
34528
- env: setupEnv
34845
+ env: tokenEnv
34529
34846
  });
34530
34847
  } catch {
34531
34848
  print(" ✗ holocron setup failed — run it manually after checking your config");
@@ -34538,8 +34855,9 @@ async function runNew(input) {
34538
34855
  print(` 1. cd ${repoDir}`);
34539
34856
  if (input.noVerify) {
34540
34857
  print(` 2. pnpm install`);
34541
- print(` 3. holocron setup # wire up secrets, teams, labels, etc.`);
34542
- print(` 4. git push -u origin HEAD`);
34858
+ print(` 3. holocron sync # thin callers, org AGENTS.md block, generated files`);
34859
+ print(` 4. holocron setup # wire up secrets, teams, labels, etc.`);
34860
+ print(` 5. git push -u origin HEAD`);
34543
34861
  } else print(` 2. git push -u origin HEAD`);
34544
34862
  logger.info({
34545
34863
  repo: newRepo,
@@ -35792,13 +36110,13 @@ function planDeps(root) {
35792
36110
  };
35793
36111
  }
35794
36112
  // src/commands/probe/deps/report-deps.ts
35795
- const kindOf$1 = (section) => section === "peerDependencies" ? "peer" : section === "devDependencies" ? "dev" : "prod";
36113
+ const kindOf = (section) => section === "peerDependencies" ? "peer" : section === "devDependencies" ? "dev" : "prod";
35796
36114
  /** Every package that uses a dependency, with how. */
35797
36115
  function usersOf(row) {
35798
36116
  const byPkg = /* @__PURE__ */ new Map();
35799
36117
  for (const e of row.edges) {
35800
36118
  const kinds = byPkg.get(e.pkg) ?? /* @__PURE__ */ new Set();
35801
- kinds.add(kindOf$1(e.section));
36119
+ kinds.add(kindOf(e.section));
35802
36120
  byPkg.set(e.pkg, kinds);
35803
36121
  }
35804
36122
  return [...byPkg.entries()].map(([pkg, kinds]) => ({
@@ -35819,7 +36137,7 @@ function detail(p, filter) {
35819
36137
  for (const e of r.edges) {
35820
36138
  const entry = byGroup.get(e.group) ?? /* @__PURE__ */ new Map();
35821
36139
  const kinds = entry.get(e.pkg) ?? /* @__PURE__ */ new Set();
35822
- kinds.add(kindOf$1(e.section));
36140
+ kinds.add(kindOf(e.section));
35823
36141
  entry.set(e.pkg, kinds);
35824
36142
  byGroup.set(e.group, entry);
35825
36143
  }
@@ -36613,7 +36931,7 @@ function writeLcov(ctx, repoRoot, packages) {
36613
36931
  function percent(documented, total) {
36614
36932
  return `${total === 0 ? 100 : Math.round(100 * documented / total)}%`;
36615
36933
  }
36616
- function summarise$1(ctx, packages) {
36934
+ function summarise(ctx, packages) {
36617
36935
  let total = 0;
36618
36936
  let documented = 0;
36619
36937
  ctx.say({
@@ -36665,7 +36983,7 @@ function docsCoverageProbes(repoRoot, typedoc = runTypedoc(repoRoot), diff = rea
36665
36983
  async run(ctx) {
36666
36984
  const packages = measure();
36667
36985
  writeLcov(ctx, repoRoot, packages);
36668
- summarise$1(ctx, packages);
36986
+ summarise(ctx, packages);
36669
36987
  }
36670
36988
  },
36671
36989
  patch: {
@@ -36732,7 +37050,7 @@ function docsCoverageProbes(repoRoot, typedoc = runTypedoc(repoRoot), diff = rea
36732
37050
  mkdirSync(dirname(file), { recursive: true });
36733
37051
  writeFileSync(file, toLcov(packages));
36734
37052
  });
36735
- summarise$1(ctx, packages);
37053
+ summarise(ctx, packages);
36736
37054
  }
36737
37055
  }
36738
37056
  };
@@ -37002,220 +37320,6 @@ function listProbes(groups) {
37002
37320
  }
37003
37321
  return lines;
37004
37322
  }
37005
- // src/commands/probe/references/clone-org.ts
37006
- const SKIP_DIRS = /* @__PURE__ */ new Set([".git", "node_modules"]);
37007
- const MAX_FILE_BYTES = 5242880;
37008
- /** How often, and how long apart, removing a clone is tried again when something is still writing into it. */
37009
- const REMOVE_RETRIES = 10;
37010
- const REMOVE_RETRY_DELAY_MS = 200;
37011
- /**
37012
- * The arguments of `gh repo clone` for `org/name` into `dest`: a shallow, quiet clone that runs none of the user's git
37013
- * hooks. The probe only reads, and a global hook (`core.hooksPath`, `init.templateDir`) such as a `post-checkout` that
37014
- * starts `ctags` in the background writes `.git/tags` after the clone has returned, which made removing the clone fail
37015
- * with `ENOTEMPTY` (#2913). `-c` takes effect before the files are checked out.
37016
- */
37017
- function cloneArgs(org, name, dest) {
37018
- return [
37019
- "repo",
37020
- "clone",
37021
- `${org}/${name}`,
37022
- dest,
37023
- "--",
37024
- "--depth",
37025
- "1",
37026
- "--quiet",
37027
- "-c",
37028
- "core.hooksPath=/dev/null"
37029
- ];
37030
- }
37031
- /**
37032
- * Removes a scratch directory, trying again when something still writes into it. A process the clone left running can
37033
- * recreate a file while the directory is being deleted; `rmSync` retries `ENOTEMPTY` (and `EBUSY`, `EPERM`) itself.
37034
- */
37035
- function removeScratch(path, remove = rmSync) {
37036
- remove(path, {
37037
- recursive: true,
37038
- force: true,
37039
- maxRetries: REMOVE_RETRIES,
37040
- retryDelay: REMOVE_RETRY_DELAY_MS
37041
- });
37042
- }
37043
- /** Every text file under `dir`: not in `.git` or `node_modules`, under 5 MiB, and without a NUL in its first KiB. */
37044
- function* textFiles(dir, root = dir) {
37045
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
37046
- if (SKIP_DIRS.has(entry.name)) continue;
37047
- const path = join(dir, entry.name);
37048
- if (entry.isDirectory()) yield* textFiles(path, root);
37049
- else if (entry.isFile() && statSync(path).size < MAX_FILE_BYTES) {
37050
- const buffer = readFileSync(path);
37051
- if (!buffer.subarray(0, 1024).includes(0)) yield {
37052
- path: relative(root, path),
37053
- text: buffer.toString("utf8")
37054
- };
37055
- }
37056
- }
37057
- }
37058
- /**
37059
- * Shallow-clones the default branch of each active (not archived) repository of `org` with `gh`, one at a time, and
37060
- * removes every clone when the scan ends. Cloning, rather than GitHub code search, because search skips repositories
37061
- * that are not indexed and gives no guarantee of completeness.
37062
- */
37063
- function cloneOrg(org) {
37064
- return JSON.parse(execFileSync("gh", [
37065
- "repo",
37066
- "list",
37067
- org,
37068
- "--limit",
37069
- "200",
37070
- "--json",
37071
- "name,isArchived,isTemplate"
37072
- ], { encoding: "utf8" })).filter((repo) => !repo.isArchived).sort((a, b) => a.name.localeCompare(b.name)).map((repo) => ({
37073
- name: repo.name,
37074
- isTemplate: repo.isTemplate,
37075
- files() {
37076
- const scratch = mkdtempSync(join(tmpdir(), "refs-"));
37077
- const dest = join(scratch, repo.name);
37078
- execFileSync("gh", cloneArgs(org, repo.name, dest), { stdio: "pipe" });
37079
- try {
37080
- return [...textFiles(dest)];
37081
- } finally {
37082
- removeScratch(scratch);
37083
- }
37084
- }
37085
- }));
37086
- /* v8 ignore stop */
37087
- }
37088
- // src/commands/probe/references/find-references.ts
37089
- const CALL = /^-?\s*uses:\s/;
37090
- /** The repository that hosts the files; its own references are the starters and shims, not callers. */
37091
- const HOST_REPO = ".github";
37092
- /** What a reference points at, from the text after the needle. */
37093
- function kindOf(line, needle) {
37094
- const rest = line.slice(line.indexOf(needle) + needle.length);
37095
- if (rest.startsWith("workflows/")) return "workflow";
37096
- if (rest.startsWith("actions/")) return "action";
37097
- return "other";
37098
- }
37099
- /** Every line of every file of `repo` that contains `needle`. */
37100
- function findReferences(repo, needle) {
37101
- const found = [];
37102
- for (const file of repo.files()) file.text.split("\n").forEach((line, index) => {
37103
- if (!line.includes(needle)) return;
37104
- found.push({
37105
- repo: repo.name,
37106
- file: file.path,
37107
- line: index + 1,
37108
- kind: kindOf(line, needle),
37109
- text: line.trim()
37110
- });
37111
- });
37112
- return found;
37113
- }
37114
- /**
37115
- * Whether a reference is a live call: a `uses:` line in a YAML file, which is what GitHub reads. Tests, docs and specs
37116
- * name the path on purpose (the legacy-path detection, a test that nothing spells it, a record of the move), so they are
37117
- * references to list but not calls to wait on.
37118
- */
37119
- function isCall(ref) {
37120
- return /\.ya?ml$/.test(ref.file) && CALL.test(ref.text);
37121
- }
37122
- // src/commands/probe/references/references-probes.ts
37123
- function scan(repos, needle) {
37124
- return {
37125
- repos,
37126
- found: repos.flatMap((repo) => findReferences(repo, needle))
37127
- };
37128
- }
37129
- function summarise(ctx, repos, found, needle, max) {
37130
- ctx.say({
37131
- status: "heading",
37132
- label: `References to ${needle}`
37133
- });
37134
- for (const repo of repos) {
37135
- const own = found.filter((ref) => ref.repo === repo.name);
37136
- const files = new Set(own.map((ref) => ref.file)).size;
37137
- const count = (kind) => own.filter((ref) => ref.kind === kind).length;
37138
- ctx.say({
37139
- status: "info",
37140
- label: repo.name === ".github" ? `${repo.name} (host)` : repo.name,
37141
- detail: `${files} files: ${count("workflow")} workflow, ${count("action")} action, ${count("other")} other; ${own.filter(isCall).length} live calls`
37142
- });
37143
- }
37144
- const outside = found.filter((ref) => ref.repo !== HOST_REPO);
37145
- const calls = outside.filter(isCall).length;
37146
- const inside = found.length - outside.length;
37147
- const detail = `${outside.length} references in all (tests, docs and specs may name the path on purpose), ${inside} more inside ${HOST_REPO}`;
37148
- if (calls > max) ctx.say({
37149
- status: "fail",
37150
- label: `${calls} live calls outside ${HOST_REPO}`,
37151
- detail: `more than the ${max} allowed; ${detail}`
37152
- });
37153
- else ctx.say({
37154
- status: "ok",
37155
- label: `${calls} live calls outside ${HOST_REPO}`,
37156
- detail
37157
- });
37158
- }
37159
- /**
37160
- * `ci refs` counts the references to the reusable workflows and composite actions hosted in `<org>/.github` across
37161
- * every active repository of the org. It is the exit test for removing the forwarding shims there: they can go when
37162
- * no live call outside `.github` is left (a `uses:` line in a YAML file; see {@link isCall}). It fails above `<max>`,
37163
- * which defaults to 0, so the exit code is the test (#2915). `ci ref-list` prints each reference with its file and line.
37164
- */
37165
- function ciProbes(org, clone = cloneOrg) {
37166
- const needle = (name) => `${name}/.github/.github/`;
37167
- const read = (ctx) => {
37168
- if (!org) {
37169
- ctx.say({
37170
- status: "fail",
37171
- label: "no org",
37172
- detail: "the config has no org to scan"
37173
- });
37174
- return null;
37175
- }
37176
- return {
37177
- org,
37178
- ...scan(clone(org), needle(org))
37179
- };
37180
- };
37181
- return {
37182
- refs: {
37183
- summary: "Count references to the reusable workflows and actions hosted in the org's .github repo; fails on a live call outside it (arg: max, default 0).",
37184
- writes: false,
37185
- async run(ctx) {
37186
- const result = read(ctx);
37187
- if (!result) return;
37188
- const max = ctx.args?.[0] === void 0 ? 0 : Number(ctx.args[0]);
37189
- if (!Number.isInteger(max) || max < 0) {
37190
- ctx.say({
37191
- status: "fail",
37192
- label: `\`${ctx.args[0]}\` is not a number`,
37193
- detail: "usage: ci refs [max]"
37194
- });
37195
- return;
37196
- }
37197
- summarise(ctx, result.repos, result.found, needle(result.org), max);
37198
- }
37199
- },
37200
- "ref-list": {
37201
- summary: "List every reference to the org's .github workflows and actions, with file and line.",
37202
- writes: false,
37203
- async run(ctx) {
37204
- const result = read(ctx);
37205
- if (!result) return;
37206
- for (const ref of result.found) ctx.say({
37207
- status: "info",
37208
- label: `${ref.repo}:${ref.file}:${ref.line}`,
37209
- detail: `${ref.kind}: ${ref.text}`
37210
- });
37211
- ctx.say({
37212
- status: "ok",
37213
- label: `${result.found.length} references`
37214
- });
37215
- }
37216
- }
37217
- };
37218
- }
37219
37323
  // src/commands/probe/specs/real-specs-io.ts
37220
37324
  /** The `specs check` probe's inputs from the real filesystem under `repoRoot`. */
37221
37325
  function realSpecsIo(repoRoot) {
@@ -44213,6 +44317,274 @@ const syncRequestsCommand = {
44213
44317
  })).status === "fail") process.exitCode = 1;
44214
44318
  }
44215
44319
  };
44320
+ // src/commands/sync-templates/plan-template-sync/plan-template-sync.ts
44321
+ /** Compares a template folder with its repo and lists only what differs: files to create, to replace and to remove. */
44322
+ async function planTemplateSync(input) {
44323
+ const remote = new Set(input.remotePaths);
44324
+ const paths = Object.keys(input.files).sort();
44325
+ const plan = {
44326
+ create: [],
44327
+ update: [],
44328
+ remove: []
44329
+ };
44330
+ for (const path of paths) {
44331
+ if (!remote.has(path)) {
44332
+ plan.create.push(path);
44333
+ continue;
44334
+ }
44335
+ const file = await input.read(path);
44336
+ if (!file) plan.create.push(path);
44337
+ else if (file.content !== input.files[path]) plan.update.push({
44338
+ path,
44339
+ version: file.version
44340
+ });
44341
+ }
44342
+ plan.remove = [...remote].filter((p) => !(p in input.files)).sort();
44343
+ return plan;
44344
+ }
44345
+ // src/commands/sync-templates/template-files/template-files.ts
44346
+ /**
44347
+ * Every file of one template folder as `path from the folder -> text`, with `/` separators. `.git` and
44348
+ * `node_modules` are not entered. A file with a NUL byte is binary and throws: the `source` capability writes text, so
44349
+ * publishing it would corrupt it.
44350
+ */
44351
+ function templateFiles(dir) {
44352
+ const files = {};
44353
+ for (const full of walkFilesSync(dir)) {
44354
+ const path = relative(dir, full).split(sep).join("/");
44355
+ const bytes = readFileSync(full);
44356
+ if (bytes.includes(0)) throw new Error(`${path} is a binary file; templates publish text files only`);
44357
+ files[path] = bytes.toString("utf8");
44358
+ }
44359
+ return files;
44360
+ }
44361
+ // src/commands/sync-templates/template-folders/template-folders.ts
44362
+ /**
44363
+ * The template types under `templates/`: its subfolders, sorted. A file beside them (`package.json` and `README.md`
44364
+ * are the group's own) is not a template, and neither is a folder named `node_modules` or one that starts with a dot.
44365
+ * An absent `templates/` folder is no templates.
44366
+ */
44367
+ function templateFolders(templatesDir) {
44368
+ let entries;
44369
+ try {
44370
+ entries = readdirSync(templatesDir, { withFileTypes: true });
44371
+ } catch (err) {
44372
+ if (err.code === "ENOENT") return [];
44373
+ throw err;
44374
+ }
44375
+ return entries.filter((e) => e.isDirectory() && e.name !== "node_modules" && !e.name.startsWith(".")).map((e) => e.name).sort();
44376
+ }
44377
+ // src/commands/sync-templates/templates-version/templates-version.ts
44378
+ /** The `templates` group's version, from `package.json` in the templates folder. Throws when it is missing or has no version. */
44379
+ function templatesVersion(templatesDir) {
44380
+ const path = join(templatesDir, "package.json");
44381
+ let version;
44382
+ try {
44383
+ version = JSON.parse(readFileSync(path, "utf8")).version;
44384
+ } catch (err) {
44385
+ throw new Error(`cannot read the templates version from ${path}`, { cause: err });
44386
+ }
44387
+ if (typeof version !== "string" || version === "") throw new Error(`${path} has no version`);
44388
+ return version;
44389
+ }
44390
+ // src/commands/sync-templates/run-sync-templates/run-sync-templates.ts
44391
+ /**
44392
+ * `holocron sync templates` -- publish each `templates/<type>/` folder to `<org>/<type>-template` and tag that repo
44393
+ * `templates-v<version>` (spec `tech-template-repos`, rollout step 3, #2926).
44394
+ *
44395
+ * Each folder is compared with its repo's default branch; only the difference is written through the `source`
44396
+ * capability (files made, replaced, and removed when the repo has them and the folder no longer does), then the repo is
44397
+ * tagged with the `templates` group's version from `templates/package.json`. A rerun writes nothing and a tag already at
44398
+ * the same content is left alone. It never creates or deletes a repository: a missing template repo is a failing row.
44399
+ * One template failing does not stop the others. It writes, so it asks first; `--yes` skips the question and, without a
44400
+ * terminal, a run with neither `--yes` nor `--dry-run` refuses.
44401
+ */
44402
+ const counts = (p) => `${p.create.length} to create, ${p.update.length} to replace, ${p.remove.length} to remove`;
44403
+ async function runSyncTemplates(input) {
44404
+ const print = input.print ?? ((line) => console.log(line));
44405
+ const row = (status, ...parts) => print(statusRow$1(status, ["sync templates", ...parts]));
44406
+ const summary = (templates) => {
44407
+ const n = (s) => templates.filter((t) => t.status === s).length;
44408
+ print("");
44409
+ print(style.header(`${n("ok")} ok, ${n("fail")} fail, ${n("skip")} skipped`));
44410
+ };
44411
+ const stop = (status, reason) => {
44412
+ row(status, reason);
44413
+ return {
44414
+ status,
44415
+ reason,
44416
+ templates: []
44417
+ };
44418
+ };
44419
+ const dryRun = Boolean(input.context.dryRun);
44420
+ const dir = input.templatesDir ?? join(input.context.repoRoot, "templates");
44421
+ let names;
44422
+ let version;
44423
+ try {
44424
+ names = templateFolders(dir);
44425
+ if (names.length === 0) return stop("skip", `no template folders under ${dir}`);
44426
+ version = templatesVersion(dir);
44427
+ } catch (err) {
44428
+ return stop("fail", errorMessage(err));
44429
+ }
44430
+ const org = input.context.org;
44431
+ if (!org) return stop("fail", "no organization to publish to: set `org` in the config or pass --org");
44432
+ const tag = `templates-v${version}`;
44433
+ /* v8 ignore next -- the real loader is only built outside tests, which always inject one */
44434
+ const loader = input.loader ?? new PluginLoader(input.loaded.resolved, input.context);
44435
+ await loader.load();
44436
+ assertPluginsResolvable(loader, "sync templates");
44437
+ const source = loader.has("source") ? loader.get("source") : void 0;
44438
+ if (!source?.readFile || !source.writeFile || !source.listFiles || !source.deleteFile || !source.ensureTag) return stop("fail", whyMissing(loader, "source", "no `source` provider that can read, write, list and delete files and tag is available"));
44439
+ const { readFile, writeFile, listFiles, deleteFile, ensureTag } = source;
44440
+ const results = [];
44441
+ const planned = [];
44442
+ for (const name of names) {
44443
+ const repo = `${org}/${name}-template`;
44444
+ try {
44445
+ const files = templateFiles(join(dir, name));
44446
+ const plan = await planTemplateSync({
44447
+ files,
44448
+ remotePaths: await listFiles.call(source, repo),
44449
+ read: (path) => readFile.call(source, path, repo)
44450
+ });
44451
+ planned.push({
44452
+ name,
44453
+ repo,
44454
+ files,
44455
+ plan
44456
+ });
44457
+ } catch (err) {
44458
+ row("fail", name, repo, describeError(err));
44459
+ results.push({
44460
+ name,
44461
+ repo,
44462
+ status: "fail",
44463
+ created: 0,
44464
+ updated: 0,
44465
+ removed: 0,
44466
+ reason: errorMessage(err)
44467
+ });
44468
+ }
44469
+ }
44470
+ if (dryRun) {
44471
+ for (const p of planned) {
44472
+ row("skip", p.name, p.repo, `dry run, nothing written: ${counts(p.plan)}; would tag ${tag}`);
44473
+ results.push({
44474
+ name: p.name,
44475
+ repo: p.repo,
44476
+ status: "skip",
44477
+ created: p.plan.create.length,
44478
+ updated: p.plan.update.length,
44479
+ removed: p.plan.remove.length
44480
+ });
44481
+ }
44482
+ summary(results);
44483
+ return {
44484
+ status: results.some((r) => r.status === "fail") ? "fail" : "ok",
44485
+ version,
44486
+ templates: results
44487
+ };
44488
+ }
44489
+ if (planned.length > 0 && !input.yes) {
44490
+ if (!(input.interactive ?? Boolean(process.stdin.isTTY))) throw new NonInteractiveError("`sync templates` writes to the template repos; pass --yes to run it without asking, or --dry-run to look");
44491
+ if (!await (input.confirm ?? ((q) => confirm({
44492
+ message: q,
44493
+ default: false
44494
+ })))(`Publish ${planned.length} template(s) as ${tag}?`)) {
44495
+ for (const p of planned) {
44496
+ row("skip", p.name, p.repo, "cancelled; nothing was changed");
44497
+ results.push({
44498
+ name: p.name,
44499
+ repo: p.repo,
44500
+ status: "skip",
44501
+ created: 0,
44502
+ updated: 0,
44503
+ removed: 0
44504
+ });
44505
+ }
44506
+ summary(results);
44507
+ return {
44508
+ status: "cancelled",
44509
+ version,
44510
+ templates: results
44511
+ };
44512
+ }
44513
+ }
44514
+ const message = `chore: sync from ${HOLOCRON_REPO$1} ${tag}`;
44515
+ for (const { name, repo, files, plan } of planned) {
44516
+ const result = {
44517
+ name,
44518
+ repo,
44519
+ status: "ok",
44520
+ created: 0,
44521
+ updated: 0,
44522
+ removed: 0
44523
+ };
44524
+ try {
44525
+ for (const path of plan.create) {
44526
+ await writeFile.call(source, path, files[path], {
44527
+ message,
44528
+ repo
44529
+ });
44530
+ result.created++;
44531
+ }
44532
+ for (const { path, version: fileVersion } of plan.update) {
44533
+ await writeFile.call(source, path, files[path], {
44534
+ message,
44535
+ version: fileVersion,
44536
+ repo
44537
+ });
44538
+ result.updated++;
44539
+ }
44540
+ for (const path of plan.remove) {
44541
+ await deleteFile.call(source, path, {
44542
+ message,
44543
+ repo
44544
+ });
44545
+ result.removed++;
44546
+ }
44547
+ result.tagged = await ensureTag.call(source, tag, repo);
44548
+ row("ok", name, repo, `${result.created} created, ${result.updated} replaced, ${result.removed} removed; ${result.tagged ? `tagged ${tag}` : `${tag} already there`}`);
44549
+ } catch (err) {
44550
+ result.status = "fail";
44551
+ result.reason = errorMessage(err);
44552
+ row("fail", name, repo, describeError(err));
44553
+ }
44554
+ results.push(result);
44555
+ }
44556
+ summary(results);
44557
+ return {
44558
+ status: results.some((r) => r.status === "fail") ? "fail" : "ok",
44559
+ version,
44560
+ templates: results
44561
+ };
44562
+ }
44563
+ // src/commands/sync-templates/sync-templates.command.ts
44564
+ const syncTemplatesCommand = {
44565
+ command: "templates",
44566
+ describe: "Publish each templates/<type>/ folder to its <type>-template repo and tag that repo with the templates version",
44567
+ builder: (y) => y.option("yes", {
44568
+ type: "boolean",
44569
+ describe: "Write without asking (a workflow needs it)"
44570
+ }),
44571
+ handler: async (argv) => {
44572
+ const tokens = tokenContext(argv.token);
44573
+ if (!tokens) return;
44574
+ const loaded = await loadConfig(argv.cwd);
44575
+ applyResolvedConfig(argv, loaded.resolved);
44576
+ if ((await runSyncTemplates({
44577
+ loaded,
44578
+ context: {
44579
+ repoRoot: argv.cwd,
44580
+ dryRun: argv.dryRun,
44581
+ ...tokens,
44582
+ org: resolveOrg(argv, loaded.resolved)
44583
+ },
44584
+ ...argv.yes ? { yes: true } : {}
44585
+ })).status === "fail") process.exitCode = 1;
44586
+ }
44587
+ };
44216
44588
  // src/commands/sync-tooling/run-sync-tooling/run-sync-tooling.ts
44217
44589
  /**
44218
44590
  * `holocron sync tooling` — runs each `tooling` provider's `sync()` and nothing else.
@@ -45277,7 +45649,7 @@ async function syncApp(argv) {
45277
45649
  const syncCommand = {
45278
45650
  command: "sync [steps..]",
45279
45651
  describe: "Sync state from config to the provider and local files (labels, properties, teams, topics, keywords, description, homepage, readme, workflows, scripts, wiki)",
45280
- builder: (y) => syncArgs(y).command(syncGithubCommand).command(syncIssuesCommand).command(syncIncidentsCommand).command(syncPrsCommand).command(syncReleasesCommand).command(syncReadmeCommand).command(ideasSyncCommand).command(syncToolingCommand).command(syncRequestsCommand).command(specsSyncCommand).command(secretsSyncCommand).command(notificationsSyncRolesCommand),
45652
+ builder: (y) => syncArgs(y).command(syncGithubCommand).command(syncIssuesCommand).command(syncIncidentsCommand).command(syncPrsCommand).command(syncReleasesCommand).command(syncTemplatesCommand).command(syncReadmeCommand).command(ideasSyncCommand).command(syncToolingCommand).command(syncRequestsCommand).command(specsSyncCommand).command(secretsSyncCommand).command(notificationsSyncRolesCommand),
45281
45653
  handler: async (argv) => {
45282
45654
  if (argv.env !== void 0 || argv.steps?.[0] !== void 0) {
45283
45655
  if (await syncApp(argv)) return;